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