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

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

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

45 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/exception.h"
54
#include "wine/list.h"
55
#include "wine/debug.h"
56
#include "ntdll_misc.h"
57 58 59 60 61 62 63 64

WINE_DEFAULT_DEBUG_CHANNEL(virtual);
WINE_DECLARE_DEBUG_CHANNEL(module);

#ifndef MS_SYNC
#define MS_SYNC 0
#endif

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

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


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

103
static struct list views_list = LIST_INIT(views_list);
104

105 106
static RTL_CRITICAL_SECTION csVirtual;
static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
107 108 109
{
    0, 0, &csVirtual,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
110
      0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
111
};
112
static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
113 114

#ifdef __i386__
115 116
static const UINT page_shift = 12;
static const UINT_PTR page_mask = 0xfff;
117
/* Note: these are Windows limits, you cannot change them. */
118 119
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 */
120
static void *working_set_limit   = (void *)0x7fff0000;  /* top of the current working set */
121
static void *address_space_start = (void *)0x110000;    /* keep DOS area clear */
122
#elif defined(__x86_64__)
123 124
static const UINT page_shift = 12;
static const UINT_PTR page_mask = 0xfff;
125 126 127
static void *address_space_limit = (void *)0x7fffffff0000;
static void *user_space_limit    = (void *)0x7fffffff0000;
static void *working_set_limit   = (void *)0x7fffffff0000;
128
static void *address_space_start = (void *)0x10000;
129
#else
130
UINT_PTR page_size = 0;
131
static UINT page_shift;
132
static UINT_PTR page_mask;
133 134 135
static void *address_space_limit;
static void *user_space_limit;
static void *working_set_limit;
136
static void *address_space_start = (void *)0x10000;
137
#endif  /* __i386__ */
138
static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
139 140

#define ROUND_ADDR(addr,mask) \
141
   ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
142 143

#define ROUND_SIZE(addr,size) \
144
   (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
145 146

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

149
#define VIRTUAL_HEAP_SIZE (sizeof(void*)*1024*1024)
150 151

static HANDLE virtual_heap;
152 153
static void *preload_reserve_start;
static void *preload_reserve_end;
154 155
static BOOL use_locks;
static BOOL force_exec_prot;  /* whether to force PROT_EXEC on all PROT_READ mmaps */
156

157 158 159 160 161 162 163 164

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


174 175 176 177 178 179 180 181 182 183 184
/***********************************************************************
 *           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;
185 186
        if (vprot & VPROT_WRITE) prot |= PROT_WRITE | PROT_READ;
        if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE | PROT_READ;
187
        if (vprot & VPROT_EXEC) prot |= PROT_EXEC | PROT_READ;
188
        if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
189 190 191 192 193 194
    }
    if (!prot) prot = PROT_NONE;
    return prot;
}


195 196 197
/***********************************************************************
 *           VIRTUAL_DumpView
 */
198
static void VIRTUAL_DumpView( struct file_view *view )
199 200 201 202 203
{
    UINT i, count;
    char *addr = view->base;
    BYTE prot = view->prot[0];

204
    TRACE( "View: %p - %p", addr, addr + view->size - 1 );
205
    if (view->protect & VPROT_SYSTEM)
206
        TRACE( " (system)\n" );
207
    else if (view->protect & VPROT_VALLOC)
208
        TRACE( " (valloc)\n" );
209
    else if (view->mapping)
210
        TRACE( " %p\n", view->mapping );
211
    else
212
        TRACE( " (anonymous)\n");
213 214 215 216

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


/***********************************************************************
 *           VIRTUAL_Dump
 */
232
#ifdef WINE_VM_DEBUG
233
static void VIRTUAL_Dump(void)
234
{
235
    sigset_t sigset;
236
    struct file_view *view;
237

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


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

265
    LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
266
    {
267 268 269 270 271
        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;
272
    }
273
    return NULL;
274 275 276
}


277 278 279 280 281 282 283 284 285 286 287
/***********************************************************************
 *           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;
}


288
/***********************************************************************
289
 *           find_view_range
290
 *
291 292 293 294 295
 * 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 )
{
296
    struct file_view *view;
297

298
    LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
299
    {
Eric Pouech's avatar
Eric Pouech committed
300 301
        if ((const char *)view->base >= (const char *)addr + size) break;
        if ((const char *)view->base + view->size > (const char *)addr) return view;
302 303 304 305 306
    }
    return NULL;
}


307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
/***********************************************************************
 *           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;
}


354 355
/***********************************************************************
 *           add_reserved_area
356
 *
357 358 359 360 361 362 363
 * 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 );

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


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

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

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


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


/***********************************************************************
 *           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 );
429 430
    else if (is_beyond_limit( addr, size, user_space_limit ))
        add_reserved_area( addr, size );
431 432 433 434 435 436 437 438 439
    else
        munmap( addr, size );
}


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


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

461
    assert( !((UINT_PTR)base & page_mask) );
462
    assert( !(size & page_mask) );
463 464 465

    /* Create the view structure */

466 467 468 469 470
    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;
    }
471

472
    view->base    = base;
473 474
    view->size    = size;
    view->mapping = 0;
475
    view->map_protect = 0;
476
    view->protect = vprot;
477
    memset( view->prot, vprot, size >> page_shift );
478

479
    /* Insert it in the linked list */
480

481
    LIST_FOR_EACH( ptr, &views_list )
482
    {
483 484
        struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
        if (next->base > base) break;
485
    }
486
    list_add_before( ptr, &view->entry );
487

488 489 490
    /* 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. */
491

492
    if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
493
    {
494
        struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
495 496 497 498 499
        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 );
500
            assert( prev->protect & VPROT_SYSTEM );
501
            delete_view( prev );
502 503
        }
    }
