virtual.c 74.3 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 44
#endif

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

WINE_DEFAULT_DEBUG_CHANNEL(virtual);
WINE_DECLARE_DEBUG_CHANNEL(module);

#ifndef MS_SYNC
#define MS_SYNC 0
#endif

64 65 66 67
#ifndef MAP_NORESERVE
#define MAP_NORESERVE 0
#endif

68
/* File view */
69
typedef struct file_view
70
{
71
    struct list   entry;       /* Entry in global view list */
72
    void         *base;        /* Base address */
73
    size_t        size;        /* Size in bytes */
74
    HANDLE        mapping;     /* Handle to the file mapping */
75
    BYTE          flags;       /* Allocation flags (VFLAG_*) */
76 77 78 79 80
    BYTE          protect;     /* Protection for all pages at allocation time */
    BYTE          prot[1];     /* Protection byte for each page */
} FILE_VIEW;

/* Per-view flags */
81
#define VFLAG_SYSTEM     0x01  /* system view (underlying mmap not under our control) */
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
#define VFLAG_VALLOC     0x02  /* allocated by VirtualAlloc */

/* 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 122
/* Note: these are Windows limits, you cannot change them. */
# define ADDRESS_SPACE_LIMIT  ((void *)0xc0000000)  /* top of the total available address space */
123
# define USER_SPACE_LIMIT     ((void *)0x7fff0000)  /* top of the user address space */
124 125 126
#else
static UINT page_shift;
static UINT page_size;
127
static UINT_PTR page_mask;
128
# define ADDRESS_SPACE_LIMIT  0   /* no limit needed on other platforms */
129
# define USER_SPACE_LIMIT     0   /* no limit needed on other platforms */
130 131 132
#endif  /* __i386__ */

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

#define ROUND_SIZE(addr,size) \
   (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)

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

141
static void *user_space_limit = USER_SPACE_LIMIT;
142 143
static void *preload_reserve_start;
static void *preload_reserve_end;
144
static int use_locks;
145
static int force_exec_prot;  /* whether to force PROT_EXEC on all PROT_READ mmaps */
146

147 148 149 150 151 152 153 154 155 156

/***********************************************************************
 *           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' : '-';
157
    buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
158 159 160 161 162 163
    buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
    buffer[5] = 0;
    return buffer;
}


164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
/***********************************************************************
 *           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;
    }
    if (!prot) prot = PROT_NONE;
    return prot;
}


184 185 186 187 188 189 190 191 192
/***********************************************************************
 *           VIRTUAL_DumpView
 */
static void VIRTUAL_DumpView( FILE_VIEW *view )
{
    UINT i, count;
    char *addr = view->base;
    BYTE prot = view->prot[0];

193
    TRACE( "View: %p - %p", addr, addr + view->size - 1 );
194
    if (view->flags & VFLAG_SYSTEM)
195
        TRACE( " (system)\n" );
196
    else if (view->flags & VFLAG_VALLOC)
197
        TRACE( " (valloc)\n" );
198
    else if (view->mapping)
199
        TRACE( " %p\n", view->mapping );
200
    else
201
        TRACE( " (anonymous)\n");
202 203 204 205

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


/***********************************************************************
 *           VIRTUAL_Dump
 */
221 222
#if WINE_VM_DEBUG
static void VIRTUAL_Dump(void)
223
{
224
    sigset_t sigset;
225
    struct file_view *view;
226

227
    TRACE( "Dump of all virtual memory views:\n" );
228
    server_enter_uninterrupted_section( &csVirtual, &sigset );
229
    LIST_FOR_EACH_ENTRY( view, &views_list, FILE_VIEW, entry )
230
    {
231
        VIRTUAL_DumpView( view );
232
    }
233
    server_leave_uninterrupted_section( &csVirtual, &sigset );
234
}
235
#endif
236 237 238 239 240


/***********************************************************************
 *           VIRTUAL_FindView
 *
241
 * Find the view containing a given address. The csVirtual section must be held by caller.
242
 *
243 244 245
 * PARAMS
 *      addr  [I] Address
 *
246 247 248 249
 * RETURNS
 *	View: Success
 *	NULL: Failure
 */
250
static struct file_view *VIRTUAL_FindView( const void *addr )
251
{
252
    struct file_view *view;
253

254
    LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
255
    {
256
        if (view->base > addr) break;
Eric Pouech's avatar
Eric Pouech committed
257
        if ((const char*)view->base + view->size > (const char*)addr) return view;
258
    }
259
    return NULL;
260 261 262
}


263 264 265 266 267 268 269 270 271 272 273
/***********************************************************************
 *           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;
}


274
/***********************************************************************
275
 *           find_view_range
276
 *
277 278 279 280 281
 * 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 )
{
282
    struct file_view *view;
283

284
    LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
285
    {
Eric Pouech's avatar
Eric Pouech committed
286 287
        if ((const char *)view->base >= (const char *)addr + size) break;
        if ((const char *)view->base + view->size > (const char *)addr) return view;
288 289 290 291 292
    }
    return NULL;
}


293 294 295 296 297 298 299 300 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
/***********************************************************************
 *           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;
}


340 341
/***********************************************************************
 *           add_reserved_area
342
 *
343 344 345 346 347 348 349
 * 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 );

350
    if (addr < user_space_limit)
351 352
    {
        /* unmap the part of the area that is below the limit */
353 354 355 356
        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;
357
    }
358 359
    /* blow away existing mappings */
    wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
360 361 362 363 364 365 366 367 368
    wine_mmap_add_reserved_area( addr, size );
}


/***********************************************************************
 *           is_beyond_limit
 *
 * Check if an address range goes beyond a given limit.
 */
369
static inline int is_beyond_limit( const void *addr, size_t size, const void *limit )
370
{
371
    return (limit && (addr >= limit || (const char *)addr + size > (const char *)limit));
372 373 374 375 376 377 378 379 380 381 382 383 384
}


/***********************************************************************
 *           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 );
385 386
    else if (is_beyond_limit( addr, size, user_space_limit ))
        add_reserved_area( addr, size );
387 388 389 390 391 392 393 394 395
    else
        munmap( addr, size );
}


/***********************************************************************
 *           delete_view
 *
 * Deletes a view. The csVirtual section must be held by caller.
396
 */
397
static void delete_view( struct file_view *view ) /* [in] View */
398
{
399
    if (!(view->flags & VFLAG_SYSTEM)) unmap_area( view->base, view->size );
400
    list_remove( &view->entry );
401 402 403 404 405
    if (view->mapping) NtClose( view->mapping );
    free( view );
}


