2 * Win32 virtual memory functions
4 * Copyright 1997, 2002 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "wine/port.h"
26 #ifdef HAVE_SYS_ERRNO_H
27 #include <sys/errno.h>
36 #include <sys/types.h>
37 #ifdef HAVE_SYS_MMAN_H
41 #define NONAMELESSUNION
42 #define NONAMELESSSTRUCT
45 #include "wine/library.h"
46 #include "wine/server.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
50 WINE_DECLARE_DEBUG_CHANNEL(module);
59 struct _FV *next; /* Next view */
60 struct _FV *prev; /* Prev view */
61 void *base; /* Base address */
62 UINT size; /* Size in bytes */
63 UINT flags; /* Allocation flags */
64 HANDLE mapping; /* Handle to the file mapping */
65 HANDLERPROC handlerProc; /* Fault handler */
66 LPVOID handlerArg; /* Fault handler argument */
67 BYTE protect; /* Protection for all pages at allocation time */
68 BYTE prot[1]; /* Protection byte for each page */
72 #define VFLAG_SYSTEM 0x01
73 #define VFLAG_VALLOC 0x02 /* allocated by VirtualAlloc */
75 /* Conversion from VPROT_* to Win32 flags */
76 static const BYTE VIRTUAL_Win32Flags[16] =
78 PAGE_NOACCESS, /* 0 */
79 PAGE_READONLY, /* READ */
80 PAGE_READWRITE, /* WRITE */
81 PAGE_READWRITE, /* READ | WRITE */
82 PAGE_EXECUTE, /* EXEC */
83 PAGE_EXECUTE_READ, /* READ | EXEC */
84 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
85 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
86 PAGE_WRITECOPY, /* WRITECOPY */
87 PAGE_WRITECOPY, /* READ | WRITECOPY */
88 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
89 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
90 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
91 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
92 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
93 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
97 static FILE_VIEW *VIRTUAL_FirstView;
98 static CRITICAL_SECTION csVirtual = CRITICAL_SECTION_INIT("csVirtual");
101 /* These are always the same on an i386, and it will be faster this way */
102 # define page_mask 0xfff
103 # define page_shift 12
104 # define page_size 0x1000
105 # define ADDRESS_SPACE_LIMIT ((void *)0xc0000000) /* top of the user address space */
107 static UINT page_shift;
108 static UINT page_mask;
109 static UINT page_size;
110 # define ADDRESS_SPACE_LIMIT 0 /* no limit needed on other platforms */
111 #endif /* __i386__ */
112 #define granularity_mask 0xffff /* Allocation granularity (usually 64k) */
114 #define ROUND_ADDR(addr,mask) \
115 ((void *)((UINT_PTR)(addr) & ~(mask)))
117 #define ROUND_SIZE(addr,size) \
118 (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
120 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
121 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
123 static LPVOID VIRTUAL_mmap( int fd, LPVOID start, DWORD size, DWORD offset_low,
124 DWORD offset_high, int prot, int flags, BOOL *removable );
127 /***********************************************************************
130 static const char *VIRTUAL_GetProtStr( BYTE prot )
132 static char buffer[6];
133 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
134 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
135 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
136 buffer[3] = (prot & VPROT_WRITE) ?
137 ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
138 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
144 /***********************************************************************
147 static void VIRTUAL_DumpView( FILE_VIEW *view )
150 char *addr = view->base;
151 BYTE prot = view->prot[0];
153 DPRINTF( "View: %p - %p", addr, addr + view->size - 1 );
154 if (view->flags & VFLAG_SYSTEM)
155 DPRINTF( " (system)\n" );
156 else if (view->flags & VFLAG_VALLOC)
157 DPRINTF( " (valloc)\n" );
158 else if (view->mapping)
159 DPRINTF( " %p\n", view->mapping );
161 DPRINTF( " (anonymous)\n");
163 for (count = i = 1; i < view->size >> page_shift; i++, count++)
165 if (view->prot[i] == prot) continue;
166 DPRINTF( " %p - %p %s\n",
167 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
168 addr += (count << page_shift);
169 prot = view->prot[i];
173 DPRINTF( " %p - %p %s\n",
174 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
178 /***********************************************************************
181 void VIRTUAL_Dump(void)
184 DPRINTF( "\nDump of all virtual memory views:\n\n" );
185 RtlEnterCriticalSection(&csVirtual);
186 view = VIRTUAL_FirstView;
189 VIRTUAL_DumpView( view );
192 RtlLeaveCriticalSection(&csVirtual);
196 /***********************************************************************
199 * Find the view containing a given address.
205 static FILE_VIEW *VIRTUAL_FindView( const void *addr ) /* [in] Address */
209 RtlEnterCriticalSection(&csVirtual);
210 view = VIRTUAL_FirstView;
213 if (view->base > addr)
218 if ((char*)view->base + view->size > (char*)addr) break;
221 RtlLeaveCriticalSection(&csVirtual);
226 /***********************************************************************
229 * Create a new view and add it in the linked list.
231 static FILE_VIEW *VIRTUAL_CreateView( void *base, UINT size, UINT flags,
232 BYTE vprot, HANDLE mapping )
234 FILE_VIEW *view, *prev;
236 /* Create the view structure */
238 assert( !((unsigned int)base & page_mask) );
239 assert( !(size & page_mask) );
241 if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
243 view->size = size << page_shift;
245 view->mapping = mapping;
246 view->protect = vprot;
247 view->handlerProc = NULL;
248 memset( view->prot, vprot, size );
250 /* Duplicate the mapping handle */
253 NtDuplicateObject( GetCurrentProcess(), view->mapping,
254 GetCurrentProcess(), &view->mapping,
255 0, 0, DUPLICATE_SAME_ACCESS ))
261 /* Insert it in the linked list */
263 RtlEnterCriticalSection(&csVirtual);
264 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
266 view->next = VIRTUAL_FirstView;
268 if (view->next) view->next->prev = view;
269 VIRTUAL_FirstView = view;
273 prev = VIRTUAL_FirstView;
274 while (prev->next && (prev->next->base < base)) prev = prev->next;
275 view->next = prev->next;
277 if (view->next) view->next->prev = view;
280 RtlLeaveCriticalSection(&csVirtual);
281 VIRTUAL_DEBUG_DUMP_VIEW( view );
286 /***********************************************************************
293 static void VIRTUAL_DeleteView( FILE_VIEW *view ) /* [in] View */
295 if (!(view->flags & VFLAG_SYSTEM))
296 munmap( (void *)view->base, view->size );
297 RtlEnterCriticalSection(&csVirtual);
298 if (view->next) view->next->prev = view->prev;
299 if (view->prev) view->prev->next = view->next;
300 else VIRTUAL_FirstView = view->next;
301 RtlLeaveCriticalSection(&csVirtual);
302 if (view->mapping) NtClose( view->mapping );
307 /***********************************************************************
308 * VIRTUAL_GetUnixProt
310 * Convert page protections to protection for mmap/mprotect.
312 static int VIRTUAL_GetUnixProt( BYTE vprot )
315 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
317 if (vprot & VPROT_READ) prot |= PROT_READ;
318 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
319 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
320 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
326 /***********************************************************************
327 * VIRTUAL_GetWin32Prot
329 * Convert page protections to Win32 flags.
334 static void VIRTUAL_GetWin32Prot(
335 BYTE vprot, /* [in] Page protection flags */
336 DWORD *protect, /* [out] Location to store Win32 protection flags */
337 DWORD *state ) /* [out] Location to store mem state flag */
340 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
341 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
342 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
344 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
347 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
351 /***********************************************************************
354 * Build page protections from Win32 flags.
357 * Value of page protection flags
359 static BYTE VIRTUAL_GetProt( DWORD protect ) /* [in] Win32 protection flags */
363 switch(protect & 0xff)
369 vprot = VPROT_READ | VPROT_WRITE;
372 /* MSDN CreateFileMapping() states that if PAGE_WRITECOPY is given,
373 * that the hFile must have been opened with GENERIC_READ and
374 * GENERIC_WRITE access. This is WRONG as tests show that you
375 * only need GENERIC_READ access (at least for Win9x,
376 * FIXME: what about NT?). Thus, we don't put VPROT_WRITE in
377 * PAGE_WRITECOPY and PAGE_EXECUTE_WRITECOPY.
379 vprot = VPROT_READ | VPROT_WRITECOPY;
384 case PAGE_EXECUTE_READ:
385 vprot = VPROT_EXEC | VPROT_READ;
387 case PAGE_EXECUTE_READWRITE:
388 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
390 case PAGE_EXECUTE_WRITECOPY:
391 /* See comment for PAGE_WRITECOPY above */
392 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
399 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
400 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
405 /***********************************************************************
408 * Change the protection of a range of pages.
414 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
415 void *base, /* [in] Starting address */
416 UINT size, /* [in] Size in bytes */
417 BYTE vprot ) /* [in] Protections to use */
420 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
422 if (mprotect( base, size, VIRTUAL_GetUnixProt(vprot) ))
423 return FALSE; /* FIXME: last error */
425 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
426 vprot, size >> page_shift );
427 VIRTUAL_DEBUG_DUMP_VIEW( view );
432 /***********************************************************************
435 * Create an anonymous mapping aligned to the allocation granularity.
437 static NTSTATUS anon_mmap_aligned( void **addr, unsigned int size, int prot, int flags )
439 void *ptr, *base = *addr;
440 unsigned int view_size = size + (base ? 0 : granularity_mask + 1);
442 if ((ptr = wine_anon_mmap( base, view_size, prot, flags )) == (void *)-1)
444 if (errno == ENOMEM) return STATUS_NO_MEMORY;
445 return STATUS_INVALID_PARAMETER;
450 /* Release the extra memory while keeping the range
451 * starting on the granularity boundary. */
452 if ((unsigned int)ptr & granularity_mask)
454 unsigned int extra = granularity_mask + 1 - ((unsigned int)ptr & granularity_mask);
455 munmap( ptr, extra );
456 ptr = (char *)ptr + extra;
459 if (view_size > size)
460 munmap( (char *)ptr + size, view_size - size );
462 else if (ptr != base)
464 /* We couldn't get the address we wanted */
465 munmap( ptr, view_size );
466 return STATUS_CONFLICTING_ADDRESSES;
469 return STATUS_SUCCESS;
473 /***********************************************************************
476 * Apply the relocations to a mapped PE image
478 static int do_relocations( char *base, const IMAGE_DATA_DIRECTORY *dir,
479 int delta, DWORD total_size )
481 IMAGE_BASE_RELOCATION *rel;
483 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
484 base - delta, base - delta + total_size, base, base + total_size );
486 for (rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
487 ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
488 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock) )
490 char *page = base + rel->VirtualAddress;
491 WORD *TypeOffset = (WORD *)(rel + 1);
492 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
494 if (!count) continue;
497 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
498 page > base + total_size)
500 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
501 rel, rel->VirtualAddress, rel->SizeOfBlock,
502 base, dir->VirtualAddress, dir->Size );
506 TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
508 /* patching in reverse order */
509 for (i = 0 ; i < count; i++)
511 int offset = TypeOffset[i] & 0xFFF;
512 int type = TypeOffset[i] >> 12;
515 case IMAGE_REL_BASED_ABSOLUTE:
517 case IMAGE_REL_BASED_HIGH:
518 *(short*)(page+offset) += HIWORD(delta);
520 case IMAGE_REL_BASED_LOW:
521 *(short*)(page+offset) += LOWORD(delta);
523 case IMAGE_REL_BASED_HIGHLOW:
524 *(int*)(page+offset) += delta;
525 /* FIXME: if this is an exported address, fire up enhanced logic */
528 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
537 /***********************************************************************
540 * Map an executable (PE format) image into memory.
542 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, DWORD total_size,
543 DWORD header_size, int shared_fd, DWORD shared_size,
544 BOOL removable, PVOID *addr_ptr )
546 IMAGE_DOS_HEADER *dos;
547 IMAGE_NT_HEADERS *nt;
548 IMAGE_SECTION_HEADER *sec;
549 IMAGE_DATA_DIRECTORY *imports;
550 NTSTATUS status = STATUS_INVALID_IMAGE_FORMAT; /* generic error (FIXME) */
555 /* zero-map the whole range */
557 if (base < (char *)0x110000 || /* make sure the DOS area remains free */
558 (ptr = wine_anon_mmap( base, total_size,
559 PROT_READ | PROT_WRITE | PROT_EXEC, 0 )) == (char *)-1)
561 ptr = wine_anon_mmap( NULL, total_size,
562 PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
563 if (ptr == (char *)-1)
565 ERR_(module)("Not enough memory for module (%ld bytes)\n", total_size);
569 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
573 if (VIRTUAL_mmap( fd, ptr, header_size, 0, 0, PROT_READ,
574 MAP_PRIVATE | MAP_FIXED, &removable ) == (char *)-1) goto error;
575 dos = (IMAGE_DOS_HEADER *)ptr;
576 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
577 if ((char *)(nt + 1) > ptr + header_size) goto error;
579 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
580 if ((char *)(sec + nt->FileHeader.NumberOfSections) > ptr + header_size) goto error;
582 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
583 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
585 /* check the architecture */
587 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
589 MESSAGE("Trying to load PE image for unsupported architecture (");
590 switch (nt->FileHeader.Machine)
592 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
593 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
594 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
595 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
596 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
597 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
598 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
599 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
605 /* map all the sections */
607 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
611 /* a few sanity checks */
612 size = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
613 if (sec->VirtualAddress > total_size || size > total_size || size < sec->VirtualAddress)
615 ERR_(module)( "Section %.8s too large (%lx+%lx/%lx)\n",
616 sec->Name, sec->VirtualAddress, sec->Misc.VirtualSize, total_size );
620 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
621 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
623 size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
624 TRACE_(module)( "mapping shared section %.8s at %p off %lx (%x) size %lx (%lx) flags %lx\n",
625 sec->Name, ptr + sec->VirtualAddress,
626 sec->PointerToRawData, pos, sec->SizeOfRawData,
627 size, sec->Characteristics );
628 if (VIRTUAL_mmap( shared_fd, ptr + sec->VirtualAddress, size,
629 pos, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
630 MAP_SHARED|MAP_FIXED, NULL ) == (void *)-1)
632 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
636 /* check if the import directory falls inside this section */
637 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
638 imports->VirtualAddress < sec->VirtualAddress + size)
640 UINT_PTR base = imports->VirtualAddress & ~page_mask;
641 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
642 if (end > sec->VirtualAddress + size) end = sec->VirtualAddress + size;
643 if (end > base) VIRTUAL_mmap( shared_fd, ptr + base, end - base,
644 pos, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
645 MAP_PRIVATE|MAP_FIXED, NULL );
651 TRACE_(module)( "mapping section %.8s at %p off %lx size %lx flags %lx\n",
652 sec->Name, ptr + sec->VirtualAddress,
653 sec->PointerToRawData, sec->SizeOfRawData,
654 sec->Characteristics );
656 if (sec->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) continue;
657 if (!sec->PointerToRawData || !sec->SizeOfRawData) continue;
659 /* Note: if the section is not aligned properly VIRTUAL_mmap will magically
660 * fall back to read(), so we don't need to check anything here.
662 if (VIRTUAL_mmap( fd, ptr + sec->VirtualAddress, sec->SizeOfRawData,
663 sec->PointerToRawData, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
664 MAP_PRIVATE | MAP_FIXED, &removable ) == (void *)-1)
666 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
670 if ((sec->SizeOfRawData < sec->Misc.VirtualSize) && (sec->SizeOfRawData & page_mask))
672 DWORD end = ROUND_SIZE( 0, sec->SizeOfRawData );
673 if (end > sec->Misc.VirtualSize) end = sec->Misc.VirtualSize;
674 TRACE_(module)("clearing %p - %p\n",
675 ptr + sec->VirtualAddress + sec->SizeOfRawData,
676 ptr + sec->VirtualAddress + end );
677 memset( ptr + sec->VirtualAddress + sec->SizeOfRawData, 0,
678 end - sec->SizeOfRawData );
683 /* perform base relocation, if necessary */
687 const IMAGE_DATA_DIRECTORY *relocs;
689 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
690 if (!relocs->VirtualAddress || !relocs->Size)
692 if (nt->OptionalHeader.ImageBase == 0x400000)
693 ERR("Standard load address for a Win32 program (0x00400000) not available - security-patched kernel ?\n");
695 ERR( "FATAL: Need to relocate module from addr %lx, but there are no relocation records\n",
696 nt->OptionalHeader.ImageBase );
700 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
701 * really make sure that the *new* base address is also > 2GB.
702 * Some DLLs really check the MSB of the module handle :-/
704 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
705 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
707 if (!do_relocations( ptr, relocs, ptr - base, total_size ))
713 if (removable) hmapping = 0; /* don't keep handle open on removable media */
714 if (!(view = VIRTUAL_CreateView( ptr, total_size, 0, VPROT_COMMITTED|VPROT_READ, hmapping )))
716 status = STATUS_NO_MEMORY;
720 /* set the image protections */
722 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
723 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
725 DWORD size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
726 BYTE vprot = VPROT_COMMITTED;
727 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
728 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_WRITE|VPROT_WRITECOPY;
729 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
731 /* make sure the import directory is writable */
732 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
733 imports->VirtualAddress < sec->VirtualAddress + size)
734 vprot |= VPROT_READ|VPROT_WRITE|VPROT_WRITECOPY;
736 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
741 return STATUS_SUCCESS;
744 if (ptr != (char *)-1) munmap( ptr, total_size );
750 /***********************************************************************
753 * Check whether a process handle is for the current process.
755 static BOOL is_current_process( HANDLE handle )
759 if (handle == GetCurrentProcess()) return TRUE;
760 SERVER_START_REQ( get_process_info )
762 req->handle = handle;
763 if (!wine_server_call( req ))
764 ret = ((DWORD)reply->pid == GetCurrentProcessId());
771 /***********************************************************************
775 DECL_GLOBAL_CONSTRUCTOR(VIRTUAL_Init)
777 page_size = getpagesize();
778 page_mask = page_size - 1;
779 /* Make sure we have a power of 2 */
780 assert( !(page_size & page_mask) );
782 while ((1 << page_shift) != page_size) page_shift++;
784 #endif /* page_mask */
787 /***********************************************************************
788 * VIRTUAL_SetFaultHandler
790 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
794 if (!(view = VIRTUAL_FindView( addr ))) return FALSE;
795 view->handlerProc = proc;
796 view->handlerArg = arg;
800 /***********************************************************************
801 * VIRTUAL_HandleFault
803 DWORD VIRTUAL_HandleFault( LPCVOID addr )
805 FILE_VIEW *view = VIRTUAL_FindView( addr );
806 DWORD ret = EXCEPTION_ACCESS_VIOLATION;
810 if (view->handlerProc)
812 if (view->handlerProc(view->handlerArg, addr)) ret = 0; /* handled */
816 BYTE vprot = view->prot[((char *)addr - (char *)view->base) >> page_shift];
817 void *page = (void *)((UINT_PTR)addr & ~page_mask);
818 char *stack = (char *)NtCurrentTeb()->stack_base + SIGNAL_STACK_SIZE + page_mask + 1;
819 if (vprot & VPROT_GUARD)
821 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
822 ret = STATUS_GUARD_PAGE_VIOLATION;
824 /* is it inside the stack guard pages? */
825 if (((char *)addr >= stack) && ((char *)addr < stack + 2*(page_mask+1)))
826 ret = STATUS_STACK_OVERFLOW;
834 /***********************************************************************
837 * Linux kernels before 2.4.x can support non page-aligned offsets, as
838 * long as the offset is aligned to the filesystem block size. This is
839 * a big performance gain so we want to take advantage of it.
841 * However, when we use 64-bit file support this doesn't work because
842 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
843 * in that it rounds unaligned offsets down to a page boundary. For
844 * these reasons we do a direct system call here.
846 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
847 unsigned int flags, int fd, unsigned int offset_low,
848 unsigned int offset_high )
850 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
851 if (!offset_high && (offset_low & page_mask))
866 args.length = length;
870 args.offset = offset_low;
872 __asm__ __volatile__("push %%ebx\n\t"
877 : "0" (90), /* SYS_mmap */
879 if (ret < 0 && ret > -4096)
887 return mmap( addr, length, prot, flags, fd, ((off_t)offset_high << 32) | offset_low );
891 /***********************************************************************
894 * Wrapper for mmap() that handles anonymous mappings portably,
895 * and falls back to read if mmap of a file fails.
897 static LPVOID VIRTUAL_mmap( int fd, LPVOID start, DWORD size,
898 DWORD offset_low, DWORD offset_high,
899 int prot, int flags, BOOL *removable )
904 BOOL is_shared_write = FALSE;
906 if (fd == -1) return wine_anon_mmap( start, size, prot, flags );
908 if (prot & PROT_WRITE)
911 if (flags & MAP_SHARED) is_shared_write = TRUE;
914 if (!(flags & MAP_PRIVATE)) is_shared_write = TRUE;
918 if (removable && *removable)
920 /* if on removable media, try using read instead of mmap */
921 if (!is_shared_write) goto fake_mmap;
925 if ((ret = unaligned_mmap( start, size, prot, flags, fd,
926 offset_low, offset_high )) != (LPVOID)-1) return ret;
928 /* mmap() failed; if this is because the file offset is not */
929 /* page-aligned (EINVAL), or because the underlying filesystem */
930 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
932 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return ret;
933 if (is_shared_write) return ret; /* we cannot fake shared write mappings */
936 /* Reserve the memory with an anonymous mmap */
937 ret = wine_anon_mmap( start, size, PROT_READ | PROT_WRITE, flags );
938 if (ret == (LPVOID)-1) return ret;
939 /* Now read in the file */
940 offset = ((off_t)offset_high << 32) | offset_low;
941 if ((pos = lseek( fd, offset, SEEK_SET )) == -1)
946 read( fd, ret, size );
947 lseek( fd, pos, SEEK_SET ); /* Restore the file pointer */
948 mprotect( ret, size, prot ); /* Set the right protection */
953 /***********************************************************************
954 * NtAllocateVirtualMemory (NTDLL.@)
955 * ZwAllocateVirtualMemory (NTDLL.@)
957 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, PVOID addr,
958 ULONG *size_ptr, ULONG type, ULONG protect )
963 DWORD size = *size_ptr;
965 if (!is_current_process( process ))
967 ERR("Unsupported on other process\n");
968 return STATUS_ACCESS_DENIED;
971 TRACE("%p %08lx %lx %08lx\n", addr, size, type, protect );
973 /* Round parameters to a page boundary */
975 if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
979 if (type & MEM_RESERVE) /* Round down to 64k boundary */
980 base = ROUND_ADDR( addr, granularity_mask );
982 base = ROUND_ADDR( addr, page_mask );
983 size = (((UINT_PTR)addr + size + page_mask) & ~page_mask) - (UINT_PTR)base;
985 /* disallow low 64k, wrap-around and kernel space */
986 if (((char *)base <= (char *)granularity_mask) ||
987 ((char *)base + size < (char *)base) ||
988 (ADDRESS_SPACE_LIMIT && ((char *)base + size > (char *)ADDRESS_SPACE_LIMIT)))
989 return STATUS_INVALID_PARAMETER;
994 size = (size + page_mask) & ~page_mask;
997 if (type & MEM_TOP_DOWN) {
998 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
999 * Is there _ANY_ way to do it with UNIX mmap()?
1001 WARN("MEM_TOP_DOWN ignored\n");
1002 type &= ~MEM_TOP_DOWN;
1005 /* Compute the alloc type flags */
1007 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)) ||
1008 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)))
1010 ERR("called with wrong alloc type flags (%08lx) !\n", type);
1011 return STATUS_INVALID_PARAMETER;
1013 if (type & (MEM_COMMIT | MEM_SYSTEM))
1014 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
1017 /* Reserve the memory */
1019 if ((type & MEM_RESERVE) || !base)
1021 if (type & MEM_SYSTEM)
1023 if (!(view = VIRTUAL_CreateView( base, size, VFLAG_VALLOC | VFLAG_SYSTEM, vprot, 0 )))
1024 return STATUS_NO_MEMORY;
1028 NTSTATUS res = anon_mmap_aligned( &base, size, VIRTUAL_GetUnixProt( vprot ), 0 );
1029 if (res) return res;
1031 if (!(view = VIRTUAL_CreateView( base, size, VFLAG_VALLOC, vprot, 0 )))
1033 munmap( base, size );
1034 return STATUS_NO_MEMORY;
1040 /* Commit the pages */
1042 if (!(view = VIRTUAL_FindView( base )) ||
1043 ((char *)base + size > (char *)view->base + view->size)) return STATUS_NOT_MAPPED_VIEW;
1045 if (!VIRTUAL_SetProt( view, base, size, vprot )) return STATUS_ACCESS_DENIED;
1050 return STATUS_SUCCESS;
1054 /***********************************************************************
1055 * NtFreeVirtualMemory (NTDLL.@)
1056 * ZwFreeVirtualMemory (NTDLL.@)
1058 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr, ULONG type )
1062 LPVOID addr = *addr_ptr;
1063 DWORD size = *size_ptr;
1065 if (!is_current_process( process ))
1067 ERR("Unsupported on other process\n");
1068 return STATUS_ACCESS_DENIED;
1071 TRACE("%p %08lx %lx\n", addr, size, type );
1073 /* Fix the parameters */
1075 size = ROUND_SIZE( addr, size );
1076 base = ROUND_ADDR( addr, page_mask );
1078 if (!(view = VIRTUAL_FindView( base )) ||
1079 (base + size > (char *)view->base + view->size) ||
1080 !(view->flags & VFLAG_VALLOC))
1081 return STATUS_INVALID_PARAMETER;
1083 /* Check the type */
1085 if (type & MEM_SYSTEM)
1087 view->flags |= VFLAG_SYSTEM;
1088 type &= ~MEM_SYSTEM;
1091 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
1093 ERR("called with wrong free type flags (%08lx) !\n", type);
1094 return STATUS_INVALID_PARAMETER;
1097 /* Free the pages */
1099 if (type == MEM_RELEASE)
1101 if (size || (base != view->base)) return STATUS_INVALID_PARAMETER;
1102 VIRTUAL_DeleteView( view );
1106 /* Decommit the pages by remapping zero-pages instead */
1108 if (wine_anon_mmap( (LPVOID)base, size, VIRTUAL_GetUnixProt(0), MAP_FIXED ) != (LPVOID)base)
1109 ERR( "Could not remap pages, expect trouble\n" );
1110 if (!VIRTUAL_SetProt( view, base, size, 0 )) return STATUS_ACCESS_DENIED; /* FIXME */
1115 return STATUS_SUCCESS;
1119 /***********************************************************************
1120 * NtProtectVirtualMemory (NTDLL.@)
1121 * ZwProtectVirtualMemory (NTDLL.@)
1123 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr,
1124 ULONG new_prot, ULONG *old_prot )
1130 DWORD prot, size = *size_ptr;
1131 LPVOID addr = *addr_ptr;
1133 if (!is_current_process( process ))
1135 ERR("Unsupported on other process\n");
1136 return STATUS_ACCESS_DENIED;
1139 TRACE("%p %08lx %08lx\n", addr, size, new_prot );
1141 /* Fix the parameters */
1143 size = ROUND_SIZE( addr, size );
1144 base = ROUND_ADDR( addr, page_mask );
1146 if (!(view = VIRTUAL_FindView( base )) ||
1147 (base + size > (char *)view->base + view->size))
1148 return STATUS_INVALID_PARAMETER;
1150 /* Make sure all the pages are committed */
1152 p = view->prot + ((base - (char *)view->base) >> page_shift);
1153 VIRTUAL_GetWin32Prot( *p, &prot, NULL );
1154 for (i = size >> page_shift; i; i--, p++)
1156 if (!(*p & VPROT_COMMITTED)) return STATUS_INVALID_PARAMETER;
1159 if (old_prot) *old_prot = prot;
1160 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1161 if (!VIRTUAL_SetProt( view, base, size, vprot )) return STATUS_ACCESS_DENIED;
1165 return STATUS_SUCCESS;
1169 /***********************************************************************
1170 * NtQueryVirtualMemory (NTDLL.@)
1171 * ZwQueryVirtualMemory (NTDLL.@)
1173 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1174 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1175 ULONG len, ULONG *res_len )
1178 char *base, *alloc_base = 0;
1180 MEMORY_BASIC_INFORMATION *info = buffer;
1182 if (info_class != MemoryBasicInformation) return STATUS_INVALID_INFO_CLASS;
1183 if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1184 return STATUS_WORKING_SET_LIMIT_RANGE; /* FIXME */
1186 if (!is_current_process( process ))
1188 ERR("Unsupported on other process\n");
1189 return STATUS_ACCESS_DENIED;
1192 base = ROUND_ADDR( addr, page_mask );
1194 /* Find the view containing the address */
1196 RtlEnterCriticalSection(&csVirtual);
1197 view = VIRTUAL_FirstView;
1202 size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1205 if ((char *)view->base > base)
1207 size = (char *)view->base - alloc_base;
1211 if ((char *)view->base + view->size > base)
1213 alloc_base = view->base;
1217 alloc_base = (char *)view->base + view->size;
1220 RtlLeaveCriticalSection(&csVirtual);
1222 /* Fill the info structure */
1226 info->State = MEM_FREE;
1228 info->AllocationProtect = 0;
1233 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1234 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
1235 for (size = base - alloc_base; size < view->size; size += page_mask+1)
1236 if (view->prot[size >> page_shift] != vprot) break;
1237 info->AllocationProtect = view->protect;
1238 info->Type = MEM_PRIVATE; /* FIXME */
1241 info->BaseAddress = (LPVOID)base;
1242 info->AllocationBase = (LPVOID)alloc_base;
1243 info->RegionSize = size - (base - alloc_base);
1244 *res_len = sizeof(*info);
1245 return STATUS_SUCCESS;
1249 /***********************************************************************
1250 * NtLockVirtualMemory (NTDLL.@)
1251 * ZwLockVirtualMemory (NTDLL.@)
1253 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1255 if (!is_current_process( process ))
1257 ERR("Unsupported on other process\n");
1258 return STATUS_ACCESS_DENIED;
1260 return STATUS_SUCCESS;
1264 /***********************************************************************
1265 * NtUnlockVirtualMemory (NTDLL.@)
1266 * ZwUnlockVirtualMemory (NTDLL.@)
1268 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1270 if (!is_current_process( process ))
1272 ERR("Unsupported on other process\n");
1273 return STATUS_ACCESS_DENIED;
1275 return STATUS_SUCCESS;
1279 /***********************************************************************
1280 * NtCreateSection (NTDLL.@)
1281 * ZwCreateSection (NTDLL.@)
1283 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1284 const LARGE_INTEGER *size, ULONG protect,
1285 ULONG sec_flags, HANDLE file )
1289 DWORD len = attr->ObjectName ? attr->ObjectName->Length : 0;
1291 /* Check parameters */
1293 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1295 vprot = VIRTUAL_GetProt( protect );
1296 if (sec_flags & SEC_RESERVE)
1298 if (file) return STATUS_INVALID_PARAMETER;
1300 else vprot |= VPROT_COMMITTED;
1301 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1302 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
1304 /* Create the server object */
1306 SERVER_START_REQ( create_mapping )
1308 req->file_handle = file;
1309 req->size_high = size ? size->s.HighPart : 0;
1310 req->size_low = size ? size->s.LowPart : 0;
1311 req->protect = vprot;
1312 req->access = access;
1313 req->inherit = (attr->Attributes & OBJ_INHERIT) != 0;
1314 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
1315 ret = wine_server_call( req );
1316 *handle = reply->handle;
1323 /***********************************************************************
1324 * NtOpenSection (NTDLL.@)
1325 * ZwOpenSection (NTDLL.@)
1327 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1330 DWORD len = attr->ObjectName->Length;
1332 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1334 SERVER_START_REQ( open_mapping )
1336 req->access = access;
1337 req->inherit = (attr->Attributes & OBJ_INHERIT) != 0;
1338 wine_server_add_data( req, attr->ObjectName->Buffer, len );
1339 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
1346 /***********************************************************************
1347 * NtMapViewOfSection (NTDLL.@)
1348 * ZwMapViewOfSection (NTDLL.@)
1350 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
1351 ULONG commit_size, const LARGE_INTEGER *offset, ULONG *size_ptr,
1352 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
1357 int flags = MAP_PRIVATE;
1358 int unix_handle = -1;
1360 void *base, *ptr = (void *)-1, *ret;
1361 DWORD size_low, size_high, header_size, shared_size;
1365 if (!is_current_process( process ))
1367 ERR("Unsupported on other process\n");
1368 return STATUS_ACCESS_DENIED;
1371 TRACE("handle=%p addr=%p off=%lx%08lx size=%x access=%lx\n",
1372 handle, *addr_ptr, offset->s.HighPart, offset->s.LowPart, size, protect );
1374 /* Check parameters */
1376 if ((offset->s.LowPart & granularity_mask) ||
1377 (*addr_ptr && ((UINT_PTR)*addr_ptr & granularity_mask)))
1378 return STATUS_INVALID_PARAMETER;
1380 SERVER_START_REQ( get_mapping_info )
1382 req->handle = handle;
1383 res = wine_server_call( req );
1384 prot = reply->protect;
1386 size_low = reply->size_low;
1387 size_high = reply->size_high;
1388 header_size = reply->header_size;
1389 shared_file = reply->shared_file;
1390 shared_size = reply->shared_size;
1391 removable = (reply->drive_type == DRIVE_REMOVABLE ||
1392 reply->drive_type == DRIVE_CDROM);
1395 if (res) goto error;
1397 if ((res = wine_server_handle_to_fd( handle, 0, &unix_handle, NULL, NULL ))) goto error;
1399 if (prot & VPROT_IMAGE)
1405 if ((res = wine_server_handle_to_fd( shared_file, GENERIC_READ, &shared_fd,
1406 NULL, NULL ))) goto error;
1407 NtClose( shared_file ); /* we no longer need it */
1409 res = map_image( handle, unix_handle, base, size_low, header_size,
1410 shared_fd, shared_size, removable, addr_ptr );
1411 if (shared_fd != -1) close( shared_fd );
1412 if (!res) *size_ptr = size_low;
1418 ERR("Sizes larger than 4Gb not supported\n");
1420 if ((offset->s.LowPart >= size_low) ||
1421 (*size_ptr > size_low - offset->s.LowPart))
1423 res = STATUS_INVALID_PARAMETER;
1426 if (*size_ptr) size = ROUND_SIZE( offset->s.LowPart, *size_ptr );
1427 else size = size_low - offset->s.LowPart;
1433 case PAGE_READWRITE:
1434 case PAGE_EXECUTE_READWRITE:
1435 if (!(prot & VPROT_WRITE))
1437 res = STATUS_INVALID_PARAMETER;
1443 case PAGE_WRITECOPY:
1445 case PAGE_EXECUTE_READ:
1446 case PAGE_EXECUTE_WRITECOPY:
1447 if (prot & VPROT_READ) break;
1450 res = STATUS_INVALID_PARAMETER;
1454 /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1455 * which has a view of this mapping commits some pages, they will
1456 * appear commited in all other processes, which have the same
1457 * view created. Since we don`t support this yet, we create the
1458 * whole mapping commited.
1460 prot |= VPROT_COMMITTED;
1462 /* Reserve a properly aligned area */
1464 if ((res = anon_mmap_aligned( addr_ptr, size, PROT_NONE, 0 ))) goto error;
1469 TRACE("handle=%p size=%x offset=%lx\n", handle, size, offset->s.LowPart );
1471 ret = VIRTUAL_mmap( unix_handle, ptr, size, offset->s.LowPart, offset->s.HighPart,
1472 VIRTUAL_GetUnixProt( prot ), flags | MAP_FIXED, &removable );
1475 ERR( "VIRTUAL_mmap %p %x %lx%08lx failed\n",
1476 ptr, size, offset->s.HighPart, offset->s.LowPart );
1477 res = STATUS_NO_MEMORY; /* FIXME */
1480 if (removable) handle = 0; /* don't keep handle open on removable media */
1482 if (!(view = VIRTUAL_CreateView( ptr, size, 0, prot, handle )))
1484 res = STATUS_NO_MEMORY;
1487 if (unix_handle != -1) close( unix_handle );
1489 return STATUS_SUCCESS;
1492 if (unix_handle != -1) close( unix_handle );
1493 if (ptr != (void *)-1) munmap( ptr, size );
1498 /***********************************************************************
1499 * NtUnmapViewOfSection (NTDLL.@)
1500 * ZwUnmapViewOfSection (NTDLL.@)
1502 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
1505 void *base = ROUND_ADDR( addr, page_mask );
1507 if (!is_current_process( process ))
1509 ERR("Unsupported on other process\n");
1510 return STATUS_ACCESS_DENIED;
1512 if (!(view = VIRTUAL_FindView( base )) || (base != view->base)) return STATUS_INVALID_PARAMETER;
1513 VIRTUAL_DeleteView( view );
1514 return STATUS_SUCCESS;
1518 /***********************************************************************
1519 * NtFlushVirtualMemory (NTDLL.@)
1520 * ZwFlushVirtualMemory (NTDLL.@)
1522 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
1523 ULONG *size_ptr, ULONG unknown )
1526 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
1528 if (!is_current_process( process ))
1530 ERR("Unsupported on other process\n");
1531 return STATUS_ACCESS_DENIED;
1533 if (!(view = VIRTUAL_FindView( addr ))) return STATUS_INVALID_PARAMETER;
1534 if (!*size_ptr) *size_ptr = view->size;
1536 if (!msync( addr, *size_ptr, MS_SYNC )) return STATUS_SUCCESS;
1537 return STATUS_NOT_MAPPED_DATA;