504
    if ((ptr = list_next( &views_list, &view->entry )) != NULL)
505
    {
506 507 508 509 510 511
        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 );
512
            assert( next->protect & VPROT_SYSTEM );
513
            delete_view( next );
514
        }
515
    }
516 517

    *view_ret = view;
518 519
    VIRTUAL_DEBUG_DUMP_VIEW( view );

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


/***********************************************************************
 *           VIRTUAL_GetWin32Prot
 *
 * Convert page protections to Win32 flags.
 */
534
static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
535
{
536 537 538 539
    DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
    if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
    if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
    return ret;
540 541 542 543
}


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


/***********************************************************************
 *           VIRTUAL_SetProt
 *
 * Change the protection of a range of pages.
 *
 * RETURNS
 *	TRUE: Success
 *	FALSE: Failure
 */
606
static BOOL VIRTUAL_SetProt( struct file_view *view, /* [in] Pointer to view */
607
                             void *base,      /* [in] Starting address */
608
                             size_t size,     /* [in] Size in bytes */
609 610
                             BYTE vprot )     /* [in] Protections to use */
{
611
    int unix_prot = VIRTUAL_GetUnixProt(vprot);
612
    BYTE *p = view->prot + (((char *)base - (char *)view->base) >> page_shift);
613

614 615 616
    TRACE("%p-%p %s\n",
          base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );

617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
    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;
    }

641 642 643
    /* 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) &&
644 645
        (base >= NtCurrentTeb()->DeallocationStack) &&
        (base < NtCurrentTeb()->Tib.StackBase))
646
    {
647
        memset( p, vprot, size >> page_shift );
648 649 650 651 652
        mprotect( base, size, unix_prot );
        VIRTUAL_DEBUG_DUMP_VIEW( view );
        return TRUE;
    }

653 654
    if (force_exec_prot && !(view->protect & VPROT_NOEXEC) &&
        (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
655 656 657 658 659 660 661 662
    {
        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 */
663

664
done:
665
    memset( p, vprot, size >> page_shift );
666 667 668 669 670
    VIRTUAL_DEBUG_DUMP_VIEW( view );
    return TRUE;
}


671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
/***********************************************************************
 *           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 );
}


699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
/***********************************************************************
 *           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;
}


719 720 721 722 723
struct alloc_area
{
    size_t size;
    size_t mask;
    int    top_down;
724
    void  *limit;
725 726 727 728 729 730 731 732 733 734 735 736 737 738
    void  *result;
};

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

    if (start < address_space_start) start = address_space_start;
739
    if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
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
    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;
}


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

780
    if (base)
781
    {
782
        if (is_beyond_limit( base, size, address_space_limit ))
783 784 785
            return STATUS_WORKING_SET_LIMIT_RANGE;

        switch (wine_mmap_is_in_reserved_area( base, size ))
786
        {
787
        case -1: /* partially in a reserved area */
788
            return STATUS_CONFLICTING_ADDRESSES;
789 790 791 792 793 794 795 796 797 798

        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 */
799
                if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
800 801 802 803 804 805 806 807 808 809 810 811
                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;
812
        }
813
        if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
814
    }
815
    else
816
    {
817
        size_t view_size = size + mask + 1;
818 819 820 821 822
        struct alloc_area alloc;

        alloc.size = size;
        alloc.mask = mask;
        alloc.top_down = top_down;
823
        alloc.limit = user_space_limit;
824 825 826 827 828 829 830 831
        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;
        }
832

833
        for (;;)
834
        {
835 836 837 838 839
            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;
            }
840
            TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
841
            /* if we got something beyond the user limit, unmap it and retry */
842
            if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
843
            else break;
844
        }
845
        ptr = unmap_extra_space( ptr, view_size, size, mask );
846
    }
847
done:
848
    status = create_view( view_ret, ptr, size, vprot );
849
    if (status != STATUS_SUCCESS) unmap_area( ptr, size );
850 851 852 853 854 855 856 857 858 859 860
    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,
861
                                    off_t offset, unsigned int vprot, BOOL removable )
862 863
{
    void *ptr;
864
    int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
865 866 867 868 869
    BOOL shared_write = (vprot & VPROT_WRITE) != 0;

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

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

877 878
    /* only try mmap if media is not removable (or if we require write access) */
    if (!removable || shared_write)
879
    {
880 881
        int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);

882
        if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
883 884
            goto done;

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

888 889 890 891
        /* 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();
892 893 894 895 896 897
        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;
        }
898
    }
899 900 901 902 903 904 905 906

    /* 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:
907
    memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
908 909 910 911
    return STATUS_SUCCESS;
}


912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
/***********************************************************************
 *           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 )
        {
930
            req->handle = wine_server_obj_handle( view->mapping );
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
            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;
}


951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
/***********************************************************************
 *           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();
}


970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
/***********************************************************************
 *           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)
        {
1011 1012 1013 1014 1015 1016
            if (!wine_anon_mmap( NULL, page_size, unix_prot, MAP_FIXED ))
            {
                addr = NULL;
                TRACE( "successfully mapped low 64K range\n" );
            }
            else TRACE( "failed to map page 0\n" );
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
        }
        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 );
}


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

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


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

    /* zero-map the whole range */

1078
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1079

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

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

    if (status != STATUS_SUCCESS) goto error;

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

    /* map the header */

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

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

1121 1122 1123 1124 1125 1126 1127 1128
    /* 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,
1129
                                !dup_mapping ) != STATUS_SUCCESS) goto error;
1130 1131

        /* check that all sections are loaded at the right offset */
1132
        if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
        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 );

1143
        /* no relocations are performed on non page-aligned binaries */
1144 1145 1146 1147
        goto done;
    }


1148 1149 1150 1151
    /* map all the sections */

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

        if (!sec->Misc.VirtualSize)
