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