Share the system heap between different address spaces. Made process
[wine] / memory / virtual.c
1 /*
2  * Win32 virtual memory functions
3  *
4  * Copyright 1997 Alexandre Julliard
5  */
6
7 #include "config.h"
8
9 #include <assert.h>
10 #include <errno.h>
11 #ifdef HAVE_SYS_ERRNO_H
12 #include <sys/errno.h>
13 #endif
14 #include <fcntl.h>
15 #include <unistd.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <sys/types.h>
19 #ifdef HAVE_SYS_MMAN_H
20 #include <sys/mman.h>
21 #endif
22 #include "winbase.h"
23 #include "winerror.h"
24 #include "file.h"
25 #include "process.h"
26 #include "xmalloc.h"
27 #include "global.h"
28 #include "server.h"
29 #include "debugtools.h"
30
31 DEFAULT_DEBUG_CHANNEL(virtual)
32
33 #ifndef MS_SYNC
34 #define MS_SYNC 0
35 #endif
36
37 /* File view */
38 typedef struct _FV
39 {
40     struct _FV   *next;        /* Next view */
41     struct _FV   *prev;        /* Prev view */
42     UINT        base;        /* Base address */
43     UINT        size;        /* Size in bytes */
44     UINT        flags;       /* Allocation flags */
45     UINT        offset;      /* Offset from start of mapped file */
46     HANDLE      mapping;     /* Handle to the file mapping */
47     HANDLERPROC   handlerProc; /* Fault handler */
48     LPVOID        handlerArg;  /* Fault handler argument */
49     BYTE          protect;     /* Protection for all pages at allocation time */
50     BYTE          prot[1];     /* Protection byte for each page */
51 } FILE_VIEW;
52
53 /* Per-view flags */
54 #define VFLAG_SYSTEM     0x01
55
56 /* Conversion from VPROT_* to Win32 flags */
57 static const BYTE VIRTUAL_Win32Flags[16] =
58 {
59     PAGE_NOACCESS,              /* 0 */
60     PAGE_READONLY,              /* READ */
61     PAGE_READWRITE,             /* WRITE */
62     PAGE_READWRITE,             /* READ | WRITE */
63     PAGE_EXECUTE,               /* EXEC */
64     PAGE_EXECUTE_READ,          /* READ | EXEC */
65     PAGE_EXECUTE_READWRITE,     /* WRITE | EXEC */
66     PAGE_EXECUTE_READWRITE,     /* READ | WRITE | EXEC */
67     PAGE_WRITECOPY,             /* WRITECOPY */
68     PAGE_WRITECOPY,             /* READ | WRITECOPY */
69     PAGE_WRITECOPY,             /* WRITE | WRITECOPY */
70     PAGE_WRITECOPY,             /* READ | WRITE | WRITECOPY */
71     PAGE_EXECUTE_WRITECOPY,     /* EXEC | WRITECOPY */
72     PAGE_EXECUTE_WRITECOPY,     /* READ | EXEC | WRITECOPY */
73     PAGE_EXECUTE_WRITECOPY,     /* WRITE | EXEC | WRITECOPY */
74     PAGE_EXECUTE_WRITECOPY      /* READ | WRITE | EXEC | WRITECOPY */
75 };
76
77
78 static FILE_VIEW *VIRTUAL_FirstView;
79
80 #ifdef __i386__
81 /* These are always the same on an i386, and it will be faster this way */
82 # define page_mask  0xfff
83 # define page_shift 12
84 # define granularity_mask 0xffff
85 #else
86 static UINT page_shift;
87 static UINT page_mask;
88 static UINT granularity_mask;  /* Allocation granularity (usually 64k) */
89 #endif  /* __i386__ */
90
91 #define ROUND_ADDR(addr) \
92    ((UINT)(addr) & ~page_mask)
93
94 #define ROUND_SIZE(addr,size) \
95    (((UINT)(size) + ((UINT)(addr) & page_mask) + page_mask) & ~page_mask)
96
97 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
98    if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
99
100 /***********************************************************************
101  *           VIRTUAL_GetProtStr
102  */
103 static const char *VIRTUAL_GetProtStr( BYTE prot )
104 {
105     static char buffer[6];
106     buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
107     buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
108     buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
109     buffer[3] = (prot & VPROT_WRITE) ?
110                     ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
111     buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
112     buffer[5] = 0;
113     return buffer;
114 }
115
116
117 /***********************************************************************
118  *           VIRTUAL_DumpView
119  */
120 static void VIRTUAL_DumpView( FILE_VIEW *view )
121 {
122     UINT i, count;
123     UINT addr = view->base;
124     BYTE prot = view->prot[0];
125
126     DPRINTF( "View: %08x - %08x%s",
127           view->base, view->base + view->size - 1,
128           (view->flags & VFLAG_SYSTEM) ? " (system)" : "" );
129     if (view->mapping)
130         DPRINTF( " %d @ %08x\n", view->mapping, view->offset );
131     else
132         DPRINTF( " (anonymous)\n");
133
134     for (count = i = 1; i < view->size >> page_shift; i++, count++)
135     {
136         if (view->prot[i] == prot) continue;
137         DPRINTF( "      %08x - %08x %s\n",
138               addr, addr + (count << page_shift) - 1,
139               VIRTUAL_GetProtStr(prot) );
140         addr += (count << page_shift);
141         prot = view->prot[i];
142         count = 0;
143     }
144     if (count)
145         DPRINTF( "      %08x - %08x %s\n",
146               addr, addr + (count << page_shift) - 1,
147               VIRTUAL_GetProtStr(prot) );
148 }
149
150
151 /***********************************************************************
152  *           VIRTUAL_Dump
153  */
154 void VIRTUAL_Dump(void)
155 {
156     FILE_VIEW *view = VIRTUAL_FirstView;
157     DPRINTF( "\nDump of all virtual memory views:\n\n" );
158     while (view)
159     {
160         VIRTUAL_DumpView( view );
161         view = view->next;
162     }
163 }
164
165
166 /***********************************************************************
167  *           VIRTUAL_FindView
168  *
169  * Find the view containing a given address.
170  *
171  * RETURNS
172  *      View: Success
173  *      NULL: Failure
174  */
175 static FILE_VIEW *VIRTUAL_FindView(
176                   UINT addr /* [in] Address */
177 ) {
178     FILE_VIEW *view = VIRTUAL_FirstView;
179     while (view)
180     {
181         if (view->base > addr) return NULL;
182         if (view->base + view->size > addr) return view;
183         view = view->next;
184     }
185     return NULL;
186 }
187
188
189 /***********************************************************************
190  *           VIRTUAL_CreateView
191  *
192  * Create a new view and add it in the linked list.
193  */
194 static FILE_VIEW *VIRTUAL_CreateView( UINT base, UINT size, UINT offset,
195                                       UINT flags, BYTE vprot,
196                                       HANDLE mapping )
197 {
198     FILE_VIEW *view, *prev;
199
200     /* Create the view structure */
201
202     assert( !(base & page_mask) );
203     assert( !(size & page_mask) );
204     size >>= page_shift;
205     if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
206     view->base    = base;
207     view->size    = size << page_shift;
208     view->flags   = flags;
209     view->offset  = offset;
210     view->mapping = mapping;
211     view->protect = vprot;
212     view->handlerProc = NULL;
213     memset( view->prot, vprot, size );
214
215     /* Duplicate the mapping handle */
216
217     if ((view->mapping != -1) &&
218         !DuplicateHandle( GetCurrentProcess(), view->mapping,
219                           GetCurrentProcess(), &view->mapping,
220                           0, FALSE, DUPLICATE_SAME_ACCESS ))
221     {
222         free( view );
223         return NULL;
224     }
225
226     /* Insert it in the linked list */
227
228     if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
229     {
230         view->next = VIRTUAL_FirstView;
231         view->prev = NULL;
232         if (view->next) view->next->prev = view;
233         VIRTUAL_FirstView = view;
234     }
235     else
236     {
237         prev = VIRTUAL_FirstView;
238         while (prev->next && (prev->next->base < base)) prev = prev->next;
239         view->next = prev->next;
240         view->prev = prev;
241         if (view->next) view->next->prev = view;
242         prev->next  = view;
243     }
244     VIRTUAL_DEBUG_DUMP_VIEW( view );
245     return view;
246 }
247
248
249 /***********************************************************************
250  *           VIRTUAL_DeleteView
251  * Deletes a view.
252  *
253  * RETURNS
254  *      None
255  */
256 static void VIRTUAL_DeleteView(
257             FILE_VIEW *view /* [in] View */
258 ) {
259     FILE_munmap( (void *)view->base, 0, view->size );
260     if (view->next) view->next->prev = view->prev;
261     if (view->prev) view->prev->next = view->next;
262     else VIRTUAL_FirstView = view->next;
263     if (view->mapping) CloseHandle( view->mapping );
264     free( view );
265 }
266
267
268 /***********************************************************************
269  *           VIRTUAL_GetUnixProt
270  *
271  * Convert page protections to protection for mmap/mprotect.
272  */
273 static int VIRTUAL_GetUnixProt( BYTE vprot )
274 {
275     int prot = 0;
276     if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
277     {
278         if (vprot & VPROT_READ) prot |= PROT_READ;
279         if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
280         if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
281     }
282     return prot;
283 }
284
285
286 /***********************************************************************
287  *           VIRTUAL_GetWin32Prot
288  *
289  * Convert page protections to Win32 flags.
290  *
291  * RETURNS
292  *      None
293  */
294 static void VIRTUAL_GetWin32Prot(
295             BYTE vprot,     /* [in] Page protection flags */
296             DWORD *protect, /* [out] Location to store Win32 protection flags */
297             DWORD *state    /* [out] Location to store mem state flag */
298 ) {
299     if (protect) {
300         *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
301 /*      if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
302         if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
303
304         if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
305     }
306
307     if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
308 }
309
310
311 /***********************************************************************
312  *           VIRTUAL_GetProt
313  *
314  * Build page protections from Win32 flags.
315  *
316  * RETURNS
317  *      Value of page protection flags
318  */
319 static BYTE VIRTUAL_GetProt(
320             DWORD protect  /* [in] Win32 protection flags */
321 ) {
322     BYTE vprot;
323
324     switch(protect & 0xff)
325     {
326     case PAGE_READONLY:
327         vprot = VPROT_READ;
328         break;
329     case PAGE_READWRITE:
330         vprot = VPROT_READ | VPROT_WRITE;
331         break;
332     case PAGE_WRITECOPY:
333         vprot = VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
334         break;
335     case PAGE_EXECUTE:
336         vprot = VPROT_EXEC;
337         break;
338     case PAGE_EXECUTE_READ:
339         vprot = VPROT_EXEC | VPROT_READ;
340         break;
341     case PAGE_EXECUTE_READWRITE:
342         vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
343         break;
344     case PAGE_EXECUTE_WRITECOPY:
345         vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
346         break;
347     case PAGE_NOACCESS:
348     default:
349         vprot = 0;
350         break;
351     }
352     if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
353     if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
354     return vprot;
355 }
356
357
358 /***********************************************************************
359  *           VIRTUAL_SetProt
360  *
361  * Change the protection of a range of pages.
362  *
363  * RETURNS
364  *      TRUE: Success
365  *      FALSE: Failure
366  */
367 static BOOL VIRTUAL_SetProt(
368               FILE_VIEW *view, /* [in] Pointer to view */
369               UINT base,     /* [in] Starting address */
370               UINT size,     /* [in] Size in bytes */
371               BYTE vprot       /* [in] Protections to use */
372 ) {
373     TRACE("%08x-%08x %s\n",
374                      base, base + size - 1, VIRTUAL_GetProtStr( vprot ) );
375
376     if (mprotect( (void *)base, size, VIRTUAL_GetUnixProt(vprot) ))
377         return FALSE;  /* FIXME: last error */
378
379     memset( view->prot + ((base - view->base) >> page_shift),
380             vprot, size >> page_shift );
381     VIRTUAL_DEBUG_DUMP_VIEW( view );
382     return TRUE;
383 }
384
385
386 /***********************************************************************
387  *             VIRTUAL_CheckFlags
388  *
389  * Check that all pages in a range have the given flags.
390  *
391  * RETURNS
392  *      TRUE: They do
393  *      FALSE: They do not
394  */
395 static BOOL VIRTUAL_CheckFlags(
396               UINT base, /* [in] Starting address */
397               UINT size, /* [in] Size in bytes */
398               BYTE flags   /* [in] Flags to check for */
399 ) {
400     FILE_VIEW *view;
401     UINT page;
402
403     if (!size) return TRUE;
404     if (!(view = VIRTUAL_FindView( base ))) return FALSE;
405     if (view->base + view->size < base + size) return FALSE;
406     page = (base - view->base) >> page_shift;
407     size = ROUND_SIZE( base, size ) >> page_shift;
408     while (size--) if ((view->prot[page++] & flags) != flags) return FALSE;
409     return TRUE;
410 }
411
412
413 /***********************************************************************
414  *           VIRTUAL_Init
415  */
416 BOOL VIRTUAL_Init(void)
417 {
418 #ifndef __i386__
419     DWORD page_size;
420
421 # ifdef HAVE_GETPAGESIZE
422     page_size = getpagesize();
423 # else
424 #  ifdef __svr4__
425     page_size = sysconf(_SC_PAGESIZE);
426 #  else
427 #   error Cannot get the page size on this platform
428 #  endif
429 # endif
430     page_mask = page_size - 1;
431     granularity_mask = 0xffff;  /* hard-coded for now */
432     /* Make sure we have a power of 2 */
433     assert( !(page_size & page_mask) );
434     page_shift = 0;
435     while ((1 << page_shift) != page_size) page_shift++;
436 #endif  /* !__i386__ */
437
438 #ifdef linux
439     {
440         /* Do not use stdio here since it may temporarily change the size
441          * of some segments (ie libc6 adds 0x1000 per open FILE)
442          */
443         int fd = open ("/proc/self/maps", O_RDONLY);
444         if (fd >= 0)
445         {
446             char buffer[512]; /* line might be rather long in 2.1 */
447
448             for (;;)
449             {
450                 int start, end, offset;
451                 char r, w, x, p;
452                 BYTE vprot = VPROT_COMMITTED;
453
454                 char * ptr = buffer;
455                 int count = sizeof(buffer);
456                 while (1 == read(fd, ptr, 1) && *ptr != '\n' && --count > 0)
457                     ptr++;
458
459                 if (*ptr != '\n') break;
460                 *ptr = '\0';
461
462                 sscanf( buffer, "%x-%x %c%c%c%c %x",
463                         &start, &end, &r, &w, &x, &p, &offset );
464                 if (r == 'r') vprot |= VPROT_READ;
465                 if (w == 'w') vprot |= VPROT_WRITE;
466                 if (x == 'x') vprot |= VPROT_EXEC;
467                 if (p == 'p') vprot |= VPROT_WRITECOPY;
468                 VIRTUAL_CreateView( start, end - start, 0,
469                                     VFLAG_SYSTEM, vprot, -1 );
470             }
471             close (fd);
472         }
473     }
474 #endif  /* linux */
475     return TRUE;
476 }
477
478
479 /***********************************************************************
480  *           VIRTUAL_GetPageSize
481  */
482 DWORD VIRTUAL_GetPageSize(void)
483 {
484     return 1 << page_shift;
485 }
486
487
488 /***********************************************************************
489  *           VIRTUAL_GetGranularity
490  */
491 DWORD VIRTUAL_GetGranularity(void)
492 {
493     return granularity_mask + 1;
494 }
495
496
497 /***********************************************************************
498  *           VIRTUAL_SetFaultHandler
499  */
500 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
501 {
502     FILE_VIEW *view;
503
504     if (!(view = VIRTUAL_FindView((UINT)addr))) return FALSE;
505     view->handlerProc = proc;
506     view->handlerArg  = arg;
507     return TRUE;
508 }
509
510 /***********************************************************************
511  *           VIRTUAL_HandleFault
512  */
513 BOOL VIRTUAL_HandleFault( LPCVOID addr )
514 {
515     FILE_VIEW *view = VIRTUAL_FindView((UINT)addr);
516
517     if (view && view->handlerProc)
518         return view->handlerProc(view->handlerArg, addr);
519     return FALSE;
520 }
521
522
523 /***********************************************************************
524  *             VirtualAlloc   (KERNEL32.548)
525  * Reserves or commits a region of pages in virtual address space
526  *
527  * RETURNS
528  *      Base address of allocated region of pages
529  *      NULL: Failure
530  */
531 LPVOID WINAPI VirtualAlloc(
532               LPVOID addr,  /* [in] Address of region to reserve or commit */
533               DWORD size,   /* [in] Size of region */
534               DWORD type,   /* [in] Type of allocation */
535               DWORD protect /* [in] Type of access protection */
536 ) {
537     FILE_VIEW *view;
538     UINT base, ptr, view_size;
539     BYTE vprot;
540
541     TRACE("%08x %08lx %lx %08lx\n",
542                      (UINT)addr, size, type, protect );
543
544     /* Round parameters to a page boundary */
545
546     if (size > 0x7fc00000)  /* 2Gb - 4Mb */
547     {
548         SetLastError( ERROR_OUTOFMEMORY );
549         return NULL;
550     }
551     if (addr)
552     {
553         if (type & MEM_RESERVE) /* Round down to 64k boundary */
554             base = (UINT)addr & ~granularity_mask;
555         else
556             base = ROUND_ADDR( addr );
557         size = (((UINT)addr + size + page_mask) & ~page_mask) - base;
558         if ((base <= granularity_mask) || (base + size < base))
559         {
560             /* disallow low 64k and wrap-around */
561             SetLastError( ERROR_INVALID_PARAMETER );
562             return NULL;
563         }
564     }
565     else
566     {
567         base = 0;
568         size = (size + page_mask) & ~page_mask;
569     }
570
571     if (type & MEM_TOP_DOWN) {
572         /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
573          *        Is there _ANY_ way to do it with UNIX mmap()?
574          */
575         WARN("MEM_TOP_DOWN ignored\n");
576         type &= ~MEM_TOP_DOWN;
577     }
578     /* Compute the protection flags */
579
580     if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
581         (type & ~(MEM_COMMIT | MEM_RESERVE)))
582     {
583         SetLastError( ERROR_INVALID_PARAMETER );
584         return NULL;
585     }
586     if (type & MEM_COMMIT)
587         vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
588     else vprot = 0;
589
590     /* Reserve the memory */
591
592     if ((type & MEM_RESERVE) || !base)
593     {
594         view_size = size + (base ? 0 : granularity_mask + 1);
595         ptr = (UINT)FILE_dommap( -1, (LPVOID)base, 0, view_size, 0, 0,
596                                    VIRTUAL_GetUnixProt( vprot ), MAP_PRIVATE );
597         if (ptr == (UINT)-1)
598         {
599             SetLastError( ERROR_OUTOFMEMORY );
600             return NULL;
601         }
602         if (!base)
603         {
604             /* Release the extra memory while keeping the range */
605             /* starting on a 64k boundary. */
606
607             if (ptr & granularity_mask)
608             {
609                 UINT extra = granularity_mask + 1 - (ptr & granularity_mask);
610                 FILE_munmap( (void *)ptr, 0, extra );
611                 ptr += extra;
612                 view_size -= extra;
613             }
614             if (view_size > size)
615                 FILE_munmap( (void *)(ptr + size), 0, view_size - size );
616         }
617         else if (ptr != base)
618         {
619             /* We couldn't get the address we wanted */
620             FILE_munmap( (void *)ptr, 0, view_size );
621             SetLastError( ERROR_INVALID_ADDRESS );
622             return NULL;
623         }
624         if (!(view = VIRTUAL_CreateView( ptr, size, 0, 0, vprot, -1 )))
625         {
626             FILE_munmap( (void *)ptr, 0, size );
627             SetLastError( ERROR_OUTOFMEMORY );
628             return NULL;
629         }
630         VIRTUAL_DEBUG_DUMP_VIEW( view );
631         return (LPVOID)ptr;
632     }
633
634     /* Commit the pages */
635
636     if (!(view = VIRTUAL_FindView( base )) ||
637         (base + size > view->base + view->size))
638     {
639         SetLastError( ERROR_INVALID_ADDRESS );
640         return NULL;
641     }
642
643     if (!VIRTUAL_SetProt( view, base, size, vprot )) return NULL;
644     return (LPVOID)base;
645 }
646
647
648 /***********************************************************************
649  *             VirtualFree   (KERNEL32.550)
650  * Release or decommits a region of pages in virtual address space.
651  * 
652  * RETURNS
653  *      TRUE: Success
654  *      FALSE: Failure
655  */
656 BOOL WINAPI VirtualFree(
657               LPVOID addr, /* [in] Address of region of committed pages */
658               DWORD size,  /* [in] Size of region */
659               DWORD type   /* [in] Type of operation */
660 ) {
661     FILE_VIEW *view;
662     UINT base;
663
664     TRACE("%08x %08lx %lx\n",
665                      (UINT)addr, size, type );
666
667     /* Fix the parameters */
668
669     size = ROUND_SIZE( addr, size );
670     base = ROUND_ADDR( addr );
671
672     if (!(view = VIRTUAL_FindView( base )) ||
673         (base + size > view->base + view->size))
674     {
675         SetLastError( ERROR_INVALID_PARAMETER );
676         return FALSE;
677     }
678
679     /* Compute the protection flags */
680
681     if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
682     {
683         SetLastError( ERROR_INVALID_PARAMETER );
684         return FALSE;
685     }
686
687     /* Free the pages */
688
689     if (type == MEM_RELEASE)
690     {
691         if (size || (base != view->base))
692         {
693             SetLastError( ERROR_INVALID_PARAMETER );
694             return FALSE;
695         }
696         VIRTUAL_DeleteView( view );
697         return TRUE;
698     }
699
700     /* Decommit the pages by remapping zero-pages instead */
701
702     if (FILE_dommap( -1, (LPVOID)base, 0, size, 0, 0,
703                      VIRTUAL_GetUnixProt( 0 ), MAP_PRIVATE|MAP_FIXED ) 
704         != (LPVOID)base)
705         ERR( "Could not remap pages, expect trouble\n" );
706     return VIRTUAL_SetProt( view, base, size, 0 );
707 }
708
709
710 /***********************************************************************
711  *             VirtualLock   (KERNEL32.551)
712  * Locks the specified region of virtual address space
713  * 
714  * NOTE
715  *      Always returns TRUE
716  *
717  * RETURNS
718  *      TRUE: Success
719  *      FALSE: Failure
720  */
721 BOOL WINAPI VirtualLock(
722               LPVOID addr, /* [in] Address of first byte of range to lock */
723               DWORD size   /* [in] Number of bytes in range to lock */
724 ) {
725     return TRUE;
726 }
727
728
729 /***********************************************************************
730  *             VirtualUnlock   (KERNEL32.556)
731  * Unlocks a range of pages in the virtual address space
732  *
733  * NOTE
734  *      Always returns TRUE
735  *
736  * RETURNS
737  *      TRUE: Success
738  *      FALSE: Failure
739  */
740 BOOL WINAPI VirtualUnlock(
741               LPVOID addr, /* [in] Address of first byte of range */
742               DWORD size   /* [in] Number of bytes in range */
743 ) {
744     return TRUE;
745 }
746
747
748 /***********************************************************************
749  *             VirtualProtect   (KERNEL32.552)
750  * Changes the access protection on a region of committed pages
751  *
752  * RETURNS
753  *      TRUE: Success
754  *      FALSE: Failure
755  */
756 BOOL WINAPI VirtualProtect(
757               LPVOID addr,     /* [in] Address of region of committed pages */
758               DWORD size,      /* [in] Size of region */
759               DWORD new_prot,  /* [in] Desired access protection */
760               LPDWORD old_prot /* [out] Address of variable to get old protection */
761 ) {
762     FILE_VIEW *view;
763     UINT base, i;
764     BYTE vprot, *p;
765
766     TRACE("%08x %08lx %08lx\n",
767                      (UINT)addr, size, new_prot );
768
769     /* Fix the parameters */
770
771     size = ROUND_SIZE( addr, size );
772     base = ROUND_ADDR( addr );
773
774     if (!(view = VIRTUAL_FindView( base )) ||
775         (base + size > view->base + view->size))
776     {
777         SetLastError( ERROR_INVALID_PARAMETER );
778         return FALSE;
779     }
780
781     /* Make sure all the pages are committed */
782
783     p = view->prot + ((base - view->base) >> page_shift);
784     for (i = size >> page_shift; i; i--, p++)
785     {
786         if (!(*p & VPROT_COMMITTED))
787         {
788             SetLastError( ERROR_INVALID_PARAMETER );
789             return FALSE;
790         }
791     }
792
793     VIRTUAL_GetWin32Prot( view->prot[0], old_prot, NULL );
794     vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
795     return VIRTUAL_SetProt( view, base, size, vprot );
796 }
797
798
799 /***********************************************************************
800  *             VirtualProtectEx   (KERNEL32.553)
801  * Changes the access protection on a region of committed pages in the
802  * virtual address space of a specified process
803  *
804  * RETURNS
805  *      TRUE: Success
806  *      FALSE: Failure
807  */
808 BOOL WINAPI VirtualProtectEx(
809               HANDLE handle, /* [in]  Handle of process */
810               LPVOID addr,     /* [in]  Address of region of committed pages */
811               DWORD size,      /* [in]  Size of region */
812               DWORD new_prot,  /* [in]  Desired access protection */
813               LPDWORD old_prot /* [out] Address of variable to get old protection */ )
814 {
815     if (PROCESS_IsCurrent( handle ))
816         return VirtualProtect( addr, size, new_prot, old_prot );
817     ERR("Unsupported on other process\n");
818     return FALSE;
819 }
820
821
822 /***********************************************************************
823  *             VirtualQuery   (KERNEL32.554)
824  * Provides info about a range of pages in virtual address space
825  *
826  * RETURNS
827  *      Number of bytes returned in information buffer
828  */
829 DWORD WINAPI VirtualQuery(
830              LPCVOID addr,                    /* [in]  Address of region */
831              LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
832              DWORD len                        /* [in]  Size of buffer */
833 ) {
834     FILE_VIEW *view = VIRTUAL_FirstView;
835     UINT base = ROUND_ADDR( addr );
836     UINT alloc_base = 0;
837     UINT size = 0;
838
839     /* Find the view containing the address */
840
841     for (;;)
842     {
843         if (!view)
844         {
845             size = 0xffff0000 - alloc_base;
846             break;
847         }
848         if (view->base > base)
849         {
850             size = view->base - alloc_base;
851             view = NULL;
852             break;
853         }
854         if (view->base + view->size > base)
855         {
856             alloc_base = view->base;
857             size = view->size;
858             break;
859         }
860         alloc_base = view->base + view->size;
861         view = view->next;
862     }
863
864     /* Fill the info structure */
865
866     if (!view)
867     {
868         info->State             = MEM_FREE;
869         info->Protect           = 0;
870         info->AllocationProtect = 0;
871         info->Type              = 0;
872     }
873     else
874     {
875         BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
876         VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
877         for (size = base - alloc_base; size < view->size; size += page_mask+1)
878             if (view->prot[size >> page_shift] != vprot) break;
879         info->AllocationProtect = view->protect;
880         info->Type              = MEM_PRIVATE;  /* FIXME */
881     }
882
883     info->BaseAddress    = (LPVOID)base;
884     info->AllocationBase = (LPVOID)alloc_base;
885     info->RegionSize     = size - (base - alloc_base);
886     return sizeof(*info);
887 }
888
889
890 /***********************************************************************
891  *             VirtualQueryEx   (KERNEL32.555)
892  * Provides info about a range of pages in virtual address space of a
893  * specified process
894  *
895  * RETURNS
896  *      Number of bytes returned in information buffer
897  */
898 DWORD WINAPI VirtualQueryEx(
899              HANDLE handle,                 /* [in] Handle of process */
900              LPCVOID addr,                    /* [in] Address of region */
901              LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
902              DWORD len                        /* [in] Size of buffer */ )
903 {
904     if (PROCESS_IsCurrent( handle ))
905         return VirtualQuery( addr, info, len );
906     ERR("Unsupported on other process\n");
907     return 0;
908 }
909
910
911 /***********************************************************************
912  *             IsBadReadPtr32   (KERNEL32.354)
913  *
914  * RETURNS
915  *      FALSE: Process has read access to entire block
916  *      TRUE: Otherwise
917  */
918 BOOL WINAPI IsBadReadPtr(
919               LPCVOID ptr, /* Address of memory block */
920               UINT size  /* Size of block */
921 ) {
922     return !VIRTUAL_CheckFlags( (UINT)ptr, size,
923                                 VPROT_READ | VPROT_COMMITTED );
924 }
925
926
927 /***********************************************************************
928  *             IsBadWritePtr32   (KERNEL32.357)
929  *
930  * RETURNS
931  *      FALSE: Process has write access to entire block
932  *      TRUE: Otherwise
933  */
934 BOOL WINAPI IsBadWritePtr(
935               LPVOID ptr, /* [in] Address of memory block */
936               UINT size /* [in] Size of block in bytes */
937 ) {
938     return !VIRTUAL_CheckFlags( (UINT)ptr, size,
939                                 VPROT_WRITE | VPROT_COMMITTED );
940 }
941
942
943 /***********************************************************************
944  *             IsBadHugeReadPtr32   (KERNEL32.352)
945  * RETURNS
946  *      FALSE: Process has read access to entire block
947  *      TRUE: Otherwise
948  */
949 BOOL WINAPI IsBadHugeReadPtr(
950               LPCVOID ptr, /* [in] Address of memory block */
951               UINT size  /* [in] Size of block */
952 ) {
953     return IsBadReadPtr( ptr, size );
954 }
955
956
957 /***********************************************************************
958  *             IsBadHugeWritePtr32   (KERNEL32.353)
959  * RETURNS
960  *      FALSE: Process has write access to entire block
961  *      TRUE: Otherwise
962  */
963 BOOL WINAPI IsBadHugeWritePtr(
964               LPVOID ptr, /* [in] Address of memory block */
965               UINT size /* [in] Size of block */
966 ) {
967     return IsBadWritePtr( ptr, size );
968 }
969
970
971 /***********************************************************************
972  *             IsBadCodePtr32   (KERNEL32.351)
973  *
974  * RETURNS
975  *      FALSE: Process has read access to specified memory
976  *      TRUE: Otherwise
977  */
978 BOOL WINAPI IsBadCodePtr(
979               FARPROC ptr /* [in] Address of function */
980 ) {
981     return !VIRTUAL_CheckFlags( (UINT)ptr, 1, VPROT_EXEC | VPROT_COMMITTED );
982 }
983
984
985 /***********************************************************************
986  *             IsBadStringPtr32A   (KERNEL32.355)
987  *
988  * RETURNS
989  *      FALSE: Read access to all bytes in string
990  *      TRUE: Else
991  */
992 BOOL WINAPI IsBadStringPtrA(
993               LPCSTR str, /* [in] Address of string */
994               UINT max  /* [in] Maximum size of string */
995 ) {
996     FILE_VIEW *view;
997     UINT page, count;
998
999     if (!max) return FALSE;
1000     if (!(view = VIRTUAL_FindView( (UINT)str ))) return TRUE;
1001     page  = ((UINT)str - view->base) >> page_shift;
1002     count = page_mask + 1 - ((UINT)str & page_mask);
1003
1004     while (max)
1005     {
1006         if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) != 
1007                                                 (VPROT_READ | VPROT_COMMITTED))
1008             return TRUE;
1009         if (count > max) count = max;
1010         max -= count;
1011         while (count--) if (!*str++) return FALSE;
1012         if (++page >= view->size >> page_shift) return TRUE;
1013         count = page_mask + 1;
1014     }
1015     return FALSE;
1016 }
1017
1018
1019 /***********************************************************************
1020  *             IsBadStringPtr32W   (KERNEL32.356)
1021  * See IsBadStringPtr32A
1022  */
1023 BOOL WINAPI IsBadStringPtrW( LPCWSTR str, UINT max )
1024 {
1025     FILE_VIEW *view;
1026     UINT page, count;
1027
1028     if (!max) return FALSE;
1029     if (!(view = VIRTUAL_FindView( (UINT)str ))) return TRUE;
1030     page  = ((UINT)str - view->base) >> page_shift;
1031     count = (page_mask + 1 - ((UINT)str & page_mask)) / sizeof(WCHAR);
1032
1033     while (max)
1034     {
1035         if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) != 
1036                                                 (VPROT_READ | VPROT_COMMITTED))
1037             return TRUE;
1038         if (count > max) count = max;
1039         max -= count;
1040         while (count--) if (!*str++) return FALSE;
1041         if (++page >= view->size >> page_shift) return TRUE;
1042         count = (page_mask + 1) / sizeof(WCHAR);
1043     }
1044     return FALSE;
1045 }
1046
1047
1048 /***********************************************************************
1049  *             CreateFileMapping32A   (KERNEL32.46)
1050  * Creates a named or unnamed file-mapping object for the specified file
1051  *
1052  * RETURNS
1053  *      Handle: Success
1054  *      0: Mapping object does not exist
1055  *      NULL: Failure
1056  */
1057 HANDLE WINAPI CreateFileMappingA(
1058                 HFILE hFile,   /* [in] Handle of file to map */
1059                 SECURITY_ATTRIBUTES *sa, /* [in] Optional security attributes*/
1060                 DWORD protect,   /* [in] Protection for mapping object */
1061                 DWORD size_high, /* [in] High-order 32 bits of object size */
1062                 DWORD size_low,  /* [in] Low-order 32 bits of object size */
1063                 LPCSTR name      /* [in] Name of file-mapping object */ )
1064 {
1065     struct create_mapping_request *req = get_req_buffer();
1066     BYTE vprot;
1067
1068     /* Check parameters */
1069
1070     TRACE("(%x,%p,%08lx,%08lx%08lx,%s)\n",
1071           hFile, sa, protect, size_high, size_low, debugstr_a(name) );
1072
1073     vprot = VIRTUAL_GetProt( protect );
1074     if (protect & SEC_RESERVE)
1075     {
1076         if (hFile != INVALID_HANDLE_VALUE)
1077         {
1078             SetLastError( ERROR_INVALID_PARAMETER );
1079             return 0;
1080         }
1081     }
1082     else vprot |= VPROT_COMMITTED;
1083     if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1084
1085     /* Create the server object */
1086
1087     req->file_handle = hFile;
1088     req->size_high   = size_high;
1089     req->size_low    = size_low;
1090     req->protect     = vprot;
1091     req->inherit     = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1092     server_strcpyAtoW( req->name, name );
1093     SetLastError(0);
1094     server_call( REQ_CREATE_MAPPING );
1095     if (req->handle == -1) return 0;
1096     return req->handle;
1097 }
1098
1099
1100 /***********************************************************************
1101  *             CreateFileMapping32W   (KERNEL32.47)
1102  * See CreateFileMapping32A
1103  */
1104 HANDLE WINAPI CreateFileMappingW( HFILE hFile, LPSECURITY_ATTRIBUTES sa, 
1105                                   DWORD protect, DWORD size_high,  
1106                                   DWORD size_low, LPCWSTR name )
1107 {
1108     struct create_mapping_request *req = get_req_buffer();
1109     BYTE vprot;
1110
1111     /* Check parameters */
1112
1113     TRACE("(%x,%p,%08lx,%08lx%08lx,%s)\n",
1114           hFile, sa, protect, size_high, size_low, debugstr_w(name) );
1115
1116     vprot = VIRTUAL_GetProt( protect );
1117     if (protect & SEC_RESERVE)
1118     {
1119         if (hFile != INVALID_HANDLE_VALUE)
1120         {
1121             SetLastError( ERROR_INVALID_PARAMETER );
1122             return 0;
1123         }
1124     }
1125     else vprot |= VPROT_COMMITTED;
1126     if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1127
1128     /* Create the server object */
1129
1130     req->file_handle = hFile;
1131     req->size_high   = size_high;
1132     req->size_low    = size_low;
1133     req->protect     = vprot;
1134     req->inherit     = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1135     server_strcpyW( req->name, name );
1136     SetLastError(0);
1137     server_call( REQ_CREATE_MAPPING );
1138     if (req->handle == -1) return 0;
1139     return req->handle;
1140 }
1141
1142
1143 /***********************************************************************
1144  *             OpenFileMapping32A   (KERNEL32.397)
1145  * Opens a named file-mapping object.
1146  *
1147  * RETURNS
1148  *      Handle: Success
1149  *      NULL: Failure
1150  */
1151 HANDLE WINAPI OpenFileMappingA(
1152                 DWORD access,   /* [in] Access mode */
1153                 BOOL inherit, /* [in] Inherit flag */
1154                 LPCSTR name )   /* [in] Name of file-mapping object */
1155 {
1156     struct open_mapping_request *req = get_req_buffer();
1157
1158     req->access  = access;
1159     req->inherit = inherit;
1160     server_strcpyAtoW( req->name, name );
1161     server_call( REQ_OPEN_MAPPING );
1162     if (req->handle == -1) return 0; /* must return 0 on failure, not -1 */
1163     return req->handle;
1164 }
1165
1166
1167 /***********************************************************************
1168  *             OpenFileMapping32W   (KERNEL32.398)
1169  * See OpenFileMapping32A
1170  */
1171 HANDLE WINAPI OpenFileMappingW( DWORD access, BOOL inherit, LPCWSTR name)
1172 {
1173     struct open_mapping_request *req = get_req_buffer();
1174
1175     req->access  = access;
1176     req->inherit = inherit;
1177     server_strcpyW( req->name, name );
1178     server_call( REQ_OPEN_MAPPING );
1179     if (req->handle == -1) return 0; /* must return 0 on failure, not -1 */
1180     return req->handle;
1181 }
1182
1183
1184 /***********************************************************************
1185  *             MapViewOfFile   (KERNEL32.385)
1186  * Maps a view of a file into the address space
1187  *
1188  * RETURNS
1189  *      Starting address of mapped view
1190  *      NULL: Failure
1191  */
1192 LPVOID WINAPI MapViewOfFile(
1193               HANDLE mapping,  /* [in] File-mapping object to map */
1194               DWORD access,      /* [in] Access mode */
1195               DWORD offset_high, /* [in] High-order 32 bits of file offset */
1196               DWORD offset_low,  /* [in] Low-order 32 bits of file offset */
1197               DWORD count        /* [in] Number of bytes to map */
1198 ) {
1199     return MapViewOfFileEx( mapping, access, offset_high,
1200                             offset_low, count, NULL );
1201 }
1202
1203
1204 /***********************************************************************
1205  *             MapViewOfFileEx   (KERNEL32.386)
1206  * Maps a view of a file into the address space
1207  *
1208  * RETURNS
1209  *      Starting address of mapped view
1210  *      NULL: Failure
1211  */
1212 LPVOID WINAPI MapViewOfFileEx(
1213               HANDLE handle,   /* [in] File-mapping object to map */
1214               DWORD access,      /* [in] Access mode */
1215               DWORD offset_high, /* [in] High-order 32 bits of file offset */
1216               DWORD offset_low,  /* [in] Low-order 32 bits of file offset */
1217               DWORD count,       /* [in] Number of bytes to map */
1218               LPVOID addr        /* [in] Suggested starting address for mapped view */
1219 ) {
1220     FILE_VIEW *view;
1221     UINT ptr = (UINT)-1, size = 0;
1222     int flags = MAP_PRIVATE;
1223     int unix_handle = -1;
1224     int prot;
1225     struct get_mapping_info_request *req = get_req_buffer();
1226
1227     /* Check parameters */
1228
1229     if ((offset_low & granularity_mask) ||
1230         (addr && ((UINT)addr & granularity_mask)))
1231     {
1232         SetLastError( ERROR_INVALID_PARAMETER );
1233         return NULL;
1234     }
1235
1236     req->handle = handle;
1237     if (server_call_fd( REQ_GET_MAPPING_INFO, -1, &unix_handle )) goto error;
1238
1239     if (req->size_high || offset_high)
1240         ERR("Offsets larger than 4Gb not supported\n");
1241
1242     if ((offset_low >= req->size_low) ||
1243         (count > req->size_low - offset_low))
1244     {
1245         SetLastError( ERROR_INVALID_PARAMETER );
1246         goto error;
1247     }
1248     if (count) size = ROUND_SIZE( offset_low, count );
1249     else size = req->size_low - offset_low;
1250     prot = req->protect;
1251
1252     switch(access)
1253     {
1254     case FILE_MAP_ALL_ACCESS:
1255     case FILE_MAP_WRITE:
1256     case FILE_MAP_WRITE | FILE_MAP_READ:
1257         if (!(prot & VPROT_WRITE))
1258         {
1259             SetLastError( ERROR_INVALID_PARAMETER );
1260             goto error;
1261         }
1262         flags = MAP_SHARED;
1263         /* fall through */
1264     case FILE_MAP_READ:
1265     case FILE_MAP_COPY:
1266     case FILE_MAP_COPY | FILE_MAP_READ:
1267         if (prot & VPROT_READ) break;
1268         /* fall through */
1269     default:
1270         SetLastError( ERROR_INVALID_PARAMETER );
1271         goto error;
1272     }
1273
1274     /* Map the file */
1275
1276     TRACE("handle=%x size=%x offset=%lx\n", handle, size, offset_low );
1277
1278     ptr = (UINT)FILE_dommap( unix_handle, addr, 0, size, 0, offset_low,
1279                              VIRTUAL_GetUnixProt( prot ), flags );
1280     if (ptr == (UINT)-1) {
1281         /* KB: Q125713, 25-SEP-1995, "Common File Mapping Problems and
1282          * Platform Differences": 
1283          * Windows NT: ERROR_INVALID_PARAMETER
1284          * Windows 95: ERROR_INVALID_ADDRESS.
1285          * FIXME: So should we add a module dependend check here? -MM
1286          */
1287         if (errno==ENOMEM)
1288             SetLastError( ERROR_OUTOFMEMORY );
1289         else
1290             SetLastError( ERROR_INVALID_PARAMETER );
1291         goto error;
1292     }
1293
1294     if (!(view = VIRTUAL_CreateView( ptr, size, offset_low, 0, prot, handle )))
1295     {
1296         SetLastError( ERROR_OUTOFMEMORY );
1297         goto error;
1298     }
1299     if (unix_handle != -1) close( unix_handle );
1300     return (LPVOID)ptr;
1301
1302 error:
1303     if (unix_handle != -1) close( unix_handle );
1304     if (ptr != (UINT)-1) FILE_munmap( (void *)ptr, 0, size );
1305     return NULL;
1306 }
1307
1308
1309 /***********************************************************************
1310  *             FlushViewOfFile   (KERNEL32.262)
1311  * Writes to the disk a byte range within a mapped view of a file
1312  *
1313  * RETURNS
1314  *      TRUE: Success
1315  *      FALSE: Failure
1316  */
1317 BOOL WINAPI FlushViewOfFile(
1318               LPCVOID base, /* [in] Start address of byte range to flush */
1319               DWORD cbFlush /* [in] Number of bytes in range */
1320 ) {
1321     FILE_VIEW *view;
1322     UINT addr = ROUND_ADDR( base );
1323
1324     TRACE("FlushViewOfFile at %p for %ld bytes\n",
1325                      base, cbFlush );
1326
1327     if (!(view = VIRTUAL_FindView( addr )))
1328     {
1329         SetLastError( ERROR_INVALID_PARAMETER );
1330         return FALSE;
1331     }
1332     if (!cbFlush) cbFlush = view->size;
1333     if (!msync( (void *)addr, cbFlush, MS_SYNC )) return TRUE;
1334     SetLastError( ERROR_INVALID_PARAMETER );
1335     return FALSE;
1336 }
1337
1338
1339 /***********************************************************************
1340  *             UnmapViewOfFile   (KERNEL32.540)
1341  * Unmaps a mapped view of a file.
1342  *
1343  * NOTES
1344  *      Should addr be an LPCVOID?
1345  *
1346  * RETURNS
1347  *      TRUE: Success
1348  *      FALSE: Failure
1349  */
1350 BOOL WINAPI UnmapViewOfFile(
1351               LPVOID addr /* [in] Address where mapped view begins */
1352 ) {
1353     FILE_VIEW *view;
1354     UINT base = ROUND_ADDR( addr );
1355     if (!(view = VIRTUAL_FindView( base )) || (base != view->base))
1356     {
1357         SetLastError( ERROR_INVALID_PARAMETER );
1358         return FALSE;
1359     }
1360     VIRTUAL_DeleteView( view );
1361     return TRUE;
1362 }
1363
1364 /***********************************************************************
1365  *             VIRTUAL_MapFileW
1366  *
1367  * Helper function to map a file to memory:
1368  *  name                        -       file name 
1369  *  [RETURN] ptr                -       pointer to mapped file
1370  */
1371 LPVOID VIRTUAL_MapFileW( LPCWSTR name )
1372 {
1373     HANDLE hFile, hMapping;
1374     LPVOID ptr = NULL;
1375
1376     hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL, 
1377                            OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0);
1378     if (hFile != INVALID_HANDLE_VALUE)
1379     {
1380         hMapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1381         CloseHandle( hFile );
1382         if (hMapping)
1383         {
1384             ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
1385             CloseHandle( hMapping );
1386         }
1387     }
1388     return ptr;
1389 }