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