- Implemented a new preprocessor that is (nearly) ANSI-C compliant. The
[wine.git] / memory / virtual.c
blobedd1ea8135637b93bd7e014018cd0300b97d4324
1 /*
2 * Win32 virtual memory functions
4 * Copyright 1997 Alexandre Julliard
5 */
7 #include "config.h"
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 <stdio.h>
18 #include <string.h>
19 #include <sys/types.h>
20 #ifdef HAVE_SYS_MMAN_H
21 #include <sys/mman.h>
22 #endif
23 #include "winbase.h"
24 #include "winerror.h"
25 #include "file.h"
26 #include "process.h"
27 #include "global.h"
28 #include "server.h"
29 #include "debugtools.h"
31 DEFAULT_DEBUG_CHANNEL(virtual);
33 #ifndef MS_SYNC
34 #define MS_SYNC 0
35 #endif
37 /* File view */
38 typedef struct _FV
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;
53 /* Per-view flags */
54 #define VFLAG_SYSTEM 0x01
56 /* Conversion from VPROT_* to Win32 flags */
57 static const BYTE VIRTUAL_Win32Flags[16] =
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 */
78 static FILE_VIEW *VIRTUAL_FirstView;
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__ */
91 #define ROUND_ADDR(addr) \
92 ((UINT)(addr) & ~page_mask)
94 #define ROUND_SIZE(addr,size) \
95 (((UINT)(size) + ((UINT)(addr) & page_mask) + page_mask) & ~page_mask)
97 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
98 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
100 /***********************************************************************
101 * VIRTUAL_GetProtStr
103 static const char *VIRTUAL_GetProtStr( BYTE prot )
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;
117 /***********************************************************************
118 * VIRTUAL_DumpView
120 static void VIRTUAL_DumpView( FILE_VIEW *view )
122 UINT i, count;
123 UINT addr = view->base;
124 BYTE prot = view->prot[0];
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");
134 for (count = i = 1; i < view->size >> page_shift; i++, count++)
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;
144 if (count)
145 DPRINTF( " %08x - %08x %s\n",
146 addr, addr + (count << page_shift) - 1,
147 VIRTUAL_GetProtStr(prot) );
151 /***********************************************************************
152 * VIRTUAL_Dump
154 void VIRTUAL_Dump(void)
156 FILE_VIEW *view = VIRTUAL_FirstView;
157 DPRINTF( "\nDump of all virtual memory views:\n\n" );
158 while (view)
160 VIRTUAL_DumpView( view );
161 view = view->next;
166 /***********************************************************************
167 * VIRTUAL_FindView
169 * Find the view containing a given address.
171 * RETURNS
172 * View: Success
173 * NULL: Failure
175 static FILE_VIEW *VIRTUAL_FindView(
176 UINT addr /* [in] Address */
178 FILE_VIEW *view = VIRTUAL_FirstView;
179 while (view)
181 if (view->base > addr) return NULL;
182 if (view->base + view->size > addr) return view;
183 view = view->next;
185 return NULL;
189 /***********************************************************************
190 * VIRTUAL_CreateView
192 * Create a new view and add it in the linked list.
194 static FILE_VIEW *VIRTUAL_CreateView( UINT base, UINT size, UINT offset,
195 UINT flags, BYTE vprot,
196 HANDLE mapping )
198 FILE_VIEW *view, *prev;
200 /* Create the view structure */
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 );
215 /* Duplicate the mapping handle */
217 if ((view->mapping != -1) &&
218 !DuplicateHandle( GetCurrentProcess(), view->mapping,
219 GetCurrentProcess(), &view->mapping,
220 0, FALSE, DUPLICATE_SAME_ACCESS ))
222 free( view );
223 return NULL;
226 /* Insert it in the linked list */
228 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
230 view->next = VIRTUAL_FirstView;
231 view->prev = NULL;
232 if (view->next) view->next->prev = view;
233 VIRTUAL_FirstView = view;
235 else
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;
244 VIRTUAL_DEBUG_DUMP_VIEW( view );
245 return view;
249 /***********************************************************************
250 * VIRTUAL_DeleteView
251 * Deletes a view.
253 * RETURNS
254 * None
256 static void VIRTUAL_DeleteView(
257 FILE_VIEW *view /* [in] View */
259 if (!(view->flags & VFLAG_SYSTEM))
260 FILE_munmap( (void *)view->base, 0, view->size );
261 if (view->next) view->next->prev = view->prev;
262 if (view->prev) view->prev->next = view->next;
263 else VIRTUAL_FirstView = view->next;
264 if (view->mapping) CloseHandle( view->mapping );
265 free( view );
269 /***********************************************************************
270 * VIRTUAL_GetUnixProt
272 * Convert page protections to protection for mmap/mprotect.
274 static int VIRTUAL_GetUnixProt( BYTE vprot )
276 int prot = 0;
277 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
279 if (vprot & VPROT_READ) prot |= PROT_READ;
280 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
281 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
282 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
284 return prot;
288 /***********************************************************************
289 * VIRTUAL_GetWin32Prot
291 * Convert page protections to Win32 flags.
293 * RETURNS
294 * None
296 static void VIRTUAL_GetWin32Prot(
297 BYTE vprot, /* [in] Page protection flags */
298 DWORD *protect, /* [out] Location to store Win32 protection flags */
299 DWORD *state /* [out] Location to store mem state flag */
301 if (protect) {
302 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
303 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
304 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
306 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
309 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
313 /***********************************************************************
314 * VIRTUAL_GetProt
316 * Build page protections from Win32 flags.
318 * RETURNS
319 * Value of page protection flags
321 static BYTE VIRTUAL_GetProt(
322 DWORD protect /* [in] Win32 protection flags */
324 BYTE vprot;
326 switch(protect & 0xff)
328 case PAGE_READONLY:
329 vprot = VPROT_READ;
330 break;
331 case PAGE_READWRITE:
332 vprot = VPROT_READ | VPROT_WRITE;
333 break;
334 case PAGE_WRITECOPY:
335 vprot = VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
336 break;
337 case PAGE_EXECUTE:
338 vprot = VPROT_EXEC;
339 break;
340 case PAGE_EXECUTE_READ:
341 vprot = VPROT_EXEC | VPROT_READ;
342 break;
343 case PAGE_EXECUTE_READWRITE:
344 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
345 break;
346 case PAGE_EXECUTE_WRITECOPY:
347 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
348 break;
349 case PAGE_NOACCESS:
350 default:
351 vprot = 0;
352 break;
354 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
355 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
356 return vprot;
360 /***********************************************************************
361 * VIRTUAL_SetProt
363 * Change the protection of a range of pages.
365 * RETURNS
366 * TRUE: Success
367 * FALSE: Failure
369 static BOOL VIRTUAL_SetProt(
370 FILE_VIEW *view, /* [in] Pointer to view */
371 UINT base, /* [in] Starting address */
372 UINT size, /* [in] Size in bytes */
373 BYTE vprot /* [in] Protections to use */
375 TRACE("%08x-%08x %s\n",
376 base, base + size - 1, VIRTUAL_GetProtStr( vprot ) );
378 if (mprotect( (void *)base, size, VIRTUAL_GetUnixProt(vprot) ))
379 return FALSE; /* FIXME: last error */
381 memset( view->prot + ((base - view->base) >> page_shift),
382 vprot, size >> page_shift );
383 VIRTUAL_DEBUG_DUMP_VIEW( view );
384 return TRUE;
388 /***********************************************************************
389 * VIRTUAL_CheckFlags
391 * Check that all pages in a range have the given flags.
393 * RETURNS
394 * TRUE: They do
395 * FALSE: They do not
397 static BOOL VIRTUAL_CheckFlags(
398 UINT base, /* [in] Starting address */
399 UINT size, /* [in] Size in bytes */
400 BYTE flags /* [in] Flags to check for */
402 FILE_VIEW *view;
403 UINT page;
405 if (!size) return TRUE;
406 if (!(view = VIRTUAL_FindView( base ))) return FALSE;
407 if (view->base + view->size < base + size) return FALSE;
408 page = (base - view->base) >> page_shift;
409 size = ROUND_SIZE( base, size ) >> page_shift;
410 while (size--) if ((view->prot[page++] & flags) != flags) return FALSE;
411 return TRUE;
415 /***********************************************************************
416 * VIRTUAL_Init
418 BOOL VIRTUAL_Init(void)
420 #ifndef __i386__
421 DWORD page_size;
423 # ifdef HAVE_GETPAGESIZE
424 page_size = getpagesize();
425 # else
426 # ifdef __svr4__
427 page_size = sysconf(_SC_PAGESIZE);
428 # else
429 # error Cannot get the page size on this platform
430 # endif
431 # endif
432 page_mask = page_size - 1;
433 granularity_mask = 0xffff; /* hard-coded for now */
434 /* Make sure we have a power of 2 */
435 assert( !(page_size & page_mask) );
436 page_shift = 0;
437 while ((1 << page_shift) != page_size) page_shift++;
438 #endif /* !__i386__ */
440 #ifdef linux
442 /* Do not use stdio here since it may temporarily change the size
443 * of some segments (ie libc6 adds 0x1000 per open FILE)
445 int fd = open ("/proc/self/maps", O_RDONLY);
446 if (fd >= 0)
448 char buffer[512]; /* line might be rather long in 2.1 */
450 for (;;)
452 int start, end, offset;
453 char r, w, x, p;
454 BYTE vprot = VPROT_COMMITTED;
456 char * ptr = buffer;
457 int count = sizeof(buffer);
458 while (1 == read(fd, ptr, 1) && *ptr != '\n' && --count > 0)
459 ptr++;
461 if (*ptr != '\n') break;
462 *ptr = '\0';
464 sscanf( buffer, "%x-%x %c%c%c%c %x",
465 &start, &end, &r, &w, &x, &p, &offset );
466 if (r == 'r') vprot |= VPROT_READ;
467 if (w == 'w') vprot |= VPROT_WRITE;
468 if (x == 'x') vprot |= VPROT_EXEC;
469 if (p == 'p') vprot |= VPROT_WRITECOPY;
470 VIRTUAL_CreateView( start, end - start, 0,
471 VFLAG_SYSTEM, vprot, -1 );
473 close (fd);
476 #endif /* linux */
477 return TRUE;
481 /***********************************************************************
482 * VIRTUAL_GetPageSize
484 DWORD VIRTUAL_GetPageSize(void)
486 return 1 << page_shift;
490 /***********************************************************************
491 * VIRTUAL_GetGranularity
493 DWORD VIRTUAL_GetGranularity(void)
495 return granularity_mask + 1;
499 /***********************************************************************
500 * VIRTUAL_SetFaultHandler
502 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
504 FILE_VIEW *view;
506 if (!(view = VIRTUAL_FindView((UINT)addr))) return FALSE;
507 view->handlerProc = proc;
508 view->handlerArg = arg;
509 return TRUE;
512 /***********************************************************************
513 * VIRTUAL_HandleFault
515 DWORD VIRTUAL_HandleFault( LPCVOID addr )
517 FILE_VIEW *view = VIRTUAL_FindView((UINT)addr);
518 DWORD ret = EXCEPTION_ACCESS_VIOLATION;
520 if (view)
522 if (view->handlerProc)
524 if (view->handlerProc(view->handlerArg, addr)) ret = 0; /* handled */
526 else
528 BYTE vprot = view->prot[((UINT)addr - view->base) >> page_shift];
529 UINT page = (UINT)addr & ~page_mask;
530 char *stack = (char *)NtCurrentTeb()->stack_base + SIGNAL_STACK_SIZE + page_mask + 1;
531 if (vprot & VPROT_GUARD)
533 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
534 ret = STATUS_GUARD_PAGE_VIOLATION;
536 /* is it inside the stack guard pages? */
537 if (((char *)addr >= stack) && ((char *)addr < stack + 2*(page_mask+1)))
538 ret = STATUS_STACK_OVERFLOW;
541 return ret;
545 /***********************************************************************
546 * VirtualAlloc (KERNEL32.548)
547 * Reserves or commits a region of pages in virtual address space
549 * RETURNS
550 * Base address of allocated region of pages
551 * NULL: Failure
553 LPVOID WINAPI VirtualAlloc(
554 LPVOID addr, /* [in] Address of region to reserve or commit */
555 DWORD size, /* [in] Size of region */
556 DWORD type, /* [in] Type of allocation */
557 DWORD protect /* [in] Type of access protection */
559 FILE_VIEW *view;
560 UINT base, ptr, view_size;
561 BYTE vprot;
563 TRACE("%08x %08lx %lx %08lx\n",
564 (UINT)addr, size, type, protect );
566 /* Round parameters to a page boundary */
568 if (size > 0x7fc00000) /* 2Gb - 4Mb */
570 SetLastError( ERROR_OUTOFMEMORY );
571 return NULL;
573 if (addr)
575 if (type & MEM_RESERVE) /* Round down to 64k boundary */
576 base = (UINT)addr & ~granularity_mask;
577 else
578 base = ROUND_ADDR( addr );
579 size = (((UINT)addr + size + page_mask) & ~page_mask) - base;
580 if ((base <= granularity_mask) || (base + size < base))
582 /* disallow low 64k and wrap-around */
583 SetLastError( ERROR_INVALID_PARAMETER );
584 return NULL;
587 else
589 base = 0;
590 size = (size + page_mask) & ~page_mask;
593 if (type & MEM_TOP_DOWN) {
594 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
595 * Is there _ANY_ way to do it with UNIX mmap()?
597 WARN("MEM_TOP_DOWN ignored\n");
598 type &= ~MEM_TOP_DOWN;
600 /* Compute the protection flags */
602 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)) ||
603 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)))
605 SetLastError( ERROR_INVALID_PARAMETER );
606 return NULL;
608 if (type & (MEM_COMMIT | MEM_SYSTEM))
609 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
610 else vprot = 0;
612 /* Reserve the memory */
614 if ((type & MEM_RESERVE) || !base)
616 view_size = size + (base ? 0 : granularity_mask + 1);
617 if (type & MEM_SYSTEM)
618 ptr = base;
619 else
620 ptr = (UINT)FILE_dommap( -1, (LPVOID)base, 0, view_size, 0, 0,
621 VIRTUAL_GetUnixProt( vprot ), MAP_PRIVATE );
622 if (ptr == (UINT)-1)
624 SetLastError( ERROR_OUTOFMEMORY );
625 return NULL;
627 if (!base)
629 /* Release the extra memory while keeping the range */
630 /* starting on a 64k boundary. */
632 if (ptr & granularity_mask)
634 UINT extra = granularity_mask + 1 - (ptr & granularity_mask);
635 FILE_munmap( (void *)ptr, 0, extra );
636 ptr += extra;
637 view_size -= extra;
639 if (view_size > size)
640 FILE_munmap( (void *)(ptr + size), 0, view_size - size );
642 else if (ptr != base)
644 /* We couldn't get the address we wanted */
645 FILE_munmap( (void *)ptr, 0, view_size );
646 SetLastError( ERROR_INVALID_ADDRESS );
647 return NULL;
649 if (!(view = VIRTUAL_CreateView( ptr, size, 0, (type & MEM_SYSTEM) ?
650 VFLAG_SYSTEM : 0, vprot, -1 )))
652 FILE_munmap( (void *)ptr, 0, size );
653 SetLastError( ERROR_OUTOFMEMORY );
654 return NULL;
656 VIRTUAL_DEBUG_DUMP_VIEW( view );
657 return (LPVOID)ptr;
660 /* Commit the pages */
662 if (!(view = VIRTUAL_FindView( base )) ||
663 (base + size > view->base + view->size))
665 SetLastError( ERROR_INVALID_ADDRESS );
666 return NULL;
669 if (!VIRTUAL_SetProt( view, base, size, vprot )) return NULL;
670 return (LPVOID)base;
674 /***********************************************************************
675 * VirtualFree (KERNEL32.550)
676 * Release or decommits a region of pages in virtual address space.
678 * RETURNS
679 * TRUE: Success
680 * FALSE: Failure
682 BOOL WINAPI VirtualFree(
683 LPVOID addr, /* [in] Address of region of committed pages */
684 DWORD size, /* [in] Size of region */
685 DWORD type /* [in] Type of operation */
687 FILE_VIEW *view;
688 UINT base;
690 TRACE("%08x %08lx %lx\n",
691 (UINT)addr, size, type );
693 /* Fix the parameters */
695 size = ROUND_SIZE( addr, size );
696 base = ROUND_ADDR( addr );
698 if (!(view = VIRTUAL_FindView( base )) ||
699 (base + size > view->base + view->size))
701 SetLastError( ERROR_INVALID_PARAMETER );
702 return FALSE;
705 /* Compute the protection flags */
707 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
709 SetLastError( ERROR_INVALID_PARAMETER );
710 return FALSE;
713 /* Free the pages */
715 if (type == MEM_RELEASE)
717 if (size || (base != view->base))
719 SetLastError( ERROR_INVALID_PARAMETER );
720 return FALSE;
722 VIRTUAL_DeleteView( view );
723 return TRUE;
726 /* Decommit the pages by remapping zero-pages instead */
728 if (FILE_dommap( -1, (LPVOID)base, 0, size, 0, 0,
729 VIRTUAL_GetUnixProt( 0 ), MAP_PRIVATE|MAP_FIXED )
730 != (LPVOID)base)
731 ERR( "Could not remap pages, expect trouble\n" );
732 return VIRTUAL_SetProt( view, base, size, 0 );
736 /***********************************************************************
737 * VirtualLock (KERNEL32.551)
738 * Locks the specified region of virtual address space
740 * NOTE
741 * Always returns TRUE
743 * RETURNS
744 * TRUE: Success
745 * FALSE: Failure
747 BOOL WINAPI VirtualLock(
748 LPVOID addr, /* [in] Address of first byte of range to lock */
749 DWORD size /* [in] Number of bytes in range to lock */
751 return TRUE;
755 /***********************************************************************
756 * VirtualUnlock (KERNEL32.556)
757 * Unlocks a range of pages in the virtual address space
759 * NOTE
760 * Always returns TRUE
762 * RETURNS
763 * TRUE: Success
764 * FALSE: Failure
766 BOOL WINAPI VirtualUnlock(
767 LPVOID addr, /* [in] Address of first byte of range */
768 DWORD size /* [in] Number of bytes in range */
770 return TRUE;
774 /***********************************************************************
775 * VirtualProtect (KERNEL32.552)
776 * Changes the access protection on a region of committed pages
778 * RETURNS
779 * TRUE: Success
780 * FALSE: Failure
782 BOOL WINAPI VirtualProtect(
783 LPVOID addr, /* [in] Address of region of committed pages */
784 DWORD size, /* [in] Size of region */
785 DWORD new_prot, /* [in] Desired access protection */
786 LPDWORD old_prot /* [out] Address of variable to get old protection */
788 FILE_VIEW *view;
789 UINT base, i;
790 BYTE vprot, *p;
792 TRACE("%08x %08lx %08lx\n",
793 (UINT)addr, size, new_prot );
795 /* Fix the parameters */
797 size = ROUND_SIZE( addr, size );
798 base = ROUND_ADDR( addr );
800 if (!(view = VIRTUAL_FindView( base )) ||
801 (base + size > view->base + view->size))
803 SetLastError( ERROR_INVALID_PARAMETER );
804 return FALSE;
807 /* Make sure all the pages are committed */
809 p = view->prot + ((base - view->base) >> page_shift);
810 for (i = size >> page_shift; i; i--, p++)
812 if (!(*p & VPROT_COMMITTED))
814 SetLastError( ERROR_INVALID_PARAMETER );
815 return FALSE;
819 VIRTUAL_GetWin32Prot( view->prot[0], old_prot, NULL );
820 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
821 return VIRTUAL_SetProt( view, base, size, vprot );
825 /***********************************************************************
826 * VirtualProtectEx (KERNEL32.553)
827 * Changes the access protection on a region of committed pages in the
828 * virtual address space of a specified process
830 * RETURNS
831 * TRUE: Success
832 * FALSE: Failure
834 BOOL WINAPI VirtualProtectEx(
835 HANDLE handle, /* [in] Handle of process */
836 LPVOID addr, /* [in] Address of region of committed pages */
837 DWORD size, /* [in] Size of region */
838 DWORD new_prot, /* [in] Desired access protection */
839 LPDWORD old_prot /* [out] Address of variable to get old protection */ )
841 if (MapProcessHandle( handle ) == GetCurrentProcessId())
842 return VirtualProtect( addr, size, new_prot, old_prot );
843 ERR("Unsupported on other process\n");
844 return FALSE;
848 /***********************************************************************
849 * VirtualQuery (KERNEL32.554)
850 * Provides info about a range of pages in virtual address space
852 * RETURNS
853 * Number of bytes returned in information buffer
855 DWORD WINAPI VirtualQuery(
856 LPCVOID addr, /* [in] Address of region */
857 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
858 DWORD len /* [in] Size of buffer */
860 FILE_VIEW *view = VIRTUAL_FirstView;
861 UINT base = ROUND_ADDR( addr );
862 UINT alloc_base = 0;
863 UINT size = 0;
865 /* Find the view containing the address */
867 for (;;)
869 if (!view)
871 size = 0xffff0000 - alloc_base;
872 break;
874 if (view->base > base)
876 size = view->base - alloc_base;
877 view = NULL;
878 break;
880 if (view->base + view->size > base)
882 alloc_base = view->base;
883 size = view->size;
884 break;
886 alloc_base = view->base + view->size;
887 view = view->next;
890 /* Fill the info structure */
892 if (!view)
894 info->State = MEM_FREE;
895 info->Protect = 0;
896 info->AllocationProtect = 0;
897 info->Type = 0;
899 else
901 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
902 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
903 for (size = base - alloc_base; size < view->size; size += page_mask+1)
904 if (view->prot[size >> page_shift] != vprot) break;
905 info->AllocationProtect = view->protect;
906 info->Type = MEM_PRIVATE; /* FIXME */
909 info->BaseAddress = (LPVOID)base;
910 info->AllocationBase = (LPVOID)alloc_base;
911 info->RegionSize = size - (base - alloc_base);
912 return sizeof(*info);
916 /***********************************************************************
917 * VirtualQueryEx (KERNEL32.555)
918 * Provides info about a range of pages in virtual address space of a
919 * specified process
921 * RETURNS
922 * Number of bytes returned in information buffer
924 DWORD WINAPI VirtualQueryEx(
925 HANDLE handle, /* [in] Handle of process */
926 LPCVOID addr, /* [in] Address of region */
927 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
928 DWORD len /* [in] Size of buffer */ )
930 if (MapProcessHandle( handle ) == GetCurrentProcessId())
931 return VirtualQuery( addr, info, len );
932 ERR("Unsupported on other process\n");
933 return 0;
937 /***********************************************************************
938 * IsBadReadPtr (KERNEL32.354)
940 * RETURNS
941 * FALSE: Process has read access to entire block
942 * TRUE: Otherwise
944 BOOL WINAPI IsBadReadPtr(
945 LPCVOID ptr, /* Address of memory block */
946 UINT size /* Size of block */
948 return !VIRTUAL_CheckFlags( (UINT)ptr, size,
949 VPROT_READ | VPROT_COMMITTED );
953 /***********************************************************************
954 * IsBadWritePtr (KERNEL32.357)
956 * RETURNS
957 * FALSE: Process has write access to entire block
958 * TRUE: Otherwise
960 BOOL WINAPI IsBadWritePtr(
961 LPVOID ptr, /* [in] Address of memory block */
962 UINT size /* [in] Size of block in bytes */
964 return !VIRTUAL_CheckFlags( (UINT)ptr, size,
965 VPROT_WRITE | VPROT_COMMITTED );
969 /***********************************************************************
970 * IsBadHugeReadPtr (KERNEL32.352)
971 * RETURNS
972 * FALSE: Process has read access to entire block
973 * TRUE: Otherwise
975 BOOL WINAPI IsBadHugeReadPtr(
976 LPCVOID ptr, /* [in] Address of memory block */
977 UINT size /* [in] Size of block */
979 return IsBadReadPtr( ptr, size );
983 /***********************************************************************
984 * IsBadHugeWritePtr (KERNEL32.353)
985 * RETURNS
986 * FALSE: Process has write access to entire block
987 * TRUE: Otherwise
989 BOOL WINAPI IsBadHugeWritePtr(
990 LPVOID ptr, /* [in] Address of memory block */
991 UINT size /* [in] Size of block */
993 return IsBadWritePtr( ptr, size );
997 /***********************************************************************
998 * IsBadCodePtr (KERNEL32.351)
1000 * RETURNS
1001 * FALSE: Process has read access to specified memory
1002 * TRUE: Otherwise
1004 BOOL WINAPI IsBadCodePtr(
1005 FARPROC ptr /* [in] Address of function */
1007 return !VIRTUAL_CheckFlags( (UINT)ptr, 1, VPROT_EXEC | VPROT_COMMITTED );
1011 /***********************************************************************
1012 * IsBadStringPtrA (KERNEL32.355)
1014 * RETURNS
1015 * FALSE: Read access to all bytes in string
1016 * TRUE: Else
1018 BOOL WINAPI IsBadStringPtrA(
1019 LPCSTR str, /* [in] Address of string */
1020 UINT max /* [in] Maximum size of string */
1022 FILE_VIEW *view;
1023 UINT page, count;
1025 if (!max) return FALSE;
1026 if (!(view = VIRTUAL_FindView( (UINT)str ))) return TRUE;
1027 page = ((UINT)str - view->base) >> page_shift;
1028 count = page_mask + 1 - ((UINT)str & page_mask);
1030 while (max)
1032 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
1033 (VPROT_READ | VPROT_COMMITTED))
1034 return TRUE;
1035 if (count > max) count = max;
1036 max -= count;
1037 while (count--) if (!*str++) return FALSE;
1038 if (++page >= view->size >> page_shift) return TRUE;
1039 count = page_mask + 1;
1041 return FALSE;
1045 /***********************************************************************
1046 * IsBadStringPtrW (KERNEL32.356)
1047 * See IsBadStringPtrA
1049 BOOL WINAPI IsBadStringPtrW( LPCWSTR str, UINT max )
1051 FILE_VIEW *view;
1052 UINT page, count;
1054 if (!max) return FALSE;
1055 if (!(view = VIRTUAL_FindView( (UINT)str ))) return TRUE;
1056 page = ((UINT)str - view->base) >> page_shift;
1057 count = (page_mask + 1 - ((UINT)str & page_mask)) / sizeof(WCHAR);
1059 while (max)
1061 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
1062 (VPROT_READ | VPROT_COMMITTED))
1063 return TRUE;
1064 if (count > max) count = max;
1065 max -= count;
1066 while (count--) if (!*str++) return FALSE;
1067 if (++page >= view->size >> page_shift) return TRUE;
1068 count = (page_mask + 1) / sizeof(WCHAR);
1070 return FALSE;
1074 /***********************************************************************
1075 * CreateFileMappingA (KERNEL32.46)
1076 * Creates a named or unnamed file-mapping object for the specified file
1078 * RETURNS
1079 * Handle: Success
1080 * 0: Mapping object does not exist
1081 * NULL: Failure
1083 HANDLE WINAPI CreateFileMappingA(
1084 HFILE hFile, /* [in] Handle of file to map */
1085 SECURITY_ATTRIBUTES *sa, /* [in] Optional security attributes*/
1086 DWORD protect, /* [in] Protection for mapping object */
1087 DWORD size_high, /* [in] High-order 32 bits of object size */
1088 DWORD size_low, /* [in] Low-order 32 bits of object size */
1089 LPCSTR name /* [in] Name of file-mapping object */ )
1091 struct create_mapping_request *req = get_req_buffer();
1092 BYTE vprot;
1094 /* Check parameters */
1096 TRACE("(%x,%p,%08lx,%08lx%08lx,%s)\n",
1097 hFile, sa, protect, size_high, size_low, debugstr_a(name) );
1099 vprot = VIRTUAL_GetProt( protect );
1100 if (protect & SEC_RESERVE)
1102 if (hFile != INVALID_HANDLE_VALUE)
1104 SetLastError( ERROR_INVALID_PARAMETER );
1105 return 0;
1108 else vprot |= VPROT_COMMITTED;
1109 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1111 /* Create the server object */
1113 req->file_handle = hFile;
1114 req->size_high = size_high;
1115 req->size_low = size_low;
1116 req->protect = vprot;
1117 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1118 server_strcpyAtoW( req->name, name );
1119 SetLastError(0);
1120 server_call( REQ_CREATE_MAPPING );
1121 if (req->handle == -1) return 0;
1122 return req->handle;
1126 /***********************************************************************
1127 * CreateFileMappingW (KERNEL32.47)
1128 * See CreateFileMappingA
1130 HANDLE WINAPI CreateFileMappingW( HFILE hFile, LPSECURITY_ATTRIBUTES sa,
1131 DWORD protect, DWORD size_high,
1132 DWORD size_low, LPCWSTR name )
1134 struct create_mapping_request *req = get_req_buffer();
1135 BYTE vprot;
1137 /* Check parameters */
1139 TRACE("(%x,%p,%08lx,%08lx%08lx,%s)\n",
1140 hFile, sa, protect, size_high, size_low, debugstr_w(name) );
1142 vprot = VIRTUAL_GetProt( protect );
1143 if (protect & SEC_RESERVE)
1145 if (hFile != INVALID_HANDLE_VALUE)
1147 SetLastError( ERROR_INVALID_PARAMETER );
1148 return 0;
1151 else vprot |= VPROT_COMMITTED;
1152 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1154 /* Create the server object */
1156 req->file_handle = hFile;
1157 req->size_high = size_high;
1158 req->size_low = size_low;
1159 req->protect = vprot;
1160 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1161 server_strcpyW( req->name, name );
1162 SetLastError(0);
1163 server_call( REQ_CREATE_MAPPING );
1164 if (req->handle == -1) return 0;
1165 return req->handle;
1169 /***********************************************************************
1170 * OpenFileMappingA (KERNEL32.397)
1171 * Opens a named file-mapping object.
1173 * RETURNS
1174 * Handle: Success
1175 * NULL: Failure
1177 HANDLE WINAPI OpenFileMappingA(
1178 DWORD access, /* [in] Access mode */
1179 BOOL inherit, /* [in] Inherit flag */
1180 LPCSTR name ) /* [in] Name of file-mapping object */
1182 struct open_mapping_request *req = get_req_buffer();
1184 req->access = access;
1185 req->inherit = inherit;
1186 server_strcpyAtoW( req->name, name );
1187 server_call( REQ_OPEN_MAPPING );
1188 if (req->handle == -1) return 0; /* must return 0 on failure, not -1 */
1189 return req->handle;
1193 /***********************************************************************
1194 * OpenFileMappingW (KERNEL32.398)
1195 * See OpenFileMappingA
1197 HANDLE WINAPI OpenFileMappingW( DWORD access, BOOL inherit, LPCWSTR name)
1199 struct open_mapping_request *req = get_req_buffer();
1201 req->access = access;
1202 req->inherit = inherit;
1203 server_strcpyW( req->name, name );
1204 server_call( REQ_OPEN_MAPPING );
1205 if (req->handle == -1) return 0; /* must return 0 on failure, not -1 */
1206 return req->handle;
1210 /***********************************************************************
1211 * MapViewOfFile (KERNEL32.385)
1212 * Maps a view of a file into the address space
1214 * RETURNS
1215 * Starting address of mapped view
1216 * NULL: Failure
1218 LPVOID WINAPI MapViewOfFile(
1219 HANDLE mapping, /* [in] File-mapping object to map */
1220 DWORD access, /* [in] Access mode */
1221 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1222 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1223 DWORD count /* [in] Number of bytes to map */
1225 return MapViewOfFileEx( mapping, access, offset_high,
1226 offset_low, count, NULL );
1230 /***********************************************************************
1231 * MapViewOfFileEx (KERNEL32.386)
1232 * Maps a view of a file into the address space
1234 * RETURNS
1235 * Starting address of mapped view
1236 * NULL: Failure
1238 LPVOID WINAPI MapViewOfFileEx(
1239 HANDLE handle, /* [in] File-mapping object to map */
1240 DWORD access, /* [in] Access mode */
1241 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1242 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1243 DWORD count, /* [in] Number of bytes to map */
1244 LPVOID addr /* [in] Suggested starting address for mapped view */
1246 FILE_VIEW *view;
1247 UINT ptr = (UINT)-1, size = 0;
1248 int flags = MAP_PRIVATE;
1249 int unix_handle = -1;
1250 int prot;
1251 struct get_mapping_info_request *req = get_req_buffer();
1253 /* Check parameters */
1255 if ((offset_low & granularity_mask) ||
1256 (addr && ((UINT)addr & granularity_mask)))
1258 SetLastError( ERROR_INVALID_PARAMETER );
1259 return NULL;
1262 req->handle = handle;
1263 if (server_call_fd( REQ_GET_MAPPING_INFO, -1, &unix_handle )) goto error;
1265 if (req->size_high || offset_high)
1266 ERR("Offsets larger than 4Gb not supported\n");
1268 if ((offset_low >= req->size_low) ||
1269 (count > req->size_low - offset_low))
1271 SetLastError( ERROR_INVALID_PARAMETER );
1272 goto error;
1274 if (count) size = ROUND_SIZE( offset_low, count );
1275 else size = req->size_low - offset_low;
1276 prot = req->protect;
1278 switch(access)
1280 case FILE_MAP_ALL_ACCESS:
1281 case FILE_MAP_WRITE:
1282 case FILE_MAP_WRITE | FILE_MAP_READ:
1283 if (!(prot & VPROT_WRITE))
1285 SetLastError( ERROR_INVALID_PARAMETER );
1286 goto error;
1288 flags = MAP_SHARED;
1289 /* fall through */
1290 case FILE_MAP_READ:
1291 case FILE_MAP_COPY:
1292 case FILE_MAP_COPY | FILE_MAP_READ:
1293 if (prot & VPROT_READ) break;
1294 /* fall through */
1295 default:
1296 SetLastError( ERROR_INVALID_PARAMETER );
1297 goto error;
1300 /* Map the file */
1302 TRACE("handle=%x size=%x offset=%lx\n", handle, size, offset_low );
1304 ptr = (UINT)FILE_dommap( unix_handle, addr, 0, size, 0, offset_low,
1305 VIRTUAL_GetUnixProt( prot ), flags );
1306 if (ptr == (UINT)-1) {
1307 /* KB: Q125713, 25-SEP-1995, "Common File Mapping Problems and
1308 * Platform Differences":
1309 * Windows NT: ERROR_INVALID_PARAMETER
1310 * Windows 95: ERROR_INVALID_ADDRESS.
1311 * FIXME: So should we add a module dependend check here? -MM
1313 if (errno==ENOMEM)
1314 SetLastError( ERROR_OUTOFMEMORY );
1315 else
1316 SetLastError( ERROR_INVALID_PARAMETER );
1317 goto error;
1320 if (!(view = VIRTUAL_CreateView( ptr, size, offset_low, 0, prot, handle )))
1322 SetLastError( ERROR_OUTOFMEMORY );
1323 goto error;
1325 if (unix_handle != -1) close( unix_handle );
1326 return (LPVOID)ptr;
1328 error:
1329 if (unix_handle != -1) close( unix_handle );
1330 if (ptr != (UINT)-1) FILE_munmap( (void *)ptr, 0, size );
1331 return NULL;
1335 /***********************************************************************
1336 * FlushViewOfFile (KERNEL32.262)
1337 * Writes to the disk a byte range within a mapped view of a file
1339 * RETURNS
1340 * TRUE: Success
1341 * FALSE: Failure
1343 BOOL WINAPI FlushViewOfFile(
1344 LPCVOID base, /* [in] Start address of byte range to flush */
1345 DWORD cbFlush /* [in] Number of bytes in range */
1347 FILE_VIEW *view;
1348 UINT addr = ROUND_ADDR( base );
1350 TRACE("FlushViewOfFile at %p for %ld bytes\n",
1351 base, cbFlush );
1353 if (!(view = VIRTUAL_FindView( addr )))
1355 SetLastError( ERROR_INVALID_PARAMETER );
1356 return FALSE;
1358 if (!cbFlush) cbFlush = view->size;
1359 if (!msync( (void *)addr, cbFlush, MS_SYNC )) return TRUE;
1360 SetLastError( ERROR_INVALID_PARAMETER );
1361 return FALSE;
1365 /***********************************************************************
1366 * UnmapViewOfFile (KERNEL32.540)
1367 * Unmaps a mapped view of a file.
1369 * NOTES
1370 * Should addr be an LPCVOID?
1372 * RETURNS
1373 * TRUE: Success
1374 * FALSE: Failure
1376 BOOL WINAPI UnmapViewOfFile(
1377 LPVOID addr /* [in] Address where mapped view begins */
1379 FILE_VIEW *view;
1380 UINT base = ROUND_ADDR( addr );
1381 if (!(view = VIRTUAL_FindView( base )) || (base != view->base))
1383 SetLastError( ERROR_INVALID_PARAMETER );
1384 return FALSE;
1386 VIRTUAL_DeleteView( view );
1387 return TRUE;
1390 /***********************************************************************
1391 * VIRTUAL_MapFileW
1393 * Helper function to map a file to memory:
1394 * name - file name
1395 * [RETURN] ptr - pointer to mapped file
1397 LPVOID VIRTUAL_MapFileW( LPCWSTR name )
1399 HANDLE hFile, hMapping;
1400 LPVOID ptr = NULL;
1402 hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
1403 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0);
1404 if (hFile != INVALID_HANDLE_VALUE)
1406 hMapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1407 CloseHandle( hFile );
1408 if (hMapping)
1410 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
1411 CloseHandle( hMapping );
1414 return ptr;