virtual.c 88.7 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 30 31 32
 */

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

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

48 49
#define NONAMELESSUNION
#define NONAMELESSSTRUCT
50
#include "ntstatus.h"
51
#define WIN32_NO_STATUS
52
#include "windef.h"
53 54 55
#include "winternl.h"
#include "wine/library.h"
#include "wine/server.h"
56
#include "wine/exception.h"
57
#include "wine/list.h"
58
#include "wine/debug.h"
59
#include "ntdll_misc.h"
60 61 62 63 64 65 66 67

WINE_DEFAULT_DEBUG_CHANNEL(virtual);
WINE_DECLARE_DEBUG_CHANNEL(module);

#ifndef MS_SYNC
#define MS_SYNC 0
#endif

68 69 70 71
#ifndef MAP_NORESERVE
#define MAP_NORESERVE 0
#endif

72
/* File view */
73
typedef struct file_view
74
{
75
    struct list   entry;       /* Entry in global view list */
76
    void         *base;        /* Base address */
77
    size_t        size;        /* Size in bytes */
78
    HANDLE        mapping;     /* Handle to the file mapping */
79
    unsigned int  protect;     /* Protection for all pages at allocation time */
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    BYTE          prot[1];     /* Protection byte for each page */
} FILE_VIEW;


/* 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 */
};

105
static struct list views_list = LIST_INIT(views_list);
106

107 108
static RTL_CRITICAL_SECTION csVirtual;
static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
109 110 111
{
    0, 0, &csVirtual,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
112
      0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
113
};
114
static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
115 116 117 118 119 120

#ifdef __i386__
/* These are always the same on an i386, and it will be faster this way */
# define page_mask  0xfff
# define page_shift 12
# define page_size  0x1000
121
/* Note: these are Windows limits, you cannot change them. */
122 123
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 */
124
static void *working_set_limit   = (void *)0x7fff0000;  /* top of the current working set */
125 126
#else
static UINT page_shift;
127
static UINT_PTR page_size;
128
static UINT_PTR page_mask;
129 130 131
static void *address_space_limit;
static void *user_space_limit;
static void *working_set_limit;
132 133 134
#endif  /* __i386__ */

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

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

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

143 144 145
#define VIRTUAL_HEAP_SIZE (4*1024*1024)

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

151 152 153 154 155 156 157 158 159 160

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


168 169 170 171 172 173 174 175 176 177 178 179 180 181
/***********************************************************************
 *           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;
        if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
        if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
        if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
182
        if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
183 184 185 186 187 188
    }
    if (!prot) prot = PROT_NONE;
    return prot;
}


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

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

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


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

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


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

259
    LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
260
    {
261 262 263 264 265
        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;
266
    }
267
    return NULL;
268 269 270
}


271 272 273 274 275 276 277 278 279 280 281
/***********************************************************************
 *           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;
}


282
/***********************************************************************
283
 *           find_view_range
284
 *
285 286 287 288 289
 * 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 )
{
290
    struct file_view *view;
291

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


301 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
/***********************************************************************
 *           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;
}


348 349
/***********************************************************************
 *           add_reserved_area
350
 *
351 352 353 354 355 356 357
 * 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 );

358
    if (addr < user_space_limit)
359 360
    {
        /* unmap the part of the area that is below the limit */
361 362 363 364
        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;
365
    }
366 367
    /* blow away existing mappings */
    wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
368 369 370 371 372 373 374 375 376
    wine_mmap_add_reserved_area( addr, size );
}


/***********************************************************************
 *           is_beyond_limit
 *
 * Check if an address range goes beyond a given limit.
 */
377
static inline int is_beyond_limit( const void *addr, size_t size, const void *limit )
378
{
379
    return (addr >= limit || (const char *)addr + size > (const char *)limit);
380 381 382 383 384 385 386 387 388 389 390 391 392
}


/***********************************************************************
 *           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 );
393 394
    else if (is_beyond_limit( addr, size, user_space_limit ))
        add_reserved_area( addr, size );
395 396 397 398 399 400 401 402 403
    else
        munmap( addr, size );
}


/***********************************************************************
 *           delete_view
 *
 * Deletes a view. The csVirtual section must be held by caller.
404
 */
405
static void delete_view( struct file_view *view ) /* [in] View */
406
{
407
    if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
408
    list_remove( &view->entry );
409
    if (view->mapping) NtClose( view->mapping );
410
    RtlFreeHeap( virtual_heap, 0, view );
411 412 413
}


414
/***********************************************************************
415
 *           create_view
416
 *
417
 * Create a view. The csVirtual section must be held by caller.
418
 */
419
static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
420
{
421 422
    struct file_view *view;
    struct list *ptr;
423
    int unix_prot = VIRTUAL_GetUnixProt( vprot );
424

425
    assert( !((UINT_PTR)base & page_mask) );
426
    assert( !(size & page_mask) );
427 428 429

    /* Create the view structure */

430 431 432 433 434
    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;
    }
435

436
    view->base    = base;
437 438
    view->size    = size;
    view->mapping = 0;
439
    view->protect = vprot;
440
    memset( view->prot, vprot, size >> page_shift );
441

442
    /* Insert it in the linked list */
443

444
    LIST_FOR_EACH( ptr, &views_list )
445
    {
446 447
        struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
        if (next->base > base) break;
448
    }
449
    list_add_before( ptr, &view->entry );
450

451 452 453
    /* 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. */
454

455
    if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
456
    {
457
        struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
458 459 460 461 462
        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 );
463
            assert( prev->protect & VPROT_SYSTEM );
464
            delete_view( prev );
465 466
        }
    }
467
    if ((ptr = list_next( &views_list, &view->entry )) != NULL)
468
    {
469 470 471 472 473 474
        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 );
475
            assert( next->protect & VPROT_SYSTEM );
476
            delete_view( next );
477
        }
478
    }
479 480

    *view_ret = view;
481 482
    VIRTUAL_DEBUG_DUMP_VIEW( view );

483
    if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
484
    {
485 486
        TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
        mprotect( base, size, unix_prot | PROT_EXEC );
487
    }
488
    return STATUS_SUCCESS;
489 490 491 492 493 494 495 496
}


/***********************************************************************
 *           VIRTUAL_GetWin32Prot
 *
 * Convert page protections to Win32 flags.
 */
497
static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
498
{
499 500 501 502
    DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
    if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
    if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
    return ret;
503 504 505 506
}


/***********************************************************************
507
 *           get_vprot_flags
508 509 510
 *
 * Build page protections from Win32 flags.
 *
511 512 513
 * PARAMS
 *      protect [I] Win32 protection flags
 *
514 515 516
 * RETURNS
 *	Value of page protection flags
 */
