gdiplus/metafile: Support playback for EmfPlusRecordTypeSetAntiAliasMode.
[wine.git] / dlls / ntdll / virtual.c
blobd28b138e575cb30b9e78b81196470f898f7db33f
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 #include <fcntl.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <sys/types.h>
35 #ifdef HAVE_SYS_SOCKET_H
36 # include <sys/socket.h>
37 #endif
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_SYS_SYSINFO_H
45 # include <sys/sysinfo.h>
46 #endif
47 #ifdef HAVE_VALGRIND_VALGRIND_H
48 # include <valgrind/valgrind.h>
49 #endif
51 #include "ntstatus.h"
52 #define WIN32_NO_STATUS
53 #define NONAMELESSUNION
54 #include "windef.h"
55 #include "winternl.h"
56 #include "wine/library.h"
57 #include "wine/server.h"
58 #include "wine/exception.h"
59 #include "wine/rbtree.h"
60 #include "wine/debug.h"
61 #include "ntdll_misc.h"
63 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
64 WINE_DECLARE_DEBUG_CHANNEL(module);
66 #ifndef MAP_NORESERVE
67 #define MAP_NORESERVE 0
68 #endif
70 /* File view */
71 struct file_view
73 struct wine_rb_entry entry; /* entry in global view tree */
74 void *base; /* base address */
75 size_t size; /* size in bytes */
76 unsigned int protect; /* protection for all pages at allocation time and SEC_* flags */
79 /* per-page protection flags */
80 #define VPROT_READ 0x01
81 #define VPROT_WRITE 0x02
82 #define VPROT_EXEC 0x04
83 #define VPROT_WRITECOPY 0x08
84 #define VPROT_GUARD 0x10
85 #define VPROT_COMMITTED 0x20
86 #define VPROT_WRITEWATCH 0x40
87 /* per-mapping protection flags */
88 #define VPROT_SYSTEM 0x0200 /* system view (underlying mmap not under our control) */
90 /* Conversion from VPROT_* to Win32 flags */
91 static const BYTE VIRTUAL_Win32Flags[16] =
93 PAGE_NOACCESS, /* 0 */
94 PAGE_READONLY, /* READ */
95 PAGE_READWRITE, /* WRITE */
96 PAGE_READWRITE, /* READ | WRITE */
97 PAGE_EXECUTE, /* EXEC */
98 PAGE_EXECUTE_READ, /* READ | EXEC */
99 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
100 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
101 PAGE_WRITECOPY, /* WRITECOPY */
102 PAGE_WRITECOPY, /* READ | WRITECOPY */
103 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
104 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
105 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
106 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
107 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
108 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
111 static struct wine_rb_tree views_tree;
113 static RTL_CRITICAL_SECTION csVirtual;
114 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
116 0, 0, &csVirtual,
117 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
118 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
120 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
122 #ifdef __i386__
123 static const UINT page_shift = 12;
124 static const UINT_PTR page_mask = 0xfff;
125 /* Note: these are Windows limits, you cannot change them. */
126 static void *address_space_limit = (void *)0xc0000000; /* top of the total available address space */
127 static void *user_space_limit = (void *)0x7fff0000; /* top of the user address space */
128 static void *working_set_limit = (void *)0x7fff0000; /* top of the current working set */
129 static void *address_space_start = (void *)0x110000; /* keep DOS area clear */
130 #elif defined(__x86_64__)
131 static const UINT page_shift = 12;
132 static const UINT_PTR page_mask = 0xfff;
133 static void *address_space_limit = (void *)0x7fffffff0000;
134 static void *user_space_limit = (void *)0x7fffffff0000;
135 static void *working_set_limit = (void *)0x7fffffff0000;
136 static void *address_space_start = (void *)0x10000;
137 #else
138 UINT_PTR page_size = 0;
139 static UINT page_shift;
140 static UINT_PTR page_mask;
141 static void *address_space_limit;
142 static void *user_space_limit;
143 static void *working_set_limit;
144 static void *address_space_start = (void *)0x10000;
145 #endif /* __i386__ */
146 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
148 #define ROUND_ADDR(addr,mask) \
149 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
151 #define ROUND_SIZE(addr,size) \
152 (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
154 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
155 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
157 #ifdef _WIN64 /* on 64-bit the page protection bytes use a 2-level table */
158 static const size_t pages_vprot_shift = 20;
159 static const size_t pages_vprot_mask = (1 << 20) - 1;
160 static size_t pages_vprot_size;
161 static BYTE **pages_vprot;
162 #else /* on 32-bit we use a simple array with one byte per page */
163 static BYTE *pages_vprot;
164 #endif
166 static struct file_view *view_block_start, *view_block_end, *next_free_view;
167 static const size_t view_block_size = 0x100000;
168 static void *preload_reserve_start;
169 static void *preload_reserve_end;
170 static BOOL use_locks;
171 static BOOL force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
173 static inline int is_view_valloc( const struct file_view *view )
175 return !(view->protect & (SEC_FILE | SEC_RESERVE | SEC_COMMIT));
178 /***********************************************************************
179 * get_page_vprot
181 * Return the page protection byte.
183 static BYTE get_page_vprot( const void *addr )
185 size_t idx = (size_t)addr >> page_shift;
187 #ifdef _WIN64
188 if (!pages_vprot[idx >> pages_vprot_shift]) return 0;
189 return pages_vprot[idx >> pages_vprot_shift][idx & pages_vprot_mask];
190 #else
191 return pages_vprot[idx];
192 #endif
196 /***********************************************************************
197 * set_page_vprot
199 * Set a range of page protection bytes.
201 static void set_page_vprot( const void *addr, size_t size, BYTE vprot )
203 size_t idx = (size_t)addr >> page_shift;
204 size_t end = ((size_t)addr + size + page_mask) >> page_shift;
206 #ifdef _WIN64
207 while (idx >> pages_vprot_shift != end >> pages_vprot_shift)
209 size_t dir_size = pages_vprot_mask + 1 - (idx & pages_vprot_mask);
210 memset( pages_vprot[idx >> pages_vprot_shift] + (idx & pages_vprot_mask), vprot, dir_size );
211 idx += dir_size;
213 memset( pages_vprot[idx >> pages_vprot_shift] + (idx & pages_vprot_mask), vprot, end - idx );
214 #else
215 memset( pages_vprot + idx, vprot, end - idx );
216 #endif
220 /***********************************************************************
221 * set_page_vprot_bits
223 * Set or clear bits in a range of page protection bytes.
225 static void set_page_vprot_bits( const void *addr, size_t size, BYTE set, BYTE clear )
227 size_t idx = (size_t)addr >> page_shift;
228 size_t end = ((size_t)addr + size + page_mask) >> page_shift;
230 #ifdef _WIN64
231 for ( ; idx < end; idx++)
233 BYTE *ptr = pages_vprot[idx >> pages_vprot_shift] + (idx & pages_vprot_mask);
234 *ptr = (*ptr & ~clear) | set;
236 #else
237 for ( ; idx < end; idx++) pages_vprot[idx] = (pages_vprot[idx] & ~clear) | set;
238 #endif
242 /***********************************************************************
243 * alloc_pages_vprot
245 * Allocate the page protection bytes for a given range.
247 static BOOL alloc_pages_vprot( const void *addr, size_t size )
249 #ifdef _WIN64
250 size_t idx = (size_t)addr >> page_shift;
251 size_t end = ((size_t)addr + size + page_mask) >> page_shift;
252 size_t i;
253 void *ptr;
255 assert( end <= pages_vprot_size << pages_vprot_shift );
256 for (i = idx >> pages_vprot_shift; i < (end + pages_vprot_mask) >> pages_vprot_shift; i++)
258 if (pages_vprot[i]) continue;
259 if ((ptr = wine_anon_mmap( NULL, pages_vprot_mask + 1, PROT_READ | PROT_WRITE, 0 )) == (void *)-1)
260 return FALSE;
261 pages_vprot[i] = ptr;
263 #endif
264 return TRUE;
268 /***********************************************************************
269 * compare_view
271 * View comparison function used for the rb tree.
273 static int compare_view( const void *addr, const struct wine_rb_entry *entry )
275 struct file_view *view = WINE_RB_ENTRY_VALUE( entry, struct file_view, entry );
277 if (addr < view->base) return -1;
278 if (addr > view->base) return 1;
279 return 0;
283 /***********************************************************************
284 * VIRTUAL_GetProtStr
286 static const char *VIRTUAL_GetProtStr( BYTE prot )
288 static char buffer[6];
289 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
290 buffer[1] = (prot & VPROT_GUARD) ? 'g' : ((prot & VPROT_WRITEWATCH) ? 'H' : '-');
291 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
292 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
293 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
294 buffer[5] = 0;
295 return buffer;
299 /***********************************************************************
300 * VIRTUAL_GetUnixProt
302 * Convert page protections to protection for mmap/mprotect.
304 static int VIRTUAL_GetUnixProt( BYTE vprot )
306 int prot = 0;
307 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
309 if (vprot & VPROT_READ) prot |= PROT_READ;
310 if (vprot & VPROT_WRITE) prot |= PROT_WRITE | PROT_READ;
311 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE | PROT_READ;
312 if (vprot & VPROT_EXEC) prot |= PROT_EXEC | PROT_READ;
313 if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
315 if (!prot) prot = PROT_NONE;
316 return prot;
320 /***********************************************************************
321 * VIRTUAL_DumpView
323 static void VIRTUAL_DumpView( struct file_view *view )
325 UINT i, count;
326 char *addr = view->base;
327 BYTE prot = get_page_vprot( addr );
329 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
330 if (view->protect & VPROT_SYSTEM)
331 TRACE( " (builtin image)\n" );
332 else if (view->protect & SEC_IMAGE)
333 TRACE( " (image)\n" );
334 else if (view->protect & SEC_FILE)
335 TRACE( " (file)\n" );
336 else if (view->protect & (SEC_RESERVE | SEC_COMMIT))
337 TRACE( " (anonymous)\n" );
338 else
339 TRACE( " (valloc)\n");
341 for (count = i = 1; i < view->size >> page_shift; i++, count++)
343 BYTE next = get_page_vprot( addr + (count << page_shift) );
344 if (next == prot) continue;
345 TRACE( " %p - %p %s\n",
346 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
347 addr += (count << page_shift);
348 prot = next;
349 count = 0;
351 if (count)
352 TRACE( " %p - %p %s\n",
353 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
357 /***********************************************************************
358 * VIRTUAL_Dump
360 #ifdef WINE_VM_DEBUG
361 static void VIRTUAL_Dump(void)
363 sigset_t sigset;
364 struct file_view *view;
366 TRACE( "Dump of all virtual memory views:\n" );
367 server_enter_uninterrupted_section( &csVirtual, &sigset );
368 WINE_RB_FOR_EACH_ENTRY( view, &views_tree, struct file_view, entry )
370 VIRTUAL_DumpView( view );
372 server_leave_uninterrupted_section( &csVirtual, &sigset );
374 #endif
377 /***********************************************************************
378 * VIRTUAL_FindView
380 * Find the view containing a given address. The csVirtual section must be held by caller.
382 * PARAMS
383 * addr [I] Address
385 * RETURNS
386 * View: Success
387 * NULL: Failure
389 static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
391 struct wine_rb_entry *ptr = views_tree.root;
393 if ((const char *)addr + size < (const char *)addr) return NULL; /* overflow */
395 while (ptr)
397 struct file_view *view = WINE_RB_ENTRY_VALUE( ptr, struct file_view, entry );
399 if (view->base > addr) ptr = ptr->left;
400 else if ((const char *)view->base + view->size <= (const char *)addr) ptr = ptr->right;
401 else if ((const char *)view->base + view->size < (const char *)addr + size) break; /* size too large */
402 else return view;
404 return NULL;
408 /***********************************************************************
409 * get_mask
411 static inline UINT_PTR get_mask( ULONG zero_bits )
413 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
414 if (zero_bits < page_shift) zero_bits = page_shift;
415 if (zero_bits > 21) return 0;
416 return (1 << zero_bits) - 1;
420 /***********************************************************************
421 * is_write_watch_range
423 static inline BOOL is_write_watch_range( const void *addr, size_t size )
425 struct file_view *view = VIRTUAL_FindView( addr, size );
426 return view && (view->protect & VPROT_WRITEWATCH);
430 /***********************************************************************
431 * find_view_range
433 * Find the first view overlapping at least part of the specified range.
434 * The csVirtual section must be held by caller.
436 static struct file_view *find_view_range( const void *addr, size_t size )
438 struct wine_rb_entry *ptr = views_tree.root;
440 while (ptr)
442 struct file_view *view = WINE_RB_ENTRY_VALUE( ptr, struct file_view, entry );
444 if ((const char *)view->base >= (const char *)addr + size) ptr = ptr->left;
445 else if ((const char *)view->base + view->size <= (const char *)addr) ptr = ptr->right;
446 else return view;
448 return NULL;
452 /***********************************************************************
453 * find_free_area
455 * Find a free area between views inside the specified range.
456 * The csVirtual section must be held by caller.
458 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
460 struct wine_rb_entry *first = NULL, *ptr = views_tree.root;
461 void *start;
463 /* find the first (resp. last) view inside the range */
464 while (ptr)
466 struct file_view *view = WINE_RB_ENTRY_VALUE( ptr, struct file_view, entry );
467 if ((char *)view->base + view->size >= (char *)end)
469 end = min( end, view->base );
470 ptr = ptr->left;
472 else if (view->base <= base)
474 base = max( (char *)base, (char *)view->base + view->size );
475 ptr = ptr->right;
477 else
479 first = ptr;
480 ptr = top_down ? ptr->right : ptr->left;
484 if (top_down)
486 start = ROUND_ADDR( (char *)end - size, mask );
487 if (start >= end || start < base) return NULL;
489 while (first)
491 struct file_view *view = WINE_RB_ENTRY_VALUE( first, struct file_view, entry );
493 if ((char *)view->base + view->size <= (char *)start) break;
494 start = ROUND_ADDR( (char *)view->base - size, mask );
495 /* stop if remaining space is not large enough */
496 if (!start || start >= end || start < base) return NULL;
497 first = wine_rb_prev( first );
500 else
502 start = ROUND_ADDR( (char *)base + mask, mask );
503 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
505 while (first)
507 struct file_view *view = WINE_RB_ENTRY_VALUE( first, struct file_view, entry );
509 if ((char *)view->base >= (char *)start + size) break;
510 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
511 /* stop if remaining space is not large enough */
512 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
513 first = wine_rb_next( first );
516 return start;
520 /***********************************************************************
521 * add_reserved_area
523 * Add a reserved area to the list maintained by libwine.
524 * The csVirtual section must be held by caller.
526 static void add_reserved_area( void *addr, size_t size )
528 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
530 if (addr < user_space_limit)
532 /* unmap the part of the area that is below the limit */
533 assert( (char *)addr + size > (char *)user_space_limit );
534 munmap( addr, (char *)user_space_limit - (char *)addr );
535 size -= (char *)user_space_limit - (char *)addr;
536 addr = user_space_limit;
538 /* blow away existing mappings */
539 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
540 wine_mmap_add_reserved_area( addr, size );
544 /***********************************************************************
545 * remove_reserved_area
547 * Remove a reserved area from the list maintained by libwine.
548 * The csVirtual section must be held by caller.
550 static void remove_reserved_area( void *addr, size_t size )
552 struct file_view *view;
554 TRACE( "removing %p-%p\n", addr, (char *)addr + size );
555 wine_mmap_remove_reserved_area( addr, size, 0 );
557 /* unmap areas not covered by an existing view */
558 WINE_RB_FOR_EACH_ENTRY( view, &views_tree, struct file_view, entry )
560 if ((char *)view->base >= (char *)addr + size) break;
561 if ((char *)view->base + view->size <= (char *)addr) continue;
562 if (view->base > addr) munmap( addr, (char *)view->base - (char *)addr );
563 if ((char *)view->base + view->size > (char *)addr + size) return;
564 size = (char *)addr + size - ((char *)view->base + view->size);
565 addr = (char *)view->base + view->size;
567 munmap( addr, size );
571 struct area_boundary
573 void *base;
574 size_t size;
575 void *boundary;
578 /***********************************************************************
579 * get_area_boundary_callback
581 * Get lowest boundary address between reserved area and non-reserved area
582 * in the specified region. If no boundaries are found, result is NULL.
583 * The csVirtual section must be held by caller.
585 static int get_area_boundary_callback( void *start, size_t size, void *arg )
587 struct area_boundary *area = arg;
588 void *end = (char *)start + size;
590 area->boundary = NULL;
591 if (area->base >= end) return 0;
592 if ((char *)start >= (char *)area->base + area->size) return 1;
593 if (area->base >= start)
595 if ((char *)area->base + area->size > (char *)end)
597 area->boundary = end;
598 return 1;
600 return 0;
602 area->boundary = start;
603 return 1;
607 /***********************************************************************
608 * is_beyond_limit
610 * Check if an address range goes beyond a given limit.
612 static inline BOOL is_beyond_limit( const void *addr, size_t size, const void *limit )
614 return (addr >= limit || (const char *)addr + size > (const char *)limit);
618 /***********************************************************************
619 * unmap_area
621 * Unmap an area, or simply replace it by an empty mapping if it is
622 * in a reserved area. The csVirtual section must be held by caller.
624 static inline void unmap_area( void *addr, size_t size )
626 switch (wine_mmap_is_in_reserved_area( addr, size ))
628 case -1: /* partially in a reserved area */
630 struct area_boundary area;
631 size_t lower_size;
632 area.base = addr;
633 area.size = size;
634 wine_mmap_enum_reserved_areas( get_area_boundary_callback, &area, 0 );
635 assert( area.boundary );
636 lower_size = (char *)area.boundary - (char *)addr;
637 unmap_area( addr, lower_size );
638 unmap_area( area.boundary, size - lower_size );
639 break;
641 case 1: /* in a reserved area */
642 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
643 break;
644 default:
645 case 0: /* not in a reserved area */
646 if (is_beyond_limit( addr, size, user_space_limit ))
647 add_reserved_area( addr, size );
648 else
649 munmap( addr, size );
650 break;
655 /***********************************************************************
656 * alloc_view
658 * Allocate a new view. The csVirtual section must be held by caller.
660 static struct file_view *alloc_view(void)
662 if (next_free_view)
664 struct file_view *ret = next_free_view;
665 next_free_view = *(struct file_view **)ret;
666 return ret;
668 if (view_block_start == view_block_end)
670 void *ptr = wine_anon_mmap( NULL, view_block_size, PROT_READ | PROT_WRITE, 0 );
671 if (ptr == (void *)-1) return NULL;
672 view_block_start = ptr;
673 view_block_end = view_block_start + view_block_size / sizeof(*view_block_start);
675 return view_block_start++;
679 /***********************************************************************
680 * delete_view
682 * Deletes a view. The csVirtual section must be held by caller.
684 static void delete_view( struct file_view *view ) /* [in] View */
686 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
687 set_page_vprot( view->base, view->size, 0 );
688 wine_rb_remove( &views_tree, &view->entry );
689 *(struct file_view **)view = next_free_view;
690 next_free_view = view;
694 /***********************************************************************
695 * create_view
697 * Create a view. The csVirtual section must be held by caller.
699 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
701 struct file_view *view;
702 int unix_prot = VIRTUAL_GetUnixProt( vprot );
704 assert( !((UINT_PTR)base & page_mask) );
705 assert( !(size & page_mask) );
707 /* Check for overlapping views. This can happen if the previous view
708 * was a system view that got unmapped behind our back. In that case
709 * we recover by simply deleting it. */
711 while ((view = find_view_range( base, size )))
713 TRACE( "overlapping view %p-%p for %p-%p\n",
714 view->base, (char *)view->base + view->size, base, (char *)base + size );
715 assert( view->protect & VPROT_SYSTEM );
716 delete_view( view );
719 if (!alloc_pages_vprot( base, size )) return STATUS_NO_MEMORY;
721 /* Create the view structure */
723 if (!(view = alloc_view()))
725 FIXME( "out of memory for %p-%p\n", base, (char *)base + size );
726 return STATUS_NO_MEMORY;
729 view->base = base;
730 view->size = size;
731 view->protect = vprot;
732 set_page_vprot( base, size, vprot );
734 wine_rb_put( &views_tree, view->base, &view->entry );
736 *view_ret = view;
738 if (force_exec_prot && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
740 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
741 mprotect( base, size, unix_prot | PROT_EXEC );
743 return STATUS_SUCCESS;
747 /***********************************************************************
748 * VIRTUAL_GetWin32Prot
750 * Convert page protections to Win32 flags.
752 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot, unsigned int map_prot )
754 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
755 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
756 if (map_prot & SEC_NOCACHE) ret |= PAGE_NOCACHE;
757 return ret;
761 /***********************************************************************
762 * get_vprot_flags
764 * Build page protections from Win32 flags.
766 * PARAMS
767 * protect [I] Win32 protection flags
769 * RETURNS
770 * Value of page protection flags
772 static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot, BOOL image )
774 switch(protect & 0xff)
776 case PAGE_READONLY:
777 *vprot = VPROT_READ;
778 break;
779 case PAGE_READWRITE:
780 if (image)
781 *vprot = VPROT_READ | VPROT_WRITECOPY;
782 else
783 *vprot = VPROT_READ | VPROT_WRITE;
784 break;
785 case PAGE_WRITECOPY:
786 *vprot = VPROT_READ | VPROT_WRITECOPY;
787 break;
788 case PAGE_EXECUTE:
789 *vprot = VPROT_EXEC;
790 break;
791 case PAGE_EXECUTE_READ:
792 *vprot = VPROT_EXEC | VPROT_READ;
793 break;
794 case PAGE_EXECUTE_READWRITE:
795 if (image)
796 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
797 else
798 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
799 break;
800 case PAGE_EXECUTE_WRITECOPY:
801 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
802 break;
803 case PAGE_NOACCESS:
804 *vprot = 0;
805 break;
806 default:
807 return STATUS_INVALID_PAGE_PROTECTION;
809 if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
810 return STATUS_SUCCESS;
814 /***********************************************************************
815 * mprotect_exec
817 * Wrapper for mprotect, adds PROT_EXEC if forced by force_exec_prot
819 static inline int mprotect_exec( void *base, size_t size, int unix_prot )
821 if (force_exec_prot && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
823 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
824 if (!mprotect( base, size, unix_prot | PROT_EXEC )) return 0;
825 /* exec + write may legitimately fail, in that case fall back to write only */
826 if (!(unix_prot & PROT_WRITE)) return -1;
829 return mprotect( base, size, unix_prot );
833 /***********************************************************************
834 * mprotect_range
836 * Call mprotect on a page range, applying the protections from the per-page byte.
838 static void mprotect_range( void *base, size_t size, BYTE set, BYTE clear )
840 size_t i, count;
841 char *addr = ROUND_ADDR( base, page_mask );
842 int prot, next;
844 size = ROUND_SIZE( base, size );
845 prot = VIRTUAL_GetUnixProt( (get_page_vprot( addr ) & ~clear ) | set );
846 for (count = i = 1; i < size >> page_shift; i++, count++)
848 next = VIRTUAL_GetUnixProt( (get_page_vprot( addr + (count << page_shift) ) & ~clear) | set );
849 if (next == prot) continue;
850 mprotect_exec( addr, count << page_shift, prot );
851 addr += count << page_shift;
852 prot = next;
853 count = 0;
855 if (count) mprotect_exec( addr, count << page_shift, prot );
859 /***********************************************************************
860 * VIRTUAL_SetProt
862 * Change the protection of a range of pages.
864 * RETURNS
865 * TRUE: Success
866 * FALSE: Failure
868 static BOOL VIRTUAL_SetProt( struct file_view *view, /* [in] Pointer to view */
869 void *base, /* [in] Starting address */
870 size_t size, /* [in] Size in bytes */
871 BYTE vprot ) /* [in] Protections to use */
873 int unix_prot = VIRTUAL_GetUnixProt(vprot);
875 if (view->protect & VPROT_WRITEWATCH)
877 /* each page may need different protections depending on write watch flag */
878 set_page_vprot_bits( base, size, vprot & ~VPROT_WRITEWATCH, ~vprot & ~VPROT_WRITEWATCH );
879 mprotect_range( base, size, 0, 0 );
880 return TRUE;
883 /* if setting stack guard pages, store the permissions first, as the guard may be
884 * triggered at any point after mprotect and change the permissions again */
885 if ((vprot & VPROT_GUARD) &&
886 (base >= NtCurrentTeb()->DeallocationStack) &&
887 (base < NtCurrentTeb()->Tib.StackBase))
889 set_page_vprot( base, size, vprot );
890 mprotect( base, size, unix_prot );
891 return TRUE;
894 if (mprotect_exec( base, size, unix_prot )) /* FIXME: last error */
895 return FALSE;
897 set_page_vprot( base, size, vprot );
898 return TRUE;
902 /***********************************************************************
903 * set_protection
905 * Set page protections on a range of pages
907 static NTSTATUS set_protection( struct file_view *view, void *base, SIZE_T size, ULONG protect )
909 unsigned int vprot;
910 NTSTATUS status;
912 if ((status = get_vprot_flags( protect, &vprot, view->protect & SEC_IMAGE ))) return status;
913 if (is_view_valloc( view ))
915 if (vprot & VPROT_WRITECOPY) return STATUS_INVALID_PAGE_PROTECTION;
917 else
919 BYTE access = vprot & (VPROT_READ | VPROT_WRITE | VPROT_EXEC);
920 if ((view->protect & access) != access) return STATUS_INVALID_PAGE_PROTECTION;
923 if (!VIRTUAL_SetProt( view, base, size, vprot | VPROT_COMMITTED )) return STATUS_ACCESS_DENIED;
924 return STATUS_SUCCESS;
928 /***********************************************************************
929 * update_write_watches
931 static void update_write_watches( void *base, size_t size, size_t accessed_size )
933 TRACE( "updating watch %p-%p-%p\n", base, (char *)base + accessed_size, (char *)base + size );
934 /* clear write watch flag on accessed pages */
935 set_page_vprot_bits( base, accessed_size, 0, VPROT_WRITEWATCH );
936 /* restore page protections on the entire range */
937 mprotect_range( base, size, 0, 0 );
941 /***********************************************************************
942 * reset_write_watches
944 * Reset write watches in a memory range.
946 static void reset_write_watches( void *base, SIZE_T size )
948 set_page_vprot_bits( base, size, VPROT_WRITEWATCH, 0 );
949 mprotect_range( base, size, 0, 0 );
953 /***********************************************************************
954 * unmap_extra_space
956 * Release the extra memory while keeping the range starting on the granularity boundary.
958 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
960 if ((ULONG_PTR)ptr & mask)
962 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
963 munmap( ptr, extra );
964 ptr = (char *)ptr + extra;
965 total_size -= extra;
967 if (total_size > wanted_size)
968 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
969 return ptr;
973 struct alloc_area
975 size_t size;
976 size_t mask;
977 int top_down;
978 void *limit;
979 void *result;
982 /***********************************************************************
983 * alloc_reserved_area_callback
985 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
987 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
989 struct alloc_area *alloc = arg;
990 void *end = (char *)start + size;
992 if (start < address_space_start) start = address_space_start;
993 if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
994 if (start >= end) return 0;
996 /* make sure we don't touch the preloader reserved range */
997 if (preload_reserve_end >= start)
999 if (preload_reserve_end >= end)
1001 if (preload_reserve_start <= start) return 0; /* no space in that area */
1002 if (preload_reserve_start < end) end = preload_reserve_start;
1004 else if (preload_reserve_start <= start) start = preload_reserve_end;
1005 else
1007 /* range is split in two by the preloader reservation, try first part */
1008 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
1009 alloc->mask, alloc->top_down )))
1010 return 1;
1011 /* then fall through to try second part */
1012 start = preload_reserve_end;
1015 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
1016 return 1;
1018 return 0;
1021 /***********************************************************************
1022 * map_fixed_area
1024 * mmap the fixed memory area.
1025 * The csVirtual section must be held by caller.
1027 static NTSTATUS map_fixed_area( void *base, size_t size, unsigned int vprot )
1029 void *ptr;
1031 switch (wine_mmap_is_in_reserved_area( base, size ))
1033 case -1: /* partially in a reserved area */
1035 NTSTATUS status;
1036 struct area_boundary area;
1037 size_t lower_size;
1038 area.base = base;
1039 area.size = size;
1040 wine_mmap_enum_reserved_areas( get_area_boundary_callback, &area, 0 );
1041 assert( area.boundary );
1042 lower_size = (char *)area.boundary - (char *)base;
1043 status = map_fixed_area( base, lower_size, vprot );
1044 if (status == STATUS_SUCCESS)
1046 status = map_fixed_area( area.boundary, size - lower_size, vprot);
1047 if (status != STATUS_SUCCESS) unmap_area( base, lower_size );
1049 return status;
1051 case 0: /* not in a reserved area, do a normal allocation */
1052 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
1054 if (errno == ENOMEM) return STATUS_NO_MEMORY;
1055 return STATUS_INVALID_PARAMETER;
1057 if (ptr != base)
1059 /* We couldn't get the address we wanted */
1060 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
1061 else munmap( ptr, size );
1062 return STATUS_CONFLICTING_ADDRESSES;
1064 break;
1066 default:
1067 case 1: /* in a reserved area, make sure the address is available */
1068 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
1069 /* replace the reserved area by our mapping */
1070 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
1071 return STATUS_INVALID_PARAMETER;
1072 break;
1074 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
1075 return STATUS_SUCCESS;
1078 /***********************************************************************
1079 * map_view
1081 * Create a view and mmap the corresponding memory area.
1082 * The csVirtual section must be held by caller.
1084 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
1085 int top_down, unsigned int vprot )
1087 void *ptr;
1088 NTSTATUS status;
1090 if (base)
1092 if (is_beyond_limit( base, size, address_space_limit ))
1093 return STATUS_WORKING_SET_LIMIT_RANGE;
1094 status = map_fixed_area( base, size, vprot );
1095 if (status != STATUS_SUCCESS) return status;
1096 ptr = base;
1098 else
1100 size_t view_size = size + mask + 1;
1101 struct alloc_area alloc;
1103 alloc.size = size;
1104 alloc.mask = mask;
1105 alloc.top_down = top_down;
1106 alloc.limit = user_space_limit;
1107 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
1109 ptr = alloc.result;
1110 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
1111 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
1112 return STATUS_INVALID_PARAMETER;
1113 goto done;
1116 for (;;)
1118 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
1120 if (errno == ENOMEM) return STATUS_NO_MEMORY;
1121 return STATUS_INVALID_PARAMETER;
1123 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
1124 /* if we got something beyond the user limit, unmap it and retry */
1125 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
1126 else break;
1128 ptr = unmap_extra_space( ptr, view_size, size, mask );
1130 done:
1131 status = create_view( view_ret, ptr, size, vprot );
1132 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
1133 return status;
1137 /***********************************************************************
1138 * map_file_into_view
1140 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
1141 * The csVirtual section must be held by caller.
1143 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
1144 off_t offset, unsigned int vprot, BOOL removable )
1146 void *ptr;
1147 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
1148 unsigned int flags = MAP_FIXED | ((vprot & VPROT_WRITECOPY) ? MAP_PRIVATE : MAP_SHARED);
1150 assert( start < view->size );
1151 assert( start + size <= view->size );
1153 if (force_exec_prot && (vprot & VPROT_READ))
1155 TRACE( "forcing exec permission on mapping %p-%p\n",
1156 (char *)view->base + start, (char *)view->base + start + size - 1 );
1157 prot |= PROT_EXEC;
1160 /* only try mmap if media is not removable (or if we require write access) */
1161 if (!removable || (flags & MAP_SHARED))
1163 if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
1164 goto done;
1166 if ((errno == EPERM) && (prot & PROT_EXEC))
1167 ERR( "failed to set %08x protection on file map, noexec filesystem?\n", prot );
1169 /* mmap() failed; if this is because the file offset is not */
1170 /* page-aligned (EINVAL), or because the underlying filesystem */
1171 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
1172 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
1173 if (flags & MAP_SHARED) /* we cannot fake shared mappings */
1175 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
1176 ERR( "shared writable mmap not supported, broken filesystem?\n" );
1177 return STATUS_NOT_SUPPORTED;
1181 /* Reserve the memory with an anonymous mmap */
1182 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1183 if (ptr == (void *)-1) return FILE_GetNtStatus();
1184 /* Now read in the file */
1185 pread( fd, ptr, size, offset );
1186 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
1187 done:
1188 set_page_vprot( (char *)view->base + start, size, vprot );
1189 return STATUS_SUCCESS;
1193 /***********************************************************************
1194 * get_committed_size
1196 * Get the size of the committed range starting at base.
1197 * Also return the protections for the first page.
1199 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
1201 SIZE_T i, start;
1203 start = ((char *)base - (char *)view->base) >> page_shift;
1204 *vprot = get_page_vprot( base );
1206 if (view->protect & SEC_RESERVE)
1208 SIZE_T ret = 0;
1209 SERVER_START_REQ( get_mapping_committed_range )
1211 req->base = wine_server_client_ptr( view->base );
1212 req->offset = start << page_shift;
1213 if (!wine_server_call( req ))
1215 ret = reply->size;
1216 if (reply->committed)
1218 *vprot |= VPROT_COMMITTED;
1219 set_page_vprot_bits( base, ret, VPROT_COMMITTED, 0 );
1223 SERVER_END_REQ;
1224 return ret;
1226 for (i = start + 1; i < view->size >> page_shift; i++)
1227 if ((*vprot ^ get_page_vprot( (char *)view->base + (i << page_shift) )) & VPROT_COMMITTED) break;
1228 return (i - start) << page_shift;
1232 /***********************************************************************
1233 * decommit_view
1235 * Decommit some pages of a given view.
1236 * The csVirtual section must be held by caller.
1238 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
1240 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
1242 set_page_vprot_bits( (char *)view->base + start, size, 0, VPROT_COMMITTED );
1243 return STATUS_SUCCESS;
1245 return FILE_GetNtStatus();
1249 /***********************************************************************
1250 * allocate_dos_memory
1252 * Allocate the DOS memory range.
1254 static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
1256 size_t size;
1257 void *addr = NULL;
1258 void * const low_64k = (void *)0x10000;
1259 const size_t dosmem_size = 0x110000;
1260 int unix_prot = VIRTUAL_GetUnixProt( vprot );
1262 /* check for existing view */
1264 if (find_view_range( 0, dosmem_size )) return STATUS_CONFLICTING_ADDRESSES;
1266 /* check without the first 64K */
1268 if (wine_mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
1270 addr = wine_anon_mmap( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
1271 if (addr != low_64k)
1273 if (addr != (void *)-1) munmap( addr, dosmem_size - 0x10000 );
1274 return map_view( view, NULL, dosmem_size, 0xffff, 0, vprot );
1278 /* now try to allocate the low 64K too */
1280 if (wine_mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
1282 addr = wine_anon_mmap( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
1283 if (addr == (void *)page_size)
1285 if (!wine_anon_mmap( NULL, page_size, unix_prot, MAP_FIXED ))
1287 addr = NULL;
1288 TRACE( "successfully mapped low 64K range\n" );
1290 else TRACE( "failed to map page 0\n" );
1292 else
1294 if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
1295 addr = low_64k;
1296 TRACE( "failed to map low 64K range\n" );
1300 /* now reserve the whole range */
1302 size = (char *)dosmem_size - (char *)addr;
1303 wine_anon_mmap( addr, size, unix_prot, MAP_FIXED );
1304 return create_view( view, addr, size, vprot );
1308 /***********************************************************************
1309 * map_image
1311 * Map an executable (PE format) image into memory.
1313 static NTSTATUS map_image( HANDLE hmapping, ACCESS_MASK access, int fd, char *base, SIZE_T total_size,
1314 SIZE_T mask, SIZE_T header_size, int shared_fd, BOOL removable, PVOID *addr_ptr )
1316 IMAGE_DOS_HEADER *dos;
1317 IMAGE_NT_HEADERS *nt;
1318 IMAGE_SECTION_HEADER sections[96];
1319 IMAGE_SECTION_HEADER *sec;
1320 IMAGE_DATA_DIRECTORY *imports;
1321 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
1322 int i;
1323 off_t pos;
1324 sigset_t sigset;
1325 struct stat st;
1326 struct file_view *view = NULL;
1327 char *ptr, *header_end, *header_start;
1329 /* zero-map the whole range */
1331 server_enter_uninterrupted_section( &csVirtual, &sigset );
1333 if (base >= (char *)address_space_start) /* make sure the DOS area remains free */
1334 status = map_view( &view, base, total_size, mask, FALSE, SEC_IMAGE | SEC_FILE |
1335 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY );
1337 if (status != STATUS_SUCCESS)
1338 status = map_view( &view, NULL, total_size, mask, FALSE, SEC_IMAGE | SEC_FILE |
1339 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY );
1341 if (status != STATUS_SUCCESS) goto error;
1343 ptr = view->base;
1344 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
1346 /* map the header */
1348 if (fstat( fd, &st ) == -1)
1350 status = FILE_GetNtStatus();
1351 goto error;
1353 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
1354 if (!st.st_size) goto error;
1355 header_size = min( header_size, st.st_size );
1356 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1357 removable ) != STATUS_SUCCESS) goto error;
1358 dos = (IMAGE_DOS_HEADER *)ptr;
1359 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1360 header_end = ptr + ROUND_SIZE( 0, header_size );
1361 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1362 if ((char *)(nt + 1) > header_end) goto error;
1363 header_start = (char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader;
1364 if (nt->FileHeader.NumberOfSections > sizeof(sections)/sizeof(*sections)) goto error;
1365 if (header_start + sizeof(*sections) * nt->FileHeader.NumberOfSections > header_end) goto error;
1366 /* Some applications (e.g. the Steam version of Borderlands) map over the top of the section headers,
1367 * copying the headers into local memory is necessary to properly load such applications. */
1368 memcpy(sections, header_start, sizeof(*sections) * nt->FileHeader.NumberOfSections);
1369 sec = sections;
1371 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
1372 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
1374 /* check for non page-aligned binary */
1376 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1378 /* unaligned sections, this happens for native subsystem binaries */
1379 /* in that case Windows simply maps in the whole file */
1381 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1382 removable ) != STATUS_SUCCESS) goto error;
1384 /* check that all sections are loaded at the right offset */
1385 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1386 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1388 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1389 goto error; /* Windows refuses to load in that case too */
1392 /* set the image protections */
1393 VIRTUAL_SetProt( view, ptr, total_size,
1394 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1396 /* no relocations are performed on non page-aligned binaries */
1397 goto done;
1401 /* map all the sections */
1403 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1405 static const SIZE_T sector_align = 0x1ff;
1406 SIZE_T map_size, file_start, file_size, end;
1408 if (!sec->Misc.VirtualSize)
1409 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1410 else
1411 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1413 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1414 file_start = sec->PointerToRawData & ~sector_align;
1415 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1416 if (file_size > map_size) file_size = map_size;
1418 /* a few sanity checks */
1419 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1420 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1422 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1423 sec->Name, sec->VirtualAddress, map_size, total_size );
1424 goto error;
1427 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1428 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1430 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1431 sec->Name, ptr + sec->VirtualAddress,
1432 sec->PointerToRawData, (int)pos, file_size, map_size,
1433 sec->Characteristics );
1434 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1435 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE, FALSE ) != STATUS_SUCCESS)
1437 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1438 goto error;
1441 /* check if the import directory falls inside this section */
1442 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1443 imports->VirtualAddress < sec->VirtualAddress + map_size)
1445 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1446 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1447 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1448 if (end > base)
1449 map_file_into_view( view, shared_fd, base, end - base,
1450 pos + (base - sec->VirtualAddress),
1451 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY, FALSE );
1453 pos += map_size;
1454 continue;
1457 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1458 sec->Name, ptr + sec->VirtualAddress,
1459 sec->PointerToRawData, sec->SizeOfRawData,
1460 sec->Misc.VirtualSize, sec->Characteristics );
1462 if (!sec->PointerToRawData || !file_size) continue;
1464 /* Note: if the section is not aligned properly map_file_into_view will magically
1465 * fall back to read(), so we don't need to check anything here.
1467 end = file_start + file_size;
1468 if (sec->PointerToRawData >= st.st_size ||
1469 end > ((st.st_size + sector_align) & ~sector_align) ||
1470 end < file_start ||
1471 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1472 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1473 removable ) != STATUS_SUCCESS)
1475 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1476 goto error;
1479 if (file_size & page_mask)
1481 end = ROUND_SIZE( 0, file_size );
1482 if (end > map_size) end = map_size;
1483 TRACE_(module)("clearing %p - %p\n",
1484 ptr + sec->VirtualAddress + file_size,
1485 ptr + sec->VirtualAddress + end );
1486 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1490 /* set the image protections */
1492 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1494 sec = sections;
1495 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1497 SIZE_T size;
1498 BYTE vprot = VPROT_COMMITTED;
1500 if (sec->Misc.VirtualSize)
1501 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1502 else
1503 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1505 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1506 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_WRITECOPY;
1507 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1509 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1510 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1511 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1512 vprot |= VPROT_EXEC;
1514 if (!VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot ) && (vprot & VPROT_EXEC))
1515 ERR( "failed to set %08x protection on section %.8s, noexec filesystem?\n",
1516 sec->Characteristics, sec->Name );
1519 done:
1521 SERVER_START_REQ( map_view )
1523 req->mapping = wine_server_obj_handle( hmapping );
1524 req->access = access;
1525 req->base = wine_server_client_ptr( view->base );
1526 req->size = view->size;
1527 req->start = 0;
1528 status = wine_server_call( req );
1530 SERVER_END_REQ;
1531 if (status) goto error;
1533 VIRTUAL_DEBUG_DUMP_VIEW( view );
1534 server_leave_uninterrupted_section( &csVirtual, &sigset );
1536 *addr_ptr = ptr;
1537 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1538 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, ptr - base);
1539 #endif
1540 if (ptr != base) return STATUS_IMAGE_NOT_AT_BASE;
1541 return STATUS_SUCCESS;
1543 error:
1544 if (view) delete_view( view );
1545 server_leave_uninterrupted_section( &csVirtual, &sigset );
1546 return status;
1550 struct alloc_virtual_heap
1552 void *base;
1553 size_t size;
1556 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1557 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1559 struct alloc_virtual_heap *alloc = arg;
1561 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1562 if (size < alloc->size) return 0;
1563 if (is_win64 && base < (void *)0x80000000) return 0;
1564 alloc->base = wine_anon_mmap( (char *)base + size - alloc->size, alloc->size,
1565 PROT_READ|PROT_WRITE, MAP_FIXED );
1566 return (alloc->base != (void *)-1);
1569 /***********************************************************************
1570 * virtual_init
1572 void virtual_init(void)
1574 const char *preload;
1575 struct alloc_virtual_heap alloc_views;
1576 size_t size;
1578 #if !defined(__i386__) && !defined(__x86_64__)
1579 page_size = sysconf( _SC_PAGESIZE );
1580 page_mask = page_size - 1;
1581 /* Make sure we have a power of 2 */
1582 assert( !(page_size & page_mask) );
1583 page_shift = 0;
1584 while ((1 << page_shift) != page_size) page_shift++;
1585 #ifdef _WIN64
1586 address_space_limit = (void *)(((1UL << 47) - 1) & ~page_mask);
1587 #else
1588 address_space_limit = (void *)~page_mask;
1589 #endif
1590 user_space_limit = working_set_limit = address_space_limit;
1591 #endif
1592 if ((preload = getenv("WINEPRELOADRESERVE")))
1594 unsigned long start, end;
1595 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1597 preload_reserve_start = (void *)start;
1598 preload_reserve_end = (void *)end;
1599 /* some apps start inside the DOS area */
1600 if (preload_reserve_start)
1601 address_space_start = min( address_space_start, preload_reserve_start );
1605 /* try to find space in a reserved area for the views and pages protection table */
1606 #ifdef _WIN64
1607 pages_vprot_size = ((size_t)address_space_limit >> page_shift >> pages_vprot_shift) + 1;
1608 alloc_views.size = view_block_size + pages_vprot_size * sizeof(*pages_vprot);
1609 #else
1610 alloc_views.size = view_block_size + (1U << (32 - page_shift));
1611 #endif
1612 if (wine_mmap_enum_reserved_areas( alloc_virtual_heap, &alloc_views, 1 ))
1613 wine_mmap_remove_reserved_area( alloc_views.base, alloc_views.size, 0 );
1614 else
1615 alloc_views.base = wine_anon_mmap( NULL, alloc_views.size, PROT_READ | PROT_WRITE, 0 );
1617 assert( alloc_views.base != (void *)-1 );
1618 view_block_start = alloc_views.base;
1619 view_block_end = view_block_start + view_block_size / sizeof(*view_block_start);
1620 pages_vprot = (void *)((char *)alloc_views.base + view_block_size);
1621 wine_rb_init( &views_tree, compare_view );
1623 /* make the DOS area accessible (except the low 64K) to hide bugs in broken apps like Excel 2003 */
1624 size = (char *)address_space_start - (char *)0x10000;
1625 if (size && wine_mmap_is_in_reserved_area( (void*)0x10000, size ) == 1)
1626 wine_anon_mmap( (void *)0x10000, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1630 /***********************************************************************
1631 * virtual_init_threading
1633 void virtual_init_threading(void)
1635 use_locks = TRUE;
1639 /***********************************************************************
1640 * virtual_get_system_info
1642 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1644 #ifdef HAVE_SYSINFO
1645 struct sysinfo sinfo;
1646 #endif
1648 info->unknown = 0;
1649 info->KeMaximumIncrement = 0; /* FIXME */
1650 info->PageSize = page_size;
1651 info->MmLowestPhysicalPage = 1;
1652 info->MmHighestPhysicalPage = 0x7fffffff / page_size;
1653 #ifdef HAVE_SYSINFO
1654 if (!sysinfo(&sinfo))
1656 ULONG64 total = (ULONG64)sinfo.totalram * sinfo.mem_unit;
1657 info->MmHighestPhysicalPage = max(1, total / page_size);
1659 #endif
1660 info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
1661 info->AllocationGranularity = get_mask(0) + 1;
1662 info->LowestUserAddress = (void *)0x10000;
1663 info->HighestUserAddress = (char *)user_space_limit - 1;
1664 info->ActiveProcessorsAffinityMask = get_system_affinity_mask();
1665 info->NumberOfProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1669 /***********************************************************************
1670 * virtual_create_builtin_view
1672 NTSTATUS virtual_create_builtin_view( void *module )
1674 NTSTATUS status;
1675 sigset_t sigset;
1676 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1677 SIZE_T size = nt->OptionalHeader.SizeOfImage;
1678 IMAGE_SECTION_HEADER *sec;
1679 struct file_view *view;
1680 void *base;
1681 int i;
1683 size = ROUND_SIZE( module, size );
1684 base = ROUND_ADDR( module, page_mask );
1685 server_enter_uninterrupted_section( &csVirtual, &sigset );
1686 status = create_view( &view, base, size, SEC_IMAGE | SEC_FILE | VPROT_SYSTEM |
1687 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1688 if (!status)
1690 TRACE( "created %p-%p\n", base, (char *)base + size );
1692 /* The PE header is always read-only, no write, no execute. */
1693 set_page_vprot( base, page_size, VPROT_COMMITTED | VPROT_READ );
1695 sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
1696 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1698 BYTE flags = VPROT_COMMITTED;
1700 if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
1701 if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
1702 if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
1703 set_page_vprot( (char *)base + sec[i].VirtualAddress, sec[i].Misc.VirtualSize, flags );
1705 VIRTUAL_DEBUG_DUMP_VIEW( view );
1707 server_leave_uninterrupted_section( &csVirtual, &sigset );
1708 return status;
1712 /***********************************************************************
1713 * virtual_alloc_thread_stack
1715 NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1717 struct file_view *view;
1718 NTSTATUS status;
1719 sigset_t sigset;
1720 SIZE_T size;
1722 if (!reserve_size || !commit_size)
1724 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1725 if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
1726 if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1729 size = max( reserve_size, commit_size );
1730 if (size < 1024 * 1024) size = 1024 * 1024; /* Xlib needs a large stack */
1731 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1733 server_enter_uninterrupted_section( &csVirtual, &sigset );
1735 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1736 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED )) != STATUS_SUCCESS)
1737 goto done;
1739 #ifdef VALGRIND_STACK_REGISTER
1740 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1741 #endif
1743 /* setup no access guard page */
1744 set_page_vprot( view->base, page_size, VPROT_COMMITTED );
1745 set_page_vprot( (char *)view->base + page_size, page_size,
1746 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1747 mprotect_range( view->base, 2 * page_size, 0, 0 );
1748 VIRTUAL_DEBUG_DUMP_VIEW( view );
1750 /* note: limit is lower than base since the stack grows down */
1751 teb->DeallocationStack = view->base;
1752 teb->Tib.StackBase = (char *)view->base + view->size;
1753 teb->Tib.StackLimit = (char *)view->base + 2 * page_size;
1754 done:
1755 server_leave_uninterrupted_section( &csVirtual, &sigset );
1756 return status;
1760 /***********************************************************************
1761 * virtual_clear_thread_stack
1763 * Clear the stack contents before calling the main entry point, some broken apps need that.
1765 void virtual_clear_thread_stack(void)
1767 void *stack = NtCurrentTeb()->Tib.StackLimit;
1768 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1770 wine_anon_mmap( stack, size - page_size, PROT_READ | PROT_WRITE, MAP_FIXED );
1771 if (force_exec_prot) mprotect( stack, size - page_size, PROT_READ | PROT_WRITE | PROT_EXEC );
1775 /***********************************************************************
1776 * virtual_handle_fault
1778 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err, BOOL on_signal_stack )
1780 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1781 void *page = ROUND_ADDR( addr, page_mask );
1782 sigset_t sigset;
1783 BYTE vprot;
1785 server_enter_uninterrupted_section( &csVirtual, &sigset );
1786 vprot = get_page_vprot( page );
1787 if (!on_signal_stack && (vprot & VPROT_GUARD))
1789 set_page_vprot_bits( page, page_size, 0, VPROT_GUARD );
1790 mprotect_range( page, page_size, 0, 0 );
1791 ret = STATUS_GUARD_PAGE_VIOLATION;
1793 else if (err & EXCEPTION_WRITE_FAULT)
1795 if (vprot & VPROT_WRITEWATCH)
1797 set_page_vprot_bits( page, page_size, 0, VPROT_WRITEWATCH );
1798 mprotect_range( page, page_size, 0, 0 );
1800 /* ignore fault if page is writable now */
1801 if (VIRTUAL_GetUnixProt( get_page_vprot( page )) & PROT_WRITE)
1803 if ((vprot & VPROT_WRITEWATCH) || is_write_watch_range( page, page_size ))
1804 ret = STATUS_SUCCESS;
1807 server_leave_uninterrupted_section( &csVirtual, &sigset );
1808 return ret;
1812 /***********************************************************************
1813 * check_write_access
1815 * Check if the memory range is writable, temporarily disabling write watches if necessary.
1817 static NTSTATUS check_write_access( void *base, size_t size, BOOL *has_write_watch )
1819 size_t i;
1820 char *addr = ROUND_ADDR( base, page_mask );
1822 size = ROUND_SIZE( base, size );
1823 for (i = 0; i < size; i += page_size)
1825 BYTE vprot = get_page_vprot( addr + i );
1826 if (vprot & VPROT_WRITEWATCH) *has_write_watch = TRUE;
1827 if (!(VIRTUAL_GetUnixProt( vprot & ~VPROT_WRITEWATCH ) & PROT_WRITE))
1828 return STATUS_INVALID_USER_BUFFER;
1830 if (*has_write_watch)
1831 mprotect_range( addr, size, 0, VPROT_WRITEWATCH ); /* temporarily enable write access */
1832 return STATUS_SUCCESS;
1836 /***********************************************************************
1837 * virtual_locked_server_call
1839 unsigned int virtual_locked_server_call( void *req_ptr )
1841 struct __server_request_info * const req = req_ptr;
1842 sigset_t sigset;
1843 void *addr = req->reply_data;
1844 data_size_t size = req->u.req.request_header.reply_size;
1845 BOOL has_write_watch = FALSE;
1846 unsigned int ret = STATUS_ACCESS_VIOLATION;
1848 if (!size) return wine_server_call( req_ptr );
1850 server_enter_uninterrupted_section( &csVirtual, &sigset );
1851 if (!(ret = check_write_access( addr, size, &has_write_watch )))
1853 ret = server_call_unlocked( req );
1854 if (has_write_watch) update_write_watches( addr, size, wine_server_reply_size( req ));
1856 server_leave_uninterrupted_section( &csVirtual, &sigset );
1857 return ret;
1861 /***********************************************************************
1862 * virtual_locked_read
1864 ssize_t virtual_locked_read( int fd, void *addr, size_t size )
1866 sigset_t sigset;
1867 BOOL has_write_watch = FALSE;
1868 int err = EFAULT;
1870 ssize_t ret = read( fd, addr, size );
1871 if (ret != -1 || errno != EFAULT) return ret;
1873 server_enter_uninterrupted_section( &csVirtual, &sigset );
1874 if (!check_write_access( addr, size, &has_write_watch ))
1876 ret = read( fd, addr, size );
1877 err = errno;
1878 if (has_write_watch) update_write_watches( addr, size, max( 0, ret ));
1880 server_leave_uninterrupted_section( &csVirtual, &sigset );
1881 errno = err;
1882 return ret;
1886 /***********************************************************************
1887 * virtual_locked_pread
1889 ssize_t virtual_locked_pread( int fd, void *addr, size_t size, off_t offset )
1891 sigset_t sigset;
1892 BOOL has_write_watch = FALSE;
1893 int err = EFAULT;
1895 ssize_t ret = pread( fd, addr, size, offset );
1896 if (ret != -1 || errno != EFAULT) return ret;
1898 server_enter_uninterrupted_section( &csVirtual, &sigset );
1899 if (!check_write_access( addr, size, &has_write_watch ))
1901 ret = pread( fd, addr, size, offset );
1902 err = errno;
1903 if (has_write_watch) update_write_watches( addr, size, max( 0, ret ));
1905 server_leave_uninterrupted_section( &csVirtual, &sigset );
1906 errno = err;
1907 return ret;
1911 /***********************************************************************
1912 * __wine_locked_recvmsg
1914 ssize_t CDECL __wine_locked_recvmsg( int fd, struct msghdr *hdr, int flags )
1916 sigset_t sigset;
1917 size_t i;
1918 BOOL has_write_watch = FALSE;
1919 int err = EFAULT;
1921 ssize_t ret = recvmsg( fd, hdr, flags );
1922 if (ret != -1 || errno != EFAULT) return ret;
1924 server_enter_uninterrupted_section( &csVirtual, &sigset );
1925 for (i = 0; i < hdr->msg_iovlen; i++)
1926 if (check_write_access( hdr->msg_iov[i].iov_base, hdr->msg_iov[i].iov_len, &has_write_watch ))
1927 break;
1928 if (i == hdr->msg_iovlen)
1930 ret = recvmsg( fd, hdr, flags );
1931 err = errno;
1933 if (has_write_watch)
1934 while (i--) update_write_watches( hdr->msg_iov[i].iov_base, hdr->msg_iov[i].iov_len, 0 );
1936 server_leave_uninterrupted_section( &csVirtual, &sigset );
1937 errno = err;
1938 return ret;
1942 /***********************************************************************
1943 * virtual_is_valid_code_address
1945 BOOL virtual_is_valid_code_address( const void *addr, SIZE_T size )
1947 struct file_view *view;
1948 BOOL ret = FALSE;
1949 sigset_t sigset;
1951 server_enter_uninterrupted_section( &csVirtual, &sigset );
1952 if ((view = VIRTUAL_FindView( addr, size )))
1953 ret = !(view->protect & VPROT_SYSTEM); /* system views are not visible to the app */
1954 server_leave_uninterrupted_section( &csVirtual, &sigset );
1955 return ret;
1959 /***********************************************************************
1960 * virtual_handle_stack_fault
1962 * Handle an access fault inside the current thread stack.
1963 * Called from inside a signal handler.
1965 BOOL virtual_handle_stack_fault( void *addr )
1967 BOOL ret = FALSE;
1969 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1970 if (get_page_vprot( addr ) & VPROT_GUARD)
1972 char *page = ROUND_ADDR( addr, page_mask );
1973 set_page_vprot_bits( page, page_size, 0, VPROT_GUARD );
1974 mprotect_range( page, page_size, 0, 0 );
1975 NtCurrentTeb()->Tib.StackLimit = page;
1976 if (page >= (char *)NtCurrentTeb()->DeallocationStack + 2*page_size)
1978 page -= page_size;
1979 set_page_vprot_bits( page, page_size, VPROT_COMMITTED | VPROT_GUARD, 0 );
1980 mprotect_range( page, page_size, 0, 0 );
1982 ret = TRUE;
1984 RtlLeaveCriticalSection( &csVirtual );
1985 return ret;
1989 /***********************************************************************
1990 * virtual_check_buffer_for_read
1992 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
1994 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
1996 if (!size) return TRUE;
1997 if (!ptr) return FALSE;
1999 __TRY
2001 volatile const char *p = ptr;
2002 char dummy __attribute__((unused));
2003 SIZE_T count = size;
2005 while (count > page_size)
2007 dummy = *p;
2008 p += page_size;
2009 count -= page_size;
2011 dummy = p[0];
2012 dummy = p[count - 1];
2014 __EXCEPT_PAGE_FAULT
2016 return FALSE;
2018 __ENDTRY
2019 return TRUE;
2023 /***********************************************************************
2024 * virtual_check_buffer_for_write
2026 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
2028 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
2030 if (!size) return TRUE;
2031 if (!ptr) return FALSE;
2033 __TRY
2035 volatile char *p = ptr;
2036 SIZE_T count = size;
2038 while (count > page_size)
2040 *p |= 0;
2041 p += page_size;
2042 count -= page_size;
2044 p[0] |= 0;
2045 p[count - 1] |= 0;
2047 __EXCEPT_PAGE_FAULT
2049 return FALSE;
2051 __ENDTRY
2052 return TRUE;
2056 /***********************************************************************
2057 * virtual_uninterrupted_read_memory
2059 * Similar to NtReadVirtualMemory, but without wineserver calls. Moreover
2060 * permissions are checked before accessing each page, to ensure that no
2061 * exceptions can happen.
2063 SIZE_T virtual_uninterrupted_read_memory( const void *addr, void *buffer, SIZE_T size )
2065 struct file_view *view;
2066 sigset_t sigset;
2067 SIZE_T bytes_read = 0;
2069 if (!size) return 0;
2071 server_enter_uninterrupted_section( &csVirtual, &sigset );
2072 if ((view = VIRTUAL_FindView( addr, size )))
2074 if (!(view->protect & VPROT_SYSTEM))
2076 char *page = ROUND_ADDR( addr, page_mask );
2078 while (bytes_read < size && (VIRTUAL_GetUnixProt( get_page_vprot( page )) & PROT_READ))
2080 SIZE_T block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
2081 memcpy( buffer, addr, block_size );
2083 addr = (const void *)((const char *)addr + block_size);
2084 buffer = (void *)((char *)buffer + block_size);
2085 bytes_read += block_size;
2086 page += page_size;
2090 server_leave_uninterrupted_section( &csVirtual, &sigset );
2091 return bytes_read;
2095 /***********************************************************************
2096 * virtual_uninterrupted_write_memory
2098 * Similar to NtWriteVirtualMemory, but without wineserver calls. Moreover
2099 * permissions are checked before accessing each page, to ensure that no
2100 * exceptions can happen.
2102 NTSTATUS virtual_uninterrupted_write_memory( void *addr, const void *buffer, SIZE_T size )
2104 BOOL has_write_watch = FALSE;
2105 sigset_t sigset;
2106 NTSTATUS ret;
2108 if (!size) return STATUS_SUCCESS;
2110 server_enter_uninterrupted_section( &csVirtual, &sigset );
2111 if (!(ret = check_write_access( addr, size, &has_write_watch )))
2113 memcpy( addr, buffer, size );
2114 if (has_write_watch) update_write_watches( addr, size, size );
2116 server_leave_uninterrupted_section( &csVirtual, &sigset );
2117 return ret;
2121 /***********************************************************************
2122 * VIRTUAL_SetForceExec
2124 * Whether to force exec prot on all views.
2126 void VIRTUAL_SetForceExec( BOOL enable )
2128 struct file_view *view;
2129 sigset_t sigset;
2131 server_enter_uninterrupted_section( &csVirtual, &sigset );
2132 if (!force_exec_prot != !enable) /* change all existing views */
2134 force_exec_prot = enable;
2136 WINE_RB_FOR_EACH_ENTRY( view, &views_tree, struct file_view, entry )
2138 /* file mappings are always accessible */
2139 BYTE commit = is_view_valloc( view ) ? 0 : VPROT_COMMITTED;
2141 mprotect_range( view->base, view->size, commit, 0 );
2144 server_leave_uninterrupted_section( &csVirtual, &sigset );
2147 struct free_range
2149 char *base;
2150 char *limit;
2153 /* free reserved areas above the limit; callback for wine_mmap_enum_reserved_areas */
2154 static int free_reserved_memory( void *base, size_t size, void *arg )
2156 struct free_range *range = arg;
2158 if ((char *)base >= range->limit) return 0;
2159 if ((char *)base + size <= range->base) return 0;
2160 if ((char *)base < range->base)
2162 size -= range->base - (char *)base;
2163 base = range->base;
2165 if ((char *)base + size > range->limit) size = range->limit - (char *)base;
2166 remove_reserved_area( base, size );
2167 return 1; /* stop enumeration since the list has changed */
2170 /***********************************************************************
2171 * virtual_release_address_space
2173 * Release some address space once we have loaded and initialized the app.
2175 void virtual_release_address_space(void)
2177 struct free_range range;
2178 sigset_t sigset;
2180 if (is_win64) return;
2182 server_enter_uninterrupted_section( &csVirtual, &sigset );
2184 range.base = (char *)0x82000000;
2185 range.limit = user_space_limit;
2187 if (range.limit > range.base)
2189 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
2191 else
2193 #ifndef __APPLE__ /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
2194 range.base = (char *)0x20000000;
2195 range.limit = (char *)0x7f000000;
2196 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
2197 #endif
2200 server_leave_uninterrupted_section( &csVirtual, &sigset );
2204 /***********************************************************************
2205 * virtual_set_large_address_space
2207 * Enable use of a large address space when allowed by the application.
2209 void virtual_set_large_address_space(void)
2211 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
2213 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE)) return;
2214 /* no large address space on win9x */
2215 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
2217 user_space_limit = working_set_limit = address_space_limit;
2221 /***********************************************************************
2222 * NtAllocateVirtualMemory (NTDLL.@)
2223 * ZwAllocateVirtualMemory (NTDLL.@)
2225 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
2226 SIZE_T *size_ptr, ULONG type, ULONG protect )
2228 void *base;
2229 unsigned int vprot;
2230 SIZE_T size = *size_ptr;
2231 SIZE_T mask = get_mask( zero_bits );
2232 NTSTATUS status = STATUS_SUCCESS;
2233 BOOL is_dos_memory = FALSE;
2234 struct file_view *view;
2235 sigset_t sigset;
2237 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
2239 if (!size) return STATUS_INVALID_PARAMETER;
2240 if (!mask) return STATUS_INVALID_PARAMETER_3;
2242 if (process != NtCurrentProcess())
2244 apc_call_t call;
2245 apc_result_t result;
2247 memset( &call, 0, sizeof(call) );
2249 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
2250 call.virtual_alloc.addr = wine_server_client_ptr( *ret );
2251 call.virtual_alloc.size = *size_ptr;
2252 call.virtual_alloc.zero_bits = zero_bits;
2253 call.virtual_alloc.op_type = type;
2254 call.virtual_alloc.prot = protect;
2255 status = server_queue_process_apc( process, &call, &result );
2256 if (status != STATUS_SUCCESS) return status;
2258 if (result.virtual_alloc.status == STATUS_SUCCESS)
2260 *ret = wine_server_get_ptr( result.virtual_alloc.addr );
2261 *size_ptr = result.virtual_alloc.size;
2263 return result.virtual_alloc.status;
2266 /* Round parameters to a page boundary */
2268 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2270 if (*ret)
2272 if (type & MEM_RESERVE) /* Round down to 64k boundary */
2273 base = ROUND_ADDR( *ret, mask );
2274 else
2275 base = ROUND_ADDR( *ret, page_mask );
2276 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
2278 /* disallow low 64k, wrap-around and kernel space */
2279 if (((char *)base < (char *)0x10000) ||
2280 ((char *)base + size < (char *)base) ||
2281 is_beyond_limit( base, size, address_space_limit ))
2283 /* address 1 is magic to mean DOS area */
2284 if (!base && *ret == (void *)1 && size == 0x110000) is_dos_memory = TRUE;
2285 else return STATUS_INVALID_PARAMETER;
2288 else
2290 base = NULL;
2291 size = (size + page_mask) & ~page_mask;
2294 /* Compute the alloc type flags */
2296 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
2297 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
2299 WARN("called with wrong alloc type flags (%08x) !\n", type);
2300 return STATUS_INVALID_PARAMETER;
2303 /* Reserve the memory */
2305 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
2307 if ((type & MEM_RESERVE) || !base)
2309 if (!(status = get_vprot_flags( protect, &vprot, FALSE )))
2311 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
2312 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
2313 if (protect & PAGE_NOCACHE) vprot |= SEC_NOCACHE;
2315 if (vprot & VPROT_WRITECOPY) status = STATUS_INVALID_PAGE_PROTECTION;
2316 else if (is_dos_memory) status = allocate_dos_memory( &view, vprot );
2317 else status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
2319 if (status == STATUS_SUCCESS) base = view->base;
2322 else if (type & MEM_RESET)
2324 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
2325 else madvise( base, size, MADV_DONTNEED );
2327 else /* commit the pages */
2329 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
2330 else if (view->protect & SEC_FILE) status = STATUS_ALREADY_COMMITTED;
2331 else if (!(status = set_protection( view, base, size, protect )) && (view->protect & SEC_RESERVE))
2333 SERVER_START_REQ( add_mapping_committed_range )
2335 req->base = wine_server_client_ptr( view->base );
2336 req->offset = (char *)base - (char *)view->base;
2337 req->size = size;
2338 wine_server_call( req );
2340 SERVER_END_REQ;
2344 if (!status) VIRTUAL_DEBUG_DUMP_VIEW( view );
2346 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
2348 if (status == STATUS_SUCCESS)
2350 *ret = base;
2351 *size_ptr = size;
2353 return status;
2357 /***********************************************************************
2358 * NtFreeVirtualMemory (NTDLL.@)
2359 * ZwFreeVirtualMemory (NTDLL.@)
2361 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
2363 struct file_view *view;
2364 char *base;
2365 sigset_t sigset;
2366 NTSTATUS status = STATUS_SUCCESS;
2367 LPVOID addr = *addr_ptr;
2368 SIZE_T size = *size_ptr;
2370 TRACE("%p %p %08lx %x\n", process, addr, size, type );
2372 if (process != NtCurrentProcess())
2374 apc_call_t call;
2375 apc_result_t result;
2377 memset( &call, 0, sizeof(call) );
2379 call.virtual_free.type = APC_VIRTUAL_FREE;
2380 call.virtual_free.addr = wine_server_client_ptr( addr );
2381 call.virtual_free.size = size;
2382 call.virtual_free.op_type = type;
2383 status = server_queue_process_apc( process, &call, &result );
2384 if (status != STATUS_SUCCESS) return status;
2386 if (result.virtual_free.status == STATUS_SUCCESS)
2388 *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
2389 *size_ptr = result.virtual_free.size;
2391 return result.virtual_free.status;
2394 /* Fix the parameters */
2396 size = ROUND_SIZE( addr, size );
2397 base = ROUND_ADDR( addr, page_mask );
2399 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
2400 if (!base) return STATUS_INVALID_PARAMETER;
2402 server_enter_uninterrupted_section( &csVirtual, &sigset );
2404 if (!(view = VIRTUAL_FindView( base, size )) || !is_view_valloc( view ))
2406 status = STATUS_INVALID_PARAMETER;
2408 else if (type == MEM_RELEASE)
2410 /* Free the pages */
2412 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
2413 else
2415 delete_view( view );
2416 *addr_ptr = base;
2417 *size_ptr = size;
2420 else if (type == MEM_DECOMMIT)
2422 status = decommit_pages( view, base - (char *)view->base, size );
2423 if (status == STATUS_SUCCESS)
2425 *addr_ptr = base;
2426 *size_ptr = size;
2429 else
2431 WARN("called with wrong free type flags (%08x) !\n", type);
2432 status = STATUS_INVALID_PARAMETER;
2435 server_leave_uninterrupted_section( &csVirtual, &sigset );
2436 return status;
2440 /***********************************************************************
2441 * NtProtectVirtualMemory (NTDLL.@)
2442 * ZwProtectVirtualMemory (NTDLL.@)
2444 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
2445 ULONG new_prot, ULONG *old_prot )
2447 struct file_view *view;
2448 sigset_t sigset;
2449 NTSTATUS status = STATUS_SUCCESS;
2450 char *base;
2451 BYTE vprot;
2452 SIZE_T size = *size_ptr;
2453 LPVOID addr = *addr_ptr;
2454 DWORD old;
2456 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
2458 if (!old_prot)
2459 return STATUS_ACCESS_VIOLATION;
2461 if (process != NtCurrentProcess())
2463 apc_call_t call;
2464 apc_result_t result;
2466 memset( &call, 0, sizeof(call) );
2468 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
2469 call.virtual_protect.addr = wine_server_client_ptr( addr );
2470 call.virtual_protect.size = size;
2471 call.virtual_protect.prot = new_prot;
2472 status = server_queue_process_apc( process, &call, &result );
2473 if (status != STATUS_SUCCESS) return status;
2475 if (result.virtual_protect.status == STATUS_SUCCESS)
2477 *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
2478 *size_ptr = result.virtual_protect.size;
2479 if (old_prot) *old_prot = result.virtual_protect.prot;
2481 return result.virtual_protect.status;
2484 /* Fix the parameters */
2486 size = ROUND_SIZE( addr, size );
2487 base = ROUND_ADDR( addr, page_mask );
2489 server_enter_uninterrupted_section( &csVirtual, &sigset );
2491 if ((view = VIRTUAL_FindView( base, size )))
2493 /* Make sure all the pages are committed */
2494 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2496 old = VIRTUAL_GetWin32Prot( vprot, view->protect );
2497 status = set_protection( view, base, size, new_prot );
2499 else status = STATUS_NOT_COMMITTED;
2501 else status = STATUS_INVALID_PARAMETER;
2503 if (!status) VIRTUAL_DEBUG_DUMP_VIEW( view );
2505 server_leave_uninterrupted_section( &csVirtual, &sigset );
2507 if (status == STATUS_SUCCESS)
2509 *addr_ptr = base;
2510 *size_ptr = size;
2511 *old_prot = old;
2513 return status;
2517 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
2518 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
2520 MEMORY_BASIC_INFORMATION *info = arg;
2521 void *end = (char *)start + size;
2523 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
2525 if (info->BaseAddress >= end)
2527 if (info->AllocationBase < end) info->AllocationBase = end;
2528 return 0;
2531 if (info->BaseAddress >= start || start <= address_space_start)
2533 /* it's a real free area */
2534 info->State = MEM_FREE;
2535 info->Protect = PAGE_NOACCESS;
2536 info->AllocationBase = 0;
2537 info->AllocationProtect = 0;
2538 info->Type = 0;
2539 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
2540 info->RegionSize = (char *)end - (char *)info->BaseAddress;
2542 else /* outside of the reserved area, pretend it's allocated */
2544 info->RegionSize = (char *)start - (char *)info->BaseAddress;
2545 info->State = MEM_RESERVE;
2546 info->Protect = PAGE_NOACCESS;
2547 info->AllocationProtect = PAGE_NOACCESS;
2548 info->Type = MEM_PRIVATE;
2550 return 1;
2553 #define UNIMPLEMENTED_INFO_CLASS(c) \
2554 case c: \
2555 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
2556 return STATUS_INVALID_INFO_CLASS
2558 /***********************************************************************
2559 * NtQueryVirtualMemory (NTDLL.@)
2560 * ZwQueryVirtualMemory (NTDLL.@)
2562 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
2563 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2564 SIZE_T len, SIZE_T *res_len )
2566 struct file_view *view;
2567 char *base, *alloc_base = 0, *alloc_end = working_set_limit;
2568 struct wine_rb_entry *ptr;
2569 MEMORY_BASIC_INFORMATION *info = buffer;
2570 sigset_t sigset;
2572 if (info_class != MemoryBasicInformation)
2574 switch(info_class)
2576 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
2577 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
2578 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
2580 default:
2581 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
2582 process, addr, info_class, buffer, len, res_len);
2583 return STATUS_INVALID_INFO_CLASS;
2587 if (process != NtCurrentProcess())
2589 NTSTATUS status;
2590 apc_call_t call;
2591 apc_result_t result;
2593 memset( &call, 0, sizeof(call) );
2595 call.virtual_query.type = APC_VIRTUAL_QUERY;
2596 call.virtual_query.addr = wine_server_client_ptr( addr );
2597 status = server_queue_process_apc( process, &call, &result );
2598 if (status != STATUS_SUCCESS) return status;
2600 if (result.virtual_query.status == STATUS_SUCCESS)
2602 info->BaseAddress = wine_server_get_ptr( result.virtual_query.base );
2603 info->AllocationBase = wine_server_get_ptr( result.virtual_query.alloc_base );
2604 info->RegionSize = result.virtual_query.size;
2605 info->Protect = result.virtual_query.prot;
2606 info->AllocationProtect = result.virtual_query.alloc_prot;
2607 info->State = (DWORD)result.virtual_query.state << 12;
2608 info->Type = (DWORD)result.virtual_query.alloc_type << 16;
2609 if (info->RegionSize != result.virtual_query.size) /* truncated */
2610 return STATUS_INVALID_PARAMETER; /* FIXME */
2611 if (res_len) *res_len = sizeof(*info);
2613 return result.virtual_query.status;
2616 base = ROUND_ADDR( addr, page_mask );
2618 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2620 /* Find the view containing the address */
2622 server_enter_uninterrupted_section( &csVirtual, &sigset );
2623 ptr = views_tree.root;
2624 while (ptr)
2626 view = WINE_RB_ENTRY_VALUE( ptr, struct file_view, entry );
2627 if ((char *)view->base > base)
2629 alloc_end = view->base;
2630 ptr = ptr->left;
2632 else if ((char *)view->base + view->size <= base)
2634 alloc_base = (char *)view->base + view->size;
2635 ptr = ptr->right;
2637 else
2639 alloc_base = view->base;
2640 alloc_end = (char *)view->base + view->size;
2641 break;
2645 /* Fill the info structure */
2647 info->AllocationBase = alloc_base;
2648 info->BaseAddress = base;
2649 info->RegionSize = alloc_end - base;
2651 if (!ptr)
2653 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2655 /* not in a reserved area at all, pretend it's allocated */
2656 #ifdef __i386__
2657 if (base >= (char *)address_space_start)
2659 info->State = MEM_RESERVE;
2660 info->Protect = PAGE_NOACCESS;
2661 info->AllocationProtect = PAGE_NOACCESS;
2662 info->Type = MEM_PRIVATE;
2664 else
2665 #endif
2667 info->State = MEM_FREE;
2668 info->Protect = PAGE_NOACCESS;
2669 info->AllocationBase = 0;
2670 info->AllocationProtect = 0;
2671 info->Type = 0;
2675 else
2677 BYTE vprot;
2678 char *ptr;
2679 SIZE_T range_size = get_committed_size( view, base, &vprot );
2681 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2682 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot, view->protect ) : 0;
2683 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect, view->protect );
2684 if (view->protect & SEC_IMAGE) info->Type = MEM_IMAGE;
2685 else if (view->protect & (SEC_FILE | SEC_RESERVE | SEC_COMMIT)) info->Type = MEM_MAPPED;
2686 else info->Type = MEM_PRIVATE;
2687 for (ptr = base; ptr < base + range_size; ptr += page_size)
2688 if ((get_page_vprot( ptr ) ^ vprot) & ~VPROT_WRITEWATCH) break;
2689 info->RegionSize = ptr - base;
2691 server_leave_uninterrupted_section( &csVirtual, &sigset );
2693 if (res_len) *res_len = sizeof(*info);
2694 return STATUS_SUCCESS;
2698 /***********************************************************************
2699 * NtLockVirtualMemory (NTDLL.@)
2700 * ZwLockVirtualMemory (NTDLL.@)
2702 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2704 NTSTATUS status = STATUS_SUCCESS;
2706 if (process != NtCurrentProcess())
2708 apc_call_t call;
2709 apc_result_t result;
2711 memset( &call, 0, sizeof(call) );
2713 call.virtual_lock.type = APC_VIRTUAL_LOCK;
2714 call.virtual_lock.addr = wine_server_client_ptr( *addr );
2715 call.virtual_lock.size = *size;
2716 status = server_queue_process_apc( process, &call, &result );
2717 if (status != STATUS_SUCCESS) return status;
2719 if (result.virtual_lock.status == STATUS_SUCCESS)
2721 *addr = wine_server_get_ptr( result.virtual_lock.addr );
2722 *size = result.virtual_lock.size;
2724 return result.virtual_lock.status;
2727 *size = ROUND_SIZE( *addr, *size );
2728 *addr = ROUND_ADDR( *addr, page_mask );
2730 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2731 return status;
2735 /***********************************************************************
2736 * NtUnlockVirtualMemory (NTDLL.@)
2737 * ZwUnlockVirtualMemory (NTDLL.@)
2739 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2741 NTSTATUS status = STATUS_SUCCESS;
2743 if (process != NtCurrentProcess())
2745 apc_call_t call;
2746 apc_result_t result;
2748 memset( &call, 0, sizeof(call) );
2750 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2751 call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2752 call.virtual_unlock.size = *size;
2753 status = server_queue_process_apc( process, &call, &result );
2754 if (status != STATUS_SUCCESS) return status;
2756 if (result.virtual_unlock.status == STATUS_SUCCESS)
2758 *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2759 *size = result.virtual_unlock.size;
2761 return result.virtual_unlock.status;
2764 *size = ROUND_SIZE( *addr, *size );
2765 *addr = ROUND_ADDR( *addr, page_mask );
2767 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2768 return status;
2772 /***********************************************************************
2773 * NtCreateSection (NTDLL.@)
2774 * ZwCreateSection (NTDLL.@)
2776 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2777 const LARGE_INTEGER *size, ULONG protect,
2778 ULONG sec_flags, HANDLE file )
2780 NTSTATUS ret;
2781 unsigned int vprot, file_access = 0;
2782 data_size_t len;
2783 struct object_attributes *objattr;
2785 if ((ret = get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE ))) return ret;
2786 if ((ret = alloc_object_attributes( attr, &objattr, &len ))) return ret;
2788 if (vprot & VPROT_READ) file_access |= FILE_READ_DATA;
2789 if (vprot & VPROT_WRITE) file_access |= FILE_WRITE_DATA;
2791 SERVER_START_REQ( create_mapping )
2793 req->access = access;
2794 req->flags = sec_flags;
2795 req->file_handle = wine_server_obj_handle( file );
2796 req->file_access = file_access;
2797 req->size = size ? size->QuadPart : 0;
2798 wine_server_add_data( req, objattr, len );
2799 ret = wine_server_call( req );
2800 *handle = wine_server_ptr_handle( reply->handle );
2802 SERVER_END_REQ;
2804 RtlFreeHeap( GetProcessHeap(), 0, objattr );
2805 return ret;
2809 /***********************************************************************
2810 * NtOpenSection (NTDLL.@)
2811 * ZwOpenSection (NTDLL.@)
2813 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2815 NTSTATUS ret;
2817 if ((ret = validate_open_object_attributes( attr ))) return ret;
2819 SERVER_START_REQ( open_mapping )
2821 req->access = access;
2822 req->attributes = attr->Attributes;
2823 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2824 if (attr->ObjectName)
2825 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
2826 ret = wine_server_call( req );
2827 *handle = wine_server_ptr_handle( reply->handle );
2829 SERVER_END_REQ;
2830 return ret;
2834 /***********************************************************************
2835 * NtMapViewOfSection (NTDLL.@)
2836 * ZwMapViewOfSection (NTDLL.@)
2838 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2839 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2840 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2842 NTSTATUS res;
2843 mem_size_t full_size;
2844 ACCESS_MASK access;
2845 SIZE_T size, mask = get_mask( zero_bits );
2846 int unix_handle = -1, needs_close;
2847 unsigned int vprot, sec_flags;
2848 struct file_view *view;
2849 pe_image_info_t image_info;
2850 HANDLE shared_file;
2851 LARGE_INTEGER offset;
2852 sigset_t sigset;
2854 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2856 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2857 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2859 /* Check parameters */
2861 if ((*addr_ptr && zero_bits) || !mask)
2862 return STATUS_INVALID_PARAMETER_4;
2864 #ifndef _WIN64
2865 if (!is_wow64 && (alloc_type & AT_ROUND_TO_PAGE))
2867 *addr_ptr = ROUND_ADDR( *addr_ptr, page_mask );
2868 mask = page_mask;
2870 #endif
2872 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2873 return STATUS_MAPPED_ALIGNMENT;
2875 switch(protect)
2877 case PAGE_NOACCESS:
2878 case PAGE_READONLY:
2879 case PAGE_WRITECOPY:
2880 access = SECTION_MAP_READ;
2881 break;
2882 case PAGE_READWRITE:
2883 access = SECTION_MAP_WRITE;
2884 break;
2885 case PAGE_EXECUTE:
2886 case PAGE_EXECUTE_READ:
2887 case PAGE_EXECUTE_WRITECOPY:
2888 access = SECTION_MAP_READ | SECTION_MAP_EXECUTE;
2889 break;
2890 case PAGE_EXECUTE_READWRITE:
2891 access = SECTION_MAP_WRITE | SECTION_MAP_EXECUTE;
2892 break;
2893 default:
2894 return STATUS_INVALID_PAGE_PROTECTION;
2897 if (process != NtCurrentProcess())
2899 apc_call_t call;
2900 apc_result_t result;
2902 memset( &call, 0, sizeof(call) );
2904 call.map_view.type = APC_MAP_VIEW;
2905 call.map_view.handle = wine_server_obj_handle( handle );
2906 call.map_view.addr = wine_server_client_ptr( *addr_ptr );
2907 call.map_view.size = *size_ptr;
2908 call.map_view.offset = offset.QuadPart;
2909 call.map_view.zero_bits = zero_bits;
2910 call.map_view.alloc_type = alloc_type;
2911 call.map_view.prot = protect;
2912 res = server_queue_process_apc( process, &call, &result );
2913 if (res != STATUS_SUCCESS) return res;
2915 if ((NTSTATUS)result.map_view.status >= 0)
2917 *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2918 *size_ptr = result.map_view.size;
2920 return result.map_view.status;
2923 SERVER_START_REQ( get_mapping_info )
2925 req->handle = wine_server_obj_handle( handle );
2926 req->access = access;
2927 wine_server_set_reply( req, &image_info, sizeof(image_info) );
2928 res = wine_server_call( req );
2929 sec_flags = reply->flags;
2930 full_size = reply->size;
2931 shared_file = wine_server_ptr_handle( reply->shared_file );
2933 SERVER_END_REQ;
2934 if (res) return res;
2936 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2938 if (sec_flags & SEC_IMAGE)
2940 void *base = wine_server_get_ptr( image_info.base );
2942 if ((ULONG_PTR)base != image_info.base) base = NULL;
2943 size = image_info.map_size;
2944 if (size != image_info.map_size) /* truncated */
2946 WARN( "Modules larger than 4Gb (%s) not supported\n",
2947 wine_dbgstr_longlong(image_info.map_size) );
2948 res = STATUS_INVALID_PARAMETER;
2949 goto done;
2951 if (shared_file)
2953 int shared_fd, shared_needs_close;
2955 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2956 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2957 res = map_image( handle, access, unix_handle, base, size, mask, image_info.header_size,
2958 shared_fd, needs_close, addr_ptr );
2959 if (shared_needs_close) close( shared_fd );
2960 close_handle( shared_file );
2962 else
2964 res = map_image( handle, access, unix_handle, base, size, mask, image_info.header_size,
2965 -1, needs_close, addr_ptr );
2967 if (needs_close) close( unix_handle );
2968 if (res >= 0) *size_ptr = size;
2969 return res;
2972 res = STATUS_INVALID_PARAMETER;
2973 if (offset.QuadPart >= full_size) goto done;
2974 if (*size_ptr)
2976 size = *size_ptr;
2977 if (size > full_size - offset.QuadPart)
2979 res = STATUS_INVALID_VIEW_SIZE;
2980 goto done;
2983 else
2985 size = full_size - offset.QuadPart;
2986 if (size != full_size - offset.QuadPart) /* truncated */
2988 WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2989 wine_dbgstr_longlong(full_size) );
2990 goto done;
2993 if (!(size = ROUND_SIZE( 0, size ))) goto done; /* wrap-around */
2995 /* Reserve a properly aligned area */
2997 server_enter_uninterrupted_section( &csVirtual, &sigset );
2999 get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE );
3000 vprot |= sec_flags;
3001 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
3002 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
3003 if (res)
3005 server_leave_uninterrupted_section( &csVirtual, &sigset );
3006 goto done;
3009 /* Map the file */
3011 TRACE("handle=%p size=%lx offset=%x%08x\n",
3012 handle, size, offset.u.HighPart, offset.u.LowPart );
3014 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, needs_close );
3015 if (res == STATUS_SUCCESS)
3017 SERVER_START_REQ( map_view )
3019 req->mapping = wine_server_obj_handle( handle );
3020 req->access = access;
3021 req->base = wine_server_client_ptr( view->base );
3022 req->size = size;
3023 req->start = offset.QuadPart;
3024 res = wine_server_call( req );
3026 SERVER_END_REQ;
3029 if (res == STATUS_SUCCESS)
3031 *addr_ptr = view->base;
3032 *size_ptr = size;
3033 VIRTUAL_DEBUG_DUMP_VIEW( view );
3035 else
3037 ERR( "map_file_into_view %p %lx %x%08x failed\n",
3038 view->base, size, offset.u.HighPart, offset.u.LowPart );
3039 delete_view( view );
3042 server_leave_uninterrupted_section( &csVirtual, &sigset );
3044 done:
3045 if (needs_close) close( unix_handle );
3046 return res;
3050 /***********************************************************************
3051 * NtUnmapViewOfSection (NTDLL.@)
3052 * ZwUnmapViewOfSection (NTDLL.@)
3054 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
3056 struct file_view *view;
3057 NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
3058 sigset_t sigset;
3060 if (process != NtCurrentProcess())
3062 apc_call_t call;
3063 apc_result_t result;
3065 memset( &call, 0, sizeof(call) );
3067 call.unmap_view.type = APC_UNMAP_VIEW;
3068 call.unmap_view.addr = wine_server_client_ptr( addr );
3069 status = server_queue_process_apc( process, &call, &result );
3070 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
3071 return status;
3074 server_enter_uninterrupted_section( &csVirtual, &sigset );
3075 if ((view = VIRTUAL_FindView( addr, 0 )) && !is_view_valloc( view ))
3077 if (!(view->protect & VPROT_SYSTEM))
3079 SERVER_START_REQ( unmap_view )
3081 req->base = wine_server_client_ptr( view->base );
3082 status = wine_server_call( req );
3084 SERVER_END_REQ;
3085 if (!status) delete_view( view );
3086 else FIXME( "failed to unmap %p %x\n", view->base, status );
3088 else delete_view( view );
3090 server_leave_uninterrupted_section( &csVirtual, &sigset );
3091 return status;
3095 /******************************************************************************
3096 * NtQuerySection (NTDLL.@)
3097 * ZwQuerySection (NTDLL.@)
3099 NTSTATUS WINAPI NtQuerySection( HANDLE handle, SECTION_INFORMATION_CLASS class, void *ptr,
3100 ULONG size, ULONG *ret_size )
3102 NTSTATUS status;
3103 pe_image_info_t image_info;
3105 switch (class)
3107 case SectionBasicInformation:
3108 if (size < sizeof(SECTION_BASIC_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
3109 break;
3110 case SectionImageInformation:
3111 if (size < sizeof(SECTION_IMAGE_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
3112 break;
3113 default:
3114 FIXME( "class %u not implemented\n", class );
3115 return STATUS_NOT_IMPLEMENTED;
3117 if (!ptr) return STATUS_ACCESS_VIOLATION;
3119 SERVER_START_REQ( get_mapping_info )
3121 req->handle = wine_server_obj_handle( handle );
3122 req->access = SECTION_QUERY;
3123 wine_server_set_reply( req, &image_info, sizeof(image_info) );
3124 if (!(status = wine_server_call( req )))
3126 if (class == SectionBasicInformation)
3128 SECTION_BASIC_INFORMATION *info = ptr;
3129 info->Attributes = reply->flags;
3130 info->BaseAddress = NULL;
3131 info->Size.QuadPart = reply->size;
3132 if (ret_size) *ret_size = sizeof(*info);
3134 else if (reply->flags & SEC_IMAGE)
3136 SECTION_IMAGE_INFORMATION *info = ptr;
3137 info->TransferAddress = wine_server_get_ptr( image_info.entry_point );
3138 info->ZeroBits = image_info.zerobits;
3139 info->MaximumStackSize = image_info.stack_size;
3140 info->CommittedStackSize = image_info.stack_commit;
3141 info->SubSystemType = image_info.subsystem;
3142 info->SubsystemVersionLow = image_info.subsystem_low;
3143 info->SubsystemVersionHigh = image_info.subsystem_high;
3144 info->GpValue = image_info.gp;
3145 info->ImageCharacteristics = image_info.image_charact;
3146 info->DllCharacteristics = image_info.dll_charact;
3147 info->Machine = image_info.machine;
3148 info->ImageContainsCode = image_info.contains_code;
3149 info->ImageFlags = image_info.image_flags;
3150 info->LoaderFlags = image_info.loader_flags;
3151 info->ImageFileSize = image_info.file_size;
3152 info->CheckSum = image_info.checksum;
3153 if (ret_size) *ret_size = sizeof(*info);
3155 else status = STATUS_SECTION_NOT_IMAGE;
3158 SERVER_END_REQ;
3160 return status;
3164 /***********************************************************************
3165 * NtFlushVirtualMemory (NTDLL.@)
3166 * ZwFlushVirtualMemory (NTDLL.@)
3168 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
3169 SIZE_T *size_ptr, ULONG unknown )
3171 struct file_view *view;
3172 NTSTATUS status = STATUS_SUCCESS;
3173 sigset_t sigset;
3174 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
3176 if (process != NtCurrentProcess())
3178 apc_call_t call;
3179 apc_result_t result;
3181 memset( &call, 0, sizeof(call) );
3183 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
3184 call.virtual_flush.addr = wine_server_client_ptr( addr );
3185 call.virtual_flush.size = *size_ptr;
3186 status = server_queue_process_apc( process, &call, &result );
3187 if (status != STATUS_SUCCESS) return status;
3189 if (result.virtual_flush.status == STATUS_SUCCESS)
3191 *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
3192 *size_ptr = result.virtual_flush.size;
3194 return result.virtual_flush.status;
3197 server_enter_uninterrupted_section( &csVirtual, &sigset );
3198 if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
3199 else
3201 if (!*size_ptr) *size_ptr = view->size;
3202 *addr_ptr = addr;
3203 #ifdef MS_ASYNC
3204 if (msync( addr, *size_ptr, MS_ASYNC )) status = STATUS_NOT_MAPPED_DATA;
3205 #endif
3207 server_leave_uninterrupted_section( &csVirtual, &sigset );
3208 return status;
3212 /***********************************************************************
3213 * NtGetWriteWatch (NTDLL.@)
3214 * ZwGetWriteWatch (NTDLL.@)
3216 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
3217 ULONG_PTR *count, ULONG *granularity )
3219 NTSTATUS status = STATUS_SUCCESS;
3220 sigset_t sigset;
3222 size = ROUND_SIZE( base, size );
3223 base = ROUND_ADDR( base, page_mask );
3225 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
3226 if (!*count || !size) return STATUS_INVALID_PARAMETER;
3227 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
3229 if (!addresses) return STATUS_ACCESS_VIOLATION;
3231 TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
3232 addresses, *count );
3234 server_enter_uninterrupted_section( &csVirtual, &sigset );
3236 if (is_write_watch_range( base, size ))
3238 ULONG_PTR pos = 0;
3239 char *addr = base;
3240 char *end = addr + size;
3242 while (pos < *count && addr < end)
3244 if (!(get_page_vprot( addr ) & VPROT_WRITEWATCH)) addresses[pos++] = addr;
3245 addr += page_size;
3247 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( base, addr - (char *)base );
3248 *count = pos;
3249 *granularity = page_size;
3251 else status = STATUS_INVALID_PARAMETER;
3253 server_leave_uninterrupted_section( &csVirtual, &sigset );
3254 return status;
3258 /***********************************************************************
3259 * NtResetWriteWatch (NTDLL.@)
3260 * ZwResetWriteWatch (NTDLL.@)
3262 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
3264 NTSTATUS status = STATUS_SUCCESS;
3265 sigset_t sigset;
3267 size = ROUND_SIZE( base, size );
3268 base = ROUND_ADDR( base, page_mask );
3270 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
3272 if (!size) return STATUS_INVALID_PARAMETER;
3274 server_enter_uninterrupted_section( &csVirtual, &sigset );
3276 if (is_write_watch_range( base, size ))
3277 reset_write_watches( base, size );
3278 else
3279 status = STATUS_INVALID_PARAMETER;
3281 server_leave_uninterrupted_section( &csVirtual, &sigset );
3282 return status;
3286 /***********************************************************************
3287 * NtReadVirtualMemory (NTDLL.@)
3288 * ZwReadVirtualMemory (NTDLL.@)
3290 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
3291 SIZE_T size, SIZE_T *bytes_read )
3293 NTSTATUS status;
3295 if (virtual_check_buffer_for_write( buffer, size ))
3297 SERVER_START_REQ( read_process_memory )
3299 req->handle = wine_server_obj_handle( process );
3300 req->addr = wine_server_client_ptr( addr );
3301 wine_server_set_reply( req, buffer, size );
3302 if ((status = wine_server_call( req ))) size = 0;
3304 SERVER_END_REQ;
3306 else
3308 status = STATUS_ACCESS_VIOLATION;
3309 size = 0;
3311 if (bytes_read) *bytes_read = size;
3312 return status;
3316 /***********************************************************************
3317 * NtWriteVirtualMemory (NTDLL.@)
3318 * ZwWriteVirtualMemory (NTDLL.@)
3320 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
3321 SIZE_T size, SIZE_T *bytes_written )
3323 NTSTATUS status;
3325 if (virtual_check_buffer_for_read( buffer, size ))
3327 SERVER_START_REQ( write_process_memory )
3329 req->handle = wine_server_obj_handle( process );
3330 req->addr = wine_server_client_ptr( addr );
3331 wine_server_add_data( req, buffer, size );
3332 if ((status = wine_server_call( req ))) size = 0;
3334 SERVER_END_REQ;
3336 else
3338 status = STATUS_PARTIAL_COPY;
3339 size = 0;
3341 if (bytes_written) *bytes_written = size;
3342 return status;
3346 /***********************************************************************
3347 * NtAreMappedFilesTheSame (NTDLL.@)
3348 * ZwAreMappedFilesTheSame (NTDLL.@)
3350 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
3352 struct file_view *view1, *view2;
3353 NTSTATUS status;
3354 sigset_t sigset;
3356 TRACE("%p %p\n", addr1, addr2);
3358 server_enter_uninterrupted_section( &csVirtual, &sigset );
3360 view1 = VIRTUAL_FindView( addr1, 0 );
3361 view2 = VIRTUAL_FindView( addr2, 0 );
3363 if (!view1 || !view2)
3364 status = STATUS_INVALID_ADDRESS;
3365 else if (is_view_valloc( view1 ) || is_view_valloc( view2 ))
3366 status = STATUS_CONFLICTING_ADDRESSES;
3367 else if (view1 == view2)
3368 status = STATUS_SUCCESS;
3369 else if ((view1->protect & VPROT_SYSTEM) || (view2->protect & VPROT_SYSTEM))
3370 status = STATUS_NOT_SAME_DEVICE;
3371 else
3373 SERVER_START_REQ( is_same_mapping )
3375 req->base1 = wine_server_client_ptr( view1->base );
3376 req->base2 = wine_server_client_ptr( view2->base );
3377 status = wine_server_call( req );
3379 SERVER_END_REQ;
3382 server_leave_uninterrupted_section( &csVirtual, &sigset );
3383 return status;