2 * Win32 virtual memory functions
4 * Copyright 1997 Alexandre Julliard
11 #ifdef HAVE_SYS_ERRNO_H
12 #include <sys/errno.h>
19 #include <sys/types.h>
20 #ifdef HAVE_SYS_MMAN_H
24 #include "wine/exception.h"
25 #include "wine/unicode.h"
31 #include "debugtools.h"
33 DEFAULT_DEBUG_CHANNEL(virtual);
34 DECLARE_DEBUG_CHANNEL(module);
43 struct _FV *next; /* Next view */
44 struct _FV *prev; /* Prev view */
45 UINT base; /* Base address */
46 UINT size; /* Size in bytes */
47 UINT flags; /* Allocation flags */
48 HANDLE mapping; /* Handle to the file mapping */
49 HANDLERPROC handlerProc; /* Fault handler */
50 LPVOID handlerArg; /* Fault handler argument */
51 BYTE protect; /* Protection for all pages at allocation time */
52 BYTE prot[1]; /* Protection byte for each page */
56 #define VFLAG_SYSTEM 0x01
58 /* Conversion from VPROT_* to Win32 flags */
59 static const BYTE VIRTUAL_Win32Flags[16] =
61 PAGE_NOACCESS, /* 0 */
62 PAGE_READONLY, /* READ */
63 PAGE_READWRITE, /* WRITE */
64 PAGE_READWRITE, /* READ | WRITE */
65 PAGE_EXECUTE, /* EXEC */
66 PAGE_EXECUTE_READ, /* READ | EXEC */
67 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
68 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
69 PAGE_WRITECOPY, /* WRITECOPY */
70 PAGE_WRITECOPY, /* READ | WRITECOPY */
71 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
72 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
73 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
74 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
75 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
76 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
80 static FILE_VIEW *VIRTUAL_FirstView;
81 static CRITICAL_SECTION csVirtual = CRITICAL_SECTION_INIT;
84 /* These are always the same on an i386, and it will be faster this way */
85 # define page_mask 0xfff
86 # define page_shift 12
88 static UINT page_shift;
89 static UINT page_mask;
91 #define granularity_mask 0xffff /* Allocation granularity (usually 64k) */
93 #define ROUND_ADDR(addr) \
94 ((UINT)(addr) & ~page_mask)
96 #define ROUND_SIZE(addr,size) \
97 (((UINT)(size) + ((UINT)(addr) & page_mask) + page_mask) & ~page_mask)
99 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
100 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
103 /* filter for page-fault exceptions */
104 static WINE_EXCEPTION_FILTER(page_fault)
106 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
107 return EXCEPTION_EXECUTE_HANDLER;
108 return EXCEPTION_CONTINUE_SEARCH;
111 /***********************************************************************
114 static const char *VIRTUAL_GetProtStr( BYTE prot )
116 static char buffer[6];
117 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
118 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
119 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
120 buffer[3] = (prot & VPROT_WRITE) ?
121 ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
122 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
128 /***********************************************************************
131 static void VIRTUAL_DumpView( FILE_VIEW *view )
134 UINT addr = view->base;
135 BYTE prot = view->prot[0];
137 DPRINTF( "View: %08x - %08x%s",
138 view->base, view->base + view->size - 1,
139 (view->flags & VFLAG_SYSTEM) ? " (system)" : "" );
141 DPRINTF( " %d\n", view->mapping );
143 DPRINTF( " (anonymous)\n");
145 for (count = i = 1; i < view->size >> page_shift; i++, count++)
147 if (view->prot[i] == prot) continue;
148 DPRINTF( " %08x - %08x %s\n",
149 addr, addr + (count << page_shift) - 1,
150 VIRTUAL_GetProtStr(prot) );
151 addr += (count << page_shift);
152 prot = view->prot[i];
156 DPRINTF( " %08x - %08x %s\n",
157 addr, addr + (count << page_shift) - 1,
158 VIRTUAL_GetProtStr(prot) );
162 /***********************************************************************
165 void VIRTUAL_Dump(void)
168 DPRINTF( "\nDump of all virtual memory views:\n\n" );
169 EnterCriticalSection(&csVirtual);
170 view = VIRTUAL_FirstView;
173 VIRTUAL_DumpView( view );
176 LeaveCriticalSection(&csVirtual);
180 /***********************************************************************
183 * Find the view containing a given address.
189 static FILE_VIEW *VIRTUAL_FindView(
190 UINT addr /* [in] Address */
194 EnterCriticalSection(&csVirtual);
195 view = VIRTUAL_FirstView;
198 if (view->base > addr)
203 if (view->base + view->size > addr) break;
206 LeaveCriticalSection(&csVirtual);
211 /***********************************************************************
214 * Create a new view and add it in the linked list.
216 static FILE_VIEW *VIRTUAL_CreateView( UINT base, UINT size, UINT flags,
217 BYTE vprot, HANDLE mapping )
219 FILE_VIEW *view, *prev;
221 /* Create the view structure */
223 assert( !(base & page_mask) );
224 assert( !(size & page_mask) );
226 if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
228 view->size = size << page_shift;
230 view->mapping = mapping;
231 view->protect = vprot;
232 view->handlerProc = NULL;
233 memset( view->prot, vprot, size );
235 /* Duplicate the mapping handle */
237 if ((view->mapping != -1) &&
238 !DuplicateHandle( GetCurrentProcess(), view->mapping,
239 GetCurrentProcess(), &view->mapping,
240 0, FALSE, DUPLICATE_SAME_ACCESS ))
246 /* Insert it in the linked list */
248 EnterCriticalSection(&csVirtual);
249 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
251 view->next = VIRTUAL_FirstView;
253 if (view->next) view->next->prev = view;
254 VIRTUAL_FirstView = view;
258 prev = VIRTUAL_FirstView;
259 while (prev->next && (prev->next->base < base)) prev = prev->next;
260 view->next = prev->next;
262 if (view->next) view->next->prev = view;
265 LeaveCriticalSection(&csVirtual);
266 VIRTUAL_DEBUG_DUMP_VIEW( view );
271 /***********************************************************************
278 static void VIRTUAL_DeleteView(
279 FILE_VIEW *view /* [in] View */
281 if (!(view->flags & VFLAG_SYSTEM))
282 munmap( (void *)view->base, view->size );
283 EnterCriticalSection(&csVirtual);
284 if (view->next) view->next->prev = view->prev;
285 if (view->prev) view->prev->next = view->next;
286 else VIRTUAL_FirstView = view->next;
287 LeaveCriticalSection(&csVirtual);
288 if (view->mapping) CloseHandle( view->mapping );
293 /***********************************************************************
294 * VIRTUAL_GetUnixProt
296 * Convert page protections to protection for mmap/mprotect.
298 static int VIRTUAL_GetUnixProt( BYTE vprot )
301 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
303 if (vprot & VPROT_READ) prot |= PROT_READ;
304 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
305 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
306 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
312 /***********************************************************************
313 * VIRTUAL_GetWin32Prot
315 * Convert page protections to Win32 flags.
320 static void VIRTUAL_GetWin32Prot(
321 BYTE vprot, /* [in] Page protection flags */
322 DWORD *protect, /* [out] Location to store Win32 protection flags */
323 DWORD *state /* [out] Location to store mem state flag */
326 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
327 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
328 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
330 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
333 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
337 /***********************************************************************
340 * Build page protections from Win32 flags.
343 * Value of page protection flags
345 static BYTE VIRTUAL_GetProt(
346 DWORD protect /* [in] Win32 protection flags */
350 switch(protect & 0xff)
356 vprot = VPROT_READ | VPROT_WRITE;
359 vprot = VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
364 case PAGE_EXECUTE_READ:
365 vprot = VPROT_EXEC | VPROT_READ;
367 case PAGE_EXECUTE_READWRITE:
368 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
370 case PAGE_EXECUTE_WRITECOPY:
371 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
378 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
379 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
384 /***********************************************************************
387 * Change the protection of a range of pages.
393 static BOOL VIRTUAL_SetProt(
394 FILE_VIEW *view, /* [in] Pointer to view */
395 UINT base, /* [in] Starting address */
396 UINT size, /* [in] Size in bytes */
397 BYTE vprot /* [in] Protections to use */
399 TRACE("%08x-%08x %s\n",
400 base, base + size - 1, VIRTUAL_GetProtStr( vprot ) );
402 if (mprotect( (void *)base, size, VIRTUAL_GetUnixProt(vprot) ))
403 return FALSE; /* FIXME: last error */
405 memset( view->prot + ((base - view->base) >> page_shift),
406 vprot, size >> page_shift );
407 VIRTUAL_DEBUG_DUMP_VIEW( view );
412 /***********************************************************************
415 * Map an executable (PE format) image into memory.
417 static LPVOID map_image( HANDLE hmapping, int fd, char *base, DWORD total_size,
418 DWORD header_size, HANDLE shared_file, DWORD shared_size )
420 IMAGE_DOS_HEADER *dos;
421 IMAGE_NT_HEADERS *nt;
422 IMAGE_SECTION_HEADER *sec;
424 DWORD err = GetLastError();
425 FILE_VIEW *view = NULL;
429 SetLastError( ERROR_BAD_EXE_FORMAT ); /* generic error */
431 /* zero-map the whole range */
433 if ((ptr = VIRTUAL_mmap( -1, base, total_size, 0,
434 PROT_READ | PROT_WRITE | PROT_EXEC, 0 )) == (char *)-1)
436 ptr = VIRTUAL_mmap( -1, NULL, total_size, 0,
437 PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
438 if (ptr == (char *)-1)
440 ERR_(module)("Not enough memory for module (%ld bytes)\n", total_size);
444 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
446 if (!(view = VIRTUAL_CreateView( (UINT)ptr, total_size, 0,
447 VPROT_COMMITTED|VPROT_READ|VPROT_WRITE|VPROT_WRITECOPY,
450 munmap( ptr, total_size );
451 SetLastError( ERROR_OUTOFMEMORY );
457 if (VIRTUAL_mmap( fd, ptr, header_size, 0, PROT_READ | PROT_WRITE,
458 MAP_PRIVATE | MAP_FIXED ) == (char *)-1) goto error;
459 dos = (IMAGE_DOS_HEADER *)ptr;
460 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
461 if ((char *)(nt + 1) > ptr + header_size) goto error;
463 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
464 if ((char *)(sec + nt->FileHeader.NumberOfSections) > ptr + header_size) goto error;
466 /* check the architecture */
468 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
470 MESSAGE("Trying to load PE image for unsupported architecture (");
471 switch (nt->FileHeader.Machine)
473 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
474 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
475 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
476 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
477 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
478 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
479 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
480 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
486 /* retrieve the shared sections file */
490 if ((shared_fd = FILE_GetUnixHandle( shared_file, GENERIC_READ )) == -1) goto error;
491 CloseHandle( shared_file ); /* we no longer need it */
492 shared_file = INVALID_HANDLE_VALUE;
495 /* map all the sections */
497 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
501 /* a few sanity checks */
502 size = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
503 if (sec->VirtualAddress > total_size || size > total_size || size < sec->VirtualAddress)
505 ERR_(module)( "Section %.8s too large (%lx+%lx/%lx)\n",
506 sec->Name, sec->VirtualAddress, sec->Misc.VirtualSize, total_size );
510 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
511 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
513 size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
514 TRACE_(module)( "mapping shared section %.8s at %p off %lx (%x) size %lx (%lx) flags %lx\n",
515 sec->Name, (char *)ptr + sec->VirtualAddress,
516 sec->PointerToRawData, pos, sec->SizeOfRawData,
517 size, sec->Characteristics );
518 if (VIRTUAL_mmap( shared_fd, (char *)ptr + sec->VirtualAddress, size,
519 pos, PROT_READ|PROT_WRITE|PROT_EXEC,
520 MAP_SHARED|MAP_FIXED ) == (void *)-1)
522 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
529 if (sec->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) continue;
530 if (!sec->PointerToRawData || !sec->SizeOfRawData) continue;
532 TRACE_(module)( "mapping section %.8s at %p off %lx size %lx flags %lx\n",
533 sec->Name, (char *)ptr + sec->VirtualAddress,
534 sec->PointerToRawData, sec->SizeOfRawData,
535 sec->Characteristics );
537 /* Note: if the section is not aligned properly VIRTUAL_mmap will magically
538 * fall back to read(), so we don't need to check anything here.
540 if (VIRTUAL_mmap( fd, (char *)ptr + sec->VirtualAddress, sec->SizeOfRawData,
541 sec->PointerToRawData, PROT_READ|PROT_WRITE|PROT_EXEC,
542 MAP_PRIVATE | MAP_FIXED ) == (void *)-1)
544 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
548 if ((sec->SizeOfRawData < sec->Misc.VirtualSize) && (sec->SizeOfRawData & page_mask))
550 DWORD end = ROUND_SIZE( 0, sec->SizeOfRawData );
551 if (end > sec->Misc.VirtualSize) end = sec->Misc.VirtualSize;
552 TRACE_(module)("clearing %p - %p\n",
553 (char *)ptr + sec->VirtualAddress + sec->SizeOfRawData,
554 (char *)ptr + sec->VirtualAddress + end );
555 memset( (char *)ptr + sec->VirtualAddress + sec->SizeOfRawData, 0,
556 end - sec->SizeOfRawData );
560 SetLastError( err ); /* restore last error */
562 if (shared_fd != -1) close( shared_fd );
566 if (view) VIRTUAL_DeleteView( view );
568 if (shared_fd != -1) close( shared_fd );
569 if (shared_file != INVALID_HANDLE_VALUE) CloseHandle( shared_file );
574 /***********************************************************************
578 DECL_GLOBAL_CONSTRUCTOR(VIRTUAL_Init)
582 # ifdef HAVE_GETPAGESIZE
583 page_size = getpagesize();
586 page_size = sysconf(_SC_PAGESIZE);
588 # error Cannot get the page size on this platform
591 page_mask = page_size - 1;
592 /* Make sure we have a power of 2 */
593 assert( !(page_size & page_mask) );
595 while ((1 << page_shift) != page_size) page_shift++;
597 #endif /* page_mask */
600 /***********************************************************************
601 * VIRTUAL_GetPageSize
603 DWORD VIRTUAL_GetPageSize(void)
605 return 1 << page_shift;
609 /***********************************************************************
610 * VIRTUAL_GetGranularity
612 DWORD VIRTUAL_GetGranularity(void)
614 return granularity_mask + 1;
618 /***********************************************************************
619 * VIRTUAL_SetFaultHandler
621 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
625 if (!(view = VIRTUAL_FindView((UINT)addr))) return FALSE;
626 view->handlerProc = proc;
627 view->handlerArg = arg;
631 /***********************************************************************
632 * VIRTUAL_HandleFault
634 DWORD VIRTUAL_HandleFault( LPCVOID addr )
636 FILE_VIEW *view = VIRTUAL_FindView((UINT)addr);
637 DWORD ret = EXCEPTION_ACCESS_VIOLATION;
641 if (view->handlerProc)
643 if (view->handlerProc(view->handlerArg, addr)) ret = 0; /* handled */
647 BYTE vprot = view->prot[((UINT)addr - view->base) >> page_shift];
648 UINT page = (UINT)addr & ~page_mask;
649 char *stack = (char *)NtCurrentTeb()->stack_base + SIGNAL_STACK_SIZE + page_mask + 1;
650 if (vprot & VPROT_GUARD)
652 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
653 ret = STATUS_GUARD_PAGE_VIOLATION;
655 /* is it inside the stack guard pages? */
656 if (((char *)addr >= stack) && ((char *)addr < stack + 2*(page_mask+1)))
657 ret = STATUS_STACK_OVERFLOW;
664 /***********************************************************************
667 * Wrapper for mmap() that handles anonymous mappings portably,
668 * and falls back to read if mmap of a file fails.
670 LPVOID VIRTUAL_mmap( int unix_handle, LPVOID start, DWORD size,
671 DWORD offset, int prot, int flags )
677 if (unix_handle == -1)
682 static int fdzero = -1;
686 if ((fdzero = open( "/dev/zero", O_RDONLY )) == -1)
688 perror( "/dev/zero: open" );
693 #endif /* MAP_ANON */
694 /* Linux EINVAL's on us if we don't pass MAP_PRIVATE to an anon mmap */
696 flags &= ~MAP_SHARED;
699 flags |= MAP_PRIVATE;
702 else fd = unix_handle;
704 if ((ret = mmap( start, size, prot, flags, fd, offset )) != (LPVOID)-1)
707 /* mmap() failed; if this is because the file offset is not */
708 /* page-aligned (EINVAL), or because the underlying filesystem */
709 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
711 if (unix_handle == -1) return ret;
712 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return ret;
713 if (prot & PROT_WRITE)
715 /* We cannot fake shared write mappings */
717 if (flags & MAP_SHARED) return ret;
720 if (!(flags & MAP_PRIVATE)) return ret;
724 /* Reserve the memory with an anonymous mmap */
725 ret = VIRTUAL_mmap( -1, start, size, 0, PROT_READ | PROT_WRITE, flags );
726 if (ret == (LPVOID)-1) return ret;
727 /* Now read in the file */
728 if ((pos = lseek( fd, offset, SEEK_SET )) == -1)
733 read( fd, ret, size );
734 lseek( fd, pos, SEEK_SET ); /* Restore the file pointer */
735 mprotect( ret, size, prot ); /* Set the right protection */
740 /***********************************************************************
741 * VirtualAlloc (KERNEL32.548)
742 * Reserves or commits a region of pages in virtual address space
745 * Base address of allocated region of pages
748 LPVOID WINAPI VirtualAlloc(
749 LPVOID addr, /* [in] Address of region to reserve or commit */
750 DWORD size, /* [in] Size of region */
751 DWORD type, /* [in] Type of allocation */
752 DWORD protect /* [in] Type of access protection */
755 UINT base, ptr, view_size;
758 TRACE("%08x %08lx %lx %08lx\n",
759 (UINT)addr, size, type, protect );
761 /* Round parameters to a page boundary */
763 if (size > 0x7fc00000) /* 2Gb - 4Mb */
765 SetLastError( ERROR_OUTOFMEMORY );
770 if (type & MEM_RESERVE) /* Round down to 64k boundary */
771 base = (UINT)addr & ~granularity_mask;
773 base = ROUND_ADDR( addr );
774 size = (((UINT)addr + size + page_mask) & ~page_mask) - base;
775 if ((base <= granularity_mask) || (base + size < base))
777 /* disallow low 64k and wrap-around */
778 SetLastError( ERROR_INVALID_PARAMETER );
785 size = (size + page_mask) & ~page_mask;
788 if (type & MEM_TOP_DOWN) {
789 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
790 * Is there _ANY_ way to do it with UNIX mmap()?
792 WARN("MEM_TOP_DOWN ignored\n");
793 type &= ~MEM_TOP_DOWN;
795 /* Compute the alloc type flags */
797 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)) ||
798 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)))
800 ERR("called with wrong alloc type flags (%08lx) !\n", type);
801 SetLastError( ERROR_INVALID_PARAMETER );
804 if (type & (MEM_COMMIT | MEM_SYSTEM))
805 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
808 /* Reserve the memory */
810 if ((type & MEM_RESERVE) || !base)
812 view_size = size + (base ? 0 : granularity_mask + 1);
813 if (type & MEM_SYSTEM)
816 ptr = (UINT)VIRTUAL_mmap( -1, (LPVOID)base, view_size, 0,
817 VIRTUAL_GetUnixProt( vprot ), 0 );
820 SetLastError( ERROR_OUTOFMEMORY );
825 /* Release the extra memory while keeping the range */
826 /* starting on a 64k boundary. */
828 if (ptr & granularity_mask)
830 UINT extra = granularity_mask + 1 - (ptr & granularity_mask);
831 munmap( (void *)ptr, extra );
835 if (view_size > size)
836 munmap( (void *)(ptr + size), view_size - size );
838 else if (ptr != base)
840 /* We couldn't get the address we wanted */
841 munmap( (void *)ptr, view_size );
842 SetLastError( ERROR_INVALID_ADDRESS );
845 if (!(view = VIRTUAL_CreateView( ptr, size, (type & MEM_SYSTEM) ?
846 VFLAG_SYSTEM : 0, vprot, -1 )))
848 munmap( (void *)ptr, size );
849 SetLastError( ERROR_OUTOFMEMORY );
855 /* Commit the pages */
857 if (!(view = VIRTUAL_FindView( base )) ||
858 (base + size > view->base + view->size))
860 SetLastError( ERROR_INVALID_ADDRESS );
864 if (!VIRTUAL_SetProt( view, base, size, vprot )) return NULL;
869 /***********************************************************************
870 * VirtualAllocEx (KERNEL32.548)
872 * Seems to be just as VirtualAlloc, but with process handle.
874 LPVOID WINAPI VirtualAllocEx(
875 HANDLE hProcess, /* [in] Handle of process to do mem operation */
876 LPVOID addr, /* [in] Address of region to reserve or commit */
877 DWORD size, /* [in] Size of region */
878 DWORD type, /* [in] Type of allocation */
879 DWORD protect /* [in] Type of access protection */
881 if (MapProcessHandle( hProcess ) == GetCurrentProcessId())
882 return VirtualAlloc( addr, size, type, protect );
883 ERR("Unsupported on other process\n");
888 /***********************************************************************
889 * VirtualFree (KERNEL32.550)
890 * Release or decommits a region of pages in virtual address space.
896 BOOL WINAPI VirtualFree(
897 LPVOID addr, /* [in] Address of region of committed pages */
898 DWORD size, /* [in] Size of region */
899 DWORD type /* [in] Type of operation */
904 TRACE("%08x %08lx %lx\n",
905 (UINT)addr, size, type );
907 /* Fix the parameters */
909 size = ROUND_SIZE( addr, size );
910 base = ROUND_ADDR( addr );
912 if (!(view = VIRTUAL_FindView( base )) ||
913 (base + size > view->base + view->size))
915 SetLastError( ERROR_INVALID_PARAMETER );
919 /* Compute the protection flags */
921 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
923 ERR("called with wrong free type flags (%08lx) !\n", type);
924 SetLastError( ERROR_INVALID_PARAMETER );
930 if (type == MEM_RELEASE)
932 if (size || (base != view->base))
934 SetLastError( ERROR_INVALID_PARAMETER );
937 VIRTUAL_DeleteView( view );
941 /* Decommit the pages by remapping zero-pages instead */
943 if (VIRTUAL_mmap( -1, (LPVOID)base, size, 0, VIRTUAL_GetUnixProt( 0 ),
944 MAP_FIXED ) != (LPVOID)base)
945 ERR( "Could not remap pages, expect trouble\n" );
946 return VIRTUAL_SetProt( view, base, size, 0 );
950 /***********************************************************************
951 * VirtualLock (KERNEL32.551)
952 * Locks the specified region of virtual address space
955 * Always returns TRUE
961 BOOL WINAPI VirtualLock(
962 LPVOID addr, /* [in] Address of first byte of range to lock */
963 DWORD size /* [in] Number of bytes in range to lock */
969 /***********************************************************************
970 * VirtualUnlock (KERNEL32.556)
971 * Unlocks a range of pages in the virtual address space
974 * Always returns TRUE
980 BOOL WINAPI VirtualUnlock(
981 LPVOID addr, /* [in] Address of first byte of range */
982 DWORD size /* [in] Number of bytes in range */
988 /***********************************************************************
989 * VirtualProtect (KERNEL32.552)
990 * Changes the access protection on a region of committed pages
996 BOOL WINAPI VirtualProtect(
997 LPVOID addr, /* [in] Address of region of committed pages */
998 DWORD size, /* [in] Size of region */
999 DWORD new_prot, /* [in] Desired access protection */
1000 LPDWORD old_prot /* [out] Address of variable to get old protection */
1006 TRACE("%08x %08lx %08lx\n",
1007 (UINT)addr, size, new_prot );
1009 /* Fix the parameters */
1011 size = ROUND_SIZE( addr, size );
1012 base = ROUND_ADDR( addr );
1014 if (!(view = VIRTUAL_FindView( base )) ||
1015 (base + size > view->base + view->size))
1017 SetLastError( ERROR_INVALID_PARAMETER );
1021 /* Make sure all the pages are committed */
1023 p = view->prot + ((base - view->base) >> page_shift);
1024 for (i = size >> page_shift; i; i--, p++)
1026 if (!(*p & VPROT_COMMITTED))
1028 SetLastError( ERROR_INVALID_PARAMETER );
1033 if (old_prot) VIRTUAL_GetWin32Prot( view->prot[0], old_prot, NULL );
1034 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1035 return VIRTUAL_SetProt( view, base, size, vprot );
1039 /***********************************************************************
1040 * VirtualProtectEx (KERNEL32.553)
1041 * Changes the access protection on a region of committed pages in the
1042 * virtual address space of a specified process
1048 BOOL WINAPI VirtualProtectEx(
1049 HANDLE handle, /* [in] Handle of process */
1050 LPVOID addr, /* [in] Address of region of committed pages */
1051 DWORD size, /* [in] Size of region */
1052 DWORD new_prot, /* [in] Desired access protection */
1053 LPDWORD old_prot /* [out] Address of variable to get old protection */ )
1055 if (MapProcessHandle( handle ) == GetCurrentProcessId())
1056 return VirtualProtect( addr, size, new_prot, old_prot );
1057 ERR("Unsupported on other process\n");
1062 /***********************************************************************
1063 * VirtualQuery (KERNEL32.554)
1064 * Provides info about a range of pages in virtual address space
1067 * Number of bytes returned in information buffer
1069 DWORD WINAPI VirtualQuery(
1070 LPCVOID addr, /* [in] Address of region */
1071 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
1072 DWORD len /* [in] Size of buffer */
1075 UINT base = ROUND_ADDR( addr );
1076 UINT alloc_base = 0;
1079 /* Find the view containing the address */
1081 EnterCriticalSection(&csVirtual);
1082 view = VIRTUAL_FirstView;
1087 size = 0xffff0000 - alloc_base;
1090 if (view->base > base)
1092 size = view->base - alloc_base;
1096 if (view->base + view->size > base)
1098 alloc_base = view->base;
1102 alloc_base = view->base + view->size;
1105 LeaveCriticalSection(&csVirtual);
1107 /* Fill the info structure */
1111 info->State = MEM_FREE;
1113 info->AllocationProtect = 0;
1118 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1119 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
1120 for (size = base - alloc_base; size < view->size; size += page_mask+1)
1121 if (view->prot[size >> page_shift] != vprot) break;
1122 info->AllocationProtect = view->protect;
1123 info->Type = MEM_PRIVATE; /* FIXME */
1126 info->BaseAddress = (LPVOID)base;
1127 info->AllocationBase = (LPVOID)alloc_base;
1128 info->RegionSize = size - (base - alloc_base);
1129 return sizeof(*info);
1133 /***********************************************************************
1134 * VirtualQueryEx (KERNEL32.555)
1135 * Provides info about a range of pages in virtual address space of a
1139 * Number of bytes returned in information buffer
1141 DWORD WINAPI VirtualQueryEx(
1142 HANDLE handle, /* [in] Handle of process */
1143 LPCVOID addr, /* [in] Address of region */
1144 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
1145 DWORD len /* [in] Size of buffer */ )
1147 if (MapProcessHandle( handle ) == GetCurrentProcessId())
1148 return VirtualQuery( addr, info, len );
1149 ERR("Unsupported on other process\n");
1154 /***********************************************************************
1155 * IsBadReadPtr (KERNEL32.354)
1158 * FALSE: Process has read access to entire block
1161 BOOL WINAPI IsBadReadPtr(
1162 LPCVOID ptr, /* Address of memory block */
1163 UINT size ) /* Size of block */
1167 volatile const char *p = ptr;
1168 volatile const char *end = p + size - 1;
1178 __EXCEPT(page_fault) { return TRUE; }
1184 /***********************************************************************
1185 * IsBadWritePtr (KERNEL32.357)
1188 * FALSE: Process has write access to entire block
1191 BOOL WINAPI IsBadWritePtr(
1192 LPVOID ptr, /* [in] Address of memory block */
1193 UINT size ) /* [in] Size of block in bytes */
1197 volatile char *p = ptr;
1198 volatile char *end = p + size - 1;
1207 __EXCEPT(page_fault) { return TRUE; }
1213 /***********************************************************************
1214 * IsBadHugeReadPtr (KERNEL32.352)
1216 * FALSE: Process has read access to entire block
1219 BOOL WINAPI IsBadHugeReadPtr(
1220 LPCVOID ptr, /* [in] Address of memory block */
1221 UINT size /* [in] Size of block */
1223 return IsBadReadPtr( ptr, size );
1227 /***********************************************************************
1228 * IsBadHugeWritePtr (KERNEL32.353)
1230 * FALSE: Process has write access to entire block
1233 BOOL WINAPI IsBadHugeWritePtr(
1234 LPVOID ptr, /* [in] Address of memory block */
1235 UINT size /* [in] Size of block */
1237 return IsBadWritePtr( ptr, size );
1241 /***********************************************************************
1242 * IsBadCodePtr (KERNEL32.351)
1245 * FALSE: Process has read access to specified memory
1248 BOOL WINAPI IsBadCodePtr( FARPROC ptr ) /* [in] Address of function */
1250 return IsBadReadPtr( ptr, 1 );
1254 /***********************************************************************
1255 * IsBadStringPtrA (KERNEL32.355)
1258 * FALSE: Read access to all bytes in string
1261 BOOL WINAPI IsBadStringPtrA(
1262 LPCSTR str, /* [in] Address of string */
1263 UINT max ) /* [in] Maximum size of string */
1267 volatile const char *p = str;
1268 while (p < str + max) if (!*p++) break;
1270 __EXCEPT(page_fault) { return TRUE; }
1276 /***********************************************************************
1277 * IsBadStringPtrW (KERNEL32.356)
1278 * See IsBadStringPtrA
1280 BOOL WINAPI IsBadStringPtrW( LPCWSTR str, UINT max )
1284 volatile const WCHAR *p = str;
1285 while (p < str + max) if (!*p++) break;
1287 __EXCEPT(page_fault) { return TRUE; }
1293 /***********************************************************************
1294 * CreateFileMappingA (KERNEL32.46)
1295 * Creates a named or unnamed file-mapping object for the specified file
1299 * 0: Mapping object does not exist
1302 HANDLE WINAPI CreateFileMappingA(
1303 HFILE hFile, /* [in] Handle of file to map */
1304 SECURITY_ATTRIBUTES *sa, /* [in] Optional security attributes*/
1305 DWORD protect, /* [in] Protection for mapping object */
1306 DWORD size_high, /* [in] High-order 32 bits of object size */
1307 DWORD size_low, /* [in] Low-order 32 bits of object size */
1308 LPCSTR name /* [in] Name of file-mapping object */ )
1312 DWORD len = name ? MultiByteToWideChar( CP_ACP, 0, name, strlen(name), NULL, 0 ) : 0;
1314 /* Check parameters */
1316 TRACE("(%x,%p,%08lx,%08lx%08lx,%s)\n",
1317 hFile, sa, protect, size_high, size_low, debugstr_a(name) );
1321 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1324 vprot = VIRTUAL_GetProt( protect );
1325 if (protect & SEC_RESERVE)
1327 if (hFile != INVALID_HANDLE_VALUE)
1329 SetLastError( ERROR_INVALID_PARAMETER );
1333 else vprot |= VPROT_COMMITTED;
1334 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1335 if (protect & SEC_IMAGE) vprot |= VPROT_IMAGE;
1337 /* Create the server object */
1341 struct create_mapping_request *req = server_alloc_req( sizeof(*req),
1342 len * sizeof(WCHAR) );
1343 req->file_handle = hFile;
1344 req->size_high = size_high;
1345 req->size_low = size_low;
1346 req->protect = vprot;
1347 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1348 if (len) MultiByteToWideChar( CP_ACP, 0, name, strlen(name), server_data_ptr(req), len );
1350 server_call( REQ_CREATE_MAPPING );
1354 if (ret == -1) ret = 0; /* must return 0 on failure, not -1 */
1359 /***********************************************************************
1360 * CreateFileMappingW (KERNEL32.47)
1361 * See CreateFileMappingA
1363 HANDLE WINAPI CreateFileMappingW( HFILE hFile, LPSECURITY_ATTRIBUTES sa,
1364 DWORD protect, DWORD size_high,
1365 DWORD size_low, LPCWSTR name )
1369 DWORD len = name ? strlenW(name) : 0;
1371 /* Check parameters */
1373 TRACE("(%x,%p,%08lx,%08lx%08lx,%s)\n",
1374 hFile, sa, protect, size_high, size_low, debugstr_w(name) );
1378 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1382 vprot = VIRTUAL_GetProt( protect );
1383 if (protect & SEC_RESERVE)
1385 if (hFile != INVALID_HANDLE_VALUE)
1387 SetLastError( ERROR_INVALID_PARAMETER );
1391 else vprot |= VPROT_COMMITTED;
1392 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1393 if (protect & SEC_IMAGE) vprot |= VPROT_IMAGE;
1395 /* Create the server object */
1399 struct create_mapping_request *req = server_alloc_req( sizeof(*req),
1400 len * sizeof(WCHAR) );
1401 req->file_handle = hFile;
1402 req->size_high = size_high;
1403 req->size_low = size_low;
1404 req->protect = vprot;
1405 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1406 memcpy( server_data_ptr(req), name, len * sizeof(WCHAR) );
1408 server_call( REQ_CREATE_MAPPING );
1412 if (ret == -1) ret = 0; /* must return 0 on failure, not -1 */
1417 /***********************************************************************
1418 * OpenFileMappingA (KERNEL32.397)
1419 * Opens a named file-mapping object.
1425 HANDLE WINAPI OpenFileMappingA(
1426 DWORD access, /* [in] Access mode */
1427 BOOL inherit, /* [in] Inherit flag */
1428 LPCSTR name ) /* [in] Name of file-mapping object */
1431 DWORD len = name ? MultiByteToWideChar( CP_ACP, 0, name, strlen(name), NULL, 0 ) : 0;
1434 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1439 struct open_mapping_request *req = server_alloc_req( sizeof(*req), len * sizeof(WCHAR) );
1441 req->access = access;
1442 req->inherit = inherit;
1443 if (len) MultiByteToWideChar( CP_ACP, 0, name, strlen(name), server_data_ptr(req), len );
1444 server_call( REQ_OPEN_MAPPING );
1448 if (ret == -1) ret = 0; /* must return 0 on failure, not -1 */
1453 /***********************************************************************
1454 * OpenFileMappingW (KERNEL32.398)
1455 * See OpenFileMappingA
1457 HANDLE WINAPI OpenFileMappingW( DWORD access, BOOL inherit, LPCWSTR name)
1460 DWORD len = name ? strlenW(name) : 0;
1463 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1468 struct open_mapping_request *req = server_alloc_req( sizeof(*req), len * sizeof(WCHAR) );
1470 req->access = access;
1471 req->inherit = inherit;
1472 memcpy( server_data_ptr(req), name, len * sizeof(WCHAR) );
1473 server_call( REQ_OPEN_MAPPING );
1477 if (ret == -1) ret = 0; /* must return 0 on failure, not -1 */
1482 /***********************************************************************
1483 * MapViewOfFile (KERNEL32.385)
1484 * Maps a view of a file into the address space
1487 * Starting address of mapped view
1490 LPVOID WINAPI MapViewOfFile(
1491 HANDLE mapping, /* [in] File-mapping object to map */
1492 DWORD access, /* [in] Access mode */
1493 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1494 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1495 DWORD count /* [in] Number of bytes to map */
1497 return MapViewOfFileEx( mapping, access, offset_high,
1498 offset_low, count, NULL );
1502 /***********************************************************************
1503 * MapViewOfFileEx (KERNEL32.386)
1504 * Maps a view of a file into the address space
1507 * Starting address of mapped view
1510 LPVOID WINAPI MapViewOfFileEx(
1511 HANDLE handle, /* [in] File-mapping object to map */
1512 DWORD access, /* [in] Access mode */
1513 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1514 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1515 DWORD count, /* [in] Number of bytes to map */
1516 LPVOID addr /* [in] Suggested starting address for mapped view */
1519 UINT ptr = (UINT)-1, size = 0;
1520 int flags = MAP_PRIVATE;
1521 int unix_handle = -1;
1523 struct get_mapping_info_request *req = get_req_buffer();
1525 /* Check parameters */
1527 if ((offset_low & granularity_mask) ||
1528 (addr && ((UINT)addr & granularity_mask)))
1530 SetLastError( ERROR_INVALID_PARAMETER );
1534 req->handle = handle;
1535 if (server_call_fd( REQ_GET_MAPPING_INFO, -1, &unix_handle )) goto error;
1536 prot = req->protect;
1538 if (prot & VPROT_IMAGE)
1539 return map_image( handle, unix_handle, req->base, req->size_low, req->header_size,
1540 req->shared_file, req->shared_size );
1542 if (req->size_high || offset_high)
1543 ERR("Offsets larger than 4Gb not supported\n");
1545 if ((offset_low >= req->size_low) ||
1546 (count > req->size_low - offset_low))
1548 SetLastError( ERROR_INVALID_PARAMETER );
1551 if (count) size = ROUND_SIZE( offset_low, count );
1552 else size = req->size_low - offset_low;
1556 case FILE_MAP_ALL_ACCESS:
1557 case FILE_MAP_WRITE:
1558 case FILE_MAP_WRITE | FILE_MAP_READ:
1559 if (!(prot & VPROT_WRITE))
1561 SetLastError( ERROR_INVALID_PARAMETER );
1568 case FILE_MAP_COPY | FILE_MAP_READ:
1569 if (prot & VPROT_READ) break;
1572 SetLastError( ERROR_INVALID_PARAMETER );
1576 /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1577 * which has a view of this mapping commits some pages, they will
1578 * appear commited in all other processes, which have the same
1579 * view created. Since we don`t support this yet, we create the
1580 * whole mapping commited.
1582 prot |= VPROT_COMMITTED;
1586 TRACE("handle=%x size=%x offset=%lx\n", handle, size, offset_low );
1588 ptr = (UINT)VIRTUAL_mmap( unix_handle, addr, size, offset_low,
1589 VIRTUAL_GetUnixProt( prot ), flags );
1590 if (ptr == (UINT)-1) {
1591 /* KB: Q125713, 25-SEP-1995, "Common File Mapping Problems and
1592 * Platform Differences":
1593 * Windows NT: ERROR_INVALID_PARAMETER
1594 * Windows 95: ERROR_INVALID_ADDRESS.
1595 * FIXME: So should we add a module dependend check here? -MM
1598 SetLastError( ERROR_OUTOFMEMORY );
1600 SetLastError( ERROR_INVALID_PARAMETER );
1604 if (!(view = VIRTUAL_CreateView( ptr, size, 0, prot, handle )))
1606 SetLastError( ERROR_OUTOFMEMORY );
1609 if (unix_handle != -1) close( unix_handle );
1613 if (unix_handle != -1) close( unix_handle );
1614 if (ptr != (UINT)-1) munmap( (void *)ptr, size );
1619 /***********************************************************************
1620 * FlushViewOfFile (KERNEL32.262)
1621 * Writes to the disk a byte range within a mapped view of a file
1627 BOOL WINAPI FlushViewOfFile(
1628 LPCVOID base, /* [in] Start address of byte range to flush */
1629 DWORD cbFlush /* [in] Number of bytes in range */
1632 UINT addr = ROUND_ADDR( base );
1634 TRACE("FlushViewOfFile at %p for %ld bytes\n",
1637 if (!(view = VIRTUAL_FindView( addr )))
1639 SetLastError( ERROR_INVALID_PARAMETER );
1642 if (!cbFlush) cbFlush = view->size;
1643 if (!msync( (void *)addr, cbFlush, MS_SYNC )) return TRUE;
1644 SetLastError( ERROR_INVALID_PARAMETER );
1649 /***********************************************************************
1650 * UnmapViewOfFile (KERNEL32.540)
1651 * Unmaps a mapped view of a file.
1654 * Should addr be an LPCVOID?
1660 BOOL WINAPI UnmapViewOfFile(
1661 LPVOID addr /* [in] Address where mapped view begins */
1664 UINT base = ROUND_ADDR( addr );
1665 if (!(view = VIRTUAL_FindView( base )) || (base != view->base))
1667 SetLastError( ERROR_INVALID_PARAMETER );
1670 VIRTUAL_DeleteView( view );
1674 /***********************************************************************
1677 * Helper function to map a file to memory:
1679 * [RETURN] ptr - pointer to mapped file
1681 LPVOID VIRTUAL_MapFileW( LPCWSTR name )
1683 HANDLE hFile, hMapping;
1686 hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
1687 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0);
1688 if (hFile != INVALID_HANDLE_VALUE)
1690 hMapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1691 CloseHandle( hFile );
1694 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
1695 CloseHandle( hMapping );