406
/***********************************************************************
407
 *           create_view
408
 *
409
 * Create a view. The csVirtual section must be held by caller.
410
 */
411
static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, BYTE vprot )
412
{
413 414
    struct file_view *view;
    struct list *ptr;
415
    int unix_prot = VIRTUAL_GetUnixProt( vprot );
416

417
    assert( !((UINT_PTR)base & page_mask) );
418
    assert( !(size & page_mask) );
419 420 421 422 423

    /* Create the view structure */

    if (!(view = malloc( sizeof(*view) + (size >> page_shift) - 1 ))) return STATUS_NO_MEMORY;

424
    view->base    = base;
425 426 427
    view->size    = size;
    view->flags   = 0;
    view->mapping = 0;
428
    view->protect = vprot;
429
    memset( view->prot, vprot & ~VPROT_IMAGE, size >> page_shift );
430

431
    /* Insert it in the linked list */
432

433
    LIST_FOR_EACH( ptr, &views_list )
434
    {
435 436
        struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
        if (next->base > base) break;
437
    }
438
    list_add_before( ptr, &view->entry );
439

440 441 442
    /* 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. */
443

444
    if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
445
    {
446
        struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
447 448 449 450 451
        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 );
452
            assert( prev->flags & VFLAG_SYSTEM );
453
            delete_view( prev );
454 455
        }
    }
456
    if ((ptr = list_next( &views_list, &view->entry )) != NULL)
457
    {
458 459 460 461 462 463 464
        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 );
            assert( next->flags & VFLAG_SYSTEM );
465
            delete_view( next );
466
        }
467
    }
468 469

    *view_ret = view;
470 471
    VIRTUAL_DEBUG_DUMP_VIEW( view );

472
    if (force_exec_prot && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
473
    {
474 475
        TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
        mprotect( base, size, unix_prot | PROT_EXEC );
476
    }
477
    return STATUS_SUCCESS;
478 479 480 481 482 483 484 485
}


/***********************************************************************
 *           VIRTUAL_GetWin32Prot
 *
 * Convert page protections to Win32 flags.
 */
486
static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
487
{
488 489 490 491
    DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
    if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
    if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
    return ret;
492 493 494 495 496 497 498 499
}


/***********************************************************************
 *           VIRTUAL_GetProt
 *
 * Build page protections from Win32 flags.
 *
500 501 502
 * PARAMS
 *      protect [I] Win32 protection flags
 *
503 504 505
 * RETURNS
 *	Value of page protection flags
 */
506
static BYTE VIRTUAL_GetProt( DWORD protect )
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
{
    BYTE vprot;

    switch(protect & 0xff)
    {
    case PAGE_READONLY:
        vprot = VPROT_READ;
        break;
    case PAGE_READWRITE:
        vprot = VPROT_READ | VPROT_WRITE;
        break;
    case PAGE_WRITECOPY:
        /* MSDN CreateFileMapping() states that if PAGE_WRITECOPY is given,
	 * that the hFile must have been opened with GENERIC_READ and
	 * GENERIC_WRITE access.  This is WRONG as tests show that you
	 * only need GENERIC_READ access (at least for Win9x,
	 * FIXME: what about NT?).  Thus, we don't put VPROT_WRITE in
	 * PAGE_WRITECOPY and PAGE_EXECUTE_WRITECOPY.
	 */
        vprot = VPROT_READ | VPROT_WRITECOPY;
        break;
    case PAGE_EXECUTE:
        vprot = VPROT_EXEC;
        break;
    case PAGE_EXECUTE_READ:
        vprot = VPROT_EXEC | VPROT_READ;
        break;
    case PAGE_EXECUTE_READWRITE:
        vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
        break;
    case PAGE_EXECUTE_WRITECOPY:
        /* See comment for PAGE_WRITECOPY above */
        vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
        break;
    case PAGE_NOACCESS:
    default:
        vprot = 0;
        break;
    }
    if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
    if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
    return vprot;
}


/***********************************************************************
 *           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 */
563
                             size_t size,     /* [in] Size in bytes */
564 565
                             BYTE vprot )     /* [in] Protections to use */
{
566 567
    int unix_prot = VIRTUAL_GetUnixProt(vprot);

568 569 570
    TRACE("%p-%p %s\n",
          base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );

571 572 573 574 575 576 577 578 579
    if (force_exec_prot && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
    {
        TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
        if (!mprotect( base, size, unix_prot | PROT_EXEC )) 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 */
580

581
done:
582 583 584 585 586 587 588
    memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
            vprot, size >> page_shift );
    VIRTUAL_DEBUG_DUMP_VIEW( view );
    return TRUE;
}


589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
/***********************************************************************
 *           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;
}


609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 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 656 657
struct alloc_area
{
    size_t size;
    size_t mask;
    int    top_down;
    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;
    if (user_space_limit && end > user_space_limit) end = user_space_limit;
    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;
}


658
/***********************************************************************
659
 *           map_view
660
 *
661 662
 * Create a view and mmap the corresponding memory area.
 * The csVirtual section must be held by caller.
663
 */
664
static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
665
                          int top_down, BYTE vprot )
666
{
667 668
    void *ptr;
    NTSTATUS status;
669

670
    if (base)
671
    {
672 673 674 675
        if (is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
            return STATUS_WORKING_SET_LIMIT_RANGE;

        switch (wine_mmap_is_in_reserved_area( base, size ))
676
        {
677
        case -1: /* partially in a reserved area */
678
            return STATUS_CONFLICTING_ADDRESSES;
679 680 681 682 683 684 685 686 687 688

        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 */
689
                if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
690 691 692 693 694 695 696 697 698 699 700 701
                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;
702
        }
703
    }
704
    else
705
    {
706
        size_t view_size = size + mask + 1;
707 708 709 710 711 712 713 714 715 716 717 718 719
        struct alloc_area alloc;

        alloc.size = size;
        alloc.mask = mask;
        alloc.top_down = top_down;
        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;
        }
720

721
        for (;;)
722
        {
723 724 725 726 727
            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;
            }
728
            TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
729
            /* if we got something beyond the user limit, unmap it and retry */
730
            if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
731
            else break;
732
        }
733
        ptr = unmap_extra_space( ptr, view_size, size, mask );
734
    }
735
done:
736
    status = create_view( view_ret, ptr, size, vprot );
737
    if (status != STATUS_SUCCESS) unmap_area( ptr, size );
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
    return status;
}


