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