2 * Win32 virtual memory functions
4 * Copyright 1997, 2002 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "wine/port.h"
26 #ifdef HAVE_SYS_ERRNO_H
27 #include <sys/errno.h>
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
41 #ifdef HAVE_SYS_MMAN_H
42 # include <sys/mman.h>
44 #ifdef HAVE_VALGRIND_VALGRIND_H
45 # include <valgrind/valgrind.h>
48 #define NONAMELESSUNION
49 #define NONAMELESSSTRUCT
51 #define WIN32_NO_STATUS
54 #include "wine/library.h"
55 #include "wine/server.h"
56 #include "wine/list.h"
57 #include "wine/debug.h"
58 #include "ntdll_misc.h"
60 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
61 WINE_DECLARE_DEBUG_CHANNEL(module);
68 #define MAP_NORESERVE 0
72 typedef struct file_view
74 struct list entry; /* Entry in global view list */
75 void *base; /* Base address */
76 size_t size; /* Size in bytes */
77 HANDLE mapping; /* Handle to the file mapping */
78 unsigned int protect; /* Protection for all pages at allocation time */
79 BYTE prot[1]; /* Protection byte for each page */
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 RTL_CRITICAL_SECTION csVirtual;
107 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
110 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
111 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
113 static RTL_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 static void *address_space_limit = (void *)0xc0000000; /* top of the total available address space */
122 static void *user_space_limit = (void *)0x7fff0000; /* top of the user address space */
123 static void *working_set_limit = (void *)0x7fff0000; /* top of the current working set */
125 static UINT page_shift;
126 static UINT page_size;
127 static UINT_PTR page_mask;
128 static void *address_space_limit;
129 static void *user_space_limit;
130 static void *working_set_limit;
131 #endif /* __i386__ */
133 #define ROUND_ADDR(addr,mask) \
134 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
136 #define ROUND_SIZE(addr,size) \
137 (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
139 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
140 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
142 #define VIRTUAL_HEAP_SIZE (4*1024*1024)
144 static HANDLE virtual_heap;
145 static void *preload_reserve_start;
146 static void *preload_reserve_end;
147 static int use_locks;
148 static int force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
151 /***********************************************************************
154 static const char *VIRTUAL_GetProtStr( BYTE prot )
156 static char buffer[6];
157 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
158 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
159 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
160 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
161 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
167 /***********************************************************************
168 * VIRTUAL_GetUnixProt
170 * Convert page protections to protection for mmap/mprotect.
172 static int VIRTUAL_GetUnixProt( BYTE vprot )
175 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
177 if (vprot & VPROT_READ) prot |= PROT_READ;
178 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
179 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
180 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
181 if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
183 if (!prot) prot = PROT_NONE;
188 /***********************************************************************
191 static void VIRTUAL_DumpView( FILE_VIEW *view )
194 char *addr = view->base;
195 BYTE prot = view->prot[0];
197 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
198 if (view->protect & VPROT_SYSTEM)
199 TRACE( " (system)\n" );
200 else if (view->protect & VPROT_VALLOC)
201 TRACE( " (valloc)\n" );
202 else if (view->mapping)
203 TRACE( " %p\n", view->mapping );
205 TRACE( " (anonymous)\n");
207 for (count = i = 1; i < view->size >> page_shift; i++, count++)
209 if (view->prot[i] == prot) continue;
210 TRACE( " %p - %p %s\n",
211 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
212 addr += (count << page_shift);
213 prot = view->prot[i];
217 TRACE( " %p - %p %s\n",
218 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
222 /***********************************************************************
226 static void VIRTUAL_Dump(void)
229 struct file_view *view;
231 TRACE( "Dump of all virtual memory views:\n" );
232 server_enter_uninterrupted_section( &csVirtual, &sigset );
233 LIST_FOR_EACH_ENTRY( view, &views_list, FILE_VIEW, entry )
235 VIRTUAL_DumpView( view );
237 server_leave_uninterrupted_section( &csVirtual, &sigset );
242 /***********************************************************************
245 * Find the view containing a given address. The csVirtual section must be held by caller.
254 static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
256 struct file_view *view;
258 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
260 if (view->base > addr) break; /* no matching view */
261 if ((const char *)view->base + view->size <= (const char *)addr) continue;
262 if ((const char *)view->base + view->size < (const char *)addr + size) break; /* size too large */
263 if ((const char *)addr + size < (const char *)addr) break; /* overflow */
270 /***********************************************************************
273 static inline UINT_PTR get_mask( ULONG zero_bits )
275 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
276 if (zero_bits < page_shift) zero_bits = page_shift;
277 return (1 << zero_bits) - 1;
281 /***********************************************************************
284 * Find the first view overlapping at least part of the specified range.
285 * The csVirtual section must be held by caller.
287 static struct file_view *find_view_range( const void *addr, size_t size )
289 struct file_view *view;
291 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
293 if ((const char *)view->base >= (const char *)addr + size) break;
294 if ((const char *)view->base + view->size > (const char *)addr) return view;
300 /***********************************************************************
303 * Find a free area between views inside the specified range.
304 * The csVirtual section must be held by caller.
306 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
313 start = ROUND_ADDR( (char *)end - size, mask );
314 if (start >= end || start < base) return NULL;
316 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
318 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
320 if ((char *)view->base + view->size <= (char *)start) break;
321 if ((char *)view->base >= (char *)start + size) continue;
322 start = ROUND_ADDR( (char *)view->base - size, mask );
323 /* stop if remaining space is not large enough */
324 if (!start || start >= end || start < base) return NULL;
329 start = ROUND_ADDR( (char *)base + mask, mask );
330 if (start >= end || (char *)end - (char *)start < size) return NULL;
332 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
334 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
336 if ((char *)view->base >= (char *)start + size) break;
337 if ((char *)view->base + view->size <= (char *)start) continue;
338 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
339 /* stop if remaining space is not large enough */
340 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
347 /***********************************************************************
350 * Add a reserved area to the list maintained by libwine.
351 * The csVirtual section must be held by caller.
353 static void add_reserved_area( void *addr, size_t size )
355 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
357 if (addr < user_space_limit)
359 /* unmap the part of the area that is below the limit */
360 assert( (char *)addr + size > (char *)user_space_limit );
361 munmap( addr, (char *)user_space_limit - (char *)addr );
362 size -= (char *)user_space_limit - (char *)addr;
363 addr = user_space_limit;
365 /* blow away existing mappings */
366 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
367 wine_mmap_add_reserved_area( addr, size );
371 /***********************************************************************
374 * Check if an address range goes beyond a given limit.
376 static inline int is_beyond_limit( const void *addr, size_t size, const void *limit )
378 return (addr >= limit || (const char *)addr + size > (const char *)limit);
382 /***********************************************************************
385 * Unmap an area, or simply replace it by an empty mapping if it is
386 * in a reserved area. The csVirtual section must be held by caller.
388 static inline void unmap_area( void *addr, size_t size )
390 if (wine_mmap_is_in_reserved_area( addr, size ))
391 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
392 else if (is_beyond_limit( addr, size, user_space_limit ))
393 add_reserved_area( addr, size );
395 munmap( addr, size );
399 /***********************************************************************
402 * Deletes a view. The csVirtual section must be held by caller.
404 static void delete_view( struct file_view *view ) /* [in] View */
406 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
407 list_remove( &view->entry );
408 if (view->mapping) NtClose( view->mapping );
409 RtlFreeHeap( virtual_heap, 0, view );
413 /***********************************************************************
416 * Create a view. The csVirtual section must be held by caller.
418 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
420 struct file_view *view;
422 int unix_prot = VIRTUAL_GetUnixProt( vprot );
424 assert( !((UINT_PTR)base & page_mask) );
425 assert( !(size & page_mask) );
427 /* Create the view structure */
429 if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
431 FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
432 return STATUS_NO_MEMORY;
438 view->protect = vprot;
439 memset( view->prot, vprot, size >> page_shift );
441 /* Insert it in the linked list */
443 LIST_FOR_EACH( ptr, &views_list )
445 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
446 if (next->base > base) break;
448 list_add_before( ptr, &view->entry );
450 /* Check for overlapping views. This can happen if the previous view
451 * was a system view that got unmapped behind our back. In that case
452 * we recover by simply deleting it. */
454 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
456 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
457 if ((char *)prev->base + prev->size > (char *)base)
459 TRACE( "overlapping prev view %p-%p for %p-%p\n",
460 prev->base, (char *)prev->base + prev->size,
461 base, (char *)base + view->size );
462 assert( prev->protect & VPROT_SYSTEM );
466 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
468 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
469 if ((char *)base + view->size > (char *)next->base)
471 TRACE( "overlapping next view %p-%p for %p-%p\n",
472 next->base, (char *)next->base + next->size,
473 base, (char *)base + view->size );
474 assert( next->protect & VPROT_SYSTEM );
480 VIRTUAL_DEBUG_DUMP_VIEW( view );
482 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
484 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
485 mprotect( base, size, unix_prot | PROT_EXEC );
487 return STATUS_SUCCESS;
491 /***********************************************************************
492 * VIRTUAL_GetWin32Prot
494 * Convert page protections to Win32 flags.
496 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
498 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
499 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
500 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
505 /***********************************************************************
508 * Build page protections from Win32 flags.
511 * protect [I] Win32 protection flags
514 * Value of page protection flags
516 static BYTE VIRTUAL_GetProt( DWORD protect )
520 switch(protect & 0xff)
526 vprot = VPROT_READ | VPROT_WRITE;
529 vprot = VPROT_READ | VPROT_WRITECOPY;
534 case PAGE_EXECUTE_READ:
535 vprot = VPROT_EXEC | VPROT_READ;
537 case PAGE_EXECUTE_READWRITE:
538 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
540 case PAGE_EXECUTE_WRITECOPY:
541 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
548 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
549 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
554 /***********************************************************************
557 * Change the protection of a range of pages.
563 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
564 void *base, /* [in] Starting address */
565 size_t size, /* [in] Size in bytes */
566 BYTE vprot ) /* [in] Protections to use */
568 int unix_prot = VIRTUAL_GetUnixProt(vprot);
569 BYTE *p = view->prot + (((char *)base - (char *)view->base) >> page_shift);
572 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
574 if (view->protect & VPROT_WRITEWATCH)
576 /* each page may need different protections depending on write watch flag */
581 p[0] = vprot | (p[0] & VPROT_WRITEWATCH);
582 unix_prot = VIRTUAL_GetUnixProt( p[0] );
583 for (count = i = 1; i < size >> page_shift; i++, count++)
585 p[i] = vprot | (p[i] & VPROT_WRITEWATCH);
586 prot = VIRTUAL_GetUnixProt( p[i] );
587 if (prot == unix_prot) continue;
588 mprotect( addr, count << page_shift, unix_prot );
589 addr += count << page_shift;
593 if (count) mprotect( addr, count << page_shift, unix_prot );
594 VIRTUAL_DEBUG_DUMP_VIEW( view );
598 /* if setting stack guard pages, store the permissions first, as the guard may be
599 * triggered at any point after mprotect and change the permissions again */
600 if ((vprot & VPROT_GUARD) &&
601 ((char *)base >= (char *)NtCurrentTeb()->DeallocationStack) &&
602 ((char *)base < (char *)NtCurrentTeb()->Tib.StackBase))
604 memset( p, vprot, size >> page_shift );
605 mprotect( base, size, unix_prot );
606 VIRTUAL_DEBUG_DUMP_VIEW( view );
610 if (force_exec_prot && !(view->protect & VPROT_NOEXEC) &&
611 (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
613 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
614 if (!mprotect( base, size, unix_prot | PROT_EXEC )) goto done;
615 /* exec + write may legitimately fail, in that case fall back to write only */
616 if (!(unix_prot & PROT_WRITE)) return FALSE;
619 if (mprotect( base, size, unix_prot )) return FALSE; /* FIXME: last error */
622 memset( p, vprot, size >> page_shift );
623 VIRTUAL_DEBUG_DUMP_VIEW( view );
628 /***********************************************************************
629 * reset_write_watches
631 * Reset write watches in a memory range.
633 static void reset_write_watches( struct file_view *view, void *base, SIZE_T size )
638 BYTE *p = view->prot + ((addr - (char *)view->base) >> page_shift);
640 p[0] |= VPROT_WRITEWATCH;
641 unix_prot = VIRTUAL_GetUnixProt( p[0] );
642 for (count = i = 1; i < size >> page_shift; i++, count++)
644 p[i] |= VPROT_WRITEWATCH;
645 prot = VIRTUAL_GetUnixProt( p[i] );
646 if (prot == unix_prot) continue;
647 mprotect( addr, count << page_shift, unix_prot );
648 addr += count << page_shift;
652 if (count) mprotect( addr, count << page_shift, unix_prot );
656 /***********************************************************************
659 * Release the extra memory while keeping the range starting on the granularity boundary.
661 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
663 if ((ULONG_PTR)ptr & mask)
665 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
666 munmap( ptr, extra );
667 ptr = (char *)ptr + extra;
670 if (total_size > wanted_size)
671 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
685 /***********************************************************************
686 * alloc_reserved_area_callback
688 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
690 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
692 static void * const address_space_start = (void *)0x110000;
693 struct alloc_area *alloc = arg;
694 void *end = (char *)start + size;
696 if (start < address_space_start) start = address_space_start;
697 if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
698 if (start >= end) return 0;
700 /* make sure we don't touch the preloader reserved range */
701 if (preload_reserve_end >= start)
703 if (preload_reserve_end >= end)
705 if (preload_reserve_start <= start) return 0; /* no space in that area */
706 if (preload_reserve_start < end) end = preload_reserve_start;
708 else if (preload_reserve_start <= start) start = preload_reserve_end;
711 /* range is split in two by the preloader reservation, try first part */
712 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
713 alloc->mask, alloc->top_down )))
715 /* then fall through to try second part */
716 start = preload_reserve_end;
719 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
726 /***********************************************************************
729 * Create a view and mmap the corresponding memory area.
730 * The csVirtual section must be held by caller.
732 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
733 int top_down, unsigned int vprot )
740 if (is_beyond_limit( base, size, address_space_limit ))
741 return STATUS_WORKING_SET_LIMIT_RANGE;
743 switch (wine_mmap_is_in_reserved_area( base, size ))
745 case -1: /* partially in a reserved area */
746 return STATUS_CONFLICTING_ADDRESSES;
748 case 0: /* not in a reserved area, do a normal allocation */
749 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
751 if (errno == ENOMEM) return STATUS_NO_MEMORY;
752 return STATUS_INVALID_PARAMETER;
756 /* We couldn't get the address we wanted */
757 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
758 else munmap( ptr, size );
759 return STATUS_CONFLICTING_ADDRESSES;
764 case 1: /* in a reserved area, make sure the address is available */
765 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
766 /* replace the reserved area by our mapping */
767 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
768 return STATUS_INVALID_PARAMETER;
771 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
775 size_t view_size = size + mask + 1;
776 struct alloc_area alloc;
780 alloc.top_down = top_down;
781 alloc.limit = user_space_limit;
782 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
785 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
786 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
787 return STATUS_INVALID_PARAMETER;
793 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
795 if (errno == ENOMEM) return STATUS_NO_MEMORY;
796 return STATUS_INVALID_PARAMETER;
798 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
799 /* if we got something beyond the user limit, unmap it and retry */
800 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
803 ptr = unmap_extra_space( ptr, view_size, size, mask );
806 status = create_view( view_ret, ptr, size, vprot );
807 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
812 /***********************************************************************
815 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
816 * The csVirtual section must be held by caller.
818 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
819 off_t offset, unsigned int vprot, BOOL removable )
822 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
823 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
825 assert( start < view->size );
826 assert( start + size <= view->size );
828 /* only try mmap if media is not removable (or if we require write access) */
829 if (!removable || shared_write)
831 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
833 if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
836 /* mmap() failed; if this is because the file offset is not */
837 /* page-aligned (EINVAL), or because the underlying filesystem */
838 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
839 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
840 if (shared_write) /* we cannot fake shared write mappings */
842 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
843 ERR( "shared writable mmap not supported, broken filesystem?\n" );
844 return STATUS_NOT_SUPPORTED;
848 /* Reserve the memory with an anonymous mmap */
849 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
850 if (ptr == (void *)-1) return FILE_GetNtStatus();
851 /* Now read in the file */
852 pread( fd, ptr, size, offset );
853 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
855 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
856 return STATUS_SUCCESS;
860 /***********************************************************************
863 * Get the size of the committed range starting at base.
864 * Also return the protections for the first page.
866 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
870 start = ((char *)base - (char *)view->base) >> page_shift;
871 *vprot = view->prot[start];
873 if (view->mapping && !(view->protect & VPROT_COMMITTED))
876 SERVER_START_REQ( get_mapping_committed_range )
878 req->handle = view->mapping;
879 req->offset = start << page_shift;
880 if (!wine_server_call( req ))
883 if (reply->committed)
885 *vprot |= VPROT_COMMITTED;
886 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
893 for (i = start + 1; i < view->size >> page_shift; i++)
894 if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
895 return (i - start) << page_shift;
899 /***********************************************************************
902 * Decommit some pages of a given view.
903 * The csVirtual section must be held by caller.
905 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
907 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
909 BYTE *p = view->prot + (start >> page_shift);
911 while (size--) *p++ &= ~VPROT_COMMITTED;
912 return STATUS_SUCCESS;
914 return FILE_GetNtStatus();
918 /***********************************************************************
919 * allocate_dos_memory
921 * Allocate the DOS memory range.
923 static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
927 void * const low_64k = (void *)0x10000;
928 const size_t dosmem_size = 0x110000;
929 int unix_prot = VIRTUAL_GetUnixProt( vprot );
932 /* check for existing view */
934 if ((ptr = list_head( &views_list )))
936 struct file_view *first_view = LIST_ENTRY( ptr, struct file_view, entry );
937 if (first_view->base < (void *)dosmem_size) return STATUS_CONFLICTING_ADDRESSES;
940 /* check without the first 64K */
942 if (wine_mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
944 addr = wine_anon_mmap( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
947 if (addr != (void *)-1) munmap( addr, dosmem_size - 0x10000 );
948 return map_view( view, NULL, dosmem_size, 0xffff, 0, vprot );
952 /* now try to allocate the low 64K too */
954 if (wine_mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
956 addr = wine_anon_mmap( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
957 if (addr == (void *)page_size)
960 TRACE( "successfully mapped low 64K range\n" );
964 if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
966 TRACE( "failed to map low 64K range\n" );
970 /* now reserve the whole range */
972 size = (char *)dosmem_size - (char *)addr;
973 wine_anon_mmap( addr, size, unix_prot, MAP_FIXED );
974 return create_view( view, addr, size, vprot );
978 /***********************************************************************
981 * Map an executable (PE format) image into memory.
983 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
984 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, PVOID *addr_ptr )
986 IMAGE_DOS_HEADER *dos;
987 IMAGE_NT_HEADERS *nt;
988 IMAGE_SECTION_HEADER *sec;
989 IMAGE_DATA_DIRECTORY *imports;
990 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
995 struct file_view *view = NULL;
996 char *ptr, *header_end;
999 /* zero-map the whole range */
1001 server_enter_uninterrupted_section( &csVirtual, &sigset );
1003 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
1004 status = map_view( &view, base, total_size, mask, FALSE,
1005 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1007 if (status == STATUS_CONFLICTING_ADDRESSES)
1008 status = map_view( &view, NULL, total_size, mask, FALSE,
1009 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1011 if (status != STATUS_SUCCESS) goto error;
1014 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
1016 /* map the header */
1018 if (fstat( fd, &st ) == -1)
1020 status = FILE_GetNtStatus();
1023 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
1024 if (!st.st_size) goto error;
1025 header_size = min( header_size, st.st_size );
1026 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1027 !dup_mapping ) != STATUS_SUCCESS) goto error;
1028 dos = (IMAGE_DOS_HEADER *)ptr;
1029 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1030 header_end = ptr + ROUND_SIZE( 0, header_size );
1031 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1032 if ((char *)(nt + 1) > header_end) goto error;
1033 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1034 if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
1036 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
1037 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
1039 /* check the architecture */
1042 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64)
1044 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
1047 MESSAGE("Trying to load PE image for unsupported architecture (");
1048 switch (nt->FileHeader.Machine)
1050 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
1051 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
1052 case IMAGE_FILE_MACHINE_I386: MESSAGE("I386"); break;
1053 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
1054 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
1055 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
1056 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
1057 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
1058 case IMAGE_FILE_MACHINE_IA64: MESSAGE("IA-64"); break;
1059 case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
1060 case IMAGE_FILE_MACHINE_AMD64: MESSAGE("AMD-64"); break;
1061 case IMAGE_FILE_MACHINE_ARM: MESSAGE("ARM"); break;
1062 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
1068 /* check for non page-aligned binary */
1070 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1072 /* unaligned sections, this happens for native subsystem binaries */
1073 /* in that case Windows simply maps in the whole file */
1075 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
1076 !dup_mapping ) != STATUS_SUCCESS) goto error;
1078 /* check that all sections are loaded at the right offset */
1079 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1080 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1082 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1083 goto error; /* Windows refuses to load in that case too */
1086 /* set the image protections */
1087 VIRTUAL_SetProt( view, ptr, total_size,
1088 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1090 /* no relocations are performed on non page-aligned binaries */
1095 /* map all the sections */
1097 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1099 static const SIZE_T sector_align = 0x1ff;
1100 SIZE_T map_size, file_start, file_size, end;
1102 if (!sec->Misc.VirtualSize)
1103 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1105 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1107 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1108 file_start = sec->PointerToRawData & ~sector_align;
1109 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1110 if (file_size > map_size) file_size = map_size;
1112 /* a few sanity checks */
1113 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1114 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1116 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1117 sec->Name, sec->VirtualAddress, map_size, total_size );
1121 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1122 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1124 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1125 sec->Name, ptr + sec->VirtualAddress,
1126 sec->PointerToRawData, (int)pos, file_size, map_size,
1127 sec->Characteristics );
1128 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1129 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1130 FALSE ) != STATUS_SUCCESS)
1132 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1136 /* check if the import directory falls inside this section */
1137 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1138 imports->VirtualAddress < sec->VirtualAddress + map_size)
1140 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1141 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1142 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1144 map_file_into_view( view, shared_fd, base, end - base,
1145 pos + (base - sec->VirtualAddress),
1146 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1153 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1154 sec->Name, ptr + sec->VirtualAddress,
1155 sec->PointerToRawData, sec->SizeOfRawData,
1156 sec->Misc.VirtualSize, sec->Characteristics );
1158 if (!sec->PointerToRawData || !file_size) continue;
1160 /* Note: if the section is not aligned properly map_file_into_view will magically
1161 * fall back to read(), so we don't need to check anything here.
1163 end = file_start + file_size;
1164 if (sec->PointerToRawData >= st.st_size ||
1165 end > ((st.st_size + sector_align) & ~sector_align) ||
1167 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1168 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1169 !dup_mapping ) != STATUS_SUCCESS)
1171 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1175 if (file_size & page_mask)
1177 end = ROUND_SIZE( 0, file_size );
1178 if (end > map_size) end = map_size;
1179 TRACE_(module)("clearing %p - %p\n",
1180 ptr + sec->VirtualAddress + file_size,
1181 ptr + sec->VirtualAddress + end );
1182 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1187 /* perform base relocation, if necessary */
1190 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1191 !NtCurrentTeb()->Peb->ImageBaseAddress) )
1193 IMAGE_BASE_RELOCATION *rel, *end;
1194 const IMAGE_DATA_DIRECTORY *relocs;
1196 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1198 WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1200 status = STATUS_CONFLICTING_ADDRESSES;
1204 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1205 base, base + total_size, ptr, ptr + total_size );
1207 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1208 rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1209 end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1212 while (rel < end - 1 && rel->SizeOfBlock)
1214 if (rel->VirtualAddress >= total_size)
1216 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1217 status = STATUS_ACCESS_VIOLATION;
1220 rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1221 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1222 (USHORT *)(rel + 1), delta );
1223 if (!rel) goto error;
1227 /* set the image protections */
1229 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1231 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1232 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1235 BYTE vprot = VPROT_COMMITTED;
1237 if (sec->Misc.VirtualSize)
1238 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1240 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1242 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1243 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
1244 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1246 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1247 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1248 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1249 vprot |= VPROT_EXEC;
1251 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
1255 view->mapping = dup_mapping;
1256 server_leave_uninterrupted_section( &csVirtual, &sigset );
1259 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1260 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1262 return STATUS_SUCCESS;
1265 if (view) delete_view( view );
1266 server_leave_uninterrupted_section( &csVirtual, &sigset );
1267 if (dup_mapping) NtClose( dup_mapping );
1272 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1273 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1275 void **heap_base = arg;
1277 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1278 if (size < VIRTUAL_HEAP_SIZE) return 0;
1279 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1280 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1281 return (*heap_base != (void *)-1);
1284 /***********************************************************************
1287 void virtual_init(void)
1289 const char *preload;
1291 struct file_view *heap_view;
1294 page_size = getpagesize();
1295 page_mask = page_size - 1;
1296 /* Make sure we have a power of 2 */
1297 assert( !(page_size & page_mask) );
1299 while ((1 << page_shift) != page_size) page_shift++;
1300 user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1301 #endif /* page_mask */
1302 if ((preload = getenv("WINEPRELOADRESERVE")))
1304 unsigned long start, end;
1305 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1307 preload_reserve_start = (void *)start;
1308 preload_reserve_end = (void *)end;
1312 /* try to find space in a reserved area for the virtual heap */
1313 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1314 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1316 assert( heap_base != (void *)-1 );
1317 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1318 VIRTUAL_HEAP_SIZE, NULL, NULL );
1319 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1323 /***********************************************************************
1324 * virtual_init_threading
1326 void virtual_init_threading(void)
1332 /***********************************************************************
1333 * virtual_get_system_info
1335 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1337 info->dwUnknown1 = 0;
1338 info->uKeMaximumIncrement = 0; /* FIXME */
1339 info->uPageSize = page_size;
1340 info->uMmLowestPhysicalPage = 1;
1341 info->uMmHighestPhysicalPage = 0x7fffffff / page_size;
1342 info->uMmNumberOfPhysicalPages = info->uMmHighestPhysicalPage - info->uMmLowestPhysicalPage;
1343 info->uAllocationGranularity = get_mask(0) + 1;
1344 info->pLowestUserAddress = (void *)0x10000;
1345 info->pMmHighestUserAddress = (char *)user_space_limit - 1;
1346 info->uKeActiveProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1347 info->bKeNumberProcessors = info->uKeActiveProcessors;
1351 /***********************************************************************
1352 * virtual_create_system_view
1354 NTSTATUS virtual_create_system_view( void *base, SIZE_T size, DWORD vprot )
1360 size = ROUND_SIZE( base, size );
1361 base = ROUND_ADDR( base, page_mask );
1362 server_enter_uninterrupted_section( &csVirtual, &sigset );
1363 status = create_view( &view, base, size, vprot );
1364 if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
1365 server_leave_uninterrupted_section( &csVirtual, &sigset );
1370 /***********************************************************************
1371 * virtual_free_system_view
1373 SIZE_T virtual_free_system_view( PVOID *addr_ptr )
1378 char *base = ROUND_ADDR( *addr_ptr, page_mask );
1380 server_enter_uninterrupted_section( &csVirtual, &sigset );
1381 if ((view = VIRTUAL_FindView( base, 0 )))
1383 TRACE( "freeing %p-%p\n", view->base, (char *)view->base + view->size );
1384 /* return the values that the caller should use to unmap the area */
1385 *addr_ptr = view->base;
1386 /* make sure we don't munmap anything from a reserved area */
1387 if (!wine_mmap_is_in_reserved_area( view->base, view->size )) size = view->size;
1388 view->protect |= VPROT_SYSTEM;
1389 delete_view( view );
1391 server_leave_uninterrupted_section( &csVirtual, &sigset );
1396 /***********************************************************************
1397 * virtual_alloc_thread_stack
1399 NTSTATUS virtual_alloc_thread_stack( void *base, SIZE_T size )
1405 server_enter_uninterrupted_section( &csVirtual, &sigset );
1407 if (base) /* already allocated, create a system view */
1409 size = ROUND_SIZE( base, size );
1410 base = ROUND_ADDR( base, page_mask );
1411 if ((status = create_view( &view, base, size,
1412 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC | VPROT_SYSTEM )) != STATUS_SUCCESS)
1417 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1418 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1419 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1421 #ifdef VALGRIND_STACK_REGISTER
1422 /* no need to de-register the stack as it's the one of the main thread */
1423 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1427 /* setup no access guard page */
1428 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1429 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1430 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1432 /* note: limit is lower than base since the stack grows down */
1433 NtCurrentTeb()->DeallocationStack = view->base;
1434 NtCurrentTeb()->Tib.StackBase = (char *)view->base + view->size;
1435 NtCurrentTeb()->Tib.StackLimit = (char *)view->base + 2 * page_size;
1438 server_leave_uninterrupted_section( &csVirtual, &sigset );
1443 /***********************************************************************
1444 * virtual_clear_thread_stack
1446 * Clear the stack contents before calling the main entry point, some broken apps need that.
1448 void virtual_clear_thread_stack(void)
1450 void *stack = NtCurrentTeb()->Tib.StackLimit;
1451 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1453 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1454 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1458 /***********************************************************************
1459 * virtual_handle_fault
1461 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err )
1464 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1467 server_enter_uninterrupted_section( &csVirtual, &sigset );
1468 if ((view = VIRTUAL_FindView( addr, 0 )))
1470 void *page = ROUND_ADDR( addr, page_mask );
1471 BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1472 if (*vprot & VPROT_GUARD)
1474 VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1475 ret = STATUS_GUARD_PAGE_VIOLATION;
1477 if ((err & EXCEPTION_WRITE_FAULT) && (*vprot & VPROT_WRITEWATCH))
1479 *vprot &= ~VPROT_WRITEWATCH;
1480 VIRTUAL_SetProt( view, page, page_size, *vprot );
1481 ret = STATUS_SUCCESS;
1484 server_leave_uninterrupted_section( &csVirtual, &sigset );
1490 /***********************************************************************
1491 * virtual_handle_stack_fault
1493 * Handle an access fault inside the current thread stack.
1494 * Called from inside a signal handler.
1496 BOOL virtual_handle_stack_fault( void *addr )
1501 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1502 if ((view = VIRTUAL_FindView( addr, 0 )))
1504 void *page = ROUND_ADDR( addr, page_mask );
1505 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1506 if (vprot & VPROT_GUARD)
1508 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1509 if ((char *)page + page_size == NtCurrentTeb()->Tib.StackLimit)
1510 NtCurrentTeb()->Tib.StackLimit = page;
1514 RtlLeaveCriticalSection( &csVirtual );
1519 /***********************************************************************
1520 * VIRTUAL_SetForceExec
1522 * Whether to force exec prot on all views.
1524 void VIRTUAL_SetForceExec( BOOL enable )
1526 struct file_view *view;
1529 server_enter_uninterrupted_section( &csVirtual, &sigset );
1530 if (!force_exec_prot != !enable) /* change all existing views */
1532 force_exec_prot = enable;
1534 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1537 char *addr = view->base;
1538 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1539 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1541 if (view->protect & VPROT_NOEXEC) continue;
1542 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1544 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1545 if (prot == unix_prot) continue;
1546 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1548 TRACE( "%s exec prot for %p-%p\n",
1549 force_exec_prot ? "enabling" : "disabling",
1550 addr, addr + (count << page_shift) - 1 );
1551 mprotect( addr, count << page_shift,
1552 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1554 addr += (count << page_shift);
1560 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1562 TRACE( "%s exec prot for %p-%p\n",
1563 force_exec_prot ? "enabling" : "disabling",
1564 addr, addr + (count << page_shift) - 1 );
1565 mprotect( addr, count << page_shift,
1566 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1571 server_leave_uninterrupted_section( &csVirtual, &sigset );
1575 /***********************************************************************
1576 * VIRTUAL_UseLargeAddressSpace
1578 * Increase the address space size for apps that support it.
1580 void VIRTUAL_UseLargeAddressSpace(void)
1582 /* no large address space on win9x */
1583 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1584 user_space_limit = working_set_limit = address_space_limit;
1588 /***********************************************************************
1589 * NtAllocateVirtualMemory (NTDLL.@)
1590 * ZwAllocateVirtualMemory (NTDLL.@)
1592 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1593 SIZE_T *size_ptr, ULONG type, ULONG protect )
1597 SIZE_T size = *size_ptr;
1598 SIZE_T mask = get_mask( zero_bits );
1599 NTSTATUS status = STATUS_SUCCESS;
1600 struct file_view *view;
1603 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1605 if (!size) return STATUS_INVALID_PARAMETER;
1607 if (process != NtCurrentProcess())
1610 apc_result_t result;
1612 memset( &call, 0, sizeof(call) );
1614 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1615 call.virtual_alloc.addr = *ret;
1616 call.virtual_alloc.size = *size_ptr;
1617 call.virtual_alloc.zero_bits = zero_bits;
1618 call.virtual_alloc.op_type = type;
1619 call.virtual_alloc.prot = protect;
1620 status = NTDLL_queue_process_apc( process, &call, &result );
1621 if (status != STATUS_SUCCESS) return status;
1623 if (result.virtual_alloc.status == STATUS_SUCCESS)
1625 *ret = result.virtual_alloc.addr;
1626 *size_ptr = result.virtual_alloc.size;
1628 return result.virtual_alloc.status;
1631 /* Round parameters to a page boundary */
1633 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1635 vprot = VIRTUAL_GetProt( protect ) | VPROT_VALLOC;
1636 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1640 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1641 base = ROUND_ADDR( *ret, mask );
1643 base = ROUND_ADDR( *ret, page_mask );
1644 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1646 /* address 1 is magic to mean DOS area */
1647 if (!base && *ret == (void *)1 && size == 0x110000)
1649 server_enter_uninterrupted_section( &csVirtual, &sigset );
1650 status = allocate_dos_memory( &view, vprot );
1651 if (status == STATUS_SUCCESS)
1654 *size_ptr = view->size;
1656 server_leave_uninterrupted_section( &csVirtual, &sigset );
1660 /* disallow low 64k, wrap-around and kernel space */
1661 if (((char *)base < (char *)0x10000) ||
1662 ((char *)base + size < (char *)base) ||
1663 is_beyond_limit( base, size, address_space_limit ))
1664 return STATUS_INVALID_PARAMETER;
1669 size = (size + page_mask) & ~page_mask;
1672 /* Compute the alloc type flags */
1674 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
1675 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1677 WARN("called with wrong alloc type flags (%08x) !\n", type);
1678 return STATUS_INVALID_PARAMETER;
1681 /* Reserve the memory */
1683 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1685 if ((type & MEM_RESERVE) || !base)
1687 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
1688 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1689 if (status == STATUS_SUCCESS) base = view->base;
1691 else /* commit the pages */
1693 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1694 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1695 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1697 SERVER_START_REQ( add_mapping_committed_range )
1699 req->handle = view->mapping;
1700 req->offset = (char *)base - (char *)view->base;
1702 wine_server_call( req );
1708 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1710 if (status == STATUS_SUCCESS)
1719 /***********************************************************************
1720 * NtFreeVirtualMemory (NTDLL.@)
1721 * ZwFreeVirtualMemory (NTDLL.@)
1723 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1728 NTSTATUS status = STATUS_SUCCESS;
1729 LPVOID addr = *addr_ptr;
1730 SIZE_T size = *size_ptr;
1732 TRACE("%p %p %08lx %x\n", process, addr, size, type );
1734 if (process != NtCurrentProcess())
1737 apc_result_t result;
1739 memset( &call, 0, sizeof(call) );
1741 call.virtual_free.type = APC_VIRTUAL_FREE;
1742 call.virtual_free.addr = addr;
1743 call.virtual_free.size = size;
1744 call.virtual_free.op_type = type;
1745 status = NTDLL_queue_process_apc( process, &call, &result );
1746 if (status != STATUS_SUCCESS) return status;
1748 if (result.virtual_free.status == STATUS_SUCCESS)
1750 *addr_ptr = result.virtual_free.addr;
1751 *size_ptr = result.virtual_free.size;
1753 return result.virtual_free.status;
1756 /* Fix the parameters */
1758 size = ROUND_SIZE( addr, size );
1759 base = ROUND_ADDR( addr, page_mask );
1761 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
1762 if (!base) return STATUS_INVALID_PARAMETER;
1764 server_enter_uninterrupted_section( &csVirtual, &sigset );
1766 if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
1768 status = STATUS_INVALID_PARAMETER;
1770 else if (type == MEM_RELEASE)
1772 /* Free the pages */
1774 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1777 delete_view( view );
1782 else if (type == MEM_DECOMMIT)
1784 status = decommit_pages( view, base - (char *)view->base, size );
1785 if (status == STATUS_SUCCESS)
1793 WARN("called with wrong free type flags (%08x) !\n", type);
1794 status = STATUS_INVALID_PARAMETER;
1797 server_leave_uninterrupted_section( &csVirtual, &sigset );
1802 /***********************************************************************
1803 * NtProtectVirtualMemory (NTDLL.@)
1804 * ZwProtectVirtualMemory (NTDLL.@)
1806 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1807 ULONG new_prot, ULONG *old_prot )
1811 NTSTATUS status = STATUS_SUCCESS;
1814 SIZE_T size = *size_ptr;
1815 LPVOID addr = *addr_ptr;
1817 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
1819 if (process != NtCurrentProcess())
1822 apc_result_t result;
1824 memset( &call, 0, sizeof(call) );
1826 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
1827 call.virtual_protect.addr = addr;
1828 call.virtual_protect.size = size;
1829 call.virtual_protect.prot = new_prot;
1830 status = NTDLL_queue_process_apc( process, &call, &result );
1831 if (status != STATUS_SUCCESS) return status;
1833 if (result.virtual_protect.status == STATUS_SUCCESS)
1835 *addr_ptr = result.virtual_protect.addr;
1836 *size_ptr = result.virtual_protect.size;
1837 if (old_prot) *old_prot = result.virtual_protect.prot;
1839 return result.virtual_protect.status;
1842 /* Fix the parameters */
1844 size = ROUND_SIZE( addr, size );
1845 base = ROUND_ADDR( addr, page_mask );
1847 server_enter_uninterrupted_section( &csVirtual, &sigset );
1849 if (!(view = VIRTUAL_FindView( base, size )))
1851 status = STATUS_INVALID_PARAMETER;
1855 /* Make sure all the pages are committed */
1856 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
1858 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
1859 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1860 if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1862 else status = STATUS_NOT_COMMITTED;
1864 server_leave_uninterrupted_section( &csVirtual, &sigset );
1866 if (status == STATUS_SUCCESS)
1875 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
1876 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
1878 MEMORY_BASIC_INFORMATION *info = arg;
1879 void *end = (char *)start + size;
1881 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
1883 if (info->BaseAddress >= end)
1885 if (info->AllocationBase < end) info->AllocationBase = end;
1889 if (info->BaseAddress >= start)
1891 /* it's a real free area */
1892 info->State = MEM_FREE;
1893 info->Protect = PAGE_NOACCESS;
1894 info->AllocationBase = 0;
1895 info->AllocationProtect = 0;
1897 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
1898 info->RegionSize = (char *)end - (char *)info->BaseAddress;
1900 else /* outside of the reserved area, pretend it's allocated */
1902 info->RegionSize = (char *)start - (char *)info->BaseAddress;
1903 info->State = MEM_RESERVE;
1904 info->Protect = PAGE_NOACCESS;
1905 info->AllocationProtect = PAGE_NOACCESS;
1906 info->Type = MEM_PRIVATE;
1911 #define UNIMPLEMENTED_INFO_CLASS(c) \
1913 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
1914 return STATUS_INVALID_INFO_CLASS
1916 /***********************************************************************
1917 * NtQueryVirtualMemory (NTDLL.@)
1918 * ZwQueryVirtualMemory (NTDLL.@)
1920 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1921 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1922 SIZE_T len, SIZE_T *res_len )
1925 char *base, *alloc_base = 0;
1928 MEMORY_BASIC_INFORMATION *info = buffer;
1931 if (info_class != MemoryBasicInformation)
1935 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
1936 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
1937 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
1940 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
1941 process, addr, info_class, buffer, len, res_len);
1942 return STATUS_INVALID_INFO_CLASS;
1946 if (process != NtCurrentProcess())
1950 apc_result_t result;
1952 memset( &call, 0, sizeof(call) );
1954 call.virtual_query.type = APC_VIRTUAL_QUERY;
1955 call.virtual_query.addr = addr;
1956 status = NTDLL_queue_process_apc( process, &call, &result );
1957 if (status != STATUS_SUCCESS) return status;
1959 if (result.virtual_query.status == STATUS_SUCCESS)
1961 info->BaseAddress = result.virtual_query.base;
1962 info->AllocationBase = result.virtual_query.alloc_base;
1963 info->RegionSize = result.virtual_query.size;
1964 info->State = result.virtual_query.state;
1965 info->Protect = result.virtual_query.prot;
1966 info->AllocationProtect = result.virtual_query.alloc_prot;
1967 info->Type = result.virtual_query.alloc_type;
1968 if (res_len) *res_len = sizeof(*info);
1970 return result.virtual_query.status;
1973 base = ROUND_ADDR( addr, page_mask );
1975 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1977 /* Find the view containing the address */
1979 server_enter_uninterrupted_section( &csVirtual, &sigset );
1980 ptr = list_head( &views_list );
1985 size = (char *)working_set_limit - alloc_base;
1989 view = LIST_ENTRY( ptr, struct file_view, entry );
1990 if ((char *)view->base > base)
1992 size = (char *)view->base - alloc_base;
1996 if ((char *)view->base + view->size > base)
1998 alloc_base = view->base;
2002 alloc_base = (char *)view->base + view->size;
2003 ptr = list_next( &views_list, ptr );
2006 /* Fill the info structure */
2008 info->AllocationBase = alloc_base;
2009 info->BaseAddress = base;
2010 info->RegionSize = size - (base - alloc_base);
2014 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2016 /* not in a reserved area at all, pretend it's allocated */
2017 info->State = MEM_RESERVE;
2018 info->Protect = PAGE_NOACCESS;
2019 info->AllocationProtect = PAGE_NOACCESS;
2020 info->Type = MEM_PRIVATE;
2026 SIZE_T range_size = get_committed_size( view, base, &vprot );
2028 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2029 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2030 info->AllocationBase = alloc_base;
2031 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2032 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2033 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2034 else info->Type = MEM_MAPPED;
2035 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2036 if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2037 info->RegionSize = size - (base - alloc_base);
2039 server_leave_uninterrupted_section( &csVirtual, &sigset );
2041 if (res_len) *res_len = sizeof(*info);
2042 return STATUS_SUCCESS;
2046 /***********************************************************************
2047 * NtLockVirtualMemory (NTDLL.@)
2048 * ZwLockVirtualMemory (NTDLL.@)
2050 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2052 NTSTATUS status = STATUS_SUCCESS;
2054 if (process != NtCurrentProcess())
2057 apc_result_t result;
2059 memset( &call, 0, sizeof(call) );
2061 call.virtual_lock.type = APC_VIRTUAL_LOCK;
2062 call.virtual_lock.addr = *addr;
2063 call.virtual_lock.size = *size;
2064 status = NTDLL_queue_process_apc( process, &call, &result );
2065 if (status != STATUS_SUCCESS) return status;
2067 if (result.virtual_lock.status == STATUS_SUCCESS)
2069 *addr = result.virtual_lock.addr;
2070 *size = result.virtual_lock.size;
2072 return result.virtual_lock.status;
2075 *size = ROUND_SIZE( *addr, *size );
2076 *addr = ROUND_ADDR( *addr, page_mask );
2078 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2083 /***********************************************************************
2084 * NtUnlockVirtualMemory (NTDLL.@)
2085 * ZwUnlockVirtualMemory (NTDLL.@)
2087 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2089 NTSTATUS status = STATUS_SUCCESS;
2091 if (process != NtCurrentProcess())
2094 apc_result_t result;
2096 memset( &call, 0, sizeof(call) );
2098 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2099 call.virtual_unlock.addr = *addr;
2100 call.virtual_unlock.size = *size;
2101 status = NTDLL_queue_process_apc( process, &call, &result );
2102 if (status != STATUS_SUCCESS) return status;
2104 if (result.virtual_unlock.status == STATUS_SUCCESS)
2106 *addr = result.virtual_unlock.addr;
2107 *size = result.virtual_unlock.size;
2109 return result.virtual_unlock.status;
2112 *size = ROUND_SIZE( *addr, *size );
2113 *addr = ROUND_ADDR( *addr, page_mask );
2115 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2120 /***********************************************************************
2121 * NtCreateSection (NTDLL.@)
2122 * ZwCreateSection (NTDLL.@)
2124 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2125 const LARGE_INTEGER *size, ULONG protect,
2126 ULONG sec_flags, HANDLE file )
2130 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2131 struct security_descriptor *sd = NULL;
2132 struct object_attributes objattr;
2134 /* Check parameters */
2136 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2138 objattr.rootdir = attr ? attr->RootDirectory : 0;
2140 objattr.name_len = len;
2143 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2144 if (ret != STATUS_SUCCESS) return ret;
2147 vprot = VIRTUAL_GetProt( protect );
2148 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2149 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2150 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2152 /* Create the server object */
2154 SERVER_START_REQ( create_mapping )
2156 req->access = access;
2157 req->attributes = (attr) ? attr->Attributes : 0;
2158 req->file_handle = file;
2159 req->size = size ? size->QuadPart : 0;
2160 req->protect = vprot;
2161 wine_server_add_data( req, &objattr, sizeof(objattr) );
2162 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2163 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2164 ret = wine_server_call( req );
2165 *handle = reply->handle;
2169 NTDLL_free_struct_sd( sd );
2175 /***********************************************************************
2176 * NtOpenSection (NTDLL.@)
2177 * ZwOpenSection (NTDLL.@)
2179 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2182 DWORD len = attr->ObjectName->Length;
2184 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2186 SERVER_START_REQ( open_mapping )
2188 req->access = access;
2189 req->attributes = attr->Attributes;
2190 req->rootdir = attr->RootDirectory;
2191 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2192 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
2199 /***********************************************************************
2200 * NtMapViewOfSection (NTDLL.@)
2201 * ZwMapViewOfSection (NTDLL.@)
2203 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2204 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2205 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2208 ULONGLONG full_size;
2211 SIZE_T mask = get_mask( zero_bits );
2212 int unix_handle = -1, needs_close;
2213 unsigned int map_vprot, vprot;
2215 struct file_view *view;
2217 HANDLE dup_mapping, shared_file;
2218 LARGE_INTEGER offset;
2221 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2223 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2224 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, size, protect );
2226 /* Check parameters */
2228 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2229 return STATUS_INVALID_PARAMETER;
2231 if (process != NtCurrentProcess())
2234 apc_result_t result;
2236 memset( &call, 0, sizeof(call) );
2238 call.map_view.type = APC_MAP_VIEW;
2239 call.map_view.handle = handle;
2240 call.map_view.addr = *addr_ptr;
2241 call.map_view.size = *size_ptr;
2242 call.map_view.offset = offset.QuadPart;
2243 call.map_view.zero_bits = zero_bits;
2244 call.map_view.alloc_type = alloc_type;
2245 call.map_view.prot = protect;
2246 res = NTDLL_queue_process_apc( process, &call, &result );
2247 if (res != STATUS_SUCCESS) return res;
2249 if (result.map_view.status == STATUS_SUCCESS)
2251 *addr_ptr = result.map_view.addr;
2252 *size_ptr = result.map_view.size;
2254 return result.map_view.status;
2260 access = SECTION_QUERY;
2262 case PAGE_READWRITE:
2263 case PAGE_EXECUTE_READWRITE:
2264 access = SECTION_QUERY | SECTION_MAP_WRITE;
2267 case PAGE_WRITECOPY:
2269 case PAGE_EXECUTE_READ:
2270 case PAGE_EXECUTE_WRITECOPY:
2271 access = SECTION_QUERY | SECTION_MAP_READ;
2274 return STATUS_INVALID_PARAMETER;
2277 SERVER_START_REQ( get_mapping_info )
2279 req->handle = handle;
2280 req->access = access;
2281 res = wine_server_call( req );
2282 map_vprot = reply->protect;
2284 full_size = reply->size;
2285 header_size = reply->header_size;
2286 dup_mapping = reply->mapping;
2287 shared_file = reply->shared_file;
2290 if (res) return res;
2293 if (sizeof(size) < sizeof(full_size) && (size != full_size))
2294 ERR( "Sizes larger than 4Gb (%x%08x) not supported on this platform\n",
2295 (DWORD)(full_size >> 32), (DWORD)full_size );
2297 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2299 if (map_vprot & VPROT_IMAGE)
2303 int shared_fd, shared_needs_close;
2305 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2306 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2307 res = map_image( handle, unix_handle, base, size, mask, header_size,
2308 shared_fd, dup_mapping, addr_ptr );
2309 if (shared_needs_close) close( shared_fd );
2310 NtClose( shared_file );
2314 res = map_image( handle, unix_handle, base, size, mask, header_size,
2315 -1, dup_mapping, addr_ptr );
2317 if (needs_close) close( unix_handle );
2318 if (!res) *size_ptr = size;
2322 if ((offset.QuadPart >= size) || (*size_ptr > size - offset.QuadPart))
2324 res = STATUS_INVALID_PARAMETER;
2327 if (*size_ptr) size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2328 else size = size - offset.QuadPart;
2330 /* Reserve a properly aligned area */
2332 server_enter_uninterrupted_section( &csVirtual, &sigset );
2334 vprot = VIRTUAL_GetProt( protect ) | (map_vprot & VPROT_COMMITTED);
2335 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2338 server_leave_uninterrupted_section( &csVirtual, &sigset );
2344 TRACE("handle=%p size=%lx offset=%x%08x\n",
2345 handle, size, offset.u.HighPart, offset.u.LowPart );
2347 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2348 if (res == STATUS_SUCCESS)
2350 *addr_ptr = view->base;
2352 view->mapping = dup_mapping;
2353 dup_mapping = 0; /* don't close it */
2357 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2358 view->base, size, offset.u.HighPart, offset.u.LowPart );
2359 delete_view( view );
2362 server_leave_uninterrupted_section( &csVirtual, &sigset );
2365 if (dup_mapping) NtClose( dup_mapping );
2366 if (needs_close) close( unix_handle );
2371 /***********************************************************************
2372 * NtUnmapViewOfSection (NTDLL.@)
2373 * ZwUnmapViewOfSection (NTDLL.@)
2375 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2378 NTSTATUS status = STATUS_INVALID_PARAMETER;
2380 void *base = ROUND_ADDR( addr, page_mask );
2382 if (process != NtCurrentProcess())
2385 apc_result_t result;
2387 memset( &call, 0, sizeof(call) );
2389 call.unmap_view.type = APC_UNMAP_VIEW;
2390 call.unmap_view.addr = addr;
2391 status = NTDLL_queue_process_apc( process, &call, &result );
2392 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2396 server_enter_uninterrupted_section( &csVirtual, &sigset );
2397 if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base))
2399 delete_view( view );
2400 status = STATUS_SUCCESS;
2402 server_leave_uninterrupted_section( &csVirtual, &sigset );
2407 /***********************************************************************
2408 * NtFlushVirtualMemory (NTDLL.@)
2409 * ZwFlushVirtualMemory (NTDLL.@)
2411 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2412 SIZE_T *size_ptr, ULONG unknown )
2415 NTSTATUS status = STATUS_SUCCESS;
2417 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2419 if (process != NtCurrentProcess())
2422 apc_result_t result;
2424 memset( &call, 0, sizeof(call) );
2426 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2427 call.virtual_flush.addr = addr;
2428 call.virtual_flush.size = *size_ptr;
2429 status = NTDLL_queue_process_apc( process, &call, &result );
2430 if (status != STATUS_SUCCESS) return status;
2432 if (result.virtual_flush.status == STATUS_SUCCESS)
2434 *addr_ptr = result.virtual_flush.addr;
2435 *size_ptr = result.virtual_flush.size;
2437 return result.virtual_flush.status;
2440 server_enter_uninterrupted_section( &csVirtual, &sigset );
2441 if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2444 if (!*size_ptr) *size_ptr = view->size;
2446 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2448 server_leave_uninterrupted_section( &csVirtual, &sigset );
2453 /***********************************************************************
2454 * NtGetWriteWatch (NTDLL.@)
2455 * ZwGetWriteWatch (NTDLL.@)
2457 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
2458 ULONG_PTR *count, ULONG *granularity )
2460 struct file_view *view;
2461 NTSTATUS status = STATUS_SUCCESS;
2464 size = ROUND_SIZE( base, size );
2465 base = ROUND_ADDR( base, page_mask );
2467 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
2468 if (!*count || !size) return STATUS_INVALID_PARAMETER;
2469 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
2471 if (!addresses) return STATUS_ACCESS_VIOLATION;
2473 TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
2474 addresses, count ? *count : 0 );
2476 server_enter_uninterrupted_section( &csVirtual, &sigset );
2478 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2482 char *end = addr + size;
2484 while (pos < *count && addr < end)
2486 BYTE prot = view->prot[(addr - (char *)view->base) >> page_shift];
2487 if (!(prot & VPROT_WRITEWATCH)) addresses[pos++] = addr;
2490 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( view, base, addr - (char *)base );
2492 *granularity = page_size;
2494 else status = STATUS_INVALID_PARAMETER;
2496 server_leave_uninterrupted_section( &csVirtual, &sigset );
2501 /***********************************************************************
2502 * NtResetWriteWatch (NTDLL.@)
2503 * ZwResetWriteWatch (NTDLL.@)
2505 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
2507 struct file_view *view;
2508 NTSTATUS status = STATUS_SUCCESS;
2511 size = ROUND_SIZE( base, size );
2512 base = ROUND_ADDR( base, page_mask );
2514 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
2516 if (!size) return STATUS_INVALID_PARAMETER;
2518 server_enter_uninterrupted_section( &csVirtual, &sigset );
2520 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2521 reset_write_watches( view, base, size );
2523 status = STATUS_INVALID_PARAMETER;
2525 server_leave_uninterrupted_section( &csVirtual, &sigset );
2530 /***********************************************************************
2531 * NtReadVirtualMemory (NTDLL.@)
2532 * ZwReadVirtualMemory (NTDLL.@)
2534 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2535 SIZE_T size, SIZE_T *bytes_read )
2539 SERVER_START_REQ( read_process_memory )
2541 req->handle = process;
2542 req->addr = (void *)addr;
2543 wine_server_set_reply( req, buffer, size );
2544 if ((status = wine_server_call( req ))) size = 0;
2547 if (bytes_read) *bytes_read = size;
2552 /***********************************************************************
2553 * NtWriteVirtualMemory (NTDLL.@)
2554 * ZwWriteVirtualMemory (NTDLL.@)
2556 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2557 SIZE_T size, SIZE_T *bytes_written )
2561 SERVER_START_REQ( write_process_memory )
2563 req->handle = process;
2565 wine_server_add_data( req, buffer, size );
2566 if ((status = wine_server_call( req ))) size = 0;
2569 if (bytes_written) *bytes_written = size;
2574 /***********************************************************************
2575 * NtAreMappedFilesTheSame (NTDLL.@)
2576 * ZwAreMappedFilesTheSame (NTDLL.@)
2578 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2580 TRACE("%p %p\n", addr1, addr2);
2582 return STATUS_NOT_SAME_DEVICE;