/***********************************************************************
 *           unaligned_mmap
 *
 * Linux kernels before 2.4.x can support non page-aligned offsets, as
 * long as the offset is aligned to the filesystem block size. This is
 * a big performance gain so we want to take advantage of it.
 *
 * However, when we use 64-bit file support this doesn't work because
 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
 * in that it rounds unaligned offsets down to a page boundary. For
 * these reasons we do a direct system call here.
 */
static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
                             unsigned int flags, int fd, off_t offset )
{
#if defined(linux) && defined(__i386__) && defined(__GNUC__)
    if (!(offset >> 32) && (offset & page_mask))
    {
        int ret;

        struct
        {
            void        *addr;
            unsigned int length;
            unsigned int prot;
            unsigned int flags;
            unsigned int fd;
            unsigned int offset;
        } args;

        args.addr   = addr;
        args.length = length;
        args.prot   = prot;
        args.flags  = flags;
        args.fd     = fd;
        args.offset = offset;

        __asm__ __volatile__("push %%ebx\n\t"
                             "movl %2,%%ebx\n\t"
                             "int $0x80\n\t"
                             "popl %%ebx"
                             : "=a" (ret)
                             : "0" (90), /* SYS_mmap */
785
                               "q" (&args)
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
                             : "memory" );
        if (ret < 0 && ret > -4096)
        {
            errno = -ret;
            ret = -1;
        }
        return (void *)ret;
    }
#endif
    return mmap( addr, length, prot, flags, fd, offset );
}


/***********************************************************************
 *           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,
                                    off_t offset, BYTE vprot, BOOL removable )
{
    void *ptr;
    int prot = VIRTUAL_GetUnixProt( vprot );
    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)
817
    {
818 819 820 821 822 823 824 825 826 827
        int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);

        if (unaligned_mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
            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();
        if (shared_write) return FILE_GetNtStatus();  /* we cannot fake shared write mappings */
828
    }
829 830 831 832 833 834 835 836

    /* 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:
837
    memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
838 839 840 841
    return STATUS_SUCCESS;
}


842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
/***********************************************************************
 *           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();
}


861 862 863 864 865 866
/***********************************************************************
 *           do_relocations
 *
 * Apply the relocations to a mapped PE image
 */
static int do_relocations( char *base, const IMAGE_DATA_DIRECTORY *dir,
867
                           int delta, SIZE_T total_size )
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
{
    IMAGE_BASE_RELOCATION *rel;

    TRACE_(module)( "relocating from %p-%p to %p-%p\n",
                    base - delta, base - delta + total_size, base, base + total_size );

    for (rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
         ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
         rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock) )
    {
        char *page = base + rel->VirtualAddress;
        WORD *TypeOffset = (WORD *)(rel + 1);
        int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);

        if (!count) continue;

        /* sanity checks */
885
        if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size)
886
        {
887
            ERR_(module)("invalid relocation %p,%x,%d at %p,%x,%x\n",
888 889 890 891 892
                         rel, rel->VirtualAddress, rel->SizeOfBlock,
                         base, dir->VirtualAddress, dir->Size );
            return 0;
        }

893 894 895 896 897 898 899
        if (page > base + total_size)
        {
            WARN_(module)("skipping %d relocations for page %p beyond module %p-%p\n",
                          count, page, base, base + total_size );
            continue;
        }

900
        TRACE_(module)("%d relocations for page %x\n", count, rel->VirtualAddress);
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935

        /* patching in reverse order */
        for (i = 0 ; i < count; i++)
        {
            int offset = TypeOffset[i] & 0xFFF;
            int type = TypeOffset[i] >> 12;
            switch(type)
            {
            case IMAGE_REL_BASED_ABSOLUTE:
                break;
            case IMAGE_REL_BASED_HIGH:
                *(short*)(page+offset) += HIWORD(delta);
                break;
            case IMAGE_REL_BASED_LOW:
                *(short*)(page+offset) += LOWORD(delta);
                break;
            case IMAGE_REL_BASED_HIGHLOW:
                *(int*)(page+offset) += delta;
                /* FIXME: if this is an exported address, fire up enhanced logic */
                break;
            default:
                FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
                break;
            }
        }
    }
    return 1;
}


/***********************************************************************
 *           map_image
 *
 * Map an executable (PE format) image into memory.
 */
936
static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
937
                           SIZE_T header_size, int shared_fd, HANDLE dup_mapping, PVOID *addr_ptr )
938 939 940 941 942
{
    IMAGE_DOS_HEADER *dos;
    IMAGE_NT_HEADERS *nt;
    IMAGE_SECTION_HEADER *sec;
    IMAGE_DATA_DIRECTORY *imports;
943 944 945
    NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
    int i;
    off_t pos;
946
    sigset_t sigset;
947
    struct stat st;
948
    struct file_view *view = NULL;
949
    char *ptr, *header_end;
950 951 952

    /* zero-map the whole range */

953
    server_enter_uninterrupted_section( &csVirtual, &sigset );
954 955

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

    if (status == STATUS_CONFLICTING_ADDRESSES)
960
        status = map_view( &view, NULL, total_size, mask, FALSE,
961 962 963 964 965
                           VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );

    if (status != STATUS_SUCCESS) goto error;

    ptr = view->base;
966 967 968 969
    TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );

    /* map the header */

970 971 972 973 974
    if (fstat( fd, &st ) == -1)
    {
        status = FILE_GetNtStatus();
        goto error;
    }
975
    status = STATUS_INVALID_IMAGE_FORMAT;  /* generic error */
976 977
    if (!st.st_size) goto error;
    header_size = min( header_size, st.st_size );
978
    if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
979
                            !dup_mapping ) != STATUS_SUCCESS) goto error;
980 981
    dos = (IMAGE_DOS_HEADER *)ptr;
    nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
982
    header_end = ptr + ROUND_SIZE( 0, header_size );
983
    memset( ptr + header_size, 0, header_end - (ptr + header_size) );
984
    if ((char *)(nt + 1) > header_end) goto error;
985
    sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
986
    if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004

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

    /* check the architecture */

    if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
    {
        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;
        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;
1005 1006 1007
        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;
1008
        case IMAGE_FILE_MACHINE_ARM:     MESSAGE("ARM"); break;
1009 1010 1011 1012 1013 1014
        default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
        }
        MESSAGE(")\n");
        goto error;
    }

