virtual.c 102 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Win32 virtual memory functions
 *
 * Copyright 1997, 2002 Alexandre Julliard
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20 21 22 23 24 25 26 27 28 29
 */

#include "config.h"
#include "wine/port.h"

#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
30
#include <stdarg.h>
31 32 33 34
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
35 36 37
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
38
#ifdef HAVE_SYS_MMAN_H
39
# include <sys/mman.h>
40
#endif
41 42
#ifdef HAVE_VALGRIND_VALGRIND_H
# include <valgrind/valgrind.h>
43
#endif
44

45
#include "ntstatus.h"
46
#define WIN32_NO_STATUS
47
#define NONAMELESSUNION
48
#include "windef.h"
49 50 51
#include "winternl.h"
#include "wine/library.h"
#include "wine/server.h"
52
#include "wine/exception.h"
53
#include "wine/list.h"
54
#include "wine/debug.h"
55
#include "ntdll_misc.h"
56 57 58 59

WINE_DEFAULT_DEBUG_CHANNEL(virtual);
WINE_DECLARE_DEBUG_CHANNEL(module);

60 61 62 63
#ifndef MAP_NORESERVE
#define MAP_NORESERVE 0
#endif

64
/* File view */
65
struct file_view
66
{
67
    struct list   entry;       /* Entry in global view list */
68
    void         *base;        /* Base address */
69
    size_t        size;        /* Size in bytes */
70
    HANDLE        mapping;     /* Handle to the file mapping */
71
    unsigned int  map_protect; /* Mapping protection */
72
    unsigned int  protect;     /* Protection for all pages at allocation time */
73
    BYTE          prot[1];     /* Protection byte for each page */
74
};
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97


/* Conversion from VPROT_* to Win32 flags */
static const BYTE VIRTUAL_Win32Flags[16] =
{
    PAGE_NOACCESS,              /* 0 */
    PAGE_READONLY,              /* READ */
    PAGE_READWRITE,             /* WRITE */
    PAGE_READWRITE,             /* READ | WRITE */
    PAGE_EXECUTE,               /* EXEC */
    PAGE_EXECUTE_READ,          /* READ | EXEC */
    PAGE_EXECUTE_READWRITE,     /* WRITE | EXEC */
    PAGE_EXECUTE_READWRITE,     /* READ | WRITE | EXEC */
    PAGE_WRITECOPY,             /* WRITECOPY */
    PAGE_WRITECOPY,             /* READ | WRITECOPY */
    PAGE_WRITECOPY,             /* WRITE | WRITECOPY */
    PAGE_WRITECOPY,             /* READ | WRITE | WRITECOPY */
    PAGE_EXECUTE_WRITECOPY,     /* EXEC | WRITECOPY */
    PAGE_EXECUTE_WRITECOPY,     /* READ | EXEC | WRITECOPY */
    PAGE_EXECUTE_WRITECOPY,     /* WRITE | EXEC | WRITECOPY */
    PAGE_EXECUTE_WRITECOPY      /* READ | WRITE | EXEC | WRITECOPY */
};

98
static struct list views_list = LIST_INIT(views_list);
99

100 101
static RTL_CRITICAL_SECTION csVirtual;
static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
102 103 104
{
    0, 0, &csVirtual,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
105
      0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
106
};
107
static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
108 109

#ifdef __i386__
110 111
static const UINT page_shift = 12;
static const UINT_PTR page_mask = 0xfff;
112
/* Note: these are Windows limits, you cannot change them. */
113 114
static void *address_space_limit = (void *)0xc0000000;  /* top of the total available address space */
static void *user_space_limit    = (void *)0x7fff0000;  /* top of the user address space */
115
static void *working_set_limit   = (void *)0x7fff0000;  /* top of the current working set */
116
static void *address_space_start = (void *)0x110000;    /* keep DOS area clear */
117
#elif defined(__x86_64__)
118 119
static const UINT page_shift = 12;
static const UINT_PTR page_mask = 0xfff;
120 121 122
static void *address_space_limit = (void *)0x7fffffff0000;
static void *user_space_limit    = (void *)0x7fffffff0000;
static void *working_set_limit   = (void *)0x7fffffff0000;
123
static void *address_space_start = (void *)0x10000;
124
#else
125
UINT_PTR page_size = 0;
126
static UINT page_shift;
127
static UINT_PTR page_mask;
128 129 130
static void *address_space_limit;
static void *user_space_limit;
static void *working_set_limit;
131
static void *address_space_start = (void *)0x10000;
132
#endif  /* __i386__ */
133
static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
134 135

#define ROUND_ADDR(addr,mask) \
136
   ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
137 138

#define ROUND_SIZE(addr,size) \
139
   (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
140 141

#define VIRTUAL_DEBUG_DUMP_VIEW(view) \
142
    do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
143

144
#define VIRTUAL_HEAP_SIZE (sizeof(void*)*1024*1024)
145 146

static HANDLE virtual_heap;
147 148
static void *preload_reserve_start;
static void *preload_reserve_end;
149 150
static BOOL use_locks;
static BOOL force_exec_prot;  /* whether to force PROT_EXEC on all PROT_READ mmaps */
151

152 153 154 155 156 157 158 159

/***********************************************************************
 *           VIRTUAL_GetProtStr
 */
static const char *VIRTUAL_GetProtStr( BYTE prot )
{
    static char buffer[6];
    buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
160
    buffer[1] = (prot & VPROT_GUARD) ? 'g' : ((prot & VPROT_WRITEWATCH) ? 'H' : '-');
161
    buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
162
    buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
163 164 165 166 167 168
    buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
    buffer[5] = 0;
    return buffer;
}


169 170 171 172 173 174 175 176 177 178 179
/***********************************************************************
 *           VIRTUAL_GetUnixProt
 *
 * Convert page protections to protection for mmap/mprotect.
 */
static int VIRTUAL_GetUnixProt( BYTE vprot )
{
    int prot = 0;
    if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
    {
        if (vprot & VPROT_READ) prot |= PROT_READ;
180 181
        if (vprot & VPROT_WRITE) prot |= PROT_WRITE | PROT_READ;
        if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE | PROT_READ;
182
        if (vprot & VPROT_EXEC) prot |= PROT_EXEC | PROT_READ;
183
        if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
184 185 186 187 188 189
    }
    if (!prot) prot = PROT_NONE;
    return prot;
}


190 191 192
/***********************************************************************
 *           VIRTUAL_DumpView
 */
193
static void VIRTUAL_DumpView( struct file_view *view )
194 195 196 197 198
{
    UINT i, count;
    char *addr = view->base;
    BYTE prot = view->prot[0];

199
    TRACE( "View: %p - %p", addr, addr + view->size - 1 );
200
    if (view->protect & VPROT_SYSTEM)
201
        TRACE( " (system)\n" );
202
    else if (view->protect & VPROT_VALLOC)
203
        TRACE( " (valloc)\n" );
204
    else if (view->mapping)
205
        TRACE( " %p\n", view->mapping );
206
    else
207
        TRACE( " (anonymous)\n");
208 209 210 211

    for (count = i = 1; i < view->size >> page_shift; i++, count++)
    {
        if (view->prot[i] == prot) continue;
212
        TRACE( "      %p - %p %s\n",
213 214 215 216 217 218
                 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
        addr += (count << page_shift);
        prot = view->prot[i];
        count = 0;
    }
    if (count)
219
        TRACE( "      %p - %p %s\n",
220 221 222 223 224 225 226
                 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
}


/***********************************************************************
 *           VIRTUAL_Dump
 */
227
#ifdef WINE_VM_DEBUG
228
static void VIRTUAL_Dump(void)
229
{
230
    sigset_t sigset;
231
    struct file_view *view;
232

233
    TRACE( "Dump of all virtual memory views:\n" );
234
    server_enter_uninterrupted_section( &csVirtual, &sigset );
235
    LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
236
    {
237
        VIRTUAL_DumpView( view );
238
    }
239
    server_leave_uninterrupted_section( &csVirtual, &sigset );
240
}
241
#endif
242 243 244 245 246


/***********************************************************************
 *           VIRTUAL_FindView
 *
247
 * Find the view containing a given address. The csVirtual section must be held by caller.
248
 *
249 250 251
 * PARAMS
 *      addr  [I] Address
 *
252 253 254 255
 * RETURNS
 *	View: Success
 *	NULL: Failure
 */
256
static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
257
{
258
    struct file_view *view;
259

260
    LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
261
    {
262 263 264 265 266
        if (view->base > addr) break;  /* no matching view */
        if ((const char *)view->base + view->size <= (const char *)addr) continue;
        if ((const char *)view->base + view->size < (const char *)addr + size) break;  /* size too large */
        if ((const char *)addr + size < (const char *)addr) break; /* overflow */
        return view;
267
    }
268
    return NULL;
269 270 271
}


272 273 274 275 276 277 278 279 280 281 282
/***********************************************************************
 *           get_mask
 */
static inline UINT_PTR get_mask( ULONG zero_bits )
{
    if (!zero_bits) return 0xffff;  /* allocations are aligned to 64K by default */
    if (zero_bits < page_shift) zero_bits = page_shift;
    return (1 << zero_bits) - 1;
}


283
/***********************************************************************
284
 *           find_view_range
285
 *
286 287 288 289 290
 * Find the first view overlapping at least part of the specified range.
 * The csVirtual section must be held by caller.
 */
static struct file_view *find_view_range( const void *addr, size_t size )
{
291
    struct file_view *view;
292

293
    LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
294
    {
Eric Pouech's avatar
Eric Pouech committed
295 296
        if ((const char *)view->base >= (const char *)addr + size) break;
        if ((const char *)view->base + view->size > (const char *)addr) return view;
297 298 299 300 301
    }
    return NULL;
}


302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
/***********************************************************************
 *           find_free_area
 *
 * Find a free area between views inside the specified range.
 * The csVirtual section must be held by caller.
 */
static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
{
    struct list *ptr;
    void *start;

    if (top_down)
    {
        start = ROUND_ADDR( (char *)end - size, mask );
        if (start >= end || start < base) return NULL;

        for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
        {
            struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );

            if ((char *)view->base + view->size <= (char *)start) break;
            if ((char *)view->base >= (char *)start + size) continue;
            start = ROUND_ADDR( (char *)view->base - size, mask );
            /* stop if remaining space is not large enough */
            if (!start || start >= end || start < base) return NULL;
        }
    }
    else
    {
        start = ROUND_ADDR( (char *)base + mask, mask );
        if (start >= end || (char *)end - (char *)start < size) return NULL;

        for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
        {
            struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );

            if ((char *)view->base >= (char *)start + size) break;
            if ((char *)view->base + view->size <= (char *)start) continue;
            start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
            /* stop if remaining space is not large enough */
            if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
        }
    }
    return start;
}


349 350
/***********************************************************************
 *           add_reserved_area
351
 *
352 353 354 355 356 357 358
 * Add a reserved area to the list maintained by libwine.
 * The csVirtual section must be held by caller.
 */
static void add_reserved_area( void *addr, size_t size )
{
    TRACE( "adding %p-%p\n", addr, (char *)addr + size );

359
    if (addr < user_space_limit)
360 361
    {
        /* unmap the part of the area that is below the limit */
362 363 364 365
        assert( (char *)addr + size > (char *)user_space_limit );
        munmap( addr, (char *)user_space_limit - (char *)addr );
        size -= (char *)user_space_limit - (char *)addr;
        addr = user_space_limit;
366
    }
367 368
    /* blow away existing mappings */
    wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
369 370 371 372
    wine_mmap_add_reserved_area( addr, size );
}


373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
/***********************************************************************
 *           remove_reserved_area
 *
 * Remove a reserved area from the list maintained by libwine.
 * The csVirtual section must be held by caller.
 */
static void remove_reserved_area( void *addr, size_t size )
{
    struct file_view *view;

    TRACE( "removing %p-%p\n", addr, (char *)addr + size );
    wine_mmap_remove_reserved_area( addr, size, 0 );

    /* unmap areas not covered by an existing view */
    LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
    {
        if ((char *)view->base >= (char *)addr + size)
        {
            munmap( addr, size );
            break;
        }
        if ((char *)view->base + view->size <= (char *)addr) continue;
        if (view->base > addr) munmap( addr, (char *)view->base - (char *)addr );
        if ((char *)view->base + view->size > (char *)addr + size) break;
        size = (char *)addr + size - ((char *)view->base + view->size);
        addr = (char *)view->base + view->size;
    }
}


403 404 405 406 407
/***********************************************************************
 *           is_beyond_limit
 *
 * Check if an address range goes beyond a given limit.
 */
408
static inline BOOL is_beyond_limit( const void *addr, size_t size, const void *limit )
409
{
410
    return (addr >= limit || (const char *)addr + size > (const char *)limit);
411 412 413 414 415 416 417 418 419 420 421 422 423
}


/***********************************************************************
 *           unmap_area
 *
 * Unmap an area, or simply replace it by an empty mapping if it is
 * in a reserved area. The csVirtual section must be held by caller.
 */
static inline void unmap_area( void *addr, size_t size )
{
    if (wine_mmap_is_in_reserved_area( addr, size ))
        wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
424 425
    else if (is_beyond_limit( addr, size, user_space_limit ))
        add_reserved_area( addr, size );
426 427 428 429 430 431 432 433 434
    else
        munmap( addr, size );
}


/***********************************************************************
 *           delete_view
 *
 * Deletes a view. The csVirtual section must be held by caller.
435
 */
436
static void delete_view( struct file_view *view ) /* [in] View */
437
{
438
    if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
439
    list_remove( &view->entry );
440
    if (view->mapping) close_handle( view->mapping );
441
    RtlFreeHeap( virtual_heap, 0, view );
442 443 444
}


445
/***********************************************************************
446
 *           create_view
447
 *
448
 * Create a view. The csVirtual section must be held by caller.
449
 */
450
static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
451
{
452 453
    struct file_view *view;
    struct list *ptr;
454
    int unix_prot = VIRTUAL_GetUnixProt( vprot );
455

456
    assert( !((UINT_PTR)base & page_mask) );
457
    assert( !(size & page_mask) );
458 459 460

    /* Create the view structure */

461 462 463 464 465
    if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
    {
        FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
        return STATUS_NO_MEMORY;
    }
466

467
    view->base    = base;
468 469
    view->size    = size;
    view->mapping = 0;
470
    view->map_protect = 0;
471
    view->protect = vprot;
472
    memset( view->prot, vprot, size >> page_shift );
473

474
    /* Insert it in the linked list */
475

476
    LIST_FOR_EACH( ptr, &views_list )
477
    {
478 479
        struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
        if (next->base > base) break;
480
    }
481
    list_add_before( ptr, &view->entry );
482

483 484 485
    /* Check for overlapping views. This can happen if the previous view
     * was a system view that got unmapped behind our back. In that case
     * we recover by simply deleting it. */
486

487
    if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
488
    {
489
        struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
490 491 492 493 494
        if ((char *)prev->base + prev->size > (char *)base)
        {
            TRACE( "overlapping prev view %p-%p for %p-%p\n",
                   prev->base, (char *)prev->base + prev->size,
                   base, (char *)base + view->size );
495
            assert( prev->protect & VPROT_SYSTEM );
496
            delete_view( prev );
497 498
        }
    }
499
    if ((ptr = list_next( &views_list, &view->entry )) != NULL)
500
    {
501 502 503 504 505 506
        struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
        if ((char *)base + view->size > (char *)next->base)
        {
            TRACE( "overlapping next view %p-%p for %p-%p\n",
                   next->base, (char *)next->base + next->size,
                   base, (char *)base + view->size );
507
            assert( next->protect & VPROT_SYSTEM );
508
            delete_view( next );
509
        }
510
    }
511 512

    *view_ret = view;
513 514
    VIRTUAL_DEBUG_DUMP_VIEW( view );

515
    if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
516
    {
517 518
        TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
        mprotect( base, size, unix_prot | PROT_EXEC );
519
    }
520
    return STATUS_SUCCESS;
521 522 523 524 525 526 527 528
}


/***********************************************************************
 *           VIRTUAL_GetWin32Prot
 *
 * Convert page protections to Win32 flags.
 */
529
static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
530
{
531 532 533 534
    DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
    if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
    if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
    return ret;
535 536 537 538
}


/***********************************************************************
539
 *           get_vprot_flags
540 541 542
 *
 * Build page protections from Win32 flags.
 *
543 544 545
 * PARAMS
 *      protect [I] Win32 protection flags
 *
546 547 548
 * RETURNS
 *	Value of page protection flags
 */
549
static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot, BOOL image )
550 551 552 553
{
    switch(protect & 0xff)
    {
    case PAGE_READONLY:
554
        *vprot = VPROT_READ;
555 556
        break;
    case PAGE_READWRITE:
557 558 559 560
        if (image)
            *vprot = VPROT_READ | VPROT_WRITECOPY;
        else
            *vprot = VPROT_READ | VPROT_WRITE;
561 562
        break;
    case PAGE_WRITECOPY:
563
        *vprot = VPROT_READ | VPROT_WRITECOPY;
564 565
        break;
    case PAGE_EXECUTE:
566
        *vprot = VPROT_EXEC;
567 568
        break;
    case PAGE_EXECUTE_READ:
569
        *vprot = VPROT_EXEC | VPROT_READ;
570 571
        break;
    case PAGE_EXECUTE_READWRITE:
572 573 574 575
        if (image)
            *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
        else
            *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
576 577
        break;
    case PAGE_EXECUTE_WRITECOPY:
578
        *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
579 580
        break;
    case PAGE_NOACCESS:
581
        *vprot = 0;
582
        break;
583
    default:
584
        return STATUS_INVALID_PAGE_PROTECTION;
585
    }
586 587 588
    if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
    if (protect & PAGE_NOCACHE) *vprot |= VPROT_NOCACHE;
    return STATUS_SUCCESS;
589 590 591
}


