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