push cc8bc80451cc24f4d7cf75168b569f0ebfe19547
[wine/hacks.git] / dlls / ntdll / virtual.c
blob33918ca5d4b90d975de7f02383b031cc35289a28
1 /*
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
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <errno.h>
26 #ifdef HAVE_SYS_ERRNO_H
27 #include <sys/errno.h>
28 #endif
29 #include <fcntl.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include <stdarg.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
40 #endif
41 #ifdef HAVE_SYS_MMAN_H
42 # include <sys/mman.h>
43 #endif
44 #ifdef HAVE_VALGRIND_VALGRIND_H
45 # include <valgrind/valgrind.h>
46 #endif
48 #define NONAMELESSUNION
49 #define NONAMELESSSTRUCT
50 #include "ntstatus.h"
51 #define WIN32_NO_STATUS
52 #include "windef.h"
53 #include "winternl.h"
54 #include "wine/library.h"
55 #include "wine/server.h"
56 #include "wine/exception.h"
57 #include "wine/list.h"
58 #include "wine/debug.h"
59 #include "ntdll_misc.h"
61 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
62 WINE_DECLARE_DEBUG_CHANNEL(module);
64 #ifndef MS_SYNC
65 #define MS_SYNC 0
66 #endif
68 #ifndef MAP_NORESERVE
69 #define MAP_NORESERVE 0
70 #endif
72 /* File view */
73 typedef struct file_view
75 struct list entry; /* Entry in global view list */
76 void *base; /* Base address */
77 size_t size; /* Size in bytes */
78 HANDLE mapping; /* Handle to the file mapping */
79 unsigned int protect; /* Protection for all pages at allocation time */
80 BYTE prot[1]; /* Protection byte for each page */
81 } FILE_VIEW;
84 /* Conversion from VPROT_* to Win32 flags */
85 static const BYTE VIRTUAL_Win32Flags[16] =
87 PAGE_NOACCESS, /* 0 */
88 PAGE_READONLY, /* READ */
89 PAGE_READWRITE, /* WRITE */
90 PAGE_READWRITE, /* READ | WRITE */
91 PAGE_EXECUTE, /* EXEC */
92 PAGE_EXECUTE_READ, /* READ | EXEC */
93 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
94 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
95 PAGE_WRITECOPY, /* WRITECOPY */
96 PAGE_WRITECOPY, /* READ | WRITECOPY */
97 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
98 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
99 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
100 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
101 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
102 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
105 static struct list views_list = LIST_INIT(views_list);
107 static RTL_CRITICAL_SECTION csVirtual;
108 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
110 0, 0, &csVirtual,
111 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
112 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
114 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
116 #ifdef __i386__
117 /* These are always the same on an i386, and it will be faster this way */
118 # define page_mask 0xfff
119 # define page_shift 12
120 # define page_size 0x1000
121 /* Note: these are Windows limits, you cannot change them. */
122 static void *address_space_limit = (void *)0xc0000000; /* top of the total available address space */
123 static void *user_space_limit = (void *)0x7fff0000; /* top of the user address space */
124 static void *working_set_limit = (void *)0x7fff0000; /* top of the current working set */
125 #else
126 static UINT page_shift;
127 static UINT_PTR page_size;
128 static UINT_PTR page_mask;
129 static void *address_space_limit;
130 static void *user_space_limit;
131 static void *working_set_limit;
132 #endif /* __i386__ */
134 #define ROUND_ADDR(addr,mask) \
135 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
137 #define ROUND_SIZE(addr,size) \
138 (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
140 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
141 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
143 #define VIRTUAL_HEAP_SIZE (4*1024*1024)
145 static HANDLE virtual_heap;
146 static void *preload_reserve_start;
147 static void *preload_reserve_end;
148 static int use_locks;
149 static int force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
152 /***********************************************************************
153 * VIRTUAL_GetProtStr
155 static const char *VIRTUAL_GetProtStr( BYTE prot )
157 static char buffer[6];
158 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
159 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
160 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
161 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
162 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
163 buffer[5] = 0;
164 return buffer;
168 /***********************************************************************
169 * VIRTUAL_GetUnixProt
171 * Convert page protections to protection for mmap/mprotect.
173 static int VIRTUAL_GetUnixProt( BYTE vprot )
175 int prot = 0;
176 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
178 if (vprot & VPROT_READ) prot |= PROT_READ;
179 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
180 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
181 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
182 if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
184 if (!prot) prot = PROT_NONE;
185 return prot;
189 /***********************************************************************
190 * VIRTUAL_DumpView
192 static void VIRTUAL_DumpView( FILE_VIEW *view )
194 UINT i, count;
195 char *addr = view->base;
196 BYTE prot = view->prot[0];
198 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
199 if (view->protect & VPROT_SYSTEM)
200 TRACE( " (system)\n" );
201 else if (view->protect & VPROT_VALLOC)
202 TRACE( " (valloc)\n" );
203 else if (view->mapping)
204 TRACE( " %p\n", view->mapping );
205 else
206 TRACE( " (anonymous)\n");
208 for (count = i = 1; i < view->size >> page_shift; i++, count++)
210 if (view->prot[i] == prot) continue;
211 TRACE( " %p - %p %s\n",
212 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
213 addr += (count << page_shift);
214 prot = view->prot[i];
215 count = 0;
217 if (count)
218 TRACE( " %p - %p %s\n",
219 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
223 /***********************************************************************
224 * VIRTUAL_Dump
226 #if WINE_VM_DEBUG
227 static void VIRTUAL_Dump(void)
229 sigset_t sigset;
230 struct file_view *view;
232 TRACE( "Dump of all virtual memory views:\n" );
233 server_enter_uninterrupted_section( &csVirtual, &sigset );
234 LIST_FOR_EACH_ENTRY( view, &views_list, FILE_VIEW, entry )
236 VIRTUAL_DumpView( view );
238 server_leave_uninterrupted_section( &csVirtual, &sigset );
240 #endif
243 /***********************************************************************
244 * VIRTUAL_FindView
246 * Find the view containing a given address. The csVirtual section must be held by caller.
248 * PARAMS
249 * addr [I] Address
251 * RETURNS
252 * View: Success
253 * NULL: Failure
255 static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
257 struct file_view *view;
259 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
261 if (view->base > addr) break; /* no matching view */
262 if ((const char *)view->base + view->size <= (const char *)addr) continue;
263 if ((const char *)view->base + view->size < (const char *)addr + size) break; /* size too large */
264 if ((const char *)addr + size < (const char *)addr) break; /* overflow */
265 return view;
267 return NULL;
271 /***********************************************************************
272 * get_mask
274 static inline UINT_PTR get_mask( ULONG zero_bits )
276 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
277 if (zero_bits < page_shift) zero_bits = page_shift;
278 return (1 << zero_bits) - 1;
282 /***********************************************************************
283 * find_view_range
285 * Find the first view overlapping at least part of the specified range.
286 * The csVirtual section must be held by caller.
288 static struct file_view *find_view_range( const void *addr, size_t size )
290 struct file_view *view;
292 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
294 if ((const char *)view->base >= (const char *)addr + size) break;
295 if ((const char *)view->base + view->size > (const char *)addr) return view;
297 return NULL;
301 /***********************************************************************
302 * find_free_area
304 * Find a free area between views inside the specified range.
305 * The csVirtual section must be held by caller.
307 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
309 struct list *ptr;
310 void *start;
312 if (top_down)
314 start = ROUND_ADDR( (char *)end - size, mask );
315 if (start >= end || start < base) return NULL;
317 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
319 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
321 if ((char *)view->base + view->size <= (char *)start) break;
322 if ((char *)view->base >= (char *)start + size) continue;
323 start = ROUND_ADDR( (char *)view->base - size, mask );
324 /* stop if remaining space is not large enough */
325 if (!start || start >= end || start < base) return NULL;
328 else
330 start = ROUND_ADDR( (char *)base + mask, mask );
331 if (start >= end || (char *)end - (char *)start < size) return NULL;
333 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
335 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
337 if ((char *)view->base >= (char *)start + size) break;
338 if ((char *)view->base + view->size <= (char *)start) continue;
339 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
340 /* stop if remaining space is not large enough */
341 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
344 return start;
348 /***********************************************************************
349 * add_reserved_area
351 * Add a reserved area to the list maintained by libwine.
352 * The csVirtual section must be held by caller.
354 static void add_reserved_area( void *addr, size_t size )
356 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
358 if (addr < user_space_limit)
360 /* unmap the part of the area that is below the limit */
361 assert( (char *)addr + size > (char *)user_space_limit );
362 munmap( addr, (char *)user_space_limit - (char *)addr );
363 size -= (char *)user_space_limit - (char *)addr;
364 addr = user_space_limit;
366 /* blow away existing mappings */
367 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
368 wine_mmap_add_reserved_area( addr, size );
372 /***********************************************************************
373 * is_beyond_limit
375 * Check if an address range goes beyond a given limit.
377 static inline int is_beyond_limit( const void *addr, size_t size, const void *limit )
379 return (addr >= limit || (const char *)addr + size > (const char *)limit);
383 /***********************************************************************
384 * unmap_area
386 * Unmap an area, or simply replace it by an empty mapping if it is
387 * in a reserved area. The csVirtual section must be held by caller.
389 static inline void unmap_area( void *addr, size_t size )
391 if (wine_mmap_is_in_reserved_area( addr, size ))
392 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
393 else if (is_beyond_limit( addr, size, user_space_limit ))
394 add_reserved_area( addr, size );
395 else
396 munmap( addr, size );
400 /***********************************************************************
401 * delete_view
403 * Deletes a view. The csVirtual section must be held by caller.
405 static void delete_view( struct file_view *view ) /* [in] View */
407 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
408 list_remove( &view->entry );
409 if (view->mapping) NtClose( view->mapping );
410 RtlFreeHeap( virtual_heap, 0, view );
414 /***********************************************************************
415 * create_view
417 * Create a view. The csVirtual section must be held by caller.
419 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
421 struct file_view *view;
422 struct list *ptr;
423 int unix_prot = VIRTUAL_GetUnixProt( vprot );
425 assert( !((UINT_PTR)base & page_mask) );
426 assert( !(size & page_mask) );
428 /* Create the view structure */
430 if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
432 FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
433 return STATUS_NO_MEMORY;
436 view->base = base;
437 view->size = size;
438 view->mapping = 0;
439 view->protect = vprot;
440 memset( view->prot, vprot, size >> page_shift );
442 /* Insert it in the linked list */
444 LIST_FOR_EACH( ptr, &views_list )
446 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
447 if (next->base > base) break;
449 list_add_before( ptr, &view->entry );
451 /* Check for overlapping views. This can happen if the previous view
452 * was a system view that got unmapped behind our back. In that case
453 * we recover by simply deleting it. */
455 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
457 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
458 if ((char *)prev->base + prev->size > (char *)base)
460 TRACE( "overlapping prev view %p-%p for %p-%p\n",
461 prev->base, (char *)prev->base + prev->size,
462 base, (char *)base + view->size );
463 assert( prev->protect & VPROT_SYSTEM );
464 delete_view( prev );
467 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
469 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
470 if ((char *)base + view->size > (char *)next->base)
472 TRACE( "overlapping next view %p-%p for %p-%p\n",
473 next->base, (char *)next->base + next->size,
474 base, (char *)base + view->size );
475 assert( next->protect & VPROT_SYSTEM );
476 delete_view( next );
480 *view_ret = view;
481 VIRTUAL_DEBUG_DUMP_VIEW( view );
483 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
485 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
486 mprotect( base, size, unix_prot | PROT_EXEC );
488 return STATUS_SUCCESS;
492 /***********************************************************************
493 * VIRTUAL_GetWin32Prot
495 * Convert page protections to Win32 flags.
497 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
499 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
500 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
501 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
502 return ret;
506 /***********************************************************************
507 * get_vprot_flags
509 * Build page protections from Win32 flags.
511 * PARAMS
512 * protect [I] Win32 protection flags
514 * RETURNS
515 * Value of page protection flags
517 static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot )
519 switch(protect & 0xff)
521 case PAGE_READONLY:
522 *vprot = VPROT_READ;
523 break;
524 case PAGE_READWRITE:
525 *vprot = VPROT_READ | VPROT_WRITE;
526 break;
527 case PAGE_WRITECOPY:
528 *vprot = VPROT_READ | VPROT_WRITECOPY;
529 break;
530 case PAGE_EXECUTE:
531 *vprot = VPROT_EXEC;
532 break;
533 case PAGE_EXECUTE_READ:
534 *vprot = VPROT_EXEC | VPROT_READ;
535 break;
536 case PAGE_EXECUTE_READWRITE:
537 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
538 break;
539 case PAGE_EXECUTE_WRITECOPY:
540 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
541 break;
542 case PAGE_NOACCESS:
543 *vprot = 0;
544 break;
545 default:
546 return STATUS_INVALID_PARAMETER;
548 if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
549 if (protect & PAGE_NOCACHE) *vprot |= VPROT_NOCACHE;
550 return STATUS_SUCCESS;
554 /***********************************************************************
555 * VIRTUAL_SetProt
557 * Change the protection of a range of pages.
559 * RETURNS
560 * TRUE: Success
561 * FALSE: Failure
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);
571 TRACE("%p-%p %s\n",
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 */
577 UINT i, count;
578 char *addr = base;
579 int prot;
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;
590 unix_prot = prot;
591 count = 0;
593 if (count) mprotect( addr, count << page_shift, unix_prot );
594 VIRTUAL_DEBUG_DUMP_VIEW( view );
595 return TRUE;
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 (base >= NtCurrentTeb()->DeallocationStack) &&
602 (base < NtCurrentTeb()->Tib.StackBase))
604 memset( p, vprot, size >> page_shift );
605 mprotect( base, size, unix_prot );
606 VIRTUAL_DEBUG_DUMP_VIEW( view );
607 return TRUE;
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 */
621 done:
622 memset( p, vprot, size >> page_shift );
623 VIRTUAL_DEBUG_DUMP_VIEW( view );
624 return TRUE;
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 )
635 SIZE_T i, count;
636 int prot, unix_prot;
637 char *addr = base;
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;
649 unix_prot = prot;
650 count = 0;
652 if (count) mprotect( addr, count << page_shift, unix_prot );
656 /***********************************************************************
657 * unmap_extra_space
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;
668 total_size -= extra;
670 if (total_size > wanted_size)
671 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
672 return ptr;
676 struct alloc_area
678 size_t size;
679 size_t mask;
680 int top_down;
681 void *limit;
682 void *result;
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;
709 else
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 )))
714 return 1;
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 )))
720 return 1;
722 return 0;
726 /***********************************************************************
727 * map_view
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 )
735 void *ptr;
736 NTSTATUS status;
738 if (base)
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;
754 if (ptr != base)
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;
761 break;
763 default:
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;
769 break;
771 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
773 else
775 size_t view_size = size + mask + 1;
776 struct alloc_area alloc;
778 alloc.size = size;
779 alloc.mask = mask;
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 ))
784 ptr = alloc.result;
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;
788 goto done;
791 for (;;)
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 );
801 else break;
803 ptr = unmap_extra_space( ptr, view_size, size, mask );
805 done:
806 status = create_view( view_ret, ptr, size, vprot );
807 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
808 return status;
812 /***********************************************************************
813 * map_file_into_view
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 )
821 void *ptr;
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)
834 goto done;
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 */
854 done:
855 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
856 return STATUS_SUCCESS;
860 /***********************************************************************
861 * get_committed_size
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 )
868 SIZE_T i, start;
870 start = ((char *)base - (char *)view->base) >> page_shift;
871 *vprot = view->prot[start];
873 if (view->mapping && !(view->protect & VPROT_COMMITTED))
875 SIZE_T ret = 0;
876 SERVER_START_REQ( get_mapping_committed_range )
878 req->handle = wine_server_obj_handle( view->mapping );
879 req->offset = start << page_shift;
880 if (!wine_server_call( req ))
882 ret = reply->size;
883 if (reply->committed)
885 *vprot |= VPROT_COMMITTED;
886 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
890 SERVER_END_REQ;
891 return ret;
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 /***********************************************************************
900 * decommit_view
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);
910 size >>= 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 )
925 size_t size;
926 void *addr = NULL;
927 void * const low_64k = (void *)0x10000;
928 const size_t dosmem_size = 0x110000;
929 int unix_prot = VIRTUAL_GetUnixProt( vprot );
930 struct list *ptr;
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 );
945 if (addr != low_64k)
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)
959 addr = NULL;
960 TRACE( "successfully mapped low 64K range\n" );
962 else
964 if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
965 addr = low_64k;
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 /***********************************************************************
979 * map_image
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;
991 int i;
992 off_t pos;
993 sigset_t sigset;
994 struct stat st;
995 struct file_view *view = NULL;
996 char *ptr, *header_end;
997 INT_PTR delta = 0;
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_SUCCESS)
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;
1013 ptr = view->base;
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();
1021 goto error;
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 */
1041 #ifdef __x86_64__
1042 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64)
1043 #else
1044 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
1045 #endif
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;
1064 MESSAGE(")\n");
1065 goto error;
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 */
1091 goto done;
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 );
1104 else
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 );
1118 goto error;
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 );
1133 goto error;
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;
1143 if (end > base)
1144 map_file_into_view( view, shared_fd, base, end - base,
1145 pos + (base - sec->VirtualAddress),
1146 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1147 FALSE );
1149 pos += map_size;
1150 continue;
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) ||
1166 end < file_start ||
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 );
1172 goto error;
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 */
1189 if (ptr != base &&
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",
1199 base, ptr );
1200 status = STATUS_CONFLICTING_ADDRESSES;
1201 goto error;
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);
1210 delta = ptr - base;
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;
1218 goto error;
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++)
1234 SIZE_T size;
1235 BYTE vprot = VPROT_COMMITTED;
1237 if (sec->Misc.VirtualSize)
1238 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1239 else
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 );
1254 done:
1255 view->mapping = dup_mapping;
1256 server_leave_uninterrupted_section( &csVirtual, &sigset );
1258 *addr_ptr = ptr;
1259 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1260 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1261 #endif
1262 return STATUS_SUCCESS;
1264 error:
1265 if (view) delete_view( view );
1266 server_leave_uninterrupted_section( &csVirtual, &sigset );
1267 if (dup_mapping) NtClose( dup_mapping );
1268 return status;
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 /***********************************************************************
1285 * virtual_init
1287 void virtual_init(void)
1289 const char *preload;
1290 void *heap_base;
1291 struct file_view *heap_view;
1293 #ifndef page_mask
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) );
1298 page_shift = 0;
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)
1328 use_locks = 1;
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 )
1356 FILE_VIEW *view;
1357 NTSTATUS status;
1358 sigset_t sigset;
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 );
1366 return status;
1370 /***********************************************************************
1371 * virtual_alloc_thread_stack
1373 NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1375 FILE_VIEW *view;
1376 NTSTATUS status;
1377 sigset_t sigset;
1378 SIZE_T size;
1380 if (!reserve_size || !commit_size)
1382 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1383 if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
1384 if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1387 size = max( reserve_size, commit_size );
1388 if (size < 1024 * 1024) size = 1024 * 1024; /* Xlib needs a large stack */
1389 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1391 server_enter_uninterrupted_section( &csVirtual, &sigset );
1393 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1394 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1395 goto done;
1397 #ifdef VALGRIND_STACK_REGISTER
1398 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1399 #endif
1401 /* setup no access guard page */
1402 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1403 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1404 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1406 /* note: limit is lower than base since the stack grows down */
1407 teb->DeallocationStack = view->base;
1408 teb->Tib.StackBase = (char *)view->base + view->size;
1409 teb->Tib.StackLimit = (char *)view->base + 2 * page_size;
1410 done:
1411 server_leave_uninterrupted_section( &csVirtual, &sigset );
1412 return status;
1416 /***********************************************************************
1417 * virtual_clear_thread_stack
1419 * Clear the stack contents before calling the main entry point, some broken apps need that.
1421 void virtual_clear_thread_stack(void)
1423 void *stack = NtCurrentTeb()->Tib.StackLimit;
1424 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1426 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1427 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1431 /***********************************************************************
1432 * virtual_handle_fault
1434 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err )
1436 FILE_VIEW *view;
1437 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1438 sigset_t sigset;
1440 server_enter_uninterrupted_section( &csVirtual, &sigset );
1441 if ((view = VIRTUAL_FindView( addr, 0 )))
1443 void *page = ROUND_ADDR( addr, page_mask );
1444 BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1445 if (*vprot & VPROT_GUARD)
1447 VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1448 ret = STATUS_GUARD_PAGE_VIOLATION;
1450 if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1452 if (*vprot & VPROT_WRITEWATCH)
1454 *vprot &= ~VPROT_WRITEWATCH;
1455 VIRTUAL_SetProt( view, page, page_size, *vprot );
1457 /* ignore fault if page is writable now */
1458 if (VIRTUAL_GetUnixProt( *vprot ) & PROT_WRITE) ret = STATUS_SUCCESS;
1461 server_leave_uninterrupted_section( &csVirtual, &sigset );
1462 return ret;
1467 /***********************************************************************
1468 * virtual_handle_stack_fault
1470 * Handle an access fault inside the current thread stack.
1471 * Called from inside a signal handler.
1473 BOOL virtual_handle_stack_fault( void *addr )
1475 FILE_VIEW *view;
1476 BOOL ret = FALSE;
1478 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1479 if ((view = VIRTUAL_FindView( addr, 0 )))
1481 void *page = ROUND_ADDR( addr, page_mask );
1482 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1483 if (vprot & VPROT_GUARD)
1485 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1486 if ((char *)page + page_size == NtCurrentTeb()->Tib.StackLimit)
1487 NtCurrentTeb()->Tib.StackLimit = page;
1488 ret = TRUE;
1491 RtlLeaveCriticalSection( &csVirtual );
1492 return ret;
1496 /***********************************************************************
1497 * virtual_check_buffer_for_read
1499 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
1501 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
1503 if (!size) return TRUE;
1504 if (!ptr) return FALSE;
1506 __TRY
1508 volatile const char *p = ptr;
1509 char dummy;
1510 SIZE_T count = size;
1512 while (count > page_size)
1514 dummy = *p;
1515 p += page_size;
1516 count -= page_size;
1518 dummy = p[0];
1519 dummy = p[count - 1];
1521 __EXCEPT_PAGE_FAULT
1523 return FALSE;
1525 __ENDTRY
1526 return TRUE;
1530 /***********************************************************************
1531 * virtual_check_buffer_for_write
1533 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
1535 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
1537 if (!size) return TRUE;
1538 if (!ptr) return FALSE;
1540 __TRY
1542 volatile char *p = ptr;
1543 SIZE_T count = size;
1545 while (count > page_size)
1547 *p |= 0;
1548 p += page_size;
1549 count -= page_size;
1551 p[0] |= 0;
1552 p[count - 1] |= 0;
1554 __EXCEPT_PAGE_FAULT
1556 return FALSE;
1558 __ENDTRY
1559 return TRUE;
1563 /***********************************************************************
1564 * VIRTUAL_SetForceExec
1566 * Whether to force exec prot on all views.
1568 void VIRTUAL_SetForceExec( BOOL enable )
1570 struct file_view *view;
1571 sigset_t sigset;
1573 server_enter_uninterrupted_section( &csVirtual, &sigset );
1574 if (!force_exec_prot != !enable) /* change all existing views */
1576 force_exec_prot = enable;
1578 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1580 UINT i, count;
1581 char *addr = view->base;
1582 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1583 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1585 if (view->protect & VPROT_NOEXEC) continue;
1586 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1588 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1589 if (prot == unix_prot) continue;
1590 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1592 TRACE( "%s exec prot for %p-%p\n",
1593 force_exec_prot ? "enabling" : "disabling",
1594 addr, addr + (count << page_shift) - 1 );
1595 mprotect( addr, count << page_shift,
1596 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1598 addr += (count << page_shift);
1599 unix_prot = prot;
1600 count = 0;
1602 if (count)
1604 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1606 TRACE( "%s exec prot for %p-%p\n",
1607 force_exec_prot ? "enabling" : "disabling",
1608 addr, addr + (count << page_shift) - 1 );
1609 mprotect( addr, count << page_shift,
1610 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1615 server_leave_uninterrupted_section( &csVirtual, &sigset );
1619 /***********************************************************************
1620 * VIRTUAL_UseLargeAddressSpace
1622 * Increase the address space size for apps that support it.
1624 void VIRTUAL_UseLargeAddressSpace(void)
1626 /* no large address space on win9x */
1627 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1628 user_space_limit = working_set_limit = address_space_limit;
1632 /***********************************************************************
1633 * NtAllocateVirtualMemory (NTDLL.@)
1634 * ZwAllocateVirtualMemory (NTDLL.@)
1636 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1637 SIZE_T *size_ptr, ULONG type, ULONG protect )
1639 void *base;
1640 unsigned int vprot;
1641 SIZE_T size = *size_ptr;
1642 SIZE_T mask = get_mask( zero_bits );
1643 NTSTATUS status = STATUS_SUCCESS;
1644 struct file_view *view;
1645 sigset_t sigset;
1647 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1649 if (!size) return STATUS_INVALID_PARAMETER;
1651 if (process != NtCurrentProcess())
1653 apc_call_t call;
1654 apc_result_t result;
1656 memset( &call, 0, sizeof(call) );
1658 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1659 call.virtual_alloc.addr = wine_server_client_ptr( *ret );
1660 call.virtual_alloc.size = *size_ptr;
1661 call.virtual_alloc.zero_bits = zero_bits;
1662 call.virtual_alloc.op_type = type;
1663 call.virtual_alloc.prot = protect;
1664 status = NTDLL_queue_process_apc( process, &call, &result );
1665 if (status != STATUS_SUCCESS) return status;
1667 if (result.virtual_alloc.status == STATUS_SUCCESS)
1669 *ret = wine_server_get_ptr( result.virtual_alloc.addr );
1670 *size_ptr = result.virtual_alloc.size;
1672 return result.virtual_alloc.status;
1675 /* Round parameters to a page boundary */
1677 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1679 if ((status = get_vprot_flags( protect, &vprot ))) return status;
1680 vprot |= VPROT_VALLOC;
1681 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1683 if (*ret)
1685 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1686 base = ROUND_ADDR( *ret, mask );
1687 else
1688 base = ROUND_ADDR( *ret, page_mask );
1689 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1691 /* address 1 is magic to mean DOS area */
1692 if (!base && *ret == (void *)1 && size == 0x110000)
1694 server_enter_uninterrupted_section( &csVirtual, &sigset );
1695 status = allocate_dos_memory( &view, vprot );
1696 if (status == STATUS_SUCCESS)
1698 *ret = view->base;
1699 *size_ptr = view->size;
1701 server_leave_uninterrupted_section( &csVirtual, &sigset );
1702 return status;
1705 /* disallow low 64k, wrap-around and kernel space */
1706 if (((char *)base < (char *)0x10000) ||
1707 ((char *)base + size < (char *)base) ||
1708 is_beyond_limit( base, size, address_space_limit ))
1709 return STATUS_INVALID_PARAMETER;
1711 else
1713 base = NULL;
1714 size = (size + page_mask) & ~page_mask;
1717 /* Compute the alloc type flags */
1719 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
1720 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1722 WARN("called with wrong alloc type flags (%08x) !\n", type);
1723 return STATUS_INVALID_PARAMETER;
1726 /* Reserve the memory */
1728 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1730 if ((type & MEM_RESERVE) || !base)
1732 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
1733 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1734 if (status == STATUS_SUCCESS) base = view->base;
1736 else /* commit the pages */
1738 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1739 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1740 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1742 SERVER_START_REQ( add_mapping_committed_range )
1744 req->handle = wine_server_obj_handle( view->mapping );
1745 req->offset = (char *)base - (char *)view->base;
1746 req->size = size;
1747 wine_server_call( req );
1749 SERVER_END_REQ;
1753 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1755 if (status == STATUS_SUCCESS)
1757 *ret = base;
1758 *size_ptr = size;
1760 return status;
1764 /***********************************************************************
1765 * NtFreeVirtualMemory (NTDLL.@)
1766 * ZwFreeVirtualMemory (NTDLL.@)
1768 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1770 FILE_VIEW *view;
1771 char *base;
1772 sigset_t sigset;
1773 NTSTATUS status = STATUS_SUCCESS;
1774 LPVOID addr = *addr_ptr;
1775 SIZE_T size = *size_ptr;
1777 TRACE("%p %p %08lx %x\n", process, addr, size, type );
1779 if (process != NtCurrentProcess())
1781 apc_call_t call;
1782 apc_result_t result;
1784 memset( &call, 0, sizeof(call) );
1786 call.virtual_free.type = APC_VIRTUAL_FREE;
1787 call.virtual_free.addr = wine_server_client_ptr( addr );
1788 call.virtual_free.size = size;
1789 call.virtual_free.op_type = type;
1790 status = NTDLL_queue_process_apc( process, &call, &result );
1791 if (status != STATUS_SUCCESS) return status;
1793 if (result.virtual_free.status == STATUS_SUCCESS)
1795 *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
1796 *size_ptr = result.virtual_free.size;
1798 return result.virtual_free.status;
1801 /* Fix the parameters */
1803 size = ROUND_SIZE( addr, size );
1804 base = ROUND_ADDR( addr, page_mask );
1806 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
1807 if (!base) return STATUS_INVALID_PARAMETER;
1809 server_enter_uninterrupted_section( &csVirtual, &sigset );
1811 if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
1813 status = STATUS_INVALID_PARAMETER;
1815 else if (type == MEM_RELEASE)
1817 /* Free the pages */
1819 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1820 else
1822 delete_view( view );
1823 *addr_ptr = base;
1824 *size_ptr = size;
1827 else if (type == MEM_DECOMMIT)
1829 status = decommit_pages( view, base - (char *)view->base, size );
1830 if (status == STATUS_SUCCESS)
1832 *addr_ptr = base;
1833 *size_ptr = size;
1836 else
1838 WARN("called with wrong free type flags (%08x) !\n", type);
1839 status = STATUS_INVALID_PARAMETER;
1842 server_leave_uninterrupted_section( &csVirtual, &sigset );
1843 return status;
1847 /***********************************************************************
1848 * NtProtectVirtualMemory (NTDLL.@)
1849 * ZwProtectVirtualMemory (NTDLL.@)
1851 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1852 ULONG new_prot, ULONG *old_prot )
1854 FILE_VIEW *view;
1855 sigset_t sigset;
1856 NTSTATUS status = STATUS_SUCCESS;
1857 char *base;
1858 BYTE vprot;
1859 unsigned int new_vprot;
1860 SIZE_T size = *size_ptr;
1861 LPVOID addr = *addr_ptr;
1863 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
1865 if (process != NtCurrentProcess())
1867 apc_call_t call;
1868 apc_result_t result;
1870 memset( &call, 0, sizeof(call) );
1872 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
1873 call.virtual_protect.addr = wine_server_client_ptr( addr );
1874 call.virtual_protect.size = size;
1875 call.virtual_protect.prot = new_prot;
1876 status = NTDLL_queue_process_apc( process, &call, &result );
1877 if (status != STATUS_SUCCESS) return status;
1879 if (result.virtual_protect.status == STATUS_SUCCESS)
1881 *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
1882 *size_ptr = result.virtual_protect.size;
1883 if (old_prot) *old_prot = result.virtual_protect.prot;
1885 return result.virtual_protect.status;
1888 /* Fix the parameters */
1890 size = ROUND_SIZE( addr, size );
1891 base = ROUND_ADDR( addr, page_mask );
1892 if ((status = get_vprot_flags( new_prot, &new_vprot ))) return status;
1893 new_vprot |= VPROT_COMMITTED;
1895 server_enter_uninterrupted_section( &csVirtual, &sigset );
1897 if (!(view = VIRTUAL_FindView( base, size )))
1899 status = STATUS_INVALID_PARAMETER;
1901 else
1903 /* Make sure all the pages are committed */
1904 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
1906 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
1907 if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
1909 else status = STATUS_NOT_COMMITTED;
1911 server_leave_uninterrupted_section( &csVirtual, &sigset );
1913 if (status == STATUS_SUCCESS)
1915 *addr_ptr = base;
1916 *size_ptr = size;
1918 return status;
1922 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
1923 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
1925 MEMORY_BASIC_INFORMATION *info = arg;
1926 void *end = (char *)start + size;
1928 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
1930 if (info->BaseAddress >= end)
1932 if (info->AllocationBase < end) info->AllocationBase = end;
1933 return 0;
1936 if (info->BaseAddress >= start)
1938 /* it's a real free area */
1939 info->State = MEM_FREE;
1940 info->Protect = PAGE_NOACCESS;
1941 info->AllocationBase = 0;
1942 info->AllocationProtect = 0;
1943 info->Type = 0;
1944 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
1945 info->RegionSize = (char *)end - (char *)info->BaseAddress;
1947 else /* outside of the reserved area, pretend it's allocated */
1949 info->RegionSize = (char *)start - (char *)info->BaseAddress;
1950 info->State = MEM_RESERVE;
1951 info->Protect = PAGE_NOACCESS;
1952 info->AllocationProtect = PAGE_NOACCESS;
1953 info->Type = MEM_PRIVATE;
1955 return 1;
1958 #define UNIMPLEMENTED_INFO_CLASS(c) \
1959 case c: \
1960 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
1961 return STATUS_INVALID_INFO_CLASS
1963 /***********************************************************************
1964 * NtQueryVirtualMemory (NTDLL.@)
1965 * ZwQueryVirtualMemory (NTDLL.@)
1967 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1968 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1969 SIZE_T len, SIZE_T *res_len )
1971 FILE_VIEW *view;
1972 char *base, *alloc_base = 0;
1973 struct list *ptr;
1974 SIZE_T size = 0;
1975 MEMORY_BASIC_INFORMATION *info = buffer;
1976 sigset_t sigset;
1978 if (info_class != MemoryBasicInformation)
1980 switch(info_class)
1982 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
1983 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
1984 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
1986 default:
1987 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
1988 process, addr, info_class, buffer, len, res_len);
1989 return STATUS_INVALID_INFO_CLASS;
1993 if (process != NtCurrentProcess())
1995 NTSTATUS status;
1996 apc_call_t call;
1997 apc_result_t result;
1999 memset( &call, 0, sizeof(call) );
2001 call.virtual_query.type = APC_VIRTUAL_QUERY;
2002 call.virtual_query.addr = wine_server_client_ptr( addr );
2003 status = NTDLL_queue_process_apc( process, &call, &result );
2004 if (status != STATUS_SUCCESS) return status;
2006 if (result.virtual_query.status == STATUS_SUCCESS)
2008 info->BaseAddress = wine_server_get_ptr( result.virtual_query.base );
2009 info->AllocationBase = wine_server_get_ptr( result.virtual_query.alloc_base );
2010 info->RegionSize = result.virtual_query.size;
2011 info->Protect = result.virtual_query.prot;
2012 info->AllocationProtect = result.virtual_query.alloc_prot;
2013 info->State = (DWORD)result.virtual_query.state << 12;
2014 info->Type = (DWORD)result.virtual_query.alloc_type << 16;
2015 if (info->RegionSize != result.virtual_query.size) /* truncated */
2016 return STATUS_INVALID_PARAMETER; /* FIXME */
2017 if (res_len) *res_len = sizeof(*info);
2019 return result.virtual_query.status;
2022 base = ROUND_ADDR( addr, page_mask );
2024 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2026 /* Find the view containing the address */
2028 server_enter_uninterrupted_section( &csVirtual, &sigset );
2029 ptr = list_head( &views_list );
2030 for (;;)
2032 if (!ptr)
2034 size = (char *)working_set_limit - alloc_base;
2035 view = NULL;
2036 break;
2038 view = LIST_ENTRY( ptr, struct file_view, entry );
2039 if ((char *)view->base > base)
2041 size = (char *)view->base - alloc_base;
2042 view = NULL;
2043 break;
2045 if ((char *)view->base + view->size > base)
2047 alloc_base = view->base;
2048 size = view->size;
2049 break;
2051 alloc_base = (char *)view->base + view->size;
2052 ptr = list_next( &views_list, ptr );
2055 /* Fill the info structure */
2057 info->AllocationBase = alloc_base;
2058 info->BaseAddress = base;
2059 info->RegionSize = size - (base - alloc_base);
2061 if (!view)
2063 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2065 /* not in a reserved area at all, pretend it's allocated */
2066 #ifdef __i386__
2067 info->State = MEM_RESERVE;
2068 info->Protect = PAGE_NOACCESS;
2069 info->AllocationProtect = PAGE_NOACCESS;
2070 info->Type = MEM_PRIVATE;
2071 #else
2072 info->State = MEM_FREE;
2073 info->Protect = PAGE_NOACCESS;
2074 info->AllocationBase = 0;
2075 info->AllocationProtect = 0;
2076 info->Type = 0;
2077 #endif
2080 else
2082 BYTE vprot;
2083 SIZE_T range_size = get_committed_size( view, base, &vprot );
2085 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2086 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2087 info->AllocationBase = alloc_base;
2088 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2089 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2090 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2091 else info->Type = MEM_MAPPED;
2092 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2093 if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2094 info->RegionSize = size - (base - alloc_base);
2096 server_leave_uninterrupted_section( &csVirtual, &sigset );
2098 if (res_len) *res_len = sizeof(*info);
2099 return STATUS_SUCCESS;
2103 /***********************************************************************
2104 * NtLockVirtualMemory (NTDLL.@)
2105 * ZwLockVirtualMemory (NTDLL.@)
2107 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2109 NTSTATUS status = STATUS_SUCCESS;
2111 if (process != NtCurrentProcess())
2113 apc_call_t call;
2114 apc_result_t result;
2116 memset( &call, 0, sizeof(call) );
2118 call.virtual_lock.type = APC_VIRTUAL_LOCK;
2119 call.virtual_lock.addr = wine_server_client_ptr( *addr );
2120 call.virtual_lock.size = *size;
2121 status = NTDLL_queue_process_apc( process, &call, &result );
2122 if (status != STATUS_SUCCESS) return status;
2124 if (result.virtual_lock.status == STATUS_SUCCESS)
2126 *addr = wine_server_get_ptr( result.virtual_lock.addr );
2127 *size = result.virtual_lock.size;
2129 return result.virtual_lock.status;
2132 *size = ROUND_SIZE( *addr, *size );
2133 *addr = ROUND_ADDR( *addr, page_mask );
2135 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2136 return status;
2140 /***********************************************************************
2141 * NtUnlockVirtualMemory (NTDLL.@)
2142 * ZwUnlockVirtualMemory (NTDLL.@)
2144 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2146 NTSTATUS status = STATUS_SUCCESS;
2148 if (process != NtCurrentProcess())
2150 apc_call_t call;
2151 apc_result_t result;
2153 memset( &call, 0, sizeof(call) );
2155 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2156 call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2157 call.virtual_unlock.size = *size;
2158 status = NTDLL_queue_process_apc( process, &call, &result );
2159 if (status != STATUS_SUCCESS) return status;
2161 if (result.virtual_unlock.status == STATUS_SUCCESS)
2163 *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2164 *size = result.virtual_unlock.size;
2166 return result.virtual_unlock.status;
2169 *size = ROUND_SIZE( *addr, *size );
2170 *addr = ROUND_ADDR( *addr, page_mask );
2172 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2173 return status;
2177 /***********************************************************************
2178 * NtCreateSection (NTDLL.@)
2179 * ZwCreateSection (NTDLL.@)
2181 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2182 const LARGE_INTEGER *size, ULONG protect,
2183 ULONG sec_flags, HANDLE file )
2185 NTSTATUS ret;
2186 unsigned int vprot;
2187 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2188 struct security_descriptor *sd = NULL;
2189 struct object_attributes objattr;
2191 /* Check parameters */
2193 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2195 if ((ret = get_vprot_flags( protect, &vprot ))) return ret;
2197 objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
2198 objattr.sd_len = 0;
2199 objattr.name_len = len;
2200 if (attr)
2202 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2203 if (ret != STATUS_SUCCESS) return ret;
2206 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2207 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2208 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2210 /* Create the server object */
2212 SERVER_START_REQ( create_mapping )
2214 req->access = access;
2215 req->attributes = (attr) ? attr->Attributes : 0;
2216 req->file_handle = wine_server_obj_handle( file );
2217 req->size = size ? size->QuadPart : 0;
2218 req->protect = vprot;
2219 wine_server_add_data( req, &objattr, sizeof(objattr) );
2220 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2221 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2222 ret = wine_server_call( req );
2223 *handle = wine_server_ptr_handle( reply->handle );
2225 SERVER_END_REQ;
2227 NTDLL_free_struct_sd( sd );
2229 return ret;
2233 /***********************************************************************
2234 * NtOpenSection (NTDLL.@)
2235 * ZwOpenSection (NTDLL.@)
2237 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2239 NTSTATUS ret;
2240 DWORD len = attr->ObjectName->Length;
2242 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2244 SERVER_START_REQ( open_mapping )
2246 req->access = access;
2247 req->attributes = attr->Attributes;
2248 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2249 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2250 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
2252 SERVER_END_REQ;
2253 return ret;
2257 /***********************************************************************
2258 * NtMapViewOfSection (NTDLL.@)
2259 * ZwMapViewOfSection (NTDLL.@)
2261 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2262 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2263 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2265 NTSTATUS res;
2266 mem_size_t full_size;
2267 ACCESS_MASK access;
2268 SIZE_T size, mask = get_mask( zero_bits );
2269 int unix_handle = -1, needs_close;
2270 unsigned int map_vprot, vprot;
2271 void *base;
2272 struct file_view *view;
2273 DWORD header_size;
2274 HANDLE dup_mapping, shared_file;
2275 LARGE_INTEGER offset;
2276 sigset_t sigset;
2278 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2280 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2281 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2283 /* Check parameters */
2285 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2286 return STATUS_INVALID_PARAMETER;
2288 switch(protect)
2290 case PAGE_NOACCESS:
2291 access = 0;
2292 break;
2293 case PAGE_READWRITE:
2294 case PAGE_EXECUTE_READWRITE:
2295 access = SECTION_MAP_WRITE;
2296 break;
2297 case PAGE_READONLY:
2298 case PAGE_WRITECOPY:
2299 case PAGE_EXECUTE:
2300 case PAGE_EXECUTE_READ:
2301 case PAGE_EXECUTE_WRITECOPY:
2302 access = SECTION_MAP_READ;
2303 break;
2304 default:
2305 return STATUS_INVALID_PARAMETER;
2308 if (process != NtCurrentProcess())
2310 apc_call_t call;
2311 apc_result_t result;
2313 memset( &call, 0, sizeof(call) );
2315 call.map_view.type = APC_MAP_VIEW;
2316 call.map_view.handle = wine_server_obj_handle( handle );
2317 call.map_view.addr = wine_server_client_ptr( *addr_ptr );
2318 call.map_view.size = *size_ptr;
2319 call.map_view.offset = offset.QuadPart;
2320 call.map_view.zero_bits = zero_bits;
2321 call.map_view.alloc_type = alloc_type;
2322 call.map_view.prot = protect;
2323 res = NTDLL_queue_process_apc( process, &call, &result );
2324 if (res != STATUS_SUCCESS) return res;
2326 if (result.map_view.status == STATUS_SUCCESS)
2328 *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2329 *size_ptr = result.map_view.size;
2331 return result.map_view.status;
2334 SERVER_START_REQ( get_mapping_info )
2336 req->handle = wine_server_obj_handle( handle );
2337 req->access = access;
2338 res = wine_server_call( req );
2339 map_vprot = reply->protect;
2340 base = wine_server_get_ptr( reply->base );
2341 full_size = reply->size;
2342 header_size = reply->header_size;
2343 dup_mapping = wine_server_ptr_handle( reply->mapping );
2344 shared_file = wine_server_ptr_handle( reply->shared_file );
2345 if ((ULONG_PTR)base != reply->base) base = NULL;
2347 SERVER_END_REQ;
2348 if (res) return res;
2350 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2352 if (map_vprot & VPROT_IMAGE)
2354 size = full_size;
2355 if (size != full_size) /* truncated */
2357 WARN( "Modules larger than 4Gb (%s) not supported\n", wine_dbgstr_longlong(full_size) );
2358 res = STATUS_INVALID_PARAMETER;
2359 goto done;
2361 if (shared_file)
2363 int shared_fd, shared_needs_close;
2365 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2366 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2367 res = map_image( handle, unix_handle, base, size, mask, header_size,
2368 shared_fd, dup_mapping, addr_ptr );
2369 if (shared_needs_close) close( shared_fd );
2370 NtClose( shared_file );
2372 else
2374 res = map_image( handle, unix_handle, base, size, mask, header_size,
2375 -1, dup_mapping, addr_ptr );
2377 if (needs_close) close( unix_handle );
2378 if (!res) *size_ptr = size;
2379 return res;
2382 res = STATUS_INVALID_PARAMETER;
2383 if (offset.QuadPart >= full_size) goto done;
2384 if (*size_ptr)
2386 if (*size_ptr > full_size - offset.QuadPart) goto done;
2387 size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2388 if (size < *size_ptr) goto done; /* wrap-around */
2390 else
2392 size = full_size - offset.QuadPart;
2393 if (size != full_size - offset.QuadPart) /* truncated */
2395 WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2396 wine_dbgstr_longlong(full_size) );
2397 goto done;
2401 /* Reserve a properly aligned area */
2403 server_enter_uninterrupted_section( &csVirtual, &sigset );
2405 get_vprot_flags( protect, &vprot );
2406 vprot |= (map_vprot & VPROT_COMMITTED);
2407 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2408 if (res)
2410 server_leave_uninterrupted_section( &csVirtual, &sigset );
2411 goto done;
2414 /* Map the file */
2416 TRACE("handle=%p size=%lx offset=%x%08x\n",
2417 handle, size, offset.u.HighPart, offset.u.LowPart );
2419 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2420 if (res == STATUS_SUCCESS)
2422 *addr_ptr = view->base;
2423 *size_ptr = size;
2424 view->mapping = dup_mapping;
2425 dup_mapping = 0; /* don't close it */
2427 else
2429 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2430 view->base, size, offset.u.HighPart, offset.u.LowPart );
2431 delete_view( view );
2434 server_leave_uninterrupted_section( &csVirtual, &sigset );
2436 done:
2437 if (dup_mapping) NtClose( dup_mapping );
2438 if (needs_close) close( unix_handle );
2439 return res;
2443 /***********************************************************************
2444 * NtUnmapViewOfSection (NTDLL.@)
2445 * ZwUnmapViewOfSection (NTDLL.@)
2447 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2449 FILE_VIEW *view;
2450 NTSTATUS status = STATUS_INVALID_PARAMETER;
2451 sigset_t sigset;
2452 void *base = ROUND_ADDR( addr, page_mask );
2454 if (process != NtCurrentProcess())
2456 apc_call_t call;
2457 apc_result_t result;
2459 memset( &call, 0, sizeof(call) );
2461 call.unmap_view.type = APC_UNMAP_VIEW;
2462 call.unmap_view.addr = wine_server_client_ptr( addr );
2463 status = NTDLL_queue_process_apc( process, &call, &result );
2464 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2465 return status;
2468 server_enter_uninterrupted_section( &csVirtual, &sigset );
2469 if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base))
2471 delete_view( view );
2472 status = STATUS_SUCCESS;
2474 server_leave_uninterrupted_section( &csVirtual, &sigset );
2475 return status;
2479 /***********************************************************************
2480 * NtFlushVirtualMemory (NTDLL.@)
2481 * ZwFlushVirtualMemory (NTDLL.@)
2483 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2484 SIZE_T *size_ptr, ULONG unknown )
2486 FILE_VIEW *view;
2487 NTSTATUS status = STATUS_SUCCESS;
2488 sigset_t sigset;
2489 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2491 if (process != NtCurrentProcess())
2493 apc_call_t call;
2494 apc_result_t result;
2496 memset( &call, 0, sizeof(call) );
2498 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2499 call.virtual_flush.addr = wine_server_client_ptr( addr );
2500 call.virtual_flush.size = *size_ptr;
2501 status = NTDLL_queue_process_apc( process, &call, &result );
2502 if (status != STATUS_SUCCESS) return status;
2504 if (result.virtual_flush.status == STATUS_SUCCESS)
2506 *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2507 *size_ptr = result.virtual_flush.size;
2509 return result.virtual_flush.status;
2512 server_enter_uninterrupted_section( &csVirtual, &sigset );
2513 if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2514 else
2516 if (!*size_ptr) *size_ptr = view->size;
2517 *addr_ptr = addr;
2518 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2520 server_leave_uninterrupted_section( &csVirtual, &sigset );
2521 return status;
2525 /***********************************************************************
2526 * NtGetWriteWatch (NTDLL.@)
2527 * ZwGetWriteWatch (NTDLL.@)
2529 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
2530 ULONG_PTR *count, ULONG *granularity )
2532 struct file_view *view;
2533 NTSTATUS status = STATUS_SUCCESS;
2534 sigset_t sigset;
2536 size = ROUND_SIZE( base, size );
2537 base = ROUND_ADDR( base, page_mask );
2539 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
2540 if (!*count || !size) return STATUS_INVALID_PARAMETER;
2541 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
2543 if (!addresses) return STATUS_ACCESS_VIOLATION;
2545 TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
2546 addresses, count ? *count : 0 );
2548 server_enter_uninterrupted_section( &csVirtual, &sigset );
2550 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2552 ULONG_PTR pos = 0;
2553 char *addr = base;
2554 char *end = addr + size;
2556 while (pos < *count && addr < end)
2558 BYTE prot = view->prot[(addr - (char *)view->base) >> page_shift];
2559 if (!(prot & VPROT_WRITEWATCH)) addresses[pos++] = addr;
2560 addr += page_size;
2562 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( view, base, addr - (char *)base );
2563 *count = pos;
2564 *granularity = page_size;
2566 else status = STATUS_INVALID_PARAMETER;
2568 server_leave_uninterrupted_section( &csVirtual, &sigset );
2569 return status;
2573 /***********************************************************************
2574 * NtResetWriteWatch (NTDLL.@)
2575 * ZwResetWriteWatch (NTDLL.@)
2577 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
2579 struct file_view *view;
2580 NTSTATUS status = STATUS_SUCCESS;
2581 sigset_t sigset;
2583 size = ROUND_SIZE( base, size );
2584 base = ROUND_ADDR( base, page_mask );
2586 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
2588 if (!size) return STATUS_INVALID_PARAMETER;
2590 server_enter_uninterrupted_section( &csVirtual, &sigset );
2592 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2593 reset_write_watches( view, base, size );
2594 else
2595 status = STATUS_INVALID_PARAMETER;
2597 server_leave_uninterrupted_section( &csVirtual, &sigset );
2598 return status;
2602 /***********************************************************************
2603 * NtReadVirtualMemory (NTDLL.@)
2604 * ZwReadVirtualMemory (NTDLL.@)
2606 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2607 SIZE_T size, SIZE_T *bytes_read )
2609 NTSTATUS status;
2611 if (virtual_check_buffer_for_write( buffer, size ))
2613 SERVER_START_REQ( read_process_memory )
2615 req->handle = wine_server_obj_handle( process );
2616 req->addr = wine_server_client_ptr( addr );
2617 wine_server_set_reply( req, buffer, size );
2618 if ((status = wine_server_call( req ))) size = 0;
2620 SERVER_END_REQ;
2622 else
2624 status = STATUS_ACCESS_VIOLATION;
2625 size = 0;
2627 if (bytes_read) *bytes_read = size;
2628 return status;
2632 /***********************************************************************
2633 * NtWriteVirtualMemory (NTDLL.@)
2634 * ZwWriteVirtualMemory (NTDLL.@)
2636 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2637 SIZE_T size, SIZE_T *bytes_written )
2639 NTSTATUS status;
2641 if (virtual_check_buffer_for_read( buffer, size ))
2643 SERVER_START_REQ( write_process_memory )
2645 req->handle = wine_server_obj_handle( process );
2646 req->addr = wine_server_client_ptr( addr );
2647 wine_server_add_data( req, buffer, size );
2648 if ((status = wine_server_call( req ))) size = 0;
2650 SERVER_END_REQ;
2652 else
2654 status = STATUS_PARTIAL_COPY;
2655 size = 0;
2657 if (bytes_written) *bytes_written = size;
2658 return status;
2662 /***********************************************************************
2663 * NtAreMappedFilesTheSame (NTDLL.@)
2664 * ZwAreMappedFilesTheSame (NTDLL.@)
2666 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2668 TRACE("%p %p\n", addr1, addr2);
2670 return STATUS_NOT_SAME_DEVICE;