517
static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot )
518 519 520 521
{
    switch(protect & 0xff)
    {
    case PAGE_READONLY:
522
        *vprot = VPROT_READ;
523 524
        break;
    case PAGE_READWRITE:
525
        *vprot = VPROT_READ | VPROT_WRITE;
526 527
        break;
    case PAGE_WRITECOPY:
528
        *vprot = VPROT_READ | VPROT_WRITECOPY;
529 530
        break;
    case PAGE_EXECUTE:
531
        *vprot = VPROT_EXEC;
532 533
        break;
    case PAGE_EXECUTE_READ:
534
        *vprot = VPROT_EXEC | VPROT_READ;
535 536
        break;
    case PAGE_EXECUTE_READWRITE:
537
        *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
538 539
        break;
    case PAGE_EXECUTE_WRITECOPY:
540
        *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
541 542
        break;
    case PAGE_NOACCESS:
543
        *vprot = 0;
544
        break;
545 546
    default:
        return STATUS_INVALID_PARAMETER;
547
    }
548 549 550
    if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
    if (protect & PAGE_NOCACHE) *vprot |= VPROT_NOCACHE;
    return STATUS_SUCCESS;
551 552 553 554 555 556 557 558 559 560 561 562 563 564
}


/***********************************************************************
 *           VIRTUAL_SetProt
 *
 * Change the protection of a range of pages.
 *
 * RETURNS
 *	TRUE: Success
 *	FALSE: Failure
 */
static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
                             void *base,      /* [in] Starting address */
565
                             size_t size,     /* [in] Size in bytes */
566 567
                             BYTE vprot )     /* [in] Protections to use */
{
568
    int unix_prot = VIRTUAL_GetUnixProt(vprot);
569
    BYTE *p = view->prot + (((char *)base - (char *)view->base) >> page_shift);
570

571 572 573
    TRACE("%p-%p %s\n",
          base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );

574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
    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;
            mprotect( addr, count << page_shift, unix_prot );
            addr += count << page_shift;
            unix_prot = prot;
            count = 0;
        }
        if (count) mprotect( addr, count << page_shift, unix_prot );
        VIRTUAL_DEBUG_DUMP_VIEW( view );
        return TRUE;
    }

598 599 600
    /* 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) &&
601 602
        (base >= NtCurrentTeb()->DeallocationStack) &&
        (base < NtCurrentTeb()->Tib.StackBase))
603
    {
604
        memset( p, vprot, size >> page_shift );
605 606 607 608 609
        mprotect( base, size, unix_prot );
        VIRTUAL_DEBUG_DUMP_VIEW( view );
        return TRUE;
    }

610 611
    if (force_exec_prot && !(view->protect & VPROT_NOEXEC) &&
        (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
612 613 614 615 616 617 618 619
    {
        TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
        if (!mprotect( base, size, unix_prot | PROT_EXEC )) goto done;
        /* exec + write may legitimately fail, in that case fall back to write only */
        if (!(unix_prot & PROT_WRITE)) return FALSE;
    }

    if (mprotect( base, size, unix_prot )) return FALSE;  /* FIXME: last error */
620

621
done:
622
    memset( p, vprot, size >> page_shift );
623 624 625 626 627
    VIRTUAL_DEBUG_DUMP_VIEW( view );
    return TRUE;
}


628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
/***********************************************************************
 *           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;
        mprotect( addr, count << page_shift, unix_prot );
        addr += count << page_shift;
        unix_prot = prot;
        count = 0;
    }
    if (count) mprotect( addr, count << page_shift, unix_prot );
}


656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
/***********************************************************************
 *           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;
}


676 677 678 679 680
struct alloc_area
{
    size_t size;
    size_t mask;
    int    top_down;
681
    void  *limit;
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
    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 )
{
    static void * const address_space_start = (void *)0x110000;
    struct alloc_area *alloc = arg;
    void *end = (char *)start + size;

    if (start < address_space_start) start = address_space_start;
697
    if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
    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;
}


726
/***********************************************************************
727
 *           map_view
728
 *
729 730
 * Create a view and mmap the corresponding memory area.
 * The csVirtual section must be held by caller.
731
 */
732
static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
733
                          int top_down, unsigned int vprot )
734
{
735 736
    void *ptr;
    NTSTATUS status;
737

738
    if (base)
739
    {
740
        if (is_beyond_limit( base, size, address_space_limit ))
741 742 743
            return STATUS_WORKING_SET_LIMIT_RANGE;

        switch (wine_mmap_is_in_reserved_area( base, size ))
744
        {
745
        case -1: /* partially in a reserved area */
746
            return STATUS_CONFLICTING_ADDRESSES;
747 748 749 750 751 752 753 754 755 756

        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 */
757
                if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
758 759 760 761 762 763 764 765 766 767 768 769
                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;
770
        }
771
        if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
772
    }
773
    else
774
    {
775
        size_t view_size = size + mask + 1;
776 777 778 779 780
        struct alloc_area alloc;

        alloc.size = size;
        alloc.mask = mask;
        alloc.top_down = top_down;
781
        alloc.limit = user_space_limit;
782 783 784 785 786 787 788 789
        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;
        }
790

791
        for (;;)
792
        {
793 794 795 796 797
            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;
            }
798
            TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
799
            /* if we got something beyond the user limit, unmap it and retry */
800
            if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
801
            else break;
802
        }
803
        ptr = unmap_extra_space( ptr, view_size, size, mask );
804
    }
805
done:
806
    status = create_view( view_ret, ptr, size, vprot );
807
    if (status != STATUS_SUCCESS) unmap_area( ptr, size );
808 809 810 811 812 813 814 815 816 817 818
    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,
819
                                    off_t offset, unsigned int vprot, BOOL removable )
820 821
{
    void *ptr;
822
    int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
823 824 825 826 827 828 829
    BOOL shared_write = (vprot & VPROT_WRITE) != 0;

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

    /* only try mmap if media is not removable (or if we require write access) */
    if (!removable || shared_write)
830
    {
831 832
        int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);

833
        if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
834 835 836 837 838 839
            goto done;

        /* 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();
840 841 842 843 844 845
        if (shared_write)  /* we cannot fake shared write mappings */
        {
            if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
            ERR( "shared writable mmap not supported, broken filesystem?\n" );
            return STATUS_NOT_SUPPORTED;
        }
846
    }
847 848 849 850 851 852 853 854

    /* 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:
855
    memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
856 857 858 859
    return STATUS_SUCCESS;
}


860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
/***********************************************************************
 *           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 )
        {
878
            req->handle = wine_server_obj_handle( view->mapping );
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
            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;
}


899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
/***********************************************************************
 *           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();
}


918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
/***********************************************************************
 *           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)
        {
            addr = NULL;
            TRACE( "successfully mapped low 64K range\n" );
        }
        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 );
}


978 979 980 981 982
/***********************************************************************
 *           map_image
 *
 * Map an executable (PE format) image into memory.
 */
