ntdll: Moved the check for removable file in load_dll to the server.
[wine] / dlls / ntdll / virtual.c
1 /*
2  * Win32 virtual memory functions
3  *
4  * Copyright 1997, 2002 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <errno.h>
26 #ifdef HAVE_SYS_ERRNO_H
27 #include <sys/errno.h>
28 #endif
29 #include <fcntl.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include <stdarg.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
40 #endif
41 #ifdef HAVE_SYS_MMAN_H
42 # include <sys/mman.h>
43 #endif
44
45 #define NONAMELESSUNION
46 #define NONAMELESSSTRUCT
47 #include "ntstatus.h"
48 #define WIN32_NO_STATUS
49 #include "windef.h"
50 #include "winternl.h"
51 #include "winioctl.h"
52 #include "wine/library.h"
53 #include "wine/server.h"
54 #include "wine/list.h"
55 #include "wine/debug.h"
56 #include "ntdll_misc.h"
57
58 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
59 WINE_DECLARE_DEBUG_CHANNEL(module);
60
61 #ifndef MS_SYNC
62 #define MS_SYNC 0
63 #endif
64
65 #ifndef MAP_NORESERVE
66 #define MAP_NORESERVE 0
67 #endif
68
69 /* File view */
70 typedef struct file_view
71 {
72     struct list   entry;       /* Entry in global view list */
73     void         *base;        /* Base address */
74     size_t        size;        /* Size in bytes */
75     HANDLE        mapping;     /* Handle to the file mapping */
76     BYTE          flags;       /* Allocation flags (VFLAG_*) */
77     BYTE          protect;     /* Protection for all pages at allocation time */
78     BYTE          prot[1];     /* Protection byte for each page */
79 } FILE_VIEW;
80
81 /* Per-view flags */
82 #define VFLAG_SYSTEM     0x01  /* system view (underlying mmap not under our control) */
83 #define VFLAG_VALLOC     0x02  /* allocated by VirtualAlloc */
84
85 /* Conversion from VPROT_* to Win32 flags */
86 static const BYTE VIRTUAL_Win32Flags[16] =
87 {
88     PAGE_NOACCESS,              /* 0 */
89     PAGE_READONLY,              /* READ */
90     PAGE_READWRITE,             /* WRITE */
91     PAGE_READWRITE,             /* READ | WRITE */
92     PAGE_EXECUTE,               /* EXEC */
93     PAGE_EXECUTE_READ,          /* READ | EXEC */
94     PAGE_EXECUTE_READWRITE,     /* WRITE | EXEC */
95     PAGE_EXECUTE_READWRITE,     /* READ | WRITE | EXEC */
96     PAGE_WRITECOPY,             /* WRITECOPY */
97     PAGE_WRITECOPY,             /* READ | WRITECOPY */
98     PAGE_WRITECOPY,             /* WRITE | WRITECOPY */
99     PAGE_WRITECOPY,             /* READ | WRITE | WRITECOPY */
100     PAGE_EXECUTE_WRITECOPY,     /* EXEC | WRITECOPY */
101     PAGE_EXECUTE_WRITECOPY,     /* READ | EXEC | WRITECOPY */
102     PAGE_EXECUTE_WRITECOPY,     /* WRITE | EXEC | WRITECOPY */
103     PAGE_EXECUTE_WRITECOPY      /* READ | WRITE | EXEC | WRITECOPY */
104 };
105
106 static struct list views_list = LIST_INIT(views_list);
107
108 static RTL_CRITICAL_SECTION csVirtual;
109 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
110 {
111     0, 0, &csVirtual,
112     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
113       0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
114 };
115 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
116
117 #ifdef __i386__
118 /* These are always the same on an i386, and it will be faster this way */
119 # define page_mask  0xfff
120 # define page_shift 12
121 # define page_size  0x1000
122 /* Note: these are Windows limits, you cannot change them. */
123 # define ADDRESS_SPACE_LIMIT  ((void *)0xc0000000)  /* top of the total available address space */
124 # define USER_SPACE_LIMIT     ((void *)0x7fff0000)  /* top of the user address space */
125 #else
126 static UINT page_shift;
127 static UINT page_size;
128 static UINT_PTR page_mask;
129 # define ADDRESS_SPACE_LIMIT  0   /* no limit needed on other platforms */
130 # define USER_SPACE_LIMIT     0   /* no limit needed on other platforms */
131 #endif  /* __i386__ */
132
133 #define ROUND_ADDR(addr,mask) \
134    ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
135
136 #define ROUND_SIZE(addr,size) \
137    (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
138
139 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
140     do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
141
142 static void *user_space_limit = USER_SPACE_LIMIT;
143 static void *preload_reserve_start;
144 static void *preload_reserve_end;
145 static int use_locks;
146 static int force_exec_prot;  /* whether to force PROT_EXEC on all PROT_READ mmaps */
147
148
149 /***********************************************************************
150  *           VIRTUAL_GetProtStr
151  */
152 static const char *VIRTUAL_GetProtStr( BYTE prot )
153 {
154     static char buffer[6];
155     buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
156     buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
157     buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
158     buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
159     buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
160     buffer[5] = 0;
161     return buffer;
162 }
163
164
165 /***********************************************************************
166  *           VIRTUAL_GetUnixProt
167  *
168  * Convert page protections to protection for mmap/mprotect.
169  */
170 static int VIRTUAL_GetUnixProt( BYTE vprot )
171 {
172     int prot = 0;
173     if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
174     {
175         if (vprot & VPROT_READ) prot |= PROT_READ;
176         if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
177         if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
178         if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
179     }
180     if (!prot) prot = PROT_NONE;
181     return prot;
182 }
183
184
185 /***********************************************************************
186  *           VIRTUAL_DumpView
187  */
188 static void VIRTUAL_DumpView( FILE_VIEW *view )
189 {
190     UINT i, count;
191     char *addr = view->base;
192     BYTE prot = view->prot[0];
193
194     TRACE( "View: %p - %p", addr, addr + view->size - 1 );
195     if (view->flags & VFLAG_SYSTEM)
196         TRACE( " (system)\n" );
197     else if (view->flags & VFLAG_VALLOC)
198         TRACE( " (valloc)\n" );
199     else if (view->mapping)
200         TRACE( " %p\n", view->mapping );
201     else
202         TRACE( " (anonymous)\n");
203
204     for (count = i = 1; i < view->size >> page_shift; i++, count++)
205     {
206         if (view->prot[i] == prot) continue;
207         TRACE( "      %p - %p %s\n",
208                  addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
209         addr += (count << page_shift);
210         prot = view->prot[i];
211         count = 0;
212     }
213     if (count)
214         TRACE( "      %p - %p %s\n",
215                  addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
216 }
217
218
219 /***********************************************************************
220  *           VIRTUAL_Dump
221  */
222 #if WINE_VM_DEBUG
223 static void VIRTUAL_Dump(void)
224 {
225     struct file_view *view;
226
227     TRACE( "Dump of all virtual memory views:\n" );
228     RtlEnterCriticalSection(&csVirtual);
229     LIST_FOR_EACH_ENTRY( view, &views_list, FILE_VIEW, entry )
230     {
231         VIRTUAL_DumpView( view );
232     }
233     RtlLeaveCriticalSection(&csVirtual);
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( void *addr, size_t size, void *limit )
370 {
371     return (limit && (addr >= limit || (char *)addr + size > (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) return FILE_GetNtStatus();  /* we cannot fake shared write mappings */
828     }
829
830     /* Reserve the memory with an anonymous mmap */
831     ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
832     if (ptr == (void *)-1) return FILE_GetNtStatus();
833     /* Now read in the file */
834     pread( fd, ptr, size, offset );
835     if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot );  /* Set the right protection */
836 done:
837     memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
838     return STATUS_SUCCESS;
839 }
840
841
842 /***********************************************************************
843  *           decommit_view
844  *
845  * Decommit some pages of a given view.
846  * The csVirtual section must be held by caller.
847  */
848 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
849 {
850     if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
851     {
852         BYTE *p = view->prot + (start >> page_shift);
853         size >>= page_shift;
854         while (size--) *p++ &= ~VPROT_COMMITTED;
855         return STATUS_SUCCESS;
856     }
857     return FILE_GetNtStatus();
858 }
859
860
861 /***********************************************************************
862  *           do_relocations
863  *
864  * Apply the relocations to a mapped PE image
865  */
866 static int do_relocations( char *base, const IMAGE_DATA_DIRECTORY *dir,
867                            int delta, SIZE_T total_size )
868 {
869     IMAGE_BASE_RELOCATION *rel;
870
871     TRACE_(module)( "relocating from %p-%p to %p-%p\n",
872                     base - delta, base - delta + total_size, base, base + total_size );
873
874     for (rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
875          ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
876          rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock) )
877     {
878         char *page = base + rel->VirtualAddress;
879         WORD *TypeOffset = (WORD *)(rel + 1);
880         int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
881
882         if (!count) continue;
883
884         /* sanity checks */
885         if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size)
886         {
887             ERR_(module)("invalid relocation %p,%x,%d at %p,%x,%x\n",
888                          rel, rel->VirtualAddress, rel->SizeOfBlock,
889                          base, dir->VirtualAddress, dir->Size );
890             return 0;
891         }
892
893         if (page > base + total_size)
894         {
895             WARN_(module)("skipping %d relocations for page %p beyond module %p-%p\n",
896                           count, page, base, base + total_size );
897             continue;
898         }
899
900         TRACE_(module)("%d relocations for page %x\n", count, rel->VirtualAddress);
901
902         /* patching in reverse order */
903         for (i = 0 ; i < count; i++)
904         {
905             int offset = TypeOffset[i] & 0xFFF;
906             int type = TypeOffset[i] >> 12;
907             switch(type)
908             {
909             case IMAGE_REL_BASED_ABSOLUTE:
910                 break;
911             case IMAGE_REL_BASED_HIGH:
912                 *(short*)(page+offset) += HIWORD(delta);
913                 break;
914             case IMAGE_REL_BASED_LOW:
915                 *(short*)(page+offset) += LOWORD(delta);
916                 break;
917             case IMAGE_REL_BASED_HIGHLOW:
918                 *(int*)(page+offset) += delta;
919                 /* FIXME: if this is an exported address, fire up enhanced logic */
920                 break;
921             default:
922                 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
923                 break;
924             }
925         }
926     }
927     return 1;
928 }
929
930
931 /***********************************************************************
932  *           map_image
933  *
934  * Map an executable (PE format) image into memory.
935  */
936 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
937                            SIZE_T header_size, int shared_fd, BOOL removable, PVOID *addr_ptr )
938 {
939     IMAGE_DOS_HEADER *dos;
940     IMAGE_NT_HEADERS *nt;
941     IMAGE_SECTION_HEADER *sec;
942     IMAGE_DATA_DIRECTORY *imports;
943     NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
944     int i;
945     off_t pos;
946     struct stat st;
947     struct file_view *view = NULL;
948     char *ptr, *header_end;
949
950     /* zero-map the whole range */
951
952     RtlEnterCriticalSection( &csVirtual );
953
954     if (base >= (char *)0x110000)  /* make sure the DOS area remains free */
955         status = map_view( &view, base, total_size, mask, FALSE,
956                            VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
957
958     if (status == STATUS_CONFLICTING_ADDRESSES)
959         status = map_view( &view, NULL, total_size, mask, FALSE,
960                            VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
961
962     if (status != STATUS_SUCCESS) goto error;
963
964     ptr = view->base;
965     TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
966
967     /* map the header */
968
969     if (fstat( fd, &st ) == -1)
970     {
971         status = FILE_GetNtStatus();
972         goto error;
973     }
974     status = STATUS_INVALID_IMAGE_FORMAT;  /* generic error */
975     if (!st.st_size) goto error;
976     header_size = min( header_size, st.st_size );
977     if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
978                             removable ) != STATUS_SUCCESS) goto error;
979     dos = (IMAGE_DOS_HEADER *)ptr;
980     nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
981     header_end = ptr + ROUND_SIZE( 0, header_size );
982     memset( ptr + header_size, 0, header_end - (ptr + header_size) );
983     if ((char *)(nt + 1) > header_end) goto error;
984     sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
985     if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
986
987     imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
988     if (!imports->Size || !imports->VirtualAddress) imports = NULL;
989
990     /* check the architecture */
991
992     if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
993     {
994         MESSAGE("Trying to load PE image for unsupported architecture (");
995         switch (nt->FileHeader.Machine)
996         {
997         case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
998         case IMAGE_FILE_MACHINE_I860:    MESSAGE("I860"); break;
999         case IMAGE_FILE_MACHINE_R3000:   MESSAGE("R3000"); break;
1000         case IMAGE_FILE_MACHINE_R4000:   MESSAGE("R4000"); break;
1001         case IMAGE_FILE_MACHINE_R10000:  MESSAGE("R10000"); break;
1002         case IMAGE_FILE_MACHINE_ALPHA:   MESSAGE("Alpha"); break;
1003         case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
1004         case IMAGE_FILE_MACHINE_IA64:    MESSAGE("IA-64"); break;
1005         case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
1006         case IMAGE_FILE_MACHINE_AMD64:   MESSAGE("AMD-64"); break;
1007         case IMAGE_FILE_MACHINE_ARM:     MESSAGE("ARM"); break;
1008         default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
1009         }
1010         MESSAGE(")\n");
1011         goto error;
1012     }
1013
1014     /* check for non page-aligned binary */
1015
1016     if (nt->OptionalHeader.SectionAlignment <= page_mask)
1017     {
1018         /* unaligned sections, this happens for native subsystem binaries */
1019         /* in that case Windows simply maps in the whole file */
1020
1021         if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
1022                                 removable ) != STATUS_SUCCESS) goto error;
1023
1024         /* check that all sections are loaded at the right offset */
1025         if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1026         for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1027         {
1028             if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1029                 goto error;  /* Windows refuses to load in that case too */
1030         }
1031
1032         /* set the image protections */
1033         VIRTUAL_SetProt( view, ptr, total_size,
1034                          VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1035
1036         /* perform relocations if necessary */
1037         /* FIXME: not 100% compatible, Windows doesn't do this for non page-aligned binaries */
1038         if (ptr != base)
1039         {
1040             const IMAGE_DATA_DIRECTORY *relocs;
1041             relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1042             if (relocs->VirtualAddress && relocs->Size)
1043                 do_relocations( ptr, relocs, ptr - base, total_size );
1044         }
1045
1046         goto done;
1047     }
1048
1049
1050     /* map all the sections */
1051
1052     for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1053     {
1054         static const SIZE_T sector_align = 0x1ff;
1055         SIZE_T map_size, file_start, file_size, end;
1056
1057         if (!sec->Misc.VirtualSize)
1058             map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1059         else
1060             map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1061
1062         /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1063         file_start = sec->PointerToRawData & ~sector_align;
1064         file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1065         if (file_size > map_size) file_size = map_size;
1066
1067         /* a few sanity checks */
1068         end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1069         if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1070         {
1071             WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1072                            sec->Name, sec->VirtualAddress, map_size, total_size );
1073             goto error;
1074         }
1075
1076         if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1077             (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1078         {
1079             TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1080                             sec->Name, ptr + sec->VirtualAddress,
1081                             sec->PointerToRawData, (int)pos, file_size, map_size,
1082                             sec->Characteristics );
1083             if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1084                                     VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1085                                     FALSE ) != STATUS_SUCCESS)
1086             {
1087                 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1088                 goto error;
1089             }
1090
1091             /* check if the import directory falls inside this section */
1092             if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1093                 imports->VirtualAddress < sec->VirtualAddress + map_size)
1094             {
1095                 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1096                 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1097                 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1098                 if (end > base)
1099                     map_file_into_view( view, shared_fd, base, end - base,
1100                                         pos + (base - sec->VirtualAddress),
1101                                         VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1102                                         FALSE );
1103             }
1104             pos += map_size;
1105             continue;
1106         }
1107
1108         TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1109                         sec->Name, ptr + sec->VirtualAddress,
1110                         sec->PointerToRawData, sec->SizeOfRawData,
1111                         sec->Misc.VirtualSize, sec->Characteristics );
1112
1113         if (!sec->PointerToRawData || !file_size) continue;
1114
1115         /* Note: if the section is not aligned properly map_file_into_view will magically
1116          *       fall back to read(), so we don't need to check anything here.
1117          */
1118         end = file_start + file_size;
1119         if (sec->PointerToRawData >= st.st_size ||
1120             end > ((st.st_size + sector_align) & ~sector_align) ||
1121             end < file_start ||
1122             map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1123                                 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1124                                 removable ) != STATUS_SUCCESS)
1125         {
1126             ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1127             goto error;
1128         }
1129
1130         if (file_size & page_mask)
1131         {
1132             end = ROUND_SIZE( 0, file_size );
1133             if (end > map_size) end = map_size;
1134             TRACE_(module)("clearing %p - %p\n",
1135                            ptr + sec->VirtualAddress + file_size,
1136                            ptr + sec->VirtualAddress + end );
1137             memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1138         }
1139     }
1140
1141
1142     /* perform base relocation, if necessary */
1143
1144     if (ptr != base)
1145     {
1146         const IMAGE_DATA_DIRECTORY *relocs;
1147
1148         relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1149         if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1150         {
1151             WARN( "Need to relocate module from addr %x, but there are no relocation records\n",
1152                   nt->OptionalHeader.ImageBase );
1153             status = STATUS_CONFLICTING_ADDRESSES;
1154             goto error;
1155         }
1156
1157         /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
1158          *        really make sure that the *new* base address is also > 2GB.
1159          *        Some DLLs really check the MSB of the module handle :-/
1160          */
1161         if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((ULONG_PTR)base & 0x80000000))
1162             ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
1163
1164         if (!do_relocations( ptr, relocs, ptr - base, total_size ))
1165         {
1166             goto error;
1167         }
1168     }
1169
1170     /* set the image protections */
1171
1172     VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1173
1174     sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1175     for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1176     {
1177         SIZE_T size;
1178         BYTE vprot = VPROT_COMMITTED;
1179
1180         if (sec->Misc.VirtualSize)
1181             size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1182         else
1183             size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1184
1185         if (sec->Characteristics & IMAGE_SCN_MEM_READ)    vprot |= VPROT_READ;
1186         if (sec->Characteristics & IMAGE_SCN_MEM_WRITE)   vprot |= VPROT_READ|VPROT_WRITECOPY;
1187         if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1188
1189         /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1190         if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1191             (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1192             vprot |= VPROT_EXEC;
1193
1194         VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
1195     }
1196
1197  done:
1198     if (!removable)  /* don't keep handle open on removable media */
1199         NtDuplicateObject( NtCurrentProcess(), hmapping,
1200                            NtCurrentProcess(), &view->mapping,
1201                            0, 0, DUPLICATE_SAME_ACCESS );
1202
1203     RtlLeaveCriticalSection( &csVirtual );
1204
1205     *addr_ptr = ptr;
1206     return STATUS_SUCCESS;
1207
1208  error:
1209     if (view) delete_view( view );
1210     RtlLeaveCriticalSection( &csVirtual );
1211     return status;
1212 }
1213
1214
1215 /***********************************************************************
1216  *           is_current_process
1217  *
1218  * Check whether a process handle is for the current process.
1219  */
1220 BOOL is_current_process( HANDLE handle )
1221 {
1222     BOOL ret = FALSE;
1223
1224     if (handle == NtCurrentProcess()) return TRUE;
1225     SERVER_START_REQ( get_process_info )
1226     {
1227         req->handle = handle;
1228         if (!wine_server_call( req ))
1229             ret = ((DWORD)reply->pid == GetCurrentProcessId());
1230     }
1231     SERVER_END_REQ;
1232     return ret;
1233 }
1234
1235
1236 /***********************************************************************
1237  *           virtual_init
1238  */
1239 void virtual_init(void)
1240 {
1241     const char *preload;
1242 #ifndef page_mask
1243     page_size = getpagesize();
1244     page_mask = page_size - 1;
1245     /* Make sure we have a power of 2 */
1246     assert( !(page_size & page_mask) );
1247     page_shift = 0;
1248     while ((1 << page_shift) != page_size) page_shift++;
1249 #endif  /* page_mask */
1250     if ((preload = getenv("WINEPRELOADRESERVE")))
1251     {
1252         unsigned long start, end;
1253         if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1254         {
1255             preload_reserve_start = (void *)start;
1256             preload_reserve_end = (void *)end;
1257         }
1258     }
1259 }
1260
1261
1262 /***********************************************************************
1263  *           virtual_init_threading
1264  */
1265 void virtual_init_threading(void)
1266 {
1267     use_locks = 1;
1268 }
1269
1270
1271 /***********************************************************************
1272  *           VIRTUAL_HandleFault
1273  */
1274 NTSTATUS VIRTUAL_HandleFault( LPCVOID addr )
1275 {
1276     FILE_VIEW *view;
1277     NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1278
1279     RtlEnterCriticalSection( &csVirtual );
1280     if ((view = VIRTUAL_FindView( addr )))
1281     {
1282         void *page = ROUND_ADDR( addr, page_mask );
1283         BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1284         if (vprot & VPROT_GUARD)
1285         {
1286             VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1287             ret = STATUS_GUARD_PAGE_VIOLATION;
1288         }
1289     }
1290     RtlLeaveCriticalSection( &csVirtual );
1291     return ret;
1292 }
1293
1294
1295 /***********************************************************************
1296  *           VIRTUAL_SetForceExec
1297  *
1298  * Whether to force exec prot on all views.
1299  */
1300 void VIRTUAL_SetForceExec( BOOL enable )
1301 {
1302     struct file_view *view;
1303
1304     RtlEnterCriticalSection( &csVirtual );
1305     if (!force_exec_prot != !enable)  /* change all existing views */
1306     {
1307         force_exec_prot = enable;
1308
1309         LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1310         {
1311             UINT i, count;
1312             int unix_prot;
1313             char *addr = view->base;
1314             BYTE prot = view->prot[0];
1315
1316             for (count = i = 1; i < view->size >> page_shift; i++, count++)
1317             {
1318                 if (view->prot[i] == prot) continue;
1319                 unix_prot = VIRTUAL_GetUnixProt( prot );
1320                 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1321                 {
1322                     TRACE( "%s exec prot for %p-%p\n",
1323                            force_exec_prot ? "enabling" : "disabling",
1324                            addr, addr + (count << page_shift) - 1 );
1325                     mprotect( addr, count << page_shift,
1326                               unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1327                 }
1328                 addr += (count << page_shift);
1329                 prot = view->prot[i];
1330                 count = 0;
1331             }
1332             if (count)
1333             {
1334                 unix_prot = VIRTUAL_GetUnixProt( prot );
1335                 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1336                 {
1337                     TRACE( "%s exec prot for %p-%p\n",
1338                            force_exec_prot ? "enabling" : "disabling",
1339                            addr, addr + (count << page_shift) - 1 );
1340                     mprotect( addr, count << page_shift,
1341                               unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1342                 }
1343             }
1344         }
1345     }
1346     RtlLeaveCriticalSection( &csVirtual );
1347 }
1348
1349
1350 /***********************************************************************
1351  *           VIRTUAL_UseLargeAddressSpace
1352  *
1353  * Increase the address space size for apps that support it.
1354  */
1355 void VIRTUAL_UseLargeAddressSpace(void)
1356 {
1357     /* no large address space on win9x */
1358     if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1359     user_space_limit = ADDRESS_SPACE_LIMIT;
1360 }
1361
1362
1363 /***********************************************************************
1364  *             NtAllocateVirtualMemory   (NTDLL.@)
1365  *             ZwAllocateVirtualMemory   (NTDLL.@)
1366  */
1367 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1368                                          SIZE_T *size_ptr, ULONG type, ULONG protect )
1369 {
1370     void *base;
1371     BYTE vprot;
1372     SIZE_T size = *size_ptr;
1373     SIZE_T mask = get_mask( zero_bits );
1374     NTSTATUS status = STATUS_SUCCESS;
1375     struct file_view *view;
1376
1377     TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1378
1379     if (!size) return STATUS_INVALID_PARAMETER;
1380
1381     if (!is_current_process( process ))
1382     {
1383         ERR("Unsupported on other process\n");
1384         return STATUS_ACCESS_DENIED;
1385     }
1386
1387     /* Round parameters to a page boundary */
1388
1389     if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
1390
1391     if (*ret)
1392     {
1393         if (type & MEM_RESERVE) /* Round down to 64k boundary */
1394             base = ROUND_ADDR( *ret, mask );
1395         else
1396             base = ROUND_ADDR( *ret, page_mask );
1397         size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1398
1399         /* disallow low 64k, wrap-around and kernel space */
1400         if (((char *)base < (char *)0x10000) ||
1401             ((char *)base + size < (char *)base) ||
1402             is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
1403             return STATUS_INVALID_PARAMETER;
1404     }
1405     else
1406     {
1407         base = NULL;
1408         size = (size + page_mask) & ~page_mask;
1409     }
1410
1411     /* Compute the alloc type flags */
1412
1413     if (!(type & MEM_SYSTEM))
1414     {
1415         if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
1416             (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1417         {
1418             WARN("called with wrong alloc type flags (%08x) !\n", type);
1419             return STATUS_INVALID_PARAMETER;
1420         }
1421         if (type & MEM_WRITE_WATCH)
1422         {
1423             FIXME("MEM_WRITE_WATCH type not supported\n");
1424             return STATUS_NOT_SUPPORTED;
1425         }
1426     }
1427     vprot = VIRTUAL_GetProt( protect );
1428     if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1429
1430     /* Reserve the memory */
1431
1432     if (use_locks) RtlEnterCriticalSection( &csVirtual );
1433
1434     if (type & MEM_SYSTEM)
1435     {
1436         if (type & MEM_IMAGE) vprot |= VPROT_IMAGE;
1437         status = create_view( &view, base, size, vprot | VPROT_COMMITTED );
1438         if (status == STATUS_SUCCESS)
1439         {
1440             view->flags |= VFLAG_VALLOC | VFLAG_SYSTEM;
1441             base = view->base;
1442         }
1443     }
1444     else if ((type & MEM_RESERVE) || !base)
1445     {
1446         status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1447         if (status == STATUS_SUCCESS)
1448         {
1449             view->flags |= VFLAG_VALLOC;
1450             base = view->base;
1451         }
1452     }
1453     else  /* commit the pages */
1454     {
1455         if (!(view = VIRTUAL_FindView( base )) ||
1456             ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
1457         else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1458     }
1459
1460     if (use_locks) RtlLeaveCriticalSection( &csVirtual );
1461
1462     if (status == STATUS_SUCCESS)
1463     {
1464         *ret = base;
1465         *size_ptr = size;
1466     }
1467     return status;
1468 }
1469
1470
1471 /***********************************************************************
1472  *             NtFreeVirtualMemory   (NTDLL.@)
1473  *             ZwFreeVirtualMemory   (NTDLL.@)
1474  */
1475 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1476 {
1477     FILE_VIEW *view;
1478     char *base;
1479     NTSTATUS status = STATUS_SUCCESS;
1480     LPVOID addr = *addr_ptr;
1481     SIZE_T size = *size_ptr;
1482
1483     TRACE("%p %p %08lx %x\n", process, addr, size, type );
1484
1485     if (!is_current_process( process ))
1486     {
1487         ERR("Unsupported on other process\n");
1488         return STATUS_ACCESS_DENIED;
1489     }
1490
1491     /* Fix the parameters */
1492
1493     size = ROUND_SIZE( addr, size );
1494     base = ROUND_ADDR( addr, page_mask );
1495
1496     /* avoid freeing the DOS area when a broken app passes a NULL pointer */
1497     if (!base && !(type & MEM_SYSTEM)) return STATUS_INVALID_PARAMETER;
1498
1499     RtlEnterCriticalSection(&csVirtual);
1500
1501     if (!(view = VIRTUAL_FindView( base )) ||
1502         (base + size > (char *)view->base + view->size) ||
1503         !(view->flags & VFLAG_VALLOC))
1504     {
1505         status = STATUS_INVALID_PARAMETER;
1506     }
1507     else if (type & MEM_SYSTEM)
1508     {
1509         /* return the values that the caller should use to unmap the area */
1510         *addr_ptr = view->base;
1511         if (!wine_mmap_is_in_reserved_area( view->base, view->size )) *size_ptr = view->size;
1512         else *size_ptr = 0;  /* make sure we don't munmap anything from a reserved area */
1513         view->flags |= VFLAG_SYSTEM;
1514         delete_view( view );
1515     }
1516     else if (type == MEM_RELEASE)
1517     {
1518         /* Free the pages */
1519
1520         if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1521         else
1522         {
1523             delete_view( view );
1524             *addr_ptr = base;
1525             *size_ptr = size;
1526         }
1527     }
1528     else if (type == MEM_DECOMMIT)
1529     {
1530         status = decommit_pages( view, base - (char *)view->base, size );
1531         if (status == STATUS_SUCCESS)
1532         {
1533             *addr_ptr = base;
1534             *size_ptr = size;
1535         }
1536     }
1537     else
1538     {
1539         WARN("called with wrong free type flags (%08x) !\n", type);
1540         status = STATUS_INVALID_PARAMETER;
1541     }
1542
1543     RtlLeaveCriticalSection(&csVirtual);
1544     return status;
1545 }
1546
1547
1548 /***********************************************************************
1549  *             NtProtectVirtualMemory   (NTDLL.@)
1550  *             ZwProtectVirtualMemory   (NTDLL.@)
1551  */
1552 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1553                                         ULONG new_prot, ULONG *old_prot )
1554 {
1555     FILE_VIEW *view;
1556     NTSTATUS status = STATUS_SUCCESS;
1557     char *base;
1558     UINT i;
1559     BYTE vprot, *p;
1560     ULONG prot;
1561     SIZE_T size = *size_ptr;
1562     LPVOID addr = *addr_ptr;
1563
1564     TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
1565
1566     if (!is_current_process( process ))
1567     {
1568         ERR("Unsupported on other process\n");
1569         return STATUS_ACCESS_DENIED;
1570     }
1571
1572     /* Fix the parameters */
1573
1574     size = ROUND_SIZE( addr, size );
1575     base = ROUND_ADDR( addr, page_mask );
1576
1577     RtlEnterCriticalSection( &csVirtual );
1578
1579     if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1580     {
1581         status = STATUS_INVALID_PARAMETER;
1582     }
1583     else
1584     {
1585         /* Make sure all the pages are committed */
1586
1587         p = view->prot + ((base - (char *)view->base) >> page_shift);
1588         prot = VIRTUAL_GetWin32Prot( *p );
1589         for (i = size >> page_shift; i; i--, p++)
1590         {
1591             if (!(*p & VPROT_COMMITTED))
1592             {
1593                 status = STATUS_NOT_COMMITTED;
1594                 break;
1595             }
1596         }
1597         if (!i)
1598         {
1599             if (old_prot) *old_prot = prot;
1600             vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1601             if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1602         }
1603     }
1604     RtlLeaveCriticalSection( &csVirtual );
1605
1606     if (status == STATUS_SUCCESS)
1607     {
1608         *addr_ptr = base;
1609         *size_ptr = size;
1610     }
1611     return status;
1612 }
1613
1614 #define UNIMPLEMENTED_INFO_CLASS(c) \
1615     case c: \
1616         FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
1617         return STATUS_INVALID_INFO_CLASS
1618
1619 /***********************************************************************
1620  *             NtQueryVirtualMemory   (NTDLL.@)
1621  *             ZwQueryVirtualMemory   (NTDLL.@)
1622  */
1623 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1624                                       MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1625                                       SIZE_T len, SIZE_T *res_len )
1626 {
1627     FILE_VIEW *view;
1628     char *base, *alloc_base = 0;
1629     struct list *ptr;
1630     SIZE_T size = 0;
1631     MEMORY_BASIC_INFORMATION *info = buffer;
1632
1633     if (info_class != MemoryBasicInformation)
1634     {
1635         switch(info_class)
1636         {
1637             UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
1638             UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
1639             UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
1640
1641             default:
1642                 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n", 
1643                       process, addr, info_class, buffer, len, res_len);
1644                 return STATUS_INVALID_INFO_CLASS;
1645         }
1646     }
1647     if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1648         return STATUS_WORKING_SET_LIMIT_RANGE;
1649
1650     if (!is_current_process( process ))
1651     {
1652         ERR("Unsupported on other process\n");
1653         return STATUS_ACCESS_DENIED;
1654     }
1655
1656     base = ROUND_ADDR( addr, page_mask );
1657
1658     /* Find the view containing the address */
1659
1660     RtlEnterCriticalSection(&csVirtual);
1661     ptr = list_head( &views_list );
1662     for (;;)
1663     {
1664         if (!ptr)
1665         {
1666             /* make the address space end at the user limit, except if
1667              * the last view was mapped beyond that */
1668             if (alloc_base <= (char *)user_space_limit)
1669             {
1670                 if (user_space_limit && base >= (char *)user_space_limit)
1671                 {
1672                     RtlLeaveCriticalSection( &csVirtual );
1673                     return STATUS_WORKING_SET_LIMIT_RANGE;
1674                 }
1675                 size = (char *)user_space_limit - alloc_base;
1676             }
1677             else size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1678             view = NULL;
1679             break;
1680         }
1681         view = LIST_ENTRY( ptr, struct file_view, entry );
1682         if ((char *)view->base > base)
1683         {
1684             size = (char *)view->base - alloc_base;
1685             view = NULL;
1686             break;
1687         }
1688         if ((char *)view->base + view->size > base)
1689         {
1690             alloc_base = view->base;
1691             size = view->size;
1692             break;
1693         }
1694         alloc_base = (char *)view->base + view->size;
1695         ptr = list_next( &views_list, ptr );
1696     }
1697
1698     /* Fill the info structure */
1699
1700     if (!view)
1701     {
1702         info->State             = MEM_FREE;
1703         info->Protect           = PAGE_NOACCESS;
1704         info->AllocationBase    = 0;
1705         info->AllocationProtect = 0;
1706         info->Type              = 0;
1707     }
1708     else
1709     {
1710         BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1711         info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
1712         info->Protect = VIRTUAL_GetWin32Prot( vprot );
1713         info->AllocationBase = alloc_base;
1714         info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
1715         if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1716         else if (view->flags & VFLAG_VALLOC) info->Type = MEM_PRIVATE;
1717         else info->Type = MEM_MAPPED;
1718         for (size = base - alloc_base; size < view->size; size += page_size)
1719             if (view->prot[size >> page_shift] != vprot) break;
1720     }
1721     RtlLeaveCriticalSection(&csVirtual);
1722
1723     info->BaseAddress    = base;
1724     info->RegionSize     = size - (base - alloc_base);
1725     if (res_len) *res_len = sizeof(*info);
1726     return STATUS_SUCCESS;
1727 }
1728
1729
1730 /***********************************************************************
1731  *             NtLockVirtualMemory   (NTDLL.@)
1732  *             ZwLockVirtualMemory   (NTDLL.@)
1733  */
1734 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1735 {
1736     if (!is_current_process( process ))
1737     {
1738         ERR("Unsupported on other process\n");
1739         return STATUS_ACCESS_DENIED;
1740     }
1741     return STATUS_SUCCESS;
1742 }
1743
1744
1745 /***********************************************************************
1746  *             NtUnlockVirtualMemory   (NTDLL.@)
1747  *             ZwUnlockVirtualMemory   (NTDLL.@)
1748  */
1749 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1750 {
1751     if (!is_current_process( process ))
1752     {
1753         ERR("Unsupported on other process\n");
1754         return STATUS_ACCESS_DENIED;
1755     }
1756     return STATUS_SUCCESS;
1757 }
1758
1759
1760 /***********************************************************************
1761  *             NtCreateSection   (NTDLL.@)
1762  *             ZwCreateSection   (NTDLL.@)
1763  */
1764 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1765                                  const LARGE_INTEGER *size, ULONG protect,
1766                                  ULONG sec_flags, HANDLE file )
1767 {
1768     NTSTATUS ret;
1769     BYTE vprot;
1770     DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
1771
1772     /* Check parameters */
1773
1774     if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1775
1776     vprot = VIRTUAL_GetProt( protect );
1777     if (sec_flags & SEC_RESERVE)
1778     {
1779         if (file) return STATUS_INVALID_PARAMETER;
1780     }
1781     else vprot |= VPROT_COMMITTED;
1782     if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1783     if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
1784
1785     /* Create the server object */
1786
1787     SERVER_START_REQ( create_mapping )
1788     {
1789         req->access      = access;
1790         req->attributes  = (attr) ? attr->Attributes : 0;
1791         req->rootdir     = attr ? attr->RootDirectory : 0;
1792         req->file_handle = file;
1793         req->size_high   = size ? size->u.HighPart : 0;
1794         req->size_low    = size ? size->u.LowPart : 0;
1795         req->protect     = vprot;
1796         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
1797         ret = wine_server_call( req );
1798         *handle = reply->handle;
1799     }
1800     SERVER_END_REQ;
1801     return ret;
1802 }
1803
1804
1805 /***********************************************************************
1806  *             NtOpenSection   (NTDLL.@)
1807  *             ZwOpenSection   (NTDLL.@)
1808  */
1809 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1810 {
1811     NTSTATUS ret;
1812     DWORD len = attr->ObjectName->Length;
1813
1814     if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1815
1816     SERVER_START_REQ( open_mapping )
1817     {
1818         req->access  = access;
1819         req->attributes = (attr) ? attr->Attributes : 0;
1820         req->rootdir = attr ? attr->RootDirectory : 0;
1821         wine_server_add_data( req, attr->ObjectName->Buffer, len );
1822         if (!(ret = wine_server_call( req ))) *handle = reply->handle;
1823     }
1824     SERVER_END_REQ;
1825     return ret;
1826 }
1827
1828
1829 /***********************************************************************
1830  *             NtMapViewOfSection   (NTDLL.@)
1831  *             ZwMapViewOfSection   (NTDLL.@)
1832  */
1833 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
1834                                     SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
1835                                     SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
1836 {
1837     NTSTATUS res;
1838     SIZE_T size = 0;
1839     SIZE_T mask = get_mask( zero_bits );
1840     int unix_handle = -1, flags, needs_close;
1841     int prot;
1842     void *base;
1843     struct file_view *view;
1844     DWORD size_low, size_high, header_size, shared_size;
1845     HANDLE shared_file;
1846     BOOL removable = FALSE;
1847     LARGE_INTEGER offset;
1848
1849     offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
1850
1851     TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
1852           handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, size, protect );
1853
1854     if (!is_current_process( process ))
1855     {
1856         ERR("Unsupported on other process\n");
1857         return STATUS_ACCESS_DENIED;
1858     }
1859
1860     /* Check parameters */
1861
1862     if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
1863         return STATUS_INVALID_PARAMETER;
1864
1865     SERVER_START_REQ( get_mapping_info )
1866     {
1867         req->handle = handle;
1868         res = wine_server_call( req );
1869         prot        = reply->protect;
1870         base        = reply->base;
1871         size_low    = reply->size_low;
1872         size_high   = reply->size_high;
1873         header_size = reply->header_size;
1874         shared_file = reply->shared_file;
1875         shared_size = reply->shared_size;
1876     }
1877     SERVER_END_REQ;
1878     if (res) return res;
1879
1880     if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, &flags ))) return res;
1881     removable = (flags & FD_FLAG_REMOVABLE) != 0;
1882
1883     if (prot & VPROT_IMAGE)
1884     {
1885         if (shared_file)
1886         {
1887             int shared_fd, shared_needs_close;
1888
1889             if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
1890                                            &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
1891             res = map_image( handle, unix_handle, base, size_low, mask, header_size,
1892                              shared_fd, removable, addr_ptr );
1893             if (shared_needs_close) close( shared_fd );
1894             NtClose( shared_file );
1895         }
1896         else
1897         {
1898             res = map_image( handle, unix_handle, base, size_low, mask, header_size,
1899                              -1, removable, addr_ptr );
1900         }
1901         if (needs_close) close( unix_handle );
1902         if (!res) *size_ptr = size_low;
1903         return res;
1904     }
1905
1906     if (size_high)
1907         ERR("Sizes larger than 4Gb not supported\n");
1908
1909     if ((offset.u.LowPart >= size_low) ||
1910         (*size_ptr > size_low - offset.u.LowPart))
1911     {
1912         res = STATUS_INVALID_PARAMETER;
1913         goto done;
1914     }
1915     if (*size_ptr) size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
1916     else size = size_low - offset.u.LowPart;
1917
1918     switch(protect)
1919     {
1920     case PAGE_NOACCESS:
1921         break;
1922     case PAGE_READWRITE:
1923     case PAGE_EXECUTE_READWRITE:
1924         if (!(prot & VPROT_WRITE))
1925         {
1926             res = STATUS_INVALID_PARAMETER;
1927             goto done;
1928         }
1929         removable = FALSE;
1930         /* fall through */
1931     case PAGE_READONLY:
1932     case PAGE_WRITECOPY:
1933     case PAGE_EXECUTE:
1934     case PAGE_EXECUTE_READ:
1935     case PAGE_EXECUTE_WRITECOPY:
1936         if (prot & VPROT_READ) break;
1937         /* fall through */
1938     default:
1939         res = STATUS_INVALID_PARAMETER;
1940         goto done;
1941     }
1942
1943     /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1944      * which has a view of this mapping commits some pages, they will
1945      * appear committed in all other processes, which have the same
1946      * view created. Since we don't support this yet, we create the
1947      * whole mapping committed.
1948      */
1949     prot |= VPROT_COMMITTED;
1950
1951     /* Reserve a properly aligned area */
1952
1953     RtlEnterCriticalSection( &csVirtual );
1954
1955     res = map_view( &view, *addr_ptr, size, mask, FALSE, prot );
1956     if (res)
1957     {
1958         RtlLeaveCriticalSection( &csVirtual );
1959         goto done;
1960     }
1961
1962     /* Map the file */
1963
1964     TRACE("handle=%p size=%lx offset=%x%08x\n",
1965           handle, size, offset.u.HighPart, offset.u.LowPart );
1966
1967     res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, prot, removable );
1968     if (res == STATUS_SUCCESS)
1969     {
1970         if (!removable)  /* don't keep handle open on removable media */
1971             NtDuplicateObject( NtCurrentProcess(), handle,
1972                                NtCurrentProcess(), &view->mapping,
1973                                0, 0, DUPLICATE_SAME_ACCESS );
1974
1975         *addr_ptr = view->base;
1976         *size_ptr = size;
1977     }
1978     else
1979     {
1980         ERR( "map_file_into_view %p %lx %x%08x failed\n",
1981              view->base, size, offset.u.HighPart, offset.u.LowPart );
1982         delete_view( view );
1983     }
1984
1985     RtlLeaveCriticalSection( &csVirtual );
1986
1987 done:
1988     if (needs_close) close( unix_handle );
1989     return res;
1990 }
1991
1992
1993 /***********************************************************************
1994  *             NtUnmapViewOfSection   (NTDLL.@)
1995  *             ZwUnmapViewOfSection   (NTDLL.@)
1996  */
1997 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
1998 {
1999     FILE_VIEW *view;
2000     NTSTATUS status = STATUS_INVALID_PARAMETER;
2001     void *base = ROUND_ADDR( addr, page_mask );
2002
2003     if (!is_current_process( process ))
2004     {
2005         ERR("Unsupported on other process\n");
2006         return STATUS_ACCESS_DENIED;
2007     }
2008     RtlEnterCriticalSection( &csVirtual );
2009     if ((view = VIRTUAL_FindView( base )) && (base == view->base))
2010     {
2011         delete_view( view );
2012         status = STATUS_SUCCESS;
2013     }
2014     RtlLeaveCriticalSection( &csVirtual );
2015     return status;
2016 }
2017
2018
2019 /***********************************************************************
2020  *             NtFlushVirtualMemory   (NTDLL.@)
2021  *             ZwFlushVirtualMemory   (NTDLL.@)
2022  */
2023 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2024                                       SIZE_T *size_ptr, ULONG unknown )
2025 {
2026     FILE_VIEW *view;
2027     NTSTATUS status = STATUS_SUCCESS;
2028     void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2029
2030     if (!is_current_process( process ))
2031     {
2032         ERR("Unsupported on other process\n");
2033         return STATUS_ACCESS_DENIED;
2034     }
2035     RtlEnterCriticalSection( &csVirtual );
2036     if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
2037     else
2038     {
2039         if (!*size_ptr) *size_ptr = view->size;
2040         *addr_ptr = addr;
2041         if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2042     }
2043     RtlLeaveCriticalSection( &csVirtual );
2044     return status;
2045 }
2046
2047
2048 /***********************************************************************
2049  *             NtReadVirtualMemory   (NTDLL.@)
2050  *             ZwReadVirtualMemory   (NTDLL.@)
2051  */
2052 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2053                                      SIZE_T size, SIZE_T *bytes_read )
2054 {
2055     NTSTATUS status;
2056
2057     SERVER_START_REQ( read_process_memory )
2058     {
2059         req->handle = process;
2060         req->addr   = (void *)addr;
2061         wine_server_set_reply( req, buffer, size );
2062         if ((status = wine_server_call( req ))) size = 0;
2063     }
2064     SERVER_END_REQ;
2065     if (bytes_read) *bytes_read = size;
2066     return status;
2067 }
2068
2069
2070 /***********************************************************************
2071  *             NtWriteVirtualMemory   (NTDLL.@)
2072  *             ZwWriteVirtualMemory   (NTDLL.@)
2073  */
2074 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2075                                       SIZE_T size, SIZE_T *bytes_written )
2076 {
2077     NTSTATUS status;
2078
2079     SERVER_START_REQ( write_process_memory )
2080     {
2081         req->handle     = process;
2082         req->addr       = addr;
2083         wine_server_add_data( req, buffer, size );
2084         if ((status = wine_server_call( req ))) size = 0;
2085     }
2086     SERVER_END_REQ;
2087     if (bytes_written) *bytes_written = size;
2088     return status;
2089 }