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 /* Note: ADDRESS_SPACE_LIMIT is a Windows limit, you cannot change it.
106 * If you are on Solaris you need to find a way to avoid having the system
107 * allocate things above 0xc000000. Don't touch that define.
109 # define ADDRESS_SPACE_LIMIT ((void *)0xc0000000) /* top of the user address space */
111 static UINT page_shift;
112 static UINT page_mask;
113 static UINT page_size;
114 # define ADDRESS_SPACE_LIMIT 0 /* no limit needed on other platforms */
115 #endif /* __i386__ */
116 #define granularity_mask 0xffff /* Allocation granularity (usually 64k) */
118 #define ROUND_ADDR(addr,mask) \
119 ((void *)((UINT_PTR)(addr) & ~(mask)))
121 #define ROUND_SIZE(addr,size) \
122 (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
124 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
125 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
127 static LPVOID VIRTUAL_mmap( int fd, LPVOID start, DWORD size, DWORD offset_low,
128 DWORD offset_high, int prot, int flags, BOOL *removable );
131 /***********************************************************************
134 static const char *VIRTUAL_GetProtStr( BYTE prot )
136 static char buffer[6];
137 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
138 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
139 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
140 buffer[3] = (prot & VPROT_WRITE) ?
141 ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
142 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
148 /***********************************************************************
151 static void VIRTUAL_DumpView( FILE_VIEW *view )
154 char *addr = view->base;
155 BYTE prot = view->prot[0];
157 DPRINTF( "View: %p - %p", addr, addr + view->size - 1 );
158 if (view->flags & VFLAG_SYSTEM)
159 DPRINTF( " (system)\n" );
160 else if (view->flags & VFLAG_VALLOC)
161 DPRINTF( " (valloc)\n" );
162 else if (view->mapping)
163 DPRINTF( " %p\n", view->mapping );
165 DPRINTF( " (anonymous)\n");
167 for (count = i = 1; i < view->size >> page_shift; i++, count++)
169 if (view->prot[i] == prot) continue;
170 DPRINTF( " %p - %p %s\n",
171 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
172 addr += (count << page_shift);
173 prot = view->prot[i];
177 DPRINTF( " %p - %p %s\n",
178 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
182 /***********************************************************************
185 void VIRTUAL_Dump(void)
188 DPRINTF( "\nDump of all virtual memory views:\n\n" );
189 RtlEnterCriticalSection(&csVirtual);
190 view = VIRTUAL_FirstView;
193 VIRTUAL_DumpView( view );
196 RtlLeaveCriticalSection(&csVirtual);
200 /***********************************************************************
203 * Find the view containing a given address.
209 static FILE_VIEW *VIRTUAL_FindView( const void *addr ) /* [in] Address */
213 RtlEnterCriticalSection(&csVirtual);
214 view = VIRTUAL_FirstView;
217 if (view->base > addr)
222 if ((char*)view->base + view->size > (char*)addr) break;
225 RtlLeaveCriticalSection(&csVirtual);
230 /***********************************************************************
233 * Create a new view and add it in the linked list.
235 static FILE_VIEW *VIRTUAL_CreateView( void *base, UINT size, UINT flags,
236 BYTE vprot, HANDLE mapping )
238 FILE_VIEW *view, *prev;
240 /* Create the view structure */
242 assert( !((unsigned int)base & page_mask) );
243 assert( !(size & page_mask) );
245 if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
247 view->size = size << page_shift;
249 view->mapping = mapping;
250 view->protect = vprot;
251 view->handlerProc = NULL;
252 memset( view->prot, vprot, size );
254 /* Duplicate the mapping handle */
257 NtDuplicateObject( GetCurrentProcess(), view->mapping,
258 GetCurrentProcess(), &view->mapping,
259 0, 0, DUPLICATE_SAME_ACCESS ))
265 /* Insert it in the linked list */
267 RtlEnterCriticalSection(&csVirtual);
268 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
270 view->next = VIRTUAL_FirstView;
272 if (view->next) view->next->prev = view;
273 VIRTUAL_FirstView = view;
277 prev = VIRTUAL_FirstView;
278 while (prev->next && (prev->next->base < base)) prev = prev->next;
279 view->next = prev->next;
281 if (view->next) view->next->prev = view;
284 RtlLeaveCriticalSection(&csVirtual);
285 VIRTUAL_DEBUG_DUMP_VIEW( view );
290 /***********************************************************************
297 static void VIRTUAL_DeleteView( FILE_VIEW *view ) /* [in] View */
299 if (!(view->flags & VFLAG_SYSTEM))
300 munmap( (void *)view->base, view->size );
301 RtlEnterCriticalSection(&csVirtual);
302 if (view->next) view->next->prev = view->prev;
303 if (view->prev) view->prev->next = view->next;
304 else VIRTUAL_FirstView = view->next;
305 RtlLeaveCriticalSection(&csVirtual);
306 if (view->mapping) NtClose( view->mapping );
311 /***********************************************************************
312 * VIRTUAL_GetUnixProt
314 * Convert page protections to protection for mmap/mprotect.
316 static int VIRTUAL_GetUnixProt( BYTE vprot )
319 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
321 if (vprot & VPROT_READ) prot |= PROT_READ;
322 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
323 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
324 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
330 /***********************************************************************
331 * VIRTUAL_GetWin32Prot
333 * Convert page protections to Win32 flags.
338 static void VIRTUAL_GetWin32Prot(
339 BYTE vprot, /* [in] Page protection flags */
340 DWORD *protect, /* [out] Location to store Win32 protection flags */
341 DWORD *state ) /* [out] Location to store mem state flag */
344 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
345 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
346 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
348 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
351 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
355 /***********************************************************************
358 * Build page protections from Win32 flags.
361 * Value of page protection flags
363 static BYTE VIRTUAL_GetProt( DWORD protect ) /* [in] Win32 protection flags */
367 switch(protect & 0xff)
373 vprot = VPROT_READ | VPROT_WRITE;
376 /* MSDN CreateFileMapping() states that if PAGE_WRITECOPY is given,
377 * that the hFile must have been opened with GENERIC_READ and
378 * GENERIC_WRITE access. This is WRONG as tests show that you
379 * only need GENERIC_READ access (at least for Win9x,
380 * FIXME: what about NT?). Thus, we don't put VPROT_WRITE in
381 * PAGE_WRITECOPY and PAGE_EXECUTE_WRITECOPY.
383 vprot = VPROT_READ | VPROT_WRITECOPY;
388 case PAGE_EXECUTE_READ:
389 vprot = VPROT_EXEC | VPROT_READ;
391 case PAGE_EXECUTE_READWRITE:
392 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
394 case PAGE_EXECUTE_WRITECOPY:
395 /* See comment for PAGE_WRITECOPY above */
396 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
403 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
404 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
409 /***********************************************************************
412 * Change the protection of a range of pages.
418 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
419 void *base, /* [in] Starting address */
420 UINT size, /* [in] Size in bytes */
421 BYTE vprot ) /* [in] Protections to use */
424 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
426 if (mprotect( base, size, VIRTUAL_GetUnixProt(vprot) ))
427 return FALSE; /* FIXME: last error */
429 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
430 vprot, size >> page_shift );
431 VIRTUAL_DEBUG_DUMP_VIEW( view );
436 /***********************************************************************
439 * Create an anonymous mapping aligned to the allocation granularity.
441 static NTSTATUS anon_mmap_aligned( void **addr, unsigned int size, int prot, int flags )
443 void *ptr, *base = *addr;
444 unsigned int view_size = size + (base ? 0 : granularity_mask + 1);
446 if ((ptr = wine_anon_mmap( base, view_size, prot, flags )) == (void *)-1)
448 if (errno == ENOMEM) return STATUS_NO_MEMORY;
449 return STATUS_INVALID_PARAMETER;
454 /* Release the extra memory while keeping the range
455 * starting on the granularity boundary. */
456 if ((unsigned int)ptr & granularity_mask)
458 unsigned int extra = granularity_mask + 1 - ((unsigned int)ptr & granularity_mask);
459 munmap( ptr, extra );
460 ptr = (char *)ptr + extra;
463 if (view_size > size)
464 munmap( (char *)ptr + size, view_size - size );
466 else if (ptr != base)
468 /* We couldn't get the address we wanted */
469 munmap( ptr, view_size );
470 return STATUS_CONFLICTING_ADDRESSES;
473 return STATUS_SUCCESS;
477 /***********************************************************************
480 * Apply the relocations to a mapped PE image
482 static int do_relocations( char *base, const IMAGE_DATA_DIRECTORY *dir,
483 int delta, DWORD total_size )
485 IMAGE_BASE_RELOCATION *rel;
487 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
488 base - delta, base - delta + total_size, base, base + total_size );
490 for (rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
491 ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
492 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock) )
494 char *page = base + rel->VirtualAddress;
495 WORD *TypeOffset = (WORD *)(rel + 1);
496 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
498 if (!count) continue;
501 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
502 page > base + total_size)
504 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
505 rel, rel->VirtualAddress, rel->SizeOfBlock,
506 base, dir->VirtualAddress, dir->Size );
510 TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
512 /* patching in reverse order */
513 for (i = 0 ; i < count; i++)
515 int offset = TypeOffset[i] & 0xFFF;
516 int type = TypeOffset[i] >> 12;
519 case IMAGE_REL_BASED_ABSOLUTE:
521 case IMAGE_REL_BASED_HIGH:
522 *(short*)(page+offset) += HIWORD(delta);
524 case IMAGE_REL_BASED_LOW:
525 *(short*)(page+offset) += LOWORD(delta);
527 case IMAGE_REL_BASED_HIGHLOW:
528 *(int*)(page+offset) += delta;
529 /* FIXME: if this is an exported address, fire up enhanced logic */
532 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
541 /***********************************************************************
544 * Map an executable (PE format) image into memory.
546 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, DWORD total_size,
547 DWORD header_size, int shared_fd, DWORD shared_size,
548 BOOL removable, PVOID *addr_ptr )
550 IMAGE_DOS_HEADER *dos;
551 IMAGE_NT_HEADERS *nt;
552 IMAGE_SECTION_HEADER *sec;
553 IMAGE_DATA_DIRECTORY *imports;
554 NTSTATUS status = STATUS_INVALID_IMAGE_FORMAT; /* generic error (FIXME) */
559 /* zero-map the whole range */
561 if (base < (char *)0x110000 || /* make sure the DOS area remains free */
562 (ptr = wine_anon_mmap( base, total_size,
563 PROT_READ | PROT_WRITE | PROT_EXEC, 0 )) == (char *)-1)
565 ptr = wine_anon_mmap( NULL, total_size,
566 PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
567 if (ptr == (char *)-1)
569 ERR_(module)("Not enough memory for module (%ld bytes)\n", total_size);
573 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
577 if (VIRTUAL_mmap( fd, ptr, header_size, 0, 0, PROT_READ,
578 MAP_PRIVATE | MAP_FIXED, &removable ) == (char *)-1) goto error;
579 dos = (IMAGE_DOS_HEADER *)ptr;
580 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
581 if ((char *)(nt + 1) > ptr + header_size) goto error;
583 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
584 if ((char *)(sec + nt->FileHeader.NumberOfSections) > ptr + header_size) goto error;
586 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
587 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
589 /* check the architecture */
591 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
593 MESSAGE("Trying to load PE image for unsupported architecture (");
594 switch (nt->FileHeader.Machine)
596 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
597 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
598 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
599 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
600 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
601 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
602 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
603 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
609 /* map all the sections */
611 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
615 /* a few sanity checks */
616 size = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
617 if (sec->VirtualAddress > total_size || size > total_size || size < sec->VirtualAddress)
619 ERR_(module)( "Section %.8s too large (%lx+%lx/%lx)\n",
620 sec->Name, sec->VirtualAddress, sec->Misc.VirtualSize, total_size );
624 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
625 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
627 size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
628 TRACE_(module)( "mapping shared section %.8s at %p off %lx (%x) size %lx (%lx) flags %lx\n",
629 sec->Name, ptr + sec->VirtualAddress,
630 sec->PointerToRawData, pos, sec->SizeOfRawData,
631 size, sec->Characteristics );
632 if (VIRTUAL_mmap( shared_fd, ptr + sec->VirtualAddress, size,
633 pos, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
634 MAP_SHARED|MAP_FIXED, NULL ) == (void *)-1)
636 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
640 /* check if the import directory falls inside this section */
641 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
642 imports->VirtualAddress < sec->VirtualAddress + size)
644 UINT_PTR base = imports->VirtualAddress & ~page_mask;
645 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
646 if (end > sec->VirtualAddress + size) end = sec->VirtualAddress + size;
647 if (end > base) VIRTUAL_mmap( shared_fd, ptr + base, end - base,
648 pos + (base - sec->VirtualAddress), 0,
649 PROT_READ|PROT_WRITE|PROT_EXEC,
650 MAP_PRIVATE|MAP_FIXED, NULL );
656 TRACE_(module)( "mapping section %.8s at %p off %lx size %lx flags %lx\n",
657 sec->Name, ptr + sec->VirtualAddress,
658 sec->PointerToRawData, sec->SizeOfRawData,
659 sec->Characteristics );
661 if (sec->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) continue;
662 if (!sec->PointerToRawData || !sec->SizeOfRawData) continue;
664 /* Note: if the section is not aligned properly VIRTUAL_mmap will magically
665 * fall back to read(), so we don't need to check anything here.
667 if (VIRTUAL_mmap( fd, ptr + sec->VirtualAddress, sec->SizeOfRawData,
668 sec->PointerToRawData, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
669 MAP_PRIVATE | MAP_FIXED, &removable ) == (void *)-1)
671 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
675 if ((sec->SizeOfRawData < sec->Misc.VirtualSize) && (sec->SizeOfRawData & page_mask))
677 DWORD end = ROUND_SIZE( 0, sec->SizeOfRawData );
678 if (end > sec->Misc.VirtualSize) end = sec->Misc.VirtualSize;
679 TRACE_(module)("clearing %p - %p\n",
680 ptr + sec->VirtualAddress + sec->SizeOfRawData,
681 ptr + sec->VirtualAddress + end );
682 memset( ptr + sec->VirtualAddress + sec->SizeOfRawData, 0,
683 end - sec->SizeOfRawData );
688 /* perform base relocation, if necessary */
692 const IMAGE_DATA_DIRECTORY *relocs;
694 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
695 if (!relocs->VirtualAddress || !relocs->Size)
697 if (nt->OptionalHeader.ImageBase == 0x400000)
698 ERR("Standard load address for a Win32 program (0x00400000) not available - security-patched kernel ?\n");
700 ERR( "FATAL: Need to relocate module from addr %lx, but there are no relocation records\n",
701 nt->OptionalHeader.ImageBase );
705 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
706 * really make sure that the *new* base address is also > 2GB.
707 * Some DLLs really check the MSB of the module handle :-/
709 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
710 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
712 if (!do_relocations( ptr, relocs, ptr - base, total_size ))
718 if (removable) hmapping = 0; /* don't keep handle open on removable media */
719 if (!(view = VIRTUAL_CreateView( ptr, total_size, 0, VPROT_COMMITTED|VPROT_READ, hmapping )))
721 status = STATUS_NO_MEMORY;
725 /* set the image protections */
727 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
728 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
730 DWORD size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
731 BYTE vprot = VPROT_COMMITTED;
732 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
733 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_WRITE|VPROT_WRITECOPY;
734 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
736 /* make sure the import directory is writable */
737 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
738 imports->VirtualAddress < sec->VirtualAddress + size)
739 vprot |= VPROT_READ|VPROT_WRITE|VPROT_WRITECOPY;
741 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
746 return STATUS_SUCCESS;
749 if (ptr != (char *)-1) munmap( ptr, total_size );
755 /***********************************************************************
758 * Check whether a process handle is for the current process.
760 static BOOL is_current_process( HANDLE handle )
764 if (handle == GetCurrentProcess()) return TRUE;
765 SERVER_START_REQ( get_process_info )
767 req->handle = handle;
768 if (!wine_server_call( req ))
769 ret = ((DWORD)reply->pid == GetCurrentProcessId());
776 /***********************************************************************
780 DECL_GLOBAL_CONSTRUCTOR(VIRTUAL_Init)
782 page_size = getpagesize();
783 page_mask = page_size - 1;
784 /* Make sure we have a power of 2 */
785 assert( !(page_size & page_mask) );
787 while ((1 << page_shift) != page_size) page_shift++;
789 #endif /* page_mask */
792 /***********************************************************************
793 * VIRTUAL_SetFaultHandler
795 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
799 if (!(view = VIRTUAL_FindView( addr ))) return FALSE;
800 view->handlerProc = proc;
801 view->handlerArg = arg;
805 /***********************************************************************
806 * VIRTUAL_HandleFault
808 DWORD VIRTUAL_HandleFault( LPCVOID addr )
810 FILE_VIEW *view = VIRTUAL_FindView( addr );
811 DWORD ret = EXCEPTION_ACCESS_VIOLATION;
815 if (view->handlerProc)
817 if (view->handlerProc(view->handlerArg, addr)) ret = 0; /* handled */
821 BYTE vprot = view->prot[((char *)addr - (char *)view->base) >> page_shift];
822 void *page = (void *)((UINT_PTR)addr & ~page_mask);
823 char *stack = (char *)NtCurrentTeb()->stack_base + SIGNAL_STACK_SIZE + page_mask + 1;
824 if (vprot & VPROT_GUARD)
826 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
827 ret = STATUS_GUARD_PAGE_VIOLATION;
829 /* is it inside the stack guard pages? */
830 if (((char *)addr >= stack) && ((char *)addr < stack + 2*(page_mask+1)))
831 ret = STATUS_STACK_OVERFLOW;
839 /***********************************************************************
842 * Linux kernels before 2.4.x can support non page-aligned offsets, as
843 * long as the offset is aligned to the filesystem block size. This is
844 * a big performance gain so we want to take advantage of it.
846 * However, when we use 64-bit file support this doesn't work because
847 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
848 * in that it rounds unaligned offsets down to a page boundary. For
849 * these reasons we do a direct system call here.
851 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
852 unsigned int flags, int fd, unsigned int offset_low,
853 unsigned int offset_high )
855 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
856 if (!offset_high && (offset_low & page_mask))
871 args.length = length;
875 args.offset = offset_low;
877 __asm__ __volatile__("push %%ebx\n\t"
882 : "0" (90), /* SYS_mmap */
884 if (ret < 0 && ret > -4096)
892 return mmap( addr, length, prot, flags, fd, ((off_t)offset_high << 32) | offset_low );
896 /***********************************************************************
899 * Wrapper for mmap() that handles anonymous mappings portably,
900 * and falls back to read if mmap of a file fails.
902 static LPVOID VIRTUAL_mmap( int fd, LPVOID start, DWORD size,
903 DWORD offset_low, DWORD offset_high,
904 int prot, int flags, BOOL *removable )
909 BOOL is_shared_write = FALSE;
911 if (fd == -1) return wine_anon_mmap( start, size, prot, flags );
913 if (prot & PROT_WRITE)
916 if (flags & MAP_SHARED) is_shared_write = TRUE;
919 if (!(flags & MAP_PRIVATE)) is_shared_write = TRUE;
923 if (removable && *removable)
925 /* if on removable media, try using read instead of mmap */
926 if (!is_shared_write) goto fake_mmap;
930 if ((ret = unaligned_mmap( start, size, prot, flags, fd,
931 offset_low, offset_high )) != (LPVOID)-1) return ret;
933 /* mmap() failed; if this is because the file offset is not */
934 /* page-aligned (EINVAL), or because the underlying filesystem */
935 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
937 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return ret;
938 if (is_shared_write) return ret; /* we cannot fake shared write mappings */
941 /* Reserve the memory with an anonymous mmap */
942 ret = wine_anon_mmap( start, size, PROT_READ | PROT_WRITE, flags );
943 if (ret == (LPVOID)-1) return ret;
944 /* Now read in the file */
945 offset = ((off_t)offset_high << 32) | offset_low;
946 if ((pos = lseek( fd, offset, SEEK_SET )) == -1)
951 read( fd, ret, size );
952 lseek( fd, pos, SEEK_SET ); /* Restore the file pointer */
953 mprotect( ret, size, prot ); /* Set the right protection */
958 /***********************************************************************
959 * NtAllocateVirtualMemory (NTDLL.@)
960 * ZwAllocateVirtualMemory (NTDLL.@)
962 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, PVOID addr,
963 ULONG *size_ptr, ULONG type, ULONG protect )
968 DWORD size = *size_ptr;
970 if (!is_current_process( process ))
972 ERR("Unsupported on other process\n");
973 return STATUS_ACCESS_DENIED;
976 TRACE("%p %08lx %lx %08lx\n", addr, size, type, protect );
978 /* Round parameters to a page boundary */
980 if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
984 if (type & MEM_RESERVE) /* Round down to 64k boundary */
985 base = ROUND_ADDR( addr, granularity_mask );
987 base = ROUND_ADDR( addr, page_mask );
988 size = (((UINT_PTR)addr + size + page_mask) & ~page_mask) - (UINT_PTR)base;
990 /* disallow low 64k, wrap-around and kernel space */
991 if (((char *)base <= (char *)granularity_mask) ||
992 ((char *)base + size < (char *)base) ||
993 (ADDRESS_SPACE_LIMIT && ((char *)base + size > (char *)ADDRESS_SPACE_LIMIT)))
994 return STATUS_INVALID_PARAMETER;
999 size = (size + page_mask) & ~page_mask;
1002 if (type & MEM_TOP_DOWN) {
1003 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
1004 * Is there _ANY_ way to do it with UNIX mmap()?
1006 WARN("MEM_TOP_DOWN ignored\n");
1007 type &= ~MEM_TOP_DOWN;
1010 /* Compute the alloc type flags */
1012 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)) ||
1013 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)))
1015 ERR("called with wrong alloc type flags (%08lx) !\n", type);
1016 return STATUS_INVALID_PARAMETER;
1018 if (type & (MEM_COMMIT | MEM_SYSTEM))
1019 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
1022 /* Reserve the memory */
1024 if ((type & MEM_RESERVE) || !base)
1026 if (type & MEM_SYSTEM)
1028 if (!(view = VIRTUAL_CreateView( base, size, VFLAG_VALLOC | VFLAG_SYSTEM, vprot, 0 )))
1029 return STATUS_NO_MEMORY;
1033 NTSTATUS res = anon_mmap_aligned( &base, size, VIRTUAL_GetUnixProt( vprot ), 0 );
1034 if (res) return res;
1036 if (!(view = VIRTUAL_CreateView( base, size, VFLAG_VALLOC, vprot, 0 )))
1038 munmap( base, size );
1039 return STATUS_NO_MEMORY;
1045 /* Commit the pages */
1047 if (!(view = VIRTUAL_FindView( base )) ||
1048 ((char *)base + size > (char *)view->base + view->size)) return STATUS_NOT_MAPPED_VIEW;
1050 if (!VIRTUAL_SetProt( view, base, size, vprot )) return STATUS_ACCESS_DENIED;
1055 return STATUS_SUCCESS;
1059 /***********************************************************************
1060 * NtFreeVirtualMemory (NTDLL.@)
1061 * ZwFreeVirtualMemory (NTDLL.@)
1063 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr, ULONG type )
1067 LPVOID addr = *addr_ptr;
1068 DWORD size = *size_ptr;
1070 if (!is_current_process( process ))
1072 ERR("Unsupported on other process\n");
1073 return STATUS_ACCESS_DENIED;
1076 TRACE("%p %08lx %lx\n", addr, size, type );
1078 /* Fix the parameters */
1080 size = ROUND_SIZE( addr, size );
1081 base = ROUND_ADDR( addr, page_mask );
1083 if (!(view = VIRTUAL_FindView( base )) ||
1084 (base + size > (char *)view->base + view->size) ||
1085 !(view->flags & VFLAG_VALLOC))
1086 return STATUS_INVALID_PARAMETER;
1088 /* Check the type */
1090 if (type & MEM_SYSTEM)
1092 view->flags |= VFLAG_SYSTEM;
1093 type &= ~MEM_SYSTEM;
1096 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
1098 ERR("called with wrong free type flags (%08lx) !\n", type);
1099 return STATUS_INVALID_PARAMETER;
1102 /* Free the pages */
1104 if (type == MEM_RELEASE)
1106 if (size || (base != view->base)) return STATUS_INVALID_PARAMETER;
1107 VIRTUAL_DeleteView( view );
1111 /* Decommit the pages by remapping zero-pages instead */
1113 if (wine_anon_mmap( (LPVOID)base, size, VIRTUAL_GetUnixProt(0), MAP_FIXED ) != (LPVOID)base)
1114 ERR( "Could not remap pages, expect trouble\n" );
1115 if (!VIRTUAL_SetProt( view, base, size, 0 )) return STATUS_ACCESS_DENIED; /* FIXME */
1120 return STATUS_SUCCESS;
1124 /***********************************************************************
1125 * NtProtectVirtualMemory (NTDLL.@)
1126 * ZwProtectVirtualMemory (NTDLL.@)
1128 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr,
1129 ULONG new_prot, ULONG *old_prot )
1135 DWORD prot, size = *size_ptr;
1136 LPVOID addr = *addr_ptr;
1138 if (!is_current_process( process ))
1140 ERR("Unsupported on other process\n");
1141 return STATUS_ACCESS_DENIED;
1144 TRACE("%p %08lx %08lx\n", addr, size, new_prot );
1146 /* Fix the parameters */
1148 size = ROUND_SIZE( addr, size );
1149 base = ROUND_ADDR( addr, page_mask );
1151 if (!(view = VIRTUAL_FindView( base )) ||
1152 (base + size > (char *)view->base + view->size))
1153 return STATUS_INVALID_PARAMETER;
1155 /* Make sure all the pages are committed */
1157 p = view->prot + ((base - (char *)view->base) >> page_shift);
1158 VIRTUAL_GetWin32Prot( *p, &prot, NULL );
1159 for (i = size >> page_shift; i; i--, p++)
1161 if (!(*p & VPROT_COMMITTED)) return STATUS_INVALID_PARAMETER;
1164 if (old_prot) *old_prot = prot;
1165 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1166 if (!VIRTUAL_SetProt( view, base, size, vprot )) return STATUS_ACCESS_DENIED;
1170 return STATUS_SUCCESS;
1174 /***********************************************************************
1175 * NtQueryVirtualMemory (NTDLL.@)
1176 * ZwQueryVirtualMemory (NTDLL.@)
1178 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1179 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1180 ULONG len, ULONG *res_len )
1183 char *base, *alloc_base = 0;
1185 MEMORY_BASIC_INFORMATION *info = buffer;
1187 if (info_class != MemoryBasicInformation) return STATUS_INVALID_INFO_CLASS;
1188 if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1189 return STATUS_WORKING_SET_LIMIT_RANGE; /* FIXME */
1191 if (!is_current_process( process ))
1193 ERR("Unsupported on other process\n");
1194 return STATUS_ACCESS_DENIED;
1197 base = ROUND_ADDR( addr, page_mask );
1199 /* Find the view containing the address */
1201 RtlEnterCriticalSection(&csVirtual);
1202 view = VIRTUAL_FirstView;
1207 size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1210 if ((char *)view->base > base)
1212 size = (char *)view->base - alloc_base;
1216 if ((char *)view->base + view->size > base)
1218 alloc_base = view->base;
1222 alloc_base = (char *)view->base + view->size;
1225 RtlLeaveCriticalSection(&csVirtual);
1227 /* Fill the info structure */
1231 info->State = MEM_FREE;
1233 info->AllocationProtect = 0;
1238 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1239 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
1240 for (size = base - alloc_base; size < view->size; size += page_mask+1)
1241 if (view->prot[size >> page_shift] != vprot) break;
1242 info->AllocationProtect = view->protect;
1243 info->Type = MEM_PRIVATE; /* FIXME */
1246 info->BaseAddress = (LPVOID)base;
1247 info->AllocationBase = (LPVOID)alloc_base;
1248 info->RegionSize = size - (base - alloc_base);
1249 if (res_len) *res_len = sizeof(*info);
1250 return STATUS_SUCCESS;
1254 /***********************************************************************
1255 * NtLockVirtualMemory (NTDLL.@)
1256 * ZwLockVirtualMemory (NTDLL.@)
1258 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1260 if (!is_current_process( process ))
1262 ERR("Unsupported on other process\n");
1263 return STATUS_ACCESS_DENIED;
1265 return STATUS_SUCCESS;
1269 /***********************************************************************
1270 * NtUnlockVirtualMemory (NTDLL.@)
1271 * ZwUnlockVirtualMemory (NTDLL.@)
1273 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1275 if (!is_current_process( process ))
1277 ERR("Unsupported on other process\n");
1278 return STATUS_ACCESS_DENIED;
1280 return STATUS_SUCCESS;
1284 /***********************************************************************
1285 * NtCreateSection (NTDLL.@)
1286 * ZwCreateSection (NTDLL.@)
1288 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1289 const LARGE_INTEGER *size, ULONG protect,
1290 ULONG sec_flags, HANDLE file )
1294 DWORD len = attr->ObjectName ? attr->ObjectName->Length : 0;
1296 /* Check parameters */
1298 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1300 vprot = VIRTUAL_GetProt( protect );
1301 if (sec_flags & SEC_RESERVE)
1303 if (file) return STATUS_INVALID_PARAMETER;
1305 else vprot |= VPROT_COMMITTED;
1306 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1307 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
1309 /* Create the server object */
1311 SERVER_START_REQ( create_mapping )
1313 req->file_handle = file;
1314 req->size_high = size ? size->s.HighPart : 0;
1315 req->size_low = size ? size->s.LowPart : 0;
1316 req->protect = vprot;
1317 req->access = access;
1318 req->inherit = (attr->Attributes & OBJ_INHERIT) != 0;
1319 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
1320 ret = wine_server_call( req );
1321 *handle = reply->handle;
1328 /***********************************************************************
1329 * NtOpenSection (NTDLL.@)
1330 * ZwOpenSection (NTDLL.@)
1332 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1335 DWORD len = attr->ObjectName->Length;
1337 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1339 SERVER_START_REQ( open_mapping )
1341 req->access = access;
1342 req->inherit = (attr->Attributes & OBJ_INHERIT) != 0;
1343 wine_server_add_data( req, attr->ObjectName->Buffer, len );
1344 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
1351 /***********************************************************************
1352 * NtMapViewOfSection (NTDLL.@)
1353 * ZwMapViewOfSection (NTDLL.@)
1355 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
1356 ULONG commit_size, const LARGE_INTEGER *offset, ULONG *size_ptr,
1357 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
1362 int flags = MAP_PRIVATE;
1363 int unix_handle = -1;
1365 void *base, *ptr = (void *)-1, *ret;
1366 DWORD size_low, size_high, header_size, shared_size;
1370 if (!is_current_process( process ))
1372 ERR("Unsupported on other process\n");
1373 return STATUS_ACCESS_DENIED;
1376 TRACE("handle=%p addr=%p off=%lx%08lx size=%x access=%lx\n",
1377 handle, *addr_ptr, offset->s.HighPart, offset->s.LowPart, size, protect );
1379 /* Check parameters */
1381 if ((offset->s.LowPart & granularity_mask) ||
1382 (*addr_ptr && ((UINT_PTR)*addr_ptr & granularity_mask)))
1383 return STATUS_INVALID_PARAMETER;
1385 SERVER_START_REQ( get_mapping_info )
1387 req->handle = handle;
1388 res = wine_server_call( req );
1389 prot = reply->protect;
1391 size_low = reply->size_low;
1392 size_high = reply->size_high;
1393 header_size = reply->header_size;
1394 shared_file = reply->shared_file;
1395 shared_size = reply->shared_size;
1396 removable = (reply->drive_type == DRIVE_REMOVABLE ||
1397 reply->drive_type == DRIVE_CDROM);
1400 if (res) goto error;
1402 if ((res = wine_server_handle_to_fd( handle, 0, &unix_handle, NULL, NULL ))) goto error;
1404 if (prot & VPROT_IMAGE)
1410 if ((res = wine_server_handle_to_fd( shared_file, GENERIC_READ, &shared_fd,
1411 NULL, NULL ))) goto error;
1412 NtClose( shared_file ); /* we no longer need it */
1414 res = map_image( handle, unix_handle, base, size_low, header_size,
1415 shared_fd, shared_size, removable, addr_ptr );
1416 if (shared_fd != -1) close( shared_fd );
1417 if (!res) *size_ptr = size_low;
1423 ERR("Sizes larger than 4Gb not supported\n");
1425 if ((offset->s.LowPart >= size_low) ||
1426 (*size_ptr > size_low - offset->s.LowPart))
1428 res = STATUS_INVALID_PARAMETER;
1431 if (*size_ptr) size = ROUND_SIZE( offset->s.LowPart, *size_ptr );
1432 else size = size_low - offset->s.LowPart;
1438 case PAGE_READWRITE:
1439 case PAGE_EXECUTE_READWRITE:
1440 if (!(prot & VPROT_WRITE))
1442 res = STATUS_INVALID_PARAMETER;
1448 case PAGE_WRITECOPY:
1450 case PAGE_EXECUTE_READ:
1451 case PAGE_EXECUTE_WRITECOPY:
1452 if (prot & VPROT_READ) break;
1455 res = STATUS_INVALID_PARAMETER;
1459 /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1460 * which has a view of this mapping commits some pages, they will
1461 * appear commited in all other processes, which have the same
1462 * view created. Since we don`t support this yet, we create the
1463 * whole mapping commited.
1465 prot |= VPROT_COMMITTED;
1467 /* Reserve a properly aligned area */
1469 if ((res = anon_mmap_aligned( addr_ptr, size, PROT_NONE, 0 ))) goto error;
1474 TRACE("handle=%p size=%x offset=%lx\n", handle, size, offset->s.LowPart );
1476 ret = VIRTUAL_mmap( unix_handle, ptr, size, offset->s.LowPart, offset->s.HighPart,
1477 VIRTUAL_GetUnixProt( prot ), flags | MAP_FIXED, &removable );
1480 ERR( "VIRTUAL_mmap %p %x %lx%08lx failed\n",
1481 ptr, size, offset->s.HighPart, offset->s.LowPart );
1482 res = STATUS_NO_MEMORY; /* FIXME */
1485 if (removable) handle = 0; /* don't keep handle open on removable media */
1487 if (!(view = VIRTUAL_CreateView( ptr, size, 0, prot, handle )))
1489 res = STATUS_NO_MEMORY;
1492 if (unix_handle != -1) close( unix_handle );
1494 return STATUS_SUCCESS;
1497 if (unix_handle != -1) close( unix_handle );
1498 if (ptr != (void *)-1) munmap( ptr, size );
1503 /***********************************************************************
1504 * NtUnmapViewOfSection (NTDLL.@)
1505 * ZwUnmapViewOfSection (NTDLL.@)
1507 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
1510 void *base = ROUND_ADDR( addr, page_mask );
1512 if (!is_current_process( process ))
1514 ERR("Unsupported on other process\n");
1515 return STATUS_ACCESS_DENIED;
1517 if (!(view = VIRTUAL_FindView( base )) || (base != view->base)) return STATUS_INVALID_PARAMETER;
1518 VIRTUAL_DeleteView( view );
1519 return STATUS_SUCCESS;
1523 /***********************************************************************
1524 * NtFlushVirtualMemory (NTDLL.@)
1525 * ZwFlushVirtualMemory (NTDLL.@)
1527 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
1528 ULONG *size_ptr, ULONG unknown )
1531 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
1533 if (!is_current_process( process ))
1535 ERR("Unsupported on other process\n");
1536 return STATUS_ACCESS_DENIED;
1538 if (!(view = VIRTUAL_FindView( addr ))) return STATUS_INVALID_PARAMETER;
1539 if (!*size_ptr) *size_ptr = view->size;
1541 if (!msync( addr, *size_ptr, MS_SYNC )) return STATUS_SUCCESS;
1542 return STATUS_NOT_MAPPED_DATA;