1015 1016 1017 1018 1019 1020 1021 1022
    /* 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,
1023
                                !dup_mapping ) != STATUS_SUCCESS) goto error;
1024 1025

        /* check that all sections are loaded at the right offset */
1026
        if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        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 );

        /* perform relocations if necessary */
        /* FIXME: not 100% compatible, Windows doesn't do this for non page-aligned binaries */
        if (ptr != base)
        {
            const IMAGE_DATA_DIRECTORY *relocs;
            relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
            if (relocs->VirtualAddress && relocs->Size)
                do_relocations( ptr, relocs, ptr - base, total_size );
        }

        goto done;
    }


1051 1052 1053 1054
    /* map all the sections */

    for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
    {
1055 1056
        static const SIZE_T sector_align = 0x1ff;
        SIZE_T map_size, file_start, file_size, end;
1057 1058

        if (!sec->Misc.VirtualSize)
1059
            map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1060 1061
        else
            map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1062 1063 1064 1065 1066

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

        /* a few sanity checks */
1069 1070
        end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
        if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1071
        {
1072 1073
            WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
                           sec->Name, sec->VirtualAddress, map_size, total_size );
1074 1075 1076 1077 1078 1079
            goto error;
        }

        if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
            (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
        {
1080
            TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1081 1082 1083 1084
                            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,
1085
                                    VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1086
                                    FALSE ) != STATUS_SUCCESS)
1087 1088 1089 1090 1091 1092 1093
            {
                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 &&
1094
                imports->VirtualAddress < sec->VirtualAddress + map_size)
1095 1096 1097
            {
                UINT_PTR base = imports->VirtualAddress & ~page_mask;
                UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1098
                if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1099 1100 1101 1102 1103
                if (end > base)
                    map_file_into_view( view, shared_fd, base, end - base,
                                        pos + (base - sec->VirtualAddress),
                                        VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
                                        FALSE );
1104
            }
1105
            pos += map_size;
1106 1107 1108
            continue;
        }

1109
        TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1110 1111
                        sec->Name, ptr + sec->VirtualAddress,
                        sec->PointerToRawData, sec->SizeOfRawData,
1112
                        sec->Misc.VirtualSize, sec->Characteristics );
1113

1114
        if (!sec->PointerToRawData || !file_size) continue;
1115

1116
        /* Note: if the section is not aligned properly map_file_into_view will magically
1117 1118
         *       fall back to read(), so we don't need to check anything here.
         */
1119 1120 1121 1122 1123
        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,
1124
                                VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1125
                                !dup_mapping ) != STATUS_SUCCESS)
1126 1127 1128 1129 1130
        {
            ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
            goto error;
        }

1131
        if (file_size & page_mask)
1132
        {
1133 1134
            end = ROUND_SIZE( 0, file_size );
            if (end > map_size) end = map_size;
1135
            TRACE_(module)("clearing %p - %p\n",
1136
                           ptr + sec->VirtualAddress + file_size,
1137
                           ptr + sec->VirtualAddress + end );
1138
            memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
        }
    }


    /* perform base relocation, if necessary */

    if (ptr != base)
    {
        const IMAGE_DATA_DIRECTORY *relocs;

        relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1150
        if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1151
        {
1152 1153
            WARN( "Need to relocate module from addr %lx, but there are no relocation records\n",
                  (ULONG_PTR)nt->OptionalHeader.ImageBase );
1154
            status = STATUS_CONFLICTING_ADDRESSES;
1155 1156 1157 1158 1159 1160 1161
            goto error;
        }

        /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
         *        really make sure that the *new* base address is also > 2GB.
         *        Some DLLs really check the MSB of the module handle :-/
         */
1162
        if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((ULONG_PTR)base & 0x80000000))
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
            ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );

        if (!do_relocations( ptr, relocs, ptr - base, total_size ))
        {
            goto error;
        }
    }

    /* set the image protections */

1173 1174
    VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );

1175 1176 1177
    sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
    for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
    {
1178
        SIZE_T size;
1179
        BYTE vprot = VPROT_COMMITTED;
1180 1181 1182 1183 1184 1185

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

1186
        if (sec->Characteristics & IMAGE_SCN_MEM_READ)    vprot |= VPROT_READ;
1187
        if (sec->Characteristics & IMAGE_SCN_MEM_WRITE)   vprot |= VPROT_READ|VPROT_WRITECOPY;
1188
        if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1189 1190 1191 1192 1193 1194

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

1195 1196
        VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
    }
1197 1198

 done:
1199
    view->mapping = dup_mapping;
1200
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1201 1202 1203 1204 1205

    *addr_ptr = ptr;
    return STATUS_SUCCESS;

 error:
1206
    if (view) delete_view( view );
1207
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1208
    if (dup_mapping) NtClose( dup_mapping );
1209 1210 1211 1212 1213
    return status;
}


/***********************************************************************
1214
 *           virtual_init
1215
 */
1216
void virtual_init(void)
1217
{
1218
    const char *preload;
1219
#ifndef page_mask
1220 1221 1222 1223 1224 1225 1226
    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++;
#endif  /* page_mask */
1227 1228 1229 1230 1231 1232 1233 1234 1235
    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;
        }
    }
1236
}
1237 1238


1239
/***********************************************************************
1240
 *           virtual_init_threading
1241
 */
1242
void virtual_init_threading(void)
1243
{
1244
    use_locks = 1;
1245 1246 1247
}


1248 1249 1250
/***********************************************************************
 *           VIRTUAL_HandleFault
 */
1251
NTSTATUS VIRTUAL_HandleFault( LPCVOID addr )
1252
{
1253
    FILE_VIEW *view;
1254
    NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1255
    sigset_t sigset;
1256

1257
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1258
    if ((view = VIRTUAL_FindView( addr )))
1259
    {
1260 1261
        void *page = ROUND_ADDR( addr, page_mask );
        BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1262
        if (vprot & VPROT_GUARD)
1263
        {
1264
            VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1265
            ret = STATUS_GUARD_PAGE_VIOLATION;
1266 1267
        }
    }
1268
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1269 1270 1271 1272
    return ret;
}


1273 1274 1275 1276 1277 1278 1279 1280
/***********************************************************************
 *           VIRTUAL_SetForceExec
 *
 * Whether to force exec prot on all views.
 */
