ntdll: Improve check_atl_thunk to prevent passing exceptions to the usermode application.
[wine/wine-gecko.git] / dlls / ntdll / virtual.c
blob4c4c05d21fcffd80409b2a2c0c993ea77836f44a
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_VALGRIND_VALGRIND_H
42 # include <valgrind/valgrind.h>
43 #endif
45 #define NONAMELESSUNION
46 #define NONAMELESSSTRUCT
47 #include "ntstatus.h"
48 #define WIN32_NO_STATUS
49 #include "windef.h"
50 #include "winternl.h"
51 #include "wine/library.h"
52 #include "wine/server.h"
53 #include "wine/exception.h"
54 #include "wine/list.h"
55 #include "wine/debug.h"
56 #include "ntdll_misc.h"
58 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
59 WINE_DECLARE_DEBUG_CHANNEL(module);
61 #ifndef MAP_NORESERVE
62 #define MAP_NORESERVE 0
63 #endif
65 /* File view */
66 struct file_view
68 struct list entry; /* Entry in global view list */
69 void *base; /* Base address */
70 size_t size; /* Size in bytes */
71 HANDLE mapping; /* Handle to the file mapping */
72 unsigned int map_protect; /* Mapping protection */
73 unsigned int protect; /* Protection for all pages at allocation time */
74 BYTE prot[1]; /* Protection byte for each page */
78 /* Conversion from VPROT_* to Win32 flags */
79 static const BYTE VIRTUAL_Win32Flags[16] =
81 PAGE_NOACCESS, /* 0 */
82 PAGE_READONLY, /* READ */
83 PAGE_READWRITE, /* WRITE */
84 PAGE_READWRITE, /* READ | WRITE */
85 PAGE_EXECUTE, /* EXEC */
86 PAGE_EXECUTE_READ, /* READ | EXEC */
87 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
88 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
89 PAGE_WRITECOPY, /* WRITECOPY */
90 PAGE_WRITECOPY, /* READ | WRITECOPY */
91 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
92 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
93 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
94 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
95 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
96 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
99 static struct list views_list = LIST_INIT(views_list);
101 static RTL_CRITICAL_SECTION csVirtual;
102 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
104 0, 0, &csVirtual,
105 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
106 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
108 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
110 #ifdef __i386__
111 static const UINT page_shift = 12;
112 static const UINT_PTR page_mask = 0xfff;
113 /* Note: these are Windows limits, you cannot change them. */
114 static void *address_space_limit = (void *)0xc0000000; /* top of the total available address space */
115 static void *user_space_limit = (void *)0x7fff0000; /* top of the user address space */
116 static void *working_set_limit = (void *)0x7fff0000; /* top of the current working set */
117 static void *address_space_start = (void *)0x110000; /* keep DOS area clear */
118 #elif defined(__x86_64__)
119 static const UINT page_shift = 12;
120 static const UINT_PTR page_mask = 0xfff;
121 static void *address_space_limit = (void *)0x7fffffff0000;
122 static void *user_space_limit = (void *)0x7fffffff0000;
123 static void *working_set_limit = (void *)0x7fffffff0000;
124 static void *address_space_start = (void *)0x10000;
125 #else
126 UINT_PTR page_size = 0;
127 static UINT page_shift;
128 static UINT_PTR page_mask;
129 static void *address_space_limit;
130 static void *user_space_limit;
131 static void *working_set_limit;
132 static void *address_space_start = (void *)0x10000;
133 #endif /* __i386__ */
134 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
136 #define ROUND_ADDR(addr,mask) \
137 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
139 #define ROUND_SIZE(addr,size) \
140 (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
142 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
143 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
145 #define VIRTUAL_HEAP_SIZE (sizeof(void*)*1024*1024)
147 static HANDLE virtual_heap;
148 static void *preload_reserve_start;
149 static void *preload_reserve_end;
150 static BOOL use_locks;
151 static BOOL force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
154 /***********************************************************************
155 * VIRTUAL_GetProtStr
157 static const char *VIRTUAL_GetProtStr( BYTE prot )
159 static char buffer[6];
160 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
161 buffer[1] = (prot & VPROT_GUARD) ? 'g' : ((prot & VPROT_WRITEWATCH) ? 'H' : '-');
162 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
163 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
164 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
165 buffer[5] = 0;
166 return buffer;
170 /***********************************************************************
171 * VIRTUAL_GetUnixProt
173 * Convert page protections to protection for mmap/mprotect.
175 static int VIRTUAL_GetUnixProt( BYTE vprot )
177 int prot = 0;
178 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
180 if (vprot & VPROT_READ) prot |= PROT_READ;
181 if (vprot & VPROT_WRITE) prot |= PROT_WRITE | PROT_READ;
182 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE | PROT_READ;
183 if (vprot & VPROT_EXEC) prot |= PROT_EXEC | PROT_READ;
184 if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
186 if (!prot) prot = PROT_NONE;
187 return prot;
191 /***********************************************************************
192 * VIRTUAL_DumpView
194 static void VIRTUAL_DumpView( struct file_view *view )
196 UINT i, count;
197 char *addr = view->base;
198 BYTE prot = view->prot[0];
200 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
201 if (view->protect & VPROT_SYSTEM)
202 TRACE( " (system)\n" );
203 else if (view->protect & VPROT_VALLOC)
204 TRACE( " (valloc)\n" );
205 else if (view->mapping)
206 TRACE( " %p\n", view->mapping );
207 else
208 TRACE( " (anonymous)\n");
210 for (count = i = 1; i < view->size >> page_shift; i++, count++)
212 if (view->prot[i] == prot) continue;
213 TRACE( " %p - %p %s\n",
214 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
215 addr += (count << page_shift);
216 prot = view->prot[i];
217 count = 0;
219 if (count)
220 TRACE( " %p - %p %s\n",
221 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
225 /***********************************************************************
226 * VIRTUAL_Dump
228 #ifdef WINE_VM_DEBUG
229 static void VIRTUAL_Dump(void)
231 sigset_t sigset;
232 struct file_view *view;
234 TRACE( "Dump of all virtual memory views:\n" );
235 server_enter_uninterrupted_section( &csVirtual, &sigset );
236 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
238 VIRTUAL_DumpView( view );
240 server_leave_uninterrupted_section( &csVirtual, &sigset );
242 #endif
245 /***********************************************************************
246 * VIRTUAL_FindView
248 * Find the view containing a given address. The csVirtual section must be held by caller.
250 * PARAMS
251 * addr [I] Address
253 * RETURNS
254 * View: Success
255 * NULL: Failure
257 static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
259 struct file_view *view;
261 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
263 if (view->base > addr) break; /* no matching view */
264 if ((const char *)view->base + view->size <= (const char *)addr) continue;
265 if ((const char *)view->base + view->size < (const char *)addr + size) break; /* size too large */
266 if ((const char *)addr + size < (const char *)addr) break; /* overflow */
267 return view;
269 return NULL;
273 /***********************************************************************
274 * get_mask
276 static inline UINT_PTR get_mask( ULONG zero_bits )
278 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
279 if (zero_bits < page_shift) zero_bits = page_shift;
280 return (1 << zero_bits) - 1;
284 /***********************************************************************
285 * find_view_range
287 * Find the first view overlapping at least part of the specified range.
288 * The csVirtual section must be held by caller.
290 static struct file_view *find_view_range( const void *addr, size_t size )
292 struct file_view *view;
294 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
296 if ((const char *)view->base >= (const char *)addr + size) break;
297 if ((const char *)view->base + view->size > (const char *)addr) return view;
299 return NULL;
303 /***********************************************************************
304 * find_free_area
306 * Find a free area between views inside the specified range.
307 * The csVirtual section must be held by caller.
309 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
311 struct list *ptr;
312 void *start;
314 if (top_down)
316 start = ROUND_ADDR( (char *)end - size, mask );
317 if (start >= end || start < base) return NULL;
319 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
321 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
323 if ((char *)view->base + view->size <= (char *)start) break;
324 if ((char *)view->base >= (char *)start + size) continue;
325 start = ROUND_ADDR( (char *)view->base - size, mask );
326 /* stop if remaining space is not large enough */
327 if (!start || start >= end || start < base) return NULL;
330 else
332 start = ROUND_ADDR( (char *)base + mask, mask );
333 if (start >= end || (char *)end - (char *)start < size) return NULL;
335 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
337 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
339 if ((char *)view->base >= (char *)start + size) break;
340 if ((char *)view->base + view->size <= (char *)start) continue;
341 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
342 /* stop if remaining space is not large enough */
343 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
346 return start;
350 /***********************************************************************
351 * add_reserved_area
353 * Add a reserved area to the list maintained by libwine.
354 * The csVirtual section must be held by caller.
356 static void add_reserved_area( void *addr, size_t size )
358 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
360 if (addr < user_space_limit)
362 /* unmap the part of the area that is below the limit */
363 assert( (char *)addr + size > (char *)user_space_limit );
364 munmap( addr, (char *)user_space_limit - (char *)addr );
365 size -= (char *)user_space_limit - (char *)addr;
366 addr = user_space_limit;
368 /* blow away existing mappings */
369 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
370 wine_mmap_add_reserved_area( addr, size );
374 /***********************************************************************
375 * remove_reserved_area
377 * Remove a reserved area from the list maintained by libwine.
378 * The csVirtual section must be held by caller.
380 static void remove_reserved_area( void *addr, size_t size )
382 struct file_view *view;
384 TRACE( "removing %p-%p\n", addr, (char *)addr + size );
385 wine_mmap_remove_reserved_area( addr, size, 0 );
387 /* unmap areas not covered by an existing view */
388 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
390 if ((char *)view->base >= (char *)addr + size)
392 munmap( addr, size );
393 break;
395 if ((char *)view->base + view->size <= (char *)addr) continue;
396 if (view->base > addr) munmap( addr, (char *)view->base - (char *)addr );
397 if ((char *)view->base + view->size > (char *)addr + size) break;
398 size = (char *)addr + size - ((char *)view->base + view->size);
399 addr = (char *)view->base + view->size;
404 /***********************************************************************
405 * is_beyond_limit
407 * Check if an address range goes beyond a given limit.
409 static inline BOOL is_beyond_limit( const void *addr, size_t size, const void *limit )
411 return (addr >= limit || (const char *)addr + size > (const char *)limit);
415 /***********************************************************************
416 * unmap_area
418 * Unmap an area, or simply replace it by an empty mapping if it is
419 * in a reserved area. The csVirtual section must be held by caller.
421 static inline void unmap_area( void *addr, size_t size )
423 if (wine_mmap_is_in_reserved_area( addr, size ))
424 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
425 else if (is_beyond_limit( addr, size, user_space_limit ))
426 add_reserved_area( addr, size );
427 else
428 munmap( addr, size );
432 /***********************************************************************
433 * delete_view
435 * Deletes a view. The csVirtual section must be held by caller.
437 static void delete_view( struct file_view *view ) /* [in] View */
439 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
440 list_remove( &view->entry );
441 if (view->mapping) close_handle( view->mapping );
442 RtlFreeHeap( virtual_heap, 0, view );
446 /***********************************************************************
447 * create_view
449 * Create a view. The csVirtual section must be held by caller.
451 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
453 struct file_view *view;
454 struct list *ptr;
455 int unix_prot = VIRTUAL_GetUnixProt( vprot );
457 assert( !((UINT_PTR)base & page_mask) );
458 assert( !(size & page_mask) );
460 /* Create the view structure */
462 if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
464 FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
465 return STATUS_NO_MEMORY;
468 view->base = base;
469 view->size = size;
470 view->mapping = 0;
471 view->map_protect = 0;
472 view->protect = vprot;
473 memset( view->prot, vprot, size >> page_shift );
475 /* Insert it in the linked list */
477 LIST_FOR_EACH( ptr, &views_list )
479 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
480 if (next->base > base) break;
482 list_add_before( ptr, &view->entry );
484 /* Check for overlapping views. This can happen if the previous view
485 * was a system view that got unmapped behind our back. In that case
486 * we recover by simply deleting it. */
488 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
490 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
491 if ((char *)prev->base + prev->size > (char *)base)
493 TRACE( "overlapping prev view %p-%p for %p-%p\n",
494 prev->base, (char *)prev->base + prev->size,
495 base, (char *)base + view->size );
496 assert( prev->protect & VPROT_SYSTEM );
497 delete_view( prev );
500 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
502 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
503 if ((char *)base + view->size > (char *)next->base)
505 TRACE( "overlapping next view %p-%p for %p-%p\n",
506 next->base, (char *)next->base + next->size,
507 base, (char *)base + view->size );
508 assert( next->protect & VPROT_SYSTEM );
509 delete_view( next );
513 *view_ret = view;
514 VIRTUAL_DEBUG_DUMP_VIEW( view );
516 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
518 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
519 mprotect( base, size, unix_prot | PROT_EXEC );
521 return STATUS_SUCCESS;
525 /***********************************************************************
526 * VIRTUAL_GetWin32Prot
528 * Convert page protections to Win32 flags.
530 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
532 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
533 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
534 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
535 return ret;
539 /***********************************************************************
540 * get_vprot_flags
542 * Build page protections from Win32 flags.
544 * PARAMS
545 * protect [I] Win32 protection flags
547 * RETURNS
548 * Value of page protection flags
550 static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot, BOOL image )
552 switch(protect & 0xff)
554 case PAGE_READONLY:
555 *vprot = VPROT_READ;
556 break;
557 case PAGE_READWRITE:
558 if (image)
559 *vprot = VPROT_READ | VPROT_WRITECOPY;
560 else
561 *vprot = VPROT_READ | VPROT_WRITE;
562 break;
563 case PAGE_WRITECOPY:
564 *vprot = VPROT_READ | VPROT_WRITECOPY;
565 break;
566 case PAGE_EXECUTE:
567 *vprot = VPROT_EXEC;
568 break;
569 case PAGE_EXECUTE_READ:
570 *vprot = VPROT_EXEC | VPROT_READ;
571 break;
572 case PAGE_EXECUTE_READWRITE:
573 if (image)
574 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
575 else
576 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
577 break;
578 case PAGE_EXECUTE_WRITECOPY:
579 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
580 break;
581 case PAGE_NOACCESS:
582 *vprot = 0;
583 break;
584 default:
585 return STATUS_INVALID_PAGE_PROTECTION;
587 if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
588 if (protect & PAGE_NOCACHE) *vprot |= VPROT_NOCACHE;
589 return STATUS_SUCCESS;
593 /***********************************************************************
594 * mprotect_exec
596 * Wrapper for mprotect, adds PROT_EXEC if forced by force_exec_prot
598 static inline int mprotect_exec( void *base, size_t size, int unix_prot, unsigned int view_protect )
600 if (force_exec_prot && !(view_protect & VPROT_NOEXEC) &&
601 (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
603 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
604 if (!mprotect( base, size, unix_prot | PROT_EXEC )) return 0;
605 /* exec + write may legitimately fail, in that case fall back to write only */
606 if (!(unix_prot & PROT_WRITE)) return -1;
609 return mprotect( base, size, unix_prot );
612 /***********************************************************************
613 * VIRTUAL_SetProt
615 * Change the protection of a range of pages.
617 * RETURNS
618 * TRUE: Success
619 * FALSE: Failure
621 static BOOL VIRTUAL_SetProt( struct file_view *view, /* [in] Pointer to view */
622 void *base, /* [in] Starting address */
623 size_t size, /* [in] Size in bytes */
624 BYTE vprot ) /* [in] Protections to use */
626 int unix_prot = VIRTUAL_GetUnixProt(vprot);
627 BYTE *p = view->prot + (((char *)base - (char *)view->base) >> page_shift);
629 TRACE("%p-%p %s\n",
630 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
632 if (view->protect & VPROT_WRITEWATCH)
634 /* each page may need different protections depending on write watch flag */
635 UINT i, count;
636 char *addr = base;
637 int prot;
639 p[0] = vprot | (p[0] & VPROT_WRITEWATCH);
640 unix_prot = VIRTUAL_GetUnixProt( p[0] );
641 for (count = i = 1; i < size >> page_shift; i++, count++)
643 p[i] = vprot | (p[i] & VPROT_WRITEWATCH);
644 prot = VIRTUAL_GetUnixProt( p[i] );
645 if (prot == unix_prot) continue;
646 mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
647 addr += count << page_shift;
648 unix_prot = prot;
649 count = 0;
651 if (count) mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
652 VIRTUAL_DEBUG_DUMP_VIEW( view );
653 return TRUE;
656 /* if setting stack guard pages, store the permissions first, as the guard may be
657 * triggered at any point after mprotect and change the permissions again */
658 if ((vprot & VPROT_GUARD) &&
659 (base >= NtCurrentTeb()->DeallocationStack) &&
660 (base < NtCurrentTeb()->Tib.StackBase))
662 memset( p, vprot, size >> page_shift );
663 mprotect( base, size, unix_prot );
664 VIRTUAL_DEBUG_DUMP_VIEW( view );
665 return TRUE;
668 if (mprotect_exec( base, size, unix_prot, view->protect )) /* FIXME: last error */
669 return FALSE;
671 memset( p, vprot, size >> page_shift );
672 VIRTUAL_DEBUG_DUMP_VIEW( view );
673 return TRUE;
677 /***********************************************************************
678 * reset_write_watches
680 * Reset write watches in a memory range.
682 static void reset_write_watches( struct file_view *view, void *base, SIZE_T size )
684 SIZE_T i, count;
685 int prot, unix_prot;
686 char *addr = base;
687 BYTE *p = view->prot + ((addr - (char *)view->base) >> page_shift);
689 p[0] |= VPROT_WRITEWATCH;
690 unix_prot = VIRTUAL_GetUnixProt( p[0] );
691 for (count = i = 1; i < size >> page_shift; i++, count++)
693 p[i] |= VPROT_WRITEWATCH;
694 prot = VIRTUAL_GetUnixProt( p[i] );
695 if (prot == unix_prot) continue;
696 mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
697 addr += count << page_shift;
698 unix_prot = prot;
699 count = 0;
701 if (count) mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
705 /***********************************************************************
706 * unmap_extra_space
708 * Release the extra memory while keeping the range starting on the granularity boundary.
710 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
712 if ((ULONG_PTR)ptr & mask)
714 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
715 munmap( ptr, extra );
716 ptr = (char *)ptr + extra;
717 total_size -= extra;
719 if (total_size > wanted_size)
720 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
721 return ptr;
725 struct alloc_area
727 size_t size;
728 size_t mask;
729 int top_down;
730 void *limit;
731 void *result;
734 /***********************************************************************
735 * alloc_reserved_area_callback
737 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
739 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
741 struct alloc_area *alloc = arg;
742 void *end = (char *)start + size;
744 if (start < address_space_start) start = address_space_start;
745 if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
746 if (start >= end) return 0;
748 /* make sure we don't touch the preloader reserved range */
749 if (preload_reserve_end >= start)
751 if (preload_reserve_end >= end)
753 if (preload_reserve_start <= start) return 0; /* no space in that area */
754 if (preload_reserve_start < end) end = preload_reserve_start;
756 else if (preload_reserve_start <= start) start = preload_reserve_end;
757 else
759 /* range is split in two by the preloader reservation, try first part */
760 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
761 alloc->mask, alloc->top_down )))
762 return 1;
763 /* then fall through to try second part */
764 start = preload_reserve_end;
767 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
768 return 1;
770 return 0;
774 /***********************************************************************
775 * map_view
777 * Create a view and mmap the corresponding memory area.
778 * The csVirtual section must be held by caller.
780 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
781 int top_down, unsigned int vprot )
783 void *ptr;
784 NTSTATUS status;
786 if (base)
788 if (is_beyond_limit( base, size, address_space_limit ))
789 return STATUS_WORKING_SET_LIMIT_RANGE;
791 switch (wine_mmap_is_in_reserved_area( base, size ))
793 case -1: /* partially in a reserved area */
794 return STATUS_CONFLICTING_ADDRESSES;
796 case 0: /* not in a reserved area, do a normal allocation */
797 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
799 if (errno == ENOMEM) return STATUS_NO_MEMORY;
800 return STATUS_INVALID_PARAMETER;
802 if (ptr != base)
804 /* We couldn't get the address we wanted */
805 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
806 else munmap( ptr, size );
807 return STATUS_CONFLICTING_ADDRESSES;
809 break;
811 default:
812 case 1: /* in a reserved area, make sure the address is available */
813 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
814 /* replace the reserved area by our mapping */
815 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
816 return STATUS_INVALID_PARAMETER;
817 break;
819 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
821 else
823 size_t view_size = size + mask + 1;
824 struct alloc_area alloc;
826 alloc.size = size;
827 alloc.mask = mask;
828 alloc.top_down = top_down;
829 alloc.limit = user_space_limit;
830 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
832 ptr = alloc.result;
833 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
834 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
835 return STATUS_INVALID_PARAMETER;
836 goto done;
839 for (;;)
841 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
843 if (errno == ENOMEM) return STATUS_NO_MEMORY;
844 return STATUS_INVALID_PARAMETER;
846 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
847 /* if we got something beyond the user limit, unmap it and retry */
848 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
849 else break;
851 ptr = unmap_extra_space( ptr, view_size, size, mask );
853 done:
854 status = create_view( view_ret, ptr, size, vprot );
855 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
856 return status;
860 /***********************************************************************
861 * map_file_into_view
863 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
864 * The csVirtual section must be held by caller.
866 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
867 off_t offset, unsigned int vprot, BOOL removable )
869 void *ptr;
870 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
871 unsigned int flags = MAP_FIXED | ((vprot & VPROT_WRITECOPY) ? MAP_PRIVATE : MAP_SHARED);
873 assert( start < view->size );
874 assert( start + size <= view->size );
876 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (vprot & VPROT_READ))
878 TRACE( "forcing exec permission on mapping %p-%p\n",
879 (char *)view->base + start, (char *)view->base + start + size - 1 );
880 prot |= PROT_EXEC;
883 /* only try mmap if media is not removable (or if we require write access) */
884 if (!removable || (flags & MAP_SHARED))
886 if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
887 goto done;
889 if ((errno == EPERM) && (prot & PROT_EXEC))
890 ERR( "failed to set %08x protection on file map, noexec filesystem?\n", prot );
892 /* mmap() failed; if this is because the file offset is not */
893 /* page-aligned (EINVAL), or because the underlying filesystem */
894 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
895 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
896 if (flags & MAP_SHARED) /* we cannot fake shared mappings */
898 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
899 ERR( "shared writable mmap not supported, broken filesystem?\n" );
900 return STATUS_NOT_SUPPORTED;
904 /* Reserve the memory with an anonymous mmap */
905 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
906 if (ptr == (void *)-1) return FILE_GetNtStatus();
907 /* Now read in the file */
908 pread( fd, ptr, size, offset );
909 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
910 done:
911 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
912 return STATUS_SUCCESS;
916 /***********************************************************************
917 * get_committed_size
919 * Get the size of the committed range starting at base.
920 * Also return the protections for the first page.
922 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
924 SIZE_T i, start;
926 start = ((char *)base - (char *)view->base) >> page_shift;
927 *vprot = view->prot[start];
929 if (view->mapping && !(view->protect & VPROT_COMMITTED))
931 SIZE_T ret = 0;
932 SERVER_START_REQ( get_mapping_committed_range )
934 req->handle = wine_server_obj_handle( view->mapping );
935 req->offset = start << page_shift;
936 if (!wine_server_call( req ))
938 ret = reply->size;
939 if (reply->committed)
941 *vprot |= VPROT_COMMITTED;
942 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
946 SERVER_END_REQ;
947 return ret;
949 for (i = start + 1; i < view->size >> page_shift; i++)
950 if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
951 return (i - start) << page_shift;
955 /***********************************************************************
956 * decommit_view
958 * Decommit some pages of a given view.
959 * The csVirtual section must be held by caller.
961 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
963 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
965 BYTE *p = view->prot + (start >> page_shift);
966 size >>= page_shift;
967 while (size--) *p++ &= ~VPROT_COMMITTED;
968 return STATUS_SUCCESS;
970 return FILE_GetNtStatus();
974 /***********************************************************************
975 * allocate_dos_memory
977 * Allocate the DOS memory range.
979 static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
981 size_t size;
982 void *addr = NULL;
983 void * const low_64k = (void *)0x10000;
984 const size_t dosmem_size = 0x110000;
985 int unix_prot = VIRTUAL_GetUnixProt( vprot );
986 struct list *ptr;
988 /* check for existing view */
990 if ((ptr = list_head( &views_list )))
992 struct file_view *first_view = LIST_ENTRY( ptr, struct file_view, entry );
993 if (first_view->base < (void *)dosmem_size) return STATUS_CONFLICTING_ADDRESSES;
996 /* check without the first 64K */
998 if (wine_mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
1000 addr = wine_anon_mmap( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
1001 if (addr != low_64k)
1003 if (addr != (void *)-1) munmap( addr, dosmem_size - 0x10000 );
1004 return map_view( view, NULL, dosmem_size, 0xffff, 0, vprot );
1008 /* now try to allocate the low 64K too */
1010 if (wine_mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
1012 addr = wine_anon_mmap( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
1013 if (addr == (void *)page_size)
1015 if (!wine_anon_mmap( NULL, page_size, unix_prot, MAP_FIXED ))
1017 addr = NULL;
1018 TRACE( "successfully mapped low 64K range\n" );
1020 else TRACE( "failed to map page 0\n" );
1022 else
1024 if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
1025 addr = low_64k;
1026 TRACE( "failed to map low 64K range\n" );
1030 /* now reserve the whole range */
1032 size = (char *)dosmem_size - (char *)addr;
1033 wine_anon_mmap( addr, size, unix_prot, MAP_FIXED );
1034 return create_view( view, addr, size, vprot );
1038 /***********************************************************************
1039 * stat_mapping_file
1041 * Stat the underlying file for a memory view.
1043 static NTSTATUS stat_mapping_file( struct file_view *view, struct stat *st )
1045 NTSTATUS status;
1046 int unix_fd, needs_close;
1048 if (!view->mapping) return STATUS_NOT_MAPPED_VIEW;
1049 if (!(status = server_get_unix_fd( view->mapping, 0, &unix_fd, &needs_close, NULL, NULL )))
1051 if (fstat( unix_fd, st ) == -1) status = FILE_GetNtStatus();
1052 if (needs_close) close( unix_fd );
1054 return status;
1058 /***********************************************************************
1059 * map_image
1061 * Map an executable (PE format) image into memory.
1063 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
1064 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, unsigned int map_vprot, PVOID *addr_ptr )
1066 IMAGE_DOS_HEADER *dos;
1067 IMAGE_NT_HEADERS *nt;
1068 IMAGE_SECTION_HEADER sections[96];
1069 IMAGE_SECTION_HEADER *sec;
1070 IMAGE_DATA_DIRECTORY *imports;
1071 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
1072 int i;
1073 off_t pos;
1074 sigset_t sigset;
1075 struct stat st;
1076 struct file_view *view = NULL;
1077 char *ptr, *header_end, *header_start;
1078 INT_PTR delta = 0;
1080 /* zero-map the whole range */
1082 server_enter_uninterrupted_section( &csVirtual, &sigset );
1084 if (base >= (char *)address_space_start) /* make sure the DOS area remains free */
1085 status = map_view( &view, base, total_size, mask, FALSE,
1086 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1088 if (status != STATUS_SUCCESS)
1089 status = map_view( &view, NULL, total_size, mask, FALSE,
1090 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1092 if (status != STATUS_SUCCESS) goto error;
1094 ptr = view->base;
1095 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
1097 /* map the header */
1099 if (fstat( fd, &st ) == -1)
1101 status = FILE_GetNtStatus();
1102 goto error;
1104 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
1105 if (!st.st_size) goto error;
1106 header_size = min( header_size, st.st_size );
1107 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1108 !dup_mapping ) != STATUS_SUCCESS) goto error;
1109 dos = (IMAGE_DOS_HEADER *)ptr;
1110 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1111 header_end = ptr + ROUND_SIZE( 0, header_size );
1112 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1113 if ((char *)(nt + 1) > header_end) goto error;
1114 header_start = (char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader;
1115 if (nt->FileHeader.NumberOfSections > sizeof(sections)/sizeof(*sections)) goto error;
1116 if (header_start + sizeof(*sections) * nt->FileHeader.NumberOfSections > header_end) goto error;
1117 /* Some applications (e.g. the Steam version of Borderlands) map over the top of the section headers,
1118 * copying the headers into local memory is necessary to properly load such applications. */
1119 memcpy(sections, header_start, sizeof(*sections) * nt->FileHeader.NumberOfSections);
1120 sec = sections;
1122 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
1123 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
1125 /* check for non page-aligned binary */
1127 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1129 /* unaligned sections, this happens for native subsystem binaries */
1130 /* in that case Windows simply maps in the whole file */
1132 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1133 !dup_mapping ) != STATUS_SUCCESS) goto error;
1135 /* check that all sections are loaded at the right offset */
1136 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1137 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1139 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1140 goto error; /* Windows refuses to load in that case too */
1143 /* set the image protections */
1144 VIRTUAL_SetProt( view, ptr, total_size,
1145 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1147 /* no relocations are performed on non page-aligned binaries */
1148 goto done;
1152 /* map all the sections */
1154 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1156 static const SIZE_T sector_align = 0x1ff;
1157 SIZE_T map_size, file_start, file_size, end;
1159 if (!sec->Misc.VirtualSize)
1160 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1161 else
1162 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1164 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1165 file_start = sec->PointerToRawData & ~sector_align;
1166 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1167 if (file_size > map_size) file_size = map_size;
1169 /* a few sanity checks */
1170 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1171 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1173 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1174 sec->Name, sec->VirtualAddress, map_size, total_size );
1175 goto error;
1178 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1179 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1181 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1182 sec->Name, ptr + sec->VirtualAddress,
1183 sec->PointerToRawData, (int)pos, file_size, map_size,
1184 sec->Characteristics );
1185 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1186 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE, FALSE ) != STATUS_SUCCESS)
1188 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1189 goto error;
1192 /* check if the import directory falls inside this section */
1193 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1194 imports->VirtualAddress < sec->VirtualAddress + map_size)
1196 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1197 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1198 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1199 if (end > base)
1200 map_file_into_view( view, shared_fd, base, end - base,
1201 pos + (base - sec->VirtualAddress),
1202 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY, FALSE );
1204 pos += map_size;
1205 continue;
1208 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1209 sec->Name, ptr + sec->VirtualAddress,
1210 sec->PointerToRawData, sec->SizeOfRawData,
1211 sec->Misc.VirtualSize, sec->Characteristics );
1213 if (!sec->PointerToRawData || !file_size) continue;
1215 /* Note: if the section is not aligned properly map_file_into_view will magically
1216 * fall back to read(), so we don't need to check anything here.
1218 end = file_start + file_size;
1219 if (sec->PointerToRawData >= st.st_size ||
1220 end > ((st.st_size + sector_align) & ~sector_align) ||
1221 end < file_start ||
1222 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1223 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1224 !dup_mapping ) != STATUS_SUCCESS)
1226 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1227 goto error;
1230 if (file_size & page_mask)
1232 end = ROUND_SIZE( 0, file_size );
1233 if (end > map_size) end = map_size;
1234 TRACE_(module)("clearing %p - %p\n",
1235 ptr + sec->VirtualAddress + file_size,
1236 ptr + sec->VirtualAddress + end );
1237 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1242 /* perform base relocation, if necessary */
1244 if (ptr != base &&
1245 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1246 !NtCurrentTeb()->Peb->ImageBaseAddress) )
1248 IMAGE_BASE_RELOCATION *rel, *end;
1249 const IMAGE_DATA_DIRECTORY *relocs;
1251 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1253 WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1254 base, ptr );
1255 status = STATUS_CONFLICTING_ADDRESSES;
1256 goto error;
1259 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1260 base, base + total_size, ptr, ptr + total_size );
1262 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1263 rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1264 end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1265 delta = ptr - base;
1267 while (rel < end - 1 && rel->SizeOfBlock)
1269 if (rel->VirtualAddress >= total_size)
1271 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1272 status = STATUS_ACCESS_VIOLATION;
1273 goto error;
1275 rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1276 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1277 (USHORT *)(rel + 1), delta );
1278 if (!rel) goto error;
1282 /* set the image protections */
1284 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1286 sec = sections;
1287 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1289 SIZE_T size;
1290 BYTE vprot = VPROT_COMMITTED;
1292 if (sec->Misc.VirtualSize)
1293 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1294 else
1295 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1297 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1298 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_WRITECOPY;
1299 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1301 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1302 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1303 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1304 vprot |= VPROT_EXEC;
1306 if (!VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot ) && (vprot & VPROT_EXEC))
1307 ERR( "failed to set %08x protection on section %.8s, noexec filesystem?\n",
1308 sec->Characteristics, sec->Name );
1311 done:
1312 view->mapping = dup_mapping;
1313 view->map_protect = map_vprot;
1314 server_leave_uninterrupted_section( &csVirtual, &sigset );
1316 *addr_ptr = ptr;
1317 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1318 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1319 #endif
1320 if (ptr != base) return STATUS_IMAGE_NOT_AT_BASE;
1321 return STATUS_SUCCESS;
1323 error:
1324 if (view) delete_view( view );
1325 server_leave_uninterrupted_section( &csVirtual, &sigset );
1326 if (dup_mapping) NtClose( dup_mapping );
1327 return status;
1331 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1332 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1334 void **heap_base = arg;
1336 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1337 if (size < VIRTUAL_HEAP_SIZE) return 0;
1338 if (is_win64 && base < (void *)0x80000000) return 0;
1339 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1340 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1341 return (*heap_base != (void *)-1);
1344 /***********************************************************************
1345 * virtual_init
1347 void virtual_init(void)
1349 const char *preload;
1350 void *heap_base;
1351 size_t size;
1352 struct file_view *heap_view;
1354 #if !defined(__i386__) && !defined(__x86_64__)
1355 page_size = sysconf( _SC_PAGESIZE );
1356 page_mask = page_size - 1;
1357 /* Make sure we have a power of 2 */
1358 assert( !(page_size & page_mask) );
1359 page_shift = 0;
1360 while ((1 << page_shift) != page_size) page_shift++;
1361 user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1362 #endif /* page_mask */
1363 if ((preload = getenv("WINEPRELOADRESERVE")))
1365 unsigned long start, end;
1366 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1368 preload_reserve_start = (void *)start;
1369 preload_reserve_end = (void *)end;
1373 /* try to find space in a reserved area for the virtual heap */
1374 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1375 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1377 assert( heap_base != (void *)-1 );
1378 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1379 VIRTUAL_HEAP_SIZE, NULL, NULL );
1380 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1382 /* make the DOS area accessible (except the low 64K) to hide bugs in broken apps like Excel 2003 */
1383 size = (char *)address_space_start - (char *)0x10000;
1384 if (size && wine_mmap_is_in_reserved_area( (void*)0x10000, size ) == 1)
1385 wine_anon_mmap( (void *)0x10000, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1389 /***********************************************************************
1390 * virtual_init_threading
1392 void virtual_init_threading(void)
1394 use_locks = TRUE;
1398 /***********************************************************************
1399 * virtual_get_system_info
1401 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1403 info->unknown = 0;
1404 info->KeMaximumIncrement = 0; /* FIXME */
1405 info->PageSize = page_size;
1406 info->MmLowestPhysicalPage = 1;
1407 info->MmHighestPhysicalPage = 0x7fffffff / page_size;
1408 info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
1409 info->AllocationGranularity = get_mask(0) + 1;
1410 info->LowestUserAddress = (void *)0x10000;
1411 info->HighestUserAddress = (char *)user_space_limit - 1;
1412 info->ActiveProcessorsAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1413 info->NumberOfProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1417 /***********************************************************************
1418 * virtual_create_builtin_view
1420 NTSTATUS virtual_create_builtin_view( void *module )
1422 NTSTATUS status;
1423 sigset_t sigset;
1424 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1425 SIZE_T size = nt->OptionalHeader.SizeOfImage;
1426 IMAGE_SECTION_HEADER *sec;
1427 struct file_view *view;
1428 void *base;
1429 int i;
1431 size = ROUND_SIZE( module, size );
1432 base = ROUND_ADDR( module, page_mask );
1433 server_enter_uninterrupted_section( &csVirtual, &sigset );
1434 status = create_view( &view, base, size, VPROT_SYSTEM | VPROT_IMAGE |
1435 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1436 if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
1437 server_leave_uninterrupted_section( &csVirtual, &sigset );
1439 if (status) return status;
1441 /* The PE header is always read-only, no write, no execute. */
1442 view->prot[0] = VPROT_COMMITTED | VPROT_READ;
1444 sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
1445 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1447 BYTE flags = VPROT_COMMITTED;
1449 if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
1450 if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
1451 if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
1452 memset (view->prot + (sec[i].VirtualAddress >> page_shift), flags,
1453 ROUND_SIZE( sec[i].VirtualAddress, sec[i].Misc.VirtualSize ) >> page_shift );
1456 return status;
1460 /***********************************************************************
1461 * virtual_alloc_thread_stack
1463 NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1465 struct file_view *view;
1466 NTSTATUS status;
1467 sigset_t sigset;
1468 SIZE_T size;
1470 if (!reserve_size || !commit_size)
1472 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1473 if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
1474 if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1477 size = max( reserve_size, commit_size );
1478 if (size < 1024 * 1024) size = 1024 * 1024; /* Xlib needs a large stack */
1479 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1481 server_enter_uninterrupted_section( &csVirtual, &sigset );
1483 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1484 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1485 goto done;
1487 #ifdef VALGRIND_STACK_REGISTER
1488 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1489 #endif
1491 /* setup no access guard page */
1492 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1493 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1494 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1496 /* note: limit is lower than base since the stack grows down */
1497 teb->DeallocationStack = view->base;
1498 teb->Tib.StackBase = (char *)view->base + view->size;
1499 teb->Tib.StackLimit = (char *)view->base + 2 * page_size;
1500 done:
1501 server_leave_uninterrupted_section( &csVirtual, &sigset );
1502 return status;
1506 /***********************************************************************
1507 * virtual_clear_thread_stack
1509 * Clear the stack contents before calling the main entry point, some broken apps need that.
1511 void virtual_clear_thread_stack(void)
1513 void *stack = NtCurrentTeb()->Tib.StackLimit;
1514 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1516 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1517 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1521 /***********************************************************************
1522 * virtual_handle_fault
1524 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err )
1526 struct file_view *view;
1527 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1528 sigset_t sigset;
1530 server_enter_uninterrupted_section( &csVirtual, &sigset );
1531 if ((view = VIRTUAL_FindView( addr, 0 )))
1533 void *page = ROUND_ADDR( addr, page_mask );
1534 BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1535 if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1537 if (*vprot & VPROT_WRITEWATCH)
1539 *vprot &= ~VPROT_WRITEWATCH;
1540 VIRTUAL_SetProt( view, page, page_size, *vprot );
1542 /* ignore fault if page is writable now */
1543 if (VIRTUAL_GetUnixProt( *vprot ) & PROT_WRITE) ret = STATUS_SUCCESS;
1545 if (*vprot & VPROT_GUARD)
1547 VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1548 ret = STATUS_GUARD_PAGE_VIOLATION;
1551 server_leave_uninterrupted_section( &csVirtual, &sigset );
1552 return ret;
1557 /***********************************************************************
1558 * virtual_is_valid_code_address
1560 BOOL virtual_is_valid_code_address( const void *addr, SIZE_T size )
1562 struct file_view *view;
1563 BOOL ret = FALSE;
1564 sigset_t sigset;
1566 server_enter_uninterrupted_section( &csVirtual, &sigset );
1567 if ((view = VIRTUAL_FindView( addr, size )))
1568 ret = !(view->protect & VPROT_SYSTEM); /* system views are not visible to the app */
1569 server_leave_uninterrupted_section( &csVirtual, &sigset );
1570 return ret;
1574 /***********************************************************************
1575 * virtual_handle_stack_fault
1577 * Handle an access fault inside the current thread stack.
1578 * Called from inside a signal handler.
1580 BOOL virtual_handle_stack_fault( void *addr )
1582 struct file_view *view;
1583 BOOL ret = FALSE;
1585 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1586 if ((view = VIRTUAL_FindView( addr, 0 )))
1588 void *page = ROUND_ADDR( addr, page_mask );
1589 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1590 if (vprot & VPROT_GUARD)
1592 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1593 NtCurrentTeb()->Tib.StackLimit = page;
1594 if ((char *)page >= (char *)NtCurrentTeb()->DeallocationStack + 2*page_size)
1596 vprot = view->prot[((char *)page - page_size - (char *)view->base) >> page_shift];
1597 VIRTUAL_SetProt( view, (char *)page - page_size, page_size, vprot | VPROT_GUARD );
1599 ret = TRUE;
1602 RtlLeaveCriticalSection( &csVirtual );
1603 return ret;
1607 /***********************************************************************
1608 * virtual_check_buffer_for_read
1610 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
1612 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
1614 if (!size) return TRUE;
1615 if (!ptr) return FALSE;
1617 __TRY
1619 volatile const char *p = ptr;
1620 char dummy __attribute__((unused));
1621 SIZE_T count = size;
1623 while (count > page_size)
1625 dummy = *p;
1626 p += page_size;
1627 count -= page_size;
1629 dummy = p[0];
1630 dummy = p[count - 1];
1632 __EXCEPT_PAGE_FAULT
1634 return FALSE;
1636 __ENDTRY
1637 return TRUE;
1641 /***********************************************************************
1642 * virtual_check_buffer_for_write
1644 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
1646 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
1648 if (!size) return TRUE;
1649 if (!ptr) return FALSE;
1651 __TRY
1653 volatile char *p = ptr;
1654 SIZE_T count = size;
1656 while (count > page_size)
1658 *p |= 0;
1659 p += page_size;
1660 count -= page_size;
1662 p[0] |= 0;
1663 p[count - 1] |= 0;
1665 __EXCEPT_PAGE_FAULT
1667 return FALSE;
1669 __ENDTRY
1670 return TRUE;
1674 /***********************************************************************
1675 * virtual_uninterrupted_read_memory
1677 * Similar to NtReadVirtualMemory, but without wineserver calls. Moreover
1678 * permissions are checked before accessing each page, to ensure that no
1679 * exceptions can happen.
1681 SIZE_T virtual_uninterrupted_read_memory( const void *addr, void *buffer, SIZE_T size )
1683 struct file_view *view;
1684 sigset_t sigset;
1685 SIZE_T bytes_read = 0;
1687 if (!size) return 0;
1689 server_enter_uninterrupted_section( &csVirtual, &sigset );
1690 if ((view = VIRTUAL_FindView( addr, size )))
1692 if (!(view->protect & VPROT_SYSTEM))
1694 void *page = ROUND_ADDR( addr, page_mask );
1695 BYTE *p = view->prot + (((const char *)page - (const char *)view->base) >> page_shift);
1697 while (bytes_read < size && (VIRTUAL_GetUnixProt( *p++ ) & PROT_READ))
1699 SIZE_T block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
1700 memcpy( buffer, addr, block_size );
1702 addr = (const void *)((const char *)addr + block_size);
1703 buffer = (void *)((char *)buffer + block_size);
1704 bytes_read += block_size;
1708 server_leave_uninterrupted_section( &csVirtual, &sigset );
1709 return bytes_read;
1713 /***********************************************************************
1714 * virtual_uninterrupted_write_memory
1716 * Similar to NtWriteVirtualMemory, but without wineserver calls. Moreover
1717 * permissions are checked before accessing each page, to ensure that no
1718 * exceptions can happen.
1720 SIZE_T virtual_uninterrupted_write_memory( void *addr, const void *buffer, SIZE_T size )
1722 struct file_view *view;
1723 sigset_t sigset;
1724 SIZE_T bytes_written = 0;
1726 if (!size) return 0;
1728 server_enter_uninterrupted_section( &csVirtual, &sigset );
1729 if ((view = VIRTUAL_FindView( addr, size )))
1731 if (!(view->protect & VPROT_SYSTEM))
1733 void *page = ROUND_ADDR( addr, page_mask );
1734 BYTE *p = view->prot + (((const char *)page - (const char *)view->base) >> page_shift);
1736 while (bytes_written < size && (VIRTUAL_GetUnixProt( *p++ ) & PROT_WRITE))
1738 SIZE_T block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
1739 memcpy( addr, buffer, block_size );
1741 addr = (void *)((char *)addr + block_size);
1742 buffer = (const void *)((const char *)buffer + block_size);
1743 bytes_written += block_size;
1747 server_leave_uninterrupted_section( &csVirtual, &sigset );
1748 return bytes_written;
1752 /***********************************************************************
1753 * VIRTUAL_SetForceExec
1755 * Whether to force exec prot on all views.
1757 void VIRTUAL_SetForceExec( BOOL enable )
1759 struct file_view *view;
1760 sigset_t sigset;
1762 server_enter_uninterrupted_section( &csVirtual, &sigset );
1763 if (!force_exec_prot != !enable) /* change all existing views */
1765 force_exec_prot = enable;
1767 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1769 UINT i, count;
1770 char *addr = view->base;
1771 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1772 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1774 if (view->protect & VPROT_NOEXEC) continue;
1775 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1777 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1778 if (prot == unix_prot) continue;
1779 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1781 TRACE( "%s exec prot for %p-%p\n",
1782 force_exec_prot ? "enabling" : "disabling",
1783 addr, addr + (count << page_shift) - 1 );
1784 mprotect( addr, count << page_shift,
1785 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1787 addr += (count << page_shift);
1788 unix_prot = prot;
1789 count = 0;
1791 if (count)
1793 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1795 TRACE( "%s exec prot for %p-%p\n",
1796 force_exec_prot ? "enabling" : "disabling",
1797 addr, addr + (count << page_shift) - 1 );
1798 mprotect( addr, count << page_shift,
1799 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1804 server_leave_uninterrupted_section( &csVirtual, &sigset );
1807 struct free_range
1809 char *base;
1810 char *limit;
1813 /* free reserved areas above the limit; callback for wine_mmap_enum_reserved_areas */
1814 static int free_reserved_memory( void *base, size_t size, void *arg )
1816 struct free_range *range = arg;
1818 if ((char *)base >= range->limit) return 0;
1819 if ((char *)base + size <= range->base) return 0;
1820 if ((char *)base < range->base)
1822 size -= range->base - (char *)base;
1823 base = range->base;
1825 if ((char *)base + size > range->limit) size = range->limit - (char *)base;
1826 remove_reserved_area( base, size );
1827 return 1; /* stop enumeration since the list has changed */
1830 /***********************************************************************
1831 * virtual_release_address_space
1833 * Release some address space once we have loaded and initialized the app.
1835 void virtual_release_address_space(void)
1837 struct free_range range;
1838 sigset_t sigset;
1840 if (is_win64) return;
1842 server_enter_uninterrupted_section( &csVirtual, &sigset );
1844 range.base = (char *)0x82000000;
1845 range.limit = user_space_limit;
1847 if (range.limit > range.base)
1849 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
1851 else
1853 #ifndef __APPLE__ /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
1854 range.base = (char *)0x20000000;
1855 range.limit = (char *)0x7f000000;
1856 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
1857 #endif
1860 server_leave_uninterrupted_section( &csVirtual, &sigset );
1864 /***********************************************************************
1865 * virtual_set_large_address_space
1867 * Enable use of a large address space when allowed by the application.
1869 void virtual_set_large_address_space(void)
1871 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1873 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE)) return;
1874 /* no large address space on win9x */
1875 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1877 user_space_limit = working_set_limit = address_space_limit;
1881 /***********************************************************************
1882 * NtAllocateVirtualMemory (NTDLL.@)
1883 * ZwAllocateVirtualMemory (NTDLL.@)
1885 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1886 SIZE_T *size_ptr, ULONG type, ULONG protect )
1888 void *base;
1889 unsigned int vprot;
1890 SIZE_T size = *size_ptr;
1891 SIZE_T mask = get_mask( zero_bits );
1892 NTSTATUS status = STATUS_SUCCESS;
1893 struct file_view *view;
1894 sigset_t sigset;
1896 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1898 if (!size) return STATUS_INVALID_PARAMETER;
1900 if (process != NtCurrentProcess())
1902 apc_call_t call;
1903 apc_result_t result;
1905 memset( &call, 0, sizeof(call) );
1907 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1908 call.virtual_alloc.addr = wine_server_client_ptr( *ret );
1909 call.virtual_alloc.size = *size_ptr;
1910 call.virtual_alloc.zero_bits = zero_bits;
1911 call.virtual_alloc.op_type = type;
1912 call.virtual_alloc.prot = protect;
1913 status = server_queue_process_apc( process, &call, &result );
1914 if (status != STATUS_SUCCESS) return status;
1916 if (result.virtual_alloc.status == STATUS_SUCCESS)
1918 *ret = wine_server_get_ptr( result.virtual_alloc.addr );
1919 *size_ptr = result.virtual_alloc.size;
1921 return result.virtual_alloc.status;
1924 /* Round parameters to a page boundary */
1926 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1928 if ((status = get_vprot_flags( protect, &vprot, FALSE ))) return status;
1929 if (vprot & VPROT_WRITECOPY) return STATUS_INVALID_PAGE_PROTECTION;
1930 vprot |= VPROT_VALLOC;
1931 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1933 if (*ret)
1935 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1936 base = ROUND_ADDR( *ret, mask );
1937 else
1938 base = ROUND_ADDR( *ret, page_mask );
1939 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1941 /* address 1 is magic to mean DOS area */
1942 if (!base && *ret == (void *)1 && size == 0x110000)
1944 server_enter_uninterrupted_section( &csVirtual, &sigset );
1945 status = allocate_dos_memory( &view, vprot );
1946 if (status == STATUS_SUCCESS)
1948 *ret = view->base;
1949 *size_ptr = view->size;
1951 server_leave_uninterrupted_section( &csVirtual, &sigset );
1952 return status;
1955 /* disallow low 64k, wrap-around and kernel space */
1956 if (((char *)base < (char *)0x10000) ||
1957 ((char *)base + size < (char *)base) ||
1958 is_beyond_limit( base, size, address_space_limit ))
1959 return STATUS_INVALID_PARAMETER;
1961 else
1963 base = NULL;
1964 size = (size + page_mask) & ~page_mask;
1967 /* Compute the alloc type flags */
1969 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
1970 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1972 WARN("called with wrong alloc type flags (%08x) !\n", type);
1973 return STATUS_INVALID_PARAMETER;
1976 /* Reserve the memory */
1978 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1980 if ((type & MEM_RESERVE) || !base)
1982 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
1983 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1984 if (status == STATUS_SUCCESS) base = view->base;
1986 else if (type & MEM_RESET)
1988 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1989 else madvise( base, size, MADV_DONTNEED );
1991 else /* commit the pages */
1993 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1994 else if (view->mapping && (view->protect & VPROT_COMMITTED)) status = STATUS_ALREADY_COMMITTED;
1995 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1996 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1998 SERVER_START_REQ( add_mapping_committed_range )
2000 req->handle = wine_server_obj_handle( view->mapping );
2001 req->offset = (char *)base - (char *)view->base;
2002 req->size = size;
2003 wine_server_call( req );
2005 SERVER_END_REQ;
2009 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
2011 if (status == STATUS_SUCCESS)
2013 *ret = base;
2014 *size_ptr = size;
2016 return status;
2020 /***********************************************************************
2021 * NtFreeVirtualMemory (NTDLL.@)
2022 * ZwFreeVirtualMemory (NTDLL.@)
2024 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
2026 struct file_view *view;
2027 char *base;
2028 sigset_t sigset;
2029 NTSTATUS status = STATUS_SUCCESS;
2030 LPVOID addr = *addr_ptr;
2031 SIZE_T size = *size_ptr;
2033 TRACE("%p %p %08lx %x\n", process, addr, size, type );
2035 if (process != NtCurrentProcess())
2037 apc_call_t call;
2038 apc_result_t result;
2040 memset( &call, 0, sizeof(call) );
2042 call.virtual_free.type = APC_VIRTUAL_FREE;
2043 call.virtual_free.addr = wine_server_client_ptr( addr );
2044 call.virtual_free.size = size;
2045 call.virtual_free.op_type = type;
2046 status = server_queue_process_apc( process, &call, &result );
2047 if (status != STATUS_SUCCESS) return status;
2049 if (result.virtual_free.status == STATUS_SUCCESS)
2051 *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
2052 *size_ptr = result.virtual_free.size;
2054 return result.virtual_free.status;
2057 /* Fix the parameters */
2059 size = ROUND_SIZE( addr, size );
2060 base = ROUND_ADDR( addr, page_mask );
2062 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
2063 if (!base) return STATUS_INVALID_PARAMETER;
2065 server_enter_uninterrupted_section( &csVirtual, &sigset );
2067 if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
2069 status = STATUS_INVALID_PARAMETER;
2071 else if (type == MEM_RELEASE)
2073 /* Free the pages */
2075 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
2076 else
2078 delete_view( view );
2079 *addr_ptr = base;
2080 *size_ptr = size;
2083 else if (type == MEM_DECOMMIT)
2085 status = decommit_pages( view, base - (char *)view->base, size );
2086 if (status == STATUS_SUCCESS)
2088 *addr_ptr = base;
2089 *size_ptr = size;
2092 else
2094 WARN("called with wrong free type flags (%08x) !\n", type);
2095 status = STATUS_INVALID_PARAMETER;
2098 server_leave_uninterrupted_section( &csVirtual, &sigset );
2099 return status;
2102 static ULONG map_protection_to_access( ULONG vprot )
2104 vprot &= VPROT_READ | VPROT_WRITE | VPROT_EXEC | VPROT_WRITECOPY;
2105 if (vprot & VPROT_EXEC)
2107 if (vprot & VPROT_WRITE) vprot |= VPROT_WRITECOPY;
2109 else vprot &= ~VPROT_WRITECOPY;
2110 return vprot;
2113 static BOOL is_compatible_protection( const struct file_view *view, ULONG new_prot )
2115 ULONG view_prot, map_prot;
2117 view_prot = map_protection_to_access( view->protect );
2118 new_prot = map_protection_to_access( new_prot );
2120 if (view_prot == new_prot) return TRUE;
2121 if (!view_prot) return FALSE;
2123 if ((view_prot & new_prot) != new_prot) return FALSE;
2125 map_prot = map_protection_to_access( view->map_protect );
2126 if ((map_prot & new_prot) == new_prot) return TRUE;
2128 return FALSE;
2131 /***********************************************************************
2132 * NtProtectVirtualMemory (NTDLL.@)
2133 * ZwProtectVirtualMemory (NTDLL.@)
2135 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
2136 ULONG new_prot, ULONG *old_prot )
2138 struct file_view *view;
2139 sigset_t sigset;
2140 NTSTATUS status = STATUS_SUCCESS;
2141 char *base;
2142 BYTE vprot;
2143 unsigned int new_vprot;
2144 SIZE_T size = *size_ptr;
2145 LPVOID addr = *addr_ptr;
2147 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
2149 if (process != NtCurrentProcess())
2151 apc_call_t call;
2152 apc_result_t result;
2154 memset( &call, 0, sizeof(call) );
2156 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
2157 call.virtual_protect.addr = wine_server_client_ptr( addr );
2158 call.virtual_protect.size = size;
2159 call.virtual_protect.prot = new_prot;
2160 status = server_queue_process_apc( process, &call, &result );
2161 if (status != STATUS_SUCCESS) return status;
2163 if (result.virtual_protect.status == STATUS_SUCCESS)
2165 *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
2166 *size_ptr = result.virtual_protect.size;
2167 if (old_prot) *old_prot = result.virtual_protect.prot;
2169 return result.virtual_protect.status;
2172 /* Fix the parameters */
2174 size = ROUND_SIZE( addr, size );
2175 base = ROUND_ADDR( addr, page_mask );
2177 server_enter_uninterrupted_section( &csVirtual, &sigset );
2179 if ((view = VIRTUAL_FindView( base, size )))
2181 /* Make sure all the pages are committed */
2182 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2184 if (!(status = get_vprot_flags( new_prot, &new_vprot, view->protect & VPROT_IMAGE )))
2186 if ((new_vprot & VPROT_WRITECOPY) && (view->protect & VPROT_VALLOC))
2187 status = STATUS_INVALID_PAGE_PROTECTION;
2188 else
2190 if (!view->mapping || is_compatible_protection( view, new_vprot ))
2192 new_vprot |= VPROT_COMMITTED;
2193 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
2194 if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
2196 else status = STATUS_INVALID_PAGE_PROTECTION;
2200 else status = STATUS_NOT_COMMITTED;
2202 else status = STATUS_INVALID_PARAMETER;
2204 server_leave_uninterrupted_section( &csVirtual, &sigset );
2206 if (status == STATUS_SUCCESS)
2208 *addr_ptr = base;
2209 *size_ptr = size;
2211 return status;
2215 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
2216 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
2218 MEMORY_BASIC_INFORMATION *info = arg;
2219 void *end = (char *)start + size;
2221 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
2223 if (info->BaseAddress >= end)
2225 if (info->AllocationBase < end) info->AllocationBase = end;
2226 return 0;
2229 if (info->BaseAddress >= start || start <= address_space_start)
2231 /* it's a real free area */
2232 info->State = MEM_FREE;
2233 info->Protect = PAGE_NOACCESS;
2234 info->AllocationBase = 0;
2235 info->AllocationProtect = 0;
2236 info->Type = 0;
2237 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
2238 info->RegionSize = (char *)end - (char *)info->BaseAddress;
2240 else /* outside of the reserved area, pretend it's allocated */
2242 info->RegionSize = (char *)start - (char *)info->BaseAddress;
2243 info->State = MEM_RESERVE;
2244 info->Protect = PAGE_NOACCESS;
2245 info->AllocationProtect = PAGE_NOACCESS;
2246 info->Type = MEM_PRIVATE;
2248 return 1;
2251 #define UNIMPLEMENTED_INFO_CLASS(c) \
2252 case c: \
2253 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
2254 return STATUS_INVALID_INFO_CLASS
2256 /***********************************************************************
2257 * NtQueryVirtualMemory (NTDLL.@)
2258 * ZwQueryVirtualMemory (NTDLL.@)
2260 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
2261 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2262 SIZE_T len, SIZE_T *res_len )
2264 struct file_view *view;
2265 char *base, *alloc_base = 0;
2266 struct list *ptr;
2267 SIZE_T size = 0;
2268 MEMORY_BASIC_INFORMATION *info = buffer;
2269 sigset_t sigset;
2271 if (info_class != MemoryBasicInformation)
2273 switch(info_class)
2275 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
2276 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
2277 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
2279 default:
2280 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
2281 process, addr, info_class, buffer, len, res_len);
2282 return STATUS_INVALID_INFO_CLASS;
2286 if (process != NtCurrentProcess())
2288 NTSTATUS status;
2289 apc_call_t call;
2290 apc_result_t result;
2292 memset( &call, 0, sizeof(call) );
2294 call.virtual_query.type = APC_VIRTUAL_QUERY;
2295 call.virtual_query.addr = wine_server_client_ptr( addr );
2296 status = server_queue_process_apc( process, &call, &result );
2297 if (status != STATUS_SUCCESS) return status;
2299 if (result.virtual_query.status == STATUS_SUCCESS)
2301 info->BaseAddress = wine_server_get_ptr( result.virtual_query.base );
2302 info->AllocationBase = wine_server_get_ptr( result.virtual_query.alloc_base );
2303 info->RegionSize = result.virtual_query.size;
2304 info->Protect = result.virtual_query.prot;
2305 info->AllocationProtect = result.virtual_query.alloc_prot;
2306 info->State = (DWORD)result.virtual_query.state << 12;
2307 info->Type = (DWORD)result.virtual_query.alloc_type << 16;
2308 if (info->RegionSize != result.virtual_query.size) /* truncated */
2309 return STATUS_INVALID_PARAMETER; /* FIXME */
2310 if (res_len) *res_len = sizeof(*info);
2312 return result.virtual_query.status;
2315 base = ROUND_ADDR( addr, page_mask );
2317 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2319 /* Find the view containing the address */
2321 server_enter_uninterrupted_section( &csVirtual, &sigset );
2322 ptr = list_head( &views_list );
2323 for (;;)
2325 if (!ptr)
2327 size = (char *)working_set_limit - alloc_base;
2328 view = NULL;
2329 break;
2331 view = LIST_ENTRY( ptr, struct file_view, entry );
2332 if ((char *)view->base > base)
2334 size = (char *)view->base - alloc_base;
2335 view = NULL;
2336 break;
2338 if ((char *)view->base + view->size > base)
2340 alloc_base = view->base;
2341 size = view->size;
2342 break;
2344 alloc_base = (char *)view->base + view->size;
2345 ptr = list_next( &views_list, ptr );
2348 /* Fill the info structure */
2350 info->AllocationBase = alloc_base;
2351 info->BaseAddress = base;
2352 info->RegionSize = size - (base - alloc_base);
2354 if (!view)
2356 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2358 /* not in a reserved area at all, pretend it's allocated */
2359 #ifdef __i386__
2360 if (base >= (char *)address_space_start)
2362 info->State = MEM_RESERVE;
2363 info->Protect = PAGE_NOACCESS;
2364 info->AllocationProtect = PAGE_NOACCESS;
2365 info->Type = MEM_PRIVATE;
2367 else
2368 #endif
2370 info->State = MEM_FREE;
2371 info->Protect = PAGE_NOACCESS;
2372 info->AllocationBase = 0;
2373 info->AllocationProtect = 0;
2374 info->Type = 0;
2378 else
2380 BYTE vprot;
2381 SIZE_T range_size = get_committed_size( view, base, &vprot );
2383 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2384 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2385 info->AllocationBase = alloc_base;
2386 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2387 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2388 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2389 else info->Type = MEM_MAPPED;
2390 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2391 if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2392 info->RegionSize = size - (base - alloc_base);
2394 server_leave_uninterrupted_section( &csVirtual, &sigset );
2396 if (res_len) *res_len = sizeof(*info);
2397 return STATUS_SUCCESS;
2401 /***********************************************************************
2402 * NtLockVirtualMemory (NTDLL.@)
2403 * ZwLockVirtualMemory (NTDLL.@)
2405 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2407 NTSTATUS status = STATUS_SUCCESS;
2409 if (process != NtCurrentProcess())
2411 apc_call_t call;
2412 apc_result_t result;
2414 memset( &call, 0, sizeof(call) );
2416 call.virtual_lock.type = APC_VIRTUAL_LOCK;
2417 call.virtual_lock.addr = wine_server_client_ptr( *addr );
2418 call.virtual_lock.size = *size;
2419 status = server_queue_process_apc( process, &call, &result );
2420 if (status != STATUS_SUCCESS) return status;
2422 if (result.virtual_lock.status == STATUS_SUCCESS)
2424 *addr = wine_server_get_ptr( result.virtual_lock.addr );
2425 *size = result.virtual_lock.size;
2427 return result.virtual_lock.status;
2430 *size = ROUND_SIZE( *addr, *size );
2431 *addr = ROUND_ADDR( *addr, page_mask );
2433 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2434 return status;
2438 /***********************************************************************
2439 * NtUnlockVirtualMemory (NTDLL.@)
2440 * ZwUnlockVirtualMemory (NTDLL.@)
2442 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2444 NTSTATUS status = STATUS_SUCCESS;
2446 if (process != NtCurrentProcess())
2448 apc_call_t call;
2449 apc_result_t result;
2451 memset( &call, 0, sizeof(call) );
2453 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2454 call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2455 call.virtual_unlock.size = *size;
2456 status = server_queue_process_apc( process, &call, &result );
2457 if (status != STATUS_SUCCESS) return status;
2459 if (result.virtual_unlock.status == STATUS_SUCCESS)
2461 *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2462 *size = result.virtual_unlock.size;
2464 return result.virtual_unlock.status;
2467 *size = ROUND_SIZE( *addr, *size );
2468 *addr = ROUND_ADDR( *addr, page_mask );
2470 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2471 return status;
2475 /***********************************************************************
2476 * NtCreateSection (NTDLL.@)
2477 * ZwCreateSection (NTDLL.@)
2479 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2480 const LARGE_INTEGER *size, ULONG protect,
2481 ULONG sec_flags, HANDLE file )
2483 NTSTATUS ret;
2484 unsigned int vprot;
2485 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2486 struct security_descriptor *sd = NULL;
2487 struct object_attributes objattr;
2489 /* Check parameters */
2491 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2493 if ((ret = get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE ))) return ret;
2495 objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
2496 objattr.sd_len = 0;
2497 objattr.name_len = len;
2498 if (attr)
2500 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2501 if (ret != STATUS_SUCCESS) return ret;
2504 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2505 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2506 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2508 /* Create the server object */
2510 SERVER_START_REQ( create_mapping )
2512 req->access = access;
2513 req->attributes = (attr) ? attr->Attributes : 0;
2514 req->file_handle = wine_server_obj_handle( file );
2515 req->size = size ? size->QuadPart : 0;
2516 req->protect = vprot;
2517 wine_server_add_data( req, &objattr, sizeof(objattr) );
2518 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2519 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2520 ret = wine_server_call( req );
2521 *handle = wine_server_ptr_handle( reply->handle );
2523 SERVER_END_REQ;
2525 NTDLL_free_struct_sd( sd );
2527 return ret;
2531 /***********************************************************************
2532 * NtOpenSection (NTDLL.@)
2533 * ZwOpenSection (NTDLL.@)
2535 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2537 NTSTATUS ret;
2538 DWORD len = attr->ObjectName->Length;
2540 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2542 SERVER_START_REQ( open_mapping )
2544 req->access = access;
2545 req->attributes = attr->Attributes;
2546 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2547 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2548 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
2550 SERVER_END_REQ;
2551 return ret;
2555 /***********************************************************************
2556 * NtMapViewOfSection (NTDLL.@)
2557 * ZwMapViewOfSection (NTDLL.@)
2559 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2560 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2561 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2563 NTSTATUS res;
2564 mem_size_t full_size;
2565 ACCESS_MASK access;
2566 SIZE_T size, mask = get_mask( zero_bits );
2567 int unix_handle = -1, needs_close;
2568 unsigned int map_vprot, vprot;
2569 void *base;
2570 struct file_view *view;
2571 DWORD header_size;
2572 HANDLE dup_mapping, shared_file;
2573 LARGE_INTEGER offset;
2574 sigset_t sigset;
2576 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2578 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2579 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2581 /* Check parameters */
2583 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2584 return STATUS_INVALID_PARAMETER;
2586 switch(protect)
2588 case PAGE_NOACCESS:
2589 access = SECTION_MAP_READ;
2590 break;
2591 case PAGE_READWRITE:
2592 case PAGE_EXECUTE_READWRITE:
2593 access = SECTION_MAP_WRITE;
2594 break;
2595 case PAGE_READONLY:
2596 case PAGE_WRITECOPY:
2597 case PAGE_EXECUTE:
2598 case PAGE_EXECUTE_READ:
2599 case PAGE_EXECUTE_WRITECOPY:
2600 access = SECTION_MAP_READ;
2601 break;
2602 default:
2603 return STATUS_INVALID_PAGE_PROTECTION;
2606 if (process != NtCurrentProcess())
2608 apc_call_t call;
2609 apc_result_t result;
2611 memset( &call, 0, sizeof(call) );
2613 call.map_view.type = APC_MAP_VIEW;
2614 call.map_view.handle = wine_server_obj_handle( handle );
2615 call.map_view.addr = wine_server_client_ptr( *addr_ptr );
2616 call.map_view.size = *size_ptr;
2617 call.map_view.offset = offset.QuadPart;
2618 call.map_view.zero_bits = zero_bits;
2619 call.map_view.alloc_type = alloc_type;
2620 call.map_view.prot = protect;
2621 res = server_queue_process_apc( process, &call, &result );
2622 if (res != STATUS_SUCCESS) return res;
2624 if ((NTSTATUS)result.map_view.status >= 0)
2626 *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2627 *size_ptr = result.map_view.size;
2629 return result.map_view.status;
2632 SERVER_START_REQ( get_mapping_info )
2634 req->handle = wine_server_obj_handle( handle );
2635 req->access = access;
2636 res = wine_server_call( req );
2637 map_vprot = reply->protect;
2638 base = wine_server_get_ptr( reply->base );
2639 full_size = reply->size;
2640 header_size = reply->header_size;
2641 dup_mapping = wine_server_ptr_handle( reply->mapping );
2642 shared_file = wine_server_ptr_handle( reply->shared_file );
2643 if ((ULONG_PTR)base != reply->base) base = NULL;
2645 SERVER_END_REQ;
2646 if (res) return res;
2648 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2650 if (map_vprot & VPROT_IMAGE)
2652 size = full_size;
2653 if (size != full_size) /* truncated */
2655 WARN( "Modules larger than 4Gb (%s) not supported\n", wine_dbgstr_longlong(full_size) );
2656 res = STATUS_INVALID_PARAMETER;
2657 goto done;
2659 if (shared_file)
2661 int shared_fd, shared_needs_close;
2663 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2664 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2665 res = map_image( handle, unix_handle, base, size, mask, header_size,
2666 shared_fd, dup_mapping, map_vprot, addr_ptr );
2667 if (shared_needs_close) close( shared_fd );
2668 NtClose( shared_file );
2670 else
2672 res = map_image( handle, unix_handle, base, size, mask, header_size,
2673 -1, dup_mapping, map_vprot, addr_ptr );
2675 if (needs_close) close( unix_handle );
2676 if (res >= 0) *size_ptr = size;
2677 return res;
2680 res = STATUS_INVALID_PARAMETER;
2681 if (offset.QuadPart >= full_size) goto done;
2682 if (*size_ptr)
2684 if (*size_ptr > full_size - offset.QuadPart) goto done;
2685 size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2686 if (size < *size_ptr) goto done; /* wrap-around */
2688 else
2690 size = full_size - offset.QuadPart;
2691 if (size != full_size - offset.QuadPart) /* truncated */
2693 WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2694 wine_dbgstr_longlong(full_size) );
2695 goto done;
2699 /* Reserve a properly aligned area */
2701 server_enter_uninterrupted_section( &csVirtual, &sigset );
2703 get_vprot_flags( protect, &vprot, map_vprot & VPROT_IMAGE );
2704 vprot |= (map_vprot & VPROT_COMMITTED);
2705 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2706 if (res)
2708 server_leave_uninterrupted_section( &csVirtual, &sigset );
2709 goto done;
2712 /* Map the file */
2714 TRACE("handle=%p size=%lx offset=%x%08x\n",
2715 handle, size, offset.u.HighPart, offset.u.LowPart );
2717 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2718 if (res == STATUS_SUCCESS)
2720 *addr_ptr = view->base;
2721 *size_ptr = size;
2722 view->mapping = dup_mapping;
2723 view->map_protect = map_vprot;
2724 dup_mapping = 0; /* don't close it */
2726 else
2728 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2729 view->base, size, offset.u.HighPart, offset.u.LowPart );
2730 delete_view( view );
2733 server_leave_uninterrupted_section( &csVirtual, &sigset );
2735 done:
2736 if (dup_mapping) NtClose( dup_mapping );
2737 if (needs_close) close( unix_handle );
2738 return res;
2742 /***********************************************************************
2743 * NtUnmapViewOfSection (NTDLL.@)
2744 * ZwUnmapViewOfSection (NTDLL.@)
2746 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2748 struct file_view *view;
2749 NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
2750 sigset_t sigset;
2751 void *base = ROUND_ADDR( addr, page_mask );
2753 if (process != NtCurrentProcess())
2755 apc_call_t call;
2756 apc_result_t result;
2758 memset( &call, 0, sizeof(call) );
2760 call.unmap_view.type = APC_UNMAP_VIEW;
2761 call.unmap_view.addr = wine_server_client_ptr( addr );
2762 status = server_queue_process_apc( process, &call, &result );
2763 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2764 return status;
2767 server_enter_uninterrupted_section( &csVirtual, &sigset );
2768 if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base) && !(view->protect & VPROT_VALLOC))
2770 delete_view( view );
2771 status = STATUS_SUCCESS;
2773 server_leave_uninterrupted_section( &csVirtual, &sigset );
2774 return status;
2778 /***********************************************************************
2779 * NtFlushVirtualMemory (NTDLL.@)
2780 * ZwFlushVirtualMemory (NTDLL.@)
2782 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2783 SIZE_T *size_ptr, ULONG unknown )
2785 struct file_view *view;
2786 NTSTATUS status = STATUS_SUCCESS;
2787 sigset_t sigset;
2788 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2790 if (process != NtCurrentProcess())
2792 apc_call_t call;
2793 apc_result_t result;
2795 memset( &call, 0, sizeof(call) );
2797 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2798 call.virtual_flush.addr = wine_server_client_ptr( addr );
2799 call.virtual_flush.size = *size_ptr;
2800 status = server_queue_process_apc( process, &call, &result );
2801 if (status != STATUS_SUCCESS) return status;
2803 if (result.virtual_flush.status == STATUS_SUCCESS)
2805 *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2806 *size_ptr = result.virtual_flush.size;
2808 return result.virtual_flush.status;
2811 server_enter_uninterrupted_section( &csVirtual, &sigset );
2812 if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2813 else
2815 if (!*size_ptr) *size_ptr = view->size;
2816 *addr_ptr = addr;
2817 #ifdef MS_ASYNC
2818 if (msync( addr, *size_ptr, MS_ASYNC )) status = STATUS_NOT_MAPPED_DATA;
2819 #endif
2821 server_leave_uninterrupted_section( &csVirtual, &sigset );
2822 return status;
2826 /***********************************************************************
2827 * NtGetWriteWatch (NTDLL.@)
2828 * ZwGetWriteWatch (NTDLL.@)
2830 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
2831 ULONG_PTR *count, ULONG *granularity )
2833 struct file_view *view;
2834 NTSTATUS status = STATUS_SUCCESS;
2835 sigset_t sigset;
2837 size = ROUND_SIZE( base, size );
2838 base = ROUND_ADDR( base, page_mask );
2840 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
2841 if (!*count || !size) return STATUS_INVALID_PARAMETER;
2842 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
2844 if (!addresses) return STATUS_ACCESS_VIOLATION;
2846 TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
2847 addresses, *count );
2849 server_enter_uninterrupted_section( &csVirtual, &sigset );
2851 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2853 ULONG_PTR pos = 0;
2854 char *addr = base;
2855 char *end = addr + size;
2857 while (pos < *count && addr < end)
2859 BYTE prot = view->prot[(addr - (char *)view->base) >> page_shift];
2860 if (!(prot & VPROT_WRITEWATCH)) addresses[pos++] = addr;
2861 addr += page_size;
2863 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( view, base, addr - (char *)base );
2864 *count = pos;
2865 *granularity = page_size;
2867 else status = STATUS_INVALID_PARAMETER;
2869 server_leave_uninterrupted_section( &csVirtual, &sigset );
2870 return status;
2874 /***********************************************************************
2875 * NtResetWriteWatch (NTDLL.@)
2876 * ZwResetWriteWatch (NTDLL.@)
2878 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
2880 struct file_view *view;
2881 NTSTATUS status = STATUS_SUCCESS;
2882 sigset_t sigset;
2884 size = ROUND_SIZE( base, size );
2885 base = ROUND_ADDR( base, page_mask );
2887 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
2889 if (!size) return STATUS_INVALID_PARAMETER;
2891 server_enter_uninterrupted_section( &csVirtual, &sigset );
2893 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2894 reset_write_watches( view, base, size );
2895 else
2896 status = STATUS_INVALID_PARAMETER;
2898 server_leave_uninterrupted_section( &csVirtual, &sigset );
2899 return status;
2903 /***********************************************************************
2904 * NtReadVirtualMemory (NTDLL.@)
2905 * ZwReadVirtualMemory (NTDLL.@)
2907 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2908 SIZE_T size, SIZE_T *bytes_read )
2910 NTSTATUS status;
2912 if (virtual_check_buffer_for_write( buffer, size ))
2914 SERVER_START_REQ( read_process_memory )
2916 req->handle = wine_server_obj_handle( process );
2917 req->addr = wine_server_client_ptr( addr );
2918 wine_server_set_reply( req, buffer, size );
2919 if ((status = wine_server_call( req ))) size = 0;
2921 SERVER_END_REQ;
2923 else
2925 status = STATUS_ACCESS_VIOLATION;
2926 size = 0;
2928 if (bytes_read) *bytes_read = size;
2929 return status;
2933 /***********************************************************************
2934 * NtWriteVirtualMemory (NTDLL.@)
2935 * ZwWriteVirtualMemory (NTDLL.@)
2937 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2938 SIZE_T size, SIZE_T *bytes_written )
2940 NTSTATUS status;
2942 if (virtual_check_buffer_for_read( buffer, size ))
2944 SERVER_START_REQ( write_process_memory )
2946 req->handle = wine_server_obj_handle( process );
2947 req->addr = wine_server_client_ptr( addr );
2948 wine_server_add_data( req, buffer, size );
2949 if ((status = wine_server_call( req ))) size = 0;
2951 SERVER_END_REQ;
2953 else
2955 status = STATUS_PARTIAL_COPY;
2956 size = 0;
2958 if (bytes_written) *bytes_written = size;
2959 return status;
2963 /***********************************************************************
2964 * NtAreMappedFilesTheSame (NTDLL.@)
2965 * ZwAreMappedFilesTheSame (NTDLL.@)
2967 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2969 struct file_view *view1, *view2;
2970 struct stat st1, st2;
2971 NTSTATUS status;
2972 sigset_t sigset;
2974 TRACE("%p %p\n", addr1, addr2);
2976 server_enter_uninterrupted_section( &csVirtual, &sigset );
2978 view1 = VIRTUAL_FindView( addr1, 0 );
2979 view2 = VIRTUAL_FindView( addr2, 0 );
2981 if (!view1 || !view2)
2982 status = STATUS_INVALID_ADDRESS;
2983 else if ((view1->protect & VPROT_VALLOC) || (view2->protect & VPROT_VALLOC))
2984 status = STATUS_CONFLICTING_ADDRESSES;
2985 else if (view1 == view2)
2986 status = STATUS_SUCCESS;
2987 else if (!(view1->protect & VPROT_IMAGE) || !(view2->protect & VPROT_IMAGE))
2988 status = STATUS_NOT_SAME_DEVICE;
2989 else if (!stat_mapping_file( view1, &st1 ) && !stat_mapping_file( view2, &st2 ) &&
2990 st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2991 status = STATUS_SUCCESS;
2992 else
2993 status = STATUS_NOT_SAME_DEVICE;
2995 server_leave_uninterrupted_section( &csVirtual, &sigset );
2996 return status;