592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
/***********************************************************************
 *           mprotect_exec
 *
 * Wrapper for mprotect, adds PROT_EXEC if forced by force_exec_prot
 */
static inline int mprotect_exec( void *base, size_t size, int unix_prot, unsigned int view_protect )
{
    if (force_exec_prot && !(view_protect & VPROT_NOEXEC) &&
        (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
    {
        TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
        if (!mprotect( base, size, unix_prot | PROT_EXEC )) return 0;
        /* exec + write may legitimately fail, in that case fall back to write only */
        if (!(unix_prot & PROT_WRITE)) return -1;
    }

    return mprotect( base, size, unix_prot );
}

611 612 613 614 615 616 617 618 619
/***********************************************************************
 *           VIRTUAL_SetProt
 *
 * Change the protection of a range of pages.
 *
 * RETURNS
 *	TRUE: Success
 *	FALSE: Failure
 */
620
static BOOL VIRTUAL_SetProt( struct file_view *view, /* [in] Pointer to view */
621
                             void *base,      /* [in] Starting address */
622
                             size_t size,     /* [in] Size in bytes */
623 624
                             BYTE vprot )     /* [in] Protections to use */
{
625
    int unix_prot = VIRTUAL_GetUnixProt(vprot);
626
    BYTE *p = view->prot + (((char *)base - (char *)view->base) >> page_shift);
627

628 629 630
    TRACE("%p-%p %s\n",
          base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );

631 632 633 634 635 636 637 638 639 640 641 642 643 644
    if (view->protect & VPROT_WRITEWATCH)
    {
        /* each page may need different protections depending on write watch flag */
        UINT i, count;
        char *addr = base;
        int prot;

        p[0] = vprot | (p[0] & VPROT_WRITEWATCH);
        unix_prot = VIRTUAL_GetUnixProt( p[0] );
        for (count = i = 1; i < size >> page_shift; i++, count++)
        {
            p[i] = vprot | (p[i] & VPROT_WRITEWATCH);
            prot = VIRTUAL_GetUnixProt( p[i] );
            if (prot == unix_prot) continue;
645
            mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
646 647 648 649
            addr += count << page_shift;
            unix_prot = prot;
            count = 0;
        }
650
        if (count) mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
651 652 653 654
        VIRTUAL_DEBUG_DUMP_VIEW( view );
        return TRUE;
    }

655 656 657
    /* if setting stack guard pages, store the permissions first, as the guard may be
     * triggered at any point after mprotect and change the permissions again */
    if ((vprot & VPROT_GUARD) &&
658 659
        (base >= NtCurrentTeb()->DeallocationStack) &&
        (base < NtCurrentTeb()->Tib.StackBase))
660
    {
661
        memset( p, vprot, size >> page_shift );
662 663 664 665 666
        mprotect( base, size, unix_prot );
        VIRTUAL_DEBUG_DUMP_VIEW( view );
        return TRUE;
    }

667 668
    if (mprotect_exec( base, size, unix_prot, view->protect )) /* FIXME: last error */
        return FALSE;
669

670
    memset( p, vprot, size >> page_shift );
671 672 673 674 675
    VIRTUAL_DEBUG_DUMP_VIEW( view );
    return TRUE;
}


676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
/***********************************************************************
 *           reset_write_watches
 *
 * Reset write watches in a memory range.
 */
static void reset_write_watches( struct file_view *view, void *base, SIZE_T size )
{
    SIZE_T i, count;
    int prot, unix_prot;
    char *addr = base;
    BYTE *p = view->prot + ((addr - (char *)view->base) >> page_shift);

    p[0] |= VPROT_WRITEWATCH;
    unix_prot = VIRTUAL_GetUnixProt( p[0] );
    for (count = i = 1; i < size >> page_shift; i++, count++)
    {
        p[i] |= VPROT_WRITEWATCH;
        prot = VIRTUAL_GetUnixProt( p[i] );
        if (prot == unix_prot) continue;
695
        mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
696 697 698 699
        addr += count << page_shift;
        unix_prot = prot;
        count = 0;
    }
700
    if (count) mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
701 702 703
}


704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
/***********************************************************************
 *           unmap_extra_space
 *
 * Release the extra memory while keeping the range starting on the granularity boundary.
 */
static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
{
    if ((ULONG_PTR)ptr & mask)
    {
        size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
        munmap( ptr, extra );
        ptr = (char *)ptr + extra;
        total_size -= extra;
    }
    if (total_size > wanted_size)
        munmap( (char *)ptr + wanted_size, total_size - wanted_size );
    return ptr;
}


724 725 726 727 728
struct alloc_area
{
    size_t size;
    size_t mask;
    int    top_down;
729
    void  *limit;
730 731 732 733 734 735 736 737 738 739 740 741 742 743
    void  *result;
};

/***********************************************************************
 *           alloc_reserved_area_callback
 *
 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
 */
static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
{
    struct alloc_area *alloc = arg;
    void *end = (char *)start + size;

    if (start < address_space_start) start = address_space_start;
744
    if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
    if (start >= end) return 0;

    /* make sure we don't touch the preloader reserved range */
    if (preload_reserve_end >= start)
    {
        if (preload_reserve_end >= end)
        {
            if (preload_reserve_start <= start) return 0;  /* no space in that area */
            if (preload_reserve_start < end) end = preload_reserve_start;
        }
        else if (preload_reserve_start <= start) start = preload_reserve_end;
        else
        {
            /* range is split in two by the preloader reservation, try first part */
            if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
                                                 alloc->mask, alloc->top_down )))
                return 1;
            /* then fall through to try second part */
            start = preload_reserve_end;
        }
    }
    if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
        return 1;

    return 0;
}


