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