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