773
/***********************************************************************
774
 *           map_view
775
 *
776 777
 * Create a view and mmap the corresponding memory area.
 * The csVirtual section must be held by caller.
778
 */
779
static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
780
                          int top_down, unsigned int vprot )
781
{
782 783
    void *ptr;
    NTSTATUS status;
784

785
    if (base)
786
    {
787
        if (is_beyond_limit( base, size, address_space_limit ))
788 789 790
            return STATUS_WORKING_SET_LIMIT_RANGE;

        switch (wine_mmap_is_in_reserved_area( base, size ))
791
        {
792
        case -1: /* partially in a reserved area */
793
            return STATUS_CONFLICTING_ADDRESSES;
794 795 796 797 798 799 800 801 802 803

        case 0:  /* not in a reserved area, do a normal allocation */
            if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
            {
                if (errno == ENOMEM) return STATUS_NO_MEMORY;
                return STATUS_INVALID_PARAMETER;
            }
            if (ptr != base)
            {
                /* We couldn't get the address we wanted */
804
                if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
805 806 807 808 809 810 811 812 813 814 815 816
                else munmap( ptr, size );
                return STATUS_CONFLICTING_ADDRESSES;
            }
            break;

        default:
        case 1:  /* in a reserved area, make sure the address is available */
            if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
            /* replace the reserved area by our mapping */
            if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
                return STATUS_INVALID_PARAMETER;
            break;
817
        }
818
        if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
819
    }
820
    else
821
    {
822
        size_t view_size = size + mask + 1;
823 824 825 826 827
        struct alloc_area alloc;

        alloc.size = size;
        alloc.mask = mask;
        alloc.top_down = top_down;
828
        alloc.limit = user_space_limit;
829 830 831 832 833 834 835 836
        if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
        {
            ptr = alloc.result;
            TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
            if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
                return STATUS_INVALID_PARAMETER;
            goto done;
        }
837

838
        for (;;)
839
        {
840 841 842 843 844
            if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
            {
                if (errno == ENOMEM) return STATUS_NO_MEMORY;
                return STATUS_INVALID_PARAMETER;
            }
845
            TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
846
            /* if we got something beyond the user limit, unmap it and retry */
847
            if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
848
            else break;
849
        }
850
        ptr = unmap_extra_space( ptr, view_size, size, mask );
851
    }
852
done:
853
    status = create_view( view_ret, ptr, size, vprot );
854
    if (status != STATUS_SUCCESS) unmap_area( ptr, size );
855 856 857 858 859 860 861 862 863 864 865
    return status;
}


/***********************************************************************
 *           map_file_into_view
 *
 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
 * The csVirtual section must be held by caller.
 */
static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
866
                                    off_t offset, unsigned int vprot, BOOL removable )
867 868
{
    void *ptr;
869
    int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
870
    unsigned int flags = MAP_FIXED | ((vprot & VPROT_WRITECOPY) ? MAP_PRIVATE : MAP_SHARED);
871 872 873 874

    assert( start < view->size );
    assert( start + size <= view->size );

875 876 877 878 879 880 881
    if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (vprot & VPROT_READ))
    {
        TRACE( "forcing exec permission on mapping %p-%p\n",
               (char *)view->base + start, (char *)view->base + start + size - 1 );
        prot |= PROT_EXEC;
    }

882
    /* only try mmap if media is not removable (or if we require write access) */
883
    if (!removable || (flags & MAP_SHARED))
884
    {
885
        if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
886 887
            goto done;

888 889 890
        if ((errno == EPERM) && (prot & PROT_EXEC))
            ERR( "failed to set %08x protection on file map, noexec filesystem?\n", prot );

891 892 893 894
        /* mmap() failed; if this is because the file offset is not    */
        /* page-aligned (EINVAL), or because the underlying filesystem */
        /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
        if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
895
        if (flags & MAP_SHARED)  /* we cannot fake shared mappings */
896 897 898 899 900
        {
            if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
            ERR( "shared writable mmap not supported, broken filesystem?\n" );
            return STATUS_NOT_SUPPORTED;
        }
901
    }
902 903 904 905 906 907 908 909

    /* Reserve the memory with an anonymous mmap */
    ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
    if (ptr == (void *)-1) return FILE_GetNtStatus();
    /* Now read in the file */
    pread( fd, ptr, size, offset );
    if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot );  /* Set the right protection */
done:
910
    memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
911 912 913 914
    return STATUS_SUCCESS;
}


915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
/***********************************************************************
 *           get_committed_size
 *
 * Get the size of the committed range starting at base.
 * Also return the protections for the first page.
 */
static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
{
    SIZE_T i, start;

    start = ((char *)base - (char *)view->base) >> page_shift;
    *vprot = view->prot[start];

    if (view->mapping && !(view->protect & VPROT_COMMITTED))
    {
        SIZE_T ret = 0;
        SERVER_START_REQ( get_mapping_committed_range )
        {
933
            req->handle = wine_server_obj_handle( view->mapping );
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
            req->offset = start << page_shift;
            if (!wine_server_call( req ))
            {
                ret = reply->size;
                if (reply->committed)
                {
                    *vprot |= VPROT_COMMITTED;
                    for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
                }
            }
        }
        SERVER_END_REQ;
        return ret;
    }
    for (i = start + 1; i < view->size >> page_shift; i++)
        if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
    return (i - start) << page_shift;
}


954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
/***********************************************************************
 *           decommit_view
 *
 * Decommit some pages of a given view.
 * The csVirtual section must be held by caller.
 */
static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
{
    if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
    {
        BYTE *p = view->prot + (start >> page_shift);
        size >>= page_shift;
        while (size--) *p++ &= ~VPROT_COMMITTED;
        return STATUS_SUCCESS;
    }
    return FILE_GetNtStatus();
}


973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
/***********************************************************************
 *           allocate_dos_memory
 *
 * Allocate the DOS memory range.
 */
static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
{
    size_t size;
    void *addr = NULL;
    void * const low_64k = (void *)0x10000;
    const size_t dosmem_size = 0x110000;
    int unix_prot = VIRTUAL_GetUnixProt( vprot );
    struct list *ptr;

    /* check for existing view */

    if ((ptr = list_head( &views_list )))
    {
        struct file_view *first_view = LIST_ENTRY( ptr, struct file_view, entry );
        if (first_view->base < (void *)dosmem_size) return STATUS_CONFLICTING_ADDRESSES;
    }

    /* check without the first 64K */

    if (wine_mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
    {
        addr = wine_anon_mmap( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
        if (addr != low_64k)
        {
            if (addr != (void *)-1) munmap( addr, dosmem_size - 0x10000 );
            return map_view( view, NULL, dosmem_size, 0xffff, 0, vprot );
        }
    }

    /* now try to allocate the low 64K too */

    if (wine_mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
    {
        addr = wine_anon_mmap( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
        if (addr == (void *)page_size)
        {
1014 1015 1016 1017 1018 1019
            if (!wine_anon_mmap( NULL, page_size, unix_prot, MAP_FIXED ))
            {
                addr = NULL;
                TRACE( "successfully mapped low 64K range\n" );
            }
            else TRACE( "failed to map page 0\n" );
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
        }
        else
        {
            if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
            addr = low_64k;
            TRACE( "failed to map low 64K range\n" );
        }
    }

    /* now reserve the whole range */

    size = (char *)dosmem_size - (char *)addr;
    wine_anon_mmap( addr, size, unix_prot, MAP_FIXED );
    return create_view( view, addr, size, vprot );
}


1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
/***********************************************************************
 *           stat_mapping_file
 *
 * Stat the underlying file for a memory view.
 */
static NTSTATUS stat_mapping_file( struct file_view *view, struct stat *st )
{
    NTSTATUS status;
    int unix_fd, needs_close;

    if (!view->mapping) return STATUS_NOT_MAPPED_VIEW;
    if (!(status = server_get_unix_fd( view->mapping, 0, &unix_fd, &needs_close, NULL, NULL )))
    {
        if (fstat( unix_fd, st ) == -1) status = FILE_GetNtStatus();
        if (needs_close) close( unix_fd );
    }
    return status;
}


1057 1058 1059 1060 1061
/***********************************************************************
 *           map_image
 *
 * Map an executable (PE format) image into memory.
 */
1062
static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
1063
                           SIZE_T header_size, int shared_fd, HANDLE dup_mapping, unsigned int map_vprot, PVOID *addr_ptr )
1064 1065 1066
{
    IMAGE_DOS_HEADER *dos;
    IMAGE_NT_HEADERS *nt;
1067 1068
    IMAGE_SECTION_HEADER sections[96];
    IMAGE_SECTION_HEADER *sec;
1069
    IMAGE_DATA_DIRECTORY *imports;
1070 1071 1072
    NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
    int i;
    off_t pos;
1073
    sigset_t sigset;
1074
    struct stat st;
1075
    struct file_view *view = NULL;
1076
    char *ptr, *header_end, *header_start;
1077
    INT_PTR delta = 0;
1078 1079 1080

    /* zero-map the whole range */

1081
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1082

1083
    if (base >= (char *)address_space_start)  /* make sure the DOS area remains free */
1084
        status = map_view( &view, base, total_size, mask, FALSE,
1085 1086
                           VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );

1087
    if (status != STATUS_SUCCESS)
1088
        status = map_view( &view, NULL, total_size, mask, FALSE,
1089 1090 1091 1092 1093
                           VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );

    if (status != STATUS_SUCCESS) goto error;

    ptr = view->base;
1094 1095 1096 1097
    TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );

    /* map the header */

1098 1099 1100 1101 1102
    if (fstat( fd, &st ) == -1)
    {
        status = FILE_GetNtStatus();
        goto error;
    }
1103
    status = STATUS_INVALID_IMAGE_FORMAT;  /* generic error */
1104 1105
    if (!st.st_size) goto error;
    header_size = min( header_size, st.st_size );
1106
    if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1107
                            !dup_mapping ) != STATUS_SUCCESS) goto error;
1108 1109
    dos = (IMAGE_DOS_HEADER *)ptr;
    nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1110
    header_end = ptr + ROUND_SIZE( 0, header_size );
1111
    memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1112
    if ((char *)(nt + 1) > header_end) goto error;
1113
    header_start = (char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader;
1114
    if (nt->FileHeader.NumberOfSections > sizeof(sections)/sizeof(*sections)) goto error;
1115
    if (header_start + sizeof(*sections) * nt->FileHeader.NumberOfSections > header_end) goto error;
1116 1117
    /* Some applications (e.g. the Steam version of Borderlands) map over the top of the section headers,
     * copying the headers into local memory is necessary to properly load such applications. */
1118 1119
    memcpy(sections, header_start, sizeof(*sections) * nt->FileHeader.NumberOfSections);
    sec = sections;
1120 1121 1122 1123

    imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
    if (!imports->Size || !imports->VirtualAddress) imports = NULL;

1124 1125 1126 1127 1128 1129 1130
    /* check for non page-aligned binary */

    if (nt->OptionalHeader.SectionAlignment <= page_mask)
    {
        /* unaligned sections, this happens for native subsystem binaries */
        /* in that case Windows simply maps in the whole file */

1131 1132
        if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
                                !dup_mapping ) != STATUS_SUCCESS) goto error;
1133 1134

        /* check that all sections are loaded at the right offset */
1135
        if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
        for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
        {
            if (sec[i].VirtualAddress != sec[i].PointerToRawData)
                goto error;  /* Windows refuses to load in that case too */
        }

        /* set the image protections */
        VIRTUAL_SetProt( view, ptr, total_size,
                         VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );

1146
        /* no relocations are performed on non page-aligned binaries */
1147 1148 1149 1150
        goto done;
    }


