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