983
static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
984
                           SIZE_T header_size, int shared_fd, HANDLE dup_mapping, PVOID *addr_ptr )
985 986 987 988 989
{
    IMAGE_DOS_HEADER *dos;
    IMAGE_NT_HEADERS *nt;
    IMAGE_SECTION_HEADER *sec;
    IMAGE_DATA_DIRECTORY *imports;
990 991 992
    NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
    int i;
    off_t pos;
993
    sigset_t sigset;
994
    struct stat st;
995
    struct file_view *view = NULL;
996
    char *ptr, *header_end;
997
    INT_PTR delta = 0;
998 999 1000

    /* zero-map the whole range */

1001
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1002 1003

    if (base >= (char *)0x110000)  /* make sure the DOS area remains free */
1004
        status = map_view( &view, base, total_size, mask, FALSE,
1005 1006
                           VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );

1007
    if (status != STATUS_SUCCESS)
1008
        status = map_view( &view, NULL, total_size, mask, FALSE,
1009 1010 1011 1012 1013
                           VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );

    if (status != STATUS_SUCCESS) goto error;

    ptr = view->base;
1014 1015 1016 1017
    TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );

    /* map the header */

1018 1019 1020 1021 1022
    if (fstat( fd, &st ) == -1)
    {
        status = FILE_GetNtStatus();
        goto error;
    }
1023
    status = STATUS_INVALID_IMAGE_FORMAT;  /* generic error */
1024 1025
    if (!st.st_size) goto error;
    header_size = min( header_size, st.st_size );
1026
    if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1027
                            !dup_mapping ) != STATUS_SUCCESS) goto error;
1028 1029
    dos = (IMAGE_DOS_HEADER *)ptr;
    nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1030
    header_end = ptr + ROUND_SIZE( 0, header_size );
1031
    memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1032
    if ((char *)(nt + 1) > header_end) goto error;
1033
    sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1034
    if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
1035 1036 1037 1038 1039 1040

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

    /* check the architecture */

1041 1042 1043
#ifdef __x86_64__
    if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64)
#else
1044
    if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
1045
#endif
1046 1047 1048 1049 1050 1051
    {
        MESSAGE("Trying to load PE image for unsupported architecture (");
        switch (nt->FileHeader.Machine)
        {
        case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
        case IMAGE_FILE_MACHINE_I860:    MESSAGE("I860"); break;
1052
        case IMAGE_FILE_MACHINE_I386:    MESSAGE("I386"); break;
1053 1054 1055 1056 1057
        case IMAGE_FILE_MACHINE_R3000:   MESSAGE("R3000"); break;
        case IMAGE_FILE_MACHINE_R4000:   MESSAGE("R4000"); break;
        case IMAGE_FILE_MACHINE_R10000:  MESSAGE("R10000"); break;
        case IMAGE_FILE_MACHINE_ALPHA:   MESSAGE("Alpha"); break;
        case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
1058 1059 1060
        case IMAGE_FILE_MACHINE_IA64:    MESSAGE("IA-64"); break;
        case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
        case IMAGE_FILE_MACHINE_AMD64:   MESSAGE("AMD-64"); break;
1061
        case IMAGE_FILE_MACHINE_ARM:     MESSAGE("ARM"); break;
1062 1063 1064 1065 1066 1067
        default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
        }
        MESSAGE(")\n");
        goto error;
    }

1068 1069 1070 1071 1072 1073 1074 1075
    /* 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 */

        if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
1076
                                !dup_mapping ) != STATUS_SUCCESS) goto error;
1077 1078

        /* check that all sections are loaded at the right offset */
1079
        if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
        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 );

1090
        /* no relocations are performed on non page-aligned binaries */
1091 1092 1093 1094
        goto done;
    }


1095 1096 1097 1098
    /* map all the sections */

    for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
    {
1099 1100
        static const SIZE_T sector_align = 0x1ff;
        SIZE_T map_size, file_start, file_size, end;
1101 1102

        if (!sec->Misc.VirtualSize)
1103
            map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1104 1105
        else
            map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1106 1107 1108 1109 1110

        /* 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;
1111 1112

        /* a few sanity checks */
1113 1114
        end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
        if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1115
        {
1116 1117
            WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
                           sec->Name, sec->VirtualAddress, map_size, total_size );
1118 1119 1120 1121 1122 1123
            goto error;
        }

        if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
            (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
        {
1124
            TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1125 1126 1127 1128
                            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,
1129
                                    VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1130
                                    FALSE ) != STATUS_SUCCESS)
1131 1132 1133 1134 1135 1136 1137
            {
                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 &&
1138
                imports->VirtualAddress < sec->VirtualAddress + map_size)
1139 1140 1141
            {
                UINT_PTR base = imports->VirtualAddress & ~page_mask;
                UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1142
                if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1143 1144 1145 1146 1147
                if (end > base)
                    map_file_into_view( view, shared_fd, base, end - base,
                                        pos + (base - sec->VirtualAddress),
                                        VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
                                        FALSE );
1148
            }
1149
            pos += map_size;
1150 1151 1152
            continue;
        }

1153
        TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1154 1155
                        sec->Name, ptr + sec->VirtualAddress,
                        sec->PointerToRawData, sec->SizeOfRawData,
1156
                        sec->Misc.VirtualSize, sec->Characteristics );
1157

1158
        if (!sec->PointerToRawData || !file_size) continue;
1159

1160
        /* Note: if the section is not aligned properly map_file_into_view will magically
1161 1162
         *       fall back to read(), so we don't need to check anything here.
         */
1163 1164 1165 1166 1167
        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,
1168
                                VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1169
                                !dup_mapping ) != STATUS_SUCCESS)
1170 1171 1172 1173 1174
        {
            ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
            goto error;
        }

1175
        if (file_size & page_mask)
1176
        {
1177 1178
            end = ROUND_SIZE( 0, file_size );
            if (end > map_size) end = map_size;
1179
            TRACE_(module)("clearing %p - %p\n",
1180
                           ptr + sec->VirtualAddress + file_size,
1181
                           ptr + sec->VirtualAddress + end );
1182
            memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1183 1184 1185 1186 1187 1188
        }
    }


    /* perform base relocation, if necessary */

1189 1190 1191
    if (ptr != base &&
        ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
          !NtCurrentTeb()->Peb->ImageBaseAddress) )
1192
    {
1193
        IMAGE_BASE_RELOCATION *rel, *end;
1194 1195
        const IMAGE_DATA_DIRECTORY *relocs;

1196
        if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1197
        {
1198 1199
            WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
                           base, ptr );
1200
            status = STATUS_CONFLICTING_ADDRESSES;
1201 1202 1203
            goto error;
        }

1204 1205 1206 1207 1208 1209
        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);
1210
        delta = ptr - base;
1211

1212
        while (rel < end - 1 && rel->SizeOfBlock)