1151 1152 1153 1154
    /* map all the sections */

    for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
    {
1155 1156
        static const SIZE_T sector_align = 0x1ff;
        SIZE_T map_size, file_start, file_size, end;
1157 1158

        if (!sec->Misc.VirtualSize)
1159
            map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1160 1161
        else
            map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1162 1163 1164 1165 1166

        /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
        file_start = sec->PointerToRawData & ~sector_align;
        file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
        if (file_size > map_size) file_size = map_size;
1167 1168

        /* a few sanity checks */
1169 1170
        end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
        if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1171
        {
1172 1173
            WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
                           sec->Name, sec->VirtualAddress, map_size, total_size );
1174 1175 1176 1177 1178 1179
            goto error;
        }

        if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
            (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
        {
1180
            TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1181 1182 1183 1184
                            sec->Name, ptr + sec->VirtualAddress,
                            sec->PointerToRawData, (int)pos, file_size, map_size,
                            sec->Characteristics );
            if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1185
                                    VPROT_COMMITTED | VPROT_READ | VPROT_WRITE, FALSE ) != STATUS_SUCCESS)
1186 1187 1188 1189 1190 1191 1192
            {
                ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
                goto error;
            }

            /* check if the import directory falls inside this section */
            if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1193
                imports->VirtualAddress < sec->VirtualAddress + map_size)
1194 1195 1196
            {
                UINT_PTR base = imports->VirtualAddress & ~page_mask;
                UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1197
                if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1198 1199 1200
                if (end > base)
                    map_file_into_view( view, shared_fd, base, end - base,
                                        pos + (base - sec->VirtualAddress),
1201
                                        VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY, FALSE );
1202
            }
1203
            pos += map_size;
1204 1205 1206
            continue;
        }

1207
        TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1208 1209
                        sec->Name, ptr + sec->VirtualAddress,
                        sec->PointerToRawData, sec->SizeOfRawData,
1210
                        sec->Misc.VirtualSize, sec->Characteristics );
1211

1212
        if (!sec->PointerToRawData || !file_size) continue;
1213

1214
        /* Note: if the section is not aligned properly map_file_into_view will magically
1215 1216
         *       fall back to read(), so we don't need to check anything here.
         */
1217 1218 1219 1220 1221
        end = file_start + file_size;
        if (sec->PointerToRawData >= st.st_size ||
            end > ((st.st_size + sector_align) & ~sector_align) ||
            end < file_start ||
            map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1222
                                VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1223
                                !dup_mapping ) != STATUS_SUCCESS)
1224 1225 1226 1227 1228
        {
            ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
            goto error;
        }

1229
        if (file_size & page_mask)
1230
        {
1231 1232
            end = ROUND_SIZE( 0, file_size );
            if (end > map_size) end = map_size;
1233
            TRACE_(module)("clearing %p - %p\n",
1234
                           ptr + sec->VirtualAddress + file_size,
1235
                           ptr + sec->VirtualAddress + end );
1236
            memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1237 1238 1239 1240 1241 1242
        }
    }


    /* perform base relocation, if necessary */

1243 1244 1245
    if (ptr != base &&
        ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
          !NtCurrentTeb()->Peb->ImageBaseAddress) )
1246
    {
1247
        IMAGE_BASE_RELOCATION *rel, *end;
1248 1249
        const IMAGE_DATA_DIRECTORY *relocs;

1250
        if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1251
        {
1252 1253
            WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
                           base, ptr );
1254
            status = STATUS_CONFLICTING_ADDRESSES;
1255 1256 1257
            goto error;
        }

1258 1259 1260 1261 1262 1263
        TRACE_(module)( "relocating from %p-%p to %p-%p\n",
                        base, base + total_size, ptr, ptr + total_size );

        relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
        rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
        end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1264
        delta = ptr - base;
1265

1266
        while (rel < end - 1 && rel->SizeOfBlock)
1267
        {
1268 1269 1270 1271 1272 1273
            if (rel->VirtualAddress >= total_size)
            {
                WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
                status = STATUS_ACCESS_VIOLATION;
                goto error;
            }
1274 1275 1276 1277
            rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
                                             (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
                                             (USHORT *)(rel + 1), delta );
            if (!rel) goto error;
1278 1279 1280 1281 1282
        }
    }

    /* set the image protections */

1283 1284
    VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );

1285
    sec = sections;
1286 1287
    for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
    {
1288
        SIZE_T size;
1289
        BYTE vprot = VPROT_COMMITTED;
1290 1291 1292 1293 1294 1295

        if (sec->Misc.VirtualSize)
            size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
        else
            size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );

1296
        if (sec->Characteristics & IMAGE_SCN_MEM_READ)    vprot |= VPROT_READ;
1297
        if (sec->Characteristics & IMAGE_SCN_MEM_WRITE)   vprot |= VPROT_WRITECOPY;
1298
        if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1299 1300 1301 1302 1303 1304

        /* Dumb game crack lets the AOEP point into a data section. Adjust. */
        if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
            (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
            vprot |= VPROT_EXEC;

1305 1306 1307
        if (!VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot ) && (vprot & VPROT_EXEC))
            ERR( "failed to set %08x protection on section %.8s, noexec filesystem?\n",
                 sec->Characteristics, sec->Name );
1308
    }
1309 1310

 done:
1311
    view->mapping = dup_mapping;
1312
    view->map_protect = map_vprot;
1313
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1314 1315

    *addr_ptr = ptr;
1316 1317 1318
#ifdef VALGRIND_LOAD_PDB_DEBUGINFO
    VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
#endif
1319
    if (ptr != base) return STATUS_IMAGE_NOT_AT_BASE;
1320 1321 1322
    return STATUS_SUCCESS;

 error:
1323
    if (view) delete_view( view );
1324
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1325
    if (dup_mapping) NtClose( dup_mapping );
1326 1327 1328 1329
    return status;
}


1330 1331
/* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
static int alloc_virtual_heap( void *base, size_t size, void *arg )
1332
{
1333 1334
    void **heap_base = arg;

1335
    if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1336
    if (size < VIRTUAL_HEAP_SIZE) return 0;
1337
    if (is_win64 && base < (void *)0x80000000) return 0;
1338 1339 1340
    *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
                                 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
    return (*heap_base != (void *)-1);
1341 1342
}

1343
/***********************************************************************
1344
 *           virtual_init
1345
 */
1346
void virtual_init(void)
1347
{
1348
    const char *preload;
1349
    void *heap_base;
1350
    size_t size;
1351 1352
    struct file_view *heap_view;

1353 1354
#if !defined(__i386__) && !defined(__x86_64__)
    page_size = sysconf( _SC_PAGESIZE );
1355 1356 1357 1358 1359
    page_mask = page_size - 1;
    /* Make sure we have a power of 2 */
    assert( !(page_size & page_mask) );
    page_shift = 0;
    while ((1 << page_shift) != page_size) page_shift++;
1360
    user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1361
#endif  /* page_mask */
1362 1363 1364 1365 1366 1367 1368 1369 1370
    if ((preload = getenv("WINEPRELOADRESERVE")))
    {
        unsigned long start, end;
        if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
        {
            preload_reserve_start = (void *)start;
            preload_reserve_end = (void *)end;
        }
    }
1371 1372 1373 1374 1375 1376 1377 1378 1379

    /* try to find space in a reserved area for the virtual heap */
    if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
        heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );

    assert( heap_base != (void *)-1 );
    virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
                                  VIRTUAL_HEAP_SIZE, NULL, NULL );
    create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1380

1381 1382 1383 1384
    /* make the DOS area accessible (except the low 64K) to hide bugs in broken apps like Excel 2003 */
    size = (char *)address_space_start - (char *)0x10000;
    if (size && wine_mmap_is_in_reserved_area( (void*)0x10000, size ) == 1)
        wine_anon_mmap( (void *)0x10000, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1385
}
1386 1387


1388
/***********************************************************************
1389
 *           virtual_init_threading
1390
 */
1391
void virtual_init_threading(void)
1392
{
1393
    use_locks = TRUE;
1394 1395 1396
}


1397 1398 1399 1400 1401
/***********************************************************************
 *           virtual_get_system_info
 */
void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
{
1402 1403 1404 1405 1406 1407 1408 1409 1410
    info->unknown                 = 0;
    info->KeMaximumIncrement      = 0;  /* FIXME */
    info->PageSize                = page_size;
    info->MmLowestPhysicalPage    = 1;
    info->MmHighestPhysicalPage   = 0x7fffffff / page_size;
    info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
    info->AllocationGranularity   = get_mask(0) + 1;
    info->LowestUserAddress       = (void *)0x10000;
    info->HighestUserAddress      = (char *)user_space_limit - 1;
1411
    info->ActiveProcessorsAffinityMask = get_system_affinity_mask();
1412
    info->NumberOfProcessors      = NtCurrentTeb()->Peb->NumberOfProcessors;
1413 1414 1415
}


1416
/***********************************************************************
André Hentschel's avatar
André Hentschel committed
1417
 *           virtual_create_builtin_view
1418
 */
