2 * Win32 virtual memory functions
4 * Copyright 1997, 2002 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "wine/port.h"
26 #ifdef HAVE_SYS_ERRNO_H
27 #include <sys/errno.h>
36 #include <sys/types.h>
37 #ifdef HAVE_SYS_MMAN_H
41 #define NONAMELESSUNION
42 #define NONAMELESSSTRUCT
47 #include "wine/library.h"
48 #include "wine/server.h"
49 #include "wine/list.h"
50 #include "wine/debug.h"
51 #include "ntdll_misc.h"
53 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
54 WINE_DECLARE_DEBUG_CHANNEL(module);
61 #define MAP_NORESERVE 0
65 typedef struct file_view
67 struct list entry; /* Entry in global view list */
68 void *base; /* Base address */
69 UINT size; /* Size in bytes */
70 HANDLE mapping; /* Handle to the file mapping */
71 HANDLERPROC handlerProc; /* Fault handler */
72 LPVOID handlerArg; /* Fault handler argument */
73 BYTE flags; /* Allocation flags (VFLAG_*) */
74 BYTE protect; /* Protection for all pages at allocation time */
75 BYTE prot[1]; /* Protection byte for each page */
79 #define VFLAG_SYSTEM 0x01 /* system view (underlying mmap not under our control) */
80 #define VFLAG_VALLOC 0x02 /* allocated by VirtualAlloc */
82 /* Conversion from VPROT_* to Win32 flags */
83 static const BYTE VIRTUAL_Win32Flags[16] =
85 PAGE_NOACCESS, /* 0 */
86 PAGE_READONLY, /* READ */
87 PAGE_READWRITE, /* WRITE */
88 PAGE_READWRITE, /* READ | WRITE */
89 PAGE_EXECUTE, /* EXEC */
90 PAGE_EXECUTE_READ, /* READ | EXEC */
91 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
92 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
93 PAGE_WRITECOPY, /* WRITECOPY */
94 PAGE_WRITECOPY, /* READ | WRITECOPY */
95 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
96 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
97 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
98 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
99 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
100 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
103 static struct list views_list = LIST_INIT(views_list);
105 static CRITICAL_SECTION csVirtual;
106 static CRITICAL_SECTION_DEBUG critsect_debug =
109 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
110 0, 0, { 0, (DWORD)(__FILE__ ": csVirtual") }
112 static CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
115 /* These are always the same on an i386, and it will be faster this way */
116 # define page_mask 0xfff
117 # define page_shift 12
118 # define page_size 0x1000
119 /* Note: these are Windows limits, you cannot change them. */
120 # define ADDRESS_SPACE_LIMIT ((void *)0xc0000000) /* top of the total available address space */
121 # define USER_SPACE_LIMIT ((void *)0x80000000) /* top of the user address space */
123 static UINT page_shift;
124 static UINT page_mask;
125 static UINT page_size;
126 # define ADDRESS_SPACE_LIMIT 0 /* no limit needed on other platforms */
127 # define USER_SPACE_LIMIT 0 /* no limit needed on other platforms */
128 #endif /* __i386__ */
129 #define granularity_mask 0xffff /* Allocation granularity (usually 64k) */
131 #define ROUND_ADDR(addr,mask) \
132 ((void *)((UINT_PTR)(addr) & ~(mask)))
134 #define ROUND_SIZE(addr,size) \
135 (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
137 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
138 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
141 /***********************************************************************
144 static const char *VIRTUAL_GetProtStr( BYTE prot )
146 static char buffer[6];
147 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
148 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
149 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
150 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
151 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
157 /***********************************************************************
160 static void VIRTUAL_DumpView( FILE_VIEW *view )
163 char *addr = view->base;
164 BYTE prot = view->prot[0];
166 DPRINTF( "View: %p - %p", addr, addr + view->size - 1 );
167 if (view->flags & VFLAG_SYSTEM)
168 DPRINTF( " (system)\n" );
169 else if (view->flags & VFLAG_VALLOC)
170 DPRINTF( " (valloc)\n" );
171 else if (view->mapping)
172 DPRINTF( " %p\n", view->mapping );
174 DPRINTF( " (anonymous)\n");
176 for (count = i = 1; i < view->size >> page_shift; i++, count++)
178 if (view->prot[i] == prot) continue;
179 DPRINTF( " %p - %p %s\n",
180 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
181 addr += (count << page_shift);
182 prot = view->prot[i];
186 DPRINTF( " %p - %p %s\n",
187 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
191 /***********************************************************************
194 void VIRTUAL_Dump(void)
198 DPRINTF( "\nDump of all virtual memory views:\n\n" );
199 RtlEnterCriticalSection(&csVirtual);
200 LIST_FOR_EACH( ptr, &views_list )
202 VIRTUAL_DumpView( LIST_ENTRY( ptr, struct file_view, entry ) );
204 RtlLeaveCriticalSection(&csVirtual);
208 /***********************************************************************
211 * Find the view containing a given address. The csVirtual section must be held by caller.
217 static struct file_view *VIRTUAL_FindView( const void *addr ) /* [in] Address */
221 LIST_FOR_EACH( ptr, &views_list )
223 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
224 if (view->base > addr) break;
225 if ((char *)view->base + view->size > (const char *)addr) return view;
231 /***********************************************************************
234 * Find the first view overlapping at least part of the specified range.
235 * The csVirtual section must be held by caller.
237 static struct file_view *find_view_range( const void *addr, size_t size )
241 LIST_FOR_EACH( ptr, &views_list )
243 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
244 if ((char *)view->base >= (const char *)addr + size) break;
245 if ((char *)view->base + view->size > (const char *)addr) return view;
251 /***********************************************************************
254 * Add a reserved area to the list maintained by libwine.
255 * The csVirtual section must be held by caller.
257 static void add_reserved_area( void *addr, size_t size )
259 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
261 if (addr < USER_SPACE_LIMIT)
263 /* unmap the part of the area that is below the limit */
264 assert( (char *)addr + size > (char *)USER_SPACE_LIMIT );
265 munmap( addr, (char *)USER_SPACE_LIMIT - (char *)addr );
266 size -= (char *)USER_SPACE_LIMIT - (char *)addr;
267 addr = USER_SPACE_LIMIT;
269 wine_mmap_add_reserved_area( addr, size );
273 /***********************************************************************
276 * Check if an address range goes beyond a given limit.
278 static inline int is_beyond_limit( void *addr, size_t size, void *limit )
280 return (limit && (addr >= limit || (char *)addr + size > (char *)limit));
284 /***********************************************************************
287 * Unmap an area, or simply replace it by an empty mapping if it is
288 * in a reserved area. The csVirtual section must be held by caller.
290 static inline void unmap_area( void *addr, size_t size )
292 if (wine_mmap_is_in_reserved_area( addr, size ))
293 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
295 munmap( addr, size );
299 /***********************************************************************
302 * Deletes a view. The csVirtual section must be held by caller.
304 static void delete_view( struct file_view *view ) /* [in] View */
306 if (!(view->flags & VFLAG_SYSTEM)) unmap_area( view->base, view->size );
307 list_remove( &view->entry );
308 if (view->mapping) NtClose( view->mapping );
313 /***********************************************************************
316 * Create a view. The csVirtual section must be held by caller.
318 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, BYTE vprot )
320 struct file_view *view;
323 assert( !((unsigned int)base & page_mask) );
324 assert( !(size & page_mask) );
326 /* Create the view structure */
328 if (!(view = malloc( sizeof(*view) + (size >> page_shift) - 1 ))) return STATUS_NO_MEMORY;
334 view->protect = vprot;
335 view->handlerProc = NULL;
336 memset( view->prot, vprot, size >> page_shift );
338 /* Insert it in the linked list */
340 LIST_FOR_EACH( ptr, &views_list )
342 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
343 if (next->base > base) break;
345 list_add_before( ptr, &view->entry );
347 /* Check for overlapping views. This can happen if the previous view
348 * was a system view that got unmapped behind our back. In that case
349 * we recover by simply deleting it. */
351 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
353 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
354 if ((char *)prev->base + prev->size > (char *)base)
356 TRACE( "overlapping prev view %p-%p for %p-%p\n",
357 prev->base, (char *)prev->base + prev->size,
358 base, (char *)base + view->size );
359 assert( prev->flags & VFLAG_SYSTEM );
363 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
365 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
366 if ((char *)base + view->size > (char *)next->base)
368 TRACE( "overlapping next view %p-%p for %p-%p\n",
369 next->base, (char *)next->base + next->size,
370 base, (char *)base + view->size );
371 assert( next->flags & VFLAG_SYSTEM );
377 VIRTUAL_DEBUG_DUMP_VIEW( view );
378 return STATUS_SUCCESS;
382 /***********************************************************************
383 * VIRTUAL_GetUnixProt
385 * Convert page protections to protection for mmap/mprotect.
387 static int VIRTUAL_GetUnixProt( BYTE vprot )
390 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
392 if (vprot & VPROT_READ) prot |= PROT_READ;
393 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
394 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
395 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
401 /***********************************************************************
402 * VIRTUAL_GetWin32Prot
404 * Convert page protections to Win32 flags.
409 static void VIRTUAL_GetWin32Prot(
410 BYTE vprot, /* [in] Page protection flags */
411 DWORD *protect, /* [out] Location to store Win32 protection flags */
412 DWORD *state ) /* [out] Location to store mem state flag */
415 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
416 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
417 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
419 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
422 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
426 /***********************************************************************
429 * Build page protections from Win32 flags.
432 * Value of page protection flags
434 static BYTE VIRTUAL_GetProt( DWORD protect ) /* [in] Win32 protection flags */
438 switch(protect & 0xff)
444 vprot = VPROT_READ | VPROT_WRITE;
447 /* MSDN CreateFileMapping() states that if PAGE_WRITECOPY is given,
448 * that the hFile must have been opened with GENERIC_READ and
449 * GENERIC_WRITE access. This is WRONG as tests show that you
450 * only need GENERIC_READ access (at least for Win9x,
451 * FIXME: what about NT?). Thus, we don't put VPROT_WRITE in
452 * PAGE_WRITECOPY and PAGE_EXECUTE_WRITECOPY.
454 vprot = VPROT_READ | VPROT_WRITECOPY;
459 case PAGE_EXECUTE_READ:
460 vprot = VPROT_EXEC | VPROT_READ;
462 case PAGE_EXECUTE_READWRITE:
463 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
465 case PAGE_EXECUTE_WRITECOPY:
466 /* See comment for PAGE_WRITECOPY above */
467 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
474 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
475 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
480 /***********************************************************************
483 * Change the protection of a range of pages.
489 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
490 void *base, /* [in] Starting address */
491 UINT size, /* [in] Size in bytes */
492 BYTE vprot ) /* [in] Protections to use */
495 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
497 if (mprotect( base, size, VIRTUAL_GetUnixProt(vprot) ))
498 return FALSE; /* FIXME: last error */
500 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
501 vprot, size >> page_shift );
502 VIRTUAL_DEBUG_DUMP_VIEW( view );
507 /***********************************************************************
510 * Create a view and mmap the corresponding memory area.
511 * The csVirtual section must be held by caller.
513 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, BYTE vprot )
520 if (is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
521 return STATUS_WORKING_SET_LIMIT_RANGE;
523 switch (wine_mmap_is_in_reserved_area( base, size ))
525 case -1: /* partially in a reserved area */
526 return STATUS_CONFLICTING_ADDRESSES;
528 case 0: /* not in a reserved area, do a normal allocation */
529 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
531 if (errno == ENOMEM) return STATUS_NO_MEMORY;
532 return STATUS_INVALID_PARAMETER;
536 /* We couldn't get the address we wanted */
537 if (is_beyond_limit( ptr, size, USER_SPACE_LIMIT )) add_reserved_area( ptr, size );
538 else munmap( ptr, size );
539 return STATUS_CONFLICTING_ADDRESSES;
544 case 1: /* in a reserved area, make sure the address is available */
545 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
546 /* replace the reserved area by our mapping */
547 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
548 return STATUS_INVALID_PARAMETER;
554 size_t view_size = size + granularity_mask + 1;
558 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
560 if (errno == ENOMEM) return STATUS_NO_MEMORY;
561 return STATUS_INVALID_PARAMETER;
563 /* if we got something beyond the user limit, unmap it and retry */
564 if (is_beyond_limit( ptr, view_size, USER_SPACE_LIMIT )) add_reserved_area( ptr, view_size );
568 /* Release the extra memory while keeping the range
569 * starting on the granularity boundary. */
570 if ((unsigned int)ptr & granularity_mask)
572 unsigned int extra = granularity_mask + 1 - ((unsigned int)ptr & granularity_mask);
573 munmap( ptr, extra );
574 ptr = (char *)ptr + extra;
577 if (view_size > size)
578 munmap( (char *)ptr + size, view_size - size );
581 status = create_view( view_ret, ptr, size, vprot );
582 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
587 /***********************************************************************
590 * Linux kernels before 2.4.x can support non page-aligned offsets, as
591 * long as the offset is aligned to the filesystem block size. This is
592 * a big performance gain so we want to take advantage of it.
594 * However, when we use 64-bit file support this doesn't work because
595 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
596 * in that it rounds unaligned offsets down to a page boundary. For
597 * these reasons we do a direct system call here.
599 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
600 unsigned int flags, int fd, off_t offset )
602 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
603 if (!(offset >> 32) && (offset & page_mask))
618 args.length = length;
622 args.offset = offset;
624 __asm__ __volatile__("push %%ebx\n\t"
629 : "0" (90), /* SYS_mmap */
632 if (ret < 0 && ret > -4096)
640 return mmap( addr, length, prot, flags, fd, offset );
644 /***********************************************************************
647 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
648 * The csVirtual section must be held by caller.
650 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
651 off_t offset, BYTE vprot, BOOL removable )
654 int prot = VIRTUAL_GetUnixProt( vprot );
655 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
657 assert( start < view->size );
658 assert( start + size <= view->size );
660 /* only try mmap if media is not removable (or if we require write access) */
661 if (!removable || shared_write)
663 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
665 if (unaligned_mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
668 /* mmap() failed; if this is because the file offset is not */
669 /* page-aligned (EINVAL), or because the underlying filesystem */
670 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
671 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
672 if (shared_write) return FILE_GetNtStatus(); /* we cannot fake shared write mappings */
675 /* Reserve the memory with an anonymous mmap */
676 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
677 if (ptr == (void *)-1) return FILE_GetNtStatus();
678 /* Now read in the file */
679 pread( fd, ptr, size, offset );
680 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
682 memset( view->prot + (start >> page_shift), vprot, size >> page_shift );
683 return STATUS_SUCCESS;
687 /***********************************************************************
690 * Decommit some pages of a given view.
691 * The csVirtual section must be held by caller.
693 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
695 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
697 BYTE *p = view->prot + (start >> page_shift);
699 while (size--) *p++ &= ~VPROT_COMMITTED;
700 return STATUS_SUCCESS;
702 return FILE_GetNtStatus();
706 /***********************************************************************
709 * Apply the relocations to a mapped PE image
711 static int do_relocations( char *base, const IMAGE_DATA_DIRECTORY *dir,
712 int delta, DWORD total_size )
714 IMAGE_BASE_RELOCATION *rel;
716 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
717 base - delta, base - delta + total_size, base, base + total_size );
719 for (rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
720 ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
721 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock) )
723 char *page = base + rel->VirtualAddress;
724 WORD *TypeOffset = (WORD *)(rel + 1);
725 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
727 if (!count) continue;
730 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
731 page > base + total_size)
733 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
734 rel, rel->VirtualAddress, rel->SizeOfBlock,
735 base, dir->VirtualAddress, dir->Size );
739 TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
741 /* patching in reverse order */
742 for (i = 0 ; i < count; i++)
744 int offset = TypeOffset[i] & 0xFFF;
745 int type = TypeOffset[i] >> 12;
748 case IMAGE_REL_BASED_ABSOLUTE:
750 case IMAGE_REL_BASED_HIGH:
751 *(short*)(page+offset) += HIWORD(delta);
753 case IMAGE_REL_BASED_LOW:
754 *(short*)(page+offset) += LOWORD(delta);
756 case IMAGE_REL_BASED_HIGHLOW:
757 *(int*)(page+offset) += delta;
758 /* FIXME: if this is an exported address, fire up enhanced logic */
761 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
770 /***********************************************************************
773 * Map an executable (PE format) image into memory.
775 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, DWORD total_size,
776 DWORD header_size, int shared_fd, BOOL removable, PVOID *addr_ptr )
778 IMAGE_DOS_HEADER *dos;
779 IMAGE_NT_HEADERS *nt;
780 IMAGE_SECTION_HEADER *sec;
781 IMAGE_DATA_DIRECTORY *imports;
782 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
785 struct file_view *view = NULL;
788 /* zero-map the whole range */
790 RtlEnterCriticalSection( &csVirtual );
792 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
793 status = map_view( &view, base, total_size,
794 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
796 if (status == STATUS_CONFLICTING_ADDRESSES)
797 status = map_view( &view, NULL, total_size,
798 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
800 if (status != STATUS_SUCCESS) goto error;
803 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
807 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
808 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ,
809 removable ) != STATUS_SUCCESS) goto error;
810 dos = (IMAGE_DOS_HEADER *)ptr;
811 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
812 if ((char *)(nt + 1) > ptr + header_size) goto error;
814 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
815 if ((char *)(sec + nt->FileHeader.NumberOfSections) > ptr + header_size) goto error;
817 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
818 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
820 /* check the architecture */
822 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
824 MESSAGE("Trying to load PE image for unsupported architecture (");
825 switch (nt->FileHeader.Machine)
827 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
828 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
829 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
830 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
831 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
832 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
833 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
834 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
840 /* map all the sections */
842 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
846 /* a few sanity checks */
847 size = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
848 if (sec->VirtualAddress > total_size || size > total_size || size < sec->VirtualAddress)
850 ERR_(module)( "Section %.8s too large (%lx+%lx/%lx)\n",
851 sec->Name, sec->VirtualAddress, sec->Misc.VirtualSize, total_size );
855 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
856 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
858 size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
859 TRACE_(module)( "mapping shared section %.8s at %p off %lx (%x) size %lx (%lx) flags %lx\n",
860 sec->Name, ptr + sec->VirtualAddress,
861 sec->PointerToRawData, (int)pos, sec->SizeOfRawData,
862 size, sec->Characteristics );
863 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, size, pos,
864 VPROT_COMMITTED | VPROT_READ | PROT_WRITE,
865 FALSE ) != STATUS_SUCCESS)
867 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
871 /* check if the import directory falls inside this section */
872 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
873 imports->VirtualAddress < sec->VirtualAddress + size)
875 UINT_PTR base = imports->VirtualAddress & ~page_mask;
876 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
877 if (end > sec->VirtualAddress + size) end = sec->VirtualAddress + size;
879 map_file_into_view( view, shared_fd, base, end - base,
880 pos + (base - sec->VirtualAddress),
881 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
888 TRACE_(module)( "mapping section %.8s at %p off %lx size %lx flags %lx\n",
889 sec->Name, ptr + sec->VirtualAddress,
890 sec->PointerToRawData, sec->SizeOfRawData,
891 sec->Characteristics );
893 if ((sec->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) &&
894 !(sec->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)) continue;
895 if (!sec->PointerToRawData || !sec->SizeOfRawData) continue;
897 /* Note: if the section is not aligned properly map_file_into_view will magically
898 * fall back to read(), so we don't need to check anything here.
900 if (map_file_into_view( view, fd, sec->VirtualAddress, sec->SizeOfRawData, sec->PointerToRawData,
901 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
902 removable ) != STATUS_SUCCESS)
904 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
908 if ((sec->SizeOfRawData < sec->Misc.VirtualSize) && (sec->SizeOfRawData & page_mask))
910 DWORD end = ROUND_SIZE( 0, sec->SizeOfRawData );
911 if (end > sec->Misc.VirtualSize) end = sec->Misc.VirtualSize;
912 TRACE_(module)("clearing %p - %p\n",
913 ptr + sec->VirtualAddress + sec->SizeOfRawData,
914 ptr + sec->VirtualAddress + end );
915 memset( ptr + sec->VirtualAddress + sec->SizeOfRawData, 0,
916 end - sec->SizeOfRawData );
921 /* perform base relocation, if necessary */
925 const IMAGE_DATA_DIRECTORY *relocs;
927 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
928 if (!relocs->VirtualAddress || !relocs->Size)
930 if (nt->OptionalHeader.ImageBase == 0x400000) {
931 ERR("Image was mapped at %p: standard load address for a Win32 program (0x00400000) not available\n", ptr);
932 ERR("Do you have exec-shield or prelink active?\n");
934 ERR( "FATAL: Need to relocate module from addr %lx, but there are no relocation records\n",
935 nt->OptionalHeader.ImageBase );
939 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
940 * really make sure that the *new* base address is also > 2GB.
941 * Some DLLs really check the MSB of the module handle :-/
943 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
944 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
946 if (!do_relocations( ptr, relocs, ptr - base, total_size ))
952 if (!removable) /* don't keep handle open on removable media */
953 NtDuplicateObject( GetCurrentProcess(), hmapping,
954 GetCurrentProcess(), &view->mapping,
955 0, 0, DUPLICATE_SAME_ACCESS );
957 /* set the image protections */
959 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
960 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
962 DWORD size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
963 BYTE vprot = VPROT_COMMITTED;
964 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
965 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
966 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
968 /* make sure the import directory is writable */
969 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
970 imports->VirtualAddress < sec->VirtualAddress + size)
971 vprot |= VPROT_READ|VPROT_WRITECOPY;
973 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
975 RtlLeaveCriticalSection( &csVirtual );
978 return STATUS_SUCCESS;
981 if (view) delete_view( view );
982 RtlLeaveCriticalSection( &csVirtual );
987 /***********************************************************************
990 * Check whether a process handle is for the current process.
992 static BOOL is_current_process( HANDLE handle )
996 if (handle == GetCurrentProcess()) return TRUE;
997 SERVER_START_REQ( get_process_info )
999 req->handle = handle;
1000 if (!wine_server_call( req ))
1001 ret = ((DWORD)reply->pid == GetCurrentProcessId());
1008 /***********************************************************************
1011 void virtual_init(void)
1014 page_size = getpagesize();
1015 page_mask = page_size - 1;
1016 /* Make sure we have a power of 2 */
1017 assert( !(page_size & page_mask) );
1019 while ((1 << page_shift) != page_size) page_shift++;
1020 #endif /* page_mask */
1024 /***********************************************************************
1025 * VIRTUAL_SetFaultHandler
1027 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
1032 RtlEnterCriticalSection( &csVirtual );
1033 if ((view = VIRTUAL_FindView( addr )))
1035 view->handlerProc = proc;
1036 view->handlerArg = arg;
1039 RtlLeaveCriticalSection( &csVirtual );
1043 /***********************************************************************
1044 * VIRTUAL_HandleFault
1046 DWORD VIRTUAL_HandleFault( LPCVOID addr )
1049 DWORD ret = EXCEPTION_ACCESS_VIOLATION;
1051 RtlEnterCriticalSection( &csVirtual );
1052 if ((view = VIRTUAL_FindView( addr )))
1054 if (view->handlerProc)
1056 HANDLERPROC proc = view->handlerProc;
1057 void *arg = view->handlerArg;
1058 RtlLeaveCriticalSection( &csVirtual );
1059 if (proc( arg, addr )) ret = 0; /* handled */
1064 BYTE vprot = view->prot[((char *)addr - (char *)view->base) >> page_shift];
1065 void *page = (void *)((UINT_PTR)addr & ~page_mask);
1066 char *stack = NtCurrentTeb()->Tib.StackLimit;
1067 if (vprot & VPROT_GUARD)
1069 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
1070 ret = STATUS_GUARD_PAGE_VIOLATION;
1072 /* is it inside the stack guard page? */
1073 if (((char *)addr >= stack) && ((char *)addr < stack + (page_mask+1)))
1074 ret = STATUS_STACK_OVERFLOW;
1077 RtlLeaveCriticalSection( &csVirtual );
1081 /***********************************************************************
1082 * VIRTUAL_HasMapping
1084 * Check if the specified view has an associated file mapping.
1086 BOOL VIRTUAL_HasMapping( LPCVOID addr )
1091 RtlEnterCriticalSection( &csVirtual );
1092 if ((view = VIRTUAL_FindView( addr ))) ret = (view->mapping != 0);
1093 RtlLeaveCriticalSection( &csVirtual );
1098 /***********************************************************************
1099 * NtAllocateVirtualMemory (NTDLL.@)
1100 * ZwAllocateVirtualMemory (NTDLL.@)
1102 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, PVOID addr,
1103 ULONG *size_ptr, ULONG type, ULONG protect )
1107 DWORD size = *size_ptr;
1108 NTSTATUS status = STATUS_SUCCESS;
1109 struct file_view *view;
1111 if (!is_current_process( process ))
1113 ERR("Unsupported on other process\n");
1114 return STATUS_ACCESS_DENIED;
1117 TRACE("%p %08lx %lx %08lx\n", addr, size, type, protect );
1119 if (!size) return STATUS_INVALID_PARAMETER;
1121 /* Round parameters to a page boundary */
1123 if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
1127 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1128 base = ROUND_ADDR( addr, granularity_mask );
1130 base = ROUND_ADDR( addr, page_mask );
1131 size = (((UINT_PTR)addr + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1133 /* disallow low 64k, wrap-around and kernel space */
1134 if (((char *)base <= (char *)granularity_mask) ||
1135 ((char *)base + size < (char *)base) ||
1136 is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
1137 return STATUS_INVALID_PARAMETER;
1142 size = (size + page_mask) & ~page_mask;
1145 if (type & MEM_TOP_DOWN) {
1146 /* FIXME: MEM_TOP_DOWN allocates the largest possible address. */
1147 WARN("MEM_TOP_DOWN ignored\n");
1148 type &= ~MEM_TOP_DOWN;
1151 /* Compute the alloc type flags */
1153 if (!(type & MEM_SYSTEM))
1155 if (!(type & (MEM_COMMIT | MEM_RESERVE)) || (type & ~(MEM_COMMIT | MEM_RESERVE)))
1157 WARN("called with wrong alloc type flags (%08lx) !\n", type);
1158 return STATUS_INVALID_PARAMETER;
1161 vprot = VIRTUAL_GetProt( protect );
1162 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1164 /* Reserve the memory */
1166 RtlEnterCriticalSection( &csVirtual );
1168 if (type & MEM_SYSTEM)
1170 if (type & MEM_IMAGE) vprot |= VPROT_IMAGE;
1171 status = create_view( &view, base, size, vprot | VPROT_COMMITTED );
1172 if (status == STATUS_SUCCESS)
1174 view->flags |= VFLAG_VALLOC | VFLAG_SYSTEM;
1178 else if ((type & MEM_RESERVE) || !base)
1180 status = map_view( &view, base, size, vprot );
1181 if (status == STATUS_SUCCESS)
1183 view->flags |= VFLAG_VALLOC;
1187 else /* commit the pages */
1189 if (!(view = VIRTUAL_FindView( base )) ||
1190 ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
1191 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1194 RtlLeaveCriticalSection( &csVirtual );
1196 if (status == STATUS_SUCCESS)
1205 /***********************************************************************
1206 * NtFreeVirtualMemory (NTDLL.@)
1207 * ZwFreeVirtualMemory (NTDLL.@)
1209 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr, ULONG type )
1213 NTSTATUS status = STATUS_SUCCESS;
1214 LPVOID addr = *addr_ptr;
1215 DWORD size = *size_ptr;
1217 if (!is_current_process( process ))
1219 ERR("Unsupported on other process\n");
1220 return STATUS_ACCESS_DENIED;
1223 TRACE("%p %08lx %lx\n", addr, size, type );
1225 /* Fix the parameters */
1227 size = ROUND_SIZE( addr, size );
1228 base = ROUND_ADDR( addr, page_mask );
1230 RtlEnterCriticalSection(&csVirtual);
1232 if (!(view = VIRTUAL_FindView( base )) ||
1233 (base + size > (char *)view->base + view->size) ||
1234 !(view->flags & VFLAG_VALLOC))
1236 status = STATUS_INVALID_PARAMETER;
1238 else if (type & MEM_SYSTEM)
1240 /* return the values that the caller should use to unmap the area */
1241 *addr_ptr = view->base;
1242 *size_ptr = view->size;
1243 view->flags |= VFLAG_SYSTEM;
1244 delete_view( view );
1246 else if (type == MEM_RELEASE)
1248 /* Free the pages */
1250 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1253 delete_view( view );
1258 else if (type == MEM_DECOMMIT)
1260 status = decommit_pages( view, base - (char *)view->base, size );
1261 if (status == STATUS_SUCCESS)
1269 WARN("called with wrong free type flags (%08lx) !\n", type);
1270 status = STATUS_INVALID_PARAMETER;
1273 RtlLeaveCriticalSection(&csVirtual);
1278 /***********************************************************************
1279 * NtProtectVirtualMemory (NTDLL.@)
1280 * ZwProtectVirtualMemory (NTDLL.@)
1282 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr,
1283 ULONG new_prot, ULONG *old_prot )
1286 NTSTATUS status = STATUS_SUCCESS;
1290 DWORD prot, size = *size_ptr;
1291 LPVOID addr = *addr_ptr;
1293 if (!is_current_process( process ))
1295 ERR("Unsupported on other process\n");
1296 return STATUS_ACCESS_DENIED;
1299 TRACE("%p %08lx %08lx\n", addr, size, new_prot );
1301 /* Fix the parameters */
1303 size = ROUND_SIZE( addr, size );
1304 base = ROUND_ADDR( addr, page_mask );
1306 RtlEnterCriticalSection( &csVirtual );
1308 if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1310 status = STATUS_INVALID_PARAMETER;
1314 /* Make sure all the pages are committed */
1316 p = view->prot + ((base - (char *)view->base) >> page_shift);
1317 VIRTUAL_GetWin32Prot( *p, &prot, NULL );
1318 for (i = size >> page_shift; i; i--, p++)
1320 if (!(*p & VPROT_COMMITTED))
1322 status = STATUS_NOT_COMMITTED;
1328 if (old_prot) *old_prot = prot;
1329 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1330 if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1333 RtlLeaveCriticalSection( &csVirtual );
1335 if (status == STATUS_SUCCESS)
1344 /***********************************************************************
1345 * NtQueryVirtualMemory (NTDLL.@)
1346 * ZwQueryVirtualMemory (NTDLL.@)
1348 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1349 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1350 ULONG len, ULONG *res_len )
1353 char *base, *alloc_base = 0;
1356 MEMORY_BASIC_INFORMATION *info = buffer;
1358 if (info_class != MemoryBasicInformation) return STATUS_INVALID_INFO_CLASS;
1359 if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1360 return STATUS_WORKING_SET_LIMIT_RANGE;
1362 if (!is_current_process( process ))
1364 ERR("Unsupported on other process\n");
1365 return STATUS_ACCESS_DENIED;
1368 base = ROUND_ADDR( addr, page_mask );
1370 /* Find the view containing the address */
1372 RtlEnterCriticalSection(&csVirtual);
1373 ptr = list_head( &views_list );
1378 /* make the address space end at the user limit, except if
1379 * the last view was mapped beyond that */
1380 if (alloc_base < (char *)USER_SPACE_LIMIT)
1382 if (USER_SPACE_LIMIT && base >= (char *)USER_SPACE_LIMIT)
1384 RtlLeaveCriticalSection( &csVirtual );
1385 return STATUS_WORKING_SET_LIMIT_RANGE;
1387 size = (char *)USER_SPACE_LIMIT - alloc_base;
1389 else size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1393 view = LIST_ENTRY( ptr, struct file_view, entry );
1394 if ((char *)view->base > base)
1396 size = (char *)view->base - alloc_base;
1400 if ((char *)view->base + view->size > base)
1402 alloc_base = view->base;
1406 alloc_base = (char *)view->base + view->size;
1407 ptr = list_next( &views_list, ptr );
1410 /* Fill the info structure */
1414 info->State = MEM_FREE;
1416 info->AllocationProtect = 0;
1421 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1422 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
1423 for (size = base - alloc_base; size < view->size; size += page_mask+1)
1424 if (view->prot[size >> page_shift] != vprot) break;
1425 VIRTUAL_GetWin32Prot( view->protect, &info->AllocationProtect, NULL );
1426 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1427 else if (view->flags & VFLAG_VALLOC) info->Type = MEM_PRIVATE;
1428 else info->Type = MEM_MAPPED;
1430 RtlLeaveCriticalSection(&csVirtual);
1432 info->BaseAddress = (LPVOID)base;
1433 info->AllocationBase = (LPVOID)alloc_base;
1434 info->RegionSize = size - (base - alloc_base);
1435 if (res_len) *res_len = sizeof(*info);
1436 return STATUS_SUCCESS;
1440 /***********************************************************************
1441 * NtLockVirtualMemory (NTDLL.@)
1442 * ZwLockVirtualMemory (NTDLL.@)
1444 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1446 if (!is_current_process( process ))
1448 ERR("Unsupported on other process\n");
1449 return STATUS_ACCESS_DENIED;
1451 return STATUS_SUCCESS;
1455 /***********************************************************************
1456 * NtUnlockVirtualMemory (NTDLL.@)
1457 * ZwUnlockVirtualMemory (NTDLL.@)
1459 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1461 if (!is_current_process( process ))
1463 ERR("Unsupported on other process\n");
1464 return STATUS_ACCESS_DENIED;
1466 return STATUS_SUCCESS;
1470 /***********************************************************************
1471 * NtCreateSection (NTDLL.@)
1472 * ZwCreateSection (NTDLL.@)
1474 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1475 const LARGE_INTEGER *size, ULONG protect,
1476 ULONG sec_flags, HANDLE file )
1480 DWORD len = attr->ObjectName ? attr->ObjectName->Length : 0;
1482 /* Check parameters */
1484 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1486 vprot = VIRTUAL_GetProt( protect );
1487 if (sec_flags & SEC_RESERVE)
1489 if (file) return STATUS_INVALID_PARAMETER;
1491 else vprot |= VPROT_COMMITTED;
1492 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1493 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
1495 /* Create the server object */
1497 SERVER_START_REQ( create_mapping )
1499 req->file_handle = file;
1500 req->size_high = size ? size->u.HighPart : 0;
1501 req->size_low = size ? size->u.LowPart : 0;
1502 req->protect = vprot;
1503 req->access = access;
1504 req->inherit = (attr->Attributes & OBJ_INHERIT) != 0;
1505 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
1506 ret = wine_server_call( req );
1507 *handle = reply->handle;
1514 /***********************************************************************
1515 * NtOpenSection (NTDLL.@)
1516 * ZwOpenSection (NTDLL.@)
1518 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1521 DWORD len = attr->ObjectName->Length;
1523 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1525 SERVER_START_REQ( open_mapping )
1527 req->access = access;
1528 req->inherit = (attr->Attributes & OBJ_INHERIT) != 0;
1529 wine_server_add_data( req, attr->ObjectName->Buffer, len );
1530 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
1537 /***********************************************************************
1538 * NtMapViewOfSection (NTDLL.@)
1539 * ZwMapViewOfSection (NTDLL.@)
1541 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
1542 ULONG commit_size, const LARGE_INTEGER *offset, ULONG *size_ptr,
1543 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
1546 FILE_FS_DEVICE_INFORMATION device_info;
1549 int unix_handle = -1;
1552 struct file_view *view;
1553 DWORD size_low, size_high, header_size, shared_size;
1555 BOOL removable = FALSE;
1557 if (!is_current_process( process ))
1559 ERR("Unsupported on other process\n");
1560 return STATUS_ACCESS_DENIED;
1563 TRACE("handle=%p addr=%p off=%lx%08lx size=%x access=%lx\n",
1564 handle, *addr_ptr, offset->u.HighPart, offset->u.LowPart, size, protect );
1566 /* Check parameters */
1568 if ((offset->u.LowPart & granularity_mask) ||
1569 (*addr_ptr && ((UINT_PTR)*addr_ptr & granularity_mask)))
1570 return STATUS_INVALID_PARAMETER;
1572 SERVER_START_REQ( get_mapping_info )
1574 req->handle = handle;
1575 res = wine_server_call( req );
1576 prot = reply->protect;
1578 size_low = reply->size_low;
1579 size_high = reply->size_high;
1580 header_size = reply->header_size;
1581 shared_file = reply->shared_file;
1582 shared_size = reply->shared_size;
1585 if (res) return res;
1587 if ((res = wine_server_handle_to_fd( handle, 0, &unix_handle, NULL, NULL ))) return res;
1589 if (NtQueryVolumeInformationFile( handle, &io, &device_info, sizeof(device_info),
1590 FileFsDeviceInformation ) == STATUS_SUCCESS)
1591 removable = device_info.Characteristics & FILE_REMOVABLE_MEDIA;
1593 if (prot & VPROT_IMAGE)
1599 if ((res = wine_server_handle_to_fd( shared_file, GENERIC_READ, &shared_fd,
1600 NULL, NULL ))) goto done;
1601 res = map_image( handle, unix_handle, base, size_low, header_size,
1602 shared_fd, removable, addr_ptr );
1603 wine_server_release_fd( shared_file, shared_fd );
1604 NtClose( shared_file );
1608 res = map_image( handle, unix_handle, base, size_low, header_size,
1609 -1, removable, addr_ptr );
1611 wine_server_release_fd( handle, unix_handle );
1612 if (!res) *size_ptr = size_low;
1617 ERR("Sizes larger than 4Gb not supported\n");
1619 if ((offset->u.LowPart >= size_low) ||
1620 (*size_ptr > size_low - offset->u.LowPart))
1622 res = STATUS_INVALID_PARAMETER;
1625 if (*size_ptr) size = ROUND_SIZE( offset->u.LowPart, *size_ptr );
1626 else size = size_low - offset->u.LowPart;
1632 case PAGE_READWRITE:
1633 case PAGE_EXECUTE_READWRITE:
1634 if (!(prot & VPROT_WRITE))
1636 res = STATUS_INVALID_PARAMETER;
1642 case PAGE_WRITECOPY:
1644 case PAGE_EXECUTE_READ:
1645 case PAGE_EXECUTE_WRITECOPY:
1646 if (prot & VPROT_READ) break;
1649 res = STATUS_INVALID_PARAMETER;
1653 /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1654 * which has a view of this mapping commits some pages, they will
1655 * appear commited in all other processes, which have the same
1656 * view created. Since we don`t support this yet, we create the
1657 * whole mapping commited.
1659 prot |= VPROT_COMMITTED;
1661 /* Reserve a properly aligned area */
1663 RtlEnterCriticalSection( &csVirtual );
1665 res = map_view( &view, *addr_ptr, size, prot );
1668 RtlLeaveCriticalSection( &csVirtual );
1674 TRACE("handle=%p size=%x offset=%lx%08lx\n",
1675 handle, size, offset->u.HighPart, offset->u.LowPart );
1677 res = map_file_into_view( view, unix_handle, 0, size, offset->QuadPart, prot, removable );
1678 if (res == STATUS_SUCCESS)
1680 if (!removable) /* don't keep handle open on removable media */
1681 NtDuplicateObject( GetCurrentProcess(), handle,
1682 GetCurrentProcess(), &view->mapping,
1683 0, 0, DUPLICATE_SAME_ACCESS );
1685 *addr_ptr = view->base;
1690 ERR( "map_file_into_view %p %x %lx%08lx failed\n",
1691 view->base, size, offset->u.HighPart, offset->u.LowPart );
1692 delete_view( view );
1695 RtlLeaveCriticalSection( &csVirtual );
1698 wine_server_release_fd( handle, unix_handle );
1703 /***********************************************************************
1704 * NtUnmapViewOfSection (NTDLL.@)
1705 * ZwUnmapViewOfSection (NTDLL.@)
1707 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
1710 NTSTATUS status = STATUS_INVALID_PARAMETER;
1711 void *base = ROUND_ADDR( addr, page_mask );
1713 if (!is_current_process( process ))
1715 ERR("Unsupported on other process\n");
1716 return STATUS_ACCESS_DENIED;
1718 RtlEnterCriticalSection( &csVirtual );
1719 if ((view = VIRTUAL_FindView( base )) && (base == view->base))
1721 delete_view( view );
1722 status = STATUS_SUCCESS;
1724 RtlLeaveCriticalSection( &csVirtual );
1729 /***********************************************************************
1730 * NtFlushVirtualMemory (NTDLL.@)
1731 * ZwFlushVirtualMemory (NTDLL.@)
1733 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
1734 ULONG *size_ptr, ULONG unknown )
1737 NTSTATUS status = STATUS_SUCCESS;
1738 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
1740 if (!is_current_process( process ))
1742 ERR("Unsupported on other process\n");
1743 return STATUS_ACCESS_DENIED;
1745 RtlEnterCriticalSection( &csVirtual );
1746 if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
1749 if (!*size_ptr) *size_ptr = view->size;
1751 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
1753 RtlLeaveCriticalSection( &csVirtual );
1758 /***********************************************************************
1759 * NtReadVirtualMemory (NTDLL.@)
1760 * ZwReadVirtualMemory (NTDLL.@)
1762 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
1763 SIZE_T size, SIZE_T *bytes_read )
1767 SERVER_START_REQ( read_process_memory )
1769 req->handle = process;
1770 req->addr = (void *)addr;
1771 wine_server_set_reply( req, buffer, size );
1772 if ((status = wine_server_call( req ))) size = 0;
1775 if (bytes_read) *bytes_read = size;
1780 /***********************************************************************
1781 * NtWriteVirtualMemory (NTDLL.@)
1782 * ZwWriteVirtualMemory (NTDLL.@)
1784 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
1785 SIZE_T size, SIZE_T *bytes_written )
1787 static const unsigned int zero;
1788 unsigned int first_offset, last_offset, first_mask, last_mask;
1791 if (!size) return STATUS_INVALID_PARAMETER;
1793 /* compute the mask for the first int */
1795 first_offset = (unsigned int)addr % sizeof(int);
1796 memset( &first_mask, 0, first_offset );
1798 /* compute the mask for the last int */
1799 last_offset = (size + first_offset) % sizeof(int);
1801 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1803 SERVER_START_REQ( write_process_memory )
1805 req->handle = process;
1806 req->addr = (char *)addr - first_offset;
1807 req->first_mask = first_mask;
1808 req->last_mask = last_mask;
1809 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1810 wine_server_add_data( req, buffer, size );
1811 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1813 if ((status = wine_server_call( req ))) size = 0;
1816 if (bytes_written) *bytes_written = size;