1156
            map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1157 1158
        else
            map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1159 1160 1161 1162 1163

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

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

        if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
            (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
        {
1177
            TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1178 1179 1180 1181
                            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,
1182
                                    VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1183
                                    FALSE ) != STATUS_SUCCESS)
1184 1185 1186 1187 1188 1189 1190
            {
                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 &&
1191
                imports->VirtualAddress < sec->VirtualAddress + map_size)
1192 1193 1194
            {
                UINT_PTR base = imports->VirtualAddress & ~page_mask;
                UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1195
                if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1196 1197 1198 1199 1200
                if (end > base)
                    map_file_into_view( view, shared_fd, base, end - base,
                                        pos + (base - sec->VirtualAddress),
                                        VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
                                        FALSE );
1201
            }
1202
            pos += map_size;
1203 1204 1205
            continue;
        }

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

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

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

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


    /* perform base relocation, if necessary */

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

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

1257 1258 1259 1260 1261 1262
        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);
1263
        delta = ptr - base;
1264

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

    /* set the image protections */

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

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

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

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

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

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

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

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

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


1329 1330
/* 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 )
1331
{
1332 1333
    void **heap_base = arg;

1334
    if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1335
    if (size < VIRTUAL_HEAP_SIZE) return 0;
1336
    if (is_win64 && base < (void *)0x80000000) return 0;
1337 1338 1339
    *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);
1340 1341
}

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

1352 1353
#if !defined(__i386__) && !defined(__x86_64__)
    page_size = sysconf( _SC_PAGESIZE );
1354 1355 1356 1357 1358
    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++;
1359
    user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1360
#endif  /* page_mask */
1361 1362 1363 1364 1365 1366 1367 1368 1369
    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;
        }
    }
1370 1371 1372 1373 1374 1375 1376 1377 1378

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

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


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


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


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

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

    if (status) return status;

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

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

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

1454 1455 1456 1457
    return status;
}


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

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

    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;

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

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

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


1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
/***********************************************************************
 *           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 );
}


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

1528
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1529
    if ((view = VIRTUAL_FindView( addr, 0 )))
1530
    {
1531
        void *page = ROUND_ADDR( addr, page_mask );
1532 1533
        BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
        if (*vprot & VPROT_GUARD)
1534
        {
1535
            VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1536
            ret = STATUS_GUARD_PAGE_VIOLATION;
1537
        }
1538
        if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1539
        {
1540 1541 1542 1543 1544 1545 1546
            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;
1547
        }
1548
    }
1549
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1550 1551 1552 1553
    return ret;
}


1554

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

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


1572 1573 1574 1575 1576 1577 1578 1579
/***********************************************************************
 *           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 )
{
1580
    struct file_view *view;
1581 1582 1583
    BOOL ret = FALSE;

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


1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
/***********************************************************************
 *           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;
1618
        char dummy __attribute__((unused));
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
        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;
}


1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
/***********************************************************************
 *           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;
}


1672 1673 1674 1675 1676 1677 1678 1679
/***********************************************************************
 *           VIRTUAL_SetForceExec
 *
 * Whether to force exec prot on all views.
 */
void VIRTUAL_SetForceExec( BOOL enable )
{
    struct file_view *view;
1680
    sigset_t sigset;
1681

1682
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1683 1684 1685 1686 1687 1688 1689 1690
    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;
1691 1692
            BYTE commit = view->mapping ? VPROT_COMMITTED : 0;  /* file mappings are always accessible */
            int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1693

1694
            if (view->protect & VPROT_NOEXEC) continue;
1695 1696
            for (count = i = 1; i < view->size >> page_shift; i++, count++)
            {
1697 1698
                int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
                if (prot == unix_prot) continue;
1699 1700 1701 1702 1703 1704 1705 1706 1707
                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);
1708
                unix_prot = prot;
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
                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) );
                }
            }
        }
    }
1724
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1725 1726
}

1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
struct free_range
{
    char *base;
    char *limit;
};

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

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

1750
/***********************************************************************
1751
 *           virtual_release_address_space
1752
 *
1753
 * Release some address space once we have loaded and initialized the app.
1754
 */
1755
void virtual_release_address_space(void)
1756
{
1757 1758 1759
    struct free_range range;
    sigset_t sigset;

1760
    if (is_win64) return;
1761

1762 1763
    server_enter_uninterrupted_section( &csVirtual, &sigset );

1764 1765 1766 1767
    range.base  = (char *)0x82000000;
    range.limit = user_space_limit;

    if (range.limit > range.base)
1768 1769 1770
    {
        while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
    }
1771 1772 1773 1774 1775 1776 1777 1778 1779
    else
    {
#ifndef __APPLE__  /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
        range.base  = (char *)0x20000000;
        range.limit = (char *)0x7f000000;
        while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
#endif
    }

1780
    server_leave_uninterrupted_section( &csVirtual, &sigset );
1781 1782 1783
}


1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
/***********************************************************************
 *           virtual_set_large_address_space
 *
 * Enable use of a large address space when allowed by the application.
 */
void virtual_set_large_address_space(void)
{
    IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );

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

    user_space_limit = working_set_limit = address_space_limit;
}


1801 1802 1803 1804
/***********************************************************************
 *             NtAllocateVirtualMemory   (NTDLL.@)
 *             ZwAllocateVirtualMemory   (NTDLL.@)
 */
1805
NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1806
                                         SIZE_T *size_ptr, ULONG type, ULONG protect )