void VIRTUAL_SetForceExec( BOOL enable )
{
    struct file_view *view;
1281
    sigset_t sigset;
1282

1283
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    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;
            int unix_prot;
            char *addr = view->base;
            BYTE prot = view->prot[0];

            for (count = i = 1; i < view->size >> page_shift; i++, count++)
            {
                if (view->prot[i] == prot) continue;
                unix_prot = VIRTUAL_GetUnixProt( prot );
                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);
                prot = view->prot[i];
                count = 0;
            }
            if (count)
            {
                unix_prot = VIRTUAL_GetUnixProt( prot );
                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) );
                }
            }
        }
    }
1325
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1326 1327 1328
}


1329 1330 1331 1332 1333 1334 1335
/***********************************************************************
 *           VIRTUAL_UseLargeAddressSpace
 *
 * Increase the address space size for apps that support it.
 */
void VIRTUAL_UseLargeAddressSpace(void)
{
1336 1337
    /* no large address space on win9x */
    if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1338 1339 1340 1341
    user_space_limit = ADDRESS_SPACE_LIMIT;
}


1342 1343 1344 1345
/***********************************************************************
 *             NtAllocateVirtualMemory   (NTDLL.@)
 *             ZwAllocateVirtualMemory   (NTDLL.@)
 */
1346
NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1347
                                         SIZE_T *size_ptr, ULONG type, ULONG protect )
1348 1349 1350
{
    void *base;
    BYTE vprot;
1351
    SIZE_T size = *size_ptr;
1352
    SIZE_T mask = get_mask( zero_bits );
1353 1354
    NTSTATUS status = STATUS_SUCCESS;
    struct file_view *view;
1355
    sigset_t sigset;
1356

1357
    TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1358 1359 1360

    if (!size) return STATUS_INVALID_PARAMETER;

1361
    if (process != NtCurrentProcess())
1362
    {
1363 1364 1365
        apc_call_t call;
        apc_result_t result;

1366 1367
        memset( &call, 0, sizeof(call) );

1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
        call.virtual_alloc.type      = APC_VIRTUAL_ALLOC;
        call.virtual_alloc.addr      = *ret;
        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)
        {
            *ret      = result.virtual_alloc.addr;
            *size_ptr = result.virtual_alloc.size;
        }
        return result.virtual_alloc.status;
1383 1384 1385 1386 1387 1388
    }

    /* Round parameters to a page boundary */

    if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */

1389
    if (*ret)
1390 1391
    {
        if (type & MEM_RESERVE) /* Round down to 64k boundary */
1392
            base = ROUND_ADDR( *ret, mask );
1393
        else
1394 1395
            base = ROUND_ADDR( *ret, page_mask );
        size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1396 1397

        /* disallow low 64k, wrap-around and kernel space */
1398
        if (((char *)base < (char *)0x10000) ||
1399
            ((char *)base + size < (char *)base) ||
1400
            is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
            return STATUS_INVALID_PARAMETER;
    }
    else
    {
        base = NULL;
        size = (size + page_mask) & ~page_mask;
    }

    /* Compute the alloc type flags */

1411
    if (!(type & MEM_SYSTEM))
1412
    {
1413
        if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
1414
            (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1415
        {
1416
            WARN("called with wrong alloc type flags (%08x) !\n", type);
1417
            return STATUS_INVALID_PARAMETER;
1418
        }
1419 1420 1421 1422 1423
        if (type & MEM_WRITE_WATCH)
        {
            FIXME("MEM_WRITE_WATCH type not supported\n");
            return STATUS_NOT_SUPPORTED;
        }
1424
    }
1425 1426
    vprot = VIRTUAL_GetProt( protect );
    if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1427

1428 1429
    /* Reserve the memory */

1430
    if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1431

1432 1433
    if (type & MEM_SYSTEM)
    {
1434 1435 1436 1437 1438 1439 1440
        if (type & MEM_IMAGE) vprot |= VPROT_IMAGE;
        status = create_view( &view, base, size, vprot | VPROT_COMMITTED );
        if (status == STATUS_SUCCESS)
        {
            view->flags |= VFLAG_VALLOC | VFLAG_SYSTEM;
            base = view->base;
        }
1441 1442 1443
    }
    else if ((type & MEM_RESERVE) || !base)
    {
1444
        status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1445
        if (status == STATUS_SUCCESS)
1446
        {
1447 1448
            view->flags |= VFLAG_VALLOC;
            base = view->base;
1449 1450
        }
    }
1451
    else  /* commit the pages */
1452 1453
    {
        if (!(view = VIRTUAL_FindView( base )) ||
1454 1455
            ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
        else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1456 1457
    }

1458
    if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1459 1460 1461 1462 1463 1464 1465

    if (status == STATUS_SUCCESS)
    {
        *ret = base;
        *size_ptr = size;
    }
    return status;
1466 1467 1468 1469 1470 1471 1472
}


/***********************************************************************
 *             NtFreeVirtualMemory   (NTDLL.@)
 *             ZwFreeVirtualMemory   (NTDLL.@)
 */
1473
NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1474 1475 1476
{
    FILE_VIEW *view;
    char *base;
1477
    sigset_t sigset;
1478
    NTSTATUS status = STATUS_SUCCESS;
1479
    LPVOID addr = *addr_ptr;
1480
    SIZE_T size = *size_ptr;
1481

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

1484
    if (process != NtCurrentProcess())
1485
    {
1486 1487 1488
        apc_call_t call;
        apc_result_t result;

1489 1490
        memset( &call, 0, sizeof(call) );

1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
        call.virtual_free.type      = APC_VIRTUAL_FREE;
        call.virtual_free.addr      = addr;
        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)
        {
            *addr_ptr = result.virtual_free.addr;
            *size_ptr = result.virtual_free.size;
        }
        return result.virtual_free.status;
1504 1505 1506 1507 1508 1509 1510
    }

    /* Fix the parameters */

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

1511 1512 1513
    /* avoid freeing the DOS area when a broken app passes a NULL pointer */
    if (!base && !(type & MEM_SYSTEM)) return STATUS_INVALID_PARAMETER;

1514
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1515

1516 1517 1518
    if (!(view = VIRTUAL_FindView( base )) ||
        (base + size > (char *)view->base + view->size) ||
        !(view->flags & VFLAG_VALLOC))
1519 1520 1521 1522
    {
        status = STATUS_INVALID_PARAMETER;
    }
    else if (type & MEM_SYSTEM)
1523
    {
1524 1525
        /* return the values that the caller should use to unmap the area */
        *addr_ptr = view->base;
1526 1527
        if (!wine_mmap_is_in_reserved_area( view->base, view->size )) *size_ptr = view->size;
        else *size_ptr = 0;  /* make sure we don't munmap anything from a reserved area */
1528
        view->flags |= VFLAG_SYSTEM;
1529
        delete_view( view );
1530
    }
1531
    else if (type == MEM_RELEASE)
1532
    {
1533 1534
        /* Free the pages */

1535 1536 1537
        if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
        else
        {
1538
            delete_view( view );
1539 1540 1541
            *addr_ptr = base;
            *size_ptr = size;
        }
1542
    }
1543
    else if (type == MEM_DECOMMIT)
1544
    {
1545 1546
        status = decommit_pages( view, base - (char *)view->base, size );
        if (status == STATUS_SUCCESS)
1547 1548 1549 1550
        {
            *addr_ptr = base;
            *size_ptr = size;
        }
1551
    }
1552 1553
    else
    {
1554
        WARN("called with wrong free type flags (%08x) !\n", type);
1555
        status = STATUS_INVALID_PARAMETER;
1556
    }
1557

1558
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1559
    return status;
1560 1561 1562 1563 1564 1565 1566
}


/***********************************************************************
 *             NtProtectVirtualMemory   (NTDLL.@)
 *             ZwProtectVirtualMemory   (NTDLL.@)
 */
1567
NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1568 1569 1570
                                        ULONG new_prot, ULONG *old_prot )
{
    FILE_VIEW *view;
1571
    sigset_t sigset;
1572
    NTSTATUS status = STATUS_SUCCESS;
1573 1574 1575
    char *base;
    UINT i;
    BYTE vprot, *p;
1576 1577
    ULONG prot;
    SIZE_T size = *size_ptr;
1578 1579
    LPVOID addr = *addr_ptr;

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

1582
    if (process != NtCurrentProcess())
1583
    {
1584 1585 1586
        apc_call_t call;
        apc_result_t result;

1587 1588
        memset( &call, 0, sizeof(call) );

1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
        call.virtual_protect.type = APC_VIRTUAL_PROTECT;
        call.virtual_protect.addr = addr;
        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)
        {
            *addr_ptr = result.virtual_protect.addr;
            *size_ptr = result.virtual_protect.size;
            if (old_prot) *old_prot = result.virtual_protect.prot;
        }
        return result.virtual_protect.status;
1603 1604 1605 1606 1607 1608 1609
    }

    /* Fix the parameters */

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