1419
NTSTATUS virtual_create_builtin_view( void *module )
1420 1421 1422
{
    NTSTATUS status;
    sigset_t sigset;
1423 1424 1425
    IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
    SIZE_T size = nt->OptionalHeader.SizeOfImage;
    IMAGE_SECTION_HEADER *sec;
1426
    struct file_view *view;
1427 1428
    void *base;
    int i;
1429

1430 1431
    size = ROUND_SIZE( module, size );
    base = ROUND_ADDR( module, page_mask );
1432
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1433 1434
    status = create_view( &view, base, size, VPROT_SYSTEM | VPROT_IMAGE |
                          VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1435 1436
    if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1437 1438 1439

    if (status) return status;

1440 1441 1442
    /* The PE header is always read-only, no write, no execute. */
    view->prot[0] = VPROT_COMMITTED | VPROT_READ;

1443 1444 1445
    sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
    for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
    {
1446
        BYTE flags = VPROT_COMMITTED;
1447 1448 1449 1450 1451 1452 1453 1454

        if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
        if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
        if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
        memset (view->prot + (sec[i].VirtualAddress >> page_shift), flags,
                ROUND_SIZE( sec[i].VirtualAddress, sec[i].Misc.VirtualSize ) >> page_shift );
    }

1455 1456 1457 1458
    return status;
}


1459 1460 1461
/***********************************************************************
 *           virtual_alloc_thread_stack
 */
1462
NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1463
{
1464
    struct file_view *view;
1465 1466
    NTSTATUS status;
    sigset_t sigset;
1467
    SIZE_T size;
1468

1469
    if (!reserve_size || !commit_size)
1470
    {
1471 1472 1473
        IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
        if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
        if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1474
    }
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485

    size = max( reserve_size, commit_size );
    if (size < 1024 * 1024) size = 1024 * 1024;  /* Xlib needs a large stack */
    size = (size + 0xffff) & ~0xffff;  /* round to 64K boundary */

    server_enter_uninterrupted_section( &csVirtual, &sigset );

    if ((status = map_view( &view, NULL, size, 0xffff, 0,
                            VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
        goto done;

1486
#ifdef VALGRIND_STACK_REGISTER
1487
    VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1488 1489 1490 1491
#endif

    /* setup no access guard page */
    VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1492 1493
    VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
                     VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1494 1495

    /* note: limit is lower than base since the stack grows down */
1496 1497 1498
    teb->DeallocationStack = view->base;
    teb->Tib.StackBase     = (char *)view->base + view->size;
    teb->Tib.StackLimit    = (char *)view->base + 2 * page_size;
1499 1500 1501 1502 1503 1504
done:
    server_leave_uninterrupted_section( &csVirtual, &sigset );
    return status;
}


1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
/***********************************************************************
 *           virtual_clear_thread_stack
 *
 * Clear the stack contents before calling the main entry point, some broken apps need that.
 */
void virtual_clear_thread_stack(void)
{
    void *stack = NtCurrentTeb()->Tib.StackLimit;
    size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;

    wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
    if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
}


1520
/***********************************************************************
1521
 *           virtual_handle_fault
1522
 */
1523
NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err, BOOL on_signal_stack )
1524
{
1525
    struct file_view *view;
1526
    NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1527
    sigset_t sigset;
1528

1529
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1530
    if ((view = VIRTUAL_FindView( addr, 0 )))
1531
    {
1532
        void *page = ROUND_ADDR( addr, page_mask );
1533
        BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1534
        if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1535
        {
1536 1537 1538 1539 1540 1541 1542
            if (*vprot & VPROT_WRITEWATCH)
            {
                *vprot &= ~VPROT_WRITEWATCH;
                VIRTUAL_SetProt( view, page, page_size, *vprot );
            }
            /* ignore fault if page is writable now */
            if (VIRTUAL_GetUnixProt( *vprot ) & PROT_WRITE) ret = STATUS_SUCCESS;
1543
        }
1544
        if (!on_signal_stack && (*vprot & VPROT_GUARD))
1545 1546 1547 1548
        {
            VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
            ret = STATUS_GUARD_PAGE_VIOLATION;
        }
1549
    }
1550
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1551 1552 1553 1554
    return ret;
}


1555

1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
/***********************************************************************
 *           virtual_is_valid_code_address
 */
BOOL virtual_is_valid_code_address( const void *addr, SIZE_T size )
{
    struct file_view *view;
    BOOL ret = FALSE;
    sigset_t sigset;

    server_enter_uninterrupted_section( &csVirtual, &sigset );
    if ((view = VIRTUAL_FindView( addr, size )))
        ret = !(view->protect & VPROT_SYSTEM);  /* system views are not visible to the app */
    server_leave_uninterrupted_section( &csVirtual, &sigset );
    return ret;
}


1573 1574 1575 1576 1577 1578 1579 1580
/***********************************************************************
 *           virtual_handle_stack_fault
 *
 * Handle an access fault inside the current thread stack.
 * Called from inside a signal handler.
 */
BOOL virtual_handle_stack_fault( void *addr )
{
1581
    struct file_view *view;
1582 1583 1584
    BOOL ret = FALSE;

    RtlEnterCriticalSection( &csVirtual );  /* no need for signal masking inside signal handler */
1585
    if ((view = VIRTUAL_FindView( addr, 0 )))
1586 1587 1588 1589 1590 1591
    {
        void *page = ROUND_ADDR( addr, page_mask );
        BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
        if (vprot & VPROT_GUARD)
        {
            VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1592 1593 1594 1595 1596 1597
            NtCurrentTeb()->Tib.StackLimit = page;
            if ((char *)page >= (char *)NtCurrentTeb()->DeallocationStack + 2*page_size)
            {
                vprot = view->prot[((char *)page - page_size - (char *)view->base) >> page_shift];
                VIRTUAL_SetProt( view, (char *)page - page_size, page_size, vprot | VPROT_GUARD );
            }
1598 1599 1600 1601 1602 1603 1604 1605
            ret = TRUE;
        }
    }
    RtlLeaveCriticalSection( &csVirtual );
    return ret;
}


1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
/***********************************************************************
 *           virtual_check_buffer_for_read
 *
 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
 */
BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
{
    if (!size) return TRUE;
    if (!ptr) return FALSE;

    __TRY
    {
        volatile const char *p = ptr;
1619
        char dummy __attribute__((unused));
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
        SIZE_T count = size;

        while (count > page_size)
        {
            dummy = *p;
            p += page_size;
            count -= page_size;
        }
        dummy = p[0];
        dummy = p[count - 1];
    }
    __EXCEPT_PAGE_FAULT
    {
        return FALSE;
    }
    __ENDTRY
    return TRUE;
}


1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
/***********************************************************************
 *           virtual_check_buffer_for_write
 *
 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
 */
BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
{
    if (!size) return TRUE;
    if (!ptr) return FALSE;

    __TRY
    {
        volatile char *p = ptr;
        SIZE_T count = size;

        while (count > page_size)
        {
            *p |= 0;
            p += page_size;
            count -= page_size;
        }
        p[0] |= 0;
        p[count - 1] |= 0;
    }
    __EXCEPT_PAGE_FAULT
    {
        return FALSE;
    }
    __ENDTRY
    return TRUE;
}


1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
/***********************************************************************
 *           virtual_uninterrupted_read_memory
 *
 * Similar to NtReadVirtualMemory, but without wineserver calls. Moreover
 * permissions are checked before accessing each page, to ensure that no
 * exceptions can happen.
 */
SIZE_T virtual_uninterrupted_read_memory( const void *addr, void *buffer, SIZE_T size )
{
    struct file_view *view;
    sigset_t sigset;
    SIZE_T bytes_read = 0;

    if (!size) return 0;

    server_enter_uninterrupted_section( &csVirtual, &sigset );
    if ((view = VIRTUAL_FindView( addr, size )))
    {
        if (!(view->protect & VPROT_SYSTEM))
        {
            void *page = ROUND_ADDR( addr, page_mask );
            BYTE *p = view->prot + (((const char *)page - (const char *)view->base) >> page_shift);

            while (bytes_read < size && (VIRTUAL_GetUnixProt( *p++ ) & PROT_READ))
            {
                SIZE_T block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
                memcpy( buffer, addr, block_size );

                addr   = (const void *)((const char *)addr + block_size);
                buffer = (void *)((char *)buffer + block_size);
                bytes_read += block_size;
            }
        }
    }
    server_leave_uninterrupted_section( &csVirtual, &sigset );
    return bytes_read;
}


/***********************************************************************
 *           virtual_uninterrupted_write_memory
 *
 * Similar to NtWriteVirtualMemory, but without wineserver calls. Moreover
 * permissions are checked before accessing each page, to ensure that no
 * exceptions can happen.
 */
SIZE_T virtual_uninterrupted_write_memory( void *addr, const void *buffer, SIZE_T size )
{
    struct file_view *view;
    sigset_t sigset;
    SIZE_T bytes_written = 0;

    if (!size) return 0;

    server_enter_uninterrupted_section( &csVirtual, &sigset );
    if ((view = VIRTUAL_FindView( addr, size )))
    {
        if (!(view->protect & VPROT_SYSTEM))
        {
1732
            while (bytes_written < size)
1733
            {
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
                void *page = ROUND_ADDR( addr, page_mask );
                BYTE *p = view->prot + (((const char *)page - (const char *)view->base) >> page_shift);
                SIZE_T block_size;

                /* If the page is not writeable then check for write watches
                 * before giving up. This can be done without raising a real
                 * exception. Similar to virtual_handle_fault. */
                if (!(VIRTUAL_GetUnixProt( *p ) & PROT_WRITE))
                {
                    if (!(view->protect & VPROT_WRITEWATCH))
                        break;

                    if (*p & VPROT_WRITEWATCH)
                    {
                        *p &= ~VPROT_WRITEWATCH;
                        VIRTUAL_SetProt( view, page, page_size, *p );
                    }
                    /* ignore fault if page is writable now */
                    if (!(VIRTUAL_GetUnixProt( *p ) & PROT_WRITE))
                        break;
                }

                block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
                memcpy( addr, buffer, block_size );

                addr   = (void *)((char *)addr + block_size);
                buffer = (const void *)((const char *)buffer + block_size);
                bytes_written += block_size;
            }
        }
    }
    server_leave_uninterrupted_section( &csVirtual, &sigset );
    return bytes_written;
}


1770 1771 1772 1773 1774 1775 1776 1777
/***********************************************************************
 *           VIRTUAL_SetForceExec
 *
 * Whether to force exec prot on all views.
 */
void VIRTUAL_SetForceExec( BOOL enable )
{
    struct file_view *view;
1778
    sigset_t sigset;
1779

1780
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1781 1782 1783 1784 1785 1786 1787 1788
    if (!force_exec_prot != !enable)  /* change all existing views */
    {
        force_exec_prot = enable;

        LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
        {
            UINT i, count;
            char *addr = view->base;
1789 1790
            BYTE commit = view->mapping ? VPROT_COMMITTED : 0;  /* file mappings are always accessible */
            int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1791

1792
            if (view->protect & VPROT_NOEXEC) continue;
1793 1794
            for (count = i = 1; i < view->size >> page_shift; i++, count++)
            {
1795 1796
                int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
                if (prot == unix_prot) continue;
1797 1798 1799 1800 1801 1802 1803 1804 1805
                if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
                {
                    TRACE( "%s exec prot for %p-%p\n",
                           force_exec_prot ? "enabling" : "disabling",
                           addr, addr + (count << page_shift) - 1 );
                    mprotect( addr, count << page_shift,
                              unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
                }
                addr += (count << page_shift);
1806
                unix_prot = prot;
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
                count = 0;
            }
            if (count)
            {
                if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
                {
                    TRACE( "%s exec prot for %p-%p\n",
                           force_exec_prot ? "enabling" : "disabling",
                           addr, addr + (count << page_shift) - 1 );
                    mprotect( addr, count << page_shift,
                              unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
                }
            }
        }
    }
1822
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1823 1824
}

1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
struct free_range
{
    char *base;
    char *limit;
};

/* free reserved areas above the limit; callback for wine_mmap_enum_reserved_areas */
static int free_reserved_memory( void *base, size_t size, void *arg )
{
    struct free_range *range = arg;

    if ((char *)base >= range->limit) return 0;
    if ((char *)base + size <= range->base) return 0;
    if ((char *)base < range->base)
    {
        size -= range->base - (char *)base;
        base = range->base;
    }
    if ((char *)base + size > range->limit) size = range->limit - (char *)base;
    remove_reserved_area( base, size );
    return 1;  /* stop enumeration since the list has changed */
}
1847

1848
/***********************************************************************
1849
 *           virtual_release_address_space
1850
 *
1851
 * Release some address space once we have loaded and initialized the app.
1852
 */
1853
void virtual_release_address_space(void)
1854
{
1855 1856 1857
    struct free_range range;
    sigset_t sigset;

1858
    if (is_win64) return;
1859

1860 1861
    server_enter_uninterrupted_section( &csVirtual, &sigset );

1862 1863 1864 1865
    range.base  = (char *)0x82000000;
    range.limit = user_space_limit;

    if (range.limit > range.base)
1866 1867 1868
    {
        while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
    }
1869 1870 1871 1872 1873 1874 1875 1876 1877
    else
    {
#ifndef __APPLE__  /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
        range.base  = (char *)0x20000000;
        range.limit = (char *)0x7f000000;
        while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
#endif
    }

1878
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1879 1880 1881
}


1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
/***********************************************************************
 *           virtual_set_large_address_space
 *
 * Enable use of a large address space when allowed by the application.
 */
void virtual_set_large_address_space(void)
{
    IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );

    if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE)) return;
    /* no large address space on win9x */
    if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;

    user_space_limit = working_set_limit = address_space_limit;
}


1899 1900 1901 1902
/***********************************************************************
 *             NtAllocateVirtualMemory   (NTDLL.@)
 *             ZwAllocateVirtualMemory   (NTDLL.@)
 */
1903
NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1904
                                         SIZE_T *size_ptr, ULONG type, ULONG protect )
1905 1906
{
    void *base;
1907
    unsigned int vprot;
1908
    SIZE_T size = *size_ptr;
1909
    SIZE_T mask = get_mask( zero_bits );
1910 1911
    NTSTATUS status = STATUS_SUCCESS;
    struct file_view *view;
1912
    sigset_t sigset;
1913

1914
    TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1915 1916 1917

    if (!size) return STATUS_INVALID_PARAMETER;

1918
    if (process != NtCurrentProcess())
1919
    {
1920 1921 1922
        apc_call_t call;
        apc_result_t result;

1923 1924
        memset( &call, 0, sizeof(call) );

1925
        call.virtual_alloc.type      = APC_VIRTUAL_ALLOC;
1926
        call.virtual_alloc.addr      = wine_server_client_ptr( *ret );
1927 1928 1929 1930
        call.virtual_alloc.size      = *size_ptr;
        call.virtual_alloc.zero_bits = zero_bits;
        call.virtual_alloc.op_type   = type;
        call.virtual_alloc.prot      = protect;
1931
        status = server_queue_process_apc( process, &call, &result );
1932 1933 1934 1935
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_alloc.status == STATUS_SUCCESS)
        {
1936
            *ret      = wine_server_get_ptr( result.virtual_alloc.addr );
1937 1938 1939
            *size_ptr = result.virtual_alloc.size;
        }
        return result.virtual_alloc.status;
1940 1941 1942 1943
    }

    /* Round parameters to a page boundary */

1944
    if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1945

1946
    if ((status = get_vprot_flags( protect, &vprot, FALSE ))) return status;
1947
    if (vprot & VPROT_WRITECOPY) return STATUS_INVALID_PAGE_PROTECTION;
1948
    vprot |= VPROT_VALLOC;
1949 1950
    if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;

1951
    if (*ret)
1952 1953
    {
        if (type & MEM_RESERVE) /* Round down to 64k boundary */
1954
            base = ROUND_ADDR( *ret, mask );
1955
        else
1956 1957
            base = ROUND_ADDR( *ret, page_mask );
        size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1958

1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
        /* address 1 is magic to mean DOS area */
        if (!base && *ret == (void *)1 && size == 0x110000)
        {
            server_enter_uninterrupted_section( &csVirtual, &sigset );
            status = allocate_dos_memory( &view, vprot );
            if (status == STATUS_SUCCESS)
            {
                *ret = view->base;
                *size_ptr = view->size;
            }
            server_leave_uninterrupted_section( &csVirtual, &sigset );
            return status;
        }

1973
        /* disallow low 64k, wrap-around and kernel space */
1974
        if (((char *)base < (char *)0x10000) ||
1975
            ((char *)base + size < (char *)base) ||
1976
            is_beyond_limit( base, size, address_space_limit ))
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
            return STATUS_INVALID_PARAMETER;
    }
    else
    {
        base = NULL;
        size = (size + page_mask) & ~page_mask;
    }

    /* Compute the alloc type flags */

1987
    if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
1988
        (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1989
    {
1990 1991 1992
        WARN("called with wrong alloc type flags (%08x) !\n", type);
        return STATUS_INVALID_PARAMETER;
    }
1993

1994 1995
    /* Reserve the memory */

1996
    if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1997

1998
    if ((type & MEM_RESERVE) || !base)
1999
    {
2000
        if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
2001
        status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
2002
        if (status == STATUS_SUCCESS) base = view->base;
2003
    }
2004 2005 2006 2007 2008
    else if (type & MEM_RESET)
    {
        if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
        else madvise( base, size, MADV_DONTNEED );
    }
2009
    else  /* commit the pages */
2010
    {
2011
        if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
2012
        else if (view->mapping && (view->protect & VPROT_COMMITTED)) status = STATUS_ALREADY_COMMITTED;
2013
        else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
2014 2015 2016 2017
        else if (view->mapping && !(view->protect & VPROT_COMMITTED))
        {
            SERVER_START_REQ( add_mapping_committed_range )
            {
2018
                req->handle = wine_server_obj_handle( view->mapping );
2019 2020 2021 2022 2023 2024
                req->offset = (char *)base - (char *)view->base;
                req->size   = size;
                wine_server_call( req );
            }
            SERVER_END_REQ;
        }
2025 2026
    }

2027
    if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
2028 2029 2030 2031 2032 2033 2034

    if (status == STATUS_SUCCESS)
    {
        *ret = base;
        *size_ptr = size;
    }
    return status;
2035 2036 2037 2038 2039 2040 2041
}


/***********************************************************************
 *             NtFreeVirtualMemory   (NTDLL.@)
 *             ZwFreeVirtualMemory   (NTDLL.@)
 */
2042
NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
2043
{
2044
    struct file_view *view;
2045
    char *base;
2046
    sigset_t sigset;
2047
    NTSTATUS status = STATUS_SUCCESS;
2048
    LPVOID addr = *addr_ptr;
2049
    SIZE_T size = *size_ptr;
2050

2051
    TRACE("%p %p %08lx %x\n", process, addr, size, type );
2052

2053
    if (process != NtCurrentProcess())
2054
    {
2055 2056 2057
        apc_call_t call;
        apc_result_t result;

2058 2059
        memset( &call, 0, sizeof(call) );

2060
        call.virtual_free.type      = APC_VIRTUAL_FREE;
2061
        call.virtual_free.addr      = wine_server_client_ptr( addr );
2062 2063
        call.virtual_free.size      = size;
        call.virtual_free.op_type   = type;
2064
        status = server_queue_process_apc( process, &call, &result );
2065 2066 2067 2068
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_free.status == STATUS_SUCCESS)
        {
2069
            *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
2070 2071 2072
            *size_ptr = result.virtual_free.size;
        }
        return result.virtual_free.status;
2073 2074 2075 2076 2077 2078 2079
    }

    /* Fix the parameters */

    size = ROUND_SIZE( addr, size );
    base = ROUND_ADDR( addr, page_mask );

2080
    /* avoid freeing the DOS area when a broken app passes a NULL pointer */
2081
    if (!base) return STATUS_INVALID_PARAMETER;
2082

2083
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2084

2085
    if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
2086 2087 2088 2089
    {
        status = STATUS_INVALID_PARAMETER;
    }
    else if (type == MEM_RELEASE)
2090
    {
2091 2092
        /* Free the pages */

2093 2094 2095
        if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
        else
        {
2096
            delete_view( view );
2097 2098 2099
            *addr_ptr = base;
            *size_ptr = size;
        }
2100
    }
2101
    else if (type == MEM_DECOMMIT)
2102
    {
2103 2104
        status = decommit_pages( view, base - (char *)view->base, size );
        if (status == STATUS_SUCCESS)
2105 2106 2107 2108
        {
            *addr_ptr = base;
            *size_ptr = size;
        }
2109
    }
2110 2111
    else
    {
2112
        WARN("called with wrong free type flags (%08x) !\n", type);
2113
        status = STATUS_INVALID_PARAMETER;
2114
    }
2115

2116
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2117
    return status;
2118 2119
}