1807 1808
{
    void *base;
1809
    unsigned int vprot;
1810
    SIZE_T size = *size_ptr;
1811
    SIZE_T mask = get_mask( zero_bits );
1812 1813
    NTSTATUS status = STATUS_SUCCESS;
    struct file_view *view;
1814
    sigset_t sigset;
1815

1816
    TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1817 1818 1819

    if (!size) return STATUS_INVALID_PARAMETER;

1820
    if (process != NtCurrentProcess())
1821
    {
1822 1823 1824
        apc_call_t call;
        apc_result_t result;

1825 1826
        memset( &call, 0, sizeof(call) );

1827
        call.virtual_alloc.type      = APC_VIRTUAL_ALLOC;
1828
        call.virtual_alloc.addr      = wine_server_client_ptr( *ret );
1829 1830 1831 1832
        call.virtual_alloc.size      = *size_ptr;
        call.virtual_alloc.zero_bits = zero_bits;
        call.virtual_alloc.op_type   = type;
        call.virtual_alloc.prot      = protect;
1833
        status = server_queue_process_apc( process, &call, &result );
1834 1835 1836 1837
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_alloc.status == STATUS_SUCCESS)
        {
1838
            *ret      = wine_server_get_ptr( result.virtual_alloc.addr );
1839 1840 1841
            *size_ptr = result.virtual_alloc.size;
        }
        return result.virtual_alloc.status;
1842 1843 1844 1845
    }

    /* Round parameters to a page boundary */

1846
    if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1847

1848
    if ((status = get_vprot_flags( protect, &vprot, FALSE ))) return status;
1849
    if (vprot & VPROT_WRITECOPY) return STATUS_INVALID_PAGE_PROTECTION;
1850
    vprot |= VPROT_VALLOC;
1851 1852
    if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;

1853
    if (*ret)
1854 1855
    {
        if (type & MEM_RESERVE) /* Round down to 64k boundary */
1856
            base = ROUND_ADDR( *ret, mask );
1857
        else
1858 1859
            base = ROUND_ADDR( *ret, page_mask );
        size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1860

1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
        /* 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;
        }

1875
        /* disallow low 64k, wrap-around and kernel space */
1876
        if (((char *)base < (char *)0x10000) ||
1877
            ((char *)base + size < (char *)base) ||
1878
            is_beyond_limit( base, size, address_space_limit ))
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
            return STATUS_INVALID_PARAMETER;
    }
    else
    {
        base = NULL;
        size = (size + page_mask) & ~page_mask;
    }

    /* Compute the alloc type flags */

1889
    if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
1890
        (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1891
    {
1892 1893 1894
        WARN("called with wrong alloc type flags (%08x) !\n", type);
        return STATUS_INVALID_PARAMETER;
    }
1895

1896 1897
    /* Reserve the memory */

1898
    if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1899

1900
    if ((type & MEM_RESERVE) || !base)
1901
    {
1902
        if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
1903
        status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1904
        if (status == STATUS_SUCCESS) base = view->base;
1905
    }
1906 1907 1908 1909 1910
    else if (type & MEM_RESET)
    {
        if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
        else madvise( base, size, MADV_DONTNEED );
    }
1911
    else  /* commit the pages */
1912
    {
1913
        if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1914
        else if (view->mapping && (view->protect & VPROT_COMMITTED)) status = STATUS_ALREADY_COMMITTED;
1915
        else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1916 1917 1918 1919
        else if (view->mapping && !(view->protect & VPROT_COMMITTED))
        {
            SERVER_START_REQ( add_mapping_committed_range )
            {
1920
                req->handle = wine_server_obj_handle( view->mapping );
1921 1922 1923 1924 1925 1926
                req->offset = (char *)base - (char *)view->base;
                req->size   = size;
                wine_server_call( req );
            }
            SERVER_END_REQ;
        }
1927 1928
    }

1929
    if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1930 1931 1932 1933 1934 1935 1936

    if (status == STATUS_SUCCESS)
    {
        *ret = base;
        *size_ptr = size;
    }
    return status;
1937 1938 1939 1940 1941 1942 1943
}


/***********************************************************************
 *             NtFreeVirtualMemory   (NTDLL.@)
 *             ZwFreeVirtualMemory   (NTDLL.@)
 */
1944
NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1945
{
1946
    struct file_view *view;
1947
    char *base;
1948
    sigset_t sigset;
1949
    NTSTATUS status = STATUS_SUCCESS;
1950
    LPVOID addr = *addr_ptr;
1951
    SIZE_T size = *size_ptr;
1952

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

1955
    if (process != NtCurrentProcess())
1956
    {
1957 1958 1959
        apc_call_t call;
        apc_result_t result;

1960 1961
        memset( &call, 0, sizeof(call) );

1962
        call.virtual_free.type      = APC_VIRTUAL_FREE;
1963
        call.virtual_free.addr      = wine_server_client_ptr( addr );
1964 1965
        call.virtual_free.size      = size;
        call.virtual_free.op_type   = type;
1966
        status = server_queue_process_apc( process, &call, &result );
1967 1968 1969 1970
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_free.status == STATUS_SUCCESS)
        {
1971
            *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
1972 1973 1974
            *size_ptr = result.virtual_free.size;
        }
        return result.virtual_free.status;
1975 1976 1977 1978 1979 1980 1981
    }

    /* Fix the parameters */

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

1982
    /* avoid freeing the DOS area when a broken app passes a NULL pointer */
1983
    if (!base) return STATUS_INVALID_PARAMETER;
1984

1985
    server_enter_uninterrupted_section( &csVirtual, &sigset );
1986

1987
    if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
1988 1989 1990 1991
    {
        status = STATUS_INVALID_PARAMETER;
    }
    else if (type == MEM_RELEASE)
1992
    {
1993 1994
        /* Free the pages */

1995 1996 1997
        if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
        else
        {
1998
            delete_view( view );
1999 2000 2001
            *addr_ptr = base;
            *size_ptr = size;
        }
2002
    }
2003
    else if (type == MEM_DECOMMIT)