1213
        {
1214 1215 1216 1217 1218 1219
            if (rel->VirtualAddress >= total_size)
            {
                WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
                status = STATUS_ACCESS_VIOLATION;
                goto error;
            }
1220 1221 1222 1223
            rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
                                             (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
                                             (USHORT *)(rel + 1), delta );
            if (!rel) goto error;
1224 1225 1226 1227 1228
        }
    }

    /* set the image protections */

1229 1230
    VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );

1231 1232 1233
    sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
    for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
    {
1234
        SIZE_T size;
1235
        BYTE vprot = VPROT_COMMITTED;
1236 1237 1238 1239 1240 1241

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

1242
        if (sec->Characteristics & IMAGE_SCN_MEM_READ)    vprot |= VPROT_READ;
1243
        if (sec->Characteristics & IMAGE_SCN_MEM_WRITE)   vprot |= VPROT_READ|VPROT_WRITECOPY;
1244
        if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1245 1246 1247 1248 1249 1250

        /* 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;

1251 1252
        VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
    }
1253 1254

 done:
1255
    view->mapping = dup_mapping;
1256
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1257 1258

    *addr_ptr = ptr;
1259 1260 1261
#ifdef VALGRIND_LOAD_PDB_DEBUGINFO
    VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
#endif
1262 1263 1264
    return STATUS_SUCCESS;

 error:
1265
    if (view) delete_view( view );
1266
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1267
    if (dup_mapping) NtClose( dup_mapping );
1268 1269 1270 1271
    return status;
}


1272 1273
/* 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 )
1274
{
1275 1276
    void **heap_base = arg;

1277
    if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1278 1279 1280 1281
    if (size < VIRTUAL_HEAP_SIZE) return 0;
    *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);
1282 1283
}

1284
/***********************************************************************
1285
 *           virtual_init
1286
 */
1287
void virtual_init(void)
1288
{
1289
    const char *preload;
1290 1291 1292
    void *heap_base;
    struct file_view *heap_view;

1293
#ifndef page_mask
1294 1295 1296 1297 1298 1299
    page_size = getpagesize();
    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++;
1300
    user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1301
#endif  /* page_mask */
1302 1303 1304 1305 1306 1307 1308 1309 1310
    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;
        }
    }
1311 1312 1313 1314 1315 1316 1317 1318 1319

    /* 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 );
1320
}
1321 1322


1323
/***********************************************************************
1324
 *           virtual_init_threading
1325
 */
1326
void virtual_init_threading(void)
1327
{
1328
    use_locks = 1;
1329 1330 1331
}


1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
/***********************************************************************
 *           virtual_get_system_info
 */
void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
{
    info->dwUnknown1 = 0;
    info->uKeMaximumIncrement = 0;  /* FIXME */
    info->uPageSize = page_size;
    info->uMmLowestPhysicalPage = 1;
    info->uMmHighestPhysicalPage = 0x7fffffff / page_size;
    info->uMmNumberOfPhysicalPages = info->uMmHighestPhysicalPage - info->uMmLowestPhysicalPage;
    info->uAllocationGranularity = get_mask(0) + 1;
    info->pLowestUserAddress = (void *)0x10000;
    info->pMmHighestUserAddress = (char *)user_space_limit - 1;
    info->uKeActiveProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
    info->bKeNumberProcessors = info->uKeActiveProcessors;
}


1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
/***********************************************************************
 *           virtual_create_system_view
 */
NTSTATUS virtual_create_system_view( void *base, SIZE_T size, DWORD vprot )
{
    FILE_VIEW *view;
    NTSTATUS status;
    sigset_t sigset;

    size = ROUND_SIZE( base, size );
    base = ROUND_ADDR( base, page_mask );
    server_enter_uninterrupted_section( &csVirtual, &sigset );
    status = create_view( &view, base, size, vprot );
    if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
    server_leave_uninterrupted_section( &csVirtual, &sigset );
    return status;
}


1370 1371 1372
/***********************************************************************
 *           virtual_alloc_thread_stack
 */
1373
NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1374 1375 1376 1377
{
    FILE_VIEW *view;
    NTSTATUS status;
    sigset_t sigset;
1378
    SIZE_T size;
1379

1380
    if (!reserve_size || !commit_size)
1381
    {
1382 1383 1384
        IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
        if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
        if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1385
    }
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396

    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;

1397
#ifdef VALGRIND_STACK_REGISTER
1398
    VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1399 1400 1401 1402
#endif

    /* setup no access guard page */
    VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1403 1404
    VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
                     VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1405 1406

    /* note: limit is lower than base since the stack grows down */
1407 1408 1409
    teb->DeallocationStack = view->base;
    teb->Tib.StackBase     = (char *)view->base + view->size;
    teb->Tib.StackLimit    = (char *)view->base + 2 * page_size;
1410 1411 1412 1413 1414 1415
done:
    server_leave_uninterrupted_section( &csVirtual, &sigset );
    return status;
}


1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
/***********************************************************************
 *           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 );
}


1431
/***********************************************************************
1432
 *           virtual_handle_fault
1433
 */
1434
NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err )
1435
{
1436
    FILE_VIEW *view;
1437
    NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1438
    sigset_t sigset;
1439

1440
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1441
    if ((view = VIRTUAL_FindView( addr, 0 )))
1442
    {
1443
        void *page = ROUND_ADDR( addr, page_mask );
1444 1445
        BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
        if (*vprot & VPROT_GUARD)
1446
        {
1447
            VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1448
            ret = STATUS_GUARD_PAGE_VIOLATION;
1449
        }
1450
        if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1451
        {
1452 1453 1454 1455 1456 1457 1458
            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;
1459
        }
1460
    }
1461
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1462 1463 1464 1465
    return ret;
}


1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478

/***********************************************************************
 *           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 )
{
    FILE_VIEW *view;
    BOOL ret = FALSE;

    RtlEnterCriticalSection( &csVirtual );  /* no need for signal masking inside signal handler */
1479
    if ((view = VIRTUAL_FindView( addr, 0 )))
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
    {
        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 );
            if ((char *)page + page_size == NtCurrentTeb()->Tib.StackLimit)
                NtCurrentTeb()->Tib.StackLimit = page;
            ret = TRUE;
        }
    }
    RtlLeaveCriticalSection( &csVirtual );
    return ret;
}


1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
/***********************************************************************
 *           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;
        char dummy;
        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;
}


1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
/***********************************************************************
 *           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;
}


1563 1564 1565 1566 1567 1568 1569 1570
/***********************************************************************
 *           VIRTUAL_SetForceExec
 *
 * Whether to force exec prot on all views.
 */
