2 * Win32 virtual memory functions
4 * Copyright 1997, 2002 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "wine/port.h"
26 #ifdef HAVE_SYS_ERRNO_H
27 #include <sys/errno.h>
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_MMAN_H
42 #define NONAMELESSUNION
43 #define NONAMELESSSTRUCT
50 #include "wine/library.h"
51 #include "wine/server.h"
52 #include "wine/list.h"
53 #include "wine/debug.h"
54 #include "ntdll_misc.h"
56 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
57 WINE_DECLARE_DEBUG_CHANNEL(module);
64 #define MAP_NORESERVE 0
68 typedef struct file_view
70 struct list entry; /* Entry in global view list */
71 void *base; /* Base address */
72 UINT size; /* Size in bytes */
73 HANDLE mapping; /* Handle to the file mapping */
74 BYTE flags; /* Allocation flags (VFLAG_*) */
75 BYTE protect; /* Protection for all pages at allocation time */
76 BYTE prot[1]; /* Protection byte for each page */
80 #define VFLAG_SYSTEM 0x01 /* system view (underlying mmap not under our control) */
81 #define VFLAG_VALLOC 0x02 /* allocated by VirtualAlloc */
83 /* Conversion from VPROT_* to Win32 flags */
84 static const BYTE VIRTUAL_Win32Flags[16] =
86 PAGE_NOACCESS, /* 0 */
87 PAGE_READONLY, /* READ */
88 PAGE_READWRITE, /* WRITE */
89 PAGE_READWRITE, /* READ | WRITE */
90 PAGE_EXECUTE, /* EXEC */
91 PAGE_EXECUTE_READ, /* READ | EXEC */
92 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
93 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
94 PAGE_WRITECOPY, /* WRITECOPY */
95 PAGE_WRITECOPY, /* READ | WRITECOPY */
96 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
97 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
98 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
99 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
100 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
101 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
104 static struct list views_list = LIST_INIT(views_list);
106 static CRITICAL_SECTION csVirtual;
107 static CRITICAL_SECTION_DEBUG critsect_debug =
110 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
111 0, 0, { 0, (DWORD)(__FILE__ ": csVirtual") }
113 static CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
116 /* These are always the same on an i386, and it will be faster this way */
117 # define page_mask 0xfff
118 # define page_shift 12
119 # define page_size 0x1000
120 /* Note: these are Windows limits, you cannot change them. */
121 # define ADDRESS_SPACE_LIMIT ((void *)0xc0000000) /* top of the total available address space */
122 # define USER_SPACE_LIMIT ((void *)0x80000000) /* top of the user address space */
124 static UINT page_shift;
125 static UINT page_mask;
126 static UINT page_size;
127 # define ADDRESS_SPACE_LIMIT 0 /* no limit needed on other platforms */
128 # define USER_SPACE_LIMIT 0 /* no limit needed on other platforms */
129 #endif /* __i386__ */
130 #define granularity_mask 0xffff /* Allocation granularity (usually 64k) */
132 #define ROUND_ADDR(addr,mask) \
133 ((void *)((UINT_PTR)(addr) & ~(mask)))
135 #define ROUND_SIZE(addr,size) \
136 (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
138 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
139 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
141 static void *user_space_limit = USER_SPACE_LIMIT;
144 /***********************************************************************
147 static const char *VIRTUAL_GetProtStr( BYTE prot )
149 static char buffer[6];
150 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
151 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
152 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
153 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
154 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
160 /***********************************************************************
163 static void VIRTUAL_DumpView( FILE_VIEW *view )
166 char *addr = view->base;
167 BYTE prot = view->prot[0];
169 DPRINTF( "View: %p - %p", addr, addr + view->size - 1 );
170 if (view->flags & VFLAG_SYSTEM)
171 DPRINTF( " (system)\n" );
172 else if (view->flags & VFLAG_VALLOC)
173 DPRINTF( " (valloc)\n" );
174 else if (view->mapping)
175 DPRINTF( " %p\n", view->mapping );
177 DPRINTF( " (anonymous)\n");
179 for (count = i = 1; i < view->size >> page_shift; i++, count++)
181 if (view->prot[i] == prot) continue;
182 DPRINTF( " %p - %p %s\n",
183 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
184 addr += (count << page_shift);
185 prot = view->prot[i];
189 DPRINTF( " %p - %p %s\n",
190 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
194 /***********************************************************************
197 void VIRTUAL_Dump(void)
199 struct file_view *view;
201 DPRINTF( "\nDump of all virtual memory views:\n\n" );
202 RtlEnterCriticalSection(&csVirtual);
203 LIST_FOR_EACH_ENTRY( view, &views_list, FILE_VIEW, entry )
205 VIRTUAL_DumpView( view );
207 RtlLeaveCriticalSection(&csVirtual);
211 /***********************************************************************
214 * Find the view containing a given address. The csVirtual section must be held by caller.
223 static struct file_view *VIRTUAL_FindView( const void *addr )
225 struct file_view *view;
227 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
229 if (view->base > addr) break;
230 if ((const char*)view->base + view->size > (const char*)addr) return view;
236 /***********************************************************************
239 * Find the first view overlapping at least part of the specified range.
240 * The csVirtual section must be held by caller.
242 static struct file_view *find_view_range( const void *addr, size_t size )
244 struct file_view *view;
246 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
248 if ((const char *)view->base >= (const char *)addr + size) break;
249 if ((const char *)view->base + view->size > (const char *)addr) return view;
255 /***********************************************************************
258 * Add a reserved area to the list maintained by libwine.
259 * The csVirtual section must be held by caller.
261 static void add_reserved_area( void *addr, size_t size )
263 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
265 if (addr < user_space_limit)
267 /* unmap the part of the area that is below the limit */
268 assert( (char *)addr + size > (char *)user_space_limit );
269 munmap( addr, (char *)user_space_limit - (char *)addr );
270 size -= (char *)user_space_limit - (char *)addr;
271 addr = user_space_limit;
273 /* blow away existing mappings */
274 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
275 wine_mmap_add_reserved_area( addr, size );
279 /***********************************************************************
280 * remove_reserved_area
282 * Remove a reserved area from the list maintained by libwine.
283 * The csVirtual section must be held by caller.
285 static void remove_reserved_area( void *addr, size_t size )
287 struct file_view *view;
289 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
291 if ((char *)view->base >= (char *)addr + size) break;
292 if ((char *)view->base + view->size <= (char *)addr) continue;
293 /* now we have an overlapping view */
294 if (view->base > addr)
296 wine_mmap_remove_reserved_area( addr, (char *)view->base - (char *)addr, TRUE );
297 size -= (char *)view->base - (char *)addr;
300 if ((char *)view->base + view->size >= (char *)addr + size)
302 /* view covers all the remaining area */
303 wine_mmap_remove_reserved_area( addr, size, FALSE );
307 else /* view covers only part of the area */
309 wine_mmap_remove_reserved_area( addr, (char *)view->base + view->size - (char *)addr, FALSE );
310 size -= (char *)view->base + view->size - (char *)addr;
311 addr = (char *)view->base + view->size;
314 /* remove remaining space */
315 if (size) wine_mmap_remove_reserved_area( addr, size, TRUE );
319 /***********************************************************************
322 * Check if an address range goes beyond a given limit.
324 static inline int is_beyond_limit( void *addr, size_t size, void *limit )
326 return (limit && (addr >= limit || (char *)addr + size > (char *)limit));
330 /***********************************************************************
333 * Unmap an area, or simply replace it by an empty mapping if it is
334 * in a reserved area. The csVirtual section must be held by caller.
336 static inline void unmap_area( void *addr, size_t size )
338 if (wine_mmap_is_in_reserved_area( addr, size ))
339 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
341 munmap( addr, size );
345 /***********************************************************************
348 * Deletes a view. The csVirtual section must be held by caller.
350 static void delete_view( struct file_view *view ) /* [in] View */
352 if (!(view->flags & VFLAG_SYSTEM)) unmap_area( view->base, view->size );
353 list_remove( &view->entry );
354 if (view->mapping) NtClose( view->mapping );
359 /***********************************************************************
362 * Create a view. The csVirtual section must be held by caller.
364 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, BYTE vprot )
366 struct file_view *view;
369 assert( !((unsigned int)base & page_mask) );
370 assert( !(size & page_mask) );
372 /* Create the view structure */
374 if (!(view = malloc( sizeof(*view) + (size >> page_shift) - 1 ))) return STATUS_NO_MEMORY;
380 view->protect = vprot;
381 memset( view->prot, vprot, size >> page_shift );
383 /* Insert it in the linked list */
385 LIST_FOR_EACH( ptr, &views_list )
387 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
388 if (next->base > base) break;
390 list_add_before( ptr, &view->entry );
392 /* Check for overlapping views. This can happen if the previous view
393 * was a system view that got unmapped behind our back. In that case
394 * we recover by simply deleting it. */
396 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
398 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
399 if ((char *)prev->base + prev->size > (char *)base)
401 TRACE( "overlapping prev view %p-%p for %p-%p\n",
402 prev->base, (char *)prev->base + prev->size,
403 base, (char *)base + view->size );
404 assert( prev->flags & VFLAG_SYSTEM );
408 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
410 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
411 if ((char *)base + view->size > (char *)next->base)
413 TRACE( "overlapping next view %p-%p for %p-%p\n",
414 next->base, (char *)next->base + next->size,
415 base, (char *)base + view->size );
416 assert( next->flags & VFLAG_SYSTEM );
422 VIRTUAL_DEBUG_DUMP_VIEW( view );
423 return STATUS_SUCCESS;
427 /***********************************************************************
428 * VIRTUAL_GetUnixProt
430 * Convert page protections to protection for mmap/mprotect.
432 static int VIRTUAL_GetUnixProt( BYTE vprot )
435 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
437 if (vprot & VPROT_READ) prot |= PROT_READ;
438 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
439 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
440 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
446 /***********************************************************************
447 * VIRTUAL_GetWin32Prot
449 * Convert page protections to Win32 flags.
454 static void VIRTUAL_GetWin32Prot(
455 BYTE vprot, /* [in] Page protection flags */
456 DWORD *protect, /* [out] Location to store Win32 protection flags */
457 DWORD *state ) /* [out] Location to store mem state flag */
460 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
461 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
462 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
464 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
467 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
471 /***********************************************************************
474 * Build page protections from Win32 flags.
477 * protect [I] Win32 protection flags
480 * Value of page protection flags
482 static BYTE VIRTUAL_GetProt( DWORD protect )
486 switch(protect & 0xff)
492 vprot = VPROT_READ | VPROT_WRITE;
495 /* MSDN CreateFileMapping() states that if PAGE_WRITECOPY is given,
496 * that the hFile must have been opened with GENERIC_READ and
497 * GENERIC_WRITE access. This is WRONG as tests show that you
498 * only need GENERIC_READ access (at least for Win9x,
499 * FIXME: what about NT?). Thus, we don't put VPROT_WRITE in
500 * PAGE_WRITECOPY and PAGE_EXECUTE_WRITECOPY.
502 vprot = VPROT_READ | VPROT_WRITECOPY;
507 case PAGE_EXECUTE_READ:
508 vprot = VPROT_EXEC | VPROT_READ;
510 case PAGE_EXECUTE_READWRITE:
511 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
513 case PAGE_EXECUTE_WRITECOPY:
514 /* See comment for PAGE_WRITECOPY above */
515 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
522 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
523 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
528 /***********************************************************************
531 * Change the protection of a range of pages.
537 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
538 void *base, /* [in] Starting address */
539 UINT size, /* [in] Size in bytes */
540 BYTE vprot ) /* [in] Protections to use */
543 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
545 if (mprotect( base, size, VIRTUAL_GetUnixProt(vprot) ))
546 return FALSE; /* FIXME: last error */
548 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
549 vprot, size >> page_shift );
550 VIRTUAL_DEBUG_DUMP_VIEW( view );
555 /***********************************************************************
558 * Create a view and mmap the corresponding memory area.
559 * The csVirtual section must be held by caller.
561 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, BYTE vprot )
568 if (is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
569 return STATUS_WORKING_SET_LIMIT_RANGE;
571 switch (wine_mmap_is_in_reserved_area( base, size ))
573 case -1: /* partially in a reserved area */
574 return STATUS_CONFLICTING_ADDRESSES;
576 case 0: /* not in a reserved area, do a normal allocation */
577 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
579 if (errno == ENOMEM) return STATUS_NO_MEMORY;
580 return STATUS_INVALID_PARAMETER;
584 /* We couldn't get the address we wanted */
585 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
586 else munmap( ptr, size );
587 return STATUS_CONFLICTING_ADDRESSES;
592 case 1: /* in a reserved area, make sure the address is available */
593 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
594 /* replace the reserved area by our mapping */
595 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
596 return STATUS_INVALID_PARAMETER;
602 size_t view_size = size + granularity_mask + 1;
606 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
608 if (errno == ENOMEM) return STATUS_NO_MEMORY;
609 return STATUS_INVALID_PARAMETER;
611 /* if we got something beyond the user limit, unmap it and retry */
612 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
616 /* Release the extra memory while keeping the range
617 * starting on the granularity boundary. */
618 if ((unsigned int)ptr & granularity_mask)
620 unsigned int extra = granularity_mask + 1 - ((unsigned int)ptr & granularity_mask);
621 munmap( ptr, extra );
622 ptr = (char *)ptr + extra;
625 if (view_size > size)
626 munmap( (char *)ptr + size, view_size - size );
629 status = create_view( view_ret, ptr, size, vprot );
630 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
635 /***********************************************************************
638 * Linux kernels before 2.4.x can support non page-aligned offsets, as
639 * long as the offset is aligned to the filesystem block size. This is
640 * a big performance gain so we want to take advantage of it.
642 * However, when we use 64-bit file support this doesn't work because
643 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
644 * in that it rounds unaligned offsets down to a page boundary. For
645 * these reasons we do a direct system call here.
647 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
648 unsigned int flags, int fd, off_t offset )
650 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
651 if (!(offset >> 32) && (offset & page_mask))
666 args.length = length;
670 args.offset = offset;
672 __asm__ __volatile__("push %%ebx\n\t"
677 : "0" (90), /* SYS_mmap */
680 if (ret < 0 && ret > -4096)
688 return mmap( addr, length, prot, flags, fd, offset );
692 /***********************************************************************
695 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
696 * The csVirtual section must be held by caller.
698 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
699 off_t offset, BYTE vprot, BOOL removable )
702 int prot = VIRTUAL_GetUnixProt( vprot );
703 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
705 assert( start < view->size );
706 assert( start + size <= view->size );
708 /* only try mmap if media is not removable (or if we require write access) */
709 if (!removable || shared_write)
711 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
713 if (unaligned_mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
716 /* mmap() failed; if this is because the file offset is not */
717 /* page-aligned (EINVAL), or because the underlying filesystem */
718 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
719 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
720 if (shared_write) return FILE_GetNtStatus(); /* we cannot fake shared write mappings */
723 /* Reserve the memory with an anonymous mmap */
724 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
725 if (ptr == (void *)-1) return FILE_GetNtStatus();
726 /* Now read in the file */
727 pread( fd, ptr, size, offset );
728 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
730 memset( view->prot + (start >> page_shift), vprot, size >> page_shift );
731 return STATUS_SUCCESS;
735 /***********************************************************************
738 * Decommit some pages of a given view.
739 * The csVirtual section must be held by caller.
741 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
743 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
745 BYTE *p = view->prot + (start >> page_shift);
747 while (size--) *p++ &= ~VPROT_COMMITTED;
748 return STATUS_SUCCESS;
750 return FILE_GetNtStatus();
754 /***********************************************************************
757 * Apply the relocations to a mapped PE image
759 static int do_relocations( char *base, const IMAGE_DATA_DIRECTORY *dir,
760 int delta, DWORD total_size )
762 IMAGE_BASE_RELOCATION *rel;
764 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
765 base - delta, base - delta + total_size, base, base + total_size );
767 for (rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
768 ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
769 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock) )
771 char *page = base + rel->VirtualAddress;
772 WORD *TypeOffset = (WORD *)(rel + 1);
773 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
775 if (!count) continue;
778 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
779 page > base + total_size)
781 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
782 rel, rel->VirtualAddress, rel->SizeOfBlock,
783 base, dir->VirtualAddress, dir->Size );
787 TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
789 /* patching in reverse order */
790 for (i = 0 ; i < count; i++)
792 int offset = TypeOffset[i] & 0xFFF;
793 int type = TypeOffset[i] >> 12;
796 case IMAGE_REL_BASED_ABSOLUTE:
798 case IMAGE_REL_BASED_HIGH:
799 *(short*)(page+offset) += HIWORD(delta);
801 case IMAGE_REL_BASED_LOW:
802 *(short*)(page+offset) += LOWORD(delta);
804 case IMAGE_REL_BASED_HIGHLOW:
805 *(int*)(page+offset) += delta;
806 /* FIXME: if this is an exported address, fire up enhanced logic */
809 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
818 /***********************************************************************
821 * Map an executable (PE format) image into memory.
823 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, DWORD total_size,
824 DWORD header_size, int shared_fd, BOOL removable, PVOID *addr_ptr )
826 IMAGE_DOS_HEADER *dos;
827 IMAGE_NT_HEADERS *nt;
828 IMAGE_SECTION_HEADER *sec;
829 IMAGE_DATA_DIRECTORY *imports;
830 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
833 struct file_view *view = NULL;
836 /* zero-map the whole range */
838 RtlEnterCriticalSection( &csVirtual );
840 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
841 status = map_view( &view, base, total_size,
842 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
844 if (status == STATUS_CONFLICTING_ADDRESSES)
845 status = map_view( &view, NULL, total_size,
846 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
848 if (status != STATUS_SUCCESS) goto error;
851 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
855 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
856 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ,
857 removable ) != STATUS_SUCCESS) goto error;
858 dos = (IMAGE_DOS_HEADER *)ptr;
859 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
860 if ((char *)(nt + 1) > ptr + header_size) goto error;
862 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
863 if ((char *)(sec + nt->FileHeader.NumberOfSections) > ptr + header_size) goto error;
865 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
866 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
868 /* check the architecture */
870 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
872 MESSAGE("Trying to load PE image for unsupported architecture (");
873 switch (nt->FileHeader.Machine)
875 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
876 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
877 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
878 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
879 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
880 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
881 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
882 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
888 /* check for non page-aligned binary */
890 if (nt->OptionalHeader.SectionAlignment <= page_mask)
892 /* unaligned sections, this happens for native subsystem binaries */
893 /* in that case Windows simply maps in the whole file */
895 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
896 removable ) != STATUS_SUCCESS) goto error;
898 /* check that all sections are loaded at the right offset */
899 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
901 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
902 goto error; /* Windows refuses to load in that case too */
905 /* set the image protections */
906 VIRTUAL_SetProt( view, ptr, total_size,
907 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
909 /* perform relocations if necessary */
910 /* FIXME: not 100% compatible, Windows doesn't do this for non page-aligned binaries */
913 const IMAGE_DATA_DIRECTORY *relocs;
914 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
915 if (relocs->VirtualAddress && relocs->Size)
916 do_relocations( ptr, relocs, ptr - base, total_size );
923 /* map all the sections */
925 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
929 /* a few sanity checks */
930 size = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
931 if (sec->VirtualAddress > total_size || size > total_size || size < sec->VirtualAddress)
933 ERR_(module)( "Section %.8s too large (%lx+%lx/%lx)\n",
934 sec->Name, sec->VirtualAddress, sec->Misc.VirtualSize, total_size );
938 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
939 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
941 size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
942 TRACE_(module)( "mapping shared section %.8s at %p off %lx (%x) size %lx (%lx) flags %lx\n",
943 sec->Name, ptr + sec->VirtualAddress,
944 sec->PointerToRawData, (int)pos, sec->SizeOfRawData,
945 size, sec->Characteristics );
946 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, size, pos,
947 VPROT_COMMITTED | VPROT_READ | PROT_WRITE,
948 FALSE ) != STATUS_SUCCESS)
950 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
954 /* check if the import directory falls inside this section */
955 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
956 imports->VirtualAddress < sec->VirtualAddress + size)
958 UINT_PTR base = imports->VirtualAddress & ~page_mask;
959 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
960 if (end > sec->VirtualAddress + size) end = sec->VirtualAddress + size;
962 map_file_into_view( view, shared_fd, base, end - base,
963 pos + (base - sec->VirtualAddress),
964 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
971 TRACE_(module)( "mapping section %.8s at %p off %lx size %lx flags %lx\n",
972 sec->Name, ptr + sec->VirtualAddress,
973 sec->PointerToRawData, sec->SizeOfRawData,
974 sec->Characteristics );
976 if ((sec->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) &&
977 !(sec->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)) continue;
978 if (!sec->PointerToRawData || !sec->SizeOfRawData) continue;
980 /* Note: if the section is not aligned properly map_file_into_view will magically
981 * fall back to read(), so we don't need to check anything here.
983 if (map_file_into_view( view, fd, sec->VirtualAddress, sec->SizeOfRawData, sec->PointerToRawData,
984 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
985 removable ) != STATUS_SUCCESS)
987 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
991 if ((sec->SizeOfRawData < sec->Misc.VirtualSize) && (sec->SizeOfRawData & page_mask))
993 DWORD end = ROUND_SIZE( 0, sec->SizeOfRawData );
994 if (end > sec->Misc.VirtualSize) end = sec->Misc.VirtualSize;
995 TRACE_(module)("clearing %p - %p\n",
996 ptr + sec->VirtualAddress + sec->SizeOfRawData,
997 ptr + sec->VirtualAddress + end );
998 memset( ptr + sec->VirtualAddress + sec->SizeOfRawData, 0,
999 end - sec->SizeOfRawData );
1004 /* perform base relocation, if necessary */
1008 const IMAGE_DATA_DIRECTORY *relocs;
1010 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1011 if (!relocs->VirtualAddress || !relocs->Size)
1013 if (nt->OptionalHeader.ImageBase == 0x400000) {
1014 ERR("Image was mapped at %p: standard load address for a Win32 program (0x00400000) not available\n", ptr);
1015 ERR("Do you have exec-shield or prelink active?\n");
1017 ERR( "FATAL: Need to relocate module from addr %lx, but there are no relocation records\n",
1018 nt->OptionalHeader.ImageBase );
1022 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
1023 * really make sure that the *new* base address is also > 2GB.
1024 * Some DLLs really check the MSB of the module handle :-/
1026 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
1027 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
1029 if (!do_relocations( ptr, relocs, ptr - base, total_size ))
1035 /* set the image protections */
1037 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1038 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1040 DWORD size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1041 BYTE vprot = VPROT_COMMITTED;
1042 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1043 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
1044 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1045 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
1049 if (!removable) /* don't keep handle open on removable media */
1050 NtDuplicateObject( NtCurrentProcess(), hmapping,
1051 NtCurrentProcess(), &view->mapping,
1052 0, 0, DUPLICATE_SAME_ACCESS );
1054 RtlLeaveCriticalSection( &csVirtual );
1057 return STATUS_SUCCESS;
1060 if (view) delete_view( view );
1061 RtlLeaveCriticalSection( &csVirtual );
1066 /***********************************************************************
1067 * is_current_process
1069 * Check whether a process handle is for the current process.
1071 BOOL is_current_process( HANDLE handle )
1075 if (handle == NtCurrentProcess()) return TRUE;
1076 SERVER_START_REQ( get_process_info )
1078 req->handle = handle;
1079 if (!wine_server_call( req ))
1080 ret = ((DWORD)reply->pid == GetCurrentProcessId());
1087 /***********************************************************************
1090 void virtual_init(void)
1093 page_size = getpagesize();
1094 page_mask = page_size - 1;
1095 /* Make sure we have a power of 2 */
1096 assert( !(page_size & page_mask) );
1098 while ((1 << page_shift) != page_size) page_shift++;
1099 #endif /* page_mask */
1103 /***********************************************************************
1104 * VIRTUAL_HandleFault
1106 DWORD VIRTUAL_HandleFault( LPCVOID addr )
1109 DWORD ret = EXCEPTION_ACCESS_VIOLATION;
1111 RtlEnterCriticalSection( &csVirtual );
1112 if ((view = VIRTUAL_FindView( addr )))
1114 BYTE vprot = view->prot[((const char *)addr - (const char *)view->base) >> page_shift];
1115 void *page = (void *)((UINT_PTR)addr & ~page_mask);
1116 char *stack = NtCurrentTeb()->Tib.StackLimit;
1117 if (vprot & VPROT_GUARD)
1119 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
1120 ret = STATUS_GUARD_PAGE_VIOLATION;
1122 /* is it inside the stack guard page? */
1123 if (((const char *)addr >= stack) && ((const char *)addr < stack + (page_mask+1)))
1124 ret = STATUS_STACK_OVERFLOW;
1126 RtlLeaveCriticalSection( &csVirtual );
1130 /***********************************************************************
1131 * VIRTUAL_HasMapping
1133 * Check if the specified view has an associated file mapping.
1135 BOOL VIRTUAL_HasMapping( LPCVOID addr )
1140 RtlEnterCriticalSection( &csVirtual );
1141 if ((view = VIRTUAL_FindView( addr ))) ret = (view->mapping != 0);
1142 RtlLeaveCriticalSection( &csVirtual );
1147 /***********************************************************************
1148 * VIRTUAL_UseLargeAddressSpace
1150 * Increase the address space size for apps that support it.
1152 void VIRTUAL_UseLargeAddressSpace(void)
1154 if (user_space_limit >= ADDRESS_SPACE_LIMIT) return;
1155 RtlEnterCriticalSection( &csVirtual );
1156 remove_reserved_area( user_space_limit, (char *)ADDRESS_SPACE_LIMIT - (char *)user_space_limit );
1157 user_space_limit = ADDRESS_SPACE_LIMIT;
1158 RtlLeaveCriticalSection( &csVirtual );
1162 /***********************************************************************
1163 * NtAllocateVirtualMemory (NTDLL.@)
1164 * ZwAllocateVirtualMemory (NTDLL.@)
1166 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1167 ULONG *size_ptr, ULONG type, ULONG protect )
1171 DWORD size = *size_ptr;
1172 NTSTATUS status = STATUS_SUCCESS;
1173 struct file_view *view;
1175 TRACE("%p %p %08lx %lx %08lx\n", process, *ret, size, type, protect );
1177 if (!size) return STATUS_INVALID_PARAMETER;
1179 if (!is_current_process( process ))
1181 ERR("Unsupported on other process\n");
1182 return STATUS_ACCESS_DENIED;
1185 /* Round parameters to a page boundary */
1187 if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
1191 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1192 base = ROUND_ADDR( *ret, granularity_mask );
1194 base = ROUND_ADDR( *ret, page_mask );
1195 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1197 /* disallow low 64k, wrap-around and kernel space */
1198 if (((char *)base <= (char *)granularity_mask) ||
1199 ((char *)base + size < (char *)base) ||
1200 is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
1201 return STATUS_INVALID_PARAMETER;
1206 size = (size + page_mask) & ~page_mask;
1209 if (type & MEM_TOP_DOWN) {
1210 /* FIXME: MEM_TOP_DOWN allocates the largest possible address. */
1211 WARN("MEM_TOP_DOWN ignored\n");
1212 type &= ~MEM_TOP_DOWN;
1216 WARN("zero_bits %lu ignored\n", zero_bits);
1218 /* Compute the alloc type flags */
1220 if (!(type & MEM_SYSTEM))
1222 if (!(type & (MEM_COMMIT | MEM_RESERVE)) || (type & ~(MEM_COMMIT | MEM_RESERVE)))
1224 WARN("called with wrong alloc type flags (%08lx) !\n", type);
1225 return STATUS_INVALID_PARAMETER;
1228 vprot = VIRTUAL_GetProt( protect );
1229 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1231 /* Reserve the memory */
1233 RtlEnterCriticalSection( &csVirtual );
1235 if (type & MEM_SYSTEM)
1237 if (type & MEM_IMAGE) vprot |= VPROT_IMAGE;
1238 status = create_view( &view, base, size, vprot | VPROT_COMMITTED );
1239 if (status == STATUS_SUCCESS)
1241 view->flags |= VFLAG_VALLOC | VFLAG_SYSTEM;
1245 else if ((type & MEM_RESERVE) || !base)
1247 status = map_view( &view, base, size, vprot );
1248 if (status == STATUS_SUCCESS)
1250 view->flags |= VFLAG_VALLOC;
1254 else /* commit the pages */
1256 if (!(view = VIRTUAL_FindView( base )) ||
1257 ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
1258 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1261 RtlLeaveCriticalSection( &csVirtual );
1263 if (status == STATUS_SUCCESS)
1272 /***********************************************************************
1273 * NtFreeVirtualMemory (NTDLL.@)
1274 * ZwFreeVirtualMemory (NTDLL.@)
1276 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr, ULONG type )
1280 NTSTATUS status = STATUS_SUCCESS;
1281 LPVOID addr = *addr_ptr;
1282 DWORD size = *size_ptr;
1284 TRACE("%p %p %08lx %lx\n", process, addr, size, type );
1286 if (!is_current_process( process ))
1288 ERR("Unsupported on other process\n");
1289 return STATUS_ACCESS_DENIED;
1292 /* Fix the parameters */
1294 size = ROUND_SIZE( addr, size );
1295 base = ROUND_ADDR( addr, page_mask );
1297 RtlEnterCriticalSection(&csVirtual);
1299 if (!(view = VIRTUAL_FindView( base )) ||
1300 (base + size > (char *)view->base + view->size) ||
1301 !(view->flags & VFLAG_VALLOC))
1303 status = STATUS_INVALID_PARAMETER;
1305 else if (type & MEM_SYSTEM)
1307 /* return the values that the caller should use to unmap the area */
1308 *addr_ptr = view->base;
1309 *size_ptr = view->size;
1310 view->flags |= VFLAG_SYSTEM;
1311 delete_view( view );
1313 else if (type == MEM_RELEASE)
1315 /* Free the pages */
1317 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1320 delete_view( view );
1325 else if (type == MEM_DECOMMIT)
1327 status = decommit_pages( view, base - (char *)view->base, size );
1328 if (status == STATUS_SUCCESS)
1336 WARN("called with wrong free type flags (%08lx) !\n", type);
1337 status = STATUS_INVALID_PARAMETER;
1340 RtlLeaveCriticalSection(&csVirtual);
1345 /***********************************************************************
1346 * NtProtectVirtualMemory (NTDLL.@)
1347 * ZwProtectVirtualMemory (NTDLL.@)
1349 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr,
1350 ULONG new_prot, ULONG *old_prot )
1353 NTSTATUS status = STATUS_SUCCESS;
1357 DWORD prot, size = *size_ptr;
1358 LPVOID addr = *addr_ptr;
1360 TRACE("%p %p %08lx %08lx\n", process, addr, size, new_prot );
1362 if (!is_current_process( process ))
1364 ERR("Unsupported on other process\n");
1365 return STATUS_ACCESS_DENIED;
1368 /* Fix the parameters */
1370 size = ROUND_SIZE( addr, size );
1371 base = ROUND_ADDR( addr, page_mask );
1373 RtlEnterCriticalSection( &csVirtual );
1375 if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1377 status = STATUS_INVALID_PARAMETER;
1381 /* Make sure all the pages are committed */
1383 p = view->prot + ((base - (char *)view->base) >> page_shift);
1384 VIRTUAL_GetWin32Prot( *p, &prot, NULL );
1385 for (i = size >> page_shift; i; i--, p++)
1387 if (!(*p & VPROT_COMMITTED))
1389 status = STATUS_NOT_COMMITTED;
1395 if (old_prot) *old_prot = prot;
1396 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1397 if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1400 RtlLeaveCriticalSection( &csVirtual );
1402 if (status == STATUS_SUCCESS)
1411 /***********************************************************************
1412 * NtQueryVirtualMemory (NTDLL.@)
1413 * ZwQueryVirtualMemory (NTDLL.@)
1415 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1416 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1417 ULONG len, ULONG *res_len )
1420 char *base, *alloc_base = 0;
1423 MEMORY_BASIC_INFORMATION *info = buffer;
1425 if (info_class != MemoryBasicInformation)
1427 FIXME("(%p, %p, %d, %p, %ld, %p) Unimplemented information class\n", process, addr,
1428 info_class, buffer, len, res_len);
1429 return STATUS_INVALID_INFO_CLASS;
1431 if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1432 return STATUS_WORKING_SET_LIMIT_RANGE;
1434 if (!is_current_process( process ))
1436 ERR("Unsupported on other process\n");
1437 return STATUS_ACCESS_DENIED;
1440 base = ROUND_ADDR( addr, page_mask );
1442 /* Find the view containing the address */
1444 RtlEnterCriticalSection(&csVirtual);
1445 ptr = list_head( &views_list );
1450 /* make the address space end at the user limit, except if
1451 * the last view was mapped beyond that */
1452 if (alloc_base < (char *)user_space_limit)
1454 if (user_space_limit && base >= (char *)user_space_limit)
1456 RtlLeaveCriticalSection( &csVirtual );
1457 return STATUS_WORKING_SET_LIMIT_RANGE;
1459 size = (char *)user_space_limit - alloc_base;
1461 else size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1465 view = LIST_ENTRY( ptr, struct file_view, entry );
1466 if ((char *)view->base > base)
1468 size = (char *)view->base - alloc_base;
1472 if ((char *)view->base + view->size > base)
1474 alloc_base = view->base;
1478 alloc_base = (char *)view->base + view->size;
1479 ptr = list_next( &views_list, ptr );
1482 /* Fill the info structure */
1486 info->State = MEM_FREE;
1488 info->AllocationProtect = 0;
1493 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1494 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
1495 for (size = base - alloc_base; size < view->size; size += page_mask+1)
1496 if (view->prot[size >> page_shift] != vprot) break;
1497 VIRTUAL_GetWin32Prot( view->protect, &info->AllocationProtect, NULL );
1498 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1499 else if (view->flags & VFLAG_VALLOC) info->Type = MEM_PRIVATE;
1500 else info->Type = MEM_MAPPED;
1502 RtlLeaveCriticalSection(&csVirtual);
1504 info->BaseAddress = (LPVOID)base;
1505 info->AllocationBase = (LPVOID)alloc_base;
1506 info->RegionSize = size - (base - alloc_base);
1507 if (res_len) *res_len = sizeof(*info);
1508 return STATUS_SUCCESS;
1512 /***********************************************************************
1513 * NtLockVirtualMemory (NTDLL.@)
1514 * ZwLockVirtualMemory (NTDLL.@)
1516 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1518 if (!is_current_process( process ))
1520 ERR("Unsupported on other process\n");
1521 return STATUS_ACCESS_DENIED;
1523 return STATUS_SUCCESS;
1527 /***********************************************************************
1528 * NtUnlockVirtualMemory (NTDLL.@)
1529 * ZwUnlockVirtualMemory (NTDLL.@)
1531 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1533 if (!is_current_process( process ))
1535 ERR("Unsupported on other process\n");
1536 return STATUS_ACCESS_DENIED;
1538 return STATUS_SUCCESS;
1542 /***********************************************************************
1543 * NtCreateSection (NTDLL.@)
1544 * ZwCreateSection (NTDLL.@)
1546 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1547 const LARGE_INTEGER *size, ULONG protect,
1548 ULONG sec_flags, HANDLE file )
1552 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
1554 /* Check parameters */
1556 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1558 vprot = VIRTUAL_GetProt( protect );
1559 if (sec_flags & SEC_RESERVE)
1561 if (file) return STATUS_INVALID_PARAMETER;
1563 else vprot |= VPROT_COMMITTED;
1564 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1565 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
1567 /* Create the server object */
1569 SERVER_START_REQ( create_mapping )
1571 req->file_handle = file;
1572 req->size_high = size ? size->u.HighPart : 0;
1573 req->size_low = size ? size->u.LowPart : 0;
1574 req->protect = vprot;
1575 req->access = access;
1576 req->inherit = (attr && (attr->Attributes & OBJ_INHERIT) != 0);
1577 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
1578 ret = wine_server_call( req );
1579 *handle = reply->handle;
1586 /***********************************************************************
1587 * NtOpenSection (NTDLL.@)
1588 * ZwOpenSection (NTDLL.@)
1590 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1593 DWORD len = attr->ObjectName->Length;
1595 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1597 SERVER_START_REQ( open_mapping )
1599 req->access = access;
1600 req->inherit = (attr->Attributes & OBJ_INHERIT) != 0;
1601 wine_server_add_data( req, attr->ObjectName->Buffer, len );
1602 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
1609 /***********************************************************************
1610 * NtMapViewOfSection (NTDLL.@)
1611 * ZwMapViewOfSection (NTDLL.@)
1613 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
1614 ULONG commit_size, const LARGE_INTEGER *offset_ptr, ULONG *size_ptr,
1615 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
1618 FILE_FS_DEVICE_INFORMATION device_info;
1621 int unix_handle = -1;
1624 struct file_view *view;
1625 DWORD size_low, size_high, header_size, shared_size;
1627 BOOL removable = FALSE;
1628 LARGE_INTEGER offset;
1630 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
1632 TRACE("handle=%p process=%p addr=%p off=%lx%08lx size=%x access=%lx\n",
1633 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, size, protect );
1635 if (!is_current_process( process ))
1637 ERR("Unsupported on other process\n");
1638 return STATUS_ACCESS_DENIED;
1641 /* Check parameters */
1643 if ((offset.u.LowPart & granularity_mask) ||
1644 (*addr_ptr && ((UINT_PTR)*addr_ptr & granularity_mask)))
1645 return STATUS_INVALID_PARAMETER;
1647 SERVER_START_REQ( get_mapping_info )
1649 req->handle = handle;
1650 res = wine_server_call( req );
1651 prot = reply->protect;
1653 size_low = reply->size_low;
1654 size_high = reply->size_high;
1655 header_size = reply->header_size;
1656 shared_file = reply->shared_file;
1657 shared_size = reply->shared_size;
1660 if (res) return res;
1662 if ((res = wine_server_handle_to_fd( handle, 0, &unix_handle, NULL ))) return res;
1664 if (NtQueryVolumeInformationFile( handle, &io, &device_info, sizeof(device_info),
1665 FileFsDeviceInformation ) == STATUS_SUCCESS)
1666 removable = device_info.Characteristics & FILE_REMOVABLE_MEDIA;
1668 if (prot & VPROT_IMAGE)
1674 if ((res = wine_server_handle_to_fd( shared_file, GENERIC_READ, &shared_fd,
1676 res = map_image( handle, unix_handle, base, size_low, header_size,
1677 shared_fd, removable, addr_ptr );
1678 wine_server_release_fd( shared_file, shared_fd );
1679 NtClose( shared_file );
1683 res = map_image( handle, unix_handle, base, size_low, header_size,
1684 -1, removable, addr_ptr );
1686 wine_server_release_fd( handle, unix_handle );
1687 if (!res) *size_ptr = size_low;
1692 ERR("Sizes larger than 4Gb not supported\n");
1694 if ((offset.u.LowPart >= size_low) ||
1695 (*size_ptr > size_low - offset.u.LowPart))
1697 res = STATUS_INVALID_PARAMETER;
1700 if (*size_ptr) size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
1701 else size = size_low - offset.u.LowPart;
1707 case PAGE_READWRITE:
1708 case PAGE_EXECUTE_READWRITE:
1709 if (!(prot & VPROT_WRITE))
1711 res = STATUS_INVALID_PARAMETER;
1717 case PAGE_WRITECOPY:
1719 case PAGE_EXECUTE_READ:
1720 case PAGE_EXECUTE_WRITECOPY:
1721 if (prot & VPROT_READ) break;
1724 res = STATUS_INVALID_PARAMETER;
1728 /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1729 * which has a view of this mapping commits some pages, they will
1730 * appear commited in all other processes, which have the same
1731 * view created. Since we don`t support this yet, we create the
1732 * whole mapping commited.
1734 prot |= VPROT_COMMITTED;
1736 /* Reserve a properly aligned area */
1738 RtlEnterCriticalSection( &csVirtual );
1740 res = map_view( &view, *addr_ptr, size, prot );
1743 RtlLeaveCriticalSection( &csVirtual );
1749 TRACE("handle=%p size=%x offset=%lx%08lx\n",
1750 handle, size, offset.u.HighPart, offset.u.LowPart );
1752 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, prot, removable );
1753 if (res == STATUS_SUCCESS)
1755 if (!removable) /* don't keep handle open on removable media */
1756 NtDuplicateObject( NtCurrentProcess(), handle,
1757 NtCurrentProcess(), &view->mapping,
1758 0, 0, DUPLICATE_SAME_ACCESS );
1760 *addr_ptr = view->base;
1765 ERR( "map_file_into_view %p %x %lx%08lx failed\n",
1766 view->base, size, offset.u.HighPart, offset.u.LowPart );
1767 delete_view( view );
1770 RtlLeaveCriticalSection( &csVirtual );
1773 wine_server_release_fd( handle, unix_handle );
1778 /***********************************************************************
1779 * NtUnmapViewOfSection (NTDLL.@)
1780 * ZwUnmapViewOfSection (NTDLL.@)
1782 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
1785 NTSTATUS status = STATUS_INVALID_PARAMETER;
1786 void *base = ROUND_ADDR( addr, page_mask );
1788 if (!is_current_process( process ))
1790 ERR("Unsupported on other process\n");
1791 return STATUS_ACCESS_DENIED;
1793 RtlEnterCriticalSection( &csVirtual );
1794 if ((view = VIRTUAL_FindView( base )) && (base == view->base))
1796 delete_view( view );
1797 status = STATUS_SUCCESS;
1799 RtlLeaveCriticalSection( &csVirtual );
1804 /***********************************************************************
1805 * NtFlushVirtualMemory (NTDLL.@)
1806 * ZwFlushVirtualMemory (NTDLL.@)
1808 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
1809 ULONG *size_ptr, ULONG unknown )
1812 NTSTATUS status = STATUS_SUCCESS;
1813 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
1815 if (!is_current_process( process ))
1817 ERR("Unsupported on other process\n");
1818 return STATUS_ACCESS_DENIED;
1820 RtlEnterCriticalSection( &csVirtual );
1821 if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
1824 if (!*size_ptr) *size_ptr = view->size;
1826 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
1828 RtlLeaveCriticalSection( &csVirtual );
1833 /***********************************************************************
1834 * NtReadVirtualMemory (NTDLL.@)
1835 * ZwReadVirtualMemory (NTDLL.@)
1837 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
1838 SIZE_T size, SIZE_T *bytes_read )
1842 SERVER_START_REQ( read_process_memory )
1844 req->handle = process;
1845 req->addr = (void *)addr;
1846 wine_server_set_reply( req, buffer, size );
1847 if ((status = wine_server_call( req ))) size = 0;
1850 if (bytes_read) *bytes_read = size;
1855 /***********************************************************************
1856 * NtWriteVirtualMemory (NTDLL.@)
1857 * ZwWriteVirtualMemory (NTDLL.@)
1859 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
1860 SIZE_T size, SIZE_T *bytes_written )
1862 static const unsigned int zero;
1863 unsigned int first_offset, last_offset, first_mask, last_mask;
1866 if (!size) return STATUS_INVALID_PARAMETER;
1868 /* compute the mask for the first int */
1870 first_offset = (unsigned int)addr % sizeof(int);
1871 memset( &first_mask, 0, first_offset );
1873 /* compute the mask for the last int */
1874 last_offset = (size + first_offset) % sizeof(int);
1876 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1878 SERVER_START_REQ( write_process_memory )
1880 req->handle = process;
1881 req->addr = (char *)addr - first_offset;
1882 req->first_mask = first_mask;
1883 req->last_mask = last_mask;
1884 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1885 wine_server_add_data( req, buffer, size );
1886 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1888 if ((status = wine_server_call( req ))) size = 0;
1891 if (bytes_written) *bytes_written = size;