Fixed type and protection values returned by NtQueryVirtualMemory to
[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     sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
742     for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
743     {
744         DWORD size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
745         BYTE vprot = VPROT_COMMITTED;
746         if (sec->Characteristics & IMAGE_SCN_MEM_READ)    vprot |= VPROT_READ;
747         if (sec->Characteristics & IMAGE_SCN_MEM_WRITE)   vprot |= VPROT_WRITE|VPROT_WRITECOPY;
748         if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
749
750         /* make sure the import directory is writable */
751         if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
752             imports->VirtualAddress < sec->VirtualAddress + size)
753             vprot |= VPROT_READ|VPROT_WRITE|VPROT_WRITECOPY;
754
755         VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
756     }
757
758     close( fd );
759     *addr_ptr = ptr;
760     return STATUS_SUCCESS;
761
762  error:
763     if (ptr != (char *)-1) munmap( ptr, total_size );
764     close( fd );
765     return status;
766 }
767
768
769 /***********************************************************************
770  *           is_current_process
771  *
772  * Check whether a process handle is for the current process.
773  */
774 static BOOL is_current_process( HANDLE handle )
775 {
776     BOOL ret = FALSE;
777
778     if (handle == GetCurrentProcess()) return TRUE;
779     SERVER_START_REQ( get_process_info )
780     {
781         req->handle = handle;
782         if (!wine_server_call( req ))
783             ret = ((DWORD)reply->pid == GetCurrentProcessId());
784     }
785     SERVER_END_REQ;
786     return ret;
787 }
788
789
790 /***********************************************************************
791  *           VIRTUAL_Init
792  */
793 #ifndef page_mask
794 DECL_GLOBAL_CONSTRUCTOR(VIRTUAL_Init)
795 {
796     page_size = getpagesize();
797     page_mask = page_size - 1;
798     /* Make sure we have a power of 2 */
799     assert( !(page_size & page_mask) );
800     page_shift = 0;
801     while ((1 << page_shift) != page_size) page_shift++;
802 }
803 #endif  /* page_mask */
804
805
806 /***********************************************************************
807  *           VIRTUAL_SetFaultHandler
808  */
809 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
810 {
811     FILE_VIEW *view;
812
813     if (!(view = VIRTUAL_FindView( addr ))) return FALSE;
814     view->handlerProc = proc;
815     view->handlerArg  = arg;
816     return TRUE;
817 }
818
819 /***********************************************************************
820  *           VIRTUAL_HandleFault
821  */
822 DWORD VIRTUAL_HandleFault( LPCVOID addr )
823 {
824     FILE_VIEW *view = VIRTUAL_FindView( addr );
825     DWORD ret = EXCEPTION_ACCESS_VIOLATION;
826
827     if (view)
828     {
829         if (view->handlerProc)
830         {
831             if (view->handlerProc(view->handlerArg, addr)) ret = 0;  /* handled */
832         }
833         else
834         {
835             BYTE vprot = view->prot[((char *)addr - (char *)view->base) >> page_shift];
836             void *page = (void *)((UINT_PTR)addr & ~page_mask);
837             char *stack = (char *)NtCurrentTeb()->DeallocationStack + SIGNAL_STACK_SIZE;
838             if (vprot & VPROT_GUARD)
839             {
840                 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
841                 ret = STATUS_GUARD_PAGE_VIOLATION;
842             }
843             /* is it inside the stack guard page? */
844             if (((char *)addr >= stack) && ((char *)addr < stack + (page_mask+1)))
845                 ret = STATUS_STACK_OVERFLOW;
846         }
847     }
848     return ret;
849 }
850
851
852
853 /***********************************************************************
854  *           unaligned_mmap
855  *
856  * Linux kernels before 2.4.x can support non page-aligned offsets, as
857  * long as the offset is aligned to the filesystem block size. This is
858  * a big performance gain so we want to take advantage of it.
859  *
860  * However, when we use 64-bit file support this doesn't work because
861  * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
862  * in that it rounds unaligned offsets down to a page boundary. For
863  * these reasons we do a direct system call here.
864  */
865 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
866                              unsigned int flags, int fd, unsigned int offset_low,
867                              unsigned int offset_high )
868 {
869 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
870     if (!offset_high && (offset_low & page_mask))
871     {
872         int ret;
873
874         struct
875         {
876             void        *addr;
877             unsigned int length;
878             unsigned int prot;
879             unsigned int flags;
880             unsigned int fd;
881             unsigned int offset;
882         } args;
883
884         args.addr   = addr;
885         args.length = length;
886         args.prot   = prot;
887         args.flags  = flags;
888         args.fd     = fd;
889         args.offset = offset_low;
890
891         __asm__ __volatile__("push %%ebx\n\t"
892                              "movl %2,%%ebx\n\t"
893                              "int $0x80\n\t"
894                              "popl %%ebx"
895                              : "=a" (ret)
896                              : "0" (90), /* SYS_mmap */
897                                "g" (&args) );
898         if (ret < 0 && ret > -4096)
899         {
900             errno = -ret;
901             ret = -1;
902         }
903         return (void *)ret;
904     }
905 #endif
906     return mmap( addr, length, prot, flags, fd, ((off_t)offset_high << 32) | offset_low );
907 }
908
909
910 /***********************************************************************
911  *           VIRTUAL_mmap
912  *
913  * Wrapper for mmap() that handles anonymous mappings portably,
914  * and falls back to read if mmap of a file fails.
915  */
916 static LPVOID VIRTUAL_mmap( int fd, LPVOID start, DWORD size,
917                             DWORD offset_low, DWORD offset_high,
918                             int prot, int flags, BOOL *removable )
919 {
920     LPVOID ret;
921     off_t offset;
922     BOOL is_shared_write = FALSE;
923
924     if (fd == -1) return wine_anon_mmap( start, size, prot, flags );
925
926     if (prot & PROT_WRITE)
927     {
928 #ifdef MAP_SHARED
929         if (flags & MAP_SHARED) is_shared_write = TRUE;
930 #endif
931 #ifdef MAP_PRIVATE
932         if (!(flags & MAP_PRIVATE)) is_shared_write = TRUE;
933 #endif
934     }
935
936     if (removable && *removable)
937     {
938         /* if on removable media, try using read instead of mmap */
939         if (!is_shared_write) goto fake_mmap;
940         *removable = FALSE;
941     }
942
943     if ((ret = unaligned_mmap( start, size, prot, flags, fd,
944                                offset_low, offset_high )) != (LPVOID)-1) return ret;
945
946     /* mmap() failed; if this is because the file offset is not    */
947     /* page-aligned (EINVAL), or because the underlying filesystem */
948     /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
949
950     if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return ret;
951     if (is_shared_write) return ret;  /* we cannot fake shared write mappings */
952
953  fake_mmap:
954     /* Reserve the memory with an anonymous mmap */
955     ret = wine_anon_mmap( start, size, PROT_READ | PROT_WRITE, flags );
956     if (ret == (LPVOID)-1) return ret;
957     /* Now read in the file */
958     offset = ((off_t)offset_high << 32) | offset_low;
959     pread( fd, ret, size, offset );
960     mprotect( ret, size, prot );  /* Set the right protection */
961     return ret;
962 }
963
964
965 /***********************************************************************
966  *             NtAllocateVirtualMemory   (NTDLL.@)
967  *             ZwAllocateVirtualMemory   (NTDLL.@)
968  */
969 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, PVOID addr,
970                                          ULONG *size_ptr, ULONG type, ULONG protect )
971 {
972     FILE_VIEW *view;
973     void *base;
974     BYTE vprot;
975     DWORD size = *size_ptr;
976
977     if (!is_current_process( process ))
978     {
979         ERR("Unsupported on other process\n");
980         return STATUS_ACCESS_DENIED;
981     }
982
983     TRACE("%p %08lx %lx %08lx\n", addr, size, type, protect );
984
985     /* Round parameters to a page boundary */
986
987     if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
988
989     if (addr)
990     {
991         if (type & MEM_RESERVE) /* Round down to 64k boundary */
992             base = ROUND_ADDR( addr, granularity_mask );
993         else
994             base = ROUND_ADDR( addr, page_mask );
995         size = (((UINT_PTR)addr + size + page_mask) & ~page_mask) - (UINT_PTR)base;
996
997         /* disallow low 64k, wrap-around and kernel space */
998         if (((char *)base <= (char *)granularity_mask) ||
999             ((char *)base + size < (char *)base) ||
1000             (ADDRESS_SPACE_LIMIT && ((char *)base + size > (char *)ADDRESS_SPACE_LIMIT)))
1001             return STATUS_INVALID_PARAMETER;
1002     }
1003     else
1004     {
1005         base = NULL;
1006         size = (size + page_mask) & ~page_mask;
1007     }
1008
1009     if (type & MEM_TOP_DOWN) {
1010         /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
1011          *        Is there _ANY_ way to do it with UNIX mmap()?
1012          */
1013         WARN("MEM_TOP_DOWN ignored\n");
1014         type &= ~MEM_TOP_DOWN;
1015     }
1016
1017     /* Compute the alloc type flags */
1018
1019     if (type & MEM_SYSTEM)
1020     {
1021         vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
1022         if (type & MEM_IMAGE) vprot |= VPROT_IMAGE;
1023     }
1024     else
1025     {
1026         if (!(type & (MEM_COMMIT | MEM_RESERVE)) || (type & ~(MEM_COMMIT | MEM_RESERVE)))
1027         {
1028             WARN("called with wrong alloc type flags (%08lx) !\n", type);
1029             return STATUS_INVALID_PARAMETER;
1030         }
1031         if (type & MEM_COMMIT)
1032             vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
1033         else
1034             vprot = 0;
1035     }
1036
1037     /* Reserve the memory */
1038
1039     if (type & MEM_SYSTEM)
1040     {
1041         if (!(view = VIRTUAL_CreateView( base, size, VFLAG_VALLOC | VFLAG_SYSTEM, vprot, 0 )))
1042             return STATUS_NO_MEMORY;
1043     }
1044     else if ((type & MEM_RESERVE) || !base)
1045     {
1046         NTSTATUS res = anon_mmap_aligned( &base, size, VIRTUAL_GetUnixProt( vprot ), 0 );
1047         if (res) return res;
1048
1049         if (!(view = VIRTUAL_CreateView( base, size, VFLAG_VALLOC, vprot, 0 )))
1050         {
1051             munmap( base, size );
1052             return STATUS_NO_MEMORY;
1053         }
1054     }
1055     else
1056     {
1057         /* Commit the pages */
1058
1059         if (!(view = VIRTUAL_FindView( base )) ||
1060             ((char *)base + size > (char *)view->base + view->size)) return STATUS_NOT_MAPPED_VIEW;
1061
1062         if (!VIRTUAL_SetProt( view, base, size, vprot )) return STATUS_ACCESS_DENIED;
1063     }
1064
1065     *ret = base;
1066     *size_ptr = size;
1067     return STATUS_SUCCESS;
1068 }
1069
1070
1071 /***********************************************************************
1072  *             NtFreeVirtualMemory   (NTDLL.@)
1073  *             ZwFreeVirtualMemory   (NTDLL.@)
1074  */
1075 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr, ULONG type )
1076 {
1077     FILE_VIEW *view;
1078     char *base;
1079     LPVOID addr = *addr_ptr;
1080     DWORD size = *size_ptr;
1081
1082     if (!is_current_process( process ))
1083     {
1084         ERR("Unsupported on other process\n");
1085         return STATUS_ACCESS_DENIED;
1086     }
1087
1088     TRACE("%p %08lx %lx\n", addr, size, type );
1089
1090     /* Fix the parameters */
1091
1092     size = ROUND_SIZE( addr, size );
1093     base = ROUND_ADDR( addr, page_mask );
1094
1095     if (!(view = VIRTUAL_FindView( base )) ||
1096         (base + size > (char *)view->base + view->size) ||
1097         !(view->flags & VFLAG_VALLOC))
1098         return STATUS_INVALID_PARAMETER;
1099
1100     /* Check the type */
1101
1102     if (type & MEM_SYSTEM)
1103     {
1104         view->flags |= VFLAG_SYSTEM;
1105         type &= ~MEM_SYSTEM;
1106     }
1107
1108     if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
1109     {
1110         ERR("called with wrong free type flags (%08lx) !\n", type);
1111         return STATUS_INVALID_PARAMETER;
1112     }
1113
1114     /* Free the pages */
1115
1116     if (type == MEM_RELEASE)
1117     {
1118         if (size || (base != view->base)) return STATUS_INVALID_PARAMETER;
1119         VIRTUAL_DeleteView( view );
1120     }
1121     else
1122     {
1123         /* Decommit the pages by remapping zero-pages instead */
1124
1125         if (wine_anon_mmap( (LPVOID)base, size, VIRTUAL_GetUnixProt(0), MAP_FIXED ) != (LPVOID)base)
1126             ERR( "Could not remap pages, expect trouble\n" );
1127         if (!VIRTUAL_SetProt( view, base, size, 0 )) return STATUS_ACCESS_DENIED;  /* FIXME */
1128     }
1129
1130     *addr_ptr = base;
1131     *size_ptr = size;
1132     return STATUS_SUCCESS;
1133 }
1134
1135
1136 /***********************************************************************
1137  *             NtProtectVirtualMemory   (NTDLL.@)
1138  *             ZwProtectVirtualMemory   (NTDLL.@)
1139  */
1140 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr,
1141                                         ULONG new_prot, ULONG *old_prot )
1142 {
1143     FILE_VIEW *view;
1144     char *base;
1145     UINT i;
1146     BYTE vprot, *p;
1147     DWORD prot, size = *size_ptr;
1148     LPVOID addr = *addr_ptr;
1149
1150     if (!is_current_process( process ))
1151     {
1152         ERR("Unsupported on other process\n");
1153         return STATUS_ACCESS_DENIED;
1154     }
1155
1156     TRACE("%p %08lx %08lx\n", addr, size, new_prot );
1157
1158     /* Fix the parameters */
1159
1160     size = ROUND_SIZE( addr, size );
1161     base = ROUND_ADDR( addr, page_mask );
1162
1163     if (!(view = VIRTUAL_FindView( base )) ||
1164         (base + size > (char *)view->base + view->size))
1165         return STATUS_INVALID_PARAMETER;
1166
1167     /* Make sure all the pages are committed */
1168
1169     p = view->prot + ((base - (char *)view->base) >> page_shift);
1170     VIRTUAL_GetWin32Prot( *p, &prot, NULL );
1171     for (i = size >> page_shift; i; i--, p++)
1172     {
1173         if (!(*p & VPROT_COMMITTED)) return STATUS_INVALID_PARAMETER;
1174     }
1175
1176     if (old_prot) *old_prot = prot;
1177     vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1178     if (!VIRTUAL_SetProt( view, base, size, vprot )) return STATUS_ACCESS_DENIED;
1179
1180     *addr_ptr = base;
1181     *size_ptr = size;
1182     return STATUS_SUCCESS;
1183 }
1184
1185
1186 /***********************************************************************
1187  *             NtQueryVirtualMemory   (NTDLL.@)
1188  *             ZwQueryVirtualMemory   (NTDLL.@)
1189  */
1190 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1191                                       MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1192                                       ULONG len, ULONG *res_len )
1193 {
1194     FILE_VIEW *view;
1195     char *base, *alloc_base = 0;
1196     UINT size = 0;
1197     MEMORY_BASIC_INFORMATION *info = buffer;
1198
1199     if (info_class != MemoryBasicInformation) return STATUS_INVALID_INFO_CLASS;
1200     if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1201         return STATUS_WORKING_SET_LIMIT_RANGE;  /* FIXME */
1202
1203     if (!is_current_process( process ))
1204     {
1205         ERR("Unsupported on other process\n");
1206         return STATUS_ACCESS_DENIED;
1207     }
1208
1209     base = ROUND_ADDR( addr, page_mask );
1210
1211     /* Find the view containing the address */
1212
1213     RtlEnterCriticalSection(&csVirtual);
1214     view = VIRTUAL_FirstView;
1215     for (;;)
1216     {
1217         if (!view)
1218         {
1219             size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1220             break;
1221         }
1222         if ((char *)view->base > base)
1223         {
1224             size = (char *)view->base - alloc_base;
1225             view = NULL;
1226             break;
1227         }
1228         if ((char *)view->base + view->size > base)
1229         {
1230             alloc_base = view->base;
1231             size = view->size;
1232             break;
1233         }
1234         alloc_base = (char *)view->base + view->size;
1235         view = view->next;
1236     }
1237     RtlLeaveCriticalSection(&csVirtual);
1238
1239     /* Fill the info structure */
1240
1241     if (!view)
1242     {
1243         info->State             = MEM_FREE;
1244         info->Protect           = 0;
1245         info->AllocationProtect = 0;
1246         info->Type              = 0;
1247     }
1248     else
1249     {
1250         BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1251         VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
1252         for (size = base - alloc_base; size < view->size; size += page_mask+1)
1253             if (view->prot[size >> page_shift] != vprot) break;
1254         VIRTUAL_GetWin32Prot( view->protect, &info->AllocationProtect, NULL );
1255         if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1256         else if (view->flags & VFLAG_VALLOC) info->Type = MEM_PRIVATE;
1257         else info->Type = MEM_MAPPED;
1258     }
1259
1260     info->BaseAddress    = (LPVOID)base;
1261     info->AllocationBase = (LPVOID)alloc_base;
1262     info->RegionSize     = size - (base - alloc_base);
1263     if (res_len) *res_len = sizeof(*info);
1264     return STATUS_SUCCESS;
1265 }
1266
1267
1268 /***********************************************************************
1269  *             NtLockVirtualMemory   (NTDLL.@)
1270  *             ZwLockVirtualMemory   (NTDLL.@)
1271  */
1272 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1273 {
1274     if (!is_current_process( process ))
1275     {
1276         ERR("Unsupported on other process\n");
1277         return STATUS_ACCESS_DENIED;
1278     }
1279     return STATUS_SUCCESS;
1280 }
1281
1282
1283 /***********************************************************************
1284  *             NtUnlockVirtualMemory   (NTDLL.@)
1285  *             ZwUnlockVirtualMemory   (NTDLL.@)
1286  */
1287 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1288 {
1289     if (!is_current_process( process ))
1290     {
1291         ERR("Unsupported on other process\n");
1292         return STATUS_ACCESS_DENIED;
1293     }
1294     return STATUS_SUCCESS;
1295 }
1296
1297
1298 /***********************************************************************
1299  *             NtCreateSection   (NTDLL.@)
1300  *             ZwCreateSection   (NTDLL.@)
1301  */
1302 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1303                                  const LARGE_INTEGER *size, ULONG protect,
1304                                  ULONG sec_flags, HANDLE file )
1305 {
1306     NTSTATUS ret;
1307     BYTE vprot;
1308     DWORD len = attr->ObjectName ? attr->ObjectName->Length : 0;
1309
1310     /* Check parameters */
1311
1312     if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1313
1314     vprot = VIRTUAL_GetProt( protect );
1315     if (sec_flags & SEC_RESERVE)
1316     {
1317         if (file) return STATUS_INVALID_PARAMETER;
1318     }
1319     else vprot |= VPROT_COMMITTED;
1320     if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1321     if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
1322
1323     /* Create the server object */
1324
1325     SERVER_START_REQ( create_mapping )
1326     {
1327         req->file_handle = file;
1328         req->size_high   = size ? size->s.HighPart : 0;
1329         req->size_low    = size ? size->s.LowPart : 0;
1330         req->protect     = vprot;
1331         req->access      = access;
1332         req->inherit     = (attr->Attributes & OBJ_INHERIT) != 0;
1333         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
1334         ret = wine_server_call( req );
1335         *handle = reply->handle;
1336     }
1337     SERVER_END_REQ;
1338     return ret;
1339 }
1340
1341
1342 /***********************************************************************
1343  *             NtOpenSection   (NTDLL.@)
1344  *             ZwOpenSection   (NTDLL.@)
1345  */
1346 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1347 {
1348     NTSTATUS ret;
1349     DWORD len = attr->ObjectName->Length;
1350
1351     if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1352
1353     SERVER_START_REQ( open_mapping )
1354     {
1355         req->access  = access;
1356         req->inherit = (attr->Attributes & OBJ_INHERIT) != 0;
1357         wine_server_add_data( req, attr->ObjectName->Buffer, len );
1358         if (!(ret = wine_server_call( req ))) *handle = reply->handle;
1359     }
1360     SERVER_END_REQ;
1361     return ret;
1362 }
1363
1364
1365 /***********************************************************************
1366  *             NtMapViewOfSection   (NTDLL.@)
1367  *             ZwMapViewOfSection   (NTDLL.@)
1368  */
1369 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
1370                                     ULONG commit_size, const LARGE_INTEGER *offset, ULONG *size_ptr,
1371                                     SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
1372 {
1373     FILE_VIEW *view;
1374     NTSTATUS res;
1375     UINT size = 0;
1376     int flags = MAP_PRIVATE;
1377     int unix_handle = -1;
1378     int prot;
1379     void *base, *ptr = (void *)-1, *ret;
1380     DWORD size_low, size_high, header_size, shared_size;
1381     HANDLE shared_file;
1382     BOOL removable;
1383
1384     if (!is_current_process( process ))
1385     {
1386         ERR("Unsupported on other process\n");
1387         return STATUS_ACCESS_DENIED;
1388     }
1389
1390     TRACE("handle=%p addr=%p off=%lx%08lx size=%x access=%lx\n",
1391           handle, *addr_ptr, offset->s.HighPart, offset->s.LowPart, size, protect );
1392
1393     /* Check parameters */
1394
1395     if ((offset->s.LowPart & granularity_mask) ||
1396         (*addr_ptr && ((UINT_PTR)*addr_ptr & granularity_mask)))
1397         return STATUS_INVALID_PARAMETER;
1398
1399     SERVER_START_REQ( get_mapping_info )
1400     {
1401         req->handle = handle;
1402         res = wine_server_call( req );
1403         prot        = reply->protect;
1404         base        = reply->base;
1405         size_low    = reply->size_low;
1406         size_high   = reply->size_high;
1407         header_size = reply->header_size;
1408         shared_file = reply->shared_file;
1409         shared_size = reply->shared_size;
1410         removable   = reply->removable;
1411     }
1412     SERVER_END_REQ;
1413     if (res) goto error;
1414
1415     if ((res = wine_server_handle_to_fd( handle, 0, &unix_handle, NULL, NULL ))) goto error;
1416
1417     if (prot & VPROT_IMAGE)
1418     {
1419         int shared_fd = -1;
1420
1421         if (shared_file)
1422         {
1423             if ((res = wine_server_handle_to_fd( shared_file, GENERIC_READ, &shared_fd,
1424                                                  NULL, NULL ))) goto error;
1425             NtClose( shared_file );  /* we no longer need it */
1426         }
1427         res = map_image( handle, unix_handle, base, size_low, header_size,
1428                          shared_fd, shared_size, removable, addr_ptr );
1429         if (shared_fd != -1) close( shared_fd );
1430         if (!res) *size_ptr = size_low;
1431         return res;
1432     }
1433
1434
1435     if (size_high)
1436         ERR("Sizes larger than 4Gb not supported\n");
1437
1438     if ((offset->s.LowPart >= size_low) ||
1439         (*size_ptr > size_low - offset->s.LowPart))
1440     {
1441         res = STATUS_INVALID_PARAMETER;
1442         goto error;
1443     }
1444     if (*size_ptr) size = ROUND_SIZE( offset->s.LowPart, *size_ptr );
1445     else size = size_low - offset->s.LowPart;
1446
1447     switch(protect)
1448     {
1449     case PAGE_NOACCESS:
1450         break;
1451     case PAGE_READWRITE:
1452     case PAGE_EXECUTE_READWRITE:
1453         if (!(prot & VPROT_WRITE))
1454         {
1455             res = STATUS_INVALID_PARAMETER;
1456             goto error;
1457         }
1458         flags = MAP_SHARED;
1459         /* fall through */
1460     case PAGE_READONLY:
1461     case PAGE_WRITECOPY:
1462     case PAGE_EXECUTE:
1463     case PAGE_EXECUTE_READ:
1464     case PAGE_EXECUTE_WRITECOPY:
1465         if (prot & VPROT_READ) break;
1466         /* fall through */
1467     default:
1468         res = STATUS_INVALID_PARAMETER;
1469         goto error;
1470     }
1471
1472     /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1473      * which has a view of this mapping commits some pages, they will
1474      * appear commited in all other processes, which have the same
1475      * view created. Since we don`t support this yet, we create the
1476      * whole mapping commited.
1477      */
1478     prot |= VPROT_COMMITTED;
1479
1480     /* Reserve a properly aligned area */
1481
1482     if ((res = anon_mmap_aligned( addr_ptr, size, PROT_NONE, 0 ))) goto error;
1483     ptr = *addr_ptr;
1484
1485     /* Map the file */
1486
1487     TRACE("handle=%p size=%x offset=%lx\n", handle, size, offset->s.LowPart );
1488
1489     ret = VIRTUAL_mmap( unix_handle, ptr, size, offset->s.LowPart, offset->s.HighPart,
1490                         VIRTUAL_GetUnixProt( prot ), flags | MAP_FIXED, &removable );
1491     if (ret != ptr)
1492     {
1493         ERR( "VIRTUAL_mmap %p %x %lx%08lx failed\n",
1494              ptr, size, offset->s.HighPart, offset->s.LowPart );
1495         res = STATUS_NO_MEMORY;  /* FIXME */
1496         goto error;
1497     }
1498     if (removable) handle = 0;  /* don't keep handle open on removable media */
1499
1500     if (!(view = VIRTUAL_CreateView( ptr, size, 0, prot, handle )))
1501     {
1502         res = STATUS_NO_MEMORY;
1503         goto error;
1504     }
1505     if (unix_handle != -1) close( unix_handle );
1506     *size_ptr = size;
1507     return STATUS_SUCCESS;
1508
1509 error:
1510     if (unix_handle != -1) close( unix_handle );
1511     if (ptr != (void *)-1) munmap( ptr, size );
1512     return res;
1513 }
1514
1515
1516 /***********************************************************************
1517  *             NtUnmapViewOfSection   (NTDLL.@)
1518  *             ZwUnmapViewOfSection   (NTDLL.@)
1519  */
1520 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
1521 {
1522     FILE_VIEW *view;
1523     void *base = ROUND_ADDR( addr, page_mask );
1524
1525     if (!is_current_process( process ))
1526     {
1527         ERR("Unsupported on other process\n");
1528         return STATUS_ACCESS_DENIED;
1529     }
1530     if (!(view = VIRTUAL_FindView( base )) || (base != view->base)) return STATUS_INVALID_PARAMETER;
1531     VIRTUAL_DeleteView( view );
1532     return STATUS_SUCCESS;
1533 }
1534
1535
1536 /***********************************************************************
1537  *             NtFlushVirtualMemory   (NTDLL.@)
1538  *             ZwFlushVirtualMemory   (NTDLL.@)
1539  */
1540 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
1541                                       ULONG *size_ptr, ULONG unknown )
1542 {
1543     FILE_VIEW *view;
1544     void *addr = ROUND_ADDR( *addr_ptr, page_mask );
1545
1546     if (!is_current_process( process ))
1547     {
1548         ERR("Unsupported on other process\n");
1549         return STATUS_ACCESS_DENIED;
1550     }
1551     if (!(view = VIRTUAL_FindView( addr ))) return STATUS_INVALID_PARAMETER;
1552     if (!*size_ptr) *size_ptr = view->size;
1553     *addr_ptr = addr;
1554     if (!msync( addr, *size_ptr, MS_SYNC )) return STATUS_SUCCESS;
1555     return STATUS_NOT_MAPPED_DATA;
1556 }
1557
1558
1559 /***********************************************************************
1560  *             NtReadVirtualMemory   (NTDLL.@)
1561  *             ZwReadVirtualMemory   (NTDLL.@)
1562  */
1563 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
1564                                      SIZE_T size, SIZE_T *bytes_read )
1565 {
1566     NTSTATUS status;
1567
1568     SERVER_START_REQ( read_process_memory )
1569     {
1570         req->handle = process;
1571         req->addr   = (void *)addr;
1572         wine_server_set_reply( req, buffer, size );
1573         if ((status = wine_server_call( req ))) size = 0;
1574     }
1575     SERVER_END_REQ;
1576     if (bytes_read) *bytes_read = size;
1577     return status;
1578 }
1579
1580
1581 /***********************************************************************
1582  *             NtWriteVirtualMemory   (NTDLL.@)
1583  *             ZwWriteVirtualMemory   (NTDLL.@)
1584  */
1585 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
1586                                       SIZE_T size, SIZE_T *bytes_written )
1587 {
1588     static const unsigned int zero;
1589     unsigned int first_offset, last_offset, first_mask, last_mask;
1590     NTSTATUS status;
1591
1592     if (!size) return STATUS_INVALID_PARAMETER;
1593
1594     /* compute the mask for the first int */
1595     first_mask = ~0;
1596     first_offset = (unsigned int)addr % sizeof(int);
1597     memset( &first_mask, 0, first_offset );
1598
1599     /* compute the mask for the last int */
1600     last_offset = (size + first_offset) % sizeof(int);
1601     last_mask = 0;
1602     memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1603
1604     SERVER_START_REQ( write_process_memory )
1605     {
1606         req->handle     = process;
1607         req->addr       = (char *)addr - first_offset;
1608         req->first_mask = first_mask;
1609         req->last_mask  = last_mask;
1610         if (first_offset) wine_server_add_data( req, &zero, first_offset );
1611         wine_server_add_data( req, buffer, size );
1612         if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1613
1614         if ((status = wine_server_call( req ))) size = 0;
1615     }
1616     SERVER_END_REQ;
1617     if (bytes_written) *bytes_written = size;
1618     return status;
1619 }