void VIRTUAL_SetForceExec( BOOL enable )
{
    struct file_view *view;
1571
    sigset_t sigset;
1572

1573
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1574 1575 1576 1577 1578 1579 1580 1581
    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;
1582 1583
            BYTE commit = view->mapping ? VPROT_COMMITTED : 0;  /* file mappings are always accessible */
            int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1584

1585
            if (view->protect & VPROT_NOEXEC) continue;
1586 1587
            for (count = i = 1; i < view->size >> page_shift; i++, count++)
            {
1588 1589
                int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
                if (prot == unix_prot) continue;
1590 1591 1592 1593 1594 1595 1596 1597 1598
                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);
1599
                unix_prot = prot;
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
                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) );
                }
            }
        }
    }
1615
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1616 1617 1618
}


1619 1620 1621 1622 1623 1624 1625
/***********************************************************************
 *           VIRTUAL_UseLargeAddressSpace
 *
 * Increase the address space size for apps that support it.
 */
void VIRTUAL_UseLargeAddressSpace(void)
{
1626 1627
    /* no large address space on win9x */
    if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1628
    user_space_limit = working_set_limit = address_space_limit;
1629 1630 1631
}


1632 1633 1634 1635
/***********************************************************************
 *             NtAllocateVirtualMemory   (NTDLL.@)
 *             ZwAllocateVirtualMemory   (NTDLL.@)
 */
1636
NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1637
                                         SIZE_T *size_ptr, ULONG type, ULONG protect )
1638 1639
{
    void *base;
1640
    unsigned int vprot;
1641
    SIZE_T size = *size_ptr;
1642
    SIZE_T mask = get_mask( zero_bits );
1643 1644
    NTSTATUS status = STATUS_SUCCESS;
    struct file_view *view;
1645
    sigset_t sigset;
1646

1647
    TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1648 1649 1650

    if (!size) return STATUS_INVALID_PARAMETER;

1651
    if (process != NtCurrentProcess())
1652
    {
1653 1654 1655
        apc_call_t call;
        apc_result_t result;

1656 1657
        memset( &call, 0, sizeof(call) );

1658
        call.virtual_alloc.type      = APC_VIRTUAL_ALLOC;
1659
        call.virtual_alloc.addr      = wine_server_client_ptr( *ret );
1660 1661 1662 1663 1664 1665 1666 1667 1668
        call.virtual_alloc.size      = *size_ptr;
        call.virtual_alloc.zero_bits = zero_bits;
        call.virtual_alloc.op_type   = type;
        call.virtual_alloc.prot      = protect;
        status = NTDLL_queue_process_apc( process, &call, &result );
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_alloc.status == STATUS_SUCCESS)
        {
1669
            *ret      = wine_server_get_ptr( result.virtual_alloc.addr );
1670 1671 1672
            *size_ptr = result.virtual_alloc.size;
        }
        return result.virtual_alloc.status;
1673 1674 1675 1676
    }

    /* Round parameters to a page boundary */

1677
    if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1678

1679 1680
    if ((status = get_vprot_flags( protect, &vprot ))) return status;
    vprot |= VPROT_VALLOC;
1681 1682
    if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;

1683
    if (*ret)
1684 1685
    {
        if (type & MEM_RESERVE) /* Round down to 64k boundary */
1686
            base = ROUND_ADDR( *ret, mask );
1687
        else
1688 1689
            base = ROUND_ADDR( *ret, page_mask );
        size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1690

1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
        /* 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;
        }

1705
        /* disallow low 64k, wrap-around and kernel space */
1706
        if (((char *)base < (char *)0x10000) ||
1707
            ((char *)base + size < (char *)base) ||
1708
            is_beyond_limit( base, size, address_space_limit ))
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
            return STATUS_INVALID_PARAMETER;
    }
    else
    {
        base = NULL;
        size = (size + page_mask) & ~page_mask;
    }

    /* Compute the alloc type flags */

1719 1720
    if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
        (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1721
    {
1722 1723 1724
        WARN("called with wrong alloc type flags (%08x) !\n", type);
        return STATUS_INVALID_PARAMETER;
    }
1725

1726 1727
    /* Reserve the memory */

1728
    if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1729

1730
    if ((type & MEM_RESERVE) || !base)
1731
    {
1732
        if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
1733
        status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1734
        if (status == STATUS_SUCCESS) base = view->base;
1735
    }
1736
    else  /* commit the pages */
1737
    {
1738
        if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1739
        else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1740 1741 1742 1743
        else if (view->mapping && !(view->protect & VPROT_COMMITTED))
        {
            SERVER_START_REQ( add_mapping_committed_range )
            {
1744
                req->handle = wine_server_obj_handle( view->mapping );
1745 1746 1747 1748 1749 1750
                req->offset = (char *)base - (char *)view->base;
                req->size   = size;
                wine_server_call( req );
            }
            SERVER_END_REQ;
        }
1751 1752
    }

1753
    if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1754 1755 1756 1757 1758 1759 1760

    if (status == STATUS_SUCCESS)
    {
        *ret = base;
        *size_ptr = size;
    }
    return status;
1761 1762 1763 1764 1765 1766 1767
}


/***********************************************************************
 *             NtFreeVirtualMemory   (NTDLL.@)
 *             ZwFreeVirtualMemory   (NTDLL.@)
 */
1768
NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1769 1770 1771
{
    FILE_VIEW *view;
    char *base;
1772
    sigset_t sigset;
1773
    NTSTATUS status = STATUS_SUCCESS;
1774
    LPVOID addr = *addr_ptr;
1775
    SIZE_T size = *size_ptr;
1776

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

1779
    if (process != NtCurrentProcess())
1780
    {
1781 1782 1783
        apc_call_t call;
        apc_result_t result;

1784 1785
        memset( &call, 0, sizeof(call) );

1786
        call.virtual_free.type      = APC_VIRTUAL_FREE;
1787
        call.virtual_free.addr      = wine_server_client_ptr( addr );
1788 1789 1790 1791 1792 1793 1794
        call.virtual_free.size      = size;
        call.virtual_free.op_type   = type;
        status = NTDLL_queue_process_apc( process, &call, &result );
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_free.status == STATUS_SUCCESS)
        {
1795
            *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
1796 1797 1798
            *size_ptr = result.virtual_free.size;
        }
        return result.virtual_free.status;
1799 1800 1801 1802 1803 1804 1805
    }

    /* Fix the parameters */

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

1806
    /* avoid freeing the DOS area when a broken app passes a NULL pointer */
1807
    if (!base) return STATUS_INVALID_PARAMETER;
1808

1809
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1810

1811
    if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
1812 1813 1814 1815
    {
        status = STATUS_INVALID_PARAMETER;
    }
    else if (type == MEM_RELEASE)
1816
    {
1817 1818
        /* Free the pages */

1819 1820 1821
        if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
        else
        {
1822
            delete_view( view );
1823 1824 1825
            *addr_ptr = base;
            *size_ptr = size;
        }
1826
    }
1827
    else if (type == MEM_DECOMMIT)
