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