ntdll: Set SO_PASSCRED before connecting to eliminate a race condition in obtaining...
[wine] / dlls / ntdll / virtual.c
1 /*
2  * Win32 virtual memory functions
3  *
4  * Copyright 1997, 2002 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * 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 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <sys/types.h>
35 #ifdef HAVE_SYS_STAT_H
36 # include <sys/stat.h>
37 #endif
38 #ifdef HAVE_SYS_MMAN_H
39 # include <sys/mman.h>
40 #endif
41 #ifdef HAVE_VALGRIND_VALGRIND_H
42 # include <valgrind/valgrind.h>
43 #endif
44
45 #define NONAMELESSUNION
46 #define NONAMELESSSTRUCT
47 #include "ntstatus.h"
48 #define WIN32_NO_STATUS
49 #include "windef.h"
50 #include "winternl.h"
51 #include "wine/library.h"
52 #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 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
59 WINE_DECLARE_DEBUG_CHANNEL(module);
60
61 #ifndef MS_SYNC
62 #define MS_SYNC 0
63 #endif
64
65 #ifndef MAP_NORESERVE
66 #define MAP_NORESERVE 0
67 #endif
68
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 /* Conversion from VPROT_* to Win32 flags */
83 static const BYTE VIRTUAL_Win32Flags[16] =
84 {
85     PAGE_NOACCESS,              /* 0 */
86     PAGE_READONLY,              /* READ */
87     PAGE_READWRITE,             /* WRITE */
88     PAGE_READWRITE,             /* READ | WRITE */
89     PAGE_EXECUTE,               /* EXEC */
90     PAGE_EXECUTE_READ,          /* READ | EXEC */
91     PAGE_EXECUTE_READWRITE,     /* WRITE | EXEC */
92     PAGE_EXECUTE_READWRITE,     /* READ | WRITE | EXEC */
93     PAGE_WRITECOPY,             /* WRITECOPY */
94     PAGE_WRITECOPY,             /* READ | WRITECOPY */
95     PAGE_WRITECOPY,             /* WRITE | WRITECOPY */
96     PAGE_WRITECOPY,             /* READ | WRITE | WRITECOPY */
97     PAGE_EXECUTE_WRITECOPY,     /* EXEC | WRITECOPY */
98     PAGE_EXECUTE_WRITECOPY,     /* READ | EXEC | WRITECOPY */
99     PAGE_EXECUTE_WRITECOPY,     /* WRITE | EXEC | WRITECOPY */
100     PAGE_EXECUTE_WRITECOPY      /* READ | WRITE | EXEC | WRITECOPY */
101 };
102
103 static struct list views_list = LIST_INIT(views_list);
104
105 static RTL_CRITICAL_SECTION csVirtual;
106 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
107 {
108     0, 0, &csVirtual,
109     { &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 /* These are always the same on an i386, and it will be faster this way */
116 # define page_mask  0xfff
117 # define page_shift 12
118 # define page_size  0x1000
119 /* Note: these are Windows limits, you cannot change them. */
120 static void *address_space_limit = (void *)0xc0000000;  /* top of the total available address space */
121 static void *user_space_limit    = (void *)0x7fff0000;  /* top of the user address space */
122 static void *working_set_limit   = (void *)0x7fff0000;  /* top of the current working set */
123 static void *address_space_start = (void *)0x110000;    /* keep DOS area clear */
124 #elif defined(__x86_64__)
125 # define page_mask  0xfff
126 # define page_shift 12
127 # define page_size  0x1000
128 static void *address_space_limit = (void *)0x7fffffff0000;
129 static void *user_space_limit    = (void *)0x7fffffff0000;
130 static void *working_set_limit   = (void *)0x7fffffff0000;
131 static void *address_space_start = (void *)0x10000;
132 #else
133 static UINT page_shift;
134 static UINT_PTR page_size;
135 static UINT_PTR page_mask;
136 static void *address_space_limit;
137 static void *user_space_limit;
138 static void *working_set_limit;
139 static void *address_space_start = (void *)0x10000;
140 #endif  /* __i386__ */
141 static const int is_win64 = (sizeof(void *) > sizeof(int));
142
143 #define ROUND_ADDR(addr,mask) \
144    ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
145
146 #define ROUND_SIZE(addr,size) \
147    (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
148
149 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
150     do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
151
152 #define VIRTUAL_HEAP_SIZE (4*1024*1024)
153
154 static HANDLE virtual_heap;
155 static void *preload_reserve_start;
156 static void *preload_reserve_end;
157 static int use_locks;
158 static int force_exec_prot;  /* whether to force PROT_EXEC on all PROT_READ mmaps */
159
160
161 /***********************************************************************
162  *           VIRTUAL_GetProtStr
163  */
164 static const char *VIRTUAL_GetProtStr( BYTE prot )
165 {
166     static char buffer[6];
167     buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
168     buffer[1] = (prot & VPROT_GUARD) ? 'g' : ((prot & VPROT_WRITEWATCH) ? 'H' : '-');
169     buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
170     buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
171     buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
172     buffer[5] = 0;
173     return buffer;
174 }
175
176
177 /***********************************************************************
178  *           VIRTUAL_GetUnixProt
179  *
180  * Convert page protections to protection for mmap/mprotect.
181  */
182 static int VIRTUAL_GetUnixProt( BYTE vprot )
183 {
184     int prot = 0;
185     if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
186     {
187         if (vprot & VPROT_READ) prot |= PROT_READ;
188         if (vprot & VPROT_WRITE) prot |= PROT_WRITE | PROT_READ;
189         if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE | PROT_READ;
190         if (vprot & VPROT_EXEC) prot |= PROT_EXEC | PROT_READ;
191         if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
192     }
193     if (!prot) prot = PROT_NONE;
194     return prot;
195 }
196
197
198 /***********************************************************************
199  *           VIRTUAL_DumpView
200  */
201 static void VIRTUAL_DumpView( struct file_view *view )
202 {
203     UINT i, count;
204     char *addr = view->base;
205     BYTE prot = view->prot[0];
206
207     TRACE( "View: %p - %p", addr, addr + view->size - 1 );
208     if (view->protect & VPROT_SYSTEM)
209         TRACE( " (system)\n" );
210     else if (view->protect & VPROT_VALLOC)
211         TRACE( " (valloc)\n" );
212     else if (view->mapping)
213         TRACE( " %p\n", view->mapping );
214     else
215         TRACE( " (anonymous)\n");
216
217     for (count = i = 1; i < view->size >> page_shift; i++, count++)
218     {
219         if (view->prot[i] == prot) continue;
220         TRACE( "      %p - %p %s\n",
221                  addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
222         addr += (count << page_shift);
223         prot = view->prot[i];
224         count = 0;
225     }
226     if (count)
227         TRACE( "      %p - %p %s\n",
228                  addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
229 }
230
231
232 /***********************************************************************
233  *           VIRTUAL_Dump
234  */
235 #ifdef WINE_VM_DEBUG
236 static void VIRTUAL_Dump(void)
237 {
238     sigset_t sigset;
239     struct file_view *view;
240
241     TRACE( "Dump of all virtual memory views:\n" );
242     server_enter_uninterrupted_section( &csVirtual, &sigset );
243     LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
244     {
245         VIRTUAL_DumpView( view );
246     }
247     server_leave_uninterrupted_section( &csVirtual, &sigset );
248 }
249 #endif
250
251
252 /***********************************************************************
253  *           VIRTUAL_FindView
254  *
255  * Find the view containing a given address. The csVirtual section must be held by caller.
256  *
257  * PARAMS
258  *      addr  [I] Address
259  *
260  * RETURNS
261  *      View: Success
262  *      NULL: Failure
263  */
264 static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
265 {
266     struct file_view *view;
267
268     LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
269     {
270         if (view->base > addr) break;  /* no matching view */
271         if ((const char *)view->base + view->size <= (const char *)addr) continue;
272         if ((const char *)view->base + view->size < (const char *)addr + size) break;  /* size too large */
273         if ((const char *)addr + size < (const char *)addr) break; /* overflow */
274         return view;
275     }
276     return NULL;
277 }
278
279
280 /***********************************************************************
281  *           get_mask
282  */
283 static inline UINT_PTR get_mask( ULONG zero_bits )
284 {
285     if (!zero_bits) return 0xffff;  /* allocations are aligned to 64K by default */
286     if (zero_bits < page_shift) zero_bits = page_shift;
287     return (1 << zero_bits) - 1;
288 }
289
290
291 /***********************************************************************
292  *           find_view_range
293  *
294  * Find the first view overlapping at least part of the specified range.
295  * The csVirtual section must be held by caller.
296  */
297 static struct file_view *find_view_range( const void *addr, size_t size )
298 {
299     struct file_view *view;
300
301     LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
302     {
303         if ((const char *)view->base >= (const char *)addr + size) break;
304         if ((const char *)view->base + view->size > (const char *)addr) return view;
305     }
306     return NULL;
307 }
308
309
310 /***********************************************************************
311  *           find_free_area
312  *
313  * Find a free area between views inside the specified range.
314  * The csVirtual section must be held by caller.
315  */
316 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
317 {
318     struct list *ptr;
319     void *start;
320
321     if (top_down)
322     {
323         start = ROUND_ADDR( (char *)end - size, mask );
324         if (start >= end || start < base) return NULL;
325
326         for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
327         {
328             struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
329
330             if ((char *)view->base + view->size <= (char *)start) break;
331             if ((char *)view->base >= (char *)start + size) continue;
332             start = ROUND_ADDR( (char *)view->base - size, mask );
333             /* stop if remaining space is not large enough */
334             if (!start || start >= end || start < base) return NULL;
335         }
336     }
337     else
338     {
339         start = ROUND_ADDR( (char *)base + mask, mask );
340         if (start >= end || (char *)end - (char *)start < size) return NULL;
341
342         for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
343         {
344             struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
345
346             if ((char *)view->base >= (char *)start + size) break;
347             if ((char *)view->base + view->size <= (char *)start) continue;
348             start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
349             /* stop if remaining space is not large enough */
350             if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
351         }
352     }
353     return start;
354 }
355
356
357 /***********************************************************************
358  *           add_reserved_area
359  *
360  * Add a reserved area to the list maintained by libwine.
361  * The csVirtual section must be held by caller.
362  */
363 static void add_reserved_area( void *addr, size_t size )
364 {
365     TRACE( "adding %p-%p\n", addr, (char *)addr + size );
366
367     if (addr < user_space_limit)
368     {
369         /* unmap the part of the area that is below the limit */
370         assert( (char *)addr + size > (char *)user_space_limit );
371         munmap( addr, (char *)user_space_limit - (char *)addr );
372         size -= (char *)user_space_limit - (char *)addr;
373         addr = user_space_limit;
374     }
375     /* blow away existing mappings */
376     wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
377     wine_mmap_add_reserved_area( addr, size );
378 }
379
380
381 /***********************************************************************
382  *           remove_reserved_area
383  *
384  * Remove a reserved area from the list maintained by libwine.
385  * The csVirtual section must be held by caller.
386  */
387 static void remove_reserved_area( void *addr, size_t size )
388 {
389     struct file_view *view;
390
391     TRACE( "removing %p-%p\n", addr, (char *)addr + size );
392     wine_mmap_remove_reserved_area( addr, size, 0 );
393
394     /* unmap areas not covered by an existing view */
395     LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
396     {
397         if ((char *)view->base >= (char *)addr + size)
398         {
399             munmap( addr, size );
400             break;
401         }
402         if ((char *)view->base + view->size <= (char *)addr) continue;
403         if (view->base > addr) munmap( addr, (char *)view->base - (char *)addr );
404         if ((char *)view->base + view->size > (char *)addr + size) break;
405         size = (char *)addr + size - ((char *)view->base + view->size);
406         addr = (char *)view->base + view->size;
407     }
408 }
409
410
411 /***********************************************************************
412  *           is_beyond_limit
413  *
414  * Check if an address range goes beyond a given limit.
415  */
416 static inline int is_beyond_limit( const void *addr, size_t size, const void *limit )
417 {
418     return (addr >= limit || (const char *)addr + size > (const char *)limit);
419 }
420
421
422 /***********************************************************************
423  *           unmap_area
424  *
425  * Unmap an area, or simply replace it by an empty mapping if it is
426  * in a reserved area. The csVirtual section must be held by caller.
427  */
428 static inline void unmap_area( void *addr, size_t size )
429 {
430     if (wine_mmap_is_in_reserved_area( addr, size ))
431         wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
432     else if (is_beyond_limit( addr, size, user_space_limit ))
433         add_reserved_area( addr, size );
434     else
435         munmap( addr, size );
436 }
437
438
439 /***********************************************************************
440  *           delete_view
441  *
442  * Deletes a view. The csVirtual section must be held by caller.
443  */
444 static void delete_view( struct file_view *view ) /* [in] View */
445 {
446     if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
447     list_remove( &view->entry );
448     if (view->mapping) close_handle( view->mapping );
449     RtlFreeHeap( virtual_heap, 0, view );
450 }
451
452
453 /***********************************************************************
454  *           create_view
455  *
456  * Create a view. The csVirtual section must be held by caller.
457  */
458 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
459 {
460     struct file_view *view;
461     struct list *ptr;
462     int unix_prot = VIRTUAL_GetUnixProt( vprot );
463
464     assert( !((UINT_PTR)base & page_mask) );
465     assert( !(size & page_mask) );
466
467     /* Create the view structure */
468
469     if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
470     {
471         FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
472         return STATUS_NO_MEMORY;
473     }
474
475     view->base    = base;
476     view->size    = size;
477     view->mapping = 0;
478     view->map_protect = 0;
479     view->protect = vprot;
480     memset( view->prot, vprot, size >> page_shift );
481
482     /* Insert it in the linked list */
483
484     LIST_FOR_EACH( ptr, &views_list )
485     {
486         struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
487         if (next->base > base) break;
488     }
489     list_add_before( ptr, &view->entry );
490
491     /* Check for overlapping views. This can happen if the previous view
492      * was a system view that got unmapped behind our back. In that case
493      * we recover by simply deleting it. */
494
495     if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
496     {
497         struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
498         if ((char *)prev->base + prev->size > (char *)base)
499         {
500             TRACE( "overlapping prev view %p-%p for %p-%p\n",
501                    prev->base, (char *)prev->base + prev->size,
502                    base, (char *)base + view->size );
503             assert( prev->protect & VPROT_SYSTEM );
504             delete_view( prev );
505         }
506     }
507     if ((ptr = list_next( &views_list, &view->entry )) != NULL)
508     {
509         struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
510         if ((char *)base + view->size > (char *)next->base)
511         {
512             TRACE( "overlapping next view %p-%p for %p-%p\n",
513                    next->base, (char *)next->base + next->size,
514                    base, (char *)base + view->size );
515             assert( next->protect & VPROT_SYSTEM );
516             delete_view( next );
517         }
518     }
519
520     *view_ret = view;
521     VIRTUAL_DEBUG_DUMP_VIEW( view );
522
523     if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
524     {
525         TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
526         mprotect( base, size, unix_prot | PROT_EXEC );
527     }
528     return STATUS_SUCCESS;
529 }
530
531
532 /***********************************************************************
533  *           VIRTUAL_GetWin32Prot
534  *
535  * Convert page protections to Win32 flags.
536  */
537 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
538 {
539     DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
540     if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
541     if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
542     return ret;
543 }
544
545
546 /***********************************************************************
547  *           get_vprot_flags
548  *
549  * Build page protections from Win32 flags.
550  *
551  * PARAMS
552  *      protect [I] Win32 protection flags
553  *
554  * RETURNS
555  *      Value of page protection flags
556  */
557 static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot, BOOL image )
558 {
559     switch(protect & 0xff)
560     {
561     case PAGE_READONLY:
562         *vprot = VPROT_READ;
563         break;
564     case PAGE_READWRITE:
565         if (image)
566             *vprot = VPROT_READ | VPROT_WRITECOPY;
567         else
568             *vprot = VPROT_READ | VPROT_WRITE;
569         break;
570     case PAGE_WRITECOPY:
571         *vprot = VPROT_READ | VPROT_WRITECOPY;
572         break;
573     case PAGE_EXECUTE:
574         *vprot = VPROT_EXEC;
575         break;
576     case PAGE_EXECUTE_READ:
577         *vprot = VPROT_EXEC | VPROT_READ;
578         break;
579     case PAGE_EXECUTE_READWRITE:
580         if (image)
581             *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
582         else
583             *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
584         break;
585     case PAGE_EXECUTE_WRITECOPY:
586         *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
587         break;
588     case PAGE_NOACCESS:
589         *vprot = 0;
590         break;
591     default:
592         return STATUS_INVALID_PAGE_PROTECTION;
593     }
594     if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
595     if (protect & PAGE_NOCACHE) *vprot |= VPROT_NOCACHE;
596     return STATUS_SUCCESS;
597 }
598
599
600 /***********************************************************************
601  *           VIRTUAL_SetProt
602  *
603  * Change the protection of a range of pages.
604  *
605  * RETURNS
606  *      TRUE: Success
607  *      FALSE: Failure
608  */
609 static BOOL VIRTUAL_SetProt( struct file_view *view, /* [in] Pointer to view */
610                              void *base,      /* [in] Starting address */
611                              size_t size,     /* [in] Size in bytes */
612                              BYTE vprot )     /* [in] Protections to use */
613 {
614     int unix_prot = VIRTUAL_GetUnixProt(vprot);
615     BYTE *p = view->prot + (((char *)base - (char *)view->base) >> page_shift);
616
617     TRACE("%p-%p %s\n",
618           base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
619
620     if (view->protect & VPROT_WRITEWATCH)
621     {
622         /* each page may need different protections depending on write watch flag */
623         UINT i, count;
624         char *addr = base;
625         int prot;
626
627         p[0] = vprot | (p[0] & VPROT_WRITEWATCH);
628         unix_prot = VIRTUAL_GetUnixProt( p[0] );
629         for (count = i = 1; i < size >> page_shift; i++, count++)
630         {
631             p[i] = vprot | (p[i] & VPROT_WRITEWATCH);
632             prot = VIRTUAL_GetUnixProt( p[i] );
633             if (prot == unix_prot) continue;
634             mprotect( addr, count << page_shift, unix_prot );
635             addr += count << page_shift;
636             unix_prot = prot;
637             count = 0;
638         }
639         if (count) mprotect( addr, count << page_shift, unix_prot );
640         VIRTUAL_DEBUG_DUMP_VIEW( view );
641         return TRUE;
642     }
643
644     /* if setting stack guard pages, store the permissions first, as the guard may be
645      * triggered at any point after mprotect and change the permissions again */
646     if ((vprot & VPROT_GUARD) &&
647         (base >= NtCurrentTeb()->DeallocationStack) &&
648         (base < NtCurrentTeb()->Tib.StackBase))
649     {
650         memset( p, vprot, size >> page_shift );
651         mprotect( base, size, unix_prot );
652         VIRTUAL_DEBUG_DUMP_VIEW( view );
653         return TRUE;
654     }
655
656     if (force_exec_prot && !(view->protect & VPROT_NOEXEC) &&
657         (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
658     {
659         TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
660         if (!mprotect( base, size, unix_prot | PROT_EXEC )) goto done;
661         /* exec + write may legitimately fail, in that case fall back to write only */
662         if (!(unix_prot & PROT_WRITE)) return FALSE;
663     }
664
665     if (mprotect( base, size, unix_prot )) return FALSE;  /* FIXME: last error */
666
667 done:
668     memset( p, vprot, size >> page_shift );
669     VIRTUAL_DEBUG_DUMP_VIEW( view );
670     return TRUE;
671 }
672
673
674 /***********************************************************************
675  *           reset_write_watches
676  *
677  * Reset write watches in a memory range.
678  */
679 static void reset_write_watches( struct file_view *view, void *base, SIZE_T size )
680 {
681     SIZE_T i, count;
682     int prot, unix_prot;
683     char *addr = base;
684     BYTE *p = view->prot + ((addr - (char *)view->base) >> page_shift);
685
686     p[0] |= VPROT_WRITEWATCH;
687     unix_prot = VIRTUAL_GetUnixProt( p[0] );
688     for (count = i = 1; i < size >> page_shift; i++, count++)
689     {
690         p[i] |= VPROT_WRITEWATCH;
691         prot = VIRTUAL_GetUnixProt( p[i] );
692         if (prot == unix_prot) continue;
693         mprotect( addr, count << page_shift, unix_prot );
694         addr += count << page_shift;
695         unix_prot = prot;
696         count = 0;
697     }
698     if (count) mprotect( addr, count << page_shift, unix_prot );
699 }
700
701
702 /***********************************************************************
703  *           unmap_extra_space
704  *
705  * Release the extra memory while keeping the range starting on the granularity boundary.
706  */
707 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
708 {
709     if ((ULONG_PTR)ptr & mask)
710     {
711         size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
712         munmap( ptr, extra );
713         ptr = (char *)ptr + extra;
714         total_size -= extra;
715     }
716     if (total_size > wanted_size)
717         munmap( (char *)ptr + wanted_size, total_size - wanted_size );
718     return ptr;
719 }
720
721
722 struct alloc_area
723 {
724     size_t size;
725     size_t mask;
726     int    top_down;
727     void  *limit;
728     void  *result;
729 };
730
731 /***********************************************************************
732  *           alloc_reserved_area_callback
733  *
734  * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
735  */
736 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
737 {
738     struct alloc_area *alloc = arg;
739     void *end = (char *)start + size;
740
741     if (start < address_space_start) start = address_space_start;
742     if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
743     if (start >= end) return 0;
744
745     /* make sure we don't touch the preloader reserved range */
746     if (preload_reserve_end >= start)
747     {
748         if (preload_reserve_end >= end)
749         {
750             if (preload_reserve_start <= start) return 0;  /* no space in that area */
751             if (preload_reserve_start < end) end = preload_reserve_start;
752         }
753         else if (preload_reserve_start <= start) start = preload_reserve_end;
754         else
755         {
756             /* range is split in two by the preloader reservation, try first part */
757             if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
758                                                  alloc->mask, alloc->top_down )))
759                 return 1;
760             /* then fall through to try second part */
761             start = preload_reserve_end;
762         }
763     }
764     if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
765         return 1;
766
767     return 0;
768 }
769
770
771 /***********************************************************************
772  *           map_view
773  *
774  * Create a view and mmap the corresponding memory area.
775  * The csVirtual section must be held by caller.
776  */
777 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
778                           int top_down, unsigned int vprot )
779 {
780     void *ptr;
781     NTSTATUS status;
782
783     if (base)
784     {
785         if (is_beyond_limit( base, size, address_space_limit ))
786             return STATUS_WORKING_SET_LIMIT_RANGE;
787
788         switch (wine_mmap_is_in_reserved_area( base, size ))
789         {
790         case -1: /* partially in a reserved area */
791             return STATUS_CONFLICTING_ADDRESSES;
792
793         case 0:  /* not in a reserved area, do a normal allocation */
794             if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
795             {
796                 if (errno == ENOMEM) return STATUS_NO_MEMORY;
797                 return STATUS_INVALID_PARAMETER;
798             }
799             if (ptr != base)
800             {
801                 /* We couldn't get the address we wanted */
802                 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
803                 else munmap( ptr, size );
804                 return STATUS_CONFLICTING_ADDRESSES;
805             }
806             break;
807
808         default:
809         case 1:  /* in a reserved area, make sure the address is available */
810             if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
811             /* replace the reserved area by our mapping */
812             if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
813                 return STATUS_INVALID_PARAMETER;
814             break;
815         }
816         if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
817     }
818     else
819     {
820         size_t view_size = size + mask + 1;
821         struct alloc_area alloc;
822
823         alloc.size = size;
824         alloc.mask = mask;
825         alloc.top_down = top_down;
826         alloc.limit = user_space_limit;
827         if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
828         {
829             ptr = alloc.result;
830             TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
831             if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
832                 return STATUS_INVALID_PARAMETER;
833             goto done;
834         }
835
836         for (;;)
837         {
838             if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
839             {
840                 if (errno == ENOMEM) return STATUS_NO_MEMORY;
841                 return STATUS_INVALID_PARAMETER;
842             }
843             TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
844             /* if we got something beyond the user limit, unmap it and retry */
845             if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
846             else break;
847         }
848         ptr = unmap_extra_space( ptr, view_size, size, mask );
849     }
850 done:
851     status = create_view( view_ret, ptr, size, vprot );
852     if (status != STATUS_SUCCESS) unmap_area( ptr, size );
853     return status;
854 }
855
856
857 /***********************************************************************
858  *           map_file_into_view
859  *
860  * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
861  * The csVirtual section must be held by caller.
862  */
863 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
864                                     off_t offset, unsigned int vprot, BOOL removable )
865 {
866     void *ptr;
867     int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
868     BOOL shared_write = (vprot & VPROT_WRITE) != 0;
869
870     assert( start < view->size );
871     assert( start + size <= view->size );
872
873     if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (vprot & VPROT_READ))
874     {
875         TRACE( "forcing exec permission on mapping %p-%p\n",
876                (char *)view->base + start, (char *)view->base + start + size - 1 );
877         prot |= PROT_EXEC;
878     }
879
880     /* only try mmap if media is not removable (or if we require write access) */
881     if (!removable || shared_write)
882     {
883         int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
884
885         if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
886             goto done;
887
888         if ((errno == EPERM) && (prot & PROT_EXEC))
889             ERR( "failed to set %08x protection on file map, noexec filesystem?\n", prot );
890
891         /* mmap() failed; if this is because the file offset is not    */
892         /* page-aligned (EINVAL), or because the underlying filesystem */
893         /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
894         if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
895         if (shared_write)  /* we cannot fake shared write mappings */
896         {
897             if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
898             ERR( "shared writable mmap not supported, broken filesystem?\n" );
899             return STATUS_NOT_SUPPORTED;
900         }
901     }
902
903     /* Reserve the memory with an anonymous mmap */
904     ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
905     if (ptr == (void *)-1) return FILE_GetNtStatus();
906     /* Now read in the file */
907     pread( fd, ptr, size, offset );
908     if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot );  /* Set the right protection */
909 done:
910     memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
911     return STATUS_SUCCESS;
912 }
913
914
915 /***********************************************************************
916  *           get_committed_size
917  *
918  * Get the size of the committed range starting at base.
919  * Also return the protections for the first page.
920  */
921 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
922 {
923     SIZE_T i, start;
924
925     start = ((char *)base - (char *)view->base) >> page_shift;
926     *vprot = view->prot[start];
927
928     if (view->mapping && !(view->protect & VPROT_COMMITTED))
929     {
930         SIZE_T ret = 0;
931         SERVER_START_REQ( get_mapping_committed_range )
932         {
933             req->handle = wine_server_obj_handle( view->mapping );
934             req->offset = start << page_shift;
935             if (!wine_server_call( req ))
936             {
937                 ret = reply->size;
938                 if (reply->committed)
939                 {
940                     *vprot |= VPROT_COMMITTED;
941                     for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
942                 }
943             }
944         }
945         SERVER_END_REQ;
946         return ret;
947     }
948     for (i = start + 1; i < view->size >> page_shift; i++)
949         if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
950     return (i - start) << page_shift;
951 }
952
953
954 /***********************************************************************
955  *           decommit_view
956  *
957  * Decommit some pages of a given view.
958  * The csVirtual section must be held by caller.
959  */
960 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
961 {
962     if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
963     {
964         BYTE *p = view->prot + (start >> page_shift);
965         size >>= page_shift;
966         while (size--) *p++ &= ~VPROT_COMMITTED;
967         return STATUS_SUCCESS;
968     }
969     return FILE_GetNtStatus();
970 }
971
972
973 /***********************************************************************
974  *           allocate_dos_memory
975  *
976  * Allocate the DOS memory range.
977  */
978 static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
979 {
980     size_t size;
981     void *addr = NULL;
982     void * const low_64k = (void *)0x10000;
983     const size_t dosmem_size = 0x110000;
984     int unix_prot = VIRTUAL_GetUnixProt( vprot );
985     struct list *ptr;
986
987     /* check for existing view */
988
989     if ((ptr = list_head( &views_list )))
990     {
991         struct file_view *first_view = LIST_ENTRY( ptr, struct file_view, entry );
992         if (first_view->base < (void *)dosmem_size) return STATUS_CONFLICTING_ADDRESSES;
993     }
994
995     /* check without the first 64K */
996
997     if (wine_mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
998     {
999         addr = wine_anon_mmap( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
1000         if (addr != low_64k)
1001         {
1002             if (addr != (void *)-1) munmap( addr, dosmem_size - 0x10000 );
1003             return map_view( view, NULL, dosmem_size, 0xffff, 0, vprot );
1004         }
1005     }
1006
1007     /* now try to allocate the low 64K too */
1008
1009     if (wine_mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
1010     {
1011         addr = wine_anon_mmap( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
1012         if (addr == (void *)page_size)
1013         {
1014             if (!wine_anon_mmap( NULL, page_size, unix_prot, MAP_FIXED ))
1015             {
1016                 addr = NULL;
1017                 TRACE( "successfully mapped low 64K range\n" );
1018             }
1019             else TRACE( "failed to map page 0\n" );
1020         }
1021         else
1022         {
1023             if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
1024             addr = low_64k;
1025             TRACE( "failed to map low 64K range\n" );
1026         }
1027     }
1028
1029     /* now reserve the whole range */
1030
1031     size = (char *)dosmem_size - (char *)addr;
1032     wine_anon_mmap( addr, size, unix_prot, MAP_FIXED );
1033     return create_view( view, addr, size, vprot );
1034 }
1035
1036
1037 /***********************************************************************
1038  *           check_architecture
1039  *
1040  * Check the architecture of a PE binary.
1041  */
1042 static NTSTATUS check_architecture( const IMAGE_NT_HEADERS *nt )
1043 {
1044     static const char *arch;
1045
1046 #ifdef __i386__
1047     if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_I386) return STATUS_SUCCESS;
1048     if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64)
1049     {
1050         if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)  /* don't warn for a 64-bit exe */
1051             WARN( "loading amd64 dll in 32-bit mode will fail\n" );
1052         return STATUS_INVALID_IMAGE_FORMAT;
1053     }
1054 #elif defined(__x86_64__)
1055     if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64) return STATUS_SUCCESS;
1056     if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_I386)
1057     {
1058         if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)  /* don't warn for a 32-bit exe */
1059             WARN( "loading 32-bit dll in 64-bit mode will fail\n" );
1060         return STATUS_INVALID_IMAGE_FORMAT;
1061     }
1062 #elif defined(__arm__) && !defined(__ARMEB__)
1063     if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_ARM ||
1064         nt->FileHeader.Machine == IMAGE_FILE_MACHINE_THUMB)
1065         return STATUS_SUCCESS;
1066     if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_ARMNT)
1067     {
1068         SYSTEM_CPU_INFORMATION sci;
1069         if (SUCCEEDED(NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL )) &&
1070             sci.Architecture == PROCESSOR_ARCHITECTURE_ARM && sci.Level >= 7)
1071             return STATUS_SUCCESS;
1072     }
1073 #endif
1074
1075     switch (nt->FileHeader.Machine)
1076     {
1077         case IMAGE_FILE_MACHINE_UNKNOWN: arch = "Unknown"; break;
1078         case IMAGE_FILE_MACHINE_I860:    arch = "I860"; break;
1079         case IMAGE_FILE_MACHINE_I386:    arch = "I386"; break;
1080         case IMAGE_FILE_MACHINE_R3000:   arch = "R3000"; break;
1081         case IMAGE_FILE_MACHINE_R4000:   arch = "R4000"; break;
1082         case IMAGE_FILE_MACHINE_R10000:  arch = "R10000"; break;
1083         case IMAGE_FILE_MACHINE_ALPHA:   arch = "Alpha"; break;
1084         case IMAGE_FILE_MACHINE_POWERPC: arch = "PowerPC"; break;
1085         case IMAGE_FILE_MACHINE_IA64:    arch = "IA-64"; break;
1086         case IMAGE_FILE_MACHINE_ALPHA64: arch = "Alpha-64"; break;
1087         case IMAGE_FILE_MACHINE_AMD64:   arch = "AMD-64"; break;
1088         case IMAGE_FILE_MACHINE_ARM:     arch = "ARM"; break;
1089         case IMAGE_FILE_MACHINE_ARMNT:   arch = "ARMNT"; break;
1090         case IMAGE_FILE_MACHINE_THUMB:   arch = "ARM Thumb"; break;
1091         case IMAGE_FILE_MACHINE_SPARC:   arch = "SPARC"; break;
1092         default: arch = wine_dbg_sprintf( "Unknown-%04x", nt->FileHeader.Machine ); break;
1093     }
1094     ERR( "Trying to load PE image for unsupported architecture %s\n", arch );
1095     return STATUS_INVALID_IMAGE_FORMAT;
1096 }
1097
1098
1099 /***********************************************************************
1100  *           stat_mapping_file
1101  *
1102  * Stat the underlying file for a memory view.
1103  */
1104 static NTSTATUS stat_mapping_file( struct file_view *view, struct stat *st )
1105 {
1106     NTSTATUS status;
1107     int unix_fd, needs_close;
1108
1109     if (!view->mapping) return STATUS_NOT_MAPPED_VIEW;
1110     if (!(status = server_get_unix_fd( view->mapping, 0, &unix_fd, &needs_close, NULL, NULL )))
1111     {
1112         if (fstat( unix_fd, st ) == -1) status = FILE_GetNtStatus();
1113         if (needs_close) close( unix_fd );
1114     }
1115     return status;
1116 }
1117
1118
1119 /***********************************************************************
1120  *           map_image
1121  *
1122  * Map an executable (PE format) image into memory.
1123  */
1124 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
1125                            SIZE_T header_size, int shared_fd, HANDLE dup_mapping, unsigned int map_vprot, PVOID *addr_ptr )
1126 {
1127     IMAGE_DOS_HEADER *dos;
1128     IMAGE_NT_HEADERS *nt;
1129     IMAGE_SECTION_HEADER sections[96];
1130     IMAGE_SECTION_HEADER *sec;
1131     IMAGE_DATA_DIRECTORY *imports;
1132     NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
1133     int i;
1134     off_t pos;
1135     sigset_t sigset;
1136     struct stat st;
1137     struct file_view *view = NULL;
1138     char *ptr, *header_end, *header_start;
1139     INT_PTR delta = 0;
1140
1141     /* zero-map the whole range */
1142
1143     server_enter_uninterrupted_section( &csVirtual, &sigset );
1144
1145     if (base >= (char *)address_space_start)  /* make sure the DOS area remains free */
1146         status = map_view( &view, base, total_size, mask, FALSE,
1147                            VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1148
1149     if (status != STATUS_SUCCESS)
1150         status = map_view( &view, NULL, total_size, mask, FALSE,
1151                            VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1152
1153     if (status != STATUS_SUCCESS) goto error;
1154
1155     ptr = view->base;
1156     TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
1157
1158     /* map the header */
1159
1160     if (fstat( fd, &st ) == -1)
1161     {
1162         status = FILE_GetNtStatus();
1163         goto error;
1164     }
1165     status = STATUS_INVALID_IMAGE_FORMAT;  /* generic error */
1166     if (!st.st_size) goto error;
1167     header_size = min( header_size, st.st_size );
1168     if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1169                             !dup_mapping ) != STATUS_SUCCESS) goto error;
1170     dos = (IMAGE_DOS_HEADER *)ptr;
1171     nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1172     header_end = ptr + ROUND_SIZE( 0, header_size );
1173     memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1174     if ((char *)(nt + 1) > header_end) goto error;
1175     header_start = (char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader;
1176     if (nt->FileHeader.NumberOfSections > sizeof(sections)/sizeof(*sections)) goto error;
1177     if (header_start + sizeof(*sections) * nt->FileHeader.NumberOfSections > header_end) goto error;
1178     /* Some applications (e.g. the Steam version of Borderlands) map over the top of the section headers,
1179      * copying the headers into local memory is necessary to properly load such applications. */
1180     memcpy(sections, header_start, sizeof(*sections) * nt->FileHeader.NumberOfSections);
1181     sec = sections;
1182
1183     imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
1184     if (!imports->Size || !imports->VirtualAddress) imports = NULL;
1185
1186     if (check_architecture( nt )) goto error;
1187
1188     /* check for non page-aligned binary */
1189
1190     if (nt->OptionalHeader.SectionAlignment <= page_mask)
1191     {
1192         /* unaligned sections, this happens for native subsystem binaries */
1193         /* in that case Windows simply maps in the whole file */
1194
1195         if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
1196                                 !dup_mapping ) != STATUS_SUCCESS) goto error;
1197
1198         /* check that all sections are loaded at the right offset */
1199         if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1200         for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1201         {
1202             if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1203                 goto error;  /* Windows refuses to load in that case too */
1204         }
1205
1206         /* set the image protections */
1207         VIRTUAL_SetProt( view, ptr, total_size,
1208                          VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1209
1210         /* no relocations are performed on non page-aligned binaries */
1211         goto done;
1212     }
1213
1214
1215     /* map all the sections */
1216
1217     for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1218     {
1219         static const SIZE_T sector_align = 0x1ff;
1220         SIZE_T map_size, file_start, file_size, end;
1221
1222         if (!sec->Misc.VirtualSize)
1223             map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1224         else
1225             map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1226
1227         /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1228         file_start = sec->PointerToRawData & ~sector_align;
1229         file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1230         if (file_size > map_size) file_size = map_size;
1231
1232         /* a few sanity checks */
1233         end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1234         if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1235         {
1236             WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1237                            sec->Name, sec->VirtualAddress, map_size, total_size );
1238             goto error;
1239         }
1240
1241         if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1242             (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1243         {
1244             TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1245                             sec->Name, ptr + sec->VirtualAddress,
1246                             sec->PointerToRawData, (int)pos, file_size, map_size,
1247                             sec->Characteristics );
1248             if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1249                                     VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1250                                     FALSE ) != STATUS_SUCCESS)
1251             {
1252                 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1253                 goto error;
1254             }
1255
1256             /* check if the import directory falls inside this section */
1257             if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1258                 imports->VirtualAddress < sec->VirtualAddress + map_size)
1259             {
1260                 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1261                 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1262                 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1263                 if (end > base)
1264                     map_file_into_view( view, shared_fd, base, end - base,
1265                                         pos + (base - sec->VirtualAddress),
1266                                         VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1267                                         FALSE );
1268             }
1269             pos += map_size;
1270             continue;
1271         }
1272
1273         TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1274                         sec->Name, ptr + sec->VirtualAddress,
1275                         sec->PointerToRawData, sec->SizeOfRawData,
1276                         sec->Misc.VirtualSize, sec->Characteristics );
1277
1278         if (!sec->PointerToRawData || !file_size) continue;
1279
1280         /* Note: if the section is not aligned properly map_file_into_view will magically
1281          *       fall back to read(), so we don't need to check anything here.
1282          */
1283         end = file_start + file_size;
1284         if (sec->PointerToRawData >= st.st_size ||
1285             end > ((st.st_size + sector_align) & ~sector_align) ||
1286             end < file_start ||
1287             map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1288                                 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1289                                 !dup_mapping ) != STATUS_SUCCESS)
1290         {
1291             ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1292             goto error;
1293         }
1294
1295         if (file_size & page_mask)
1296         {
1297             end = ROUND_SIZE( 0, file_size );
1298             if (end > map_size) end = map_size;
1299             TRACE_(module)("clearing %p - %p\n",
1300                            ptr + sec->VirtualAddress + file_size,
1301                            ptr + sec->VirtualAddress + end );
1302             memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1303         }
1304     }
1305
1306
1307     /* perform base relocation, if necessary */
1308
1309     if (ptr != base &&
1310         ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1311           !NtCurrentTeb()->Peb->ImageBaseAddress) )
1312     {
1313         IMAGE_BASE_RELOCATION *rel, *end;
1314         const IMAGE_DATA_DIRECTORY *relocs;
1315
1316         if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1317         {
1318             WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1319                            base, ptr );
1320             status = STATUS_CONFLICTING_ADDRESSES;
1321             goto error;
1322         }
1323
1324         TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1325                         base, base + total_size, ptr, ptr + total_size );
1326
1327         relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1328         rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1329         end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1330         delta = ptr - base;
1331
1332         while (rel < end - 1 && rel->SizeOfBlock)
1333         {
1334             if (rel->VirtualAddress >= total_size)
1335             {
1336                 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1337                 status = STATUS_ACCESS_VIOLATION;
1338                 goto error;
1339             }
1340             rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1341                                              (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1342                                              (USHORT *)(rel + 1), delta );
1343             if (!rel) goto error;
1344         }
1345     }
1346
1347     /* set the image protections */
1348
1349     VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1350
1351     sec = sections;
1352     for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1353     {
1354         SIZE_T size;
1355         BYTE vprot = VPROT_COMMITTED;
1356
1357         if (sec->Misc.VirtualSize)
1358             size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1359         else
1360             size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1361
1362         if (sec->Characteristics & IMAGE_SCN_MEM_READ)    vprot |= VPROT_READ;
1363         if (sec->Characteristics & IMAGE_SCN_MEM_WRITE)   vprot |= VPROT_WRITECOPY;
1364         if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1365
1366         /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1367         if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1368             (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1369             vprot |= VPROT_EXEC;
1370
1371         if (!VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot ) && (vprot & VPROT_EXEC))
1372             ERR( "failed to set %08x protection on section %.8s, noexec filesystem?\n",
1373                  sec->Characteristics, sec->Name );
1374     }
1375
1376  done:
1377     view->mapping = dup_mapping;
1378     view->map_protect = map_vprot;
1379     server_leave_uninterrupted_section( &csVirtual, &sigset );
1380
1381     *addr_ptr = ptr;
1382 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1383     VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1384 #endif
1385     if (ptr != base) return STATUS_IMAGE_NOT_AT_BASE;
1386     return STATUS_SUCCESS;
1387
1388  error:
1389     if (view) delete_view( view );
1390     server_leave_uninterrupted_section( &csVirtual, &sigset );
1391     if (dup_mapping) NtClose( dup_mapping );
1392     return status;
1393 }
1394
1395
1396 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1397 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1398 {
1399     void **heap_base = arg;
1400
1401     if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1402     if (size < VIRTUAL_HEAP_SIZE) return 0;
1403     if (is_win64 && base < (void *)0x80000000) return 0;
1404     *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1405                                  VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1406     return (*heap_base != (void *)-1);
1407 }
1408
1409 /***********************************************************************
1410  *           virtual_init
1411  */
1412 void virtual_init(void)
1413 {
1414     const char *preload;
1415     void *heap_base;
1416     size_t size;
1417     struct file_view *heap_view;
1418
1419 #ifndef page_mask
1420     page_size = getpagesize();
1421     page_mask = page_size - 1;
1422     /* Make sure we have a power of 2 */
1423     assert( !(page_size & page_mask) );
1424     page_shift = 0;
1425     while ((1 << page_shift) != page_size) page_shift++;
1426     user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1427 #endif  /* page_mask */
1428     if ((preload = getenv("WINEPRELOADRESERVE")))
1429     {
1430         unsigned long start, end;
1431         if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1432         {
1433             preload_reserve_start = (void *)start;
1434             preload_reserve_end = (void *)end;
1435         }
1436     }
1437
1438     /* try to find space in a reserved area for the virtual heap */
1439     if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1440         heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1441
1442     assert( heap_base != (void *)-1 );
1443     virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1444                                   VIRTUAL_HEAP_SIZE, NULL, NULL );
1445     create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1446
1447     /* make the DOS area accessible (except the low 64K) to hide bugs in broken apps like Excel 2003 */
1448     size = (char *)address_space_start - (char *)0x10000;
1449     if (size && wine_mmap_is_in_reserved_area( (void*)0x10000, size ) == 1)
1450         wine_anon_mmap( (void *)0x10000, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1451 }
1452
1453
1454 /***********************************************************************
1455  *           virtual_init_threading
1456  */
1457 void virtual_init_threading(void)
1458 {
1459     use_locks = 1;
1460 }
1461
1462
1463 /***********************************************************************
1464  *           virtual_get_system_info
1465  */
1466 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1467 {
1468     info->unknown                 = 0;
1469     info->KeMaximumIncrement      = 0;  /* FIXME */
1470     info->PageSize                = page_size;
1471     info->MmLowestPhysicalPage    = 1;
1472     info->MmHighestPhysicalPage   = 0x7fffffff / page_size;
1473     info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
1474     info->AllocationGranularity   = get_mask(0) + 1;
1475     info->LowestUserAddress       = (void *)0x10000;
1476     info->HighestUserAddress      = (char *)user_space_limit - 1;
1477     info->ActiveProcessorsAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1478     info->NumberOfProcessors      = NtCurrentTeb()->Peb->NumberOfProcessors;
1479 }
1480
1481
1482 /***********************************************************************
1483  *           virtual_create_builtin_view
1484  */
1485 NTSTATUS virtual_create_builtin_view( void *module )
1486 {
1487     NTSTATUS status;
1488     sigset_t sigset;
1489     IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1490     SIZE_T size = nt->OptionalHeader.SizeOfImage;
1491     IMAGE_SECTION_HEADER *sec;
1492     struct file_view *view;
1493     void *base;
1494     int i;
1495
1496     size = ROUND_SIZE( module, size );
1497     base = ROUND_ADDR( module, page_mask );
1498     server_enter_uninterrupted_section( &csVirtual, &sigset );
1499     status = create_view( &view, base, size, VPROT_SYSTEM | VPROT_IMAGE |
1500                           VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1501     if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
1502     server_leave_uninterrupted_section( &csVirtual, &sigset );
1503
1504     if (status) return status;
1505
1506     /* The PE header is always read-only, no write, no execute. */
1507     view->prot[0] = VPROT_COMMITTED | VPROT_READ;
1508
1509     sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
1510     for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1511     {
1512         BYTE flags = VPROT_COMMITTED;
1513
1514         if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
1515         if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
1516         if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
1517         memset (view->prot + (sec[i].VirtualAddress >> page_shift), flags,
1518                 ROUND_SIZE( sec[i].VirtualAddress, sec[i].Misc.VirtualSize ) >> page_shift );
1519     }
1520
1521     return status;
1522 }
1523
1524
1525 /***********************************************************************
1526  *           virtual_alloc_thread_stack
1527  */
1528 NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1529 {
1530     struct file_view *view;
1531     NTSTATUS status;
1532     sigset_t sigset;
1533     SIZE_T size;
1534
1535     if (!reserve_size || !commit_size)
1536     {
1537         IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1538         if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
1539         if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1540     }
1541
1542     size = max( reserve_size, commit_size );
1543     if (size < 1024 * 1024) size = 1024 * 1024;  /* Xlib needs a large stack */
1544     size = (size + 0xffff) & ~0xffff;  /* round to 64K boundary */
1545
1546     server_enter_uninterrupted_section( &csVirtual, &sigset );
1547
1548     if ((status = map_view( &view, NULL, size, 0xffff, 0,
1549                             VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1550         goto done;
1551
1552 #ifdef VALGRIND_STACK_REGISTER
1553     VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1554 #endif
1555
1556     /* setup no access guard page */
1557     VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1558     VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1559                      VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1560
1561     /* note: limit is lower than base since the stack grows down */
1562     teb->DeallocationStack = view->base;
1563     teb->Tib.StackBase     = (char *)view->base + view->size;
1564     teb->Tib.StackLimit    = (char *)view->base + 2 * page_size;
1565 done:
1566     server_leave_uninterrupted_section( &csVirtual, &sigset );
1567     return status;
1568 }
1569
1570
1571 /***********************************************************************
1572  *           virtual_clear_thread_stack
1573  *
1574  * Clear the stack contents before calling the main entry point, some broken apps need that.
1575  */
1576 void virtual_clear_thread_stack(void)
1577 {
1578     void *stack = NtCurrentTeb()->Tib.StackLimit;
1579     size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1580
1581     wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1582     if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1583 }
1584
1585
1586 /***********************************************************************
1587  *           virtual_handle_fault
1588  */
1589 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err )
1590 {
1591     struct file_view *view;
1592     NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1593     sigset_t sigset;
1594
1595     server_enter_uninterrupted_section( &csVirtual, &sigset );
1596     if ((view = VIRTUAL_FindView( addr, 0 )))
1597     {
1598         void *page = ROUND_ADDR( addr, page_mask );
1599         BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1600         if (*vprot & VPROT_GUARD)
1601         {
1602             VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1603             ret = STATUS_GUARD_PAGE_VIOLATION;
1604         }
1605         if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1606         {
1607             if (*vprot & VPROT_WRITEWATCH)
1608             {
1609                 *vprot &= ~VPROT_WRITEWATCH;
1610                 VIRTUAL_SetProt( view, page, page_size, *vprot );
1611             }
1612             /* ignore fault if page is writable now */
1613             if (VIRTUAL_GetUnixProt( *vprot ) & PROT_WRITE) ret = STATUS_SUCCESS;
1614         }
1615     }
1616     server_leave_uninterrupted_section( &csVirtual, &sigset );
1617     return ret;
1618 }
1619
1620
1621
1622 /***********************************************************************
1623  *           virtual_handle_stack_fault
1624  *
1625  * Handle an access fault inside the current thread stack.
1626  * Called from inside a signal handler.
1627  */
1628 BOOL virtual_handle_stack_fault( void *addr )
1629 {
1630     struct file_view *view;
1631     BOOL ret = FALSE;
1632
1633     RtlEnterCriticalSection( &csVirtual );  /* no need for signal masking inside signal handler */
1634     if ((view = VIRTUAL_FindView( addr, 0 )))
1635     {
1636         void *page = ROUND_ADDR( addr, page_mask );
1637         BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1638         if (vprot & VPROT_GUARD)
1639         {
1640             VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1641             NtCurrentTeb()->Tib.StackLimit = page;
1642             if ((char *)page >= (char *)NtCurrentTeb()->DeallocationStack + 2*page_size)
1643             {
1644                 vprot = view->prot[((char *)page - page_size - (char *)view->base) >> page_shift];
1645                 VIRTUAL_SetProt( view, (char *)page - page_size, page_size, vprot | VPROT_GUARD );
1646             }
1647             ret = TRUE;
1648         }
1649     }
1650     RtlLeaveCriticalSection( &csVirtual );
1651     return ret;
1652 }
1653
1654
1655 /***********************************************************************
1656  *           virtual_check_buffer_for_read
1657  *
1658  * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
1659  */
1660 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
1661 {
1662     if (!size) return TRUE;
1663     if (!ptr) return FALSE;
1664
1665     __TRY
1666     {
1667         volatile const char *p = ptr;
1668         char dummy __attribute__((unused));
1669         SIZE_T count = size;
1670
1671         while (count > page_size)
1672         {
1673             dummy = *p;
1674             p += page_size;
1675             count -= page_size;
1676         }
1677         dummy = p[0];
1678         dummy = p[count - 1];
1679     }
1680     __EXCEPT_PAGE_FAULT
1681     {
1682         return FALSE;
1683     }
1684     __ENDTRY
1685     return TRUE;
1686 }
1687
1688
1689 /***********************************************************************
1690  *           virtual_check_buffer_for_write
1691  *
1692  * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
1693  */
1694 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
1695 {
1696     if (!size) return TRUE;
1697     if (!ptr) return FALSE;
1698
1699     __TRY
1700     {
1701         volatile char *p = ptr;
1702         SIZE_T count = size;
1703
1704         while (count > page_size)
1705         {
1706             *p |= 0;
1707             p += page_size;
1708             count -= page_size;
1709         }
1710         p[0] |= 0;
1711         p[count - 1] |= 0;
1712     }
1713     __EXCEPT_PAGE_FAULT
1714     {
1715         return FALSE;
1716     }
1717     __ENDTRY
1718     return TRUE;
1719 }
1720
1721
1722 /***********************************************************************
1723  *           VIRTUAL_SetForceExec
1724  *
1725  * Whether to force exec prot on all views.
1726  */
1727 void VIRTUAL_SetForceExec( BOOL enable )
1728 {
1729     struct file_view *view;
1730     sigset_t sigset;
1731
1732     server_enter_uninterrupted_section( &csVirtual, &sigset );
1733     if (!force_exec_prot != !enable)  /* change all existing views */
1734     {
1735         force_exec_prot = enable;
1736
1737         LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1738         {
1739             UINT i, count;
1740             char *addr = view->base;
1741             BYTE commit = view->mapping ? VPROT_COMMITTED : 0;  /* file mappings are always accessible */
1742             int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1743
1744             if (view->protect & VPROT_NOEXEC) continue;
1745             for (count = i = 1; i < view->size >> page_shift; i++, count++)
1746             {
1747                 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1748                 if (prot == unix_prot) continue;
1749                 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1750                 {
1751                     TRACE( "%s exec prot for %p-%p\n",
1752                            force_exec_prot ? "enabling" : "disabling",
1753                            addr, addr + (count << page_shift) - 1 );
1754                     mprotect( addr, count << page_shift,
1755                               unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1756                 }
1757                 addr += (count << page_shift);
1758                 unix_prot = prot;
1759                 count = 0;
1760             }
1761             if (count)
1762             {
1763                 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1764                 {
1765                     TRACE( "%s exec prot for %p-%p\n",
1766                            force_exec_prot ? "enabling" : "disabling",
1767                            addr, addr + (count << page_shift) - 1 );
1768                     mprotect( addr, count << page_shift,
1769                               unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1770                 }
1771             }
1772         }
1773     }
1774     server_leave_uninterrupted_section( &csVirtual, &sigset );
1775 }
1776
1777 struct free_range
1778 {
1779     char *base;
1780     char *limit;
1781 };
1782
1783 /* free reserved areas above the limit; callback for wine_mmap_enum_reserved_areas */
1784 static int free_reserved_memory( void *base, size_t size, void *arg )
1785 {
1786     struct free_range *range = arg;
1787
1788     if ((char *)base >= range->limit) return 0;
1789     if ((char *)base + size <= range->base) return 0;
1790     if ((char *)base < range->base)
1791     {
1792         size -= range->base - (char *)base;
1793         base = range->base;
1794     }
1795     if ((char *)base + size > range->limit) size = range->limit - (char *)base;
1796     remove_reserved_area( base, size );
1797     return 1;  /* stop enumeration since the list has changed */
1798 }
1799
1800 /***********************************************************************
1801  *           virtual_release_address_space
1802  *
1803  * Release some address space once we have loaded and initialized the app.
1804  */
1805 void virtual_release_address_space( BOOL free_high_mem )
1806 {
1807     struct free_range range;
1808     sigset_t sigset;
1809
1810     if (user_space_limit == address_space_limit) return;  /* no need to free anything */
1811
1812     server_enter_uninterrupted_section( &csVirtual, &sigset );
1813
1814     /* no large address space on win9x */
1815     if (free_high_mem && NtCurrentTeb()->Peb->OSPlatformId == VER_PLATFORM_WIN32_NT)
1816     {
1817         range.base  = (char *)0x82000000;
1818         range.limit = address_space_limit;
1819         while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
1820         user_space_limit = working_set_limit = address_space_limit;
1821     }
1822     else
1823     {
1824 #ifndef __APPLE__  /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
1825         range.base  = (char *)0x20000000;
1826         range.limit = (char *)0x7f000000;
1827         while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
1828 #endif
1829     }
1830
1831     server_leave_uninterrupted_section( &csVirtual, &sigset );
1832 }
1833
1834
1835 /***********************************************************************
1836  *             NtAllocateVirtualMemory   (NTDLL.@)
1837  *             ZwAllocateVirtualMemory   (NTDLL.@)
1838  */
1839 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1840                                          SIZE_T *size_ptr, ULONG type, ULONG protect )
1841 {
1842     void *base;
1843     unsigned int vprot;
1844     SIZE_T size = *size_ptr;
1845     SIZE_T mask = get_mask( zero_bits );
1846     NTSTATUS status = STATUS_SUCCESS;
1847     struct file_view *view;
1848     sigset_t sigset;
1849
1850     TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1851
1852     if (!size) return STATUS_INVALID_PARAMETER;
1853
1854     if (process != NtCurrentProcess())
1855     {
1856         apc_call_t call;
1857         apc_result_t result;
1858
1859         memset( &call, 0, sizeof(call) );
1860
1861         call.virtual_alloc.type      = APC_VIRTUAL_ALLOC;
1862         call.virtual_alloc.addr      = wine_server_client_ptr( *ret );
1863         call.virtual_alloc.size      = *size_ptr;
1864         call.virtual_alloc.zero_bits = zero_bits;
1865         call.virtual_alloc.op_type   = type;
1866         call.virtual_alloc.prot      = protect;
1867         status = NTDLL_queue_process_apc( process, &call, &result );
1868         if (status != STATUS_SUCCESS) return status;
1869
1870         if (result.virtual_alloc.status == STATUS_SUCCESS)
1871         {
1872             *ret      = wine_server_get_ptr( result.virtual_alloc.addr );
1873             *size_ptr = result.virtual_alloc.size;
1874         }
1875         return result.virtual_alloc.status;
1876     }
1877
1878     /* Round parameters to a page boundary */
1879
1880     if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1881
1882     if ((status = get_vprot_flags( protect, &vprot, FALSE ))) return status;
1883     if (vprot & VPROT_WRITECOPY) return STATUS_INVALID_PAGE_PROTECTION;
1884     vprot |= VPROT_VALLOC;
1885     if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1886
1887     if (*ret)
1888     {
1889         if (type & MEM_RESERVE) /* Round down to 64k boundary */
1890             base = ROUND_ADDR( *ret, mask );
1891         else
1892             base = ROUND_ADDR( *ret, page_mask );
1893         size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1894
1895         /* address 1 is magic to mean DOS area */
1896         if (!base && *ret == (void *)1 && size == 0x110000)
1897         {
1898             server_enter_uninterrupted_section( &csVirtual, &sigset );
1899             status = allocate_dos_memory( &view, vprot );
1900             if (status == STATUS_SUCCESS)
1901             {
1902                 *ret = view->base;
1903                 *size_ptr = view->size;
1904             }
1905             server_leave_uninterrupted_section( &csVirtual, &sigset );
1906             return status;
1907         }
1908
1909         /* disallow low 64k, wrap-around and kernel space */
1910         if (((char *)base < (char *)0x10000) ||
1911             ((char *)base + size < (char *)base) ||
1912             is_beyond_limit( base, size, address_space_limit ))
1913             return STATUS_INVALID_PARAMETER;
1914     }
1915     else
1916     {
1917         base = NULL;
1918         size = (size + page_mask) & ~page_mask;
1919     }
1920
1921     /* Compute the alloc type flags */
1922
1923     if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
1924         (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1925     {
1926         WARN("called with wrong alloc type flags (%08x) !\n", type);
1927         return STATUS_INVALID_PARAMETER;
1928     }
1929
1930     /* Reserve the memory */
1931
1932     if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1933
1934     if ((type & MEM_RESERVE) || !base)
1935     {
1936         if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
1937         status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1938         if (status == STATUS_SUCCESS) base = view->base;
1939     }
1940     else if (type & MEM_RESET)
1941     {
1942         if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1943         else madvise( base, size, MADV_DONTNEED );
1944     }
1945     else  /* commit the pages */
1946     {
1947         if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1948         else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1949         else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1950         {
1951             SERVER_START_REQ( add_mapping_committed_range )
1952             {
1953                 req->handle = wine_server_obj_handle( view->mapping );
1954                 req->offset = (char *)base - (char *)view->base;
1955                 req->size   = size;
1956                 wine_server_call( req );
1957             }
1958             SERVER_END_REQ;
1959         }
1960     }
1961
1962     if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1963
1964     if (status == STATUS_SUCCESS)
1965     {
1966         *ret = base;
1967         *size_ptr = size;
1968     }
1969     return status;
1970 }
1971
1972
1973 /***********************************************************************
1974  *             NtFreeVirtualMemory   (NTDLL.@)
1975  *             ZwFreeVirtualMemory   (NTDLL.@)
1976  */
1977 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1978 {
1979     struct file_view *view;
1980     char *base;
1981     sigset_t sigset;
1982     NTSTATUS status = STATUS_SUCCESS;
1983     LPVOID addr = *addr_ptr;
1984     SIZE_T size = *size_ptr;
1985
1986     TRACE("%p %p %08lx %x\n", process, addr, size, type );
1987
1988     if (process != NtCurrentProcess())
1989     {
1990         apc_call_t call;
1991         apc_result_t result;
1992
1993         memset( &call, 0, sizeof(call) );
1994
1995         call.virtual_free.type      = APC_VIRTUAL_FREE;
1996         call.virtual_free.addr      = wine_server_client_ptr( addr );
1997         call.virtual_free.size      = size;
1998         call.virtual_free.op_type   = type;
1999         status = NTDLL_queue_process_apc( process, &call, &result );
2000         if (status != STATUS_SUCCESS) return status;
2001
2002         if (result.virtual_free.status == STATUS_SUCCESS)
2003         {
2004             *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
2005             *size_ptr = result.virtual_free.size;
2006         }
2007         return result.virtual_free.status;
2008     }
2009
2010     /* Fix the parameters */
2011
2012     size = ROUND_SIZE( addr, size );
2013     base = ROUND_ADDR( addr, page_mask );
2014
2015     /* avoid freeing the DOS area when a broken app passes a NULL pointer */
2016     if (!base) return STATUS_INVALID_PARAMETER;
2017
2018     server_enter_uninterrupted_section( &csVirtual, &sigset );
2019
2020     if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
2021     {
2022         status = STATUS_INVALID_PARAMETER;
2023     }
2024     else if (type == MEM_RELEASE)
2025     {
2026         /* Free the pages */
2027
2028         if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
2029         else
2030         {
2031             delete_view( view );
2032             *addr_ptr = base;
2033             *size_ptr = size;
2034         }
2035     }
2036     else if (type == MEM_DECOMMIT)
2037     {
2038         status = decommit_pages( view, base - (char *)view->base, size );
2039         if (status == STATUS_SUCCESS)
2040         {
2041             *addr_ptr = base;
2042             *size_ptr = size;
2043         }
2044     }
2045     else
2046     {
2047         WARN("called with wrong free type flags (%08x) !\n", type);
2048         status = STATUS_INVALID_PARAMETER;
2049     }
2050
2051     server_leave_uninterrupted_section( &csVirtual, &sigset );
2052     return status;
2053 }
2054
2055 static ULONG map_protection_to_access( ULONG vprot )
2056 {
2057     vprot &= VPROT_READ | VPROT_WRITE | VPROT_EXEC | VPROT_WRITECOPY;
2058     if (vprot & VPROT_EXEC)
2059     {
2060         if (vprot & VPROT_WRITE) vprot |= VPROT_WRITECOPY;
2061     }
2062     else vprot &= ~VPROT_WRITECOPY;
2063     return vprot;
2064 }
2065
2066 static BOOL is_compatible_protection( const struct file_view *view, ULONG new_prot )
2067 {
2068     ULONG view_prot, map_prot;
2069
2070     view_prot = map_protection_to_access( view->protect );
2071     new_prot = map_protection_to_access( new_prot );
2072
2073     if (view_prot == new_prot) return TRUE;
2074     if (!view_prot) return FALSE;
2075
2076     if ((view_prot & new_prot) != new_prot) return FALSE;
2077
2078     map_prot = map_protection_to_access( view->map_protect );
2079     if ((map_prot & new_prot) == new_prot) return TRUE;
2080
2081     return FALSE;
2082 }
2083
2084 /***********************************************************************
2085  *             NtProtectVirtualMemory   (NTDLL.@)
2086  *             ZwProtectVirtualMemory   (NTDLL.@)
2087  */
2088 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
2089                                         ULONG new_prot, ULONG *old_prot )
2090 {
2091     struct file_view *view;
2092     sigset_t sigset;
2093     NTSTATUS status = STATUS_SUCCESS;
2094     char *base;
2095     BYTE vprot;
2096     unsigned int new_vprot;
2097     SIZE_T size = *size_ptr;
2098     LPVOID addr = *addr_ptr;
2099
2100     TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
2101
2102     if (process != NtCurrentProcess())
2103     {
2104         apc_call_t call;
2105         apc_result_t result;
2106
2107         memset( &call, 0, sizeof(call) );
2108
2109         call.virtual_protect.type = APC_VIRTUAL_PROTECT;
2110         call.virtual_protect.addr = wine_server_client_ptr( addr );
2111         call.virtual_protect.size = size;
2112         call.virtual_protect.prot = new_prot;
2113         status = NTDLL_queue_process_apc( process, &call, &result );
2114         if (status != STATUS_SUCCESS) return status;
2115
2116         if (result.virtual_protect.status == STATUS_SUCCESS)
2117         {
2118             *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
2119             *size_ptr = result.virtual_protect.size;
2120             if (old_prot) *old_prot = result.virtual_protect.prot;
2121         }
2122         return result.virtual_protect.status;
2123     }
2124
2125     /* Fix the parameters */
2126
2127     size = ROUND_SIZE( addr, size );
2128     base = ROUND_ADDR( addr, page_mask );
2129
2130     server_enter_uninterrupted_section( &csVirtual, &sigset );
2131
2132     if ((view = VIRTUAL_FindView( base, size )))
2133     {
2134         /* Make sure all the pages are committed */
2135         if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2136         {
2137             if (!(status = get_vprot_flags( new_prot, &new_vprot, view->protect & VPROT_IMAGE )))
2138             {
2139                 if ((new_vprot & VPROT_WRITECOPY) && (view->protect & VPROT_VALLOC))
2140                     status = STATUS_INVALID_PAGE_PROTECTION;
2141                 else
2142                 {
2143                     if (!view->mapping || is_compatible_protection( view, new_vprot ))
2144                     {
2145                         new_vprot |= VPROT_COMMITTED;
2146                         if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
2147                         if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
2148                     }
2149                     else status = STATUS_INVALID_PAGE_PROTECTION;
2150                 }
2151             }
2152         }
2153         else status = STATUS_NOT_COMMITTED;
2154     }
2155     else status = STATUS_INVALID_PARAMETER;
2156
2157     server_leave_uninterrupted_section( &csVirtual, &sigset );
2158
2159     if (status == STATUS_SUCCESS)
2160     {
2161         *addr_ptr = base;
2162         *size_ptr = size;
2163     }
2164     return status;
2165 }
2166
2167
2168 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
2169 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
2170 {
2171     MEMORY_BASIC_INFORMATION *info = arg;
2172     void *end = (char *)start + size;
2173
2174     if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
2175
2176     if (info->BaseAddress >= end)
2177     {
2178         if (info->AllocationBase < end) info->AllocationBase = end;
2179         return 0;
2180     }
2181
2182     if (info->BaseAddress >= start || start <= address_space_start)
2183     {
2184         /* it's a real free area */
2185         info->State             = MEM_FREE;
2186         info->Protect           = PAGE_NOACCESS;
2187         info->AllocationBase    = 0;
2188         info->AllocationProtect = 0;
2189         info->Type              = 0;
2190         if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
2191             info->RegionSize = (char *)end - (char *)info->BaseAddress;
2192     }
2193     else /* outside of the reserved area, pretend it's allocated */
2194     {
2195         info->RegionSize        = (char *)start - (char *)info->BaseAddress;
2196         info->State             = MEM_RESERVE;
2197         info->Protect           = PAGE_NOACCESS;
2198         info->AllocationProtect = PAGE_NOACCESS;
2199         info->Type              = MEM_PRIVATE;
2200     }
2201     return 1;
2202 }
2203
2204 #define UNIMPLEMENTED_INFO_CLASS(c) \
2205     case c: \
2206         FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
2207         return STATUS_INVALID_INFO_CLASS
2208
2209 /***********************************************************************
2210  *             NtQueryVirtualMemory   (NTDLL.@)
2211  *             ZwQueryVirtualMemory   (NTDLL.@)
2212  */
2213 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
2214                                       MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2215                                       SIZE_T len, SIZE_T *res_len )
2216 {
2217     struct file_view *view;
2218     char *base, *alloc_base = 0;
2219     struct list *ptr;
2220     SIZE_T size = 0;
2221     MEMORY_BASIC_INFORMATION *info = buffer;
2222     sigset_t sigset;
2223
2224     if (info_class != MemoryBasicInformation)
2225     {
2226         switch(info_class)
2227         {
2228             UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
2229             UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
2230             UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
2231
2232             default:
2233                 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n", 
2234                       process, addr, info_class, buffer, len, res_len);
2235                 return STATUS_INVALID_INFO_CLASS;
2236         }
2237     }
2238
2239     if (process != NtCurrentProcess())
2240     {
2241         NTSTATUS status;
2242         apc_call_t call;
2243         apc_result_t result;
2244
2245         memset( &call, 0, sizeof(call) );
2246
2247         call.virtual_query.type = APC_VIRTUAL_QUERY;
2248         call.virtual_query.addr = wine_server_client_ptr( addr );
2249         status = NTDLL_queue_process_apc( process, &call, &result );
2250         if (status != STATUS_SUCCESS) return status;
2251
2252         if (result.virtual_query.status == STATUS_SUCCESS)
2253         {
2254             info->BaseAddress       = wine_server_get_ptr( result.virtual_query.base );
2255             info->AllocationBase    = wine_server_get_ptr( result.virtual_query.alloc_base );
2256             info->RegionSize        = result.virtual_query.size;
2257             info->Protect           = result.virtual_query.prot;
2258             info->AllocationProtect = result.virtual_query.alloc_prot;
2259             info->State             = (DWORD)result.virtual_query.state << 12;
2260             info->Type              = (DWORD)result.virtual_query.alloc_type << 16;
2261             if (info->RegionSize != result.virtual_query.size)  /* truncated */
2262                 return STATUS_INVALID_PARAMETER;  /* FIXME */
2263             if (res_len) *res_len = sizeof(*info);
2264         }
2265         return result.virtual_query.status;
2266     }
2267
2268     base = ROUND_ADDR( addr, page_mask );
2269
2270     if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2271
2272     /* Find the view containing the address */
2273
2274     server_enter_uninterrupted_section( &csVirtual, &sigset );
2275     ptr = list_head( &views_list );
2276     for (;;)
2277     {
2278         if (!ptr)
2279         {
2280             size = (char *)working_set_limit - alloc_base;
2281             view = NULL;
2282             break;
2283         }
2284         view = LIST_ENTRY( ptr, struct file_view, entry );
2285         if ((char *)view->base > base)
2286         {
2287             size = (char *)view->base - alloc_base;
2288             view = NULL;
2289             break;
2290         }
2291         if ((char *)view->base + view->size > base)
2292         {
2293             alloc_base = view->base;
2294             size = view->size;
2295             break;
2296         }
2297         alloc_base = (char *)view->base + view->size;
2298         ptr = list_next( &views_list, ptr );
2299     }
2300
2301     /* Fill the info structure */
2302
2303     info->AllocationBase = alloc_base;
2304     info->BaseAddress    = base;
2305     info->RegionSize     = size - (base - alloc_base);
2306
2307     if (!view)
2308     {
2309         if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2310         {
2311             /* not in a reserved area at all, pretend it's allocated */
2312 #ifdef __i386__
2313             if (base >= (char *)address_space_start)
2314             {
2315                 info->State             = MEM_RESERVE;
2316                 info->Protect           = PAGE_NOACCESS;
2317                 info->AllocationProtect = PAGE_NOACCESS;
2318                 info->Type              = MEM_PRIVATE;
2319             }
2320             else
2321 #endif
2322             {
2323                 info->State             = MEM_FREE;
2324                 info->Protect           = PAGE_NOACCESS;
2325                 info->AllocationBase    = 0;
2326                 info->AllocationProtect = 0;
2327                 info->Type              = 0;
2328             }
2329         }
2330     }
2331     else
2332     {
2333         BYTE vprot;
2334         SIZE_T range_size = get_committed_size( view, base, &vprot );
2335
2336         info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2337         info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2338         info->AllocationBase = alloc_base;
2339         info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2340         if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2341         else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2342         else info->Type = MEM_MAPPED;
2343         for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2344             if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2345         info->RegionSize = size - (base - alloc_base);
2346     }
2347     server_leave_uninterrupted_section( &csVirtual, &sigset );
2348
2349     if (res_len) *res_len = sizeof(*info);
2350     return STATUS_SUCCESS;
2351 }
2352
2353
2354 /***********************************************************************
2355  *             NtLockVirtualMemory   (NTDLL.@)
2356  *             ZwLockVirtualMemory   (NTDLL.@)
2357  */
2358 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2359 {
2360     NTSTATUS status = STATUS_SUCCESS;
2361
2362     if (process != NtCurrentProcess())
2363     {
2364         apc_call_t call;
2365         apc_result_t result;
2366
2367         memset( &call, 0, sizeof(call) );
2368
2369         call.virtual_lock.type = APC_VIRTUAL_LOCK;
2370         call.virtual_lock.addr = wine_server_client_ptr( *addr );
2371         call.virtual_lock.size = *size;
2372         status = NTDLL_queue_process_apc( process, &call, &result );
2373         if (status != STATUS_SUCCESS) return status;
2374
2375         if (result.virtual_lock.status == STATUS_SUCCESS)
2376         {
2377             *addr = wine_server_get_ptr( result.virtual_lock.addr );
2378             *size = result.virtual_lock.size;
2379         }
2380         return result.virtual_lock.status;
2381     }
2382
2383     *size = ROUND_SIZE( *addr, *size );
2384     *addr = ROUND_ADDR( *addr, page_mask );
2385
2386     if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2387     return status;
2388 }
2389
2390
2391 /***********************************************************************
2392  *             NtUnlockVirtualMemory   (NTDLL.@)
2393  *             ZwUnlockVirtualMemory   (NTDLL.@)
2394  */
2395 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2396 {
2397     NTSTATUS status = STATUS_SUCCESS;
2398
2399     if (process != NtCurrentProcess())
2400     {
2401         apc_call_t call;
2402         apc_result_t result;
2403
2404         memset( &call, 0, sizeof(call) );
2405
2406         call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2407         call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2408         call.virtual_unlock.size = *size;
2409         status = NTDLL_queue_process_apc( process, &call, &result );
2410         if (status != STATUS_SUCCESS) return status;
2411
2412         if (result.virtual_unlock.status == STATUS_SUCCESS)
2413         {
2414             *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2415             *size = result.virtual_unlock.size;
2416         }
2417         return result.virtual_unlock.status;
2418     }
2419
2420     *size = ROUND_SIZE( *addr, *size );
2421     *addr = ROUND_ADDR( *addr, page_mask );
2422
2423     if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2424     return status;
2425 }
2426
2427
2428 /***********************************************************************
2429  *             NtCreateSection   (NTDLL.@)
2430  *             ZwCreateSection   (NTDLL.@)
2431  */
2432 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2433                                  const LARGE_INTEGER *size, ULONG protect,
2434                                  ULONG sec_flags, HANDLE file )
2435 {
2436     NTSTATUS ret;
2437     unsigned int vprot;
2438     DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2439     struct security_descriptor *sd = NULL;
2440     struct object_attributes objattr;
2441
2442     /* Check parameters */
2443
2444     if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2445
2446     if ((ret = get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE ))) return ret;
2447
2448     objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
2449     objattr.sd_len = 0;
2450     objattr.name_len = len;
2451     if (attr)
2452     {
2453         ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2454         if (ret != STATUS_SUCCESS) return ret;
2455     }
2456
2457     if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2458     if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2459     if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2460
2461     /* Create the server object */
2462
2463     SERVER_START_REQ( create_mapping )
2464     {
2465         req->access      = access;
2466         req->attributes  = (attr) ? attr->Attributes : 0;
2467         req->file_handle = wine_server_obj_handle( file );
2468         req->size        = size ? size->QuadPart : 0;
2469         req->protect     = vprot;
2470         wine_server_add_data( req, &objattr, sizeof(objattr) );
2471         if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2472         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2473         ret = wine_server_call( req );
2474         *handle = wine_server_ptr_handle( reply->handle );
2475     }
2476     SERVER_END_REQ;
2477
2478     NTDLL_free_struct_sd( sd );
2479
2480     return ret;
2481 }
2482
2483
2484 /***********************************************************************
2485  *             NtOpenSection   (NTDLL.@)
2486  *             ZwOpenSection   (NTDLL.@)
2487  */
2488 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2489 {
2490     NTSTATUS ret;
2491     DWORD len = attr->ObjectName->Length;
2492
2493     if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2494
2495     SERVER_START_REQ( open_mapping )
2496     {
2497         req->access  = access;
2498         req->attributes = attr->Attributes;
2499         req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2500         wine_server_add_data( req, attr->ObjectName->Buffer, len );
2501         if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
2502     }
2503     SERVER_END_REQ;
2504     return ret;
2505 }
2506
2507
2508 /***********************************************************************
2509  *             NtMapViewOfSection   (NTDLL.@)
2510  *             ZwMapViewOfSection   (NTDLL.@)
2511  */
2512 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2513                                     SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2514                                     SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2515 {
2516     NTSTATUS res;
2517     mem_size_t full_size;
2518     ACCESS_MASK access;
2519     SIZE_T size, mask = get_mask( zero_bits );
2520     int unix_handle = -1, needs_close;
2521     unsigned int map_vprot, vprot;
2522     void *base;
2523     struct file_view *view;
2524     DWORD header_size;
2525     HANDLE dup_mapping, shared_file;
2526     LARGE_INTEGER offset;
2527     sigset_t sigset;
2528
2529     offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2530
2531     TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2532           handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2533
2534     /* Check parameters */
2535
2536     if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2537         return STATUS_INVALID_PARAMETER;
2538
2539     switch(protect)
2540     {
2541     case PAGE_NOACCESS:
2542         access = SECTION_MAP_READ;
2543         break;
2544     case PAGE_READWRITE:
2545     case PAGE_EXECUTE_READWRITE:
2546         access = SECTION_MAP_WRITE;
2547         break;
2548     case PAGE_READONLY:
2549     case PAGE_WRITECOPY:
2550     case PAGE_EXECUTE:
2551     case PAGE_EXECUTE_READ:
2552     case PAGE_EXECUTE_WRITECOPY:
2553         access = SECTION_MAP_READ;
2554         break;
2555     default:
2556         return STATUS_INVALID_PAGE_PROTECTION;
2557     }
2558
2559     if (process != NtCurrentProcess())
2560     {
2561         apc_call_t call;
2562         apc_result_t result;
2563
2564         memset( &call, 0, sizeof(call) );
2565
2566         call.map_view.type        = APC_MAP_VIEW;
2567         call.map_view.handle      = wine_server_obj_handle( handle );
2568         call.map_view.addr        = wine_server_client_ptr( *addr_ptr );
2569         call.map_view.size        = *size_ptr;
2570         call.map_view.offset      = offset.QuadPart;
2571         call.map_view.zero_bits   = zero_bits;
2572         call.map_view.alloc_type  = alloc_type;
2573         call.map_view.prot        = protect;
2574         res = NTDLL_queue_process_apc( process, &call, &result );
2575         if (res != STATUS_SUCCESS) return res;
2576
2577         if ((NTSTATUS)result.map_view.status >= 0)
2578         {
2579             *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2580             *size_ptr = result.map_view.size;
2581         }
2582         return result.map_view.status;
2583     }
2584
2585     SERVER_START_REQ( get_mapping_info )
2586     {
2587         req->handle = wine_server_obj_handle( handle );
2588         req->access = access;
2589         res = wine_server_call( req );
2590         map_vprot   = reply->protect;
2591         base        = wine_server_get_ptr( reply->base );
2592         full_size   = reply->size;
2593         header_size = reply->header_size;
2594         dup_mapping = wine_server_ptr_handle( reply->mapping );
2595         shared_file = wine_server_ptr_handle( reply->shared_file );
2596         if ((ULONG_PTR)base != reply->base) base = NULL;
2597     }
2598     SERVER_END_REQ;
2599     if (res) return res;
2600
2601     if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2602
2603     if (map_vprot & VPROT_IMAGE)
2604     {
2605         size = full_size;
2606         if (size != full_size)  /* truncated */
2607         {
2608             WARN( "Modules larger than 4Gb (%s) not supported\n", wine_dbgstr_longlong(full_size) );
2609             res = STATUS_INVALID_PARAMETER;
2610             goto done;
2611         }
2612         if (shared_file)
2613         {
2614             int shared_fd, shared_needs_close;
2615
2616             if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2617                                            &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2618             res = map_image( handle, unix_handle, base, size, mask, header_size,
2619                              shared_fd, dup_mapping, map_vprot, addr_ptr );
2620             if (shared_needs_close) close( shared_fd );
2621             NtClose( shared_file );
2622         }
2623         else
2624         {
2625             res = map_image( handle, unix_handle, base, size, mask, header_size,
2626                              -1, dup_mapping, map_vprot, addr_ptr );
2627         }
2628         if (needs_close) close( unix_handle );
2629         if (res >= 0) *size_ptr = size;
2630         return res;
2631     }
2632
2633     res = STATUS_INVALID_PARAMETER;
2634     if (offset.QuadPart >= full_size) goto done;
2635     if (*size_ptr)
2636     {
2637         if (*size_ptr > full_size - offset.QuadPart) goto done;
2638         size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2639         if (size < *size_ptr) goto done;  /* wrap-around */
2640     }
2641     else
2642     {
2643         size = full_size - offset.QuadPart;
2644         if (size != full_size - offset.QuadPart)  /* truncated */
2645         {
2646             WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2647                   wine_dbgstr_longlong(full_size) );
2648             goto done;
2649         }
2650     }
2651
2652     /* Reserve a properly aligned area */
2653
2654     server_enter_uninterrupted_section( &csVirtual, &sigset );
2655
2656     get_vprot_flags( protect, &vprot, map_vprot & VPROT_IMAGE );
2657     vprot |= (map_vprot & VPROT_COMMITTED);
2658     res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2659     if (res)
2660     {
2661         server_leave_uninterrupted_section( &csVirtual, &sigset );
2662         goto done;
2663     }
2664
2665     /* Map the file */
2666
2667     TRACE("handle=%p size=%lx offset=%x%08x\n",
2668           handle, size, offset.u.HighPart, offset.u.LowPart );
2669
2670     res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2671     if (res == STATUS_SUCCESS)
2672     {
2673         *addr_ptr = view->base;
2674         *size_ptr = size;
2675         view->mapping = dup_mapping;
2676         view->map_protect = map_vprot;
2677         dup_mapping = 0;  /* don't close it */
2678     }
2679     else
2680     {
2681         ERR( "map_file_into_view %p %lx %x%08x failed\n",
2682              view->base, size, offset.u.HighPart, offset.u.LowPart );
2683         delete_view( view );
2684     }
2685
2686     server_leave_uninterrupted_section( &csVirtual, &sigset );
2687
2688 done:
2689     if (dup_mapping) NtClose( dup_mapping );
2690     if (needs_close) close( unix_handle );
2691     return res;
2692 }
2693
2694
2695 /***********************************************************************
2696  *             NtUnmapViewOfSection   (NTDLL.@)
2697  *             ZwUnmapViewOfSection   (NTDLL.@)
2698  */
2699 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2700 {
2701     struct file_view *view;
2702     NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
2703     sigset_t sigset;
2704     void *base = ROUND_ADDR( addr, page_mask );
2705
2706     if (process != NtCurrentProcess())
2707     {
2708         apc_call_t call;
2709         apc_result_t result;
2710
2711         memset( &call, 0, sizeof(call) );
2712
2713         call.unmap_view.type = APC_UNMAP_VIEW;
2714         call.unmap_view.addr = wine_server_client_ptr( addr );
2715         status = NTDLL_queue_process_apc( process, &call, &result );
2716         if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2717         return status;
2718     }
2719
2720     server_enter_uninterrupted_section( &csVirtual, &sigset );
2721     if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base) && !(view->protect & VPROT_VALLOC))
2722     {
2723         delete_view( view );
2724         status = STATUS_SUCCESS;
2725     }
2726     server_leave_uninterrupted_section( &csVirtual, &sigset );
2727     return status;
2728 }
2729
2730
2731 /***********************************************************************
2732  *             NtFlushVirtualMemory   (NTDLL.@)
2733  *             ZwFlushVirtualMemory   (NTDLL.@)
2734  */
2735 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2736                                       SIZE_T *size_ptr, ULONG unknown )
2737 {
2738     struct file_view *view;
2739     NTSTATUS status = STATUS_SUCCESS;
2740     sigset_t sigset;
2741     void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2742
2743     if (process != NtCurrentProcess())
2744     {
2745         apc_call_t call;
2746         apc_result_t result;
2747
2748         memset( &call, 0, sizeof(call) );
2749
2750         call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2751         call.virtual_flush.addr = wine_server_client_ptr( addr );
2752         call.virtual_flush.size = *size_ptr;
2753         status = NTDLL_queue_process_apc( process, &call, &result );
2754         if (status != STATUS_SUCCESS) return status;
2755
2756         if (result.virtual_flush.status == STATUS_SUCCESS)
2757         {
2758             *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2759             *size_ptr = result.virtual_flush.size;
2760         }
2761         return result.virtual_flush.status;
2762     }
2763
2764     server_enter_uninterrupted_section( &csVirtual, &sigset );
2765     if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2766     else
2767     {
2768         if (!*size_ptr) *size_ptr = view->size;
2769         *addr_ptr = addr;
2770         if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2771     }
2772     server_leave_uninterrupted_section( &csVirtual, &sigset );
2773     return status;
2774 }
2775
2776
2777 /***********************************************************************
2778  *             NtGetWriteWatch   (NTDLL.@)
2779  *             ZwGetWriteWatch   (NTDLL.@)
2780  */
2781 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
2782                                  ULONG_PTR *count, ULONG *granularity )
2783 {
2784     struct file_view *view;
2785     NTSTATUS status = STATUS_SUCCESS;
2786     sigset_t sigset;
2787
2788     size = ROUND_SIZE( base, size );
2789     base = ROUND_ADDR( base, page_mask );
2790
2791     if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
2792     if (!*count || !size) return STATUS_INVALID_PARAMETER;
2793     if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
2794
2795     if (!addresses) return STATUS_ACCESS_VIOLATION;
2796
2797     TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
2798            addresses, *count );
2799
2800     server_enter_uninterrupted_section( &csVirtual, &sigset );
2801
2802     if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2803     {
2804         ULONG_PTR pos = 0;
2805         char *addr = base;
2806         char *end = addr + size;
2807
2808         while (pos < *count && addr < end)
2809         {
2810             BYTE prot = view->prot[(addr - (char *)view->base) >> page_shift];
2811             if (!(prot & VPROT_WRITEWATCH)) addresses[pos++] = addr;
2812             addr += page_size;
2813         }
2814         if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( view, base, addr - (char *)base );
2815         *count = pos;
2816         *granularity = page_size;
2817     }
2818     else status = STATUS_INVALID_PARAMETER;
2819
2820     server_leave_uninterrupted_section( &csVirtual, &sigset );
2821     return status;
2822 }
2823
2824
2825 /***********************************************************************
2826  *             NtResetWriteWatch   (NTDLL.@)
2827  *             ZwResetWriteWatch   (NTDLL.@)
2828  */
2829 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
2830 {
2831     struct file_view *view;
2832     NTSTATUS status = STATUS_SUCCESS;
2833     sigset_t sigset;
2834
2835     size = ROUND_SIZE( base, size );
2836     base = ROUND_ADDR( base, page_mask );
2837
2838     TRACE( "%p %p-%p\n", process, base, (char *)base + size );
2839
2840     if (!size) return STATUS_INVALID_PARAMETER;
2841
2842     server_enter_uninterrupted_section( &csVirtual, &sigset );
2843
2844     if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2845         reset_write_watches( view, base, size );
2846     else
2847         status = STATUS_INVALID_PARAMETER;
2848
2849     server_leave_uninterrupted_section( &csVirtual, &sigset );
2850     return status;
2851 }
2852
2853
2854 /***********************************************************************
2855  *             NtReadVirtualMemory   (NTDLL.@)
2856  *             ZwReadVirtualMemory   (NTDLL.@)
2857  */
2858 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2859                                      SIZE_T size, SIZE_T *bytes_read )
2860 {
2861     NTSTATUS status;
2862
2863     if (virtual_check_buffer_for_write( buffer, size ))
2864     {
2865         SERVER_START_REQ( read_process_memory )
2866         {
2867             req->handle = wine_server_obj_handle( process );
2868             req->addr   = wine_server_client_ptr( addr );
2869             wine_server_set_reply( req, buffer, size );
2870             if ((status = wine_server_call( req ))) size = 0;
2871         }
2872         SERVER_END_REQ;
2873     }
2874     else
2875     {
2876         status = STATUS_ACCESS_VIOLATION;
2877         size = 0;
2878     }
2879     if (bytes_read) *bytes_read = size;
2880     return status;
2881 }
2882
2883
2884 /***********************************************************************
2885  *             NtWriteVirtualMemory   (NTDLL.@)
2886  *             ZwWriteVirtualMemory   (NTDLL.@)
2887  */
2888 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2889                                       SIZE_T size, SIZE_T *bytes_written )
2890 {
2891     NTSTATUS status;
2892
2893     if (virtual_check_buffer_for_read( buffer, size ))
2894     {
2895         SERVER_START_REQ( write_process_memory )
2896         {
2897             req->handle     = wine_server_obj_handle( process );
2898             req->addr       = wine_server_client_ptr( addr );
2899             wine_server_add_data( req, buffer, size );
2900             if ((status = wine_server_call( req ))) size = 0;
2901         }
2902         SERVER_END_REQ;
2903     }
2904     else
2905     {
2906         status = STATUS_PARTIAL_COPY;
2907         size = 0;
2908     }
2909     if (bytes_written) *bytes_written = size;
2910     return status;
2911 }
2912
2913
2914 /***********************************************************************
2915  *             NtAreMappedFilesTheSame   (NTDLL.@)
2916  *             ZwAreMappedFilesTheSame   (NTDLL.@)
2917  */
2918 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2919 {
2920     struct file_view *view1, *view2;
2921     struct stat st1, st2;
2922     NTSTATUS status;
2923     sigset_t sigset;
2924
2925     TRACE("%p %p\n", addr1, addr2);
2926
2927     server_enter_uninterrupted_section( &csVirtual, &sigset );
2928
2929     view1 = VIRTUAL_FindView( addr1, 0 );
2930     view2 = VIRTUAL_FindView( addr2, 0 );
2931
2932     if (!view1 || !view2)
2933         status = STATUS_INVALID_ADDRESS;
2934     else if ((view1->protect & VPROT_VALLOC) || (view2->protect & VPROT_VALLOC))
2935         status = STATUS_CONFLICTING_ADDRESSES;
2936     else if (!(view1->protect & VPROT_IMAGE) || !(view2->protect & VPROT_IMAGE))
2937         status = STATUS_NOT_SAME_DEVICE;
2938     else if (view1 == view2)
2939         status = STATUS_SUCCESS;
2940     else if (!stat_mapping_file( view1, &st1 ) && !stat_mapping_file( view2, &st2 ) &&
2941              st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2942         status = STATUS_SUCCESS;
2943     else
2944         status = STATUS_NOT_SAME_DEVICE;
2945
2946     server_leave_uninterrupted_section( &csVirtual, &sigset );
2947     return status;
2948 }