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