1828
    {
1829 1830
        status = decommit_pages( view, base - (char *)view->base, size );
        if (status == STATUS_SUCCESS)
1831 1832 1833 1834
        {
            *addr_ptr = base;
            *size_ptr = size;
        }
1835
    }
1836 1837
    else
    {
1838
        WARN("called with wrong free type flags (%08x) !\n", type);
1839
        status = STATUS_INVALID_PARAMETER;
1840
    }
1841

1842
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1843
    return status;
1844 1845 1846 1847 1848 1849 1850
}


/***********************************************************************
 *             NtProtectVirtualMemory   (NTDLL.@)
 *             ZwProtectVirtualMemory   (NTDLL.@)
 */
1851
NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1852 1853 1854
                                        ULONG new_prot, ULONG *old_prot )
{
    FILE_VIEW *view;
1855
    sigset_t sigset;
1856
    NTSTATUS status = STATUS_SUCCESS;
1857
    char *base;
1858
    BYTE vprot;
1859
    unsigned int new_vprot;
1860
    SIZE_T size = *size_ptr;
1861 1862
    LPVOID addr = *addr_ptr;

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

1865
    if (process != NtCurrentProcess())
1866
    {
1867 1868 1869
        apc_call_t call;
        apc_result_t result;

1870 1871
        memset( &call, 0, sizeof(call) );

1872
        call.virtual_protect.type = APC_VIRTUAL_PROTECT;
1873
        call.virtual_protect.addr = wine_server_client_ptr( addr );
1874 1875 1876 1877 1878 1879 1880
        call.virtual_protect.size = size;
        call.virtual_protect.prot = new_prot;
        status = NTDLL_queue_process_apc( process, &call, &result );
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_protect.status == STATUS_SUCCESS)
        {
1881
            *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
1882 1883 1884 1885
            *size_ptr = result.virtual_protect.size;
            if (old_prot) *old_prot = result.virtual_protect.prot;
        }
        return result.virtual_protect.status;
1886 1887 1888 1889 1890 1891
    }

    /* Fix the parameters */

    size = ROUND_SIZE( addr, size );
    base = ROUND_ADDR( addr, page_mask );
1892 1893
    if ((status = get_vprot_flags( new_prot, &new_vprot ))) return status;
    new_vprot |= VPROT_COMMITTED;
1894

1895
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1896

1897
    if (!(view = VIRTUAL_FindView( base, size )))
1898
    {
1899
        status = STATUS_INVALID_PARAMETER;
1900
    }
1901 1902 1903
    else
    {
        /* Make sure all the pages are committed */
1904
        if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
1905
        {
1906
            if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
1907
            if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
1908
        }
1909
        else status = STATUS_NOT_COMMITTED;
1910
    }
1911
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1912

1913 1914 1915 1916 1917 1918
    if (status == STATUS_SUCCESS)
    {
        *addr_ptr = base;
        *size_ptr = size;
    }
    return status;
1919 1920
}

1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957

/* 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;
    }

    if (info->BaseAddress >= start)
    {
        /* 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;
}

1958 1959 1960 1961
#define UNIMPLEMENTED_INFO_CLASS(c) \
    case c: \
        FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
        return STATUS_INVALID_INFO_CLASS
1962 1963 1964 1965 1966 1967 1968

/***********************************************************************
 *             NtQueryVirtualMemory   (NTDLL.@)
 *             ZwQueryVirtualMemory   (NTDLL.@)
 */
NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
                                      MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1969
                                      SIZE_T len, SIZE_T *res_len )
1970 1971 1972
{
    FILE_VIEW *view;
    char *base, *alloc_base = 0;
1973
    struct list *ptr;
1974
    SIZE_T size = 0;
1975
    MEMORY_BASIC_INFORMATION *info = buffer;
1976
    sigset_t sigset;
1977

1978 1979
    if (info_class != MemoryBasicInformation)
    {
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
        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;
        }
1991
    }
1992

1993
    if (process != NtCurrentProcess())
1994
    {
1995 1996 1997 1998
        NTSTATUS status;
        apc_call_t call;
        apc_result_t result;

1999 2000
        memset( &call, 0, sizeof(call) );

2001
        call.virtual_query.type = APC_VIRTUAL_QUERY;
2002
        call.virtual_query.addr = wine_server_client_ptr( addr );
2003 2004 2005 2006 2007
        status = NTDLL_queue_process_apc( process, &call, &result );
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_query.status == STATUS_SUCCESS)
        {
2008 2009
            info->BaseAddress       = wine_server_get_ptr( result.virtual_query.base );
            info->AllocationBase    = wine_server_get_ptr( result.virtual_query.alloc_base );
2010 2011 2012
            info->RegionSize        = result.virtual_query.size;
            info->Protect           = result.virtual_query.prot;
            info->AllocationProtect = result.virtual_query.alloc_prot;
2013 2014
            info->State             = (DWORD)result.virtual_query.state << 12;
            info->Type              = (DWORD)result.virtual_query.alloc_type << 16;
2015 2016
            if (info->RegionSize != result.virtual_query.size)  /* truncated */
                return STATUS_INVALID_PARAMETER;  /* FIXME */
2017 2018 2019
            if (res_len) *res_len = sizeof(*info);
        }
        return result.virtual_query.status;
2020 2021 2022 2023
    }

    base = ROUND_ADDR( addr, page_mask );

2024 2025
    if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;

2026 2027
    /* Find the view containing the address */

2028
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2029
    ptr = list_head( &views_list );
2030 2031
    for (;;)
    {
2032
        if (!ptr)
2033
        {
2034
            size = (char *)working_set_limit - alloc_base;
2035
            view = NULL;
2036 2037
            break;
        }
2038
        view = LIST_ENTRY( ptr, struct file_view, entry );
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
        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;
2052
        ptr = list_next( &views_list, ptr );
2053 2054 2055 2056
    }

    /* Fill the info structure */

2057 2058 2059 2060
    info->AllocationBase = alloc_base;
    info->BaseAddress    = base;
    info->RegionSize     = size - (base - alloc_base);

2061 2062
    if (!view)
    {
2063 2064 2065
        if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
        {
            /* not in a reserved area at all, pretend it's allocated */
2066
#ifdef __i386__
2067 2068 2069 2070
            info->State             = MEM_RESERVE;
            info->Protect           = PAGE_NOACCESS;
            info->AllocationProtect = PAGE_NOACCESS;
            info->Type              = MEM_PRIVATE;
2071 2072 2073 2074 2075 2076 2077
#else
            info->State             = MEM_FREE;
            info->Protect           = PAGE_NOACCESS;
            info->AllocationBase    = 0;
            info->AllocationProtect = 0;
            info->Type              = 0;
#endif
2078
        }
2079 2080 2081
    }
    else
    {
2082 2083 2084
        BYTE vprot;
        SIZE_T range_size = get_committed_size( view, base, &vprot );

2085
        info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2086
        info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2087
        info->AllocationBase = alloc_base;
2088
        info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2089
        if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2090
        else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2091
        else info->Type = MEM_MAPPED;
2092
        for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2093
            if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2094
        info->RegionSize = size - (base - alloc_base);
2095
    }
