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