2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
static ULONG map_protection_to_access( ULONG vprot )
{
    vprot &= VPROT_READ | VPROT_WRITE | VPROT_EXEC | VPROT_WRITECOPY;
    if (vprot & VPROT_EXEC)
    {
        if (vprot & VPROT_WRITE) vprot |= VPROT_WRITECOPY;
    }
    else vprot &= ~VPROT_WRITECOPY;
    return vprot;
}

static BOOL is_compatible_protection( const struct file_view *view, ULONG new_prot )
{
    ULONG view_prot, map_prot;

    view_prot = map_protection_to_access( view->protect );
    new_prot = map_protection_to_access( new_prot );

    if (view_prot == new_prot) return TRUE;
    if (!view_prot) return FALSE;

    if ((view_prot & new_prot) != new_prot) return FALSE;

    map_prot = map_protection_to_access( view->map_protect );
    if ((map_prot & new_prot) == new_prot) return TRUE;

    return FALSE;
}
2148 2149 2150 2151 2152

/***********************************************************************
 *             NtProtectVirtualMemory   (NTDLL.@)
 *             ZwProtectVirtualMemory   (NTDLL.@)
 */
2153
NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
2154 2155
                                        ULONG new_prot, ULONG *old_prot )
{
2156
    struct file_view *view;
2157
    sigset_t sigset;
2158
    NTSTATUS status = STATUS_SUCCESS;
2159
    char *base;
2160
    BYTE vprot;
2161
    unsigned int new_vprot;
2162
    SIZE_T size = *size_ptr;
2163 2164
    LPVOID addr = *addr_ptr;

2165
    TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
2166

2167 2168 2169
    if (!old_prot)
        return STATUS_ACCESS_VIOLATION;

2170
    if (process != NtCurrentProcess())
2171
    {
2172 2173 2174
        apc_call_t call;
        apc_result_t result;

2175 2176
        memset( &call, 0, sizeof(call) );

2177
        call.virtual_protect.type = APC_VIRTUAL_PROTECT;
2178
        call.virtual_protect.addr = wine_server_client_ptr( addr );
2179 2180
        call.virtual_protect.size = size;
        call.virtual_protect.prot = new_prot;
2181
        status = server_queue_process_apc( process, &call, &result );
2182 2183 2184 2185
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_protect.status == STATUS_SUCCESS)
        {
2186
            *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
2187 2188 2189 2190
            *size_ptr = result.virtual_protect.size;
            if (old_prot) *old_prot = result.virtual_protect.prot;
        }
        return result.virtual_protect.status;
2191 2192 2193 2194 2195 2196 2197
    }

    /* Fix the parameters */

    size = ROUND_SIZE( addr, size );
    base = ROUND_ADDR( addr, page_mask );

2198
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2199

2200
    if ((view = VIRTUAL_FindView( base, size )))
2201 2202
    {
        /* Make sure all the pages are committed */
2203
        if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2204
        {
2205
            if (!(status = get_vprot_flags( new_prot, &new_vprot, view->protect & VPROT_IMAGE )))
2206 2207 2208 2209 2210
            {
                if ((new_vprot & VPROT_WRITECOPY) && (view->protect & VPROT_VALLOC))
                    status = STATUS_INVALID_PAGE_PROTECTION;
                else
                {
2211 2212 2213 2214 2215 2216 2217
                    if (!view->mapping || is_compatible_protection( view, new_vprot ))
                    {
                        new_vprot |= VPROT_COMMITTED;
                        if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
                        if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
                    }
                    else status = STATUS_INVALID_PAGE_PROTECTION;
2218 2219
                }
            }
2220
        }
2221
        else status = STATUS_NOT_COMMITTED;
2222
    }
2223 2224
    else status = STATUS_INVALID_PARAMETER;

2225
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2226

2227 2228 2229 2230 2231 2232
    if (status == STATUS_SUCCESS)
    {
        *addr_ptr = base;
        *size_ptr = size;
    }
    return status;
2233 2234
}

2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249

/* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
static int get_free_mem_state_callback( void *start, size_t size, void *arg )
{
    MEMORY_BASIC_INFORMATION *info = arg;
    void *end = (char *)start + size;

    if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;

    if (info->BaseAddress >= end)
    {
        if (info->AllocationBase < end) info->AllocationBase = end;
        return 0;
    }

2250
    if (info->BaseAddress >= start || start <= address_space_start)
2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
    {
        /* it's a real free area */
        info->State             = MEM_FREE;
        info->Protect           = PAGE_NOACCESS;
        info->AllocationBase    = 0;
        info->AllocationProtect = 0;
        info->Type              = 0;
        if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
            info->RegionSize = (char *)end - (char *)info->BaseAddress;
    }
    else /* outside of the reserved area, pretend it's allocated */
    {
        info->RegionSize        = (char *)start - (char *)info->BaseAddress;
        info->State             = MEM_RESERVE;
        info->Protect           = PAGE_NOACCESS;
        info->AllocationProtect = PAGE_NOACCESS;
        info->Type              = MEM_PRIVATE;
    }
    return 1;
}

2272 2273 2274 2275
#define UNIMPLEMENTED_INFO_CLASS(c) \
    case c: \
        FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
        return STATUS_INVALID_INFO_CLASS
2276 2277 2278 2279 2280 2281 2282

