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>
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_MMAN_H
42 #define NONAMELESSUNION
43 #define NONAMELESSSTRUCT
45 #define WIN32_NO_STATUS
49 #include "wine/library.h"
50 #include "wine/server.h"
51 #include "wine/list.h"
52 #include "wine/debug.h"
53 #include "ntdll_misc.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
56 WINE_DECLARE_DEBUG_CHANNEL(module);
63 #define MAP_NORESERVE 0
67 typedef struct file_view
69 struct list entry; /* Entry in global view list */
70 void *base; /* Base address */
71 size_t size; /* Size in bytes */
72 HANDLE mapping; /* Handle to the file mapping */
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 RTL_CRITICAL_SECTION csVirtual;
106 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
109 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
110 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
112 static RTL_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_size;
125 static UINT_PTR page_mask;
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 static const UINT_PTR granularity_mask = 0xffff; /* Allocation granularity (usually 64k) */
131 #define ROUND_ADDR(addr,mask) \
132 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(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 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
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 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
169 if (view->flags & VFLAG_SYSTEM)
170 TRACE( " (system)\n" );
171 else if (view->flags & VFLAG_VALLOC)
172 TRACE( " (valloc)\n" );
173 else if (view->mapping)
174 TRACE( " %p\n", view->mapping );
176 TRACE( " (anonymous)\n");
178 for (count = i = 1; i < view->size >> page_shift; i++, count++)
180 if (view->prot[i] == prot) continue;
181 TRACE( " %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 TRACE( " %p - %p %s\n",
189 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
193 /***********************************************************************
196 void VIRTUAL_Dump(void)
198 struct file_view *view;
200 TRACE( "Dump of all virtual memory views:\n" );
201 RtlEnterCriticalSection(&csVirtual);
202 LIST_FOR_EACH_ENTRY( view, &views_list, FILE_VIEW, entry )
204 VIRTUAL_DumpView( view );
206 RtlLeaveCriticalSection(&csVirtual);
210 /***********************************************************************
213 * Find the view containing a given address. The csVirtual section must be held by caller.
222 static struct file_view *VIRTUAL_FindView( const void *addr )
224 struct file_view *view;
226 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
228 if (view->base > addr) break;
229 if ((const char*)view->base + view->size > (const char*)addr) return view;
235 /***********************************************************************
238 * Find the first view overlapping at least part of the specified range.
239 * The csVirtual section must be held by caller.
241 static struct file_view *find_view_range( const void *addr, size_t size )
243 struct file_view *view;
245 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
247 if ((const char *)view->base >= (const char *)addr + size) break;
248 if ((const char *)view->base + view->size > (const char *)addr) return view;
254 /***********************************************************************
257 * Add a reserved area to the list maintained by libwine.
258 * The csVirtual section must be held by caller.
260 static void add_reserved_area( void *addr, size_t size )
262 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
264 if (addr < user_space_limit)
266 /* unmap the part of the area that is below the limit */
267 assert( (char *)addr + size > (char *)user_space_limit );
268 munmap( addr, (char *)user_space_limit - (char *)addr );
269 size -= (char *)user_space_limit - (char *)addr;
270 addr = user_space_limit;
272 /* blow away existing mappings */
273 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
274 wine_mmap_add_reserved_area( addr, size );
278 /***********************************************************************
279 * remove_reserved_area
281 * Remove a reserved area from the list maintained by libwine.
282 * The csVirtual section must be held by caller.
284 static void remove_reserved_area( void *addr, size_t size )
286 struct file_view *view;
288 LIST_FOR_EACH_ENTRY( view, &views_list, 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( !((UINT_PTR)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 memset( view->prot, vprot, size >> page_shift );
382 /* Insert it in the linked list */
384 LIST_FOR_EACH( ptr, &views_list )
386 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
387 if (next->base > base) break;
389 list_add_before( ptr, &view->entry );
391 /* Check for overlapping views. This can happen if the previous view
392 * was a system view that got unmapped behind our back. In that case
393 * we recover by simply deleting it. */
395 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
397 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
398 if ((char *)prev->base + prev->size > (char *)base)
400 TRACE( "overlapping prev view %p-%p for %p-%p\n",
401 prev->base, (char *)prev->base + prev->size,
402 base, (char *)base + view->size );
403 assert( prev->flags & VFLAG_SYSTEM );
407 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
409 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
410 if ((char *)base + view->size > (char *)next->base)
412 TRACE( "overlapping next view %p-%p for %p-%p\n",
413 next->base, (char *)next->base + next->size,
414 base, (char *)base + view->size );
415 assert( next->flags & VFLAG_SYSTEM );
421 VIRTUAL_DEBUG_DUMP_VIEW( view );
422 return STATUS_SUCCESS;
426 /***********************************************************************
427 * VIRTUAL_GetUnixProt
429 * Convert page protections to protection for mmap/mprotect.
431 static int VIRTUAL_GetUnixProt( BYTE vprot )
434 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
436 if (vprot & VPROT_READ) prot |= PROT_READ;
437 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
438 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
439 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
445 /***********************************************************************
446 * VIRTUAL_GetWin32Prot
448 * Convert page protections to Win32 flags.
453 static void VIRTUAL_GetWin32Prot(
454 BYTE vprot, /* [in] Page protection flags */
455 DWORD *protect, /* [out] Location to store Win32 protection flags */
456 DWORD *state ) /* [out] Location to store mem state flag */
459 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
460 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
461 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS | PAGE_GUARD;
464 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
468 /***********************************************************************
471 * Build page protections from Win32 flags.
474 * protect [I] Win32 protection flags
477 * Value of page protection flags
479 static BYTE VIRTUAL_GetProt( DWORD protect )
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 size_t 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 * Release the extra memory while keeping the range starting on the granularity boundary.
557 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
559 if ((ULONG_PTR)ptr & mask)
561 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
562 munmap( ptr, extra );
563 ptr = (char *)ptr + extra;
566 if (total_size > wanted_size)
567 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
572 /***********************************************************************
575 * Create a view and mmap the corresponding memory area.
576 * The csVirtual section must be held by caller.
578 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, BYTE vprot )
585 if (is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
586 return STATUS_WORKING_SET_LIMIT_RANGE;
588 switch (wine_mmap_is_in_reserved_area( base, size ))
590 case -1: /* partially in a reserved area */
591 return STATUS_CONFLICTING_ADDRESSES;
593 case 0: /* not in a reserved area, do a normal allocation */
594 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
596 if (errno == ENOMEM) return STATUS_NO_MEMORY;
597 return STATUS_INVALID_PARAMETER;
601 /* We couldn't get the address we wanted */
602 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
603 else munmap( ptr, size );
604 return STATUS_CONFLICTING_ADDRESSES;
609 case 1: /* in a reserved area, make sure the address is available */
610 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
611 /* replace the reserved area by our mapping */
612 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
613 return STATUS_INVALID_PARAMETER;
619 size_t view_size = size + granularity_mask + 1;
623 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
625 if (errno == ENOMEM) return STATUS_NO_MEMORY;
626 return STATUS_INVALID_PARAMETER;
628 /* if we got something beyond the user limit, unmap it and retry */
629 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
632 ptr = unmap_extra_space( ptr, view_size, size, granularity_mask );
635 status = create_view( view_ret, ptr, size, vprot );
636 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
641 /***********************************************************************
644 * Linux kernels before 2.4.x can support non page-aligned offsets, as
645 * long as the offset is aligned to the filesystem block size. This is
646 * a big performance gain so we want to take advantage of it.
648 * However, when we use 64-bit file support this doesn't work because
649 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
650 * in that it rounds unaligned offsets down to a page boundary. For
651 * these reasons we do a direct system call here.
653 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
654 unsigned int flags, int fd, off_t offset )
656 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
657 if (!(offset >> 32) && (offset & page_mask))
672 args.length = length;
676 args.offset = offset;
678 __asm__ __volatile__("push %%ebx\n\t"
683 : "0" (90), /* SYS_mmap */
686 if (ret < 0 && ret > -4096)
694 return mmap( addr, length, prot, flags, fd, offset );
698 /***********************************************************************
701 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
702 * The csVirtual section must be held by caller.
704 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
705 off_t offset, BYTE vprot, BOOL removable )
708 int prot = VIRTUAL_GetUnixProt( vprot );
709 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
711 assert( start < view->size );
712 assert( start + size <= view->size );
714 /* only try mmap if media is not removable (or if we require write access) */
715 if (!removable || shared_write)
717 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
719 if (unaligned_mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
722 /* mmap() failed; if this is because the file offset is not */
723 /* page-aligned (EINVAL), or because the underlying filesystem */
724 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
725 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
726 if (shared_write) return FILE_GetNtStatus(); /* we cannot fake shared write mappings */
729 /* Reserve the memory with an anonymous mmap */
730 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
731 if (ptr == (void *)-1) return FILE_GetNtStatus();
732 /* Now read in the file */
733 pread( fd, ptr, size, offset );
734 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
736 memset( view->prot + (start >> page_shift), vprot, size >> page_shift );
737 return STATUS_SUCCESS;
741 /***********************************************************************
744 * Decommit some pages of a given view.
745 * The csVirtual section must be held by caller.
747 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
749 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
751 BYTE *p = view->prot + (start >> page_shift);
753 while (size--) *p++ &= ~VPROT_COMMITTED;
754 return STATUS_SUCCESS;
756 return FILE_GetNtStatus();
760 /***********************************************************************
763 * Apply the relocations to a mapped PE image
765 static int do_relocations( char *base, const IMAGE_DATA_DIRECTORY *dir,
766 int delta, SIZE_T total_size )
768 IMAGE_BASE_RELOCATION *rel;
770 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
771 base - delta, base - delta + total_size, base, base + total_size );
773 for (rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
774 ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
775 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock) )
777 char *page = base + rel->VirtualAddress;
778 WORD *TypeOffset = (WORD *)(rel + 1);
779 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
781 if (!count) continue;
784 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size)
786 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
787 rel, rel->VirtualAddress, rel->SizeOfBlock,
788 base, dir->VirtualAddress, dir->Size );
792 if (page > base + total_size)
794 WARN_(module)("skipping %d relocations for page %p beyond module %p-%p\n",
795 count, page, base, base + total_size );
799 TRACE_(module)("%d relocations for page %lx\n", count, rel->VirtualAddress);
801 /* patching in reverse order */
802 for (i = 0 ; i < count; i++)
804 int offset = TypeOffset[i] & 0xFFF;
805 int type = TypeOffset[i] >> 12;
808 case IMAGE_REL_BASED_ABSOLUTE:
810 case IMAGE_REL_BASED_HIGH:
811 *(short*)(page+offset) += HIWORD(delta);
813 case IMAGE_REL_BASED_LOW:
814 *(short*)(page+offset) += LOWORD(delta);
816 case IMAGE_REL_BASED_HIGHLOW:
817 *(int*)(page+offset) += delta;
818 /* FIXME: if this is an exported address, fire up enhanced logic */
821 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
830 /***********************************************************************
833 * Map an executable (PE format) image into memory.
835 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size,
836 SIZE_T header_size, int shared_fd, BOOL removable, PVOID *addr_ptr )
838 IMAGE_DOS_HEADER *dos;
839 IMAGE_NT_HEADERS *nt;
840 IMAGE_SECTION_HEADER *sec;
841 IMAGE_DATA_DIRECTORY *imports;
842 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
845 struct file_view *view = NULL;
848 /* zero-map the whole range */
850 RtlEnterCriticalSection( &csVirtual );
852 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
853 status = map_view( &view, base, total_size,
854 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
856 if (status == STATUS_CONFLICTING_ADDRESSES)
857 status = map_view( &view, NULL, total_size,
858 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
860 if (status != STATUS_SUCCESS) goto error;
863 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
867 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
868 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ,
869 removable ) != STATUS_SUCCESS) goto error;
870 dos = (IMAGE_DOS_HEADER *)ptr;
871 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
872 if ((char *)(nt + 1) > ptr + header_size) goto error;
874 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
875 if ((char *)(sec + nt->FileHeader.NumberOfSections) > ptr + header_size) goto error;
877 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
878 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
880 /* check the architecture */
882 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
884 MESSAGE("Trying to load PE image for unsupported architecture (");
885 switch (nt->FileHeader.Machine)
887 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
888 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
889 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
890 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
891 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
892 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
893 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
894 case IMAGE_FILE_MACHINE_IA64: MESSAGE("IA-64"); break;
895 case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
896 case IMAGE_FILE_MACHINE_AMD64: MESSAGE("AMD-64"); break;
897 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
903 /* check for non page-aligned binary */
905 if (nt->OptionalHeader.SectionAlignment <= page_mask)
907 /* unaligned sections, this happens for native subsystem binaries */
908 /* in that case Windows simply maps in the whole file */
910 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
911 removable ) != STATUS_SUCCESS) goto error;
913 /* check that all sections are loaded at the right offset */
914 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
916 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
917 goto error; /* Windows refuses to load in that case too */
920 /* set the image protections */
921 VIRTUAL_SetProt( view, ptr, total_size,
922 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
924 /* perform relocations if necessary */
925 /* FIXME: not 100% compatible, Windows doesn't do this for non page-aligned binaries */
928 const IMAGE_DATA_DIRECTORY *relocs;
929 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
930 if (relocs->VirtualAddress && relocs->Size)
931 do_relocations( ptr, relocs, ptr - base, total_size );
938 /* map all the sections */
940 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
942 SIZE_T map_size, file_size, end;
944 if (!sec->Misc.VirtualSize)
946 file_size = sec->SizeOfRawData;
947 map_size = ROUND_SIZE( 0, file_size );
951 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
952 file_size = min( sec->SizeOfRawData, map_size );
955 /* a few sanity checks */
956 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
957 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
959 ERR_(module)( "Section %.8s too large (%lx+%lx/%lx)\n",
960 sec->Name, sec->VirtualAddress, map_size, total_size );
964 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
965 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
967 TRACE_(module)( "mapping shared section %.8s at %p off %lx (%x) size %lx (%lx) flags %lx\n",
968 sec->Name, ptr + sec->VirtualAddress,
969 sec->PointerToRawData, (int)pos, file_size, map_size,
970 sec->Characteristics );
971 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
972 VPROT_COMMITTED | VPROT_READ | PROT_WRITE,
973 FALSE ) != STATUS_SUCCESS)
975 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
979 /* check if the import directory falls inside this section */
980 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
981 imports->VirtualAddress < sec->VirtualAddress + map_size)
983 UINT_PTR base = imports->VirtualAddress & ~page_mask;
984 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
985 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
987 map_file_into_view( view, shared_fd, base, end - base,
988 pos + (base - sec->VirtualAddress),
989 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
996 TRACE_(module)( "mapping section %.8s at %p off %lx size %lx virt %lx flags %lx\n",
997 sec->Name, ptr + sec->VirtualAddress,
998 sec->PointerToRawData, sec->SizeOfRawData,
999 sec->Misc.VirtualSize, sec->Characteristics );
1001 if (!sec->PointerToRawData || !file_size) continue;
1003 /* Note: if the section is not aligned properly map_file_into_view will magically
1004 * fall back to read(), so we don't need to check anything here.
1006 if (map_file_into_view( view, fd, sec->VirtualAddress, file_size, sec->PointerToRawData,
1007 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1008 removable ) != STATUS_SUCCESS)
1010 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1014 if (file_size & page_mask)
1016 end = ROUND_SIZE( 0, file_size );
1017 if (end > map_size) end = map_size;
1018 TRACE_(module)("clearing %p - %p\n",
1019 ptr + sec->VirtualAddress + file_size,
1020 ptr + sec->VirtualAddress + end );
1021 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1026 /* perform base relocation, if necessary */
1030 const IMAGE_DATA_DIRECTORY *relocs;
1032 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1033 if (!relocs->VirtualAddress || !relocs->Size)
1035 if (nt->OptionalHeader.ImageBase == 0x400000) {
1036 ERR("Image was mapped at %p: standard load address for a Win32 program (0x00400000) not available\n", ptr);
1037 ERR("Do you have exec-shield or prelink active?\n");
1039 ERR( "FATAL: Need to relocate module from addr %lx, but there are no relocation records\n",
1040 nt->OptionalHeader.ImageBase );
1044 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
1045 * really make sure that the *new* base address is also > 2GB.
1046 * Some DLLs really check the MSB of the module handle :-/
1048 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((ULONG_PTR)base & 0x80000000))
1049 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
1051 if (!do_relocations( ptr, relocs, ptr - base, total_size ))
1057 /* set the image protections */
1059 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1060 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1062 SIZE_T size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1063 BYTE vprot = VPROT_COMMITTED;
1064 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1065 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
1066 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1067 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
1071 if (!removable) /* don't keep handle open on removable media */
1072 NtDuplicateObject( NtCurrentProcess(), hmapping,
1073 NtCurrentProcess(), &view->mapping,
1074 0, 0, DUPLICATE_SAME_ACCESS );
1076 RtlLeaveCriticalSection( &csVirtual );
1079 return STATUS_SUCCESS;
1082 if (view) delete_view( view );
1083 RtlLeaveCriticalSection( &csVirtual );
1088 /***********************************************************************
1089 * is_current_process
1091 * Check whether a process handle is for the current process.
1093 BOOL is_current_process( HANDLE handle )
1097 if (handle == NtCurrentProcess()) return TRUE;
1098 SERVER_START_REQ( get_process_info )
1100 req->handle = handle;
1101 if (!wine_server_call( req ))
1102 ret = ((DWORD)reply->pid == GetCurrentProcessId());
1109 /***********************************************************************
1112 static inline void virtual_init(void)
1115 page_size = getpagesize();
1116 page_mask = page_size - 1;
1117 /* Make sure we have a power of 2 */
1118 assert( !(page_size & page_mask) );
1120 while ((1 << page_shift) != page_size) page_shift++;
1121 #endif /* page_mask */
1125 /***********************************************************************
1128 * Allocate a memory view for a new TEB, properly aligned to a multiple of the size.
1130 NTSTATUS VIRTUAL_alloc_teb( void **ret, size_t size, BOOL first )
1134 struct file_view *view;
1136 BYTE vprot = VPROT_READ | VPROT_WRITE | VPROT_COMMITTED;
1138 if (first) virtual_init();
1141 size = ROUND_SIZE( 0, size );
1142 align_size = page_size;
1143 while (align_size < size) align_size *= 2;
1147 if ((ptr = wine_anon_mmap( NULL, 2 * align_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
1149 if (errno == ENOMEM) return STATUS_NO_MEMORY;
1150 return STATUS_INVALID_PARAMETER;
1152 if (!is_beyond_limit( ptr, 2 * align_size, user_space_limit ))
1154 ptr = unmap_extra_space( ptr, 2 * align_size, align_size, align_size - 1 );
1157 /* if we got something beyond the user limit, unmap it and retry */
1158 add_reserved_area( ptr, 2 * align_size );
1161 if (!first) RtlEnterCriticalSection( &csVirtual );
1163 status = create_view( &view, ptr, size, vprot );
1164 if (status == STATUS_SUCCESS)
1166 view->flags |= VFLAG_VALLOC;
1169 else unmap_area( ptr, size );
1171 if (!first) RtlLeaveCriticalSection( &csVirtual );
1177 /***********************************************************************
1178 * VIRTUAL_HandleFault
1180 NTSTATUS VIRTUAL_HandleFault( LPCVOID addr )
1183 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1185 RtlEnterCriticalSection( &csVirtual );
1186 if ((view = VIRTUAL_FindView( addr )))
1188 BYTE vprot = view->prot[((const char *)addr - (const char *)view->base) >> page_shift];
1189 void *page = (void *)((UINT_PTR)addr & ~page_mask);
1190 char *stack = NtCurrentTeb()->Tib.StackLimit;
1191 if (vprot & VPROT_GUARD)
1193 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
1194 ret = STATUS_GUARD_PAGE_VIOLATION;
1196 /* is it inside the stack guard page? */
1197 if (((const char *)addr >= stack) && ((const char *)addr < stack + (page_mask+1)))
1198 ret = STATUS_STACK_OVERFLOW;
1200 RtlLeaveCriticalSection( &csVirtual );
1204 /***********************************************************************
1205 * VIRTUAL_HasMapping
1207 * Check if the specified view has an associated file mapping.
1209 BOOL VIRTUAL_HasMapping( LPCVOID addr )
1214 RtlEnterCriticalSection( &csVirtual );
1215 if ((view = VIRTUAL_FindView( addr ))) ret = (view->mapping != 0);
1216 RtlLeaveCriticalSection( &csVirtual );
1221 /***********************************************************************
1222 * VIRTUAL_UseLargeAddressSpace
1224 * Increase the address space size for apps that support it.
1226 void VIRTUAL_UseLargeAddressSpace(void)
1228 if (user_space_limit >= ADDRESS_SPACE_LIMIT) return;
1229 RtlEnterCriticalSection( &csVirtual );
1230 remove_reserved_area( user_space_limit, (char *)ADDRESS_SPACE_LIMIT - (char *)user_space_limit );
1231 user_space_limit = ADDRESS_SPACE_LIMIT;
1232 RtlLeaveCriticalSection( &csVirtual );
1236 /***********************************************************************
1237 * NtAllocateVirtualMemory (NTDLL.@)
1238 * ZwAllocateVirtualMemory (NTDLL.@)
1240 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1241 SIZE_T *size_ptr, ULONG type, ULONG protect )
1245 SIZE_T size = *size_ptr;
1246 NTSTATUS status = STATUS_SUCCESS;
1247 struct file_view *view;
1249 TRACE("%p %p %08lx %lx %08lx\n", process, *ret, size, type, protect );
1251 if (!size) return STATUS_INVALID_PARAMETER;
1253 if (!is_current_process( process ))
1255 ERR("Unsupported on other process\n");
1256 return STATUS_ACCESS_DENIED;
1259 /* Round parameters to a page boundary */
1261 if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
1265 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1266 base = ROUND_ADDR( *ret, granularity_mask );
1268 base = ROUND_ADDR( *ret, page_mask );
1269 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1271 /* disallow low 64k, wrap-around and kernel space */
1272 if (((char *)base <= (char *)granularity_mask) ||
1273 ((char *)base + size < (char *)base) ||
1274 is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
1275 return STATUS_INVALID_PARAMETER;
1280 size = (size + page_mask) & ~page_mask;
1283 if (type & MEM_TOP_DOWN) {
1284 /* FIXME: MEM_TOP_DOWN allocates the largest possible address. */
1285 WARN("MEM_TOP_DOWN ignored\n");
1286 type &= ~MEM_TOP_DOWN;
1290 WARN("zero_bits %lu ignored\n", zero_bits);
1292 /* Compute the alloc type flags */
1294 if (!(type & MEM_SYSTEM))
1296 if (!(type & (MEM_COMMIT | MEM_RESERVE)) || (type & ~(MEM_COMMIT | MEM_RESERVE)))
1298 WARN("called with wrong alloc type flags (%08lx) !\n", type);
1299 return STATUS_INVALID_PARAMETER;
1302 vprot = VIRTUAL_GetProt( protect );
1303 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1305 /* Reserve the memory */
1307 RtlEnterCriticalSection( &csVirtual );
1309 if (type & MEM_SYSTEM)
1311 if (type & MEM_IMAGE) vprot |= VPROT_IMAGE;
1312 status = create_view( &view, base, size, vprot | VPROT_COMMITTED );
1313 if (status == STATUS_SUCCESS)
1315 view->flags |= VFLAG_VALLOC | VFLAG_SYSTEM;
1319 else if ((type & MEM_RESERVE) || !base)
1321 status = map_view( &view, base, size, vprot );
1322 if (status == STATUS_SUCCESS)
1324 view->flags |= VFLAG_VALLOC;
1328 else /* commit the pages */
1330 if (!(view = VIRTUAL_FindView( base )) ||
1331 ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
1332 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1335 RtlLeaveCriticalSection( &csVirtual );
1337 if (status == STATUS_SUCCESS)
1346 /***********************************************************************
1347 * NtFreeVirtualMemory (NTDLL.@)
1348 * ZwFreeVirtualMemory (NTDLL.@)
1350 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1354 NTSTATUS status = STATUS_SUCCESS;
1355 LPVOID addr = *addr_ptr;
1356 SIZE_T size = *size_ptr;
1358 TRACE("%p %p %08lx %lx\n", process, addr, size, type );
1360 if (!is_current_process( process ))
1362 ERR("Unsupported on other process\n");
1363 return STATUS_ACCESS_DENIED;
1366 /* Fix the parameters */
1368 size = ROUND_SIZE( addr, size );
1369 base = ROUND_ADDR( addr, page_mask );
1371 RtlEnterCriticalSection(&csVirtual);
1373 if (!(view = VIRTUAL_FindView( base )) ||
1374 (base + size > (char *)view->base + view->size) ||
1375 !(view->flags & VFLAG_VALLOC))
1377 status = STATUS_INVALID_PARAMETER;
1379 else if (type & MEM_SYSTEM)
1381 /* return the values that the caller should use to unmap the area */
1382 *addr_ptr = view->base;
1383 *size_ptr = view->size;
1384 view->flags |= VFLAG_SYSTEM;
1385 delete_view( view );
1387 else if (type == MEM_RELEASE)
1389 /* Free the pages */
1391 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1394 delete_view( view );
1399 else if (type == MEM_DECOMMIT)
1401 status = decommit_pages( view, base - (char *)view->base, size );
1402 if (status == STATUS_SUCCESS)
1410 WARN("called with wrong free type flags (%08lx) !\n", type);
1411 status = STATUS_INVALID_PARAMETER;
1414 RtlLeaveCriticalSection(&csVirtual);
1419 /***********************************************************************
1420 * NtProtectVirtualMemory (NTDLL.@)
1421 * ZwProtectVirtualMemory (NTDLL.@)
1423 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1424 ULONG new_prot, ULONG *old_prot )
1427 NTSTATUS status = STATUS_SUCCESS;
1432 SIZE_T size = *size_ptr;
1433 LPVOID addr = *addr_ptr;
1435 TRACE("%p %p %08lx %08lx\n", process, addr, size, new_prot );
1437 if (!is_current_process( process ))
1439 ERR("Unsupported on other process\n");
1440 return STATUS_ACCESS_DENIED;
1443 /* Fix the parameters */
1445 size = ROUND_SIZE( addr, size );
1446 base = ROUND_ADDR( addr, page_mask );
1448 RtlEnterCriticalSection( &csVirtual );
1450 if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1452 status = STATUS_INVALID_PARAMETER;
1456 /* Make sure all the pages are committed */
1458 p = view->prot + ((base - (char *)view->base) >> page_shift);
1459 VIRTUAL_GetWin32Prot( *p, &prot, NULL );
1460 for (i = size >> page_shift; i; i--, p++)
1462 if (!(*p & VPROT_COMMITTED))
1464 status = STATUS_NOT_COMMITTED;
1470 if (old_prot) *old_prot = prot;
1471 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1472 if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1475 RtlLeaveCriticalSection( &csVirtual );
1477 if (status == STATUS_SUCCESS)
1485 #define UNIMPLEMENTED_INFO_CLASS(c) \
1487 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
1488 return STATUS_INVALID_INFO_CLASS
1490 /***********************************************************************
1491 * NtQueryVirtualMemory (NTDLL.@)
1492 * ZwQueryVirtualMemory (NTDLL.@)
1494 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1495 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1496 SIZE_T len, SIZE_T *res_len )
1499 char *base, *alloc_base = 0;
1502 MEMORY_BASIC_INFORMATION *info = buffer;
1504 if (info_class != MemoryBasicInformation)
1508 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
1509 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
1510 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
1513 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
1514 process, addr, info_class, buffer, len, res_len);
1515 return STATUS_INVALID_INFO_CLASS;
1518 if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1519 return STATUS_WORKING_SET_LIMIT_RANGE;
1521 if (!is_current_process( process ))
1523 ERR("Unsupported on other process\n");
1524 return STATUS_ACCESS_DENIED;
1527 base = ROUND_ADDR( addr, page_mask );
1529 /* Find the view containing the address */
1531 RtlEnterCriticalSection(&csVirtual);
1532 ptr = list_head( &views_list );
1537 /* make the address space end at the user limit, except if
1538 * the last view was mapped beyond that */
1539 if (alloc_base <= (char *)user_space_limit)
1541 if (user_space_limit && base >= (char *)user_space_limit)
1543 RtlLeaveCriticalSection( &csVirtual );
1544 return STATUS_WORKING_SET_LIMIT_RANGE;
1546 size = (char *)user_space_limit - alloc_base;
1548 else size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1552 view = LIST_ENTRY( ptr, struct file_view, entry );
1553 if ((char *)view->base > base)
1555 size = (char *)view->base - alloc_base;
1559 if ((char *)view->base + view->size > base)
1561 alloc_base = view->base;
1565 alloc_base = (char *)view->base + view->size;
1566 ptr = list_next( &views_list, ptr );
1569 /* Fill the info structure */
1573 info->State = MEM_FREE;
1575 info->AllocationProtect = 0;
1580 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1581 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
1582 for (size = base - alloc_base; size < view->size; size += page_mask+1)
1583 if (view->prot[size >> page_shift] != vprot) break;
1584 VIRTUAL_GetWin32Prot( view->protect, &info->AllocationProtect, NULL );
1585 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1586 else if (view->flags & VFLAG_VALLOC) info->Type = MEM_PRIVATE;
1587 else info->Type = MEM_MAPPED;
1589 RtlLeaveCriticalSection(&csVirtual);
1591 info->BaseAddress = (LPVOID)base;
1592 info->AllocationBase = (LPVOID)alloc_base;
1593 info->RegionSize = size - (base - alloc_base);
1594 if (res_len) *res_len = sizeof(*info);
1595 return STATUS_SUCCESS;
1599 /***********************************************************************
1600 * NtLockVirtualMemory (NTDLL.@)
1601 * ZwLockVirtualMemory (NTDLL.@)
1603 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1605 if (!is_current_process( process ))
1607 ERR("Unsupported on other process\n");
1608 return STATUS_ACCESS_DENIED;
1610 return STATUS_SUCCESS;
1614 /***********************************************************************
1615 * NtUnlockVirtualMemory (NTDLL.@)
1616 * ZwUnlockVirtualMemory (NTDLL.@)
1618 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1620 if (!is_current_process( process ))
1622 ERR("Unsupported on other process\n");
1623 return STATUS_ACCESS_DENIED;
1625 return STATUS_SUCCESS;
1629 /***********************************************************************
1630 * NtCreateSection (NTDLL.@)
1631 * ZwCreateSection (NTDLL.@)
1633 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1634 const LARGE_INTEGER *size, ULONG protect,
1635 ULONG sec_flags, HANDLE file )
1639 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
1641 /* Check parameters */
1643 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1645 vprot = VIRTUAL_GetProt( protect );
1646 if (sec_flags & SEC_RESERVE)
1648 if (file) return STATUS_INVALID_PARAMETER;
1650 else vprot |= VPROT_COMMITTED;
1651 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1652 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
1654 /* Create the server object */
1656 SERVER_START_REQ( create_mapping )
1658 req->access = access;
1659 req->attributes = (attr) ? attr->Attributes : 0;
1660 req->file_handle = file;
1661 req->size_high = size ? size->u.HighPart : 0;
1662 req->size_low = size ? size->u.LowPart : 0;
1663 req->protect = vprot;
1664 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
1665 ret = wine_server_call( req );
1666 *handle = reply->handle;
1673 /***********************************************************************
1674 * NtOpenSection (NTDLL.@)
1675 * ZwOpenSection (NTDLL.@)
1677 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1680 DWORD len = attr->ObjectName->Length;
1682 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1684 SERVER_START_REQ( open_mapping )
1686 req->access = access;
1687 req->attributes = (attr) ? attr->Attributes : 0;
1688 wine_server_add_data( req, attr->ObjectName->Buffer, len );
1689 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
1696 /***********************************************************************
1697 * NtMapViewOfSection (NTDLL.@)
1698 * ZwMapViewOfSection (NTDLL.@)
1700 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
1701 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
1702 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
1704 FILE_FS_DEVICE_INFORMATION device_info;
1707 int unix_handle = -1;
1710 struct file_view *view;
1711 DWORD size_low, size_high, header_size, shared_size;
1713 BOOL removable = FALSE;
1714 LARGE_INTEGER offset;
1716 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
1718 TRACE("handle=%p process=%p addr=%p off=%lx%08lx size=%lx access=%lx\n",
1719 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, size, protect );
1721 if (!is_current_process( process ))
1723 ERR("Unsupported on other process\n");
1724 return STATUS_ACCESS_DENIED;
1727 /* Check parameters */
1729 if ((offset.u.LowPart & granularity_mask) ||
1730 (*addr_ptr && ((UINT_PTR)*addr_ptr & granularity_mask)))
1731 return STATUS_INVALID_PARAMETER;
1733 SERVER_START_REQ( get_mapping_info )
1735 req->handle = handle;
1736 res = wine_server_call( req );
1737 prot = reply->protect;
1739 size_low = reply->size_low;
1740 size_high = reply->size_high;
1741 header_size = reply->header_size;
1742 shared_file = reply->shared_file;
1743 shared_size = reply->shared_size;
1746 if (res) return res;
1748 if ((res = wine_server_handle_to_fd( handle, 0, &unix_handle, NULL ))) return res;
1750 if (FILE_GetDeviceInfo( unix_handle, &device_info ) == STATUS_SUCCESS)
1751 removable = device_info.Characteristics & FILE_REMOVABLE_MEDIA;
1753 if (prot & VPROT_IMAGE)
1759 if ((res = wine_server_handle_to_fd( shared_file, GENERIC_READ, &shared_fd,
1761 res = map_image( handle, unix_handle, base, size_low, header_size,
1762 shared_fd, removable, addr_ptr );
1763 wine_server_release_fd( shared_file, shared_fd );
1764 NtClose( shared_file );
1768 res = map_image( handle, unix_handle, base, size_low, header_size,
1769 -1, removable, addr_ptr );
1771 wine_server_release_fd( handle, unix_handle );
1772 if (!res) *size_ptr = size_low;
1777 ERR("Sizes larger than 4Gb not supported\n");
1779 if ((offset.u.LowPart >= size_low) ||
1780 (*size_ptr > size_low - offset.u.LowPart))
1782 res = STATUS_INVALID_PARAMETER;
1785 if (*size_ptr) size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
1786 else size = size_low - offset.u.LowPart;
1792 case PAGE_READWRITE:
1793 case PAGE_EXECUTE_READWRITE:
1794 if (!(prot & VPROT_WRITE))
1796 res = STATUS_INVALID_PARAMETER;
1802 case PAGE_WRITECOPY:
1804 case PAGE_EXECUTE_READ:
1805 case PAGE_EXECUTE_WRITECOPY:
1806 if (prot & VPROT_READ) break;
1809 res = STATUS_INVALID_PARAMETER;
1813 /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1814 * which has a view of this mapping commits some pages, they will
1815 * appear commited in all other processes, which have the same
1816 * view created. Since we don`t support this yet, we create the
1817 * whole mapping commited.
1819 prot |= VPROT_COMMITTED;
1821 /* Reserve a properly aligned area */
1823 RtlEnterCriticalSection( &csVirtual );
1825 res = map_view( &view, *addr_ptr, size, prot );
1828 RtlLeaveCriticalSection( &csVirtual );
1834 TRACE("handle=%p size=%lx offset=%lx%08lx\n",
1835 handle, size, offset.u.HighPart, offset.u.LowPart );
1837 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, prot, removable );
1838 if (res == STATUS_SUCCESS)
1840 if (!removable) /* don't keep handle open on removable media */
1841 NtDuplicateObject( NtCurrentProcess(), handle,
1842 NtCurrentProcess(), &view->mapping,
1843 0, 0, DUPLICATE_SAME_ACCESS );
1845 *addr_ptr = view->base;
1850 ERR( "map_file_into_view %p %lx %lx%08lx failed\n",
1851 view->base, size, offset.u.HighPart, offset.u.LowPart );
1852 delete_view( view );
1855 RtlLeaveCriticalSection( &csVirtual );
1858 wine_server_release_fd( handle, unix_handle );
1863 /***********************************************************************
1864 * NtUnmapViewOfSection (NTDLL.@)
1865 * ZwUnmapViewOfSection (NTDLL.@)
1867 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
1870 NTSTATUS status = STATUS_INVALID_PARAMETER;
1871 void *base = ROUND_ADDR( addr, page_mask );
1873 if (!is_current_process( process ))
1875 ERR("Unsupported on other process\n");
1876 return STATUS_ACCESS_DENIED;
1878 RtlEnterCriticalSection( &csVirtual );
1879 if ((view = VIRTUAL_FindView( base )) && (base == view->base))
1881 delete_view( view );
1882 status = STATUS_SUCCESS;
1884 RtlLeaveCriticalSection( &csVirtual );
1889 /***********************************************************************
1890 * NtFlushVirtualMemory (NTDLL.@)
1891 * ZwFlushVirtualMemory (NTDLL.@)
1893 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
1894 SIZE_T *size_ptr, ULONG unknown )
1897 NTSTATUS status = STATUS_SUCCESS;
1898 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
1900 if (!is_current_process( process ))
1902 ERR("Unsupported on other process\n");
1903 return STATUS_ACCESS_DENIED;
1905 RtlEnterCriticalSection( &csVirtual );
1906 if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
1909 if (!*size_ptr) *size_ptr = view->size;
1911 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
1913 RtlLeaveCriticalSection( &csVirtual );
1918 /***********************************************************************
1919 * NtReadVirtualMemory (NTDLL.@)
1920 * ZwReadVirtualMemory (NTDLL.@)
1922 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
1923 SIZE_T size, SIZE_T *bytes_read )
1927 SERVER_START_REQ( read_process_memory )
1929 req->handle = process;
1930 req->addr = (void *)addr;
1931 wine_server_set_reply( req, buffer, size );
1932 if ((status = wine_server_call( req ))) size = 0;
1935 if (bytes_read) *bytes_read = size;
1940 /***********************************************************************
1941 * NtWriteVirtualMemory (NTDLL.@)
1942 * ZwWriteVirtualMemory (NTDLL.@)
1944 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
1945 SIZE_T size, SIZE_T *bytes_written )
1947 static const unsigned int zero;
1948 SIZE_T first_offset, last_offset, first_mask, last_mask;
1951 if (!size) return STATUS_INVALID_PARAMETER;
1953 /* compute the mask for the first int */
1955 first_offset = (ULONG_PTR)addr % sizeof(int);
1956 memset( &first_mask, 0, first_offset );
1958 /* compute the mask for the last int */
1959 last_offset = (size + first_offset) % sizeof(int);
1961 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1963 SERVER_START_REQ( write_process_memory )
1965 req->handle = process;
1966 req->addr = (char *)addr - first_offset;
1967 req->first_mask = first_mask;
1968 req->last_mask = last_mask;
1969 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1970 wine_server_add_data( req, buffer, size );
1971 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1973 if ((status = wine_server_call( req ))) size = 0;
1976 if (bytes_written) *bytes_written = size;