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