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