2004
    {
2005 2006
        status = decommit_pages( view, base - (char *)view->base, size );
        if (status == STATUS_SUCCESS)
2007 2008 2009 2010
        {
            *addr_ptr = base;
            *size_ptr = size;
        }
2011
    }
2012 2013
    else
    {
2014
        WARN("called with wrong free type flags (%08x) !\n", type);
2015
        status = STATUS_INVALID_PARAMETER;
2016
    }
2017

2018
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2019
    return status;
2020 2021
}

2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
static ULONG map_protection_to_access( ULONG vprot )
{
    vprot &= VPROT_READ | VPROT_WRITE | VPROT_EXEC | VPROT_WRITECOPY;
    if (vprot & VPROT_EXEC)
    {
        if (vprot & VPROT_WRITE) vprot |= VPROT_WRITECOPY;
    }
    else vprot &= ~VPROT_WRITECOPY;
    return vprot;
}

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

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

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

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

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

    return FALSE;
}
2050 2051 2052 2053 2054

/***********************************************************************
 *             NtProtectVirtualMemory   (NTDLL.@)
 *             ZwProtectVirtualMemory   (NTDLL.@)
 */
2055
NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
2056 2057
                                        ULONG new_prot, ULONG *old_prot )
{
2058
    struct file_view *view;
2059
    sigset_t sigset;
2060
    NTSTATUS status = STATUS_SUCCESS;
2061
    char *base;
2062
    BYTE vprot;
2063
    unsigned int new_vprot;
2064
    SIZE_T size = *size_ptr;
2065 2066
    LPVOID addr = *addr_ptr;

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

2069
    if (process != NtCurrentProcess())
2070
    {
2071 2072 2073
        apc_call_t call;
        apc_result_t result;

2074 2075
        memset( &call, 0, sizeof(call) );

2076
        call.virtual_protect.type = APC_VIRTUAL_PROTECT;
2077
        call.virtual_protect.addr = wine_server_client_ptr( addr );
2078 2079
        call.virtual_protect.size = size;
        call.virtual_protect.prot = new_prot;
2080
        status = server_queue_process_apc( process, &call, &result );
2081 2082 2083 2084
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_protect.status == STATUS_SUCCESS)
        {
2085
            *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
2086 2087 2088 2089
            *size_ptr = result.virtual_protect.size;
            if (old_prot) *old_prot = result.virtual_protect.prot;
        }
        return result.virtual_protect.status;
2090 2091 2092 2093 2094 2095 2096
    }

    /* Fix the parameters */

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

2097
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2098

2099
    if ((view = VIRTUAL_FindView( base, size )))
2100 2101
    {
        /* Make sure all the pages are committed */
2102
        if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2103
        {
2104
            if (!(status = get_vprot_flags( new_prot, &new_vprot, view->protect & VPROT_IMAGE )))
2105 2106 2107 2108 2109
            {
                if ((new_vprot & VPROT_WRITECOPY) && (view->protect & VPROT_VALLOC))
                    status = STATUS_INVALID_PAGE_PROTECTION;
                else
                {
2110 2111 2112 2113 2114 2115 2116
                    if (!view->mapping || is_compatible_protection( view, new_vprot ))
                    {
                        new_vprot |= VPROT_COMMITTED;
                        if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
                        if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
                    }
                    else status = STATUS_INVALID_PAGE_PROTECTION;
2117 2118
                }
            }
2119
        }
2120
        else status = STATUS_NOT_COMMITTED;
2121
    }
2122 2123
    else status = STATUS_INVALID_PARAMETER;

2124
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2125

2126 2127 2128 2129 2130 2131
    if (status == STATUS_SUCCESS)
    {
        *addr_ptr = base;
        *size_ptr = size;
    }
    return status;
2132 2133
}

2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148

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

2149
    if (info->BaseAddress >= start || start <= address_space_start)
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
    {
        /* 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;
}

2171 2172 2173 2174
#define UNIMPLEMENTED_INFO_CLASS(c) \
    case c: \
        FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
        return STATUS_INVALID_INFO_CLASS
2175 2176 2177 2178 2179 2180 2181

/***********************************************************************
 *             NtQueryVirtualMemory   (NTDLL.@)
 *             ZwQueryVirtualMemory   (NTDLL.@)
 */
NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
                                      MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2182
                                      SIZE_T len, SIZE_T *res_len )
2183
{
2184
    struct file_view *view;
2185
    char *base, *alloc_base = 0;
2186
    struct list *ptr;
2187
    SIZE_T size = 0;
2188
    MEMORY_BASIC_INFORMATION *info = buffer;
2189
    sigset_t sigset;
2190

2191 2192
    if (info_class != MemoryBasicInformation)
    {
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
        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;
        }
2204
    }
2205

2206
    if (process != NtCurrentProcess())
2207
    {
2208 2209 2210 2211
        NTSTATUS status;
        apc_call_t call;
        apc_result_t result;

2212 2213
        memset( &call, 0, sizeof(call) );

2214
        call.virtual_query.type = APC_VIRTUAL_QUERY;
2215
        call.virtual_query.addr = wine_server_client_ptr( addr );
2216
        status = server_queue_process_apc( process, &call, &result );
2217 2218 2219 2220
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_query.status == STATUS_SUCCESS)
        {
2221 2222
            info->BaseAddress       = wine_server_get_ptr( result.virtual_query.base );
            info->AllocationBase    = wine_server_get_ptr( result.virtual_query.alloc_base );
2223 2224 2225
            info->RegionSize        = result.virtual_query.size;
            info->Protect           = result.virtual_query.prot;
            info->AllocationProtect = result.virtual_query.alloc_prot;
2226 2227
            info->State             = (DWORD)result.virtual_query.state << 12;
            info->Type              = (DWORD)result.virtual_query.alloc_type << 16;
2228 2229
            if (info->RegionSize != result.virtual_query.size)  /* truncated */
                return STATUS_INVALID_PARAMETER;  /* FIXME */
2230 2231 2232
            if (res_len) *res_len = sizeof(*info);
        }
        return result.virtual_query.status;
