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