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