~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/dlls/ntdll/virtual.c

Version: ~ [ wine-1.1.33 ] ~ [ wine-1.1.32 ] ~ [ wine-1.1.31 ] ~ [ wine-1.1.30 ] ~ [ wine-1.1.29 ] ~ [ wine-1.1.28 ] ~ [ wine-1.1.27 ] ~ [ wine-1.1.26 ] ~ [ wine-1.1.25 ] ~ [ wine-1.1.24 ] ~ [ wine-1.1.23 ] ~ [ wine-1.1.22 ] ~ [ wine-1.1.21 ] ~ [ wine-1.1.20 ] ~ [ wine-1.1.19 ] ~ [ wine-1.1.18 ] ~ [ wine-1.1.17 ] ~ [ wine-1.1.16 ] ~ [ wine-1.1.15 ] ~ [ wine-1.1.14 ] ~ [ wine-1.1.13 ] ~ [ wine-1.1.12 ] ~ [ wine-1.1.11 ] ~ [ wine-1.1.10 ] ~ [ wine-1.1.9 ] ~ [ wine-1.1.8 ] ~ [ wine-1.1.7 ] ~ [ wine-1.0.1 ] ~ [ wine-1.1.6 ] ~ [ wine-1.1.5 ] ~ [ wine-1.1.4 ] ~ [ wine-1.1.3 ] ~ [ wine-1.1.2 ] ~ [ wine-1.1.1 ] ~ [ wine-1.1.0 ] ~ [ wine-1.0 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

This page was automatically generated by the LXR engine.
Visit the LXR main site for more information.