1610
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1611

1612
    if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1613
    {
1614
        status = STATUS_INVALID_PARAMETER;
1615
    }
1616 1617 1618
    else
    {
        /* Make sure all the pages are committed */
1619

1620
        p = view->prot + ((base - (char *)view->base) >> page_shift);
1621
        prot = VIRTUAL_GetWin32Prot( *p );
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
        for (i = size >> page_shift; i; i--, p++)
        {
            if (!(*p & VPROT_COMMITTED))
            {
                status = STATUS_NOT_COMMITTED;
                break;
            }
        }
        if (!i)
        {
            if (old_prot) *old_prot = prot;
            vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
            if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
        }
    }
1637
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1638

1639 1640 1641 1642 1643 1644
    if (status == STATUS_SUCCESS)
    {
        *addr_ptr = base;
        *size_ptr = size;
    }
    return status;
1645 1646
}

1647 1648 1649 1650
#define UNIMPLEMENTED_INFO_CLASS(c) \
    case c: \
        FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
        return STATUS_INVALID_INFO_CLASS
1651 1652 1653 1654 1655 1656 1657

/***********************************************************************
 *             NtQueryVirtualMemory   (NTDLL.@)
 *             ZwQueryVirtualMemory   (NTDLL.@)
 */
NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
                                      MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1658
                                      SIZE_T len, SIZE_T *res_len )
1659 1660 1661
{
    FILE_VIEW *view;
    char *base, *alloc_base = 0;
1662
    struct list *ptr;
1663
    SIZE_T size = 0;
1664
    MEMORY_BASIC_INFORMATION *info = buffer;
1665
    sigset_t sigset;
1666

1667 1668
    if (info_class != MemoryBasicInformation)
    {
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
        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;
        }
1680
    }
1681
    if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1682
        return STATUS_WORKING_SET_LIMIT_RANGE;
1683

1684
    if (process != NtCurrentProcess())
1685
    {
1686 1687 1688 1689
        NTSTATUS status;
        apc_call_t call;
        apc_result_t result;

1690 1691
        memset( &call, 0, sizeof(call) );

1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
        call.virtual_query.type = APC_VIRTUAL_QUERY;
        call.virtual_query.addr = addr;
        status = NTDLL_queue_process_apc( process, &call, &result );
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_query.status == STATUS_SUCCESS)
        {
            info->BaseAddress       = result.virtual_query.base;
            info->AllocationBase    = result.virtual_query.alloc_base;
            info->RegionSize        = result.virtual_query.size;
            info->State             = result.virtual_query.state;
            info->Protect           = result.virtual_query.prot;
            info->AllocationProtect = result.virtual_query.alloc_prot;
            info->Type              = result.virtual_query.alloc_type;
            if (res_len) *res_len = sizeof(*info);
        }
        return result.virtual_query.status;
1709 1710 1711 1712 1713 1714
    }

    base = ROUND_ADDR( addr, page_mask );

    /* Find the view containing the address */

1715
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1716
    ptr = list_head( &views_list );
1717 1718
    for (;;)
    {
1719
        if (!ptr)
1720
        {
1721 1722
            /* make the address space end at the user limit, except if
             * the last view was mapped beyond that */
1723
            if (alloc_base <= (char *)user_space_limit)
1724
            {
1725
                if (user_space_limit && base >= (char *)user_space_limit)
1726
                {
1727
                    server_leave_uninterrupted_section( &csVirtual, &sigset );
1728 1729
                    return STATUS_WORKING_SET_LIMIT_RANGE;
                }
1730
                size = (char *)user_space_limit - alloc_base;
1731 1732
            }
            else size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1733
            view = NULL;
1734 1735
            break;
        }
1736
        view = LIST_ENTRY( ptr, struct file_view, entry );
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
        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;
1750
        ptr = list_next( &views_list, ptr );
1751 1752 1753 1754 1755 1756 1757
    }

    /* Fill the info structure */

    if (!view)
    {
        info->State             = MEM_FREE;
1758 1759
        info->Protect           = PAGE_NOACCESS;
        info->AllocationBase    = 0;
1760 1761 1762 1763 1764 1765
        info->AllocationProtect = 0;
        info->Type              = 0;
    }
    else
    {
        BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1766 1767
        info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
        info->Protect = VIRTUAL_GetWin32Prot( vprot );
1768
        info->AllocationBase = alloc_base;
1769
        info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
1770 1771 1772
        if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
        else if (view->flags & VFLAG_VALLOC) info->Type = MEM_PRIVATE;
        else info->Type = MEM_MAPPED;
1773
        for (size = base - alloc_base; size < view->size; size += page_size)
1774
            if (view->prot[size >> page_shift] != vprot) break;
1775
    }