2096
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2097

2098
    if (res_len) *res_len = sizeof(*info);
2099 2100 2101 2102 2103 2104 2105 2106
    return STATUS_SUCCESS;
}


/***********************************************************************
 *             NtLockVirtualMemory   (NTDLL.@)
 *             ZwLockVirtualMemory   (NTDLL.@)
 */
2107
NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2108
{
2109 2110 2111
    NTSTATUS status = STATUS_SUCCESS;

    if (process != NtCurrentProcess())
2112
    {
2113 2114 2115
        apc_call_t call;
        apc_result_t result;

2116 2117
        memset( &call, 0, sizeof(call) );

2118
        call.virtual_lock.type = APC_VIRTUAL_LOCK;
2119
        call.virtual_lock.addr = wine_server_client_ptr( *addr );
2120 2121 2122 2123 2124 2125
        call.virtual_lock.size = *size;
        status = NTDLL_queue_process_apc( process, &call, &result );
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_lock.status == STATUS_SUCCESS)
        {
2126
            *addr = wine_server_get_ptr( result.virtual_lock.addr );
2127 2128 2129
            *size = result.virtual_lock.size;
        }
        return result.virtual_lock.status;
2130
    }
2131 2132 2133 2134 2135 2136

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

    if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
    return status;
2137 2138 2139 2140 2141 2142 2143
}


/***********************************************************************
 *             NtUnlockVirtualMemory   (NTDLL.@)
 *             ZwUnlockVirtualMemory   (NTDLL.@)
 */
2144
NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2145
{
2146 2147 2148
    NTSTATUS status = STATUS_SUCCESS;

    if (process != NtCurrentProcess())
2149
    {
2150 2151 2152
        apc_call_t call;
        apc_result_t result;

2153 2154
        memset( &call, 0, sizeof(call) );

2155
        call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2156
        call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2157 2158 2159 2160 2161 2162
        call.virtual_unlock.size = *size;
        status = NTDLL_queue_process_apc( process, &call, &result );
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_unlock.status == STATUS_SUCCESS)
        {
2163
            *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2164 2165 2166
            *size = result.virtual_unlock.size;
        }
        return result.virtual_unlock.status;
2167
    }
2168 2169 2170 2171 2172 2173

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

    if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
    return status;
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
}


/***********************************************************************
 *             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;
2186
    unsigned int vprot;
2187
    DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2188 2189
    struct security_descriptor *sd = NULL;
    struct object_attributes objattr;
2190 2191 2192 2193 2194

    /* Check parameters */

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

2195 2196
    if ((ret = get_vprot_flags( protect, &vprot ))) return ret;

2197
    objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
2198
    objattr.sd_len = 0;
2199
    objattr.name_len = len;
2200 2201 2202 2203 2204 2205
    if (attr)
    {
        ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
        if (ret != STATUS_SUCCESS) return ret;
    }

2206
    if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2207 2208 2209 2210 2211 2212 2213
    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 )
    {
2214 2215
        req->access      = access;
        req->attributes  = (attr) ? attr->Attributes : 0;
2216
        req->file_handle = wine_server_obj_handle( file );
2217
        req->size        = size ? size->QuadPart : 0;
2218
        req->protect     = vprot;
2219 2220
        wine_server_add_data( req, &objattr, sizeof(objattr) );
        if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2221 2222
        if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
        ret = wine_server_call( req );
2223
        *handle = wine_server_ptr_handle( reply->handle );
2224 2225
    }
    SERVER_END_REQ;
2226 2227 2228

    NTDLL_free_struct_sd( sd );

2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
    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;
2247
        req->attributes = attr->Attributes;
2248
        req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2249
        wine_server_add_data( req, attr->ObjectName->Buffer, len );
2250
        if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
    }
    SERVER_END_REQ;
    return ret;
}


/***********************************************************************
 *             NtMapViewOfSection   (NTDLL.@)
 *             ZwMapViewOfSection   (NTDLL.@)
 */
NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2262
                                    SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2263 2264 2265
                                    SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
{
    NTSTATUS res;
2266
    mem_size_t full_size;
2267
    ACCESS_MASK access;
2268
    SIZE_T size, mask = get_mask( zero_bits );
2269
    int unix_handle = -1, needs_close;
2270
    unsigned int map_vprot, vprot;
2271 2272
    void *base;
    struct file_view *view;
2273
    DWORD header_size;
2274
    HANDLE dup_mapping, shared_file;
2275
    LARGE_INTEGER offset;
2276
    sigset_t sigset;
2277 2278

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

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

2283 2284
    /* Check parameters */

2285
    if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2286 2287
        return STATUS_INVALID_PARAMETER;

2288 2289 2290
    switch(protect)
    {
    case PAGE_NOACCESS:
2291
        access = 0;
2292 2293 2294
        break;
    case PAGE_READWRITE:
    case PAGE_EXECUTE_READWRITE:
2295
        access = SECTION_MAP_WRITE;
2296 2297 2298 2299 2300 2301
        break;
    case PAGE_READONLY:
    case PAGE_WRITECOPY:
    case PAGE_EXECUTE:
    case PAGE_EXECUTE_READ:
    case PAGE_EXECUTE_WRITECOPY:
2302
        access = SECTION_MAP_READ;
2303 2304 2305 2306 2307
        break;
    default:
        return STATUS_INVALID_PARAMETER;
    }

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

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

2315
        call.map_view.type        = APC_MAP_VIEW;
2316
        call.map_view.handle      = wine_server_obj_handle( handle );
2317
        call.map_view.addr        = wine_server_client_ptr( *addr_ptr );
2318
        call.map_view.size        = *size_ptr;
2319
        call.map_view.offset      = offset.QuadPart;
2320 2321 2322 2323 2324 2325 2326 2327
        call.map_view.zero_bits   = zero_bits;
        call.map_view.alloc_type  = alloc_type;
        call.map_view.prot        = protect;
        res = NTDLL_queue_process_apc( process, &call, &result );
        if (res != STATUS_SUCCESS) return res;

        if (result.map_view.status == STATUS_SUCCESS)
        {
2328
            *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2329 2330 2331 2332 2333
            *size_ptr = result.map_view.size;
        }
        return result.map_view.status;
    }

2334 2335
    SERVER_START_REQ( get_mapping_info )
    {
2336
        req->handle = wine_server_obj_handle( handle );
2337
        req->access = access;
2338
        res = wine_server_call( req );
2339
        map_vprot   = reply->protect;
2340
        base        = wine_server_get_ptr( reply->base );
2341
        full_size   = reply->size;
2342
        header_size = reply->header_size;
2343 2344
        dup_mapping = wine_server_ptr_handle( reply->mapping );
        shared_file = wine_server_ptr_handle( reply->shared_file );
2345
        if ((ULONG_PTR)base != reply->base) base = NULL;
2346 2347
    }
    SERVER_END_REQ;