/***********************************************************************
 *             NtQueryVirtualMemory   (NTDLL.@)
 *             ZwQueryVirtualMemory   (NTDLL.@)
 */
NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
                                      MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2283
                                      SIZE_T len, SIZE_T *res_len )
2284
{
2285
    struct file_view *view;
2286
    char *base, *alloc_base = 0;
2287
    struct list *ptr;
2288
    SIZE_T size = 0;
2289
    MEMORY_BASIC_INFORMATION *info = buffer;
2290
    sigset_t sigset;
2291

2292 2293
    if (info_class != MemoryBasicInformation)
    {
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
        switch(info_class)
        {
            UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
            UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
            UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);

            default:
                FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n", 
                      process, addr, info_class, buffer, len, res_len);
                return STATUS_INVALID_INFO_CLASS;
        }
2305
    }
2306

2307
    if (process != NtCurrentProcess())
2308
    {
2309 2310 2311 2312
        NTSTATUS status;
        apc_call_t call;
        apc_result_t result;

2313 2314
        memset( &call, 0, sizeof(call) );

2315
        call.virtual_query.type = APC_VIRTUAL_QUERY;
2316
        call.virtual_query.addr = wine_server_client_ptr( addr );
2317
        status = server_queue_process_apc( process, &call, &result );
2318 2319 2320 2321
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_query.status == STATUS_SUCCESS)
        {
2322 2323
            info->BaseAddress       = wine_server_get_ptr( result.virtual_query.base );
            info->AllocationBase    = wine_server_get_ptr( result.virtual_query.alloc_base );
2324 2325 2326
            info->RegionSize        = result.virtual_query.size;
            info->Protect           = result.virtual_query.prot;
            info->AllocationProtect = result.virtual_query.alloc_prot;
2327 2328
            info->State             = (DWORD)result.virtual_query.state << 12;
            info->Type              = (DWORD)result.virtual_query.alloc_type << 16;
2329 2330
            if (info->RegionSize != result.virtual_query.size)  /* truncated */
                return STATUS_INVALID_PARAMETER;  /* FIXME */
2331 2332 2333
            if (res_len) *res_len = sizeof(*info);
        }
        return result.virtual_query.status;
2334 2335 2336 2337
    }

    base = ROUND_ADDR( addr, page_mask );

2338 2339
    if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;

2340 2341
    /* Find the view containing the address */

2342
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2343
    ptr = list_head( &views_list );
2344 2345
    for (;;)
    {
2346
        if (!ptr)
2347
        {
2348
            size = (char *)working_set_limit - alloc_base;
2349
            view = NULL;
2350 2351
            break;
        }
2352
        view = LIST_ENTRY( ptr, struct file_view, entry );
2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
        if ((char *)view->base > base)
        {
            size = (char *)view->base - alloc_base;
            view = NULL;
            break;
        }
        if ((char *)view->base + view->size > base)
        {
            alloc_base = view->base;
            size = view->size;
            break;
        }
        alloc_base = (char *)view->base + view->size;
2366
        ptr = list_next( &views_list, ptr );
2367 2368 2369 2370
    }

    /* Fill the info structure */

2371 2372 2373 2374
    info->AllocationBase = alloc_base;
    info->BaseAddress    = base;
    info->RegionSize     = size - (base - alloc_base);

2375 2376
    if (!view)
    {
2377 2378 2379
        if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
        {
            /* not in a reserved area at all, pretend it's allocated */
2380
#ifdef __i386__
2381 2382 2383 2384 2385 2386 2387 2388
            if (base >= (char *)address_space_start)
            {
                info->State             = MEM_RESERVE;
                info->Protect           = PAGE_NOACCESS;
                info->AllocationProtect = PAGE_NOACCESS;
                info->Type              = MEM_PRIVATE;
            }
            else
2389
#endif
2390 2391 2392 2393 2394 2395 2396
            {
                info->State             = MEM_FREE;
                info->Protect           = PAGE_NOACCESS;
                info->AllocationBase    = 0;
                info->AllocationProtect = 0;
                info->Type              = 0;
            }
2397
        }
2398 2399 2400
    }
    else
    {
2401 2402 2403
        BYTE vprot;
        SIZE_T range_size = get_committed_size( view, base, &vprot );

2404
        info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2405
        info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2406
        info->AllocationBase = alloc_base;
2407
        info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2408
        if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2409
        else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2410
        else info->Type = MEM_MAPPED;
2411
        for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2412
            if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2413
        info->RegionSize = size - (base - alloc_base);
2414
    }
2415
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2416

2417
    if (res_len) *res_len = sizeof(*info);
2418 2419 2420 2421 2422 2423 2424 2425
    return STATUS_SUCCESS;
}


/***********************************************************************
 *             NtLockVirtualMemory   (NTDLL.@)
 *             ZwLockVirtualMemory   (NTDLL.@)
 */
2426
NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2427
{
2428 2429 2430
    NTSTATUS status = STATUS_SUCCESS;

    if (process != NtCurrentProcess())
2431
    {
2432 2433 2434
        apc_call_t call;
        apc_result_t result;

2435 2436
        memset( &call, 0, sizeof(call) );

2437
        call.virtual_lock.type = APC_VIRTUAL_LOCK;
2438
        call.virtual_lock.addr = wine_server_client_ptr( *addr );
2439
        call.virtual_lock.size = *size;
2440
        status = server_queue_process_apc( process, &call, &result );
2441 2442 2443 2444
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_lock.status == STATUS_SUCCESS)
        {
2445
            *addr = wine_server_get_ptr( result.virtual_lock.addr );
2446 2447 2448
            *size = result.virtual_lock.size;
        }
        return result.virtual_lock.status;
2449
    }
2450 2451 2452 2453 2454 2455

    *size = ROUND_SIZE( *addr, *size );
    *addr = ROUND_ADDR( *addr, page_mask );

    if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
    return status;
2456 2457 2458 2459 2460 2461 2462
}


/***********************************************************************
 *             NtUnlockVirtualMemory   (NTDLL.@)
 *             ZwUnlockVirtualMemory   (NTDLL.@)
 */
2463
NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2464
{
2465 2466 2467
    NTSTATUS status = STATUS_SUCCESS;

    if (process != NtCurrentProcess())
2468
    {
2469 2470 2471
        apc_call_t call;
        apc_result_t result;

2472 2473
        memset( &call, 0, sizeof(call) );

2474
        call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2475
        call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2476
        call.virtual_unlock.size = *size;
2477
        status = server_queue_process_apc( process, &call, &result );
2478 2479 2480 2481
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_unlock.status == STATUS_SUCCESS)
        {
2482
            *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2483 2484 2485
            *size = result.virtual_unlock.size;
        }
        return result.virtual_unlock.status;
2486
    }
2487 2488 2489 2490 2491 2492

    *size = ROUND_SIZE( *addr, *size );
    *addr = ROUND_ADDR( *addr, page_mask );

    if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
    return status;
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504
}


/***********************************************************************
 *             NtCreateSection   (NTDLL.@)
 *             ZwCreateSection   (NTDLL.@)
 */
NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
                                 const LARGE_INTEGER *size, ULONG protect,
                                 ULONG sec_flags, HANDLE file )
{
    NTSTATUS ret;
2505
    unsigned int vprot;
2506
    DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2507 2508
    struct security_descriptor *sd = NULL;
    struct object_attributes objattr;
2509 2510 2511 2512 2513

    /* Check parameters */

    if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;

2514
    if ((ret = get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE ))) return ret;
2515

2516
    objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
2517
    objattr.sd_len = 0;
2518
    objattr.name_len = len;
2519 2520 2521 2522 2523 2524
    if (attr)
    {
        ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
        if (ret != STATUS_SUCCESS) return ret;
    }

2525
    if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2526 2527 2528 2529 2530 2531 2532
    if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
    if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;

    /* Create the server object */

    SERVER_START_REQ( create_mapping )
    {
2533 2534
        req->access      = access;
        req->attributes  = (attr) ? attr->Attributes : 0;
2535
        req->file_handle = wine_server_obj_handle( file );
2536
        req->size        = size ? size->QuadPart : 0;
2537
        req->protect     = vprot;
2538 2539
        wine_server_add_data( req, &objattr, sizeof(objattr) );
        if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2540 2541
        if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
        ret = wine_server_call( req );
2542
        *handle = wine_server_ptr_handle( reply->handle );
2543 2544
    }
    SERVER_END_REQ;
2545 2546 2547

    NTDLL_free_struct_sd( sd );

2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
    return ret;
}


/***********************************************************************
 *             NtOpenSection   (NTDLL.@)
 *             ZwOpenSection   (NTDLL.@)
 */
NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
{
    NTSTATUS ret;
    DWORD len = attr->ObjectName->Length;

    if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;

    SERVER_START_REQ( open_mapping )
    {
        req->access  = access;
2566
        req->attributes = attr->Attributes;
2567
        req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2568
        wine_server_add_data( req, attr->ObjectName->Buffer, len );
2569
        if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
    }
    SERVER_END_REQ;
    return ret;
}


/***********************************************************************
 *             NtMapViewOfSection   (NTDLL.@)
 *             ZwMapViewOfSection   (NTDLL.@)
 */
NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2581
                                    SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2582 2583 2584
                                    SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
{
    NTSTATUS res;
2585
    mem_size_t full_size;
2586
    ACCESS_MASK access;
2587
    SIZE_T size, mask = get_mask( zero_bits );
2588
    int unix_handle = -1, needs_close;
2589
    unsigned int map_vprot, vprot;
2590 2591
    void *base;
    struct file_view *view;
2592
    DWORD header_size;
2593
    HANDLE dup_mapping, shared_file;
2594
    LARGE_INTEGER offset;
2595
    sigset_t sigset;
2596 2597

    offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2598

2599
    TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2600
          handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2601

2602 2603
    /* Check parameters */

2604
    if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2605 2606
        return STATUS_INVALID_PARAMETER;

2607 2608 2609
    switch(protect)
    {
    case PAGE_NOACCESS:
2610
        access = SECTION_MAP_READ;
2611 2612 2613
        break;
    case PAGE_READWRITE:
    case PAGE_EXECUTE_READWRITE:
2614
        access = SECTION_MAP_WRITE;
2615 2616 2617 2618 2619 2620
        break;
    case PAGE_READONLY:
    case PAGE_WRITECOPY:
    case PAGE_EXECUTE:
    case PAGE_EXECUTE_READ:
    case PAGE_EXECUTE_WRITECOPY:
2621
        access = SECTION_MAP_READ;
2622 2623
        break;
    default:
2624
        return STATUS_INVALID_PAGE_PROTECTION;
2625 2626
    }

2627 2628 2629 2630 2631
    if (process != NtCurrentProcess())
    {
        apc_call_t call;
        apc_result_t result;

2632 2633
        memset( &call, 0, sizeof(call) );

2634
        call.map_view.type        = APC_MAP_VIEW;
2635
        call.map_view.handle      = wine_server_obj_handle( handle );
2636
        call.map_view.addr        = wine_server_client_ptr( *addr_ptr );
2637
        call.map_view.size        = *size_ptr;
2638
        call.map_view.offset      = offset.QuadPart;
2639 2640 2641
        call.map_view.zero_bits   = zero_bits;
        call.map_view.alloc_type  = alloc_type;
        call.map_view.prot        = protect;
2642
        res = server_queue_process_apc( process, &call, &result );
2643 2644
        if (res != STATUS_SUCCESS) return res;

2645
        if ((NTSTATUS)result.map_view.status >= 0)
2646
        {
2647
            *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2648 2649 2650 2651 2652
            *size_ptr = result.map_view.size;
        }
        return result.map_view.status;
    }

2653 2654
    SERVER_START_REQ( get_mapping_info )
    {
2655
        req->handle = wine_server_obj_handle( handle );
2656
        req->access = access;
2657
        res = wine_server_call( req );
2658
        map_vprot   = reply->protect;
2659
        base        = wine_server_get_ptr( reply->base );
2660
        full_size   = reply->size;
2661
        header_size = reply->header_size;
2662 2663
        dup_mapping = wine_server_ptr_handle( reply->mapping );
        shared_file = wine_server_ptr_handle( reply->shared_file );
2664
        if ((ULONG_PTR)base != reply->base) base = NULL;
2665 2666
    }
    SERVER_END_REQ;
2667
    if (res) return res;
2668

2669
    if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2670

2671
    if (map_vprot & VPROT_IMAGE)
2672
    {
2673 2674 2675 2676 2677 2678 2679
        size = full_size;
        if (size != full_size)  /* truncated */
        {
            WARN( "Modules larger than 4Gb (%s) not supported\n", wine_dbgstr_longlong(full_size) );
            res = STATUS_INVALID_PARAMETER;
            goto done;
        }
2680 2681
        if (shared_file)
        {
2682
            int shared_fd, shared_needs_close;
2683

2684
            if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2685
                                           &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2686
            res = map_image( handle, unix_handle, base, size, mask, header_size,
2687
                             shared_fd, dup_mapping, map_vprot, addr_ptr );
2688
            if (shared_needs_close) close( shared_fd );
2689 2690 2691 2692
            NtClose( shared_file );
        }
        else
        {
2693
            res = map_image( handle, unix_handle, base, size, mask, header_size,
2694
                             -1, dup_mapping, map_vprot, addr_ptr );
2695
        }
2696
        if (needs_close) close( unix_handle );
2697
        if (res >= 0) *size_ptr = size;
2698 2699 2700
        return res;
    }

2701 2702 2703
    res = STATUS_INVALID_PARAMETER;
    if (offset.QuadPart >= full_size) goto done;
    if (*size_ptr)
2704
    {
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717
        if (*size_ptr > full_size - offset.QuadPart) goto done;
        size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
        if (size < *size_ptr) goto done;  /* wrap-around */
    }
    else
    {
        size = full_size - offset.QuadPart;
        if (size != full_size - offset.QuadPart)  /* truncated */
        {
            WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
                  wine_dbgstr_longlong(full_size) );
            goto done;
        }
2718 2719 2720 2721
    }

    /* Reserve a properly aligned area */