1776
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1777

1778
    info->BaseAddress    = base;
1779
    info->RegionSize     = size - (base - alloc_base);
1780
    if (res_len) *res_len = sizeof(*info);
1781 1782 1783 1784 1785 1786 1787 1788
    return STATUS_SUCCESS;
}


/***********************************************************************
 *             NtLockVirtualMemory   (NTDLL.@)
 *             ZwLockVirtualMemory   (NTDLL.@)
 */
1789
NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1790
{
1791 1792 1793
    NTSTATUS status = STATUS_SUCCESS;

    if (process != NtCurrentProcess())
1794
    {
1795 1796 1797
        apc_call_t call;
        apc_result_t result;

1798 1799
        memset( &call, 0, sizeof(call) );

1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
        call.virtual_lock.type = APC_VIRTUAL_LOCK;
        call.virtual_lock.addr = *addr;
        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)
        {
            *addr = result.virtual_lock.addr;
            *size = result.virtual_lock.size;
        }
        return result.virtual_lock.status;
1812
    }
1813 1814 1815 1816 1817 1818

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

    if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
    return status;
1819 1820 1821 1822 1823 1824 1825
}


/***********************************************************************
 *             NtUnlockVirtualMemory   (NTDLL.@)
 *             ZwUnlockVirtualMemory   (NTDLL.@)
 */
1826
NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1827
{
1828 1829 1830
    NTSTATUS status = STATUS_SUCCESS;

    if (process != NtCurrentProcess())
1831
    {
1832 1833 1834
        apc_call_t call;
        apc_result_t result;

1835 1836
        memset( &call, 0, sizeof(call) );

1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
        call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
        call.virtual_unlock.addr = *addr;
        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)
        {
            *addr = result.virtual_unlock.addr;
            *size = result.virtual_unlock.size;
        }
        return result.virtual_unlock.status;
1849
    }
1850 1851 1852 1853 1854 1855

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

    if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
    return status;
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
}


/***********************************************************************
 *             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;
    BYTE vprot;
1869
    DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
1870 1871
    struct security_descriptor *sd = NULL;
    struct object_attributes objattr;
1872 1873 1874 1875 1876

    /* Check parameters */

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

1877 1878
    objattr.rootdir = attr ? attr->RootDirectory : 0;
    objattr.sd_len = 0;
1879
    objattr.name_len = len;
1880 1881 1882 1883 1884 1885
    if (attr)
    {
        ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
        if (ret != STATUS_SUCCESS) return ret;
    }

1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
    vprot = VIRTUAL_GetProt( protect );
    if (sec_flags & SEC_RESERVE)
    {
        if (file) return STATUS_INVALID_PARAMETER;
    }
    else vprot |= VPROT_COMMITTED;
    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 )
    {
1899 1900
        req->access      = access;
        req->attributes  = (attr) ? attr->Attributes : 0;
1901
        req->file_handle = file;
1902
        req->size        = size ? size->QuadPart : 0;
1903
        req->protect     = vprot;
1904 1905
        wine_server_add_data( req, &objattr, sizeof(objattr) );
        if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
1906 1907 1908 1909 1910
        if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
        ret = wine_server_call( req );
        *handle = reply->handle;
    }
    SERVER_END_REQ;
1911 1912 1913

    NTDLL_free_struct_sd( sd );

1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
    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;
1932
        req->attributes = (attr) ? attr->Attributes : 0;
1933
        req->rootdir = attr ? attr->RootDirectory : 0;
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
        wine_server_add_data( req, attr->ObjectName->Buffer, len );
        if (!(ret = wine_server_call( req ))) *handle = reply->handle;
    }
    SERVER_END_REQ;
    return ret;
}


/***********************************************************************
 *             NtMapViewOfSection   (NTDLL.@)
 *             ZwMapViewOfSection   (NTDLL.@)
 */
NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
1947
                                    SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
1948 1949 1950
                                    SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
{
    NTSTATUS res;
1951
    ULONGLONG full_size;
1952
    SIZE_T size = 0;
1953
    SIZE_T mask = get_mask( zero_bits );
1954
    int unix_handle = -1, needs_close;
1955
    int prot;
1956 1957
    void *base;
    struct file_view *view;
1958
    DWORD header_size;
1959
    HANDLE dup_mapping, shared_file;
1960
    LARGE_INTEGER offset;
1961
    sigset_t sigset;
1962 1963

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

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

1968 1969
    /* Check parameters */

1970
    if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
1971 1972
        return STATUS_INVALID_PARAMETER;

1973 1974 1975 1976 1977
    if (process != NtCurrentProcess())
    {
        apc_call_t call;
        apc_result_t result;

1978 1979
        memset( &call, 0, sizeof(call) );

1980 1981 1982 1983
        call.map_view.type        = APC_MAP_VIEW;
        call.map_view.handle      = handle;
        call.map_view.addr        = *addr_ptr;
        call.map_view.size        = *size_ptr;
1984
        call.map_view.offset      = offset.QuadPart;
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
        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)
        {
            *addr_ptr = result.map_view.addr;
            *size_ptr = result.map_view.size;
        }
        return result.map_view.status;
    }

1999 2000 2001 2002 2003 2004
    SERVER_START_REQ( get_mapping_info )
    {
        req->handle = handle;
        res = wine_server_call( req );
        prot        = reply->protect;
        base        = reply->base;
2005
        full_size   = reply->size;
2006
        header_size = reply->header_size;
2007
        dup_mapping = reply->mapping;
2008 2009 2010
        shared_file = reply->shared_file;
    }
    SERVER_END_REQ;
2011
    if (res) return res;
2012

2013 2014 2015 2016
    size = full_size;
    if (sizeof(size) < sizeof(full_size) && (size != full_size))
        ERR( "Sizes larger than 4Gb (%x%08x) not supported on this platform\n",
             (DWORD)(full_size >> 32), (DWORD)full_size );
2017

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