2233 2234 2235 2236
    }

    base = ROUND_ADDR( addr, page_mask );

2237 2238
    if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;

2239 2240
    /* Find the view containing the address */

2241
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2242
    ptr = list_head( &views_list );
2243 2244
    for (;;)
    {
2245
        if (!ptr)
2246
        {
2247
            size = (char *)working_set_limit - alloc_base;
2248
            view = NULL;
2249 2250
            break;
        }
2251
        view = LIST_ENTRY( ptr, struct file_view, entry );
2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
        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;
2265
        ptr = list_next( &views_list, ptr );
2266 2267 2268 2269
    }

    /* Fill the info structure */

2270 2271 2272 2273
    info->AllocationBase = alloc_base;
    info->BaseAddress    = base;
    info->RegionSize     = size - (base - alloc_base);

2274 2275
    if (!view)
    {
2276 2277 2278
        if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
        {
            /* not in a reserved area at all, pretend it's allocated */
2279
#ifdef __i386__
2280 2281 2282 2283 2284 2285 2286 2287
            if (base >= (char *)address_space_start)
            {
                info->State             = MEM_RESERVE;
                info->Protect           = PAGE_NOACCESS;
                info->AllocationProtect = PAGE_NOACCESS;
                info->Type              = MEM_PRIVATE;
            }
            else
2288
#endif
2289 2290 2291 2292 2293 2294 2295
            {
                info->State             = MEM_FREE;
                info->Protect           = PAGE_NOACCESS;
                info->AllocationBase    = 0;
                info->AllocationProtect = 0;
                info->Type              = 0;
            }
2296
        }
2297 2298 2299
    }
    else
    {
2300 2301 2302
        BYTE vprot;
        SIZE_T range_size = get_committed_size( view, base, &vprot );

2303
        info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2304
        info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2305
        info->AllocationBase = alloc_base;
2306
        info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2307
        if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2308
        else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2309
        else info->Type = MEM_MAPPED;
2310
        for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2311
            if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2312
        info->RegionSize = size - (base - alloc_base);
2313
    }
2314
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2315

2316
    if (res_len) *res_len = sizeof(*info);
2317 2318 2319 2320 2321 2322 2323 2324
    return STATUS_SUCCESS;
}


/***********************************************************************
 *             NtLockVirtualMemory   (NTDLL.@)
 *             ZwLockVirtualMemory   (NTDLL.@)
 */
2325
NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2326
{
2327 2328 2329
    NTSTATUS status = STATUS_SUCCESS;

    if (process != NtCurrentProcess())
2330
    {
2331 2332 2333
        apc_call_t call;
        apc_result_t result;

2334 2335
        memset( &call, 0, sizeof(call) );

2336
        call.virtual_lock.type = APC_VIRTUAL_LOCK;
2337
        call.virtual_lock.addr = wine_server_client_ptr( *addr );
2338
        call.virtual_lock.size = *size;
2339
        status = server_queue_process_apc( process, &call, &result );
2340 2341 2342 2343
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_lock.status == STATUS_SUCCESS)
        {
2344
            *addr = wine_server_get_ptr( result.virtual_lock.addr );
2345 2346 2347
            *size = result.virtual_lock.size;
        }
        return result.virtual_lock.status;
2348
    }
2349 2350 2351 2352 2353 2354

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

    if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
    return status;
2355 2356 2357 2358 2359 2360 2361
}


/***********************************************************************
 *             NtUnlockVirtualMemory   (NTDLL.@)
 *             ZwUnlockVirtualMemory   (NTDLL.@)
 */
2362
NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2363
{
2364 2365 2366
    NTSTATUS status = STATUS_SUCCESS;

    if (process != NtCurrentProcess())
2367
    {
2368 2369 2370
        apc_call_t call;
        apc_result_t result;

2371 2372
        memset( &call, 0, sizeof(call) );

2373
        call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2374
        call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2375
        call.virtual_unlock.size = *size;
2376
        status = server_queue_process_apc( process, &call, &result );
2377 2378 2379 2380
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_unlock.status == STATUS_SUCCESS)
        {
2381
            *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2382 2383 2384
            *size = result.virtual_unlock.size;
        }
        return result.virtual_unlock.status;
2385
    }
2386 2387 2388 2389 2390 2391

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

    if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
    return status;
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403
}


/***********************************************************************
 *             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;
2404
    unsigned int vprot;
2405
    DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2406 2407
    struct security_descriptor *sd = NULL;
    struct object_attributes objattr;
2408 2409 2410 2411 2412

    /* Check parameters */

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

2413
    if ((ret = get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE ))) return ret;
2414

2415
    objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
2416
    objattr.sd_len = 0;
2417
    objattr.name_len = len;
2418 2419 2420 2421 2422 2423
    if (attr)
    {
        ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
        if (ret != STATUS_SUCCESS) return ret;
    }

2424
    if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2425 2426 2427 2428 2429 2430 2431
    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 )
    {
2432 2433
        req->access      = access;
        req->attributes  = (attr) ? attr->Attributes : 0;
2434
        req->file_handle = wine_server_obj_handle( file );
2435
        req->size        = size ? size->QuadPart : 0;
2436
        req->protect     = vprot;
2437 2438
        wine_server_add_data( req, &objattr, sizeof(objattr) );
        if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2439 2440
        if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
        ret = wine_server_call( req );
2441
        *handle = wine_server_ptr_handle( reply->handle );
2442 2443
    }
    SERVER_END_REQ;
2444 2445 2446

    NTDLL_free_struct_sd( sd );