2348
    if (res) return res;
2349

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

2352
    if (map_vprot & VPROT_IMAGE)
2353
    {
2354 2355 2356 2357 2358 2359 2360
        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;
        }
2361 2362
        if (shared_file)
        {
2363
            int shared_fd, shared_needs_close;
2364

2365
            if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2366
                                           &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2367
            res = map_image( handle, unix_handle, base, size, mask, header_size,
2368
                             shared_fd, dup_mapping, addr_ptr );
2369
            if (shared_needs_close) close( shared_fd );
2370 2371 2372 2373
            NtClose( shared_file );
        }
        else
        {
2374
            res = map_image( handle, unix_handle, base, size, mask, header_size,
2375
                             -1, dup_mapping, addr_ptr );
2376
        }
2377
        if (needs_close) close( unix_handle );
2378
        if (!res) *size_ptr = size;
2379 2380 2381
        return res;
    }

2382 2383 2384
    res = STATUS_INVALID_PARAMETER;
    if (offset.QuadPart >= full_size) goto done;
    if (*size_ptr)
2385
    {
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
        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;
        }
2399 2400 2401 2402
    }

    /* Reserve a properly aligned area */

2403
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2404

2405 2406
    get_vprot_flags( protect, &vprot );
    vprot |= (map_vprot & VPROT_COMMITTED);
2407
    res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2408 2409
    if (res)
    {
2410
        server_leave_uninterrupted_section( &csVirtual, &sigset );
2411 2412
        goto done;
    }
2413 2414 2415

    /* Map the file */

2416
    TRACE("handle=%p size=%lx offset=%x%08x\n",
2417
          handle, size, offset.u.HighPart, offset.u.LowPart );
2418

2419
    res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2420
    if (res == STATUS_SUCCESS)
2421
    {
2422 2423
        *addr_ptr = view->base;
        *size_ptr = size;
2424 2425
        view->mapping = dup_mapping;
        dup_mapping = 0;  /* don't close it */
2426 2427
    }
    else
2428
    {
2429
        ERR( "map_file_into_view %p %lx %x%08x failed\n",
2430
             view->base, size, offset.u.HighPart, offset.u.LowPart );
2431
        delete_view( view );
2432 2433
    }

2434
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2435 2436

done:
2437
    if (dup_mapping) NtClose( dup_mapping );
2438
    if (needs_close) close( unix_handle );
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
    return res;
}


/***********************************************************************
 *             NtUnmapViewOfSection   (NTDLL.@)
 *             ZwUnmapViewOfSection   (NTDLL.@)
 */
NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
{
    FILE_VIEW *view;
2450
    NTSTATUS status = STATUS_INVALID_PARAMETER;
2451
    sigset_t sigset;
2452 2453
    void *base = ROUND_ADDR( addr, page_mask );

2454
    if (process != NtCurrentProcess())
2455
    {
2456 2457 2458
        apc_call_t call;
        apc_result_t result;

2459 2460
        memset( &call, 0, sizeof(call) );

2461
        call.unmap_view.type = APC_UNMAP_VIEW;
2462
        call.unmap_view.addr = wine_server_client_ptr( addr );
2463 2464 2465
        status = NTDLL_queue_process_apc( process, &call, &result );
        if (status == STATUS_SUCCESS) status = result.unmap_view.status;
        return status;
2466
    }
2467

2468
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2469
    if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base))
2470
    {
2471
        delete_view( view );
2472 2473
        status = STATUS_SUCCESS;
    }
2474
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2475
    return status;
2476 2477 2478 2479 2480 2481 2482 2483
}


/***********************************************************************
 *             NtFlushVirtualMemory   (NTDLL.@)
 *             ZwFlushVirtualMemory   (NTDLL.@)
 */
NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2484
                                      SIZE_T *size_ptr, ULONG unknown )
2485 2486
{
    FILE_VIEW *view;
2487
    NTSTATUS status = STATUS_SUCCESS;
2488
    sigset_t sigset;
2489 2490
    void *addr = ROUND_ADDR( *addr_ptr, page_mask );

2491
    if (process != NtCurrentProcess())
2492
    {
2493 2494 2495
        apc_call_t call;
        apc_result_t result;

2496 2497
        memset( &call, 0, sizeof(call) );

2498
        call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2499
        call.virtual_flush.addr = wine_server_client_ptr( addr );
2500 2501 2502 2503 2504 2505
        call.virtual_flush.size = *size_ptr;
        status = NTDLL_queue_process_apc( process, &call, &result );
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_flush.status == STATUS_SUCCESS)
        {
2506
            *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2507 2508 2509
            *size_ptr = result.virtual_flush.size;
        }
        return result.virtual_flush.status;
2510
    }
2511

2512
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2513
    if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2514 2515 2516 2517 2518 2519
    else
    {
        if (!*size_ptr) *size_ptr = view->size;
        *addr_ptr = addr;
        if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
    }
2520
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2521
    return status;
2522
}
2523 2524


2525 2526 2527 2528 2529 2530 2531
/***********************************************************************
 *             NtGetWriteWatch   (NTDLL.@)
 *             ZwGetWriteWatch   (NTDLL.@)
 */
NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
                                 ULONG_PTR *count, ULONG *granularity )
{
2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569
    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,
           addresses, count ? *count : 0 );

    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;
2570 2571 2572 2573 2574 2575 2576 2577 2578
}


/***********************************************************************
 *             NtResetWriteWatch   (NTDLL.@)
 *             ZwResetWriteWatch   (NTDLL.@)
 */
NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
{
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598
    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;
2599 2600 2601
}


2602 2603 2604 2605 2606 2607 2608 2609 2610
/***********************************************************************
 *             NtReadVirtualMemory   (NTDLL.@)
 *             ZwReadVirtualMemory   (NTDLL.@)
 */
NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
                                     SIZE_T size, SIZE_T *bytes_read )
{
    NTSTATUS status;

2611
    if (virtual_check_buffer_for_write( buffer, size ))
2612
    {
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625
        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;
2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640
    }
    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;

2641
    if (virtual_check_buffer_for_read( buffer, size ))
2642
    {
2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
        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;
2656 2657 2658 2659
    }
    if (bytes_written) *bytes_written = size;
    return status;
}
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671


/***********************************************************************
 *             NtAreMappedFilesTheSame   (NTDLL.@)
 *             ZwAreMappedFilesTheSame   (NTDLL.@)
 */
NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
{
    TRACE("%p %p\n", addr1, addr2);

    return STATUS_NOT_SAME_DEVICE;
}