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