2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464
    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;
2465
        req->attributes = attr->Attributes;
2466
        req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2467
        wine_server_add_data( req, attr->ObjectName->Buffer, len );
2468
        if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479
    }
    SERVER_END_REQ;
    return ret;
}


/***********************************************************************
 *             NtMapViewOfSection   (NTDLL.@)
 *             ZwMapViewOfSection   (NTDLL.@)
 */
NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2480
                                    SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2481 2482 2483
                                    SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
{
    NTSTATUS res;
2484
    mem_size_t full_size;
2485
    ACCESS_MASK access;
2486
    SIZE_T size, mask = get_mask( zero_bits );
2487
    int unix_handle = -1, needs_close;
2488
    unsigned int map_vprot, vprot;
2489 2490
    void *base;
    struct file_view *view;
2491
    DWORD header_size;
2492
    HANDLE dup_mapping, shared_file;
2493
    LARGE_INTEGER offset;
2494
    sigset_t sigset;
2495 2496

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

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

2501 2502
    /* Check parameters */

2503
    if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2504 2505
        return STATUS_INVALID_PARAMETER;

2506 2507 2508
    switch(protect)
    {
    case PAGE_NOACCESS:
2509
        access = SECTION_MAP_READ;
2510 2511 2512
        break;
    case PAGE_READWRITE:
    case PAGE_EXECUTE_READWRITE:
2513
        access = SECTION_MAP_WRITE;
2514 2515 2516 2517 2518 2519
        break;
    case PAGE_READONLY:
    case PAGE_WRITECOPY:
    case PAGE_EXECUTE:
    case PAGE_EXECUTE_READ:
    case PAGE_EXECUTE_WRITECOPY:
2520
        access = SECTION_MAP_READ;
2521 2522
        break;
    default:
2523
        return STATUS_INVALID_PAGE_PROTECTION;
2524 2525
    }

2526 2527 2528 2529 2530
    if (process != NtCurrentProcess())
    {
        apc_call_t call;
        apc_result_t result;

2531 2532
        memset( &call, 0, sizeof(call) );

2533
        call.map_view.type        = APC_MAP_VIEW;
2534
        call.map_view.handle      = wine_server_obj_handle( handle );
2535
        call.map_view.addr        = wine_server_client_ptr( *addr_ptr );
2536
        call.map_view.size        = *size_ptr;
2537
        call.map_view.offset      = offset.QuadPart;
2538 2539 2540
        call.map_view.zero_bits   = zero_bits;
        call.map_view.alloc_type  = alloc_type;
        call.map_view.prot        = protect;
2541
        res = server_queue_process_apc( process, &call, &result );
2542 2543
        if (res != STATUS_SUCCESS) return res;

2544
        if ((NTSTATUS)result.map_view.status >= 0)
2545
        {
2546
            *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2547 2548 2549 2550 2551
            *size_ptr = result.map_view.size;
        }
        return result.map_view.status;
    }

2552 2553
    SERVER_START_REQ( get_mapping_info )
    {
2554
        req->handle = wine_server_obj_handle( handle );
2555
        req->access = access;
2556
        res = wine_server_call( req );
2557
        map_vprot   = reply->protect;
2558
        base        = wine_server_get_ptr( reply->base );
2559
        full_size   = reply->size;
2560
        header_size = reply->header_size;
2561 2562
        dup_mapping = wine_server_ptr_handle( reply->mapping );
        shared_file = wine_server_ptr_handle( reply->shared_file );
2563
        if ((ULONG_PTR)base != reply->base) base = NULL;
2564 2565
    }
    SERVER_END_REQ;
2566
    if (res) return res;
2567

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

2570
    if (map_vprot & VPROT_IMAGE)
2571
    {
2572 2573 2574 2575 2576 2577 2578
        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;
        }
2579 2580
        if (shared_file)
        {
2581
            int shared_fd, shared_needs_close;
2582

2583
            if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2584
                                           &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2585
            res = map_image( handle, unix_handle, base, size, mask, header_size,
2586
                             shared_fd, dup_mapping, map_vprot, addr_ptr );
2587
            if (shared_needs_close) close( shared_fd );
2588 2589 2590 2591
            NtClose( shared_file );
        }
        else
        {
2592
            res = map_image( handle, unix_handle, base, size, mask, header_size,
2593
                             -1, dup_mapping, map_vprot, addr_ptr );
2594
        }
2595
        if (needs_close) close( unix_handle );
2596
        if (res >= 0) *size_ptr = size;
2597 2598 2599
        return res;
    }

2600 2601 2602
    res = STATUS_INVALID_PARAMETER;
    if (offset.QuadPart >= full_size) goto done;
    if (*size_ptr)
2603
    {
2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616
        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;
        }
2617 2618 2619 2620
    }

    /* Reserve a properly aligned area */

2621
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2622

2623
    get_vprot_flags( protect, &vprot, map_vprot & VPROT_IMAGE );
2624
    vprot |= (map_vprot & VPROT_COMMITTED);
2625
    res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2626 2627
    if (res)
    {
2628
        server_leave_uninterrupted_section( &csVirtual, &sigset );
2629 2630
        goto done;
    }
2631 2632 2633

    /* Map the file */

2634
    TRACE("handle=%p size=%lx offset=%x%08x\n",
2635
          handle, size, offset.u.HighPart, offset.u.LowPart );
2636

2637
    res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2638
    if (res == STATUS_SUCCESS)
2639
    {
2640 2641
        *addr_ptr = view->base;
        *size_ptr = size;
2642
        view->mapping = dup_mapping;
2643
        view->map_protect = map_vprot;
2644
        dup_mapping = 0;  /* don't close it */
2645 2646
    }
    else
