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