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