server: Implement NtAreMappedFilesTheSame functionality on the server side.
[wine.git] / dlls / ntdll / virtual.c
blobc2492d9faac9b87487a9c91eed0a9e6565cfc714
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_STAT_H
36 # include <sys/stat.h>
37 #endif
38 #ifdef HAVE_SYS_MMAN_H
39 # include <sys/mman.h>
40 #endif
41 #ifdef HAVE_SYS_SYSINFO_H
42 # include <sys/sysinfo.h>
43 #endif
44 #ifdef HAVE_VALGRIND_VALGRIND_H
45 # include <valgrind/valgrind.h>
46 #endif
48 #include "ntstatus.h"
49 #define WIN32_NO_STATUS
50 #define NONAMELESSUNION
51 #include "windef.h"
52 #include "winternl.h"
53 #include "wine/library.h"
54 #include "wine/server.h"
55 #include "wine/exception.h"
56 #include "wine/rbtree.h"
57 #include "wine/debug.h"
58 #include "ntdll_misc.h"
60 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
61 WINE_DECLARE_DEBUG_CHANNEL(module);
63 #ifndef MAP_NORESERVE
64 #define MAP_NORESERVE 0
65 #endif
67 /* File view */
68 struct file_view
70 struct wine_rb_entry entry; /* entry in global view tree */
71 void *base; /* base address */
72 size_t size; /* size in bytes */
73 HANDLE mapping; /* handle to the file mapping */
74 unsigned int protect; /* protection for all pages at allocation time and SEC_* flags */
77 /* per-page protection flags */
78 #define VPROT_READ 0x01
79 #define VPROT_WRITE 0x02
80 #define VPROT_EXEC 0x04
81 #define VPROT_WRITECOPY 0x08
82 #define VPROT_GUARD 0x10
83 #define VPROT_COMMITTED 0x20
84 #define VPROT_WRITEWATCH 0x40
85 /* per-mapping protection flags */
86 #define VPROT_SYSTEM 0x0200 /* system view (underlying mmap not under our control) */
88 /* Conversion from VPROT_* to Win32 flags */
89 static const BYTE VIRTUAL_Win32Flags[16] =
91 PAGE_NOACCESS, /* 0 */
92 PAGE_READONLY, /* READ */
93 PAGE_READWRITE, /* WRITE */
94 PAGE_READWRITE, /* READ | WRITE */
95 PAGE_EXECUTE, /* EXEC */
96 PAGE_EXECUTE_READ, /* READ | EXEC */
97 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
98 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
99 PAGE_WRITECOPY, /* WRITECOPY */
100 PAGE_WRITECOPY, /* READ | WRITECOPY */
101 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
102 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
103 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
104 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
105 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
106 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
109 static struct wine_rb_tree views_tree;
111 static RTL_CRITICAL_SECTION csVirtual;
112 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
114 0, 0, &csVirtual,
115 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
116 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
118 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
120 #ifdef __i386__
121 static const UINT page_shift = 12;
122 static const UINT_PTR page_mask = 0xfff;
123 /* Note: these are Windows limits, you cannot change them. */
124 static void *address_space_limit = (void *)0xc0000000; /* top of the total available address space */
125 static void *user_space_limit = (void *)0x7fff0000; /* top of the user address space */
126 static void *working_set_limit = (void *)0x7fff0000; /* top of the current working set */
127 static void *address_space_start = (void *)0x110000; /* keep DOS area clear */
128 #elif defined(__x86_64__)
129 static const UINT page_shift = 12;
130 static const UINT_PTR page_mask = 0xfff;
131 static void *address_space_limit = (void *)0x7fffffff0000;
132 static void *user_space_limit = (void *)0x7fffffff0000;
133 static void *working_set_limit = (void *)0x7fffffff0000;
134 static void *address_space_start = (void *)0x10000;
135 #else
136 UINT_PTR page_size = 0;
137 static UINT page_shift;
138 static UINT_PTR page_mask;
139 static void *address_space_limit;
140 static void *user_space_limit;
141 static void *working_set_limit;
142 static void *address_space_start = (void *)0x10000;
143 #endif /* __i386__ */
144 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
146 #define ROUND_ADDR(addr,mask) \
147 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
149 #define ROUND_SIZE(addr,size) \
150 (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
152 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
153 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
155 #ifdef _WIN64 /* on 64-bit the page protection bytes use a 2-level table */
156 static const size_t pages_vprot_shift = 20;
157 static const size_t pages_vprot_mask = (1 << 20) - 1;
158 static size_t pages_vprot_size;
159 static BYTE **pages_vprot;
160 #else /* on 32-bit we use a simple array with one byte per page */
161 static BYTE *pages_vprot;
162 #endif
164 static struct file_view *view_block_start, *view_block_end, *next_free_view;
165 static const size_t view_block_size = 0x100000;
166 static void *preload_reserve_start;
167 static void *preload_reserve_end;
168 static BOOL use_locks;
169 static BOOL force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
171 static inline int is_view_valloc( const struct file_view *view )
173 return !(view->protect & (SEC_FILE | SEC_RESERVE | SEC_COMMIT));
176 /***********************************************************************
177 * get_page_vprot
179 * Return the page protection byte.
181 static BYTE get_page_vprot( const void *addr )
183 size_t idx = (size_t)addr >> page_shift;
185 #ifdef _WIN64
186 if (!pages_vprot[idx >> pages_vprot_shift]) return 0;
187 return pages_vprot[idx >> pages_vprot_shift][idx & pages_vprot_mask];
188 #else
189 return pages_vprot[idx];
190 #endif
194 /***********************************************************************
195 * set_page_vprot
197 * Set a range of page protection bytes.
199 static void set_page_vprot( const void *addr, size_t size, BYTE vprot )
201 size_t idx = (size_t)addr >> page_shift;
202 size_t end = ((size_t)addr + size + page_mask) >> page_shift;
204 #ifdef _WIN64
205 while (idx >> pages_vprot_shift != end >> pages_vprot_shift)
207 size_t dir_size = pages_vprot_mask + 1 - (idx & pages_vprot_mask);
208 memset( pages_vprot[idx >> pages_vprot_shift] + (idx & pages_vprot_mask), vprot, dir_size );
209 idx += dir_size;
211 memset( pages_vprot[idx >> pages_vprot_shift] + (idx & pages_vprot_mask), vprot, end - idx );
212 #else
213 memset( pages_vprot + idx, vprot, end - idx );
214 #endif
218 /***********************************************************************
219 * set_page_vprot_bits
221 * Set or clear bits in a range of page protection bytes.
223 static void set_page_vprot_bits( const void *addr, size_t size, BYTE set, BYTE clear )
225 size_t idx = (size_t)addr >> page_shift;
226 size_t end = ((size_t)addr + size + page_mask) >> page_shift;
228 #ifdef _WIN64
229 for ( ; idx < end; idx++)
231 BYTE *ptr = pages_vprot[idx >> pages_vprot_shift] + (idx & pages_vprot_mask);
232 *ptr = (*ptr & ~clear) | set;
234 #else
235 for ( ; idx < end; idx++) pages_vprot[idx] = (pages_vprot[idx] & ~clear) | set;
236 #endif
240 /***********************************************************************
241 * alloc_pages_vprot
243 * Allocate the page protection bytes for a given range.
245 static BOOL alloc_pages_vprot( const void *addr, size_t size )
247 #ifdef _WIN64
248 size_t idx = (size_t)addr >> page_shift;
249 size_t end = ((size_t)addr + size + page_mask) >> page_shift;
250 size_t i;
251 void *ptr;
253 assert( end <= pages_vprot_size << pages_vprot_shift );
254 for (i = idx >> pages_vprot_shift; i < (end + pages_vprot_mask) >> pages_vprot_shift; i++)
256 if (pages_vprot[i]) continue;
257 if ((ptr = wine_anon_mmap( NULL, pages_vprot_mask + 1, PROT_READ | PROT_WRITE, 0 )) == (void *)-1)
258 return FALSE;
259 pages_vprot[i] = ptr;
261 #endif
262 return TRUE;
266 /***********************************************************************
267 * compare_view
269 * View comparison function used for the rb tree.
271 static int compare_view( const void *addr, const struct wine_rb_entry *entry )
273 struct file_view *view = WINE_RB_ENTRY_VALUE( entry, struct file_view, entry );
275 if (addr < view->base) return -1;
276 if (addr > view->base) return 1;
277 return 0;
281 /***********************************************************************
282 * VIRTUAL_GetProtStr
284 static const char *VIRTUAL_GetProtStr( BYTE prot )
286 static char buffer[6];
287 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
288 buffer[1] = (prot & VPROT_GUARD) ? 'g' : ((prot & VPROT_WRITEWATCH) ? 'H' : '-');
289 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
290 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
291 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
292 buffer[5] = 0;
293 return buffer;
297 /***********************************************************************
298 * VIRTUAL_GetUnixProt
300 * Convert page protections to protection for mmap/mprotect.
302 static int VIRTUAL_GetUnixProt( BYTE vprot )
304 int prot = 0;
305 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
307 if (vprot & VPROT_READ) prot |= PROT_READ;
308 if (vprot & VPROT_WRITE) prot |= PROT_WRITE | PROT_READ;
309 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE | PROT_READ;
310 if (vprot & VPROT_EXEC) prot |= PROT_EXEC | PROT_READ;
311 if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
313 if (!prot) prot = PROT_NONE;
314 return prot;
318 /***********************************************************************
319 * VIRTUAL_DumpView
321 static void VIRTUAL_DumpView( struct file_view *view )
323 UINT i, count;
324 char *addr = view->base;
325 BYTE prot = get_page_vprot( addr );
327 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
328 if (view->protect & VPROT_SYSTEM)
329 TRACE( " (builtin image)\n" );
330 else if (view->protect & SEC_IMAGE)
331 TRACE( " (image) %p\n", view->mapping );
332 else if (view->protect & SEC_FILE)
333 TRACE( " (file) %p\n", view->mapping );
334 else if (view->protect & (SEC_RESERVE | SEC_COMMIT))
335 TRACE( " (anonymous) %p\n", view->mapping );
336 else
337 TRACE( " (valloc)\n");
339 for (count = i = 1; i < view->size >> page_shift; i++, count++)
341 BYTE next = get_page_vprot( addr + (count << page_shift) );
342 if (next == prot) continue;
343 TRACE( " %p - %p %s\n",
344 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
345 addr += (count << page_shift);
346 prot = next;
347 count = 0;
349 if (count)
350 TRACE( " %p - %p %s\n",
351 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
355 /***********************************************************************
356 * VIRTUAL_Dump
358 #ifdef WINE_VM_DEBUG
359 static void VIRTUAL_Dump(void)
361 sigset_t sigset;
362 struct file_view *view;
364 TRACE( "Dump of all virtual memory views:\n" );
365 server_enter_uninterrupted_section( &csVirtual, &sigset );
366 WINE_RB_FOR_EACH_ENTRY( view, &views_tree, struct file_view, entry )
368 VIRTUAL_DumpView( view );
370 server_leave_uninterrupted_section( &csVirtual, &sigset );
372 #endif
375 /***********************************************************************
376 * VIRTUAL_FindView
378 * Find the view containing a given address. The csVirtual section must be held by caller.
380 * PARAMS
381 * addr [I] Address
383 * RETURNS
384 * View: Success
385 * NULL: Failure
387 static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
389 struct wine_rb_entry *ptr = views_tree.root;
391 if ((const char *)addr + size < (const char *)addr) return NULL; /* overflow */
393 while (ptr)
395 struct file_view *view = WINE_RB_ENTRY_VALUE( ptr, struct file_view, entry );
397 if (view->base > addr) ptr = ptr->left;
398 else if ((const char *)view->base + view->size <= (const char *)addr) ptr = ptr->right;
399 else if ((const char *)view->base + view->size < (const char *)addr + size) break; /* size too large */
400 else return view;
402 return NULL;
406 /***********************************************************************
407 * get_mask
409 static inline UINT_PTR get_mask( ULONG zero_bits )
411 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
412 if (zero_bits < page_shift) zero_bits = page_shift;
413 if (zero_bits > 21) return 0;
414 return (1 << zero_bits) - 1;
418 /***********************************************************************
419 * is_write_watch_range
421 static inline BOOL is_write_watch_range( const void *addr, size_t size )
423 struct file_view *view = VIRTUAL_FindView( addr, size );
424 return view && (view->protect & VPROT_WRITEWATCH);
428 /***********************************************************************
429 * find_view_range
431 * Find the first view overlapping at least part of the specified range.
432 * The csVirtual section must be held by caller.
434 static struct file_view *find_view_range( const void *addr, size_t size )
436 struct wine_rb_entry *ptr = views_tree.root;
438 while (ptr)
440 struct file_view *view = WINE_RB_ENTRY_VALUE( ptr, struct file_view, entry );
442 if ((const char *)view->base >= (const char *)addr + size) ptr = ptr->left;
443 else if ((const char *)view->base + view->size <= (const char *)addr) ptr = ptr->right;
444 else return view;
446 return NULL;
450 /***********************************************************************
451 * find_free_area
453 * Find a free area between views inside the specified range.
454 * The csVirtual section must be held by caller.
456 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
458 struct wine_rb_entry *first = NULL, *ptr = views_tree.root;
459 void *start;
461 /* find the first (resp. last) view inside the range */
462 while (ptr)
464 struct file_view *view = WINE_RB_ENTRY_VALUE( ptr, struct file_view, entry );
465 if ((char *)view->base + view->size >= (char *)end)
467 end = min( end, view->base );
468 ptr = ptr->left;
470 else if (view->base <= base)
472 base = max( (char *)base, (char *)view->base + view->size );
473 ptr = ptr->right;
475 else
477 first = ptr;
478 ptr = top_down ? ptr->right : ptr->left;
482 if (top_down)
484 start = ROUND_ADDR( (char *)end - size, mask );
485 if (start >= end || start < base) return NULL;
487 while (first)
489 struct file_view *view = WINE_RB_ENTRY_VALUE( first, struct file_view, entry );
491 if ((char *)view->base + view->size <= (char *)start) break;
492 start = ROUND_ADDR( (char *)view->base - size, mask );
493 /* stop if remaining space is not large enough */
494 if (!start || start >= end || start < base) return NULL;
495 first = wine_rb_prev( first );
498 else
500 start = ROUND_ADDR( (char *)base + mask, mask );
501 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
503 while (first)
505 struct file_view *view = WINE_RB_ENTRY_VALUE( first, struct file_view, entry );
507 if ((char *)view->base >= (char *)start + size) break;
508 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
509 /* stop if remaining space is not large enough */
510 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
511 first = wine_rb_next( first );
514 return start;
518 /***********************************************************************
519 * add_reserved_area
521 * Add a reserved area to the list maintained by libwine.
522 * The csVirtual section must be held by caller.
524 static void add_reserved_area( void *addr, size_t size )
526 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
528 if (addr < user_space_limit)
530 /* unmap the part of the area that is below the limit */
531 assert( (char *)addr + size > (char *)user_space_limit );
532 munmap( addr, (char *)user_space_limit - (char *)addr );
533 size -= (char *)user_space_limit - (char *)addr;
534 addr = user_space_limit;
536 /* blow away existing mappings */
537 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
538 wine_mmap_add_reserved_area( addr, size );
542 /***********************************************************************
543 * remove_reserved_area
545 * Remove a reserved area from the list maintained by libwine.
546 * The csVirtual section must be held by caller.
548 static void remove_reserved_area( void *addr, size_t size )
550 struct file_view *view;
552 TRACE( "removing %p-%p\n", addr, (char *)addr + size );
553 wine_mmap_remove_reserved_area( addr, size, 0 );
555 /* unmap areas not covered by an existing view */
556 WINE_RB_FOR_EACH_ENTRY( view, &views_tree, struct file_view, entry )
558 if ((char *)view->base >= (char *)addr + size) break;
559 if ((char *)view->base + view->size <= (char *)addr) continue;
560 if (view->base > addr) munmap( addr, (char *)view->base - (char *)addr );
561 if ((char *)view->base + view->size > (char *)addr + size) return;
562 size = (char *)addr + size - ((char *)view->base + view->size);
563 addr = (char *)view->base + view->size;
565 munmap( addr, size );
569 struct area_boundary
571 void *base;
572 size_t size;
573 void *boundary;
576 /***********************************************************************
577 * get_area_boundary_callback
579 * Get lowest boundary address between reserved area and non-reserved area
580 * in the specified region. If no boundaries are found, result is NULL.
581 * The csVirtual section must be held by caller.
583 static int get_area_boundary_callback( void *start, size_t size, void *arg )
585 struct area_boundary *area = arg;
586 void *end = (char *)start + size;
588 area->boundary = NULL;
589 if (area->base >= end) return 0;
590 if ((char *)start >= (char *)area->base + area->size) return 1;
591 if (area->base >= start)
593 if ((char *)area->base + area->size > (char *)end)
595 area->boundary = end;
596 return 1;
598 return 0;
600 area->boundary = start;
601 return 1;
605 /***********************************************************************
606 * is_beyond_limit
608 * Check if an address range goes beyond a given limit.
610 static inline BOOL is_beyond_limit( const void *addr, size_t size, const void *limit )
612 return (addr >= limit || (const char *)addr + size > (const char *)limit);
616 /***********************************************************************
617 * unmap_area
619 * Unmap an area, or simply replace it by an empty mapping if it is
620 * in a reserved area. The csVirtual section must be held by caller.
622 static inline void unmap_area( void *addr, size_t size )
624 switch (wine_mmap_is_in_reserved_area( addr, size ))
626 case -1: /* partially in a reserved area */
628 struct area_boundary area;
629 size_t lower_size;
630 area.base = addr;
631 area.size = size;
632 wine_mmap_enum_reserved_areas( get_area_boundary_callback, &area, 0 );
633 assert( area.boundary );
634 lower_size = (char *)area.boundary - (char *)addr;
635 unmap_area( addr, lower_size );
636 unmap_area( area.boundary, size - lower_size );
637 break;
639 case 1: /* in a reserved area */
640 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
641 break;
642 default:
643 case 0: /* not in a reserved area */
644 if (is_beyond_limit( addr, size, user_space_limit ))
645 add_reserved_area( addr, size );
646 else
647 munmap( addr, size );
648 break;
653 /***********************************************************************
654 * alloc_view
656 * Allocate a new view. The csVirtual section must be held by caller.
658 static struct file_view *alloc_view(void)
660 if (next_free_view)
662 struct file_view *ret = next_free_view;
663 next_free_view = *(struct file_view **)ret;
664 return ret;
666 if (view_block_start == view_block_end)
668 void *ptr = wine_anon_mmap( NULL, view_block_size, PROT_READ | PROT_WRITE, 0 );
669 if (ptr == (void *)-1) return NULL;
670 view_block_start = ptr;
671 view_block_end = view_block_start + view_block_size / sizeof(*view_block_start);
673 return view_block_start++;
677 /***********************************************************************
678 * delete_view
680 * Deletes a view. The csVirtual section must be held by caller.
682 static void delete_view( struct file_view *view ) /* [in] View */
684 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
685 set_page_vprot( view->base, view->size, 0 );
686 wine_rb_remove( &views_tree, &view->entry );
687 if (view->mapping) close_handle( view->mapping );
688 *(struct file_view **)view = next_free_view;
689 next_free_view = view;
693 /***********************************************************************
694 * create_view
696 * Create a view. The csVirtual section must be held by caller.
698 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
700 struct file_view *view;
701 int unix_prot = VIRTUAL_GetUnixProt( vprot );
703 assert( !((UINT_PTR)base & page_mask) );
704 assert( !(size & page_mask) );
706 /* Check for overlapping views. This can happen if the previous view
707 * was a system view that got unmapped behind our back. In that case
708 * we recover by simply deleting it. */
710 while ((view = find_view_range( base, size )))
712 TRACE( "overlapping view %p-%p for %p-%p\n",
713 view->base, (char *)view->base + view->size, base, (char *)base + size );
714 assert( view->protect & VPROT_SYSTEM );
715 delete_view( view );
718 if (!alloc_pages_vprot( base, size )) return STATUS_NO_MEMORY;
720 /* Create the view structure */
722 if (!(view = alloc_view()))
724 FIXME( "out of memory for %p-%p\n", base, (char *)base + size );
725 return STATUS_NO_MEMORY;
728 view->base = base;
729 view->size = size;
730 view->mapping = 0;
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, HANDLE dup_mapping, 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 !dup_mapping ) != 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 !dup_mapping ) != 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 !dup_mapping ) != 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:
1520 view->mapping = dup_mapping;
1522 SERVER_START_REQ( map_view )
1524 req->mapping = wine_server_obj_handle( hmapping );
1525 req->access = access;
1526 req->base = wine_server_client_ptr( view->base );
1527 req->size = view->size;
1528 req->start = 0;
1529 status = wine_server_call( req );
1531 SERVER_END_REQ;
1532 if (status) goto error;
1534 VIRTUAL_DEBUG_DUMP_VIEW( view );
1535 server_leave_uninterrupted_section( &csVirtual, &sigset );
1537 *addr_ptr = ptr;
1538 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1539 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, ptr - base);
1540 #endif
1541 if (ptr != base) return STATUS_IMAGE_NOT_AT_BASE;
1542 return STATUS_SUCCESS;
1544 error:
1545 if (view) delete_view( view );
1546 server_leave_uninterrupted_section( &csVirtual, &sigset );
1547 if (dup_mapping) close_handle( dup_mapping );
1548 return status;
1552 struct alloc_virtual_heap
1554 void *base;
1555 size_t size;
1558 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1559 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1561 struct alloc_virtual_heap *alloc = arg;
1563 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1564 if (size < alloc->size) return 0;
1565 if (is_win64 && base < (void *)0x80000000) return 0;
1566 alloc->base = wine_anon_mmap( (char *)base + size - alloc->size, alloc->size,
1567 PROT_READ|PROT_WRITE, MAP_FIXED );
1568 return (alloc->base != (void *)-1);
1571 /***********************************************************************
1572 * virtual_init
1574 void virtual_init(void)
1576 const char *preload;
1577 struct alloc_virtual_heap alloc_views;
1578 size_t size;
1580 #if !defined(__i386__) && !defined(__x86_64__)
1581 page_size = sysconf( _SC_PAGESIZE );
1582 page_mask = page_size - 1;
1583 /* Make sure we have a power of 2 */
1584 assert( !(page_size & page_mask) );
1585 page_shift = 0;
1586 while ((1 << page_shift) != page_size) page_shift++;
1587 #ifdef _WIN64
1588 address_space_limit = (void *)(((1UL << 47) - 1) & ~page_mask);
1589 #else
1590 address_space_limit = (void *)~page_mask;
1591 #endif
1592 user_space_limit = working_set_limit = address_space_limit;
1593 #endif
1594 if ((preload = getenv("WINEPRELOADRESERVE")))
1596 unsigned long start, end;
1597 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1599 preload_reserve_start = (void *)start;
1600 preload_reserve_end = (void *)end;
1604 /* try to find space in a reserved area for the views and pages protection table */
1605 #ifdef _WIN64
1606 pages_vprot_size = ((size_t)address_space_limit >> page_shift >> pages_vprot_shift) + 1;
1607 alloc_views.size = view_block_size + pages_vprot_size * sizeof(*pages_vprot);
1608 #else
1609 alloc_views.size = view_block_size + (1U << (32 - page_shift));
1610 #endif
1611 if (wine_mmap_enum_reserved_areas( alloc_virtual_heap, &alloc_views, 1 ))
1612 wine_mmap_remove_reserved_area( alloc_views.base, alloc_views.size, 0 );
1613 else
1614 alloc_views.base = wine_anon_mmap( NULL, alloc_views.size, PROT_READ | PROT_WRITE, 0 );
1616 assert( alloc_views.base != (void *)-1 );
1617 view_block_start = alloc_views.base;
1618 view_block_end = view_block_start + view_block_size / sizeof(*view_block_start);
1619 pages_vprot = (void *)((char *)alloc_views.base + view_block_size);
1620 wine_rb_init( &views_tree, compare_view );
1622 /* make the DOS area accessible (except the low 64K) to hide bugs in broken apps like Excel 2003 */
1623 size = (char *)address_space_start - (char *)0x10000;
1624 if (size && wine_mmap_is_in_reserved_area( (void*)0x10000, size ) == 1)
1625 wine_anon_mmap( (void *)0x10000, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1629 /***********************************************************************
1630 * virtual_init_threading
1632 void virtual_init_threading(void)
1634 use_locks = TRUE;
1638 /***********************************************************************
1639 * virtual_get_system_info
1641 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1643 #ifdef HAVE_SYSINFO
1644 struct sysinfo sinfo;
1645 #endif
1647 info->unknown = 0;
1648 info->KeMaximumIncrement = 0; /* FIXME */
1649 info->PageSize = page_size;
1650 info->MmLowestPhysicalPage = 1;
1651 info->MmHighestPhysicalPage = 0x7fffffff / page_size;
1652 #ifdef HAVE_SYSINFO
1653 if (!sysinfo(&sinfo))
1655 ULONG64 total = (ULONG64)sinfo.totalram * sinfo.mem_unit;
1656 info->MmHighestPhysicalPage = max(1, total / page_size);
1658 #endif
1659 info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
1660 info->AllocationGranularity = get_mask(0) + 1;
1661 info->LowestUserAddress = (void *)0x10000;
1662 info->HighestUserAddress = (char *)user_space_limit - 1;
1663 info->ActiveProcessorsAffinityMask = get_system_affinity_mask();
1664 info->NumberOfProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1668 /***********************************************************************
1669 * virtual_create_builtin_view
1671 NTSTATUS virtual_create_builtin_view( void *module )
1673 NTSTATUS status;
1674 sigset_t sigset;
1675 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1676 SIZE_T size = nt->OptionalHeader.SizeOfImage;
1677 IMAGE_SECTION_HEADER *sec;
1678 struct file_view *view;
1679 void *base;
1680 int i;
1682 size = ROUND_SIZE( module, size );
1683 base = ROUND_ADDR( module, page_mask );
1684 server_enter_uninterrupted_section( &csVirtual, &sigset );
1685 status = create_view( &view, base, size, SEC_IMAGE | SEC_FILE | VPROT_SYSTEM |
1686 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1687 if (!status)
1689 TRACE( "created %p-%p\n", base, (char *)base + size );
1691 /* The PE header is always read-only, no write, no execute. */
1692 set_page_vprot( base, page_size, VPROT_COMMITTED | VPROT_READ );
1694 sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
1695 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1697 BYTE flags = VPROT_COMMITTED;
1699 if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
1700 if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
1701 if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
1702 set_page_vprot( (char *)base + sec[i].VirtualAddress, sec[i].Misc.VirtualSize, flags );
1704 VIRTUAL_DEBUG_DUMP_VIEW( view );
1706 server_leave_uninterrupted_section( &csVirtual, &sigset );
1707 return status;
1711 /***********************************************************************
1712 * virtual_alloc_thread_stack
1714 NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1716 struct file_view *view;
1717 NTSTATUS status;
1718 sigset_t sigset;
1719 SIZE_T size;
1721 if (!reserve_size || !commit_size)
1723 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1724 if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
1725 if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1728 size = max( reserve_size, commit_size );
1729 if (size < 1024 * 1024) size = 1024 * 1024; /* Xlib needs a large stack */
1730 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1732 server_enter_uninterrupted_section( &csVirtual, &sigset );
1734 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1735 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED )) != STATUS_SUCCESS)
1736 goto done;
1738 #ifdef VALGRIND_STACK_REGISTER
1739 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1740 #endif
1742 /* setup no access guard page */
1743 set_page_vprot( view->base, page_size, VPROT_COMMITTED );
1744 set_page_vprot( (char *)view->base + page_size, page_size,
1745 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1746 mprotect_range( view->base, 2 * page_size, 0, 0 );
1747 VIRTUAL_DEBUG_DUMP_VIEW( view );
1749 /* note: limit is lower than base since the stack grows down */
1750 teb->DeallocationStack = view->base;
1751 teb->Tib.StackBase = (char *)view->base + view->size;
1752 teb->Tib.StackLimit = (char *)view->base + 2 * page_size;
1753 done:
1754 server_leave_uninterrupted_section( &csVirtual, &sigset );
1755 return status;
1759 /***********************************************************************
1760 * virtual_clear_thread_stack
1762 * Clear the stack contents before calling the main entry point, some broken apps need that.
1764 void virtual_clear_thread_stack(void)
1766 void *stack = NtCurrentTeb()->Tib.StackLimit;
1767 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1769 wine_anon_mmap( stack, size - page_size, PROT_READ | PROT_WRITE, MAP_FIXED );
1770 if (force_exec_prot) mprotect( stack, size - page_size, PROT_READ | PROT_WRITE | PROT_EXEC );
1774 /***********************************************************************
1775 * virtual_handle_fault
1777 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err, BOOL on_signal_stack )
1779 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1780 void *page = ROUND_ADDR( addr, page_mask );
1781 sigset_t sigset;
1782 BYTE vprot;
1784 server_enter_uninterrupted_section( &csVirtual, &sigset );
1785 vprot = get_page_vprot( page );
1786 if (!on_signal_stack && (vprot & VPROT_GUARD))
1788 set_page_vprot_bits( page, page_size, 0, VPROT_GUARD );
1789 mprotect_range( page, page_size, 0, 0 );
1790 ret = STATUS_GUARD_PAGE_VIOLATION;
1792 else if (err & EXCEPTION_WRITE_FAULT)
1794 if (vprot & VPROT_WRITEWATCH)
1796 set_page_vprot_bits( page, page_size, 0, VPROT_WRITEWATCH );
1797 mprotect_range( page, page_size, 0, 0 );
1799 /* ignore fault if page is writable now */
1800 if (VIRTUAL_GetUnixProt( get_page_vprot( page )) & PROT_WRITE)
1802 if ((vprot & VPROT_WRITEWATCH) || is_write_watch_range( page, page_size ))
1803 ret = STATUS_SUCCESS;
1806 server_leave_uninterrupted_section( &csVirtual, &sigset );
1807 return ret;
1811 /***********************************************************************
1812 * check_write_access
1814 * Check if the memory range is writable, temporarily disabling write watches if necessary.
1816 static NTSTATUS check_write_access( void *base, size_t size, BOOL *has_write_watch )
1818 size_t i;
1819 char *addr = ROUND_ADDR( base, page_mask );
1821 size = ROUND_SIZE( base, size );
1822 for (i = 0; i < size; i += page_size)
1824 BYTE vprot = get_page_vprot( addr + i );
1825 if (vprot & VPROT_WRITEWATCH) *has_write_watch = TRUE;
1826 if (!(VIRTUAL_GetUnixProt( vprot & ~VPROT_WRITEWATCH ) & PROT_WRITE))
1827 return STATUS_INVALID_USER_BUFFER;
1829 if (*has_write_watch)
1830 mprotect_range( addr, size, 0, VPROT_WRITEWATCH ); /* temporarily enable write access */
1831 return STATUS_SUCCESS;
1835 /***********************************************************************
1836 * virtual_locked_server_call
1838 unsigned int virtual_locked_server_call( void *req_ptr )
1840 struct __server_request_info * const req = req_ptr;
1841 sigset_t sigset;
1842 void *addr = req->reply_data;
1843 data_size_t size = req->u.req.request_header.reply_size;
1844 BOOL has_write_watch = FALSE;
1845 unsigned int ret = STATUS_ACCESS_VIOLATION;
1847 if (!size) return wine_server_call( req_ptr );
1849 server_enter_uninterrupted_section( &csVirtual, &sigset );
1850 if (!(ret = check_write_access( addr, size, &has_write_watch )))
1852 ret = server_call_unlocked( req );
1853 if (has_write_watch) update_write_watches( addr, size, wine_server_reply_size( req ));
1855 server_leave_uninterrupted_section( &csVirtual, &sigset );
1856 return ret;
1860 /***********************************************************************
1861 * virtual_locked_read
1863 ssize_t virtual_locked_read( int fd, void *addr, size_t size )
1865 sigset_t sigset;
1866 BOOL has_write_watch = FALSE;
1867 int err = EFAULT;
1869 ssize_t ret = read( fd, addr, size );
1870 if (ret != -1 || errno != EFAULT) return ret;
1872 server_enter_uninterrupted_section( &csVirtual, &sigset );
1873 if (!check_write_access( addr, size, &has_write_watch ))
1875 ret = read( fd, addr, size );
1876 err = errno;
1877 if (has_write_watch) update_write_watches( addr, size, max( 0, ret ));
1879 server_leave_uninterrupted_section( &csVirtual, &sigset );
1880 errno = err;
1881 return ret;
1885 /***********************************************************************
1886 * virtual_locked_pread
1888 ssize_t virtual_locked_pread( int fd, void *addr, size_t size, off_t offset )
1890 sigset_t sigset;
1891 BOOL has_write_watch = FALSE;
1892 int err = EFAULT;
1894 ssize_t ret = pread( fd, addr, size, offset );
1895 if (ret != -1 || errno != EFAULT) return ret;
1897 server_enter_uninterrupted_section( &csVirtual, &sigset );
1898 if (!check_write_access( addr, size, &has_write_watch ))
1900 ret = pread( fd, addr, size, offset );
1901 err = errno;
1902 if (has_write_watch) update_write_watches( addr, size, max( 0, ret ));
1904 server_leave_uninterrupted_section( &csVirtual, &sigset );
1905 errno = err;
1906 return ret;
1911 /***********************************************************************
1912 * virtual_is_valid_code_address
1914 BOOL virtual_is_valid_code_address( const void *addr, SIZE_T size )
1916 struct file_view *view;
1917 BOOL ret = FALSE;
1918 sigset_t sigset;
1920 server_enter_uninterrupted_section( &csVirtual, &sigset );
1921 if ((view = VIRTUAL_FindView( addr, size )))
1922 ret = !(view->protect & VPROT_SYSTEM); /* system views are not visible to the app */
1923 server_leave_uninterrupted_section( &csVirtual, &sigset );
1924 return ret;
1928 /***********************************************************************
1929 * virtual_handle_stack_fault
1931 * Handle an access fault inside the current thread stack.
1932 * Called from inside a signal handler.
1934 BOOL virtual_handle_stack_fault( void *addr )
1936 BOOL ret = FALSE;
1938 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1939 if (get_page_vprot( addr ) & VPROT_GUARD)
1941 char *page = ROUND_ADDR( addr, page_mask );
1942 set_page_vprot_bits( page, page_size, 0, VPROT_GUARD );
1943 mprotect_range( page, page_size, 0, 0 );
1944 NtCurrentTeb()->Tib.StackLimit = page;
1945 if (page >= (char *)NtCurrentTeb()->DeallocationStack + 2*page_size)
1947 page -= page_size;
1948 set_page_vprot_bits( page, page_size, VPROT_COMMITTED | VPROT_GUARD, 0 );
1949 mprotect_range( page, page_size, 0, 0 );
1951 ret = TRUE;
1953 RtlLeaveCriticalSection( &csVirtual );
1954 return ret;
1958 /***********************************************************************
1959 * virtual_check_buffer_for_read
1961 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
1963 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
1965 if (!size) return TRUE;
1966 if (!ptr) return FALSE;
1968 __TRY
1970 volatile const char *p = ptr;
1971 char dummy __attribute__((unused));
1972 SIZE_T count = size;
1974 while (count > page_size)
1976 dummy = *p;
1977 p += page_size;
1978 count -= page_size;
1980 dummy = p[0];
1981 dummy = p[count - 1];
1983 __EXCEPT_PAGE_FAULT
1985 return FALSE;
1987 __ENDTRY
1988 return TRUE;
1992 /***********************************************************************
1993 * virtual_check_buffer_for_write
1995 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
1997 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
1999 if (!size) return TRUE;
2000 if (!ptr) return FALSE;
2002 __TRY
2004 volatile char *p = ptr;
2005 SIZE_T count = size;
2007 while (count > page_size)
2009 *p |= 0;
2010 p += page_size;
2011 count -= page_size;
2013 p[0] |= 0;
2014 p[count - 1] |= 0;
2016 __EXCEPT_PAGE_FAULT
2018 return FALSE;
2020 __ENDTRY
2021 return TRUE;
2025 /***********************************************************************
2026 * virtual_uninterrupted_read_memory
2028 * Similar to NtReadVirtualMemory, but without wineserver calls. Moreover
2029 * permissions are checked before accessing each page, to ensure that no
2030 * exceptions can happen.
2032 SIZE_T virtual_uninterrupted_read_memory( const void *addr, void *buffer, SIZE_T size )
2034 struct file_view *view;
2035 sigset_t sigset;
2036 SIZE_T bytes_read = 0;
2038 if (!size) return 0;
2040 server_enter_uninterrupted_section( &csVirtual, &sigset );
2041 if ((view = VIRTUAL_FindView( addr, size )))
2043 if (!(view->protect & VPROT_SYSTEM))
2045 char *page = ROUND_ADDR( addr, page_mask );
2047 while (bytes_read < size && (VIRTUAL_GetUnixProt( get_page_vprot( page )) & PROT_READ))
2049 SIZE_T block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
2050 memcpy( buffer, addr, block_size );
2052 addr = (const void *)((const char *)addr + block_size);
2053 buffer = (void *)((char *)buffer + block_size);
2054 bytes_read += block_size;
2055 page += page_size;
2059 server_leave_uninterrupted_section( &csVirtual, &sigset );
2060 return bytes_read;
2064 /***********************************************************************
2065 * virtual_uninterrupted_write_memory
2067 * Similar to NtWriteVirtualMemory, but without wineserver calls. Moreover
2068 * permissions are checked before accessing each page, to ensure that no
2069 * exceptions can happen.
2071 NTSTATUS virtual_uninterrupted_write_memory( void *addr, const void *buffer, SIZE_T size )
2073 BOOL has_write_watch = FALSE;
2074 sigset_t sigset;
2075 NTSTATUS ret;
2077 if (!size) return STATUS_SUCCESS;
2079 server_enter_uninterrupted_section( &csVirtual, &sigset );
2080 if (!(ret = check_write_access( addr, size, &has_write_watch )))
2082 memcpy( addr, buffer, size );
2083 if (has_write_watch) update_write_watches( addr, size, size );
2085 server_leave_uninterrupted_section( &csVirtual, &sigset );
2086 return ret;
2090 /***********************************************************************
2091 * VIRTUAL_SetForceExec
2093 * Whether to force exec prot on all views.
2095 void VIRTUAL_SetForceExec( BOOL enable )
2097 struct file_view *view;
2098 sigset_t sigset;
2100 server_enter_uninterrupted_section( &csVirtual, &sigset );
2101 if (!force_exec_prot != !enable) /* change all existing views */
2103 force_exec_prot = enable;
2105 WINE_RB_FOR_EACH_ENTRY( view, &views_tree, struct file_view, entry )
2107 /* file mappings are always accessible */
2108 BYTE commit = is_view_valloc( view ) ? 0 : VPROT_COMMITTED;
2110 mprotect_range( view->base, view->size, commit, 0 );
2113 server_leave_uninterrupted_section( &csVirtual, &sigset );
2116 struct free_range
2118 char *base;
2119 char *limit;
2122 /* free reserved areas above the limit; callback for wine_mmap_enum_reserved_areas */
2123 static int free_reserved_memory( void *base, size_t size, void *arg )
2125 struct free_range *range = arg;
2127 if ((char *)base >= range->limit) return 0;
2128 if ((char *)base + size <= range->base) return 0;
2129 if ((char *)base < range->base)
2131 size -= range->base - (char *)base;
2132 base = range->base;
2134 if ((char *)base + size > range->limit) size = range->limit - (char *)base;
2135 remove_reserved_area( base, size );
2136 return 1; /* stop enumeration since the list has changed */
2139 /***********************************************************************
2140 * virtual_release_address_space
2142 * Release some address space once we have loaded and initialized the app.
2144 void virtual_release_address_space(void)
2146 struct free_range range;
2147 sigset_t sigset;
2149 if (is_win64) return;
2151 server_enter_uninterrupted_section( &csVirtual, &sigset );
2153 range.base = (char *)0x82000000;
2154 range.limit = user_space_limit;
2156 if (range.limit > range.base)
2158 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
2160 else
2162 #ifndef __APPLE__ /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
2163 range.base = (char *)0x20000000;
2164 range.limit = (char *)0x7f000000;
2165 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
2166 #endif
2169 server_leave_uninterrupted_section( &csVirtual, &sigset );
2173 /***********************************************************************
2174 * virtual_set_large_address_space
2176 * Enable use of a large address space when allowed by the application.
2178 void virtual_set_large_address_space(void)
2180 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
2182 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE)) return;
2183 /* no large address space on win9x */
2184 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
2186 user_space_limit = working_set_limit = address_space_limit;
2190 /***********************************************************************
2191 * NtAllocateVirtualMemory (NTDLL.@)
2192 * ZwAllocateVirtualMemory (NTDLL.@)
2194 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
2195 SIZE_T *size_ptr, ULONG type, ULONG protect )
2197 void *base;
2198 unsigned int vprot;
2199 SIZE_T size = *size_ptr;
2200 SIZE_T mask = get_mask( zero_bits );
2201 NTSTATUS status = STATUS_SUCCESS;
2202 BOOL is_dos_memory = FALSE;
2203 struct file_view *view;
2204 sigset_t sigset;
2206 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
2208 if (!size) return STATUS_INVALID_PARAMETER;
2209 if (!mask) return STATUS_INVALID_PARAMETER_3;
2211 if (process != NtCurrentProcess())
2213 apc_call_t call;
2214 apc_result_t result;
2216 memset( &call, 0, sizeof(call) );
2218 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
2219 call.virtual_alloc.addr = wine_server_client_ptr( *ret );
2220 call.virtual_alloc.size = *size_ptr;
2221 call.virtual_alloc.zero_bits = zero_bits;
2222 call.virtual_alloc.op_type = type;
2223 call.virtual_alloc.prot = protect;
2224 status = server_queue_process_apc( process, &call, &result );
2225 if (status != STATUS_SUCCESS) return status;
2227 if (result.virtual_alloc.status == STATUS_SUCCESS)
2229 *ret = wine_server_get_ptr( result.virtual_alloc.addr );
2230 *size_ptr = result.virtual_alloc.size;
2232 return result.virtual_alloc.status;
2235 /* Round parameters to a page boundary */
2237 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2239 if (*ret)
2241 if (type & MEM_RESERVE) /* Round down to 64k boundary */
2242 base = ROUND_ADDR( *ret, mask );
2243 else
2244 base = ROUND_ADDR( *ret, page_mask );
2245 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
2247 /* disallow low 64k, wrap-around and kernel space */
2248 if (((char *)base < (char *)0x10000) ||
2249 ((char *)base + size < (char *)base) ||
2250 is_beyond_limit( base, size, address_space_limit ))
2252 /* address 1 is magic to mean DOS area */
2253 if (!base && *ret == (void *)1 && size == 0x110000) is_dos_memory = TRUE;
2254 else return STATUS_INVALID_PARAMETER;
2257 else
2259 base = NULL;
2260 size = (size + page_mask) & ~page_mask;
2263 /* Compute the alloc type flags */
2265 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
2266 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
2268 WARN("called with wrong alloc type flags (%08x) !\n", type);
2269 return STATUS_INVALID_PARAMETER;
2272 /* Reserve the memory */
2274 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
2276 if ((type & MEM_RESERVE) || !base)
2278 if (!(status = get_vprot_flags( protect, &vprot, FALSE )))
2280 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
2281 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
2282 if (protect & PAGE_NOCACHE) vprot |= SEC_NOCACHE;
2284 if (vprot & VPROT_WRITECOPY) status = STATUS_INVALID_PAGE_PROTECTION;
2285 else if (is_dos_memory) status = allocate_dos_memory( &view, vprot );
2286 else status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
2288 if (status == STATUS_SUCCESS) base = view->base;
2291 else if (type & MEM_RESET)
2293 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
2294 else madvise( base, size, MADV_DONTNEED );
2296 else /* commit the pages */
2298 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
2299 else if (view->protect & SEC_FILE) status = STATUS_ALREADY_COMMITTED;
2300 else if (!(status = set_protection( view, base, size, protect )) && (view->protect & SEC_RESERVE))
2302 SERVER_START_REQ( add_mapping_committed_range )
2304 req->base = wine_server_client_ptr( view->base );
2305 req->offset = (char *)base - (char *)view->base;
2306 req->size = size;
2307 wine_server_call( req );
2309 SERVER_END_REQ;
2313 if (!status) VIRTUAL_DEBUG_DUMP_VIEW( view );
2315 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
2317 if (status == STATUS_SUCCESS)
2319 *ret = base;
2320 *size_ptr = size;
2322 return status;
2326 /***********************************************************************
2327 * NtFreeVirtualMemory (NTDLL.@)
2328 * ZwFreeVirtualMemory (NTDLL.@)
2330 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
2332 struct file_view *view;
2333 char *base;
2334 sigset_t sigset;
2335 NTSTATUS status = STATUS_SUCCESS;
2336 LPVOID addr = *addr_ptr;
2337 SIZE_T size = *size_ptr;
2339 TRACE("%p %p %08lx %x\n", process, addr, size, type );
2341 if (process != NtCurrentProcess())
2343 apc_call_t call;
2344 apc_result_t result;
2346 memset( &call, 0, sizeof(call) );
2348 call.virtual_free.type = APC_VIRTUAL_FREE;
2349 call.virtual_free.addr = wine_server_client_ptr( addr );
2350 call.virtual_free.size = size;
2351 call.virtual_free.op_type = type;
2352 status = server_queue_process_apc( process, &call, &result );
2353 if (status != STATUS_SUCCESS) return status;
2355 if (result.virtual_free.status == STATUS_SUCCESS)
2357 *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
2358 *size_ptr = result.virtual_free.size;
2360 return result.virtual_free.status;
2363 /* Fix the parameters */
2365 size = ROUND_SIZE( addr, size );
2366 base = ROUND_ADDR( addr, page_mask );
2368 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
2369 if (!base) return STATUS_INVALID_PARAMETER;
2371 server_enter_uninterrupted_section( &csVirtual, &sigset );
2373 if (!(view = VIRTUAL_FindView( base, size )) || !is_view_valloc( view ))
2375 status = STATUS_INVALID_PARAMETER;
2377 else if (type == MEM_RELEASE)
2379 /* Free the pages */
2381 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
2382 else
2384 delete_view( view );
2385 *addr_ptr = base;
2386 *size_ptr = size;
2389 else if (type == MEM_DECOMMIT)
2391 status = decommit_pages( view, base - (char *)view->base, size );
2392 if (status == STATUS_SUCCESS)
2394 *addr_ptr = base;
2395 *size_ptr = size;
2398 else
2400 WARN("called with wrong free type flags (%08x) !\n", type);
2401 status = STATUS_INVALID_PARAMETER;
2404 server_leave_uninterrupted_section( &csVirtual, &sigset );
2405 return status;
2409 /***********************************************************************
2410 * NtProtectVirtualMemory (NTDLL.@)
2411 * ZwProtectVirtualMemory (NTDLL.@)
2413 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
2414 ULONG new_prot, ULONG *old_prot )
2416 struct file_view *view;
2417 sigset_t sigset;
2418 NTSTATUS status = STATUS_SUCCESS;
2419 char *base;
2420 BYTE vprot;
2421 SIZE_T size = *size_ptr;
2422 LPVOID addr = *addr_ptr;
2423 DWORD old;
2425 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
2427 if (!old_prot)
2428 return STATUS_ACCESS_VIOLATION;
2430 if (process != NtCurrentProcess())
2432 apc_call_t call;
2433 apc_result_t result;
2435 memset( &call, 0, sizeof(call) );
2437 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
2438 call.virtual_protect.addr = wine_server_client_ptr( addr );
2439 call.virtual_protect.size = size;
2440 call.virtual_protect.prot = new_prot;
2441 status = server_queue_process_apc( process, &call, &result );
2442 if (status != STATUS_SUCCESS) return status;
2444 if (result.virtual_protect.status == STATUS_SUCCESS)
2446 *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
2447 *size_ptr = result.virtual_protect.size;
2448 if (old_prot) *old_prot = result.virtual_protect.prot;
2450 return result.virtual_protect.status;
2453 /* Fix the parameters */
2455 size = ROUND_SIZE( addr, size );
2456 base = ROUND_ADDR( addr, page_mask );
2458 server_enter_uninterrupted_section( &csVirtual, &sigset );
2460 if ((view = VIRTUAL_FindView( base, size )))
2462 /* Make sure all the pages are committed */
2463 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2465 old = VIRTUAL_GetWin32Prot( vprot, view->protect );
2466 status = set_protection( view, base, size, new_prot );
2468 else status = STATUS_NOT_COMMITTED;
2470 else status = STATUS_INVALID_PARAMETER;
2472 if (!status) VIRTUAL_DEBUG_DUMP_VIEW( view );
2474 server_leave_uninterrupted_section( &csVirtual, &sigset );
2476 if (status == STATUS_SUCCESS)
2478 *addr_ptr = base;
2479 *size_ptr = size;
2480 *old_prot = old;
2482 return status;
2486 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
2487 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
2489 MEMORY_BASIC_INFORMATION *info = arg;
2490 void *end = (char *)start + size;
2492 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
2494 if (info->BaseAddress >= end)
2496 if (info->AllocationBase < end) info->AllocationBase = end;
2497 return 0;
2500 if (info->BaseAddress >= start || start <= address_space_start)
2502 /* it's a real free area */
2503 info->State = MEM_FREE;
2504 info->Protect = PAGE_NOACCESS;
2505 info->AllocationBase = 0;
2506 info->AllocationProtect = 0;
2507 info->Type = 0;
2508 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
2509 info->RegionSize = (char *)end - (char *)info->BaseAddress;
2511 else /* outside of the reserved area, pretend it's allocated */
2513 info->RegionSize = (char *)start - (char *)info->BaseAddress;
2514 info->State = MEM_RESERVE;
2515 info->Protect = PAGE_NOACCESS;
2516 info->AllocationProtect = PAGE_NOACCESS;
2517 info->Type = MEM_PRIVATE;
2519 return 1;
2522 #define UNIMPLEMENTED_INFO_CLASS(c) \
2523 case c: \
2524 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
2525 return STATUS_INVALID_INFO_CLASS
2527 /***********************************************************************
2528 * NtQueryVirtualMemory (NTDLL.@)
2529 * ZwQueryVirtualMemory (NTDLL.@)
2531 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
2532 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2533 SIZE_T len, SIZE_T *res_len )
2535 struct file_view *view;
2536 char *base, *alloc_base = 0, *alloc_end = working_set_limit;
2537 struct wine_rb_entry *ptr;
2538 MEMORY_BASIC_INFORMATION *info = buffer;
2539 sigset_t sigset;
2541 if (info_class != MemoryBasicInformation)
2543 switch(info_class)
2545 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
2546 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
2547 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
2549 default:
2550 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
2551 process, addr, info_class, buffer, len, res_len);
2552 return STATUS_INVALID_INFO_CLASS;
2556 if (process != NtCurrentProcess())
2558 NTSTATUS status;
2559 apc_call_t call;
2560 apc_result_t result;
2562 memset( &call, 0, sizeof(call) );
2564 call.virtual_query.type = APC_VIRTUAL_QUERY;
2565 call.virtual_query.addr = wine_server_client_ptr( addr );
2566 status = server_queue_process_apc( process, &call, &result );
2567 if (status != STATUS_SUCCESS) return status;
2569 if (result.virtual_query.status == STATUS_SUCCESS)
2571 info->BaseAddress = wine_server_get_ptr( result.virtual_query.base );
2572 info->AllocationBase = wine_server_get_ptr( result.virtual_query.alloc_base );
2573 info->RegionSize = result.virtual_query.size;
2574 info->Protect = result.virtual_query.prot;
2575 info->AllocationProtect = result.virtual_query.alloc_prot;
2576 info->State = (DWORD)result.virtual_query.state << 12;
2577 info->Type = (DWORD)result.virtual_query.alloc_type << 16;
2578 if (info->RegionSize != result.virtual_query.size) /* truncated */
2579 return STATUS_INVALID_PARAMETER; /* FIXME */
2580 if (res_len) *res_len = sizeof(*info);
2582 return result.virtual_query.status;
2585 base = ROUND_ADDR( addr, page_mask );
2587 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2589 /* Find the view containing the address */
2591 server_enter_uninterrupted_section( &csVirtual, &sigset );
2592 ptr = views_tree.root;
2593 while (ptr)
2595 view = WINE_RB_ENTRY_VALUE( ptr, struct file_view, entry );
2596 if ((char *)view->base > base)
2598 alloc_end = view->base;
2599 ptr = ptr->left;
2601 else if ((char *)view->base + view->size <= base)
2603 alloc_base = (char *)view->base + view->size;
2604 ptr = ptr->right;
2606 else
2608 alloc_base = view->base;
2609 alloc_end = (char *)view->base + view->size;
2610 break;
2614 /* Fill the info structure */
2616 info->AllocationBase = alloc_base;
2617 info->BaseAddress = base;
2618 info->RegionSize = alloc_end - base;
2620 if (!ptr)
2622 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2624 /* not in a reserved area at all, pretend it's allocated */
2625 #ifdef __i386__
2626 if (base >= (char *)address_space_start)
2628 info->State = MEM_RESERVE;
2629 info->Protect = PAGE_NOACCESS;
2630 info->AllocationProtect = PAGE_NOACCESS;
2631 info->Type = MEM_PRIVATE;
2633 else
2634 #endif
2636 info->State = MEM_FREE;
2637 info->Protect = PAGE_NOACCESS;
2638 info->AllocationBase = 0;
2639 info->AllocationProtect = 0;
2640 info->Type = 0;
2644 else
2646 BYTE vprot;
2647 char *ptr;
2648 SIZE_T range_size = get_committed_size( view, base, &vprot );
2650 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2651 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot, view->protect ) : 0;
2652 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect, view->protect );
2653 if (view->protect & SEC_IMAGE) info->Type = MEM_IMAGE;
2654 else if (view->protect & (SEC_FILE | SEC_RESERVE | SEC_COMMIT)) info->Type = MEM_MAPPED;
2655 else info->Type = MEM_PRIVATE;
2656 for (ptr = base; ptr < base + range_size; ptr += page_size)
2657 if ((get_page_vprot( ptr ) ^ vprot) & ~VPROT_WRITEWATCH) break;
2658 info->RegionSize = ptr - base;
2660 server_leave_uninterrupted_section( &csVirtual, &sigset );
2662 if (res_len) *res_len = sizeof(*info);
2663 return STATUS_SUCCESS;
2667 /***********************************************************************
2668 * NtLockVirtualMemory (NTDLL.@)
2669 * ZwLockVirtualMemory (NTDLL.@)
2671 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2673 NTSTATUS status = STATUS_SUCCESS;
2675 if (process != NtCurrentProcess())
2677 apc_call_t call;
2678 apc_result_t result;
2680 memset( &call, 0, sizeof(call) );
2682 call.virtual_lock.type = APC_VIRTUAL_LOCK;
2683 call.virtual_lock.addr = wine_server_client_ptr( *addr );
2684 call.virtual_lock.size = *size;
2685 status = server_queue_process_apc( process, &call, &result );
2686 if (status != STATUS_SUCCESS) return status;
2688 if (result.virtual_lock.status == STATUS_SUCCESS)
2690 *addr = wine_server_get_ptr( result.virtual_lock.addr );
2691 *size = result.virtual_lock.size;
2693 return result.virtual_lock.status;
2696 *size = ROUND_SIZE( *addr, *size );
2697 *addr = ROUND_ADDR( *addr, page_mask );
2699 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2700 return status;
2704 /***********************************************************************
2705 * NtUnlockVirtualMemory (NTDLL.@)
2706 * ZwUnlockVirtualMemory (NTDLL.@)
2708 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2710 NTSTATUS status = STATUS_SUCCESS;
2712 if (process != NtCurrentProcess())
2714 apc_call_t call;
2715 apc_result_t result;
2717 memset( &call, 0, sizeof(call) );
2719 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2720 call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2721 call.virtual_unlock.size = *size;
2722 status = server_queue_process_apc( process, &call, &result );
2723 if (status != STATUS_SUCCESS) return status;
2725 if (result.virtual_unlock.status == STATUS_SUCCESS)
2727 *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2728 *size = result.virtual_unlock.size;
2730 return result.virtual_unlock.status;
2733 *size = ROUND_SIZE( *addr, *size );
2734 *addr = ROUND_ADDR( *addr, page_mask );
2736 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2737 return status;
2741 /***********************************************************************
2742 * NtCreateSection (NTDLL.@)
2743 * ZwCreateSection (NTDLL.@)
2745 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2746 const LARGE_INTEGER *size, ULONG protect,
2747 ULONG sec_flags, HANDLE file )
2749 NTSTATUS ret;
2750 unsigned int vprot, file_access = 0;
2751 data_size_t len;
2752 struct object_attributes *objattr;
2754 if ((ret = get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE ))) return ret;
2755 if ((ret = alloc_object_attributes( attr, &objattr, &len ))) return ret;
2757 if (vprot & VPROT_READ) file_access |= FILE_READ_DATA;
2758 if (vprot & VPROT_WRITE) file_access |= FILE_WRITE_DATA;
2760 SERVER_START_REQ( create_mapping )
2762 req->access = access;
2763 req->flags = sec_flags;
2764 req->file_handle = wine_server_obj_handle( file );
2765 req->file_access = file_access;
2766 req->size = size ? size->QuadPart : 0;
2767 wine_server_add_data( req, objattr, len );
2768 ret = wine_server_call( req );
2769 *handle = wine_server_ptr_handle( reply->handle );
2771 SERVER_END_REQ;
2773 RtlFreeHeap( GetProcessHeap(), 0, objattr );
2774 return ret;
2778 /***********************************************************************
2779 * NtOpenSection (NTDLL.@)
2780 * ZwOpenSection (NTDLL.@)
2782 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2784 NTSTATUS ret;
2786 if ((ret = validate_open_object_attributes( attr ))) return ret;
2788 SERVER_START_REQ( open_mapping )
2790 req->access = access;
2791 req->attributes = attr->Attributes;
2792 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2793 if (attr->ObjectName)
2794 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
2795 ret = wine_server_call( req );
2796 *handle = wine_server_ptr_handle( reply->handle );
2798 SERVER_END_REQ;
2799 return ret;
2803 /***********************************************************************
2804 * NtMapViewOfSection (NTDLL.@)
2805 * ZwMapViewOfSection (NTDLL.@)
2807 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2808 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2809 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2811 NTSTATUS res;
2812 mem_size_t full_size;
2813 ACCESS_MASK access;
2814 SIZE_T size, mask = get_mask( zero_bits );
2815 int unix_handle = -1, needs_close;
2816 unsigned int vprot, sec_flags;
2817 struct file_view *view;
2818 pe_image_info_t image_info;
2819 HANDLE dup_mapping, shared_file;
2820 LARGE_INTEGER offset;
2821 sigset_t sigset;
2823 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2825 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2826 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2828 /* Check parameters */
2830 if ((*addr_ptr && zero_bits) || !mask)
2831 return STATUS_INVALID_PARAMETER_4;
2833 #ifndef _WIN64
2834 if (!is_wow64 && (alloc_type & AT_ROUND_TO_PAGE))
2836 *addr_ptr = ROUND_ADDR( *addr_ptr, page_mask );
2837 mask = page_mask;
2839 #endif
2841 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2842 return STATUS_MAPPED_ALIGNMENT;
2844 switch(protect)
2846 case PAGE_NOACCESS:
2847 case PAGE_READONLY:
2848 case PAGE_WRITECOPY:
2849 access = SECTION_MAP_READ;
2850 break;
2851 case PAGE_READWRITE:
2852 access = SECTION_MAP_WRITE;
2853 break;
2854 case PAGE_EXECUTE:
2855 case PAGE_EXECUTE_READ:
2856 case PAGE_EXECUTE_WRITECOPY:
2857 access = SECTION_MAP_READ | SECTION_MAP_EXECUTE;
2858 break;
2859 case PAGE_EXECUTE_READWRITE:
2860 access = SECTION_MAP_WRITE | SECTION_MAP_EXECUTE;
2861 break;
2862 default:
2863 return STATUS_INVALID_PAGE_PROTECTION;
2866 if (process != NtCurrentProcess())
2868 apc_call_t call;
2869 apc_result_t result;
2871 memset( &call, 0, sizeof(call) );
2873 call.map_view.type = APC_MAP_VIEW;
2874 call.map_view.handle = wine_server_obj_handle( handle );
2875 call.map_view.addr = wine_server_client_ptr( *addr_ptr );
2876 call.map_view.size = *size_ptr;
2877 call.map_view.offset = offset.QuadPart;
2878 call.map_view.zero_bits = zero_bits;
2879 call.map_view.alloc_type = alloc_type;
2880 call.map_view.prot = protect;
2881 res = server_queue_process_apc( process, &call, &result );
2882 if (res != STATUS_SUCCESS) return res;
2884 if ((NTSTATUS)result.map_view.status >= 0)
2886 *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2887 *size_ptr = result.map_view.size;
2889 return result.map_view.status;
2892 SERVER_START_REQ( get_mapping_info )
2894 req->handle = wine_server_obj_handle( handle );
2895 req->access = access;
2896 wine_server_set_reply( req, &image_info, sizeof(image_info) );
2897 res = wine_server_call( req );
2898 sec_flags = reply->flags;
2899 full_size = reply->size;
2900 dup_mapping = wine_server_ptr_handle( reply->mapping );
2901 shared_file = wine_server_ptr_handle( reply->shared_file );
2903 SERVER_END_REQ;
2904 if (res) return res;
2906 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2908 if (sec_flags & SEC_IMAGE)
2910 void *base = wine_server_get_ptr( image_info.base );
2912 if ((ULONG_PTR)base != image_info.base) base = NULL;
2913 size = image_info.map_size;
2914 if (size != image_info.map_size) /* truncated */
2916 WARN( "Modules larger than 4Gb (%s) not supported\n",
2917 wine_dbgstr_longlong(image_info.map_size) );
2918 res = STATUS_INVALID_PARAMETER;
2919 goto done;
2921 if (shared_file)
2923 int shared_fd, shared_needs_close;
2925 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2926 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2927 res = map_image( handle, access, unix_handle, base, size, mask, image_info.header_size,
2928 shared_fd, dup_mapping, addr_ptr );
2929 if (shared_needs_close) close( shared_fd );
2930 close_handle( shared_file );
2932 else
2934 res = map_image( handle, access, unix_handle, base, size, mask, image_info.header_size,
2935 -1, dup_mapping, addr_ptr );
2937 if (needs_close) close( unix_handle );
2938 if (res >= 0) *size_ptr = size;
2939 return res;
2942 res = STATUS_INVALID_PARAMETER;
2943 if (offset.QuadPart >= full_size) goto done;
2944 if (*size_ptr)
2946 size = *size_ptr;
2947 if (size > full_size - offset.QuadPart)
2949 res = STATUS_INVALID_VIEW_SIZE;
2950 goto done;
2953 else
2955 size = full_size - offset.QuadPart;
2956 if (size != full_size - offset.QuadPart) /* truncated */
2958 WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2959 wine_dbgstr_longlong(full_size) );
2960 goto done;
2963 if (!(size = ROUND_SIZE( 0, size ))) goto done; /* wrap-around */
2965 /* Reserve a properly aligned area */
2967 server_enter_uninterrupted_section( &csVirtual, &sigset );
2969 get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE );
2970 vprot |= sec_flags;
2971 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2972 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2973 if (res)
2975 server_leave_uninterrupted_section( &csVirtual, &sigset );
2976 goto done;
2979 /* Map the file */
2981 TRACE("handle=%p size=%lx offset=%x%08x\n",
2982 handle, size, offset.u.HighPart, offset.u.LowPart );
2984 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2985 if (res == STATUS_SUCCESS)
2987 SERVER_START_REQ( map_view )
2989 req->mapping = wine_server_obj_handle( handle );
2990 req->access = access;
2991 req->base = wine_server_client_ptr( view->base );
2992 req->size = size;
2993 req->start = offset.QuadPart;
2994 res = wine_server_call( req );
2996 SERVER_END_REQ;
2999 if (res == STATUS_SUCCESS)
3001 *addr_ptr = view->base;
3002 *size_ptr = size;
3003 view->mapping = dup_mapping;
3004 dup_mapping = 0; /* don't close it */
3005 VIRTUAL_DEBUG_DUMP_VIEW( view );
3007 else
3009 ERR( "map_file_into_view %p %lx %x%08x failed\n",
3010 view->base, size, offset.u.HighPart, offset.u.LowPart );
3011 delete_view( view );
3014 server_leave_uninterrupted_section( &csVirtual, &sigset );
3016 done:
3017 if (dup_mapping) close_handle( dup_mapping );
3018 if (needs_close) close( unix_handle );
3019 return res;
3023 /***********************************************************************
3024 * NtUnmapViewOfSection (NTDLL.@)
3025 * ZwUnmapViewOfSection (NTDLL.@)
3027 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
3029 struct file_view *view;
3030 NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
3031 sigset_t sigset;
3033 if (process != NtCurrentProcess())
3035 apc_call_t call;
3036 apc_result_t result;
3038 memset( &call, 0, sizeof(call) );
3040 call.unmap_view.type = APC_UNMAP_VIEW;
3041 call.unmap_view.addr = wine_server_client_ptr( addr );
3042 status = server_queue_process_apc( process, &call, &result );
3043 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
3044 return status;
3047 server_enter_uninterrupted_section( &csVirtual, &sigset );
3048 if ((view = VIRTUAL_FindView( addr, 0 )) && !is_view_valloc( view ))
3050 SERVER_START_REQ( unmap_view )
3052 req->base = wine_server_client_ptr( view->base );
3053 status = wine_server_call( req );
3055 SERVER_END_REQ;
3056 if (!status) delete_view( view );
3058 server_leave_uninterrupted_section( &csVirtual, &sigset );
3059 return status;
3063 /******************************************************************************
3064 * NtQuerySection (NTDLL.@)
3065 * ZwQuerySection (NTDLL.@)
3067 NTSTATUS WINAPI NtQuerySection( HANDLE handle, SECTION_INFORMATION_CLASS class, void *ptr,
3068 ULONG size, ULONG *ret_size )
3070 NTSTATUS status;
3071 pe_image_info_t image_info;
3073 switch (class)
3075 case SectionBasicInformation:
3076 if (size < sizeof(SECTION_BASIC_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
3077 break;
3078 case SectionImageInformation:
3079 if (size < sizeof(SECTION_IMAGE_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
3080 break;
3081 default:
3082 FIXME( "class %u not implemented\n", class );
3083 return STATUS_NOT_IMPLEMENTED;
3085 if (!ptr) return STATUS_ACCESS_VIOLATION;
3087 SERVER_START_REQ( get_mapping_info )
3089 req->handle = wine_server_obj_handle( handle );
3090 req->access = SECTION_QUERY;
3091 wine_server_set_reply( req, &image_info, sizeof(image_info) );
3092 if (!(status = wine_server_call( req )))
3094 if (class == SectionBasicInformation)
3096 SECTION_BASIC_INFORMATION *info = ptr;
3097 info->Attributes = reply->flags;
3098 info->BaseAddress = NULL;
3099 info->Size.QuadPart = reply->size;
3100 if (ret_size) *ret_size = sizeof(*info);
3102 else if (reply->flags & SEC_IMAGE)
3104 SECTION_IMAGE_INFORMATION *info = ptr;
3105 info->TransferAddress = wine_server_get_ptr( image_info.entry_point );
3106 info->ZeroBits = image_info.zerobits;
3107 info->MaximumStackSize = image_info.stack_size;
3108 info->CommittedStackSize = image_info.stack_commit;
3109 info->SubSystemType = image_info.subsystem;
3110 info->SubsystemVersionLow = image_info.subsystem_low;
3111 info->SubsystemVersionHigh = image_info.subsystem_high;
3112 info->GpValue = image_info.gp;
3113 info->ImageCharacteristics = image_info.image_charact;
3114 info->DllCharacteristics = image_info.dll_charact;
3115 info->Machine = image_info.machine;
3116 info->ImageContainsCode = image_info.contains_code;
3117 info->ImageFlags = image_info.image_flags;
3118 info->LoaderFlags = image_info.loader_flags;
3119 info->ImageFileSize = image_info.file_size;
3120 info->CheckSum = image_info.checksum;
3121 if (ret_size) *ret_size = sizeof(*info);
3123 else status = STATUS_SECTION_NOT_IMAGE;
3126 SERVER_END_REQ;
3128 return status;
3132 /***********************************************************************
3133 * NtFlushVirtualMemory (NTDLL.@)
3134 * ZwFlushVirtualMemory (NTDLL.@)
3136 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
3137 SIZE_T *size_ptr, ULONG unknown )
3139 struct file_view *view;
3140 NTSTATUS status = STATUS_SUCCESS;
3141 sigset_t sigset;
3142 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
3144 if (process != NtCurrentProcess())
3146 apc_call_t call;
3147 apc_result_t result;
3149 memset( &call, 0, sizeof(call) );
3151 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
3152 call.virtual_flush.addr = wine_server_client_ptr( addr );
3153 call.virtual_flush.size = *size_ptr;
3154 status = server_queue_process_apc( process, &call, &result );
3155 if (status != STATUS_SUCCESS) return status;
3157 if (result.virtual_flush.status == STATUS_SUCCESS)
3159 *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
3160 *size_ptr = result.virtual_flush.size;
3162 return result.virtual_flush.status;
3165 server_enter_uninterrupted_section( &csVirtual, &sigset );
3166 if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
3167 else
3169 if (!*size_ptr) *size_ptr = view->size;
3170 *addr_ptr = addr;
3171 #ifdef MS_ASYNC
3172 if (msync( addr, *size_ptr, MS_ASYNC )) status = STATUS_NOT_MAPPED_DATA;
3173 #endif
3175 server_leave_uninterrupted_section( &csVirtual, &sigset );
3176 return status;
3180 /***********************************************************************
3181 * NtGetWriteWatch (NTDLL.@)
3182 * ZwGetWriteWatch (NTDLL.@)
3184 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
3185 ULONG_PTR *count, ULONG *granularity )
3187 NTSTATUS status = STATUS_SUCCESS;
3188 sigset_t sigset;
3190 size = ROUND_SIZE( base, size );
3191 base = ROUND_ADDR( base, page_mask );
3193 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
3194 if (!*count || !size) return STATUS_INVALID_PARAMETER;
3195 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
3197 if (!addresses) return STATUS_ACCESS_VIOLATION;
3199 TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
3200 addresses, *count );
3202 server_enter_uninterrupted_section( &csVirtual, &sigset );
3204 if (is_write_watch_range( base, size ))
3206 ULONG_PTR pos = 0;
3207 char *addr = base;
3208 char *end = addr + size;
3210 while (pos < *count && addr < end)
3212 if (!(get_page_vprot( addr ) & VPROT_WRITEWATCH)) addresses[pos++] = addr;
3213 addr += page_size;
3215 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( base, addr - (char *)base );
3216 *count = pos;
3217 *granularity = page_size;
3219 else status = STATUS_INVALID_PARAMETER;
3221 server_leave_uninterrupted_section( &csVirtual, &sigset );
3222 return status;
3226 /***********************************************************************
3227 * NtResetWriteWatch (NTDLL.@)
3228 * ZwResetWriteWatch (NTDLL.@)
3230 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
3232 NTSTATUS status = STATUS_SUCCESS;
3233 sigset_t sigset;
3235 size = ROUND_SIZE( base, size );
3236 base = ROUND_ADDR( base, page_mask );
3238 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
3240 if (!size) return STATUS_INVALID_PARAMETER;
3242 server_enter_uninterrupted_section( &csVirtual, &sigset );
3244 if (is_write_watch_range( base, size ))
3245 reset_write_watches( base, size );
3246 else
3247 status = STATUS_INVALID_PARAMETER;
3249 server_leave_uninterrupted_section( &csVirtual, &sigset );
3250 return status;
3254 /***********************************************************************
3255 * NtReadVirtualMemory (NTDLL.@)
3256 * ZwReadVirtualMemory (NTDLL.@)
3258 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
3259 SIZE_T size, SIZE_T *bytes_read )
3261 NTSTATUS status;
3263 if (virtual_check_buffer_for_write( buffer, size ))
3265 SERVER_START_REQ( read_process_memory )
3267 req->handle = wine_server_obj_handle( process );
3268 req->addr = wine_server_client_ptr( addr );
3269 wine_server_set_reply( req, buffer, size );
3270 if ((status = wine_server_call( req ))) size = 0;
3272 SERVER_END_REQ;
3274 else
3276 status = STATUS_ACCESS_VIOLATION;
3277 size = 0;
3279 if (bytes_read) *bytes_read = size;
3280 return status;
3284 /***********************************************************************
3285 * NtWriteVirtualMemory (NTDLL.@)
3286 * ZwWriteVirtualMemory (NTDLL.@)
3288 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
3289 SIZE_T size, SIZE_T *bytes_written )
3291 NTSTATUS status;
3293 if (virtual_check_buffer_for_read( buffer, size ))
3295 SERVER_START_REQ( write_process_memory )
3297 req->handle = wine_server_obj_handle( process );
3298 req->addr = wine_server_client_ptr( addr );
3299 wine_server_add_data( req, buffer, size );
3300 if ((status = wine_server_call( req ))) size = 0;
3302 SERVER_END_REQ;
3304 else
3306 status = STATUS_PARTIAL_COPY;
3307 size = 0;
3309 if (bytes_written) *bytes_written = size;
3310 return status;
3314 /***********************************************************************
3315 * NtAreMappedFilesTheSame (NTDLL.@)
3316 * ZwAreMappedFilesTheSame (NTDLL.@)
3318 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
3320 struct file_view *view1, *view2;
3321 NTSTATUS status;
3322 sigset_t sigset;
3324 TRACE("%p %p\n", addr1, addr2);
3326 server_enter_uninterrupted_section( &csVirtual, &sigset );
3328 view1 = VIRTUAL_FindView( addr1, 0 );
3329 view2 = VIRTUAL_FindView( addr2, 0 );
3331 if (!view1 || !view2)
3332 status = STATUS_INVALID_ADDRESS;
3333 else if (is_view_valloc( view1 ) || is_view_valloc( view2 ))
3334 status = STATUS_CONFLICTING_ADDRESSES;
3335 else if (view1 == view2)
3336 status = STATUS_SUCCESS;
3337 else if ((view1->protect & VPROT_SYSTEM) || (view2->protect & VPROT_SYSTEM))
3338 status = STATUS_NOT_SAME_DEVICE;
3339 else
3341 SERVER_START_REQ( is_same_mapping )
3343 req->base1 = wine_server_client_ptr( view1->base );
3344 req->base2 = wine_server_client_ptr( view2->base );
3345 status = wine_server_call( req );
3347 SERVER_END_REQ;
3350 server_leave_uninterrupted_section( &csVirtual, &sigset );
3351 return status;