Changed the GDI driver interface to pass an opaque PHYSDEV pointer
[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 (view->base + view->size > 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  *           map_image
495  *
496  * Map an executable (PE format) image into memory.
497  */
498 static LPVOID map_image( HANDLE hmapping, int fd, char *base, DWORD total_size,
499                          DWORD header_size, HANDLE shared_file, DWORD shared_size,
500                          BOOL removable )
501 {
502     IMAGE_DOS_HEADER *dos;
503     IMAGE_NT_HEADERS *nt;
504     IMAGE_SECTION_HEADER *sec;
505     int i, pos;
506     DWORD err = GetLastError();
507     FILE_VIEW *view;
508     char *ptr;
509     int shared_fd = -1;
510
511     SetLastError( ERROR_BAD_EXE_FORMAT );  /* generic error */
512
513     /* zero-map the whole range */
514
515     if ((ptr = wine_anon_mmap( base, total_size,
516                              PROT_READ | PROT_WRITE | PROT_EXEC, 0 )) == (char *)-1)
517     {
518         ptr = wine_anon_mmap( NULL, total_size,
519                             PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
520         if (ptr == (char *)-1)
521         {
522             ERR_(module)("Not enough memory for module (%ld bytes)\n", total_size);
523             goto error;
524         }
525     }
526     TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
527
528     /* map the header */
529
530     if (VIRTUAL_mmap( fd, ptr, header_size, 0, 0, PROT_READ,
531                       MAP_PRIVATE | MAP_FIXED, &removable ) == (char *)-1) goto error;
532     dos = (IMAGE_DOS_HEADER *)ptr;
533     nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
534     if ((char *)(nt + 1) > ptr + header_size) goto error;
535
536     sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
537     if ((char *)(sec + nt->FileHeader.NumberOfSections) > ptr + header_size) goto error;
538
539     /* check the architecture */
540
541     if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
542     {
543         MESSAGE("Trying to load PE image for unsupported architecture (");
544         switch (nt->FileHeader.Machine)
545         {
546         case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
547         case IMAGE_FILE_MACHINE_I860:    MESSAGE("I860"); break;
548         case IMAGE_FILE_MACHINE_R3000:   MESSAGE("R3000"); break;
549         case IMAGE_FILE_MACHINE_R4000:   MESSAGE("R4000"); break;
550         case IMAGE_FILE_MACHINE_R10000:  MESSAGE("R10000"); break;
551         case IMAGE_FILE_MACHINE_ALPHA:   MESSAGE("Alpha"); break;
552         case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
553         default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
554         }
555         MESSAGE(")\n");
556         goto error;
557     }
558     
559     /* retrieve the shared sections file */
560
561     if (shared_size)
562     {
563         if ((shared_fd = FILE_GetUnixHandle( shared_file, GENERIC_READ )) == -1) goto error;
564         CloseHandle( shared_file );  /* we no longer need it */
565         shared_file = 0;
566     }
567
568     /* map all the sections */
569
570     for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
571     {
572         DWORD size;
573
574         /* a few sanity checks */
575         size = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
576         if (sec->VirtualAddress > total_size || size > total_size || size < sec->VirtualAddress)
577         {
578             ERR_(module)( "Section %.8s too large (%lx+%lx/%lx)\n",
579                           sec->Name, sec->VirtualAddress, sec->Misc.VirtualSize, total_size );
580             goto error;
581         }
582
583         if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
584             (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
585         {
586             size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
587             TRACE_(module)( "mapping shared section %.8s at %p off %lx (%x) size %lx (%lx) flags %lx\n",
588                           sec->Name, ptr + sec->VirtualAddress,
589                           sec->PointerToRawData, pos, sec->SizeOfRawData,
590                           size, sec->Characteristics );
591             if (VIRTUAL_mmap( shared_fd, ptr + sec->VirtualAddress, size,
592                               pos, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
593                               MAP_SHARED|MAP_FIXED, NULL ) == (void *)-1)
594             {
595                 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
596                 goto error;
597             }
598             pos += size;
599             continue;
600         }
601
602         if (sec->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) continue;
603         if (!sec->PointerToRawData || !sec->SizeOfRawData) continue;
604
605         TRACE_(module)( "mapping section %.8s at %p off %lx size %lx flags %lx\n",
606                         sec->Name, ptr + sec->VirtualAddress,
607                         sec->PointerToRawData, sec->SizeOfRawData,
608                         sec->Characteristics );
609
610         /* Note: if the section is not aligned properly VIRTUAL_mmap will magically
611          *       fall back to read(), so we don't need to check anything here.
612          */
613         if (VIRTUAL_mmap( fd, ptr + sec->VirtualAddress, sec->SizeOfRawData,
614                           sec->PointerToRawData, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
615                           MAP_PRIVATE | MAP_FIXED, &removable ) == (void *)-1)
616         {
617             ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
618             goto error;
619         }
620
621         if ((sec->SizeOfRawData < sec->Misc.VirtualSize) && (sec->SizeOfRawData & page_mask))
622         {
623             DWORD end = ROUND_SIZE( 0, sec->SizeOfRawData );
624             if (end > sec->Misc.VirtualSize) end = sec->Misc.VirtualSize;
625             TRACE_(module)("clearing %p - %p\n",
626                            ptr + sec->VirtualAddress + sec->SizeOfRawData,
627                            ptr + sec->VirtualAddress + end );
628             memset( ptr + sec->VirtualAddress + sec->SizeOfRawData, 0,
629                     end - sec->SizeOfRawData );
630         }
631     }
632
633     if (removable) hmapping = 0;  /* don't keep handle open on removable media */
634     if (!(view = VIRTUAL_CreateView( ptr, total_size, 0,
635                                      VPROT_COMMITTED|VPROT_READ|VPROT_WRITE|VPROT_WRITECOPY,
636                                      hmapping )))
637     {
638         SetLastError( ERROR_OUTOFMEMORY );
639         goto error;
640     }
641
642     SetLastError( err );  /* restore last error */
643     close( fd );
644     if (shared_fd != -1) close( shared_fd );
645     return ptr;
646
647  error:
648     if (ptr != (char *)-1) munmap( ptr, total_size );
649     close( fd );
650     if (shared_fd != -1) close( shared_fd );
651     if (shared_file) CloseHandle( shared_file );
652     return NULL;
653 }
654
655
656 /***********************************************************************
657  *           VIRTUAL_Init
658  */
659 #ifndef page_mask
660 DECL_GLOBAL_CONSTRUCTOR(VIRTUAL_Init)
661 {
662     page_size = getpagesize();
663     page_mask = page_size - 1;
664     /* Make sure we have a power of 2 */
665     assert( !(page_size & page_mask) );
666     page_shift = 0;
667     while ((1 << page_shift) != page_size) page_shift++;
668 }
669 #endif  /* page_mask */
670
671
672 /***********************************************************************
673  *           VIRTUAL_SetFaultHandler
674  */
675 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
676 {
677     FILE_VIEW *view;
678
679     if (!(view = VIRTUAL_FindView( addr ))) return FALSE;
680     view->handlerProc = proc;
681     view->handlerArg  = arg;
682     return TRUE;
683 }
684
685 /***********************************************************************
686  *           VIRTUAL_HandleFault
687  */
688 DWORD VIRTUAL_HandleFault( LPCVOID addr )
689 {
690     FILE_VIEW *view = VIRTUAL_FindView( addr );
691     DWORD ret = EXCEPTION_ACCESS_VIOLATION;
692
693     if (view)
694     {
695         if (view->handlerProc)
696         {
697             if (view->handlerProc(view->handlerArg, addr)) ret = 0;  /* handled */
698         }
699         else
700         {
701             BYTE vprot = view->prot[((char *)addr - (char *)view->base) >> page_shift];
702             void *page = (void *)((UINT_PTR)addr & ~page_mask);
703             char *stack = (char *)NtCurrentTeb()->stack_base + SIGNAL_STACK_SIZE + page_mask + 1;
704             if (vprot & VPROT_GUARD)
705             {
706                 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
707                 ret = STATUS_GUARD_PAGE_VIOLATION;
708             }
709             /* is it inside the stack guard pages? */
710             if (((char *)addr >= stack) && ((char *)addr < stack + 2*(page_mask+1)))
711                 ret = STATUS_STACK_OVERFLOW;
712         }
713     }
714     return ret;
715 }
716
717
718
719 /***********************************************************************
720  *           unaligned_mmap
721  *
722  * Linux kernels before 2.4.x can support non page-aligned offsets, as
723  * long as the offset is aligned to the filesystem block size. This is
724  * a big performance gain so we want to take advantage of it.
725  *
726  * However, when we use 64-bit file support this doesn't work because
727  * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
728  * in that it rounds unaligned offsets down to a page boundary. For
729  * these reasons we do a direct system call here.
730  */
731 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
732                              unsigned int flags, int fd, unsigned int offset_low,
733                              unsigned int offset_high )
734 {
735 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
736     if (!offset_high && (offset_low & page_mask))
737     {
738         int ret;
739         __asm__ __volatile__("push %%ebx\n\t"
740                              "movl %2,%%ebx\n\t"
741                              "int $0x80\n\t"
742                              "popl %%ebx"
743                              : "=a" (ret)
744                              : "0" (90), /* SYS_mmap */
745                                "g" (&addr) );
746         if (ret < 0 && ret > -4096)
747         {
748             errno = -ret;
749             ret = -1;
750         }
751         return (void *)ret;
752     }
753 #endif
754     return mmap( addr, length, prot, flags, fd, ((off_t)offset_high << 32) | offset_low );
755 }
756
757
758 /***********************************************************************
759  *           VIRTUAL_mmap
760  *
761  * Wrapper for mmap() that handles anonymous mappings portably,
762  * and falls back to read if mmap of a file fails.
763  */
764 static LPVOID VIRTUAL_mmap( int fd, LPVOID start, DWORD size,
765                             DWORD offset_low, DWORD offset_high,
766                             int prot, int flags, BOOL *removable )
767 {
768     int pos;
769     LPVOID ret;
770     off_t offset;
771     BOOL is_shared_write = FALSE;
772
773     if (fd == -1) return wine_anon_mmap( start, size, prot, flags );
774
775     if (prot & PROT_WRITE)
776     {
777 #ifdef MAP_SHARED
778         if (flags & MAP_SHARED) is_shared_write = TRUE;
779 #endif
780 #ifdef MAP_PRIVATE
781         if (!(flags & MAP_PRIVATE)) is_shared_write = TRUE;
782 #endif
783     }
784
785     if (removable && *removable)
786     {
787         /* if on removable media, try using read instead of mmap */
788         if (!is_shared_write) goto fake_mmap;
789         *removable = FALSE;
790     }
791
792     if ((ret = unaligned_mmap( start, size, prot, flags, fd,
793                                offset_low, offset_high )) != (LPVOID)-1) return ret;
794
795     /* mmap() failed; if this is because the file offset is not    */
796     /* page-aligned (EINVAL), or because the underlying filesystem */
797     /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
798
799     if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return ret;
800     if (is_shared_write) return ret;  /* we cannot fake shared write mappings */
801
802  fake_mmap:
803     /* Reserve the memory with an anonymous mmap */
804     ret = wine_anon_mmap( start, size, PROT_READ | PROT_WRITE, flags );
805     if (ret == (LPVOID)-1) return ret;
806     /* Now read in the file */
807     offset = ((off_t)offset_high << 32) | offset_low;
808     if ((pos = lseek( fd, offset, SEEK_SET )) == -1)
809     {
810         munmap( ret, size );
811         return (LPVOID)-1;
812     }
813     read( fd, ret, size );
814     lseek( fd, pos, SEEK_SET );  /* Restore the file pointer */
815     mprotect( ret, size, prot );  /* Set the right protection */
816     return ret;
817 }
818
819
820 /***********************************************************************
821  *             VirtualAlloc   (KERNEL32.@)
822  * Reserves or commits a region of pages in virtual address space
823  *
824  * RETURNS
825  *      Base address of allocated region of pages
826  *      NULL: Failure
827  */
828 LPVOID WINAPI VirtualAlloc(
829               LPVOID addr,  /* [in] Address of region to reserve or commit */
830               DWORD size,   /* [in] Size of region */
831               DWORD type,   /* [in] Type of allocation */
832               DWORD protect)/* [in] Type of access protection */
833 {
834     FILE_VIEW *view;
835     char *ptr, *base;
836     BYTE vprot;
837
838     TRACE("%p %08lx %lx %08lx\n", addr, size, type, protect );
839
840     /* Round parameters to a page boundary */
841
842     if (size > 0x7fc00000)  /* 2Gb - 4Mb */
843     {
844         SetLastError( ERROR_OUTOFMEMORY );
845         return NULL;
846     }
847     if (addr)
848     {
849         if (type & MEM_RESERVE) /* Round down to 64k boundary */
850             base = ROUND_ADDR( addr, granularity_mask );
851         else
852             base = ROUND_ADDR( addr, page_mask );
853         size = (((UINT_PTR)addr + size + page_mask) & ~page_mask) - (UINT_PTR)base;
854         if ((base <= (char *)granularity_mask) || (base + size < base))
855         {
856             /* disallow low 64k and wrap-around */
857             SetLastError( ERROR_INVALID_PARAMETER );
858             return NULL;
859         }
860     }
861     else
862     {
863         base = 0;
864         size = (size + page_mask) & ~page_mask;
865     }
866
867     if (type & MEM_TOP_DOWN) {
868         /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
869          *        Is there _ANY_ way to do it with UNIX mmap()?
870          */
871         WARN("MEM_TOP_DOWN ignored\n");
872         type &= ~MEM_TOP_DOWN;
873     }
874     /* Compute the alloc type flags */
875
876     if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)) ||
877         (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)))
878     {
879         ERR("called with wrong alloc type flags (%08lx) !\n", type);
880         SetLastError( ERROR_INVALID_PARAMETER );
881         return NULL;
882     }
883     if (type & (MEM_COMMIT | MEM_SYSTEM))
884         vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
885     else vprot = 0;
886
887     /* Reserve the memory */
888
889     if ((type & MEM_RESERVE) || !base)
890     {
891         if (type & MEM_SYSTEM)
892         {
893             if (!(view = VIRTUAL_CreateView( base, size, VFLAG_VALLOC | VFLAG_SYSTEM, vprot, 0 )))
894             {
895                 SetLastError( ERROR_OUTOFMEMORY );
896                 return NULL;
897             }
898             return (LPVOID)base;
899         }
900         ptr = anon_mmap_aligned( base, size, VIRTUAL_GetUnixProt( vprot ), 0 );
901         if (ptr == (void *)-1) return NULL;
902
903         if (!(view = VIRTUAL_CreateView( ptr, size, VFLAG_VALLOC, vprot, 0 )))
904         {
905             munmap( ptr, size );
906             SetLastError( ERROR_OUTOFMEMORY );
907             return NULL;
908         }
909         return ptr;
910     }
911
912     /* Commit the pages */
913
914     if (!(view = VIRTUAL_FindView( base )) ||
915         (base + size > (char *)view->base + view->size))
916     {
917         SetLastError( ERROR_INVALID_ADDRESS );
918         return NULL;
919     }
920
921     if (!VIRTUAL_SetProt( view, base, size, vprot )) return NULL;
922     return (LPVOID)base;
923 }
924
925
926 /***********************************************************************
927  *             VirtualAllocEx   (KERNEL32.@)
928  *
929  * Seems to be just as VirtualAlloc, but with process handle.
930  */
931 LPVOID WINAPI VirtualAllocEx(
932               HANDLE hProcess, /* [in] Handle of process to do mem operation */
933               LPVOID addr,  /* [in] Address of region to reserve or commit */
934               DWORD size,   /* [in] Size of region */
935               DWORD type,   /* [in] Type of allocation */
936               DWORD protect /* [in] Type of access protection */
937 ) {
938     if (MapProcessHandle( hProcess ) == GetCurrentProcessId())
939         return VirtualAlloc( addr, size, type, protect );
940     ERR("Unsupported on other process\n");
941     return NULL;
942 }
943
944
945 /***********************************************************************
946  *             VirtualFree   (KERNEL32.@)
947  * Release or decommits a region of pages in virtual address space.
948  * 
949  * RETURNS
950  *      TRUE: Success
951  *      FALSE: Failure
952  */
953 BOOL WINAPI VirtualFree(
954               LPVOID addr, /* [in] Address of region of committed pages */
955               DWORD size,  /* [in] Size of region */
956               DWORD type   /* [in] Type of operation */
957 ) {
958     FILE_VIEW *view;
959     char *base;
960
961     TRACE("%p %08lx %lx\n", addr, size, type );
962
963     /* Fix the parameters */
964
965     size = ROUND_SIZE( addr, size );
966     base = ROUND_ADDR( addr, page_mask );
967
968     if (!(view = VIRTUAL_FindView( base )) ||
969         (base + size > (char *)view->base + view->size) ||
970         !(view->flags & VFLAG_VALLOC))
971     {
972         SetLastError( ERROR_INVALID_PARAMETER );
973         return FALSE;
974     }
975
976     /* Check the type */
977
978     if (type & MEM_SYSTEM)
979     {
980         view->flags |= VFLAG_SYSTEM;
981         type &= ~MEM_SYSTEM;
982     }
983
984     if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
985     {
986         ERR("called with wrong free type flags (%08lx) !\n", type);
987         SetLastError( ERROR_INVALID_PARAMETER );
988         return FALSE;
989     }
990
991     /* Free the pages */
992
993     if (type == MEM_RELEASE)
994     {
995         if (size || (base != view->base))
996         {
997             SetLastError( ERROR_INVALID_PARAMETER );
998             return FALSE;
999         }
1000         VIRTUAL_DeleteView( view );
1001         return TRUE;
1002     }
1003
1004     /* Decommit the pages by remapping zero-pages instead */
1005
1006     if (wine_anon_mmap( (LPVOID)base, size, VIRTUAL_GetUnixProt(0), MAP_FIXED ) != (LPVOID)base)
1007         ERR( "Could not remap pages, expect trouble\n" );
1008     return VIRTUAL_SetProt( view, base, size, 0 );
1009 }
1010
1011
1012 /***********************************************************************
1013  *             VirtualLock   (KERNEL32.@)
1014  * Locks the specified region of virtual address space
1015  * 
1016  * NOTE
1017  *      Always returns TRUE
1018  *
1019  * RETURNS
1020  *      TRUE: Success
1021  *      FALSE: Failure
1022  */
1023 BOOL WINAPI VirtualLock(
1024               LPVOID addr, /* [in] Address of first byte of range to lock */
1025               DWORD size   /* [in] Number of bytes in range to lock */
1026 ) {
1027     return TRUE;
1028 }
1029
1030
1031 /***********************************************************************
1032  *             VirtualUnlock   (KERNEL32.@)
1033  * Unlocks a range of pages in the virtual address space
1034  *
1035  * NOTE
1036  *      Always returns TRUE
1037  *
1038  * RETURNS
1039  *      TRUE: Success
1040  *      FALSE: Failure
1041  */
1042 BOOL WINAPI VirtualUnlock(
1043               LPVOID addr, /* [in] Address of first byte of range */
1044               DWORD size   /* [in] Number of bytes in range */
1045 ) {
1046     return TRUE;
1047 }
1048
1049
1050 /***********************************************************************
1051  *             VirtualProtect   (KERNEL32.@)
1052  * Changes the access protection on a region of committed pages
1053  *
1054  * RETURNS
1055  *      TRUE: Success
1056  *      FALSE: Failure
1057  */
1058 BOOL WINAPI VirtualProtect(
1059               LPVOID addr,     /* [in] Address of region of committed pages */
1060               DWORD size,      /* [in] Size of region */
1061               DWORD new_prot,  /* [in] Desired access protection */
1062               LPDWORD old_prot /* [out] Address of variable to get old protection */
1063 ) {
1064     FILE_VIEW *view;
1065     char *base;
1066     UINT i;
1067     BYTE vprot, *p;
1068     DWORD prot;
1069
1070     TRACE("%p %08lx %08lx\n", addr, size, new_prot );
1071
1072     /* Fix the parameters */
1073
1074     size = ROUND_SIZE( addr, size );
1075     base = ROUND_ADDR( addr, page_mask );
1076
1077     if (!(view = VIRTUAL_FindView( base )) ||
1078         (base + size > (char *)view->base + view->size))
1079     {
1080         SetLastError( ERROR_INVALID_PARAMETER );
1081         return FALSE;
1082     }
1083
1084     /* Make sure all the pages are committed */
1085
1086     p = view->prot + ((base - (char *)view->base) >> page_shift);
1087     VIRTUAL_GetWin32Prot( *p, &prot, NULL );
1088     for (i = size >> page_shift; i; i--, p++)
1089     {
1090         if (!(*p & VPROT_COMMITTED))
1091         {
1092             SetLastError( ERROR_INVALID_PARAMETER );
1093             return FALSE;
1094         }
1095     }
1096
1097     if (old_prot) *old_prot = prot;
1098     vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1099     return VIRTUAL_SetProt( view, base, size, vprot );
1100 }
1101
1102
1103 /***********************************************************************
1104  *             VirtualProtectEx   (KERNEL32.@)
1105  * Changes the access protection on a region of committed pages in the
1106  * virtual address space of a specified process
1107  *
1108  * RETURNS
1109  *      TRUE: Success
1110  *      FALSE: Failure
1111  */
1112 BOOL WINAPI VirtualProtectEx(
1113               HANDLE handle, /* [in]  Handle of process */
1114               LPVOID addr,     /* [in]  Address of region of committed pages */
1115               DWORD size,      /* [in]  Size of region */
1116               DWORD new_prot,  /* [in]  Desired access protection */
1117               LPDWORD old_prot /* [out] Address of variable to get old protection */ )
1118 {
1119     if (MapProcessHandle( handle ) == GetCurrentProcessId())
1120         return VirtualProtect( addr, size, new_prot, old_prot );
1121     ERR("Unsupported on other process\n");
1122     return FALSE;
1123 }
1124
1125
1126 /***********************************************************************
1127  *             VirtualQuery   (KERNEL32.@)
1128  * Provides info about a range of pages in virtual address space
1129  *
1130  * RETURNS
1131  *      Number of bytes returned in information buffer
1132  *      or 0 if addr is >= 0xc0000000 (kernel space).
1133  */
1134 DWORD WINAPI VirtualQuery(
1135              LPCVOID addr,                    /* [in]  Address of region */
1136              LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
1137              DWORD len                        /* [in]  Size of buffer */
1138 ) {
1139     FILE_VIEW *view;
1140     char *base, *alloc_base = 0;
1141     UINT size = 0;
1142
1143     if (addr >= (void*)0xc0000000) return 0;
1144
1145     base = ROUND_ADDR( addr, page_mask );
1146
1147     /* Find the view containing the address */
1148
1149     EnterCriticalSection(&csVirtual);
1150     view = VIRTUAL_FirstView;
1151     for (;;)
1152     {
1153         if (!view)
1154         {
1155             size = (char *)0xffff0000 - alloc_base;
1156             break;
1157         }
1158         if ((char *)view->base > base)
1159         {
1160             size = (char *)view->base - alloc_base;
1161             view = NULL;
1162             break;
1163         }
1164         if ((char *)view->base + view->size > base)
1165         {
1166             alloc_base = view->base;
1167             size = view->size;
1168             break;
1169         }
1170         alloc_base = (char *)view->base + view->size;
1171         view = view->next;
1172     }
1173     LeaveCriticalSection(&csVirtual);
1174
1175     /* Fill the info structure */
1176
1177     if (!view)
1178     {
1179         info->State             = MEM_FREE;
1180         info->Protect           = 0;
1181         info->AllocationProtect = 0;
1182         info->Type              = 0;
1183     }
1184     else
1185     {
1186         BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1187         VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
1188         for (size = base - alloc_base; size < view->size; size += page_mask+1)
1189             if (view->prot[size >> page_shift] != vprot) break;
1190         info->AllocationProtect = view->protect;
1191         info->Type              = MEM_PRIVATE;  /* FIXME */
1192     }
1193
1194     info->BaseAddress    = (LPVOID)base;
1195     info->AllocationBase = (LPVOID)alloc_base;
1196     info->RegionSize     = size - (base - alloc_base);
1197     return sizeof(*info);
1198 }
1199
1200
1201 /***********************************************************************
1202  *             VirtualQueryEx   (KERNEL32.@)
1203  * Provides info about a range of pages in virtual address space of a
1204  * specified process
1205  *
1206  * RETURNS
1207  *      Number of bytes returned in information buffer
1208  */
1209 DWORD WINAPI VirtualQueryEx(
1210              HANDLE handle,                 /* [in] Handle of process */
1211              LPCVOID addr,                    /* [in] Address of region */
1212              LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
1213              DWORD len                        /* [in] Size of buffer */ )
1214 {
1215     if (MapProcessHandle( handle ) == GetCurrentProcessId())
1216         return VirtualQuery( addr, info, len );
1217     ERR("Unsupported on other process\n");
1218     return 0;
1219 }
1220
1221
1222 /***********************************************************************
1223  *             IsBadReadPtr   (KERNEL32.@)
1224  *
1225  * RETURNS
1226  *      FALSE: Process has read access to entire block
1227  *      TRUE: Otherwise
1228  */
1229 BOOL WINAPI IsBadReadPtr(
1230               LPCVOID ptr, /* [in] Address of memory block */
1231               UINT size )  /* [in] Size of block */
1232 {
1233     if (!size) return FALSE;  /* handle 0 size case w/o reference */
1234     __TRY
1235     {
1236         volatile const char *p = ptr;
1237         char dummy;
1238         UINT count = size;
1239
1240         while (count > page_size)
1241         {
1242             dummy = *p;
1243             p += page_size;
1244             count -= page_size;
1245         }
1246         dummy = p[0];
1247         dummy = p[count - 1];
1248     }
1249     __EXCEPT(page_fault) { return TRUE; }
1250     __ENDTRY
1251     return FALSE;
1252 }
1253
1254
1255 /***********************************************************************
1256  *             IsBadWritePtr   (KERNEL32.@)
1257  *
1258  * RETURNS
1259  *      FALSE: Process has write access to entire block
1260  *      TRUE: Otherwise
1261  */
1262 BOOL WINAPI IsBadWritePtr(
1263               LPVOID ptr, /* [in] Address of memory block */
1264               UINT size ) /* [in] Size of block in bytes */
1265 {
1266     if (!size) return FALSE;  /* handle 0 size case w/o reference */
1267     __TRY
1268     {
1269         volatile char *p = ptr;
1270         UINT count = size;
1271
1272         while (count > page_size)
1273         {
1274             *p |= 0;
1275             p += page_size;
1276             count -= page_size;
1277         }
1278         p[0] |= 0;
1279         p[count - 1] |= 0;
1280     }
1281     __EXCEPT(page_fault) { return TRUE; }
1282     __ENDTRY
1283     return FALSE;
1284 }
1285
1286
1287 /***********************************************************************
1288  *             IsBadHugeReadPtr   (KERNEL32.@)
1289  * RETURNS
1290  *      FALSE: Process has read access to entire block
1291  *      TRUE: Otherwise
1292  */
1293 BOOL WINAPI IsBadHugeReadPtr(
1294               LPCVOID ptr, /* [in] Address of memory block */
1295               UINT size  /* [in] Size of block */
1296 ) {
1297     return IsBadReadPtr( ptr, size );
1298 }
1299
1300
1301 /***********************************************************************
1302  *             IsBadHugeWritePtr   (KERNEL32.@)
1303  * RETURNS
1304  *      FALSE: Process has write access to entire block
1305  *      TRUE: Otherwise
1306  */
1307 BOOL WINAPI IsBadHugeWritePtr(
1308               LPVOID ptr, /* [in] Address of memory block */
1309               UINT size /* [in] Size of block */
1310 ) {
1311     return IsBadWritePtr( ptr, size );
1312 }
1313
1314
1315 /***********************************************************************
1316  *             IsBadCodePtr   (KERNEL32.@)
1317  *
1318  * RETURNS
1319  *      FALSE: Process has read access to specified memory
1320  *      TRUE: Otherwise
1321  */
1322 BOOL WINAPI IsBadCodePtr( FARPROC ptr ) /* [in] Address of function */
1323 {
1324     return IsBadReadPtr( ptr, 1 );
1325 }
1326
1327
1328 /***********************************************************************
1329  *             IsBadStringPtrA   (KERNEL32.@)
1330  *
1331  * RETURNS
1332  *      FALSE: Read access to all bytes in string
1333  *      TRUE: Else
1334  */
1335 BOOL WINAPI IsBadStringPtrA(
1336               LPCSTR str, /* [in] Address of string */
1337               UINT max )  /* [in] Maximum size of string */
1338 {
1339     __TRY
1340     {
1341         volatile const char *p = str;
1342         while (p != str + max) if (!*p++) break;
1343     }
1344     __EXCEPT(page_fault) { return TRUE; }
1345     __ENDTRY
1346     return FALSE;
1347 }
1348
1349
1350 /***********************************************************************
1351  *             IsBadStringPtrW   (KERNEL32.@)
1352  * See IsBadStringPtrA
1353  */
1354 BOOL WINAPI IsBadStringPtrW( LPCWSTR str, UINT max )
1355 {
1356     __TRY
1357     {
1358         volatile const WCHAR *p = str;
1359         while (p != str + max) if (!*p++) break;
1360     }
1361     __EXCEPT(page_fault) { return TRUE; }
1362     __ENDTRY
1363     return FALSE;
1364 }
1365
1366
1367 /***********************************************************************
1368  *             CreateFileMappingA   (KERNEL32.@)
1369  * Creates a named or unnamed file-mapping object for the specified file
1370  *
1371  * RETURNS
1372  *      Handle: Success
1373  *      0: Mapping object does not exist
1374  *      NULL: Failure
1375  */
1376 HANDLE WINAPI CreateFileMappingA(
1377                 HANDLE hFile,   /* [in] Handle of file to map */
1378                 SECURITY_ATTRIBUTES *sa, /* [in] Optional security attributes*/
1379                 DWORD protect,   /* [in] Protection for mapping object */
1380                 DWORD size_high, /* [in] High-order 32 bits of object size */
1381                 DWORD size_low,  /* [in] Low-order 32 bits of object size */
1382                 LPCSTR name      /* [in] Name of file-mapping object */ )
1383 {
1384     WCHAR buffer[MAX_PATH];
1385
1386     if (!name) return CreateFileMappingW( hFile, sa, protect, size_high, size_low, NULL );
1387
1388     if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1389     {
1390         SetLastError( ERROR_FILENAME_EXCED_RANGE );
1391         return 0;
1392     }
1393     return CreateFileMappingW( hFile, sa, protect, size_high, size_low, buffer );
1394 }
1395
1396
1397 /***********************************************************************
1398  *             CreateFileMappingW   (KERNEL32.@)
1399  * See CreateFileMappingA
1400  */
1401 HANDLE WINAPI CreateFileMappingW( HANDLE hFile, LPSECURITY_ATTRIBUTES sa, 
1402                                   DWORD protect, DWORD size_high,  
1403                                   DWORD size_low, LPCWSTR name )
1404 {
1405     HANDLE ret;
1406     BYTE vprot;
1407     DWORD len = name ? strlenW(name) : 0;
1408
1409     /* Check parameters */
1410
1411     TRACE("(%x,%p,%08lx,%08lx%08lx,%s)\n",
1412           hFile, sa, protect, size_high, size_low, debugstr_w(name) );
1413
1414     if (len > MAX_PATH)
1415     {
1416         SetLastError( ERROR_FILENAME_EXCED_RANGE );
1417         return 0;
1418     }
1419
1420     vprot = VIRTUAL_GetProt( protect );
1421     if (protect & SEC_RESERVE)
1422     {
1423         if (hFile != INVALID_HANDLE_VALUE)
1424         {
1425             SetLastError( ERROR_INVALID_PARAMETER );
1426             return 0;
1427         }
1428     }
1429     else vprot |= VPROT_COMMITTED;
1430     if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1431     if (protect & SEC_IMAGE) vprot |= VPROT_IMAGE;
1432
1433     /* Create the server object */
1434
1435     if (hFile == INVALID_HANDLE_VALUE) hFile = 0;
1436     SERVER_START_REQ( create_mapping )
1437     {
1438         req->file_handle = hFile;
1439         req->size_high   = size_high;
1440         req->size_low    = size_low;
1441         req->protect     = vprot;
1442         req->inherit     = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1443         wine_server_add_data( req, name, len * sizeof(WCHAR) );
1444         SetLastError(0);
1445         wine_server_call_err( req );
1446         ret = reply->handle;
1447     }
1448     SERVER_END_REQ;
1449     return ret;
1450 }
1451
1452
1453 /***********************************************************************
1454  *             OpenFileMappingA   (KERNEL32.@)
1455  * Opens a named file-mapping object.
1456  *
1457  * RETURNS
1458  *      Handle: Success
1459  *      NULL: Failure
1460  */
1461 HANDLE WINAPI OpenFileMappingA(
1462                 DWORD access,   /* [in] Access mode */
1463                 BOOL inherit, /* [in] Inherit flag */
1464                 LPCSTR name )   /* [in] Name of file-mapping object */
1465 {
1466     WCHAR buffer[MAX_PATH];
1467
1468     if (!name) return OpenFileMappingW( access, inherit, NULL );
1469
1470     if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1471     {
1472         SetLastError( ERROR_FILENAME_EXCED_RANGE );
1473         return 0;
1474     }
1475     return OpenFileMappingW( access, inherit, buffer );
1476 }
1477
1478
1479 /***********************************************************************
1480  *             OpenFileMappingW   (KERNEL32.@)
1481  * See OpenFileMappingA
1482  */
1483 HANDLE WINAPI OpenFileMappingW( DWORD access, BOOL inherit, LPCWSTR name)
1484 {
1485     HANDLE ret;
1486     DWORD len = name ? strlenW(name) : 0;
1487     if (len >= MAX_PATH)
1488     {
1489         SetLastError( ERROR_FILENAME_EXCED_RANGE );
1490         return 0;
1491     }
1492     SERVER_START_REQ( open_mapping )
1493     {
1494         req->access  = access;
1495         req->inherit = inherit;
1496         wine_server_add_data( req, name, len * sizeof(WCHAR) );
1497         wine_server_call_err( req );
1498         ret = reply->handle;
1499     }
1500     SERVER_END_REQ;
1501     return ret;
1502 }
1503
1504
1505 /***********************************************************************
1506  *             MapViewOfFile   (KERNEL32.@)
1507  * Maps a view of a file into the address space
1508  *
1509  * RETURNS
1510  *      Starting address of mapped view
1511  *      NULL: Failure
1512  */
1513 LPVOID WINAPI MapViewOfFile(
1514               HANDLE mapping,  /* [in] File-mapping object to map */
1515               DWORD access,      /* [in] Access mode */
1516               DWORD offset_high, /* [in] High-order 32 bits of file offset */
1517               DWORD offset_low,  /* [in] Low-order 32 bits of file offset */
1518               DWORD count        /* [in] Number of bytes to map */
1519 ) {
1520     return MapViewOfFileEx( mapping, access, offset_high,
1521                             offset_low, count, NULL );
1522 }
1523
1524
1525 /***********************************************************************
1526  *             MapViewOfFileEx   (KERNEL32.@)
1527  * Maps a view of a file into the address space
1528  *
1529  * RETURNS
1530  *      Starting address of mapped view
1531  *      NULL: Failure
1532  */
1533 LPVOID WINAPI MapViewOfFileEx(
1534               HANDLE handle,   /* [in] File-mapping object to map */
1535               DWORD access,      /* [in] Access mode */
1536               DWORD offset_high, /* [in] High-order 32 bits of file offset */
1537               DWORD offset_low,  /* [in] Low-order 32 bits of file offset */
1538               DWORD count,       /* [in] Number of bytes to map */
1539               LPVOID addr        /* [in] Suggested starting address for mapped view */
1540 ) {
1541     FILE_VIEW *view;
1542     UINT size = 0;
1543     int flags = MAP_PRIVATE;
1544     int unix_handle = -1;
1545     int prot, res;
1546     void *base, *ptr = (void *)-1, *ret;
1547     DWORD size_low, size_high, header_size, shared_size;
1548     HANDLE shared_file;
1549     BOOL removable;
1550
1551     /* Check parameters */
1552
1553     if ((offset_low & granularity_mask) ||
1554         (addr && ((UINT_PTR)addr & granularity_mask)))
1555     {
1556         SetLastError( ERROR_INVALID_PARAMETER );
1557         return NULL;
1558     }
1559
1560     SERVER_START_REQ( get_mapping_info )
1561     {
1562         req->handle = handle;
1563         res = wine_server_call_err( req );
1564         prot        = reply->protect;
1565         base        = reply->base;
1566         size_low    = reply->size_low;
1567         size_high   = reply->size_high;
1568         header_size = reply->header_size;
1569         shared_file = reply->shared_file;
1570         shared_size = reply->shared_size;
1571         removable   = (reply->drive_type == DRIVE_REMOVABLE ||
1572                        reply->drive_type == DRIVE_CDROM);
1573     }
1574     SERVER_END_REQ;
1575     if (res) goto error;
1576
1577     if ((unix_handle = FILE_GetUnixHandle( handle, 0 )) == -1) goto error;
1578
1579     if (prot & VPROT_IMAGE)
1580         return map_image( handle, unix_handle, base, size_low, header_size,
1581                           shared_file, shared_size, removable );
1582
1583
1584     if (size_high)
1585         ERR("Sizes larger than 4Gb not supported\n");
1586
1587     if ((offset_low >= size_low) ||
1588         (count > size_low - offset_low))
1589     {
1590         SetLastError( ERROR_INVALID_PARAMETER );
1591         goto error;
1592     }
1593     if (count) size = ROUND_SIZE( offset_low, count );
1594     else size = size_low - offset_low;
1595
1596     switch(access)
1597     {
1598     case FILE_MAP_ALL_ACCESS:
1599     case FILE_MAP_WRITE:
1600     case FILE_MAP_WRITE | FILE_MAP_READ:
1601         if (!(prot & VPROT_WRITE))
1602         {
1603             SetLastError( ERROR_INVALID_PARAMETER );
1604             goto error;
1605         }
1606         flags = MAP_SHARED;
1607         /* fall through */
1608     case FILE_MAP_READ:
1609     case FILE_MAP_COPY:
1610     case FILE_MAP_COPY | FILE_MAP_READ:
1611         if (prot & VPROT_READ) break;
1612         /* fall through */
1613     default:
1614         SetLastError( ERROR_INVALID_PARAMETER );
1615         goto error;
1616     }
1617
1618     /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1619      * which has a view of this mapping commits some pages, they will
1620      * appear commited in all other processes, which have the same
1621      * view created. Since we don`t support this yet, we create the
1622      * whole mapping commited.
1623      */
1624     prot |= VPROT_COMMITTED;
1625
1626     /* Reserve a properly aligned area */
1627
1628     if ((ptr = anon_mmap_aligned( addr, size, PROT_NONE, 0 )) == (void *)-1) goto error;
1629
1630     /* Map the file */
1631
1632     TRACE("handle=%x size=%x offset=%lx\n", handle, size, offset_low );
1633
1634     ret = VIRTUAL_mmap( unix_handle, ptr, size, offset_low, offset_high,
1635                         VIRTUAL_GetUnixProt( prot ), flags | MAP_FIXED, &removable );
1636     if (ret != ptr)
1637     {
1638         ERR( "VIRTUAL_mmap %p %x %lx%08lx failed\n", ptr, size, offset_high, offset_low );
1639         goto error;
1640     }
1641     if (removable) handle = 0;  /* don't keep handle open on removable media */
1642
1643     if (!(view = VIRTUAL_CreateView( ptr, size, 0, prot, handle )))
1644     {
1645         SetLastError( ERROR_OUTOFMEMORY );
1646         goto error;
1647     }
1648     if (unix_handle != -1) close( unix_handle );
1649     return ptr;
1650
1651 error:
1652     if (unix_handle != -1) close( unix_handle );
1653     if (ptr != (void *)-1) munmap( ptr, size );
1654     return NULL;
1655 }
1656
1657
1658 /***********************************************************************
1659  *             FlushViewOfFile   (KERNEL32.@)
1660  * Writes to the disk a byte range within a mapped view of a file
1661  *
1662  * RETURNS
1663  *      TRUE: Success
1664  *      FALSE: Failure
1665  */
1666 BOOL WINAPI FlushViewOfFile(
1667               LPCVOID base, /* [in] Start address of byte range to flush */
1668               DWORD cbFlush /* [in] Number of bytes in range */
1669 ) {
1670     FILE_VIEW *view;
1671     void *addr = ROUND_ADDR( base, page_mask );
1672
1673     TRACE("FlushViewOfFile at %p for %ld bytes\n",
1674                      base, cbFlush );
1675
1676     if (!(view = VIRTUAL_FindView( addr )))
1677     {
1678         SetLastError( ERROR_INVALID_PARAMETER );
1679         return FALSE;
1680     }
1681     if (!cbFlush) cbFlush = view->size;
1682     if (!msync( addr, cbFlush, MS_SYNC )) return TRUE;
1683     SetLastError( ERROR_INVALID_PARAMETER );
1684     return FALSE;
1685 }
1686
1687
1688 /***********************************************************************
1689  *             UnmapViewOfFile   (KERNEL32.@)
1690  * Unmaps a mapped view of a file.
1691  *
1692  * NOTES
1693  *      Should addr be an LPCVOID?
1694  *
1695  * RETURNS
1696  *      TRUE: Success
1697  *      FALSE: Failure
1698  */
1699 BOOL WINAPI UnmapViewOfFile(
1700               LPVOID addr /* [in] Address where mapped view begins */
1701 ) {
1702     FILE_VIEW *view;
1703     void *base = ROUND_ADDR( addr, page_mask );
1704     if (!(view = VIRTUAL_FindView( base )) || (base != view->base))
1705     {
1706         SetLastError( ERROR_INVALID_PARAMETER );
1707         return FALSE;
1708     }
1709     VIRTUAL_DeleteView( view );
1710     return TRUE;
1711 }