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