2020 2021 2022 2023
    if (prot & VPROT_IMAGE)
    {
        if (shared_file)
        {
2024
            int shared_fd, shared_needs_close;
2025

2026
            if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2027
                                           &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2028
            res = map_image( handle, unix_handle, base, size, mask, header_size,
2029
                             shared_fd, dup_mapping, addr_ptr );
2030
            if (shared_needs_close) close( shared_fd );
2031 2032 2033 2034
            NtClose( shared_file );
        }
        else
        {
2035
            res = map_image( handle, unix_handle, base, size, mask, header_size,
2036
                             -1, dup_mapping, addr_ptr );
2037
        }
2038
        if (needs_close) close( unix_handle );
2039
        if (!res) *size_ptr = size;
2040 2041 2042
        return res;
    }

2043
    if ((offset.QuadPart >= size) || (*size_ptr > size - offset.QuadPart))
2044 2045
    {
        res = STATUS_INVALID_PARAMETER;
2046
        goto done;
2047
    }
2048
    if (*size_ptr) size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2049
    else size = size - offset.QuadPart;
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059

    switch(protect)
    {
    case PAGE_NOACCESS:
        break;
    case PAGE_READWRITE:
    case PAGE_EXECUTE_READWRITE:
        if (!(prot & VPROT_WRITE))
        {
            res = STATUS_INVALID_PARAMETER;
2060
            goto done;
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
        }
        /* fall through */
    case PAGE_READONLY:
    case PAGE_WRITECOPY:
    case PAGE_EXECUTE:
    case PAGE_EXECUTE_READ:
    case PAGE_EXECUTE_WRITECOPY:
        if (prot & VPROT_READ) break;
        /* fall through */
    default:
        res = STATUS_INVALID_PARAMETER;
2072
        goto done;
2073 2074 2075 2076
    }

    /* FIXME: If a mapping is created with SEC_RESERVE and a process,
     * which has a view of this mapping commits some pages, they will
2077 2078 2079
     * appear committed in all other processes, which have the same
     * view created. Since we don't support this yet, we create the
     * whole mapping committed.
2080 2081 2082 2083 2084
     */
    prot |= VPROT_COMMITTED;

    /* Reserve a properly aligned area */

2085
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2086

2087
    res = map_view( &view, *addr_ptr, size, mask, FALSE, prot );
2088 2089
    if (res)
    {
2090
        server_leave_uninterrupted_section( &csVirtual, &sigset );
2091 2092
        goto done;
    }
2093 2094 2095

    /* Map the file */

2096
    TRACE("handle=%p size=%lx offset=%x%08x\n",
2097
          handle, size, offset.u.HighPart, offset.u.LowPart );
2098

2099
    res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, prot, !dup_mapping );
2100
    if (res == STATUS_SUCCESS)
2101
    {
2102 2103
        *addr_ptr = view->base;
        *size_ptr = size;
2104 2105
        view->mapping = dup_mapping;
        dup_mapping = 0;  /* don't close it */
2106 2107
    }
    else
2108
    {
2109
        ERR( "map_file_into_view %p %lx %x%08x failed\n",
2110
             view->base, size, offset.u.HighPart, offset.u.LowPart );
2111
        delete_view( view );
2112 2113
    }

2114
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2115 2116

done:
2117
    if (dup_mapping) NtClose( dup_mapping );
2118
    if (needs_close) close( unix_handle );
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
    return res;
}


/***********************************************************************
 *             NtUnmapViewOfSection   (NTDLL.@)
 *             ZwUnmapViewOfSection   (NTDLL.@)
 */
NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
{
    FILE_VIEW *view;
2130
    NTSTATUS status = STATUS_INVALID_PARAMETER;
2131
    sigset_t sigset;
2132 2133
    void *base = ROUND_ADDR( addr, page_mask );

2134
    if (process != NtCurrentProcess())
2135
    {
2136 2137 2138
        apc_call_t call;
        apc_result_t result;

2139 2140
        memset( &call, 0, sizeof(call) );

2141 2142 2143 2144 2145
        call.unmap_view.type = APC_UNMAP_VIEW;
        call.unmap_view.addr = addr;
        status = NTDLL_queue_process_apc( process, &call, &result );
        if (status == STATUS_SUCCESS) status = result.unmap_view.status;
        return status;
2146
    }
2147

2148
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2149 2150
    if ((view = VIRTUAL_FindView( base )) && (base == view->base))
    {
2151
        delete_view( view );
2152 2153
        status = STATUS_SUCCESS;
    }
2154
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2155
    return status;
2156 2157 2158 2159 2160 2161 2162 2163
}


/***********************************************************************
 *             NtFlushVirtualMemory   (NTDLL.@)
 *             ZwFlushVirtualMemory   (NTDLL.@)
 */
NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2164
                                      SIZE_T *size_ptr, ULONG unknown )
2165 2166
{
    FILE_VIEW *view;
2167
    NTSTATUS status = STATUS_SUCCESS;
2168
    sigset_t sigset;
2169 2170
    void *addr = ROUND_ADDR( *addr_ptr, page_mask );

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

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

2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
        call.virtual_flush.type = APC_VIRTUAL_FLUSH;
        call.virtual_flush.addr = addr;
        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)
        {
            *addr_ptr = result.virtual_flush.addr;
            *size_ptr = result.virtual_flush.size;
        }
        return result.virtual_flush.status;
2190
    }
2191

2192
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2193 2194 2195 2196 2197 2198 2199
    if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
    else
    {
        if (!*size_ptr) *size_ptr = view->size;
        *addr_ptr = addr;
        if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
    }
2200
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2201
    return status;
2202
}
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238


/***********************************************************************
 *             NtReadVirtualMemory   (NTDLL.@)
 *             ZwReadVirtualMemory   (NTDLL.@)
 */
NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
                                     SIZE_T size, SIZE_T *bytes_read )
{
    NTSTATUS status;

    SERVER_START_REQ( read_process_memory )
    {
        req->handle = process;
        req->addr   = (void *)addr;
        wine_server_set_reply( req, buffer, size );
        if ((status = wine_server_call( req ))) size = 0;
    }
    SERVER_END_REQ;
    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;

    SERVER_START_REQ( write_process_memory )
    {
        req->handle     = process;
2239
        req->addr       = addr;
2240 2241 2242 2243 2244 2245 2246
        wine_server_add_data( req, buffer, size );
        if ((status = wine_server_call( req ))) size = 0;
    }
    SERVER_END_REQ;
    if (bytes_written) *bytes_written = size;
    return status;
}
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258


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

    return STATUS_NOT_SAME_DEVICE;
}