2647
    {
2648
        ERR( "map_file_into_view %p %lx %x%08x failed\n",
2649
             view->base, size, offset.u.HighPart, offset.u.LowPart );
2650
        delete_view( view );
2651 2652
    }

2653
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2654 2655

done:
2656
    if (dup_mapping) NtClose( dup_mapping );
2657
    if (needs_close) close( unix_handle );
2658 2659 2660 2661 2662 2663 2664 2665 2666 2667
    return res;
}


/***********************************************************************
 *             NtUnmapViewOfSection   (NTDLL.@)
 *             ZwUnmapViewOfSection   (NTDLL.@)
 */
NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
{
2668
    struct file_view *view;
2669
    NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
2670
    sigset_t sigset;
2671 2672
    void *base = ROUND_ADDR( addr, page_mask );

2673
    if (process != NtCurrentProcess())
2674
    {
2675 2676 2677
        apc_call_t call;
        apc_result_t result;

2678 2679
        memset( &call, 0, sizeof(call) );

2680
        call.unmap_view.type = APC_UNMAP_VIEW;
2681
        call.unmap_view.addr = wine_server_client_ptr( addr );
2682
        status = server_queue_process_apc( process, &call, &result );
2683 2684
        if (status == STATUS_SUCCESS) status = result.unmap_view.status;
        return status;
2685
    }
2686

2687
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2688
    if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base) && !(view->protect & VPROT_VALLOC))
2689
    {
2690
        delete_view( view );
2691 2692
        status = STATUS_SUCCESS;
    }
2693
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2694
    return status;
2695 2696 2697 2698 2699 2700 2701 2702
}


/***********************************************************************
 *             NtFlushVirtualMemory   (NTDLL.@)
 *             ZwFlushVirtualMemory   (NTDLL.@)
 */
NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2703
                                      SIZE_T *size_ptr, ULONG unknown )
2704
{
2705
    struct file_view *view;
2706
    NTSTATUS status = STATUS_SUCCESS;
2707
    sigset_t sigset;
2708 2709
    void *addr = ROUND_ADDR( *addr_ptr, page_mask );

2710
    if (process != NtCurrentProcess())
2711
    {
2712 2713 2714
        apc_call_t call;
        apc_result_t result;

2715 2716
        memset( &call, 0, sizeof(call) );

2717
        call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2718
        call.virtual_flush.addr = wine_server_client_ptr( addr );
2719
        call.virtual_flush.size = *size_ptr;
2720
        status = server_queue_process_apc( process, &call, &result );
2721 2722 2723 2724
        if (status != STATUS_SUCCESS) return status;

        if (result.virtual_flush.status == STATUS_SUCCESS)
        {
2725
            *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2726 2727 2728
            *size_ptr = result.virtual_flush.size;
        }
        return result.virtual_flush.status;
2729
    }
2730

2731
    server_enter_uninterrupted_section( &csVirtual, &sigset );
2732
    if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2733 2734 2735 2736 2737 2738
    else
    {
        if (!*size_ptr) *size_ptr = view->size;
        *addr_ptr = addr;
        if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
    }
2739
    server_leave_uninterrupted_section( &csVirtual, &sigset );
2740
    return status;
2741
}
2742 2743


2744 2745 2746 2747 2748 2749 2750
/***********************************************************************
 *             NtGetWriteWatch   (NTDLL.@)
 *             ZwGetWriteWatch   (NTDLL.@)
 */
NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
                                 ULONG_PTR *count, ULONG *granularity )
{
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
    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,
2765
           addresses, *count );
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788

    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;
2789 2790 2791 2792 2793 2794 2795 2796 2797
}


/***********************************************************************
 *             NtResetWriteWatch   (NTDLL.@)
 *             ZwResetWriteWatch   (NTDLL.@)
 */
NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
{
2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
    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;
2818 2819 2820
}


2821 2822 2823 2824 2825 2826 2827 2828 2829
/***********************************************************************
 *             NtReadVirtualMemory   (NTDLL.@)
 *             ZwReadVirtualMemory   (NTDLL.@)
 */
NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
                                     SIZE_T size, SIZE_T *bytes_read )
{
    NTSTATUS status;

2830
    if (virtual_check_buffer_for_write( buffer, size ))
2831
    {
2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844
        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;
2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
    }
    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;

2860
    if (virtual_check_buffer_for_read( buffer, size ))
2861
    {
2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874
        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;
2875 2876 2877 2878
    }
    if (bytes_written) *bytes_written = size;
    return status;
}
2879 2880 2881 2882 2883 2884 2885 2886


/***********************************************************************
 *             NtAreMappedFilesTheSame   (NTDLL.@)
 *             ZwAreMappedFilesTheSame   (NTDLL.@)
 */
NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
{
2887 2888 2889 2890 2891
    struct file_view *view1, *view2;
    struct stat st1, st2;
    NTSTATUS status;
    sigset_t sigset;

2892 2893
    TRACE("%p %p\n", addr1, addr2);

2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904
    server_enter_uninterrupted_section( &csVirtual, &sigset );

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

    if (!view1 || !view2)
        status = STATUS_INVALID_ADDRESS;
    else if ((view1->protect & VPROT_VALLOC) || (view2->protect & VPROT_VALLOC))
        status = STATUS_CONFLICTING_ADDRESSES;
    else if (view1 == view2)
        status = STATUS_SUCCESS;
2905 2906
    else if (!(view1->protect & VPROT_IMAGE) || !(view2->protect & VPROT_IMAGE))
        status = STATUS_NOT_SAME_DEVICE;
2907 2908 2909 2910 2911 2912 2913 2914
    else if (!stat_mapping_file( view1, &st1 ) && !stat_mapping_file( view2, &st2 ) &&
             st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
        status = STATUS_SUCCESS;
    else
        status = STATUS_NOT_SAME_DEVICE;

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