2722
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2723

2724
    get_vprot_flags( protect, &vprot, map_vprot & VPROT_IMAGE );
2725
    vprot |= (map_vprot & VPROT_COMMITTED);
2726
    res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2727 2728
    if (res)
    {
2729
        server_leave_uninterrupted_section( &csVirtual, &sigset );
2730 2731
        goto done;
    }
2732 2733 2734

    /* Map the file */

2735
    TRACE("handle=%p size=%lx offset=%x%08x\n",
2736
          handle, size, offset.u.HighPart, offset.u.LowPart );
2737

2738
    res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2739
    if (res == STATUS_SUCCESS)
2740
    {
2741 2742
        *addr_ptr = view->base;
        *size_ptr = size;
2743
        view->mapping = dup_mapping;
2744
        view->map_protect = map_vprot;
2745
        dup_mapping = 0;  /* don't close it */
2746 2747
    }
    else
2748
    {
2749
        ERR( "map_file_into_view %p %lx %x%08x failed\n",
2750
             view->base, size, offset.u.HighPart, offset.u.LowPart );
2751
        delete_view( view );
2752 2753
    }

2754
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2755 2756

done:
2757
    if (dup_mapping) NtClose( dup_mapping );
2758
    if (needs_close) close( unix_handle );
2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
    return res;
}


/***********************************************************************
 *             NtUnmapViewOfSection   (NTDLL.@)
 *             ZwUnmapViewOfSection   (NTDLL.@)
 */
NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
{
2769
    struct file_view *view;
2770
    NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
2771
    sigset_t sigset;
2772 2773
    void *base = ROUND_ADDR( addr, page_mask );

2774
    if (process != NtCurrentProcess())
2775
    {
2776 2777 2778
        apc_call_t call;
        apc_result_t result;

2779 2780
        memset( &call, 0, sizeof(call) );

2781
        call.unmap_view.type = APC_UNMAP_VIEW;
2782
        call.unmap_view.addr = wine_server_client_ptr( addr );
2783
        status = server_queue_process_apc( process, &call, &result );
2784 2785
        if (status == STATUS_SUCCESS) status = result.unmap_view.status;
        return status;
2786
    }
2787

2788
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2789
    if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base) && !(view->protect & VPROT_VALLOC))
2790
    {
2791
        delete_view( view );
2792 2793
        status = STATUS_SUCCESS;
    }
2794
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2795
    return status;
2796 2797 2798 2799 2800 2801 2802 2803
}


/***********************************************************************
 *             NtFlushVirtualMemory   (NTDLL.@)
 *             ZwFlushVirtualMemory   (NTDLL.@)
 */
NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2804
                                      SIZE_T *size_ptr, ULONG unknown )
2805
{
2806
    struct file_view *view;
2807
    NTSTATUS status = STATUS_SUCCESS;
2808
    sigset_t sigset;
2809 2810
    void *addr = ROUND_ADDR( *addr_ptr, page_mask );

2811
    if (process != NtCurrentProcess())
2812
    {
2813 2814 2815
        apc_call_t call;
        apc_result_t result;

2816 2817
        memset( &call, 0, sizeof(call) );

2818
        call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2819
        call.virtual_flush.addr = wine_server_client_ptr( addr );
2820
        call.virtual_flush.size = *size_ptr;
2821
        status = server_queue_process_apc( process, &call, &result );
2822 2823 2824 2825
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_flush.status == STATUS_SUCCESS)
        {
2826
            *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2827 2828 2829
            *size_ptr = result.virtual_flush.size;
        }
        return result.virtual_flush.status;
2830
    }
2831

2832
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2833
    if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2834 2835 2836 2837
    else
    {
        if (!*size_ptr) *size_ptr = view->size;
        *addr_ptr = addr;
2838 2839 2840
#ifdef MS_ASYNC
        if (msync( addr, *size_ptr, MS_ASYNC )) status = STATUS_NOT_MAPPED_DATA;
#endif
2841
    }
2842
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2843
    return status;
2844
}
2845 2846


2847 2848 2849 2850 2851 2852 2853
/***********************************************************************
 *             NtGetWriteWatch   (NTDLL.@)
 *             ZwGetWriteWatch   (NTDLL.@)
 */
NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
                                 ULONG_PTR *count, ULONG *granularity )
{
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867
    struct file_view *view;
    NTSTATUS status = STATUS_SUCCESS;
    sigset_t sigset;

    size = ROUND_SIZE( base, size );
    base = ROUND_ADDR( base, page_mask );

    if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
    if (!*count || !size) return STATUS_INVALID_PARAMETER;
    if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;

    if (!addresses) return STATUS_ACCESS_VIOLATION;

    TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
2868
           addresses, *count );
2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891

    server_enter_uninterrupted_section( &csVirtual, &sigset );

    if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
    {
        ULONG_PTR pos = 0;
        char *addr = base;
        char *end = addr + size;

        while (pos < *count && addr < end)
        {
            BYTE prot = view->prot[(addr - (char *)view->base) >> page_shift];
            if (!(prot & VPROT_WRITEWATCH)) addresses[pos++] = addr;
            addr += page_size;
        }
        if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( view, base, addr - (char *)base );
        *count = pos;
        *granularity = page_size;
    }
    else status = STATUS_INVALID_PARAMETER;

    server_leave_uninterrupted_section( &csVirtual, &sigset );
    return status;
2892 2893 2894 2895 2896 2897 2898 2899 2900
}


/***********************************************************************
 *             NtResetWriteWatch   (NTDLL.@)
 *             ZwResetWriteWatch   (NTDLL.@)
 */
NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
{
2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920
    struct file_view *view;
    NTSTATUS status = STATUS_SUCCESS;
    sigset_t sigset;

    size = ROUND_SIZE( base, size );
    base = ROUND_ADDR( base, page_mask );

    TRACE( "%p %p-%p\n", process, base, (char *)base + size );

    if (!size) return STATUS_INVALID_PARAMETER;

    server_enter_uninterrupted_section( &csVirtual, &sigset );

    if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
        reset_write_watches( view, base, size );
    else
        status = STATUS_INVALID_PARAMETER;

    server_leave_uninterrupted_section( &csVirtual, &sigset );
    return status;
2921 2922 2923
}


2924 2925 2926 2927 2928 2929 2930 2931 2932
/***********************************************************************
 *             NtReadVirtualMemory   (NTDLL.@)
 *             ZwReadVirtualMemory   (NTDLL.@)
 */
NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
                                     SIZE_T size, SIZE_T *bytes_read )
{
    NTSTATUS status;

2933
    if (virtual_check_buffer_for_write( buffer, size ))
2934
    {
2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947
        SERVER_START_REQ( read_process_memory )
        {
            req->handle = wine_server_obj_handle( process );
            req->addr   = wine_server_client_ptr( addr );
            wine_server_set_reply( req, buffer, size );
            if ((status = wine_server_call( req ))) size = 0;
        }
        SERVER_END_REQ;
    }
    else
    {
        status = STATUS_ACCESS_VIOLATION;
        size = 0;
2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962
    }
    if (bytes_read) *bytes_read = size;
    return status;
}


/***********************************************************************
 *             NtWriteVirtualMemory   (NTDLL.@)
 *             ZwWriteVirtualMemory   (NTDLL.@)
 */
NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
                                      SIZE_T size, SIZE_T *bytes_written )
{
    NTSTATUS status;

2963
    if (virtual_check_buffer_for_read( buffer, size ))
2964
    {
2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977
        SERVER_START_REQ( write_process_memory )
        {
            req->handle     = wine_server_obj_handle( process );
            req->addr       = wine_server_client_ptr( addr );
            wine_server_add_data( req, buffer, size );
            if ((status = wine_server_call( req ))) size = 0;
        }
        SERVER_END_REQ;
    }
    else
    {
        status = STATUS_PARTIAL_COPY;
        size = 0;
2978 2979 2980 2981
    }
    if (bytes_written) *bytes_written = size;
    return status;
}
2982 2983 2984 2985 2986 2987 2988 2989


/***********************************************************************
 *             NtAreMappedFilesTheSame   (NTDLL.@)
 *             ZwAreMappedFilesTheSame   (NTDLL.@)
 */
NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
{
2990 2991 2992 2993 2994
    struct file_view *view1, *view2;
    struct stat st1, st2;
    NTSTATUS status;
    sigset_t sigset;

2995 2996
    TRACE("%p %p\n", addr1, addr2);

2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007
    server_enter_uninterrupted_section( &csVirtual, &sigset );

    view1 = VIRTUAL_FindView( addr1, 0 );
    view2 = VIRTUAL_FindView( addr2, 0 );

    if (!view1 || !view2)
        status = STATUS_INVALID_ADDRESS;
    else if ((view1->protect & VPROT_VALLOC) || (view2->protect & VPROT_VALLOC))
        status = STATUS_CONFLICTING_ADDRESSES;
    else if (view1 == view2)
        status = STATUS_SUCCESS;
3008 3009
    else if (!(view1->protect & VPROT_IMAGE) || !(view2->protect & VPROT_IMAGE))
        status = STATUS_NOT_SAME_DEVICE;
3010 3011 3012 3013 3014 3015 3016 3017
    else if (!stat_mapping_file( view1, &st1 ) && !stat_mapping_file( view2, &st2 ) &&
             st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
        status = STATUS_SUCCESS;
    else
        status = STATUS_NOT_SAME_DEVICE;

    server_leave_uninterrupted_section( &csVirtual, &sigset );
    return status;
3018
}