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
47 #include "wine/library.h"
48 #include "wine/server.h"
49 #include "wine/list.h"
50 #include "wine/debug.h"
51 #include "ntdll_misc.h"
53 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
54 WINE_DECLARE_DEBUG_CHANNEL(module);
61 #define MAP_NORESERVE 0
65 typedef struct file_view
67 struct list entry; /* Entry in global view list */
68 void *base; /* Base address */
69 UINT size; /* Size in bytes */
70 HANDLE mapping; /* Handle to the file mapping */
71 HANDLERPROC handlerProc; /* Fault handler */
72 LPVOID handlerArg; /* Fault handler argument */
73 BYTE flags; /* Allocation flags (VFLAG_*) */
74 BYTE protect; /* Protection for all pages at allocation time */
75 BYTE prot[1]; /* Protection byte for each page */
79 #define VFLAG_SYSTEM 0x01 /* system view (underlying mmap not under our control) */
80 #define VFLAG_VALLOC 0x02 /* allocated by VirtualAlloc */
82 /* Conversion from VPROT_* to Win32 flags */
83 static const BYTE VIRTUAL_Win32Flags[16] =
85 PAGE_NOACCESS, /* 0 */
86 PAGE_READONLY, /* READ */
87 PAGE_READWRITE, /* WRITE */
88 PAGE_READWRITE, /* READ | WRITE */
89 PAGE_EXECUTE, /* EXEC */
90 PAGE_EXECUTE_READ, /* READ | EXEC */
91 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
92 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
93 PAGE_WRITECOPY, /* WRITECOPY */
94 PAGE_WRITECOPY, /* READ | WRITECOPY */
95 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
96 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
97 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
98 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
99 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
100 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
103 static struct list views_list = LIST_INIT(views_list);
105 static CRITICAL_SECTION csVirtual;
106 static CRITICAL_SECTION_DEBUG critsect_debug =
109 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
110 0, 0, { 0, (DWORD)(__FILE__ ": csVirtual") }
112 static CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
115 /* These are always the same on an i386, and it will be faster this way */
116 # define page_mask 0xfff
117 # define page_shift 12
118 # define page_size 0x1000
119 /* Note: these are Windows limits, you cannot change them. */
120 # define ADDRESS_SPACE_LIMIT ((void *)0xc0000000) /* top of the total available address space */
121 # define USER_SPACE_LIMIT ((void *)0x80000000) /* top of the user address space */
123 static UINT page_shift;
124 static UINT page_mask;
125 static UINT page_size;
126 # define ADDRESS_SPACE_LIMIT 0 /* no limit needed on other platforms */
127 # define USER_SPACE_LIMIT 0 /* no limit needed on other platforms */
128 #endif /* __i386__ */
129 #define granularity_mask 0xffff /* Allocation granularity (usually 64k) */
131 #define ROUND_ADDR(addr,mask) \
132 ((void *)((UINT_PTR)(addr) & ~(mask)))
134 #define ROUND_SIZE(addr,size) \
135 (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
137 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
138 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
140 static void *user_space_limit = USER_SPACE_LIMIT;
143 /***********************************************************************
146 static const char *VIRTUAL_GetProtStr( BYTE prot )
148 static char buffer[6];
149 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
150 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
151 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
152 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
153 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
159 /***********************************************************************
162 static void VIRTUAL_DumpView( FILE_VIEW *view )
165 char *addr = view->base;
166 BYTE prot = view->prot[0];
168 DPRINTF( "View: %p - %p", addr, addr + view->size - 1 );
169 if (view->flags & VFLAG_SYSTEM)
170 DPRINTF( " (system)\n" );
171 else if (view->flags & VFLAG_VALLOC)
172 DPRINTF( " (valloc)\n" );
173 else if (view->mapping)
174 DPRINTF( " %p\n", view->mapping );
176 DPRINTF( " (anonymous)\n");
178 for (count = i = 1; i < view->size >> page_shift; i++, count++)
180 if (view->prot[i] == prot) continue;
181 DPRINTF( " %p - %p %s\n",
182 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
183 addr += (count << page_shift);
184 prot = view->prot[i];
188 DPRINTF( " %p - %p %s\n",
189 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
193 /***********************************************************************
196 void VIRTUAL_Dump(void)
200 DPRINTF( "\nDump of all virtual memory views:\n\n" );
201 RtlEnterCriticalSection(&csVirtual);
202 LIST_FOR_EACH( ptr, &views_list )
204 VIRTUAL_DumpView( LIST_ENTRY( ptr, struct file_view, entry ) );
206 RtlLeaveCriticalSection(&csVirtual);
210 /***********************************************************************
213 * Find the view containing a given address. The csVirtual section must be held by caller.
219 static struct file_view *VIRTUAL_FindView( const void *addr ) /* [in] Address */
223 LIST_FOR_EACH( ptr, &views_list )
225 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
226 if (view->base > addr) break;
227 if ((const char*)view->base + view->size > (const char*)addr) return view;
233 /***********************************************************************
236 * Find the first view overlapping at least part of the specified range.
237 * The csVirtual section must be held by caller.
239 static struct file_view *find_view_range( const void *addr, size_t size )
243 LIST_FOR_EACH( ptr, &views_list )
245 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
246 if ((const char *)view->base >= (const char *)addr + size) break;
247 if ((const char *)view->base + view->size > (const char *)addr) return view;
253 /***********************************************************************
256 * Add a reserved area to the list maintained by libwine.
257 * The csVirtual section must be held by caller.
259 static void add_reserved_area( void *addr, size_t size )
261 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
263 if (addr < user_space_limit)
265 /* unmap the part of the area that is below the limit */
266 assert( (char *)addr + size > (char *)user_space_limit );
267 munmap( addr, (char *)user_space_limit - (char *)addr );
268 size -= (char *)user_space_limit - (char *)addr;
269 addr = user_space_limit;
271 /* blow away existing mappings */
272 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
273 wine_mmap_add_reserved_area( addr, size );
277 /***********************************************************************
278 * remove_reserved_area
280 * Remove a reserved area from the list maintained by libwine.
281 * The csVirtual section must be held by caller.
283 static void remove_reserved_area( void *addr, size_t size )
287 LIST_FOR_EACH( ptr, &views_list )
289 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
290 if ((char *)view->base >= (char *)addr + size) break;
291 if ((char *)view->base + view->size <= (char *)addr) continue;
292 /* now we have an overlapping view */
293 if (view->base > addr)
295 wine_mmap_remove_reserved_area( addr, (char *)view->base - (char *)addr, TRUE );
296 size -= (char *)view->base - (char *)addr;
299 if ((char *)view->base + view->size >= (char *)addr + size)
301 /* view covers all the remaining area */
302 wine_mmap_remove_reserved_area( addr, size, FALSE );
306 else /* view covers only part of the area */
308 wine_mmap_remove_reserved_area( addr, (char *)view->base + view->size - (char *)addr, FALSE );
309 size -= (char *)view->base + view->size - (char *)addr;
310 addr = (char *)view->base + view->size;
313 /* remove remaining space */
314 if (size) wine_mmap_remove_reserved_area( addr, size, TRUE );
318 /***********************************************************************
321 * Check if an address range goes beyond a given limit.
323 static inline int is_beyond_limit( void *addr, size_t size, void *limit )
325 return (limit && (addr >= limit || (char *)addr + size > (char *)limit));
329 /***********************************************************************
332 * Unmap an area, or simply replace it by an empty mapping if it is
333 * in a reserved area. The csVirtual section must be held by caller.
335 static inline void unmap_area( void *addr, size_t size )
337 if (wine_mmap_is_in_reserved_area( addr, size ))
338 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
340 munmap( addr, size );
344 /***********************************************************************
347 * Deletes a view. The csVirtual section must be held by caller.
349 static void delete_view( struct file_view *view ) /* [in] View */
351 if (!(view->flags & VFLAG_SYSTEM)) unmap_area( view->base, view->size );
352 list_remove( &view->entry );
353 if (view->mapping) NtClose( view->mapping );
358 /***********************************************************************
361 * Create a view. The csVirtual section must be held by caller.
363 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, BYTE vprot )
365 struct file_view *view;
368 assert( !((unsigned int)base & page_mask) );
369 assert( !(size & page_mask) );
371 /* Create the view structure */
373 if (!(view = malloc( sizeof(*view) + (size >> page_shift) - 1 ))) return STATUS_NO_MEMORY;
379 view->protect = vprot;
380 view->handlerProc = NULL;
381 memset( view->prot, vprot, size >> page_shift );
383 /* Insert it in the linked list */
385 LIST_FOR_EACH( ptr, &views_list )
387 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
388 if (next->base > base) break;
390 list_add_before( ptr, &view->entry );
392 /* Check for overlapping views. This can happen if the previous view
393 * was a system view that got unmapped behind our back. In that case
394 * we recover by simply deleting it. */
396 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
398 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
399 if ((char *)prev->base + prev->size > (char *)base)
401 TRACE( "overlapping prev view %p-%p for %p-%p\n",
402 prev->base, (char *)prev->base + prev->size,
403 base, (char *)base + view->size );
404 assert( prev->flags & VFLAG_SYSTEM );
408 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
410 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
411 if ((char *)base + view->size > (char *)next->base)
413 TRACE( "overlapping next view %p-%p for %p-%p\n",
414 next->base, (char *)next->base + next->size,
415 base, (char *)base + view->size );
416 assert( next->flags & VFLAG_SYSTEM );
422 VIRTUAL_DEBUG_DUMP_VIEW( view );
423 return STATUS_SUCCESS;
427 /***********************************************************************
428 * VIRTUAL_GetUnixProt
430 * Convert page protections to protection for mmap/mprotect.
432 static int VIRTUAL_GetUnixProt( BYTE vprot )
435 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
437 if (vprot & VPROT_READ) prot |= PROT_READ;
438 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
439 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
440 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
446 /***********************************************************************
447 * VIRTUAL_GetWin32Prot
449 * Convert page protections to Win32 flags.
454 static void VIRTUAL_GetWin32Prot(
455 BYTE vprot, /* [in] Page protection flags */
456 DWORD *protect, /* [out] Location to store Win32 protection flags */
457 DWORD *state ) /* [out] Location to store mem state flag */
460 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
461 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
462 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
464 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
467 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
471 /***********************************************************************
474 * Build page protections from Win32 flags.
477 * Value of page protection flags
479 static BYTE VIRTUAL_GetProt( DWORD protect ) /* [in] Win32 protection flags */
483 switch(protect & 0xff)
489 vprot = VPROT_READ | VPROT_WRITE;
492 /* MSDN CreateFileMapping() states that if PAGE_WRITECOPY is given,
493 * that the hFile must have been opened with GENERIC_READ and
494 * GENERIC_WRITE access. This is WRONG as tests show that you
495 * only need GENERIC_READ access (at least for Win9x,
496 * FIXME: what about NT?). Thus, we don't put VPROT_WRITE in
497 * PAGE_WRITECOPY and PAGE_EXECUTE_WRITECOPY.
499 vprot = VPROT_READ | VPROT_WRITECOPY;
504 case PAGE_EXECUTE_READ:
505 vprot = VPROT_EXEC | VPROT_READ;
507 case PAGE_EXECUTE_READWRITE:
508 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
510 case PAGE_EXECUTE_WRITECOPY:
511 /* See comment for PAGE_WRITECOPY above */
512 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
519 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
520 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
525 /***********************************************************************
528 * Change the protection of a range of pages.
534 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
535 void *base, /* [in] Starting address */
536 UINT size, /* [in] Size in bytes */
537 BYTE vprot ) /* [in] Protections to use */
540 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
542 if (mprotect( base, size, VIRTUAL_GetUnixProt(vprot) ))
543 return FALSE; /* FIXME: last error */
545 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
546 vprot, size >> page_shift );
547 VIRTUAL_DEBUG_DUMP_VIEW( view );
552 /***********************************************************************
555 * Create a view and mmap the corresponding memory area.
556 * The csVirtual section must be held by caller.
558 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, BYTE vprot )
565 if (is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
566 return STATUS_WORKING_SET_LIMIT_RANGE;
568 switch (wine_mmap_is_in_reserved_area( base, size ))
570 case -1: /* partially in a reserved area */
571 return STATUS_CONFLICTING_ADDRESSES;
573 case 0: /* not in a reserved area, do a normal allocation */
574 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
576 if (errno == ENOMEM) return STATUS_NO_MEMORY;
577 return STATUS_INVALID_PARAMETER;
581 /* We couldn't get the address we wanted */
582 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
583 else munmap( ptr, size );
584 return STATUS_CONFLICTING_ADDRESSES;
589 case 1: /* in a reserved area, make sure the address is available */
590 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
591 /* replace the reserved area by our mapping */
592 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
593 return STATUS_INVALID_PARAMETER;
599 size_t view_size = size + granularity_mask + 1;
603 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
605 if (errno == ENOMEM) return STATUS_NO_MEMORY;
606 return STATUS_INVALID_PARAMETER;
608 /* if we got something beyond the user limit, unmap it and retry */
609 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
613 /* Release the extra memory while keeping the range
614 * starting on the granularity boundary. */
615 if ((unsigned int)ptr & granularity_mask)
617 unsigned int extra = granularity_mask + 1 - ((unsigned int)ptr & granularity_mask);
618 munmap( ptr, extra );
619 ptr = (char *)ptr + extra;
622 if (view_size > size)
623 munmap( (char *)ptr + size, view_size - size );
626 status = create_view( view_ret, ptr, size, vprot );
627 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
632 /***********************************************************************
635 * Linux kernels before 2.4.x can support non page-aligned offsets, as
636 * long as the offset is aligned to the filesystem block size. This is
637 * a big performance gain so we want to take advantage of it.
639 * However, when we use 64-bit file support this doesn't work because
640 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
641 * in that it rounds unaligned offsets down to a page boundary. For
642 * these reasons we do a direct system call here.
644 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
645 unsigned int flags, int fd, off_t offset )
647 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
648 if (!(offset >> 32) && (offset & page_mask))
663 args.length = length;
667 args.offset = offset;
669 __asm__ __volatile__("push %%ebx\n\t"
674 : "0" (90), /* SYS_mmap */
677 if (ret < 0 && ret > -4096)
685 return mmap( addr, length, prot, flags, fd, offset );
689 /***********************************************************************
692 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
693 * The csVirtual section must be held by caller.
695 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
696 off_t offset, BYTE vprot, BOOL removable )
699 int prot = VIRTUAL_GetUnixProt( vprot );
700 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
702 assert( start < view->size );
703 assert( start + size <= view->size );
705 /* only try mmap if media is not removable (or if we require write access) */
706 if (!removable || shared_write)
708 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
710 if (unaligned_mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
713 /* mmap() failed; if this is because the file offset is not */
714 /* page-aligned (EINVAL), or because the underlying filesystem */
715 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
716 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
717 if (shared_write) return FILE_GetNtStatus(); /* we cannot fake shared write mappings */
720 /* Reserve the memory with an anonymous mmap */
721 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
722 if (ptr == (void *)-1) return FILE_GetNtStatus();
723 /* Now read in the file */
724 pread( fd, ptr, size, offset );
725 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
727 memset( view->prot + (start >> page_shift), vprot, size >> page_shift );
728 return STATUS_SUCCESS;
732 /***********************************************************************
735 * Decommit some pages of a given view.
736 * The csVirtual section must be held by caller.
738 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
740 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
742 BYTE *p = view->prot + (start >> page_shift);
744 while (size--) *p++ &= ~VPROT_COMMITTED;
745 return STATUS_SUCCESS;
747 return FILE_GetNtStatus();
751 /***********************************************************************
754 * Apply the relocations to a mapped PE image
756 static int do_relocations( char *base, const IMAGE_DATA_DIRECTORY *dir,
757 int delta, DWORD total_size )
759 IMAGE_BASE_RELOCATION *rel;
761 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
762 base - delta, base - delta + total_size, base, base + total_size );
764 for (rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
765 ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
766 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock) )
768 char *page = base + rel->VirtualAddress;
769 WORD *TypeOffset = (WORD *)(rel + 1);
770 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
772 if (!count) continue;
775 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
776 page > base + total_size)
778 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
779 rel, rel->VirtualAddress, rel->SizeOfBlock,
780 base, dir->VirtualAddress, dir->Size );
784 TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
786 /* patching in reverse order */
787 for (i = 0 ; i < count; i++)
789 int offset = TypeOffset[i] & 0xFFF;
790 int type = TypeOffset[i] >> 12;
793 case IMAGE_REL_BASED_ABSOLUTE:
795 case IMAGE_REL_BASED_HIGH:
796 *(short*)(page+offset) += HIWORD(delta);
798 case IMAGE_REL_BASED_LOW:
799 *(short*)(page+offset) += LOWORD(delta);
801 case IMAGE_REL_BASED_HIGHLOW:
802 *(int*)(page+offset) += delta;
803 /* FIXME: if this is an exported address, fire up enhanced logic */
806 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
815 /***********************************************************************
818 * Map an executable (PE format) image into memory.
820 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, DWORD total_size,
821 DWORD header_size, int shared_fd, BOOL removable, PVOID *addr_ptr )
823 IMAGE_DOS_HEADER *dos;
824 IMAGE_NT_HEADERS *nt;
825 IMAGE_SECTION_HEADER *sec;
826 IMAGE_DATA_DIRECTORY *imports;
827 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
830 struct file_view *view = NULL;
833 /* zero-map the whole range */
835 RtlEnterCriticalSection( &csVirtual );
837 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
838 status = map_view( &view, base, total_size,
839 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
841 if (status == STATUS_CONFLICTING_ADDRESSES)
842 status = map_view( &view, NULL, total_size,
843 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
845 if (status != STATUS_SUCCESS) goto error;
848 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
852 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
853 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ,
854 removable ) != STATUS_SUCCESS) goto error;
855 dos = (IMAGE_DOS_HEADER *)ptr;
856 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
857 if ((char *)(nt + 1) > ptr + header_size) goto error;
859 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
860 if ((char *)(sec + nt->FileHeader.NumberOfSections) > ptr + header_size) goto error;
862 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
863 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
865 /* check the architecture */
867 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
869 MESSAGE("Trying to load PE image for unsupported architecture (");
870 switch (nt->FileHeader.Machine)
872 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
873 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
874 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
875 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
876 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
877 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
878 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
879 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
885 /* check for non page-aligned binary */
887 if (nt->OptionalHeader.SectionAlignment <= page_mask)
889 /* unaligned sections, this happens for native subsystem binaries */
890 /* in that case Windows simply maps in the whole file */
892 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
893 removable ) != STATUS_SUCCESS) goto error;
895 /* check that all sections are loaded at the right offset */
896 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
898 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
899 goto error; /* Windows refuses to load in that case too */
902 /* set the image protections */
903 VIRTUAL_SetProt( view, ptr, total_size,
904 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
906 /* perform relocations if necessary */
907 /* FIXME: not 100% compatible, Windows doesn't do this for non page-aligned binaries */
910 const IMAGE_DATA_DIRECTORY *relocs;
911 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
912 if (relocs->VirtualAddress && relocs->Size)
913 do_relocations( ptr, relocs, ptr - base, total_size );
920 /* map all the sections */
922 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
926 /* a few sanity checks */
927 size = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
928 if (sec->VirtualAddress > total_size || size > total_size || size < sec->VirtualAddress)
930 ERR_(module)( "Section %.8s too large (%lx+%lx/%lx)\n",
931 sec->Name, sec->VirtualAddress, sec->Misc.VirtualSize, total_size );
935 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
936 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
938 size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
939 TRACE_(module)( "mapping shared section %.8s at %p off %lx (%x) size %lx (%lx) flags %lx\n",
940 sec->Name, ptr + sec->VirtualAddress,
941 sec->PointerToRawData, (int)pos, sec->SizeOfRawData,
942 size, sec->Characteristics );
943 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, size, pos,
944 VPROT_COMMITTED | VPROT_READ | PROT_WRITE,
945 FALSE ) != STATUS_SUCCESS)
947 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
951 /* check if the import directory falls inside this section */
952 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
953 imports->VirtualAddress < sec->VirtualAddress + size)
955 UINT_PTR base = imports->VirtualAddress & ~page_mask;
956 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
957 if (end > sec->VirtualAddress + size) end = sec->VirtualAddress + size;
959 map_file_into_view( view, shared_fd, base, end - base,
960 pos + (base - sec->VirtualAddress),
961 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
968 TRACE_(module)( "mapping section %.8s at %p off %lx size %lx flags %lx\n",
969 sec->Name, ptr + sec->VirtualAddress,
970 sec->PointerToRawData, sec->SizeOfRawData,
971 sec->Characteristics );
973 if ((sec->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) &&
974 !(sec->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)) continue;
975 if (!sec->PointerToRawData || !sec->SizeOfRawData) continue;
977 /* Note: if the section is not aligned properly map_file_into_view will magically
978 * fall back to read(), so we don't need to check anything here.
980 if (map_file_into_view( view, fd, sec->VirtualAddress, sec->SizeOfRawData, sec->PointerToRawData,
981 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
982 removable ) != STATUS_SUCCESS)
984 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
988 if ((sec->SizeOfRawData < sec->Misc.VirtualSize) && (sec->SizeOfRawData & page_mask))
990 DWORD end = ROUND_SIZE( 0, sec->SizeOfRawData );
991 if (end > sec->Misc.VirtualSize) end = sec->Misc.VirtualSize;
992 TRACE_(module)("clearing %p - %p\n",
993 ptr + sec->VirtualAddress + sec->SizeOfRawData,
994 ptr + sec->VirtualAddress + end );
995 memset( ptr + sec->VirtualAddress + sec->SizeOfRawData, 0,
996 end - sec->SizeOfRawData );
1001 /* perform base relocation, if necessary */
1005 const IMAGE_DATA_DIRECTORY *relocs;
1007 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1008 if (!relocs->VirtualAddress || !relocs->Size)
1010 if (nt->OptionalHeader.ImageBase == 0x400000) {
1011 ERR("Image was mapped at %p: standard load address for a Win32 program (0x00400000) not available\n", ptr);
1012 ERR("Do you have exec-shield or prelink active?\n");
1014 ERR( "FATAL: Need to relocate module from addr %lx, but there are no relocation records\n",
1015 nt->OptionalHeader.ImageBase );
1019 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
1020 * really make sure that the *new* base address is also > 2GB.
1021 * Some DLLs really check the MSB of the module handle :-/
1023 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
1024 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
1026 if (!do_relocations( ptr, relocs, ptr - base, total_size ))
1032 /* set the image protections */
1034 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1035 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1037 DWORD size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1038 BYTE vprot = VPROT_COMMITTED;
1039 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1040 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
1041 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1042 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
1046 if (!removable) /* don't keep handle open on removable media */
1047 NtDuplicateObject( GetCurrentProcess(), hmapping,
1048 GetCurrentProcess(), &view->mapping,
1049 0, 0, DUPLICATE_SAME_ACCESS );
1051 RtlLeaveCriticalSection( &csVirtual );
1054 return STATUS_SUCCESS;
1057 if (view) delete_view( view );
1058 RtlLeaveCriticalSection( &csVirtual );
1063 /***********************************************************************
1064 * is_current_process
1066 * Check whether a process handle is for the current process.
1068 BOOL is_current_process( HANDLE handle )
1072 if (handle == GetCurrentProcess()) return TRUE;
1073 SERVER_START_REQ( get_process_info )
1075 req->handle = handle;
1076 if (!wine_server_call( req ))
1077 ret = ((DWORD)reply->pid == GetCurrentProcessId());
1084 /***********************************************************************
1087 void virtual_init(void)
1090 page_size = getpagesize();
1091 page_mask = page_size - 1;
1092 /* Make sure we have a power of 2 */
1093 assert( !(page_size & page_mask) );
1095 while ((1 << page_shift) != page_size) page_shift++;
1096 #endif /* page_mask */
1100 /***********************************************************************
1101 * VIRTUAL_SetFaultHandler
1103 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
1108 RtlEnterCriticalSection( &csVirtual );
1109 if ((view = VIRTUAL_FindView( addr )))
1111 view->handlerProc = proc;
1112 view->handlerArg = arg;
1115 RtlLeaveCriticalSection( &csVirtual );
1119 /***********************************************************************
1120 * VIRTUAL_HandleFault
1122 DWORD VIRTUAL_HandleFault( LPCVOID addr )
1125 DWORD ret = EXCEPTION_ACCESS_VIOLATION;
1127 RtlEnterCriticalSection( &csVirtual );
1128 if ((view = VIRTUAL_FindView( addr )))
1130 if (view->handlerProc)
1132 HANDLERPROC proc = view->handlerProc;
1133 void *arg = view->handlerArg;
1134 RtlLeaveCriticalSection( &csVirtual );
1135 if (proc( arg, addr )) ret = 0; /* handled */
1140 BYTE vprot = view->prot[((const char *)addr - (const char *)view->base) >> page_shift];
1141 void *page = (void *)((UINT_PTR)addr & ~page_mask);
1142 char *stack = NtCurrentTeb()->Tib.StackLimit;
1143 if (vprot & VPROT_GUARD)
1145 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
1146 ret = STATUS_GUARD_PAGE_VIOLATION;
1148 /* is it inside the stack guard page? */
1149 if (((const char *)addr >= stack) && ((const char *)addr < stack + (page_mask+1)))
1150 ret = STATUS_STACK_OVERFLOW;
1153 RtlLeaveCriticalSection( &csVirtual );
1157 /***********************************************************************
1158 * VIRTUAL_HasMapping
1160 * Check if the specified view has an associated file mapping.
1162 BOOL VIRTUAL_HasMapping( LPCVOID addr )
1167 RtlEnterCriticalSection( &csVirtual );
1168 if ((view = VIRTUAL_FindView( addr ))) ret = (view->mapping != 0);
1169 RtlLeaveCriticalSection( &csVirtual );
1174 /***********************************************************************
1175 * VIRTUAL_UseLargeAddressSpace
1177 * Increase the address space size for apps that support it.
1179 void VIRTUAL_UseLargeAddressSpace(void)
1181 if (user_space_limit >= ADDRESS_SPACE_LIMIT) return;
1182 RtlEnterCriticalSection( &csVirtual );
1183 remove_reserved_area( user_space_limit, (char *)ADDRESS_SPACE_LIMIT - (char *)user_space_limit );
1184 user_space_limit = ADDRESS_SPACE_LIMIT;
1185 RtlLeaveCriticalSection( &csVirtual );
1189 /***********************************************************************
1190 * NtAllocateVirtualMemory (NTDLL.@)
1191 * ZwAllocateVirtualMemory (NTDLL.@)
1193 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1194 ULONG *size_ptr, ULONG type, ULONG protect )
1198 DWORD size = *size_ptr;
1199 NTSTATUS status = STATUS_SUCCESS;
1200 struct file_view *view;
1202 TRACE("%p %p %08lx %lx %08lx\n", process, *ret, size, type, protect );
1204 if (!size) return STATUS_INVALID_PARAMETER;
1206 if (!is_current_process( process ))
1208 ERR("Unsupported on other process\n");
1209 return STATUS_ACCESS_DENIED;
1212 /* Round parameters to a page boundary */
1214 if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
1218 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1219 base = ROUND_ADDR( *ret, granularity_mask );
1221 base = ROUND_ADDR( *ret, page_mask );
1222 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1224 /* disallow low 64k, wrap-around and kernel space */
1225 if (((char *)base <= (char *)granularity_mask) ||
1226 ((char *)base + size < (char *)base) ||
1227 is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
1228 return STATUS_INVALID_PARAMETER;
1233 size = (size + page_mask) & ~page_mask;
1236 if (type & MEM_TOP_DOWN) {
1237 /* FIXME: MEM_TOP_DOWN allocates the largest possible address. */
1238 WARN("MEM_TOP_DOWN ignored\n");
1239 type &= ~MEM_TOP_DOWN;
1243 WARN("zero_bits %lu ignored\n", zero_bits);
1245 /* Compute the alloc type flags */
1247 if (!(type & MEM_SYSTEM))
1249 if (!(type & (MEM_COMMIT | MEM_RESERVE)) || (type & ~(MEM_COMMIT | MEM_RESERVE)))
1251 WARN("called with wrong alloc type flags (%08lx) !\n", type);
1252 return STATUS_INVALID_PARAMETER;
1255 vprot = VIRTUAL_GetProt( protect );
1256 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1258 /* Reserve the memory */
1260 RtlEnterCriticalSection( &csVirtual );
1262 if (type & MEM_SYSTEM)
1264 if (type & MEM_IMAGE) vprot |= VPROT_IMAGE;
1265 status = create_view( &view, base, size, vprot | VPROT_COMMITTED );
1266 if (status == STATUS_SUCCESS)
1268 view->flags |= VFLAG_VALLOC | VFLAG_SYSTEM;
1272 else if ((type & MEM_RESERVE) || !base)
1274 status = map_view( &view, base, size, vprot );
1275 if (status == STATUS_SUCCESS)
1277 view->flags |= VFLAG_VALLOC;
1281 else /* commit the pages */
1283 if (!(view = VIRTUAL_FindView( base )) ||
1284 ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
1285 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1288 RtlLeaveCriticalSection( &csVirtual );
1290 if (status == STATUS_SUCCESS)
1299 /***********************************************************************
1300 * NtFreeVirtualMemory (NTDLL.@)
1301 * ZwFreeVirtualMemory (NTDLL.@)
1303 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr, ULONG type )
1307 NTSTATUS status = STATUS_SUCCESS;
1308 LPVOID addr = *addr_ptr;
1309 DWORD size = *size_ptr;
1311 TRACE("%p %p %08lx %lx\n", process, addr, size, type );
1313 if (!is_current_process( process ))
1315 ERR("Unsupported on other process\n");
1316 return STATUS_ACCESS_DENIED;
1319 /* Fix the parameters */
1321 size = ROUND_SIZE( addr, size );
1322 base = ROUND_ADDR( addr, page_mask );
1324 RtlEnterCriticalSection(&csVirtual);
1326 if (!(view = VIRTUAL_FindView( base )) ||
1327 (base + size > (char *)view->base + view->size) ||
1328 !(view->flags & VFLAG_VALLOC))
1330 status = STATUS_INVALID_PARAMETER;
1332 else if (type & MEM_SYSTEM)
1334 /* return the values that the caller should use to unmap the area */
1335 *addr_ptr = view->base;
1336 *size_ptr = view->size;
1337 view->flags |= VFLAG_SYSTEM;
1338 delete_view( view );
1340 else if (type == MEM_RELEASE)
1342 /* Free the pages */
1344 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1347 delete_view( view );
1352 else if (type == MEM_DECOMMIT)
1354 status = decommit_pages( view, base - (char *)view->base, size );
1355 if (status == STATUS_SUCCESS)
1363 WARN("called with wrong free type flags (%08lx) !\n", type);
1364 status = STATUS_INVALID_PARAMETER;
1367 RtlLeaveCriticalSection(&csVirtual);
1372 /***********************************************************************
1373 * NtProtectVirtualMemory (NTDLL.@)
1374 * ZwProtectVirtualMemory (NTDLL.@)
1376 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr,
1377 ULONG new_prot, ULONG *old_prot )
1380 NTSTATUS status = STATUS_SUCCESS;
1384 DWORD prot, size = *size_ptr;
1385 LPVOID addr = *addr_ptr;
1387 TRACE("%p %p %08lx %08lx\n", process, addr, size, new_prot );
1389 if (!is_current_process( process ))
1391 ERR("Unsupported on other process\n");
1392 return STATUS_ACCESS_DENIED;
1395 /* Fix the parameters */
1397 size = ROUND_SIZE( addr, size );
1398 base = ROUND_ADDR( addr, page_mask );
1400 RtlEnterCriticalSection( &csVirtual );
1402 if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1404 status = STATUS_INVALID_PARAMETER;
1408 /* Make sure all the pages are committed */
1410 p = view->prot + ((base - (char *)view->base) >> page_shift);
1411 VIRTUAL_GetWin32Prot( *p, &prot, NULL );
1412 for (i = size >> page_shift; i; i--, p++)
1414 if (!(*p & VPROT_COMMITTED))
1416 status = STATUS_NOT_COMMITTED;
1422 if (old_prot) *old_prot = prot;
1423 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1424 if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1427 RtlLeaveCriticalSection( &csVirtual );
1429 if (status == STATUS_SUCCESS)
1438 /***********************************************************************
1439 * NtQueryVirtualMemory (NTDLL.@)
1440 * ZwQueryVirtualMemory (NTDLL.@)
1442 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1443 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1444 ULONG len, ULONG *res_len )
1447 char *base, *alloc_base = 0;
1450 MEMORY_BASIC_INFORMATION *info = buffer;
1452 if (info_class != MemoryBasicInformation) return STATUS_INVALID_INFO_CLASS;
1453 if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1454 return STATUS_WORKING_SET_LIMIT_RANGE;
1456 if (!is_current_process( process ))
1458 ERR("Unsupported on other process\n");
1459 return STATUS_ACCESS_DENIED;
1462 base = ROUND_ADDR( addr, page_mask );
1464 /* Find the view containing the address */
1466 RtlEnterCriticalSection(&csVirtual);
1467 ptr = list_head( &views_list );
1472 /* make the address space end at the user limit, except if
1473 * the last view was mapped beyond that */
1474 if (alloc_base < (char *)user_space_limit)
1476 if (user_space_limit && base >= (char *)user_space_limit)
1478 RtlLeaveCriticalSection( &csVirtual );
1479 return STATUS_WORKING_SET_LIMIT_RANGE;
1481 size = (char *)user_space_limit - alloc_base;
1483 else size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1487 view = LIST_ENTRY( ptr, struct file_view, entry );
1488 if ((char *)view->base > base)
1490 size = (char *)view->base - alloc_base;
1494 if ((char *)view->base + view->size > base)
1496 alloc_base = view->base;
1500 alloc_base = (char *)view->base + view->size;
1501 ptr = list_next( &views_list, ptr );
1504 /* Fill the info structure */
1508 info->State = MEM_FREE;
1510 info->AllocationProtect = 0;
1515 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1516 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
1517 for (size = base - alloc_base; size < view->size; size += page_mask+1)
1518 if (view->prot[size >> page_shift] != vprot) break;
1519 VIRTUAL_GetWin32Prot( view->protect, &info->AllocationProtect, NULL );
1520 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1521 else if (view->flags & VFLAG_VALLOC) info->Type = MEM_PRIVATE;
1522 else info->Type = MEM_MAPPED;
1524 RtlLeaveCriticalSection(&csVirtual);
1526 info->BaseAddress = (LPVOID)base;
1527 info->AllocationBase = (LPVOID)alloc_base;
1528 info->RegionSize = size - (base - alloc_base);
1529 if (res_len) *res_len = sizeof(*info);
1530 return STATUS_SUCCESS;
1534 /***********************************************************************
1535 * NtLockVirtualMemory (NTDLL.@)
1536 * ZwLockVirtualMemory (NTDLL.@)
1538 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1540 if (!is_current_process( process ))
1542 ERR("Unsupported on other process\n");
1543 return STATUS_ACCESS_DENIED;
1545 return STATUS_SUCCESS;
1549 /***********************************************************************
1550 * NtUnlockVirtualMemory (NTDLL.@)
1551 * ZwUnlockVirtualMemory (NTDLL.@)
1553 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1555 if (!is_current_process( process ))
1557 ERR("Unsupported on other process\n");
1558 return STATUS_ACCESS_DENIED;
1560 return STATUS_SUCCESS;
1564 /***********************************************************************
1565 * NtCreateSection (NTDLL.@)
1566 * ZwCreateSection (NTDLL.@)
1568 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1569 const LARGE_INTEGER *size, ULONG protect,
1570 ULONG sec_flags, HANDLE file )
1574 DWORD len = attr->ObjectName ? attr->ObjectName->Length : 0;
1576 /* Check parameters */
1578 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1580 vprot = VIRTUAL_GetProt( protect );
1581 if (sec_flags & SEC_RESERVE)
1583 if (file) return STATUS_INVALID_PARAMETER;
1585 else vprot |= VPROT_COMMITTED;
1586 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1587 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
1589 /* Create the server object */
1591 SERVER_START_REQ( create_mapping )
1593 req->file_handle = file;
1594 req->size_high = size ? size->u.HighPart : 0;
1595 req->size_low = size ? size->u.LowPart : 0;
1596 req->protect = vprot;
1597 req->access = access;
1598 req->inherit = (attr->Attributes & OBJ_INHERIT) != 0;
1599 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
1600 ret = wine_server_call( req );
1601 *handle = reply->handle;
1608 /***********************************************************************
1609 * NtOpenSection (NTDLL.@)
1610 * ZwOpenSection (NTDLL.@)
1612 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1615 DWORD len = attr->ObjectName->Length;
1617 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1619 SERVER_START_REQ( open_mapping )
1621 req->access = access;
1622 req->inherit = (attr->Attributes & OBJ_INHERIT) != 0;
1623 wine_server_add_data( req, attr->ObjectName->Buffer, len );
1624 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
1631 /***********************************************************************
1632 * NtMapViewOfSection (NTDLL.@)
1633 * ZwMapViewOfSection (NTDLL.@)
1635 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
1636 ULONG commit_size, const LARGE_INTEGER *offset, ULONG *size_ptr,
1637 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
1640 FILE_FS_DEVICE_INFORMATION device_info;
1643 int unix_handle = -1;
1646 struct file_view *view;
1647 DWORD size_low, size_high, header_size, shared_size;
1649 BOOL removable = FALSE;
1651 TRACE("handle=%p process=%p addr=%p off=%lx%08lx size=%x access=%lx\n",
1652 handle, process, *addr_ptr, offset->u.HighPart, offset->u.LowPart, size, protect );
1654 if (!is_current_process( process ))
1656 ERR("Unsupported on other process\n");
1657 return STATUS_ACCESS_DENIED;
1660 /* Check parameters */
1662 if ((offset->u.LowPart & granularity_mask) ||
1663 (*addr_ptr && ((UINT_PTR)*addr_ptr & granularity_mask)))
1664 return STATUS_INVALID_PARAMETER;
1666 SERVER_START_REQ( get_mapping_info )
1668 req->handle = handle;
1669 res = wine_server_call( req );
1670 prot = reply->protect;
1672 size_low = reply->size_low;
1673 size_high = reply->size_high;
1674 header_size = reply->header_size;
1675 shared_file = reply->shared_file;
1676 shared_size = reply->shared_size;
1679 if (res) return res;
1681 if ((res = wine_server_handle_to_fd( handle, 0, &unix_handle, NULL ))) return res;
1683 if (NtQueryVolumeInformationFile( handle, &io, &device_info, sizeof(device_info),
1684 FileFsDeviceInformation ) == STATUS_SUCCESS)
1685 removable = device_info.Characteristics & FILE_REMOVABLE_MEDIA;
1687 if (prot & VPROT_IMAGE)
1693 if ((res = wine_server_handle_to_fd( shared_file, GENERIC_READ, &shared_fd,
1695 res = map_image( handle, unix_handle, base, size_low, header_size,
1696 shared_fd, removable, addr_ptr );
1697 wine_server_release_fd( shared_file, shared_fd );
1698 NtClose( shared_file );
1702 res = map_image( handle, unix_handle, base, size_low, header_size,
1703 -1, removable, addr_ptr );
1705 wine_server_release_fd( handle, unix_handle );
1706 if (!res) *size_ptr = size_low;
1711 ERR("Sizes larger than 4Gb not supported\n");
1713 if ((offset->u.LowPart >= size_low) ||
1714 (*size_ptr > size_low - offset->u.LowPart))
1716 res = STATUS_INVALID_PARAMETER;
1719 if (*size_ptr) size = ROUND_SIZE( offset->u.LowPart, *size_ptr );
1720 else size = size_low - offset->u.LowPart;
1726 case PAGE_READWRITE:
1727 case PAGE_EXECUTE_READWRITE:
1728 if (!(prot & VPROT_WRITE))
1730 res = STATUS_INVALID_PARAMETER;
1736 case PAGE_WRITECOPY:
1738 case PAGE_EXECUTE_READ:
1739 case PAGE_EXECUTE_WRITECOPY:
1740 if (prot & VPROT_READ) break;
1743 res = STATUS_INVALID_PARAMETER;
1747 /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1748 * which has a view of this mapping commits some pages, they will
1749 * appear commited in all other processes, which have the same
1750 * view created. Since we don`t support this yet, we create the
1751 * whole mapping commited.
1753 prot |= VPROT_COMMITTED;
1755 /* Reserve a properly aligned area */
1757 RtlEnterCriticalSection( &csVirtual );
1759 res = map_view( &view, *addr_ptr, size, prot );
1762 RtlLeaveCriticalSection( &csVirtual );
1768 TRACE("handle=%p size=%x offset=%lx%08lx\n",
1769 handle, size, offset->u.HighPart, offset->u.LowPart );
1771 res = map_file_into_view( view, unix_handle, 0, size, offset->QuadPart, prot, removable );
1772 if (res == STATUS_SUCCESS)
1774 if (!removable) /* don't keep handle open on removable media */
1775 NtDuplicateObject( GetCurrentProcess(), handle,
1776 GetCurrentProcess(), &view->mapping,
1777 0, 0, DUPLICATE_SAME_ACCESS );
1779 *addr_ptr = view->base;
1784 ERR( "map_file_into_view %p %x %lx%08lx failed\n",
1785 view->base, size, offset->u.HighPart, offset->u.LowPart );
1786 delete_view( view );
1789 RtlLeaveCriticalSection( &csVirtual );
1792 wine_server_release_fd( handle, unix_handle );
1797 /***********************************************************************
1798 * NtUnmapViewOfSection (NTDLL.@)
1799 * ZwUnmapViewOfSection (NTDLL.@)
1801 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
1804 NTSTATUS status = STATUS_INVALID_PARAMETER;
1805 void *base = ROUND_ADDR( addr, page_mask );
1807 if (!is_current_process( process ))
1809 ERR("Unsupported on other process\n");
1810 return STATUS_ACCESS_DENIED;
1812 RtlEnterCriticalSection( &csVirtual );
1813 if ((view = VIRTUAL_FindView( base )) && (base == view->base))
1815 delete_view( view );
1816 status = STATUS_SUCCESS;
1818 RtlLeaveCriticalSection( &csVirtual );
1823 /***********************************************************************
1824 * NtFlushVirtualMemory (NTDLL.@)
1825 * ZwFlushVirtualMemory (NTDLL.@)
1827 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
1828 ULONG *size_ptr, ULONG unknown )
1831 NTSTATUS status = STATUS_SUCCESS;
1832 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
1834 if (!is_current_process( process ))
1836 ERR("Unsupported on other process\n");
1837 return STATUS_ACCESS_DENIED;
1839 RtlEnterCriticalSection( &csVirtual );
1840 if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
1843 if (!*size_ptr) *size_ptr = view->size;
1845 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
1847 RtlLeaveCriticalSection( &csVirtual );
1852 /***********************************************************************
1853 * NtReadVirtualMemory (NTDLL.@)
1854 * ZwReadVirtualMemory (NTDLL.@)
1856 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
1857 SIZE_T size, SIZE_T *bytes_read )
1861 SERVER_START_REQ( read_process_memory )
1863 req->handle = process;
1864 req->addr = (void *)addr;
1865 wine_server_set_reply( req, buffer, size );
1866 if ((status = wine_server_call( req ))) size = 0;
1869 if (bytes_read) *bytes_read = size;
1874 /***********************************************************************
1875 * NtWriteVirtualMemory (NTDLL.@)
1876 * ZwWriteVirtualMemory (NTDLL.@)
1878 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
1879 SIZE_T size, SIZE_T *bytes_written )
1881 static const unsigned int zero;
1882 unsigned int first_offset, last_offset, first_mask, last_mask;
1885 if (!size) return STATUS_INVALID_PARAMETER;
1887 /* compute the mask for the first int */
1889 first_offset = (unsigned int)addr % sizeof(int);
1890 memset( &first_mask, 0, first_offset );
1892 /* compute the mask for the last int */
1893 last_offset = (size + first_offset) % sizeof(int);
1895 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1897 SERVER_START_REQ( write_process_memory )
1899 req->handle = process;
1900 req->addr = (char *)addr - first_offset;
1901 req->first_mask = first_mask;
1902 req->last_mask = last_mask;
1903 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1904 wine_server_add_data( req, buffer, size );
1905 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1907 if ((status = wine_server_call( req ))) size = 0;
1910 if (bytes_written) *bytes_written = size;