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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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_STAT_H
39 # include <sys/stat.h>
41 #ifdef HAVE_SYS_MMAN_H
42 # include <sys/mman.h>
45 #define NONAMELESSUNION
46 #define NONAMELESSSTRUCT
48 #define WIN32_NO_STATUS
52 #include "wine/library.h"
53 #include "wine/server.h"
54 #include "wine/list.h"
55 #include "wine/debug.h"
56 #include "ntdll_misc.h"
58 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
59 WINE_DECLARE_DEBUG_CHANNEL(module);
66 #define MAP_NORESERVE 0
70 typedef struct file_view
72 struct list entry; /* Entry in global view list */
73 void *base; /* Base address */
74 size_t size; /* Size in bytes */
75 HANDLE mapping; /* Handle to the file mapping */
76 BYTE flags; /* Allocation flags (VFLAG_*) */
77 BYTE protect; /* Protection for all pages at allocation time */
78 BYTE prot[1]; /* Protection byte for each page */
82 #define VFLAG_SYSTEM 0x01 /* system view (underlying mmap not under our control) */
83 #define VFLAG_VALLOC 0x02 /* allocated by VirtualAlloc */
85 /* Conversion from VPROT_* to Win32 flags */
86 static const BYTE VIRTUAL_Win32Flags[16] =
88 PAGE_NOACCESS, /* 0 */
89 PAGE_READONLY, /* READ */
90 PAGE_READWRITE, /* WRITE */
91 PAGE_READWRITE, /* READ | WRITE */
92 PAGE_EXECUTE, /* EXEC */
93 PAGE_EXECUTE_READ, /* READ | EXEC */
94 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
95 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
96 PAGE_WRITECOPY, /* WRITECOPY */
97 PAGE_WRITECOPY, /* READ | WRITECOPY */
98 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
99 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
100 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
101 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
102 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
103 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
106 static struct list views_list = LIST_INIT(views_list);
108 static RTL_CRITICAL_SECTION csVirtual;
109 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
112 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
113 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
115 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
118 /* These are always the same on an i386, and it will be faster this way */
119 # define page_mask 0xfff
120 # define page_shift 12
121 # define page_size 0x1000
122 /* Note: these are Windows limits, you cannot change them. */
123 # define ADDRESS_SPACE_LIMIT ((void *)0xc0000000) /* top of the total available address space */
124 # define USER_SPACE_LIMIT ((void *)0x7fff0000) /* top of the user address space */
126 static UINT page_shift;
127 static UINT page_size;
128 static UINT_PTR page_mask;
129 # define ADDRESS_SPACE_LIMIT 0 /* no limit needed on other platforms */
130 # define USER_SPACE_LIMIT 0 /* no limit needed on other platforms */
131 #endif /* __i386__ */
133 #define ROUND_ADDR(addr,mask) \
134 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
136 #define ROUND_SIZE(addr,size) \
137 (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
139 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
140 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
142 static void *user_space_limit = USER_SPACE_LIMIT;
145 /***********************************************************************
148 static const char *VIRTUAL_GetProtStr( BYTE prot )
150 static char buffer[6];
151 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
152 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
153 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
154 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
155 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
161 /***********************************************************************
164 static void VIRTUAL_DumpView( FILE_VIEW *view )
167 char *addr = view->base;
168 BYTE prot = view->prot[0];
170 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
171 if (view->flags & VFLAG_SYSTEM)
172 TRACE( " (system)\n" );
173 else if (view->flags & VFLAG_VALLOC)
174 TRACE( " (valloc)\n" );
175 else if (view->mapping)
176 TRACE( " %p\n", view->mapping );
178 TRACE( " (anonymous)\n");
180 for (count = i = 1; i < view->size >> page_shift; i++, count++)
182 if (view->prot[i] == prot) continue;
183 TRACE( " %p - %p %s\n",
184 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
185 addr += (count << page_shift);
186 prot = view->prot[i];
190 TRACE( " %p - %p %s\n",
191 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
195 /***********************************************************************
199 static void VIRTUAL_Dump(void)
201 struct file_view *view;
203 TRACE( "Dump of all virtual memory views:\n" );
204 RtlEnterCriticalSection(&csVirtual);
205 LIST_FOR_EACH_ENTRY( view, &views_list, FILE_VIEW, entry )
207 VIRTUAL_DumpView( view );
209 RtlLeaveCriticalSection(&csVirtual);
214 /***********************************************************************
217 * Find the view containing a given address. The csVirtual section must be held by caller.
226 static struct file_view *VIRTUAL_FindView( const void *addr )
228 struct file_view *view;
230 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
232 if (view->base > addr) break;
233 if ((const char*)view->base + view->size > (const char*)addr) return view;
239 /***********************************************************************
242 static inline UINT_PTR get_mask( ULONG zero_bits )
244 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
245 if (zero_bits < page_shift) zero_bits = page_shift;
246 return (1 << zero_bits) - 1;
250 /***********************************************************************
253 * Find the first view overlapping at least part of the specified range.
254 * The csVirtual section must be held by caller.
256 static struct file_view *find_view_range( const void *addr, size_t size )
258 struct file_view *view;
260 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
262 if ((const char *)view->base >= (const char *)addr + size) break;
263 if ((const char *)view->base + view->size > (const char *)addr) return view;
269 /***********************************************************************
272 * Add a reserved area to the list maintained by libwine.
273 * The csVirtual section must be held by caller.
275 static void add_reserved_area( void *addr, size_t size )
277 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
279 if (addr < user_space_limit)
281 /* unmap the part of the area that is below the limit */
282 assert( (char *)addr + size > (char *)user_space_limit );
283 munmap( addr, (char *)user_space_limit - (char *)addr );
284 size -= (char *)user_space_limit - (char *)addr;
285 addr = user_space_limit;
287 /* blow away existing mappings */
288 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
289 wine_mmap_add_reserved_area( addr, size );
293 /***********************************************************************
294 * remove_reserved_area
296 * Remove a reserved area from the list maintained by libwine.
297 * The csVirtual section must be held by caller.
299 static void remove_reserved_area( void *addr, size_t size )
301 struct file_view *view;
303 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
305 if ((char *)view->base >= (char *)addr + size) break;
306 if ((char *)view->base + view->size <= (char *)addr) continue;
307 /* now we have an overlapping view */
308 if (view->base > addr)
310 wine_mmap_remove_reserved_area( addr, (char *)view->base - (char *)addr, TRUE );
311 size -= (char *)view->base - (char *)addr;
314 if ((char *)view->base + view->size >= (char *)addr + size)
316 /* view covers all the remaining area */
317 wine_mmap_remove_reserved_area( addr, size, FALSE );
321 else /* view covers only part of the area */
323 wine_mmap_remove_reserved_area( addr, (char *)view->base + view->size - (char *)addr, FALSE );
324 size -= (char *)view->base + view->size - (char *)addr;
325 addr = (char *)view->base + view->size;
328 /* remove remaining space */
329 if (size) wine_mmap_remove_reserved_area( addr, size, TRUE );
333 /***********************************************************************
336 * Check if an address range goes beyond a given limit.
338 static inline int is_beyond_limit( void *addr, size_t size, void *limit )
340 return (limit && (addr >= limit || (char *)addr + size > (char *)limit));
344 /***********************************************************************
347 * Unmap an area, or simply replace it by an empty mapping if it is
348 * in a reserved area. The csVirtual section must be held by caller.
350 static inline void unmap_area( void *addr, size_t size )
352 if (wine_mmap_is_in_reserved_area( addr, size ))
353 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
354 else if (is_beyond_limit( addr, size, user_space_limit ))
355 add_reserved_area( addr, size );
357 munmap( addr, size );
361 /***********************************************************************
364 * Deletes a view. The csVirtual section must be held by caller.
366 static void delete_view( struct file_view *view ) /* [in] View */
368 if (!(view->flags & VFLAG_SYSTEM)) unmap_area( view->base, view->size );
369 list_remove( &view->entry );
370 if (view->mapping) NtClose( view->mapping );
375 /***********************************************************************
378 * Create a view. The csVirtual section must be held by caller.
380 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, BYTE vprot )
382 struct file_view *view;
385 assert( !((UINT_PTR)base & page_mask) );
386 assert( !(size & page_mask) );
388 /* Create the view structure */
390 if (!(view = malloc( sizeof(*view) + (size >> page_shift) - 1 ))) return STATUS_NO_MEMORY;
396 view->protect = vprot;
397 memset( view->prot, vprot & ~VPROT_IMAGE, size >> page_shift );
399 /* Insert it in the linked list */
401 LIST_FOR_EACH( ptr, &views_list )
403 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
404 if (next->base > base) break;
406 list_add_before( ptr, &view->entry );
408 /* Check for overlapping views. This can happen if the previous view
409 * was a system view that got unmapped behind our back. In that case
410 * we recover by simply deleting it. */
412 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
414 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
415 if ((char *)prev->base + prev->size > (char *)base)
417 TRACE( "overlapping prev view %p-%p for %p-%p\n",
418 prev->base, (char *)prev->base + prev->size,
419 base, (char *)base + view->size );
420 assert( prev->flags & VFLAG_SYSTEM );
424 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
426 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
427 if ((char *)base + view->size > (char *)next->base)
429 TRACE( "overlapping next view %p-%p for %p-%p\n",
430 next->base, (char *)next->base + next->size,
431 base, (char *)base + view->size );
432 assert( next->flags & VFLAG_SYSTEM );
438 VIRTUAL_DEBUG_DUMP_VIEW( view );
439 return STATUS_SUCCESS;
443 /***********************************************************************
444 * VIRTUAL_GetUnixProt
446 * Convert page protections to protection for mmap/mprotect.
448 static int VIRTUAL_GetUnixProt( BYTE vprot )
451 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
453 if (vprot & VPROT_READ) prot |= PROT_READ;
454 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
455 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
456 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
458 if (!prot) prot = PROT_NONE;
463 /***********************************************************************
464 * VIRTUAL_GetWin32Prot
466 * Convert page protections to Win32 flags.
468 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
470 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
471 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
472 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
477 /***********************************************************************
480 * Build page protections from Win32 flags.
483 * protect [I] Win32 protection flags
486 * Value of page protection flags
488 static BYTE VIRTUAL_GetProt( DWORD protect )
492 switch(protect & 0xff)
498 vprot = VPROT_READ | VPROT_WRITE;
501 /* MSDN CreateFileMapping() states that if PAGE_WRITECOPY is given,
502 * that the hFile must have been opened with GENERIC_READ and
503 * GENERIC_WRITE access. This is WRONG as tests show that you
504 * only need GENERIC_READ access (at least for Win9x,
505 * FIXME: what about NT?). Thus, we don't put VPROT_WRITE in
506 * PAGE_WRITECOPY and PAGE_EXECUTE_WRITECOPY.
508 vprot = VPROT_READ | VPROT_WRITECOPY;
513 case PAGE_EXECUTE_READ:
514 vprot = VPROT_EXEC | VPROT_READ;
516 case PAGE_EXECUTE_READWRITE:
517 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
519 case PAGE_EXECUTE_WRITECOPY:
520 /* See comment for PAGE_WRITECOPY above */
521 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
528 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
529 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
534 /***********************************************************************
537 * Change the protection of a range of pages.
543 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
544 void *base, /* [in] Starting address */
545 size_t size, /* [in] Size in bytes */
546 BYTE vprot ) /* [in] Protections to use */
549 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
551 if (mprotect( base, size, VIRTUAL_GetUnixProt(vprot) ))
552 return FALSE; /* FIXME: last error */
554 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
555 vprot, size >> page_shift );
556 VIRTUAL_DEBUG_DUMP_VIEW( view );
561 /***********************************************************************
564 * Release the extra memory while keeping the range starting on the granularity boundary.
566 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
568 if ((ULONG_PTR)ptr & mask)
570 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
571 munmap( ptr, extra );
572 ptr = (char *)ptr + extra;
575 if (total_size > wanted_size)
576 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
581 /***********************************************************************
584 * Create a view and mmap the corresponding memory area.
585 * The csVirtual section must be held by caller.
587 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
595 if (is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
596 return STATUS_WORKING_SET_LIMIT_RANGE;
598 switch (wine_mmap_is_in_reserved_area( base, size ))
600 case -1: /* partially in a reserved area */
601 return STATUS_CONFLICTING_ADDRESSES;
603 case 0: /* not in a reserved area, do a normal allocation */
604 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
606 if (errno == ENOMEM) return STATUS_NO_MEMORY;
607 return STATUS_INVALID_PARAMETER;
611 /* We couldn't get the address we wanted */
612 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
613 else munmap( ptr, size );
614 return STATUS_CONFLICTING_ADDRESSES;
619 case 1: /* in a reserved area, make sure the address is available */
620 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
621 /* replace the reserved area by our mapping */
622 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
623 return STATUS_INVALID_PARAMETER;
629 size_t view_size = size + mask + 1;
633 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
635 if (errno == ENOMEM) return STATUS_NO_MEMORY;
636 return STATUS_INVALID_PARAMETER;
638 /* if we got something beyond the user limit, unmap it and retry */
639 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
642 ptr = unmap_extra_space( ptr, view_size, size, mask );
645 status = create_view( view_ret, ptr, size, vprot );
646 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
651 /***********************************************************************
654 * Linux kernels before 2.4.x can support non page-aligned offsets, as
655 * long as the offset is aligned to the filesystem block size. This is
656 * a big performance gain so we want to take advantage of it.
658 * However, when we use 64-bit file support this doesn't work because
659 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
660 * in that it rounds unaligned offsets down to a page boundary. For
661 * these reasons we do a direct system call here.
663 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
664 unsigned int flags, int fd, off_t offset )
666 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
667 if (!(offset >> 32) && (offset & page_mask))
682 args.length = length;
686 args.offset = offset;
688 __asm__ __volatile__("push %%ebx\n\t"
693 : "0" (90), /* SYS_mmap */
696 if (ret < 0 && ret > -4096)
704 return mmap( addr, length, prot, flags, fd, offset );
708 /***********************************************************************
711 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
712 * The csVirtual section must be held by caller.
714 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
715 off_t offset, BYTE vprot, BOOL removable )
718 int prot = VIRTUAL_GetUnixProt( vprot );
719 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
721 assert( start < view->size );
722 assert( start + size <= view->size );
724 /* only try mmap if media is not removable (or if we require write access) */
725 if (!removable || shared_write)
727 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
729 if (unaligned_mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
732 /* mmap() failed; if this is because the file offset is not */
733 /* page-aligned (EINVAL), or because the underlying filesystem */
734 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
735 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
736 if (shared_write) return FILE_GetNtStatus(); /* we cannot fake shared write mappings */
739 /* Reserve the memory with an anonymous mmap */
740 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
741 if (ptr == (void *)-1) return FILE_GetNtStatus();
742 /* Now read in the file */
743 pread( fd, ptr, size, offset );
744 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
746 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
747 return STATUS_SUCCESS;
751 /***********************************************************************
754 * Decommit some pages of a given view.
755 * The csVirtual section must be held by caller.
757 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
759 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
761 BYTE *p = view->prot + (start >> page_shift);
763 while (size--) *p++ &= ~VPROT_COMMITTED;
764 return STATUS_SUCCESS;
766 return FILE_GetNtStatus();
770 /***********************************************************************
773 * Apply the relocations to a mapped PE image
775 static int do_relocations( char *base, const IMAGE_DATA_DIRECTORY *dir,
776 int delta, SIZE_T total_size )
778 IMAGE_BASE_RELOCATION *rel;
780 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
781 base - delta, base - delta + total_size, base, base + total_size );
783 for (rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
784 ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
785 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock) )
787 char *page = base + rel->VirtualAddress;
788 WORD *TypeOffset = (WORD *)(rel + 1);
789 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
791 if (!count) continue;
794 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size)
796 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
797 rel, rel->VirtualAddress, rel->SizeOfBlock,
798 base, dir->VirtualAddress, dir->Size );
802 if (page > base + total_size)
804 WARN_(module)("skipping %d relocations for page %p beyond module %p-%p\n",
805 count, page, base, base + total_size );
809 TRACE_(module)("%d relocations for page %lx\n", count, rel->VirtualAddress);
811 /* patching in reverse order */
812 for (i = 0 ; i < count; i++)
814 int offset = TypeOffset[i] & 0xFFF;
815 int type = TypeOffset[i] >> 12;
818 case IMAGE_REL_BASED_ABSOLUTE:
820 case IMAGE_REL_BASED_HIGH:
821 *(short*)(page+offset) += HIWORD(delta);
823 case IMAGE_REL_BASED_LOW:
824 *(short*)(page+offset) += LOWORD(delta);
826 case IMAGE_REL_BASED_HIGHLOW:
827 *(int*)(page+offset) += delta;
828 /* FIXME: if this is an exported address, fire up enhanced logic */
831 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
840 /***********************************************************************
843 * Map an executable (PE format) image into memory.
845 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
846 SIZE_T header_size, int shared_fd, BOOL removable, PVOID *addr_ptr )
848 IMAGE_DOS_HEADER *dos;
849 IMAGE_NT_HEADERS *nt;
850 IMAGE_SECTION_HEADER *sec;
851 IMAGE_DATA_DIRECTORY *imports;
852 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
856 struct file_view *view = NULL;
857 char *ptr, *header_end;
859 /* zero-map the whole range */
861 RtlEnterCriticalSection( &csVirtual );
863 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
864 status = map_view( &view, base, total_size, mask,
865 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
867 if (status == STATUS_CONFLICTING_ADDRESSES)
868 status = map_view( &view, NULL, total_size, mask,
869 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
871 if (status != STATUS_SUCCESS) goto error;
874 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
878 if (fstat( fd, &st ) == -1)
880 status = FILE_GetNtStatus();
883 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
884 if (!st.st_size) goto error;
885 header_size = min( header_size, st.st_size );
886 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ,
887 removable ) != STATUS_SUCCESS) goto error;
888 dos = (IMAGE_DOS_HEADER *)ptr;
889 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
890 header_end = ptr + ROUND_SIZE( 0, header_size );
891 if ((char *)(nt + 1) > header_end) goto error;
892 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
893 if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
895 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
896 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
898 /* check the architecture */
900 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
902 MESSAGE("Trying to load PE image for unsupported architecture (");
903 switch (nt->FileHeader.Machine)
905 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
906 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
907 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
908 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
909 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
910 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
911 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
912 case IMAGE_FILE_MACHINE_IA64: MESSAGE("IA-64"); break;
913 case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
914 case IMAGE_FILE_MACHINE_AMD64: MESSAGE("AMD-64"); break;
915 case IMAGE_FILE_MACHINE_ARM: MESSAGE("ARM"); break;
916 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
922 /* check for non page-aligned binary */
924 if (nt->OptionalHeader.SectionAlignment <= page_mask)
926 /* unaligned sections, this happens for native subsystem binaries */
927 /* in that case Windows simply maps in the whole file */
929 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
930 removable ) != STATUS_SUCCESS) goto error;
932 /* check that all sections are loaded at the right offset */
933 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
935 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
936 goto error; /* Windows refuses to load in that case too */
939 /* set the image protections */
940 VIRTUAL_SetProt( view, ptr, total_size,
941 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
943 /* perform relocations if necessary */
944 /* FIXME: not 100% compatible, Windows doesn't do this for non page-aligned binaries */
947 const IMAGE_DATA_DIRECTORY *relocs;
948 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
949 if (relocs->VirtualAddress && relocs->Size)
950 do_relocations( ptr, relocs, ptr - base, total_size );
957 /* map all the sections */
959 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
961 SIZE_T map_size, file_size, end;
963 if (!sec->Misc.VirtualSize)
965 file_size = sec->SizeOfRawData;
966 map_size = ROUND_SIZE( 0, file_size );
970 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
971 file_size = min( sec->SizeOfRawData, map_size );
974 /* a few sanity checks */
975 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
976 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
978 ERR_(module)( "Section %.8s too large (%lx+%lx/%lx)\n",
979 sec->Name, sec->VirtualAddress, map_size, total_size );
983 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
984 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
986 TRACE_(module)( "mapping shared section %.8s at %p off %lx (%x) size %lx (%lx) flags %lx\n",
987 sec->Name, ptr + sec->VirtualAddress,
988 sec->PointerToRawData, (int)pos, file_size, map_size,
989 sec->Characteristics );
990 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
991 VPROT_COMMITTED | VPROT_READ | PROT_WRITE,
992 FALSE ) != STATUS_SUCCESS)
994 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
998 /* check if the import directory falls inside this section */
999 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1000 imports->VirtualAddress < sec->VirtualAddress + map_size)
1002 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1003 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1004 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1006 map_file_into_view( view, shared_fd, base, end - base,
1007 pos + (base - sec->VirtualAddress),
1008 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1015 TRACE_(module)( "mapping section %.8s at %p off %lx size %lx virt %lx flags %lx\n",
1016 sec->Name, ptr + sec->VirtualAddress,
1017 sec->PointerToRawData, sec->SizeOfRawData,
1018 sec->Misc.VirtualSize, sec->Characteristics );
1020 if (!sec->PointerToRawData || !file_size) continue;
1022 /* Note: if the section is not aligned properly map_file_into_view will magically
1023 * fall back to read(), so we don't need to check anything here.
1025 end = sec->PointerToRawData + file_size;
1026 if (sec->PointerToRawData >= st.st_size || end > st.st_size || end < sec->PointerToRawData ||
1027 map_file_into_view( view, fd, sec->VirtualAddress, file_size, sec->PointerToRawData,
1028 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1029 removable ) != STATUS_SUCCESS)
1031 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1035 if (file_size & page_mask)
1037 end = ROUND_SIZE( 0, file_size );
1038 if (end > map_size) end = map_size;
1039 TRACE_(module)("clearing %p - %p\n",
1040 ptr + sec->VirtualAddress + file_size,
1041 ptr + sec->VirtualAddress + end );
1042 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1047 /* perform base relocation, if necessary */
1051 const IMAGE_DATA_DIRECTORY *relocs;
1053 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1054 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1056 if (nt->OptionalHeader.ImageBase == 0x400000) {
1057 ERR("Image was mapped at %p: standard load address for a Win32 program (0x00400000) not available\n", ptr);
1058 ERR("Do you have exec-shield or prelink active?\n");
1060 ERR( "FATAL: Need to relocate module from addr %lx, but there are no relocation records\n",
1061 nt->OptionalHeader.ImageBase );
1065 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
1066 * really make sure that the *new* base address is also > 2GB.
1067 * Some DLLs really check the MSB of the module handle :-/
1069 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((ULONG_PTR)base & 0x80000000))
1070 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
1072 if (!do_relocations( ptr, relocs, ptr - base, total_size ))
1078 /* set the image protections */
1080 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1081 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1083 SIZE_T size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1084 BYTE vprot = VPROT_COMMITTED;
1085 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1086 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
1087 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1089 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1090 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1091 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1092 vprot |= VPROT_EXEC;
1094 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
1098 if (!removable) /* don't keep handle open on removable media */
1099 NtDuplicateObject( NtCurrentProcess(), hmapping,
1100 NtCurrentProcess(), &view->mapping,
1101 0, 0, DUPLICATE_SAME_ACCESS );
1103 RtlLeaveCriticalSection( &csVirtual );
1106 return STATUS_SUCCESS;
1109 if (view) delete_view( view );
1110 RtlLeaveCriticalSection( &csVirtual );
1115 /***********************************************************************
1116 * is_current_process
1118 * Check whether a process handle is for the current process.
1120 BOOL is_current_process( HANDLE handle )
1124 if (handle == NtCurrentProcess()) return TRUE;
1125 SERVER_START_REQ( get_process_info )
1127 req->handle = handle;
1128 if (!wine_server_call( req ))
1129 ret = ((DWORD)reply->pid == GetCurrentProcessId());
1136 /***********************************************************************
1139 static inline void virtual_init(void)
1142 page_size = getpagesize();
1143 page_mask = page_size - 1;
1144 /* Make sure we have a power of 2 */
1145 assert( !(page_size & page_mask) );
1147 while ((1 << page_shift) != page_size) page_shift++;
1148 #endif /* page_mask */
1152 /***********************************************************************
1155 * Allocate a memory view for a new TEB, properly aligned to a multiple of the size.
1157 NTSTATUS VIRTUAL_alloc_teb( void **ret, size_t size, BOOL first )
1160 struct file_view *view;
1163 if (first) virtual_init();
1166 size = ROUND_SIZE( 0, size );
1167 align_size = page_size;
1168 while (align_size < size) align_size *= 2;
1170 if (!first) RtlEnterCriticalSection( &csVirtual );
1172 status = map_view( &view, NULL, align_size, align_size - 1,
1173 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED );
1174 if (status == STATUS_SUCCESS)
1176 view->flags |= VFLAG_VALLOC;
1180 if (!first) RtlLeaveCriticalSection( &csVirtual );
1186 /***********************************************************************
1187 * VIRTUAL_HandleFault
1189 NTSTATUS VIRTUAL_HandleFault( LPCVOID addr )
1192 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1194 RtlEnterCriticalSection( &csVirtual );
1195 if ((view = VIRTUAL_FindView( addr )))
1197 void *page = ROUND_ADDR( addr, page_mask );
1198 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1199 if (vprot & VPROT_GUARD)
1201 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1202 ret = STATUS_GUARD_PAGE_VIOLATION;
1205 RtlLeaveCriticalSection( &csVirtual );
1209 /***********************************************************************
1210 * VIRTUAL_HasMapping
1212 * Check if the specified view has an associated file mapping.
1214 BOOL VIRTUAL_HasMapping( LPCVOID addr )
1219 RtlEnterCriticalSection( &csVirtual );
1220 if ((view = VIRTUAL_FindView( addr ))) ret = (view->mapping != 0);
1221 RtlLeaveCriticalSection( &csVirtual );
1226 /***********************************************************************
1227 * VIRTUAL_UseLargeAddressSpace
1229 * Increase the address space size for apps that support it.
1231 void VIRTUAL_UseLargeAddressSpace(void)
1233 if (user_space_limit >= ADDRESS_SPACE_LIMIT) return;
1234 /* no large address space on win9x */
1235 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1237 RtlEnterCriticalSection( &csVirtual );
1238 remove_reserved_area( user_space_limit, (char *)ADDRESS_SPACE_LIMIT - (char *)user_space_limit );
1239 user_space_limit = ADDRESS_SPACE_LIMIT;
1240 RtlLeaveCriticalSection( &csVirtual );
1244 /***********************************************************************
1245 * NtAllocateVirtualMemory (NTDLL.@)
1246 * ZwAllocateVirtualMemory (NTDLL.@)
1248 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1249 SIZE_T *size_ptr, ULONG type, ULONG protect )
1253 SIZE_T size = *size_ptr;
1254 SIZE_T mask = get_mask( zero_bits );
1255 NTSTATUS status = STATUS_SUCCESS;
1256 struct file_view *view;
1258 TRACE("%p %p %08lx %lx %08lx\n", process, *ret, size, type, protect );
1260 if (!size) return STATUS_INVALID_PARAMETER;
1262 if (!is_current_process( process ))
1264 ERR("Unsupported on other process\n");
1265 return STATUS_ACCESS_DENIED;
1268 /* Round parameters to a page boundary */
1270 if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
1274 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1275 base = ROUND_ADDR( *ret, mask );
1277 base = ROUND_ADDR( *ret, page_mask );
1278 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1280 /* disallow low 64k, wrap-around and kernel space */
1281 if (((char *)base < (char *)0x10000) ||
1282 ((char *)base + size < (char *)base) ||
1283 is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
1284 return STATUS_INVALID_PARAMETER;
1289 size = (size + page_mask) & ~page_mask;
1292 if (type & MEM_TOP_DOWN) {
1293 /* FIXME: MEM_TOP_DOWN allocates the largest possible address. */
1294 WARN("MEM_TOP_DOWN ignored\n");
1295 type &= ~MEM_TOP_DOWN;
1298 /* Compute the alloc type flags */
1300 if (!(type & MEM_SYSTEM))
1302 if (!(type & (MEM_COMMIT | MEM_RESERVE)) || (type & ~(MEM_COMMIT | MEM_RESERVE)))
1304 WARN("called with wrong alloc type flags (%08lx) !\n", type);
1305 return STATUS_INVALID_PARAMETER;
1308 vprot = VIRTUAL_GetProt( protect );
1309 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1311 /* Reserve the memory */
1313 RtlEnterCriticalSection( &csVirtual );
1315 if (type & MEM_SYSTEM)
1317 if (type & MEM_IMAGE) vprot |= VPROT_IMAGE;
1318 status = create_view( &view, base, size, vprot | VPROT_COMMITTED );
1319 if (status == STATUS_SUCCESS)
1321 view->flags |= VFLAG_VALLOC | VFLAG_SYSTEM;
1325 else if ((type & MEM_RESERVE) || !base)
1327 status = map_view( &view, base, size, mask, vprot );
1328 if (status == STATUS_SUCCESS)
1330 view->flags |= VFLAG_VALLOC;
1334 else /* commit the pages */
1336 if (!(view = VIRTUAL_FindView( base )) ||
1337 ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
1338 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1341 RtlLeaveCriticalSection( &csVirtual );
1343 if (status == STATUS_SUCCESS)
1352 /***********************************************************************
1353 * NtFreeVirtualMemory (NTDLL.@)
1354 * ZwFreeVirtualMemory (NTDLL.@)
1356 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1360 NTSTATUS status = STATUS_SUCCESS;
1361 LPVOID addr = *addr_ptr;
1362 SIZE_T size = *size_ptr;
1364 TRACE("%p %p %08lx %lx\n", process, addr, size, type );
1366 if (!is_current_process( process ))
1368 ERR("Unsupported on other process\n");
1369 return STATUS_ACCESS_DENIED;
1372 /* Fix the parameters */
1374 size = ROUND_SIZE( addr, size );
1375 base = ROUND_ADDR( addr, page_mask );
1377 RtlEnterCriticalSection(&csVirtual);
1379 if (!(view = VIRTUAL_FindView( base )) ||
1380 (base + size > (char *)view->base + view->size) ||
1381 !(view->flags & VFLAG_VALLOC))
1383 status = STATUS_INVALID_PARAMETER;
1385 else if (type & MEM_SYSTEM)
1387 /* return the values that the caller should use to unmap the area */
1388 *addr_ptr = view->base;
1389 if (!wine_mmap_is_in_reserved_area( view->base, view->size )) *size_ptr = view->size;
1390 else *size_ptr = 0; /* make sure we don't munmap anything from a reserved area */
1391 view->flags |= VFLAG_SYSTEM;
1392 delete_view( view );
1394 else if (type == MEM_RELEASE)
1396 /* Free the pages */
1398 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1401 delete_view( view );
1406 else if (type == MEM_DECOMMIT)
1408 status = decommit_pages( view, base - (char *)view->base, size );
1409 if (status == STATUS_SUCCESS)
1417 WARN("called with wrong free type flags (%08lx) !\n", type);
1418 status = STATUS_INVALID_PARAMETER;
1421 RtlLeaveCriticalSection(&csVirtual);
1426 /***********************************************************************
1427 * NtProtectVirtualMemory (NTDLL.@)
1428 * ZwProtectVirtualMemory (NTDLL.@)
1430 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1431 ULONG new_prot, ULONG *old_prot )
1434 NTSTATUS status = STATUS_SUCCESS;
1439 SIZE_T size = *size_ptr;
1440 LPVOID addr = *addr_ptr;
1442 TRACE("%p %p %08lx %08lx\n", process, addr, size, new_prot );
1444 if (!is_current_process( process ))
1446 ERR("Unsupported on other process\n");
1447 return STATUS_ACCESS_DENIED;
1450 /* Fix the parameters */
1452 size = ROUND_SIZE( addr, size );
1453 base = ROUND_ADDR( addr, page_mask );
1455 RtlEnterCriticalSection( &csVirtual );
1457 if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1459 status = STATUS_INVALID_PARAMETER;
1463 /* Make sure all the pages are committed */
1465 p = view->prot + ((base - (char *)view->base) >> page_shift);
1466 prot = VIRTUAL_GetWin32Prot( *p );
1467 for (i = size >> page_shift; i; i--, p++)
1469 if (!(*p & VPROT_COMMITTED))
1471 status = STATUS_NOT_COMMITTED;
1477 if (old_prot) *old_prot = prot;
1478 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1479 if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1482 RtlLeaveCriticalSection( &csVirtual );
1484 if (status == STATUS_SUCCESS)
1492 #define UNIMPLEMENTED_INFO_CLASS(c) \
1494 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
1495 return STATUS_INVALID_INFO_CLASS
1497 /***********************************************************************
1498 * NtQueryVirtualMemory (NTDLL.@)
1499 * ZwQueryVirtualMemory (NTDLL.@)
1501 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1502 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1503 SIZE_T len, SIZE_T *res_len )
1506 char *base, *alloc_base = 0;
1509 MEMORY_BASIC_INFORMATION *info = buffer;
1511 if (info_class != MemoryBasicInformation)
1515 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
1516 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
1517 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
1520 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
1521 process, addr, info_class, buffer, len, res_len);
1522 return STATUS_INVALID_INFO_CLASS;
1525 if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1526 return STATUS_WORKING_SET_LIMIT_RANGE;
1528 if (!is_current_process( process ))
1530 ERR("Unsupported on other process\n");
1531 return STATUS_ACCESS_DENIED;
1534 base = ROUND_ADDR( addr, page_mask );
1536 /* Find the view containing the address */
1538 RtlEnterCriticalSection(&csVirtual);
1539 ptr = list_head( &views_list );
1544 /* make the address space end at the user limit, except if
1545 * the last view was mapped beyond that */
1546 if (alloc_base <= (char *)user_space_limit)
1548 if (user_space_limit && base >= (char *)user_space_limit)
1550 RtlLeaveCriticalSection( &csVirtual );
1551 return STATUS_WORKING_SET_LIMIT_RANGE;
1553 size = (char *)user_space_limit - alloc_base;
1555 else size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1559 view = LIST_ENTRY( ptr, struct file_view, entry );
1560 if ((char *)view->base > base)
1562 size = (char *)view->base - alloc_base;
1566 if ((char *)view->base + view->size > base)
1568 alloc_base = view->base;
1572 alloc_base = (char *)view->base + view->size;
1573 ptr = list_next( &views_list, ptr );
1576 /* Fill the info structure */
1580 info->State = MEM_FREE;
1582 info->AllocationProtect = 0;
1587 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1588 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
1589 info->Protect = VIRTUAL_GetWin32Prot( vprot );
1590 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
1591 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1592 else if (view->flags & VFLAG_VALLOC) info->Type = MEM_PRIVATE;
1593 else info->Type = MEM_MAPPED;
1594 for (size = base - alloc_base; size < view->size; size += page_size)
1595 if (view->prot[size >> page_shift] != vprot) break;
1597 RtlLeaveCriticalSection(&csVirtual);
1599 info->BaseAddress = (LPVOID)base;
1600 info->AllocationBase = (LPVOID)alloc_base;
1601 info->RegionSize = size - (base - alloc_base);
1602 if (res_len) *res_len = sizeof(*info);
1603 return STATUS_SUCCESS;
1607 /***********************************************************************
1608 * NtLockVirtualMemory (NTDLL.@)
1609 * ZwLockVirtualMemory (NTDLL.@)
1611 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1613 if (!is_current_process( process ))
1615 ERR("Unsupported on other process\n");
1616 return STATUS_ACCESS_DENIED;
1618 return STATUS_SUCCESS;
1622 /***********************************************************************
1623 * NtUnlockVirtualMemory (NTDLL.@)
1624 * ZwUnlockVirtualMemory (NTDLL.@)
1626 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1628 if (!is_current_process( process ))
1630 ERR("Unsupported on other process\n");
1631 return STATUS_ACCESS_DENIED;
1633 return STATUS_SUCCESS;
1637 /***********************************************************************
1638 * NtCreateSection (NTDLL.@)
1639 * ZwCreateSection (NTDLL.@)
1641 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1642 const LARGE_INTEGER *size, ULONG protect,
1643 ULONG sec_flags, HANDLE file )
1647 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
1649 /* Check parameters */
1651 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1653 vprot = VIRTUAL_GetProt( protect );
1654 if (sec_flags & SEC_RESERVE)
1656 if (file) return STATUS_INVALID_PARAMETER;
1658 else vprot |= VPROT_COMMITTED;
1659 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1660 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
1662 /* Create the server object */
1664 SERVER_START_REQ( create_mapping )
1666 req->access = access;
1667 req->attributes = (attr) ? attr->Attributes : 0;
1668 req->rootdir = attr ? attr->RootDirectory : 0;
1669 req->file_handle = file;
1670 req->size_high = size ? size->u.HighPart : 0;
1671 req->size_low = size ? size->u.LowPart : 0;
1672 req->protect = vprot;
1673 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
1674 ret = wine_server_call( req );
1675 *handle = reply->handle;
1682 /***********************************************************************
1683 * NtOpenSection (NTDLL.@)
1684 * ZwOpenSection (NTDLL.@)
1686 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1689 DWORD len = attr->ObjectName->Length;
1691 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1693 SERVER_START_REQ( open_mapping )
1695 req->access = access;
1696 req->attributes = (attr) ? attr->Attributes : 0;
1697 req->rootdir = attr ? attr->RootDirectory : 0;
1698 wine_server_add_data( req, attr->ObjectName->Buffer, len );
1699 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
1706 /***********************************************************************
1707 * NtMapViewOfSection (NTDLL.@)
1708 * ZwMapViewOfSection (NTDLL.@)
1710 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
1711 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
1712 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
1714 FILE_FS_DEVICE_INFORMATION device_info;
1717 SIZE_T mask = get_mask( zero_bits );
1718 int unix_handle = -1;
1721 struct file_view *view;
1722 DWORD size_low, size_high, header_size, shared_size;
1724 BOOL removable = FALSE;
1725 LARGE_INTEGER offset;
1727 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
1729 TRACE("handle=%p process=%p addr=%p off=%lx%08lx size=%lx access=%lx\n",
1730 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, size, protect );
1732 if (!is_current_process( process ))
1734 ERR("Unsupported on other process\n");
1735 return STATUS_ACCESS_DENIED;
1738 /* Check parameters */
1740 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
1741 return STATUS_INVALID_PARAMETER;
1743 SERVER_START_REQ( get_mapping_info )
1745 req->handle = handle;
1746 res = wine_server_call( req );
1747 prot = reply->protect;
1749 size_low = reply->size_low;
1750 size_high = reply->size_high;
1751 header_size = reply->header_size;
1752 shared_file = reply->shared_file;
1753 shared_size = reply->shared_size;
1756 if (res) return res;
1758 if ((res = wine_server_handle_to_fd( handle, 0, &unix_handle, NULL ))) return res;
1760 if (FILE_GetDeviceInfo( unix_handle, &device_info ) == STATUS_SUCCESS)
1761 removable = device_info.Characteristics & FILE_REMOVABLE_MEDIA;
1763 if (prot & VPROT_IMAGE)
1769 if ((res = wine_server_handle_to_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
1770 &shared_fd, NULL ))) goto done;
1771 res = map_image( handle, unix_handle, base, size_low, mask, header_size,
1772 shared_fd, removable, addr_ptr );
1773 wine_server_release_fd( shared_file, shared_fd );
1774 NtClose( shared_file );
1778 res = map_image( handle, unix_handle, base, size_low, mask, header_size,
1779 -1, removable, addr_ptr );
1781 wine_server_release_fd( handle, unix_handle );
1782 if (!res) *size_ptr = size_low;
1787 ERR("Sizes larger than 4Gb not supported\n");
1789 if ((offset.u.LowPart >= size_low) ||
1790 (*size_ptr > size_low - offset.u.LowPart))
1792 res = STATUS_INVALID_PARAMETER;
1795 if (*size_ptr) size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
1796 else size = size_low - offset.u.LowPart;
1802 case PAGE_READWRITE:
1803 case PAGE_EXECUTE_READWRITE:
1804 if (!(prot & VPROT_WRITE))
1806 res = STATUS_INVALID_PARAMETER;
1812 case PAGE_WRITECOPY:
1814 case PAGE_EXECUTE_READ:
1815 case PAGE_EXECUTE_WRITECOPY:
1816 if (prot & VPROT_READ) break;
1819 res = STATUS_INVALID_PARAMETER;
1823 /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1824 * which has a view of this mapping commits some pages, they will
1825 * appear commited in all other processes, which have the same
1826 * view created. Since we don`t support this yet, we create the
1827 * whole mapping commited.
1829 prot |= VPROT_COMMITTED;
1831 /* Reserve a properly aligned area */
1833 RtlEnterCriticalSection( &csVirtual );
1835 res = map_view( &view, *addr_ptr, size, mask, prot );
1838 RtlLeaveCriticalSection( &csVirtual );
1844 TRACE("handle=%p size=%lx offset=%lx%08lx\n",
1845 handle, size, offset.u.HighPart, offset.u.LowPart );
1847 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, prot, removable );
1848 if (res == STATUS_SUCCESS)
1850 if (!removable) /* don't keep handle open on removable media */
1851 NtDuplicateObject( NtCurrentProcess(), handle,
1852 NtCurrentProcess(), &view->mapping,
1853 0, 0, DUPLICATE_SAME_ACCESS );
1855 *addr_ptr = view->base;
1860 ERR( "map_file_into_view %p %lx %lx%08lx failed\n",
1861 view->base, size, offset.u.HighPart, offset.u.LowPart );
1862 delete_view( view );
1865 RtlLeaveCriticalSection( &csVirtual );
1868 wine_server_release_fd( handle, unix_handle );
1873 /***********************************************************************
1874 * NtUnmapViewOfSection (NTDLL.@)
1875 * ZwUnmapViewOfSection (NTDLL.@)
1877 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
1880 NTSTATUS status = STATUS_INVALID_PARAMETER;
1881 void *base = ROUND_ADDR( addr, page_mask );
1883 if (!is_current_process( process ))
1885 ERR("Unsupported on other process\n");
1886 return STATUS_ACCESS_DENIED;
1888 RtlEnterCriticalSection( &csVirtual );
1889 if ((view = VIRTUAL_FindView( base )) && (base == view->base))
1891 delete_view( view );
1892 status = STATUS_SUCCESS;
1894 RtlLeaveCriticalSection( &csVirtual );
1899 /***********************************************************************
1900 * NtFlushVirtualMemory (NTDLL.@)
1901 * ZwFlushVirtualMemory (NTDLL.@)
1903 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
1904 SIZE_T *size_ptr, ULONG unknown )
1907 NTSTATUS status = STATUS_SUCCESS;
1908 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
1910 if (!is_current_process( process ))
1912 ERR("Unsupported on other process\n");
1913 return STATUS_ACCESS_DENIED;
1915 RtlEnterCriticalSection( &csVirtual );
1916 if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
1919 if (!*size_ptr) *size_ptr = view->size;
1921 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
1923 RtlLeaveCriticalSection( &csVirtual );
1928 /***********************************************************************
1929 * NtReadVirtualMemory (NTDLL.@)
1930 * ZwReadVirtualMemory (NTDLL.@)
1932 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
1933 SIZE_T size, SIZE_T *bytes_read )
1937 SERVER_START_REQ( read_process_memory )
1939 req->handle = process;
1940 req->addr = (void *)addr;
1941 wine_server_set_reply( req, buffer, size );
1942 if ((status = wine_server_call( req ))) size = 0;
1945 if (bytes_read) *bytes_read = size;
1950 /***********************************************************************
1951 * NtWriteVirtualMemory (NTDLL.@)
1952 * ZwWriteVirtualMemory (NTDLL.@)
1954 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
1955 SIZE_T size, SIZE_T *bytes_written )
1959 SERVER_START_REQ( write_process_memory )
1961 req->handle = process;
1963 wine_server_add_data( req, buffer, size );
1964 if ((status = wine_server_call( req ))) size = 0;
1967 if (bytes_written) *bytes_written = size;