ieframe: shellbrowser: Strip 'file://' from file URLs in BEFORENAVIGATE2 callbacks.
[wine/multimedia.git] / dlls / ntdll / virtual.c
blob72309f6ec051d4de7bea39ecd14710383a9bc5df
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 #include "ntstatus.h"
46 #define WIN32_NO_STATUS
47 #define NONAMELESSUNION
48 #include "windef.h"
49 #include "winternl.h"
50 #include "wine/library.h"
51 #include "wine/server.h"
52 #include "wine/exception.h"
53 #include "wine/list.h"
54 #include "wine/debug.h"
55 #include "ntdll_misc.h"
57 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
58 WINE_DECLARE_DEBUG_CHANNEL(module);
60 #ifndef MAP_NORESERVE
61 #define MAP_NORESERVE 0
62 #endif
64 /* File view */
65 struct file_view
67 struct list entry; /* Entry in global view list */
68 void *base; /* Base address */
69 size_t size; /* Size in bytes */
70 HANDLE mapping; /* Handle to the file mapping */
71 unsigned int map_protect; /* Mapping protection */
72 unsigned int protect; /* Protection for all pages at allocation time */
73 BYTE prot[1]; /* Protection byte for each page */
77 /* Conversion from VPROT_* to Win32 flags */
78 static const BYTE VIRTUAL_Win32Flags[16] =
80 PAGE_NOACCESS, /* 0 */
81 PAGE_READONLY, /* READ */
82 PAGE_READWRITE, /* WRITE */
83 PAGE_READWRITE, /* READ | WRITE */
84 PAGE_EXECUTE, /* EXEC */
85 PAGE_EXECUTE_READ, /* READ | EXEC */
86 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
87 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
88 PAGE_WRITECOPY, /* WRITECOPY */
89 PAGE_WRITECOPY, /* READ | WRITECOPY */
90 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
91 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
92 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
93 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
94 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
95 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
98 static struct list views_list = LIST_INIT(views_list);
100 static RTL_CRITICAL_SECTION csVirtual;
101 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
103 0, 0, &csVirtual,
104 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
105 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
107 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
109 #ifdef __i386__
110 static const UINT page_shift = 12;
111 static const UINT_PTR page_mask = 0xfff;
112 /* Note: these are Windows limits, you cannot change them. */
113 static void *address_space_limit = (void *)0xc0000000; /* top of the total available address space */
114 static void *user_space_limit = (void *)0x7fff0000; /* top of the user address space */
115 static void *working_set_limit = (void *)0x7fff0000; /* top of the current working set */
116 static void *address_space_start = (void *)0x110000; /* keep DOS area clear */
117 #elif defined(__x86_64__)
118 static const UINT page_shift = 12;
119 static const UINT_PTR page_mask = 0xfff;
120 static void *address_space_limit = (void *)0x7fffffff0000;
121 static void *user_space_limit = (void *)0x7fffffff0000;
122 static void *working_set_limit = (void *)0x7fffffff0000;
123 static void *address_space_start = (void *)0x10000;
124 #else
125 UINT_PTR page_size = 0;
126 static UINT page_shift;
127 static UINT_PTR page_mask;
128 static void *address_space_limit;
129 static void *user_space_limit;
130 static void *working_set_limit;
131 static void *address_space_start = (void *)0x10000;
132 #endif /* __i386__ */
133 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
135 #define ROUND_ADDR(addr,mask) \
136 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
138 #define ROUND_SIZE(addr,size) \
139 (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
141 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
142 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
144 #define VIRTUAL_HEAP_SIZE (sizeof(void*)*1024*1024)
146 static HANDLE virtual_heap;
147 static void *preload_reserve_start;
148 static void *preload_reserve_end;
149 static BOOL use_locks;
150 static BOOL force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
153 /***********************************************************************
154 * VIRTUAL_GetProtStr
156 static const char *VIRTUAL_GetProtStr( BYTE prot )
158 static char buffer[6];
159 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
160 buffer[1] = (prot & VPROT_GUARD) ? 'g' : ((prot & VPROT_WRITEWATCH) ? 'H' : '-');
161 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
162 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
163 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
164 buffer[5] = 0;
165 return buffer;
169 /***********************************************************************
170 * VIRTUAL_GetUnixProt
172 * Convert page protections to protection for mmap/mprotect.
174 static int VIRTUAL_GetUnixProt( BYTE vprot )
176 int prot = 0;
177 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
179 if (vprot & VPROT_READ) prot |= PROT_READ;
180 if (vprot & VPROT_WRITE) prot |= PROT_WRITE | PROT_READ;
181 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE | PROT_READ;
182 if (vprot & VPROT_EXEC) prot |= PROT_EXEC | PROT_READ;
183 if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
185 if (!prot) prot = PROT_NONE;
186 return prot;
190 /***********************************************************************
191 * VIRTUAL_DumpView
193 static void VIRTUAL_DumpView( struct file_view *view )
195 UINT i, count;
196 char *addr = view->base;
197 BYTE prot = view->prot[0];
199 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
200 if (view->protect & VPROT_SYSTEM)
201 TRACE( " (system)\n" );
202 else if (view->protect & VPROT_VALLOC)
203 TRACE( " (valloc)\n" );
204 else if (view->mapping)
205 TRACE( " %p\n", view->mapping );
206 else
207 TRACE( " (anonymous)\n");
209 for (count = i = 1; i < view->size >> page_shift; i++, count++)
211 if (view->prot[i] == prot) continue;
212 TRACE( " %p - %p %s\n",
213 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
214 addr += (count << page_shift);
215 prot = view->prot[i];
216 count = 0;
218 if (count)
219 TRACE( " %p - %p %s\n",
220 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
224 /***********************************************************************
225 * VIRTUAL_Dump
227 #ifdef WINE_VM_DEBUG
228 static void VIRTUAL_Dump(void)
230 sigset_t sigset;
231 struct file_view *view;
233 TRACE( "Dump of all virtual memory views:\n" );
234 server_enter_uninterrupted_section( &csVirtual, &sigset );
235 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
237 VIRTUAL_DumpView( view );
239 server_leave_uninterrupted_section( &csVirtual, &sigset );
241 #endif
244 /***********************************************************************
245 * VIRTUAL_FindView
247 * Find the view containing a given address. The csVirtual section must be held by caller.
249 * PARAMS
250 * addr [I] Address
252 * RETURNS
253 * View: Success
254 * NULL: Failure
256 static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
258 struct file_view *view;
260 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
262 if (view->base > addr) break; /* no matching view */
263 if ((const char *)view->base + view->size <= (const char *)addr) continue;
264 if ((const char *)view->base + view->size < (const char *)addr + size) break; /* size too large */
265 if ((const char *)addr + size < (const char *)addr) break; /* overflow */
266 return view;
268 return NULL;
272 /***********************************************************************
273 * get_mask
275 static inline UINT_PTR get_mask( ULONG zero_bits )
277 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
278 if (zero_bits < page_shift) zero_bits = page_shift;
279 return (1 << zero_bits) - 1;
283 /***********************************************************************
284 * find_view_range
286 * Find the first view overlapping at least part of the specified range.
287 * The csVirtual section must be held by caller.
289 static struct file_view *find_view_range( const void *addr, size_t size )
291 struct file_view *view;
293 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
295 if ((const char *)view->base >= (const char *)addr + size) break;
296 if ((const char *)view->base + view->size > (const char *)addr) return view;
298 return NULL;
302 /***********************************************************************
303 * find_free_area
305 * Find a free area between views inside the specified range.
306 * The csVirtual section must be held by caller.
308 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
310 struct list *ptr;
311 void *start;
313 if (top_down)
315 start = ROUND_ADDR( (char *)end - size, mask );
316 if (start >= end || start < base) return NULL;
318 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
320 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
322 if ((char *)view->base + view->size <= (char *)start) break;
323 if ((char *)view->base >= (char *)start + size) continue;
324 start = ROUND_ADDR( (char *)view->base - size, mask );
325 /* stop if remaining space is not large enough */
326 if (!start || start >= end || start < base) return NULL;
329 else
331 start = ROUND_ADDR( (char *)base + mask, mask );
332 if (start >= end || (char *)end - (char *)start < size) return NULL;
334 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
336 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
338 if ((char *)view->base >= (char *)start + size) break;
339 if ((char *)view->base + view->size <= (char *)start) continue;
340 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
341 /* stop if remaining space is not large enough */
342 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
345 return start;
349 /***********************************************************************
350 * add_reserved_area
352 * Add a reserved area to the list maintained by libwine.
353 * The csVirtual section must be held by caller.
355 static void add_reserved_area( void *addr, size_t size )
357 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
359 if (addr < user_space_limit)
361 /* unmap the part of the area that is below the limit */
362 assert( (char *)addr + size > (char *)user_space_limit );
363 munmap( addr, (char *)user_space_limit - (char *)addr );
364 size -= (char *)user_space_limit - (char *)addr;
365 addr = user_space_limit;
367 /* blow away existing mappings */
368 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
369 wine_mmap_add_reserved_area( addr, size );
373 /***********************************************************************
374 * remove_reserved_area
376 * Remove a reserved area from the list maintained by libwine.
377 * The csVirtual section must be held by caller.
379 static void remove_reserved_area( void *addr, size_t size )
381 struct file_view *view;
383 TRACE( "removing %p-%p\n", addr, (char *)addr + size );
384 wine_mmap_remove_reserved_area( addr, size, 0 );
386 /* unmap areas not covered by an existing view */
387 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
389 if ((char *)view->base >= (char *)addr + size)
391 munmap( addr, size );
392 break;
394 if ((char *)view->base + view->size <= (char *)addr) continue;
395 if (view->base > addr) munmap( addr, (char *)view->base - (char *)addr );
396 if ((char *)view->base + view->size > (char *)addr + size) break;
397 size = (char *)addr + size - ((char *)view->base + view->size);
398 addr = (char *)view->base + view->size;
403 /***********************************************************************
404 * is_beyond_limit
406 * Check if an address range goes beyond a given limit.
408 static inline BOOL is_beyond_limit( const void *addr, size_t size, const void *limit )
410 return (addr >= limit || (const char *)addr + size > (const char *)limit);
414 /***********************************************************************
415 * unmap_area
417 * Unmap an area, or simply replace it by an empty mapping if it is
418 * in a reserved area. The csVirtual section must be held by caller.
420 static inline void unmap_area( void *addr, size_t size )
422 if (wine_mmap_is_in_reserved_area( addr, size ))
423 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
424 else if (is_beyond_limit( addr, size, user_space_limit ))
425 add_reserved_area( addr, size );
426 else
427 munmap( addr, size );
431 /***********************************************************************
432 * delete_view
434 * Deletes a view. The csVirtual section must be held by caller.
436 static void delete_view( struct file_view *view ) /* [in] View */
438 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
439 list_remove( &view->entry );
440 if (view->mapping) close_handle( view->mapping );
441 RtlFreeHeap( virtual_heap, 0, view );
445 /***********************************************************************
446 * create_view
448 * Create a view. The csVirtual section must be held by caller.
450 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
452 struct file_view *view;
453 struct list *ptr;
454 int unix_prot = VIRTUAL_GetUnixProt( vprot );
456 assert( !((UINT_PTR)base & page_mask) );
457 assert( !(size & page_mask) );
459 /* Create the view structure */
461 if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
463 FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
464 return STATUS_NO_MEMORY;
467 view->base = base;
468 view->size = size;
469 view->mapping = 0;
470 view->map_protect = 0;
471 view->protect = vprot;
472 memset( view->prot, vprot, size >> page_shift );
474 /* Insert it in the linked list */
476 LIST_FOR_EACH( ptr, &views_list )
478 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
479 if (next->base > base) break;
481 list_add_before( ptr, &view->entry );
483 /* Check for overlapping views. This can happen if the previous view
484 * was a system view that got unmapped behind our back. In that case
485 * we recover by simply deleting it. */
487 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
489 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
490 if ((char *)prev->base + prev->size > (char *)base)
492 TRACE( "overlapping prev view %p-%p for %p-%p\n",
493 prev->base, (char *)prev->base + prev->size,
494 base, (char *)base + view->size );
495 assert( prev->protect & VPROT_SYSTEM );
496 delete_view( prev );
499 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
501 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
502 if ((char *)base + view->size > (char *)next->base)
504 TRACE( "overlapping next view %p-%p for %p-%p\n",
505 next->base, (char *)next->base + next->size,
506 base, (char *)base + view->size );
507 assert( next->protect & VPROT_SYSTEM );
508 delete_view( next );
512 *view_ret = view;
513 VIRTUAL_DEBUG_DUMP_VIEW( view );
515 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
517 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
518 mprotect( base, size, unix_prot | PROT_EXEC );
520 return STATUS_SUCCESS;
524 /***********************************************************************
525 * VIRTUAL_GetWin32Prot
527 * Convert page protections to Win32 flags.
529 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
531 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
532 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
533 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
534 return ret;
538 /***********************************************************************
539 * get_vprot_flags
541 * Build page protections from Win32 flags.
543 * PARAMS
544 * protect [I] Win32 protection flags
546 * RETURNS
547 * Value of page protection flags
549 static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot, BOOL image )
551 switch(protect & 0xff)
553 case PAGE_READONLY:
554 *vprot = VPROT_READ;
555 break;
556 case PAGE_READWRITE:
557 if (image)
558 *vprot = VPROT_READ | VPROT_WRITECOPY;
559 else
560 *vprot = VPROT_READ | VPROT_WRITE;
561 break;
562 case PAGE_WRITECOPY:
563 *vprot = VPROT_READ | VPROT_WRITECOPY;
564 break;
565 case PAGE_EXECUTE:
566 *vprot = VPROT_EXEC;
567 break;
568 case PAGE_EXECUTE_READ:
569 *vprot = VPROT_EXEC | VPROT_READ;
570 break;
571 case PAGE_EXECUTE_READWRITE:
572 if (image)
573 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
574 else
575 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
576 break;
577 case PAGE_EXECUTE_WRITECOPY:
578 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
579 break;
580 case PAGE_NOACCESS:
581 *vprot = 0;
582 break;
583 default:
584 return STATUS_INVALID_PAGE_PROTECTION;
586 if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
587 if (protect & PAGE_NOCACHE) *vprot |= VPROT_NOCACHE;
588 return STATUS_SUCCESS;
592 /***********************************************************************
593 * mprotect_exec
595 * Wrapper for mprotect, adds PROT_EXEC if forced by force_exec_prot
597 static inline int mprotect_exec( void *base, size_t size, int unix_prot, unsigned int view_protect )
599 if (force_exec_prot && !(view_protect & VPROT_NOEXEC) &&
600 (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
602 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
603 if (!mprotect( base, size, unix_prot | PROT_EXEC )) return 0;
604 /* exec + write may legitimately fail, in that case fall back to write only */
605 if (!(unix_prot & PROT_WRITE)) return -1;
608 return mprotect( base, size, unix_prot );
611 /***********************************************************************
612 * VIRTUAL_SetProt
614 * Change the protection of a range of pages.
616 * RETURNS
617 * TRUE: Success
618 * FALSE: Failure
620 static BOOL VIRTUAL_SetProt( struct file_view *view, /* [in] Pointer to view */
621 void *base, /* [in] Starting address */
622 size_t size, /* [in] Size in bytes */
623 BYTE vprot ) /* [in] Protections to use */
625 int unix_prot = VIRTUAL_GetUnixProt(vprot);
626 BYTE *p = view->prot + (((char *)base - (char *)view->base) >> page_shift);
628 TRACE("%p-%p %s\n",
629 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
631 if (view->protect & VPROT_WRITEWATCH)
633 /* each page may need different protections depending on write watch flag */
634 UINT i, count;
635 char *addr = base;
636 int prot;
638 p[0] = vprot | (p[0] & VPROT_WRITEWATCH);
639 unix_prot = VIRTUAL_GetUnixProt( p[0] );
640 for (count = i = 1; i < size >> page_shift; i++, count++)
642 p[i] = vprot | (p[i] & VPROT_WRITEWATCH);
643 prot = VIRTUAL_GetUnixProt( p[i] );
644 if (prot == unix_prot) continue;
645 mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
646 addr += count << page_shift;
647 unix_prot = prot;
648 count = 0;
650 if (count) mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
651 VIRTUAL_DEBUG_DUMP_VIEW( view );
652 return TRUE;
655 /* if setting stack guard pages, store the permissions first, as the guard may be
656 * triggered at any point after mprotect and change the permissions again */
657 if ((vprot & VPROT_GUARD) &&
658 (base >= NtCurrentTeb()->DeallocationStack) &&
659 (base < NtCurrentTeb()->Tib.StackBase))
661 memset( p, vprot, size >> page_shift );
662 mprotect( base, size, unix_prot );
663 VIRTUAL_DEBUG_DUMP_VIEW( view );
664 return TRUE;
667 if (mprotect_exec( base, size, unix_prot, view->protect )) /* FIXME: last error */
668 return FALSE;
670 memset( p, vprot, size >> page_shift );
671 VIRTUAL_DEBUG_DUMP_VIEW( view );
672 return TRUE;
676 /***********************************************************************
677 * reset_write_watches
679 * Reset write watches in a memory range.
681 static void reset_write_watches( struct file_view *view, void *base, SIZE_T size )
683 SIZE_T i, count;
684 int prot, unix_prot;
685 char *addr = base;
686 BYTE *p = view->prot + ((addr - (char *)view->base) >> page_shift);
688 p[0] |= VPROT_WRITEWATCH;
689 unix_prot = VIRTUAL_GetUnixProt( p[0] );
690 for (count = i = 1; i < size >> page_shift; i++, count++)
692 p[i] |= VPROT_WRITEWATCH;
693 prot = VIRTUAL_GetUnixProt( p[i] );
694 if (prot == unix_prot) continue;
695 mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
696 addr += count << page_shift;
697 unix_prot = prot;
698 count = 0;
700 if (count) mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
704 /***********************************************************************
705 * unmap_extra_space
707 * Release the extra memory while keeping the range starting on the granularity boundary.
709 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
711 if ((ULONG_PTR)ptr & mask)
713 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
714 munmap( ptr, extra );
715 ptr = (char *)ptr + extra;
716 total_size -= extra;
718 if (total_size > wanted_size)
719 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
720 return ptr;
724 struct alloc_area
726 size_t size;
727 size_t mask;
728 int top_down;
729 void *limit;
730 void *result;
733 /***********************************************************************
734 * alloc_reserved_area_callback
736 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
738 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
740 struct alloc_area *alloc = arg;
741 void *end = (char *)start + size;
743 if (start < address_space_start) start = address_space_start;
744 if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
745 if (start >= end) return 0;
747 /* make sure we don't touch the preloader reserved range */
748 if (preload_reserve_end >= start)
750 if (preload_reserve_end >= end)
752 if (preload_reserve_start <= start) return 0; /* no space in that area */
753 if (preload_reserve_start < end) end = preload_reserve_start;
755 else if (preload_reserve_start <= start) start = preload_reserve_end;
756 else
758 /* range is split in two by the preloader reservation, try first part */
759 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
760 alloc->mask, alloc->top_down )))
761 return 1;
762 /* then fall through to try second part */
763 start = preload_reserve_end;
766 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
767 return 1;
769 return 0;
773 /***********************************************************************
774 * map_view
776 * Create a view and mmap the corresponding memory area.
777 * The csVirtual section must be held by caller.
779 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
780 int top_down, unsigned int vprot )
782 void *ptr;
783 NTSTATUS status;
785 if (base)
787 if (is_beyond_limit( base, size, address_space_limit ))
788 return STATUS_WORKING_SET_LIMIT_RANGE;
790 switch (wine_mmap_is_in_reserved_area( base, size ))
792 case -1: /* partially in a reserved area */
793 return STATUS_CONFLICTING_ADDRESSES;
795 case 0: /* not in a reserved area, do a normal allocation */
796 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
798 if (errno == ENOMEM) return STATUS_NO_MEMORY;
799 return STATUS_INVALID_PARAMETER;
801 if (ptr != base)
803 /* We couldn't get the address we wanted */
804 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
805 else munmap( ptr, size );
806 return STATUS_CONFLICTING_ADDRESSES;
808 break;
810 default:
811 case 1: /* in a reserved area, make sure the address is available */
812 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
813 /* replace the reserved area by our mapping */
814 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
815 return STATUS_INVALID_PARAMETER;
816 break;
818 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
820 else
822 size_t view_size = size + mask + 1;
823 struct alloc_area alloc;
825 alloc.size = size;
826 alloc.mask = mask;
827 alloc.top_down = top_down;
828 alloc.limit = user_space_limit;
829 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
831 ptr = alloc.result;
832 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
833 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
834 return STATUS_INVALID_PARAMETER;
835 goto done;
838 for (;;)
840 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
842 if (errno == ENOMEM) return STATUS_NO_MEMORY;
843 return STATUS_INVALID_PARAMETER;
845 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
846 /* if we got something beyond the user limit, unmap it and retry */
847 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
848 else break;
850 ptr = unmap_extra_space( ptr, view_size, size, mask );
852 done:
853 status = create_view( view_ret, ptr, size, vprot );
854 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
855 return status;
859 /***********************************************************************
860 * map_file_into_view
862 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
863 * The csVirtual section must be held by caller.
865 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
866 off_t offset, unsigned int vprot, BOOL removable )
868 void *ptr;
869 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
870 unsigned int flags = MAP_FIXED | ((vprot & VPROT_WRITECOPY) ? MAP_PRIVATE : MAP_SHARED);
872 assert( start < view->size );
873 assert( start + size <= view->size );
875 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (vprot & VPROT_READ))
877 TRACE( "forcing exec permission on mapping %p-%p\n",
878 (char *)view->base + start, (char *)view->base + start + size - 1 );
879 prot |= PROT_EXEC;
882 /* only try mmap if media is not removable (or if we require write access) */
883 if (!removable || (flags & MAP_SHARED))
885 if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
886 goto done;
888 if ((errno == EPERM) && (prot & PROT_EXEC))
889 ERR( "failed to set %08x protection on file map, noexec filesystem?\n", prot );
891 /* mmap() failed; if this is because the file offset is not */
892 /* page-aligned (EINVAL), or because the underlying filesystem */
893 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
894 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
895 if (flags & MAP_SHARED) /* we cannot fake shared mappings */
897 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
898 ERR( "shared writable mmap not supported, broken filesystem?\n" );
899 return STATUS_NOT_SUPPORTED;
903 /* Reserve the memory with an anonymous mmap */
904 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
905 if (ptr == (void *)-1) return FILE_GetNtStatus();
906 /* Now read in the file */
907 pread( fd, ptr, size, offset );
908 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
909 done:
910 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
911 return STATUS_SUCCESS;
915 /***********************************************************************
916 * get_committed_size
918 * Get the size of the committed range starting at base.
919 * Also return the protections for the first page.
921 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
923 SIZE_T i, start;
925 start = ((char *)base - (char *)view->base) >> page_shift;
926 *vprot = view->prot[start];
928 if (view->mapping && !(view->protect & VPROT_COMMITTED))
930 SIZE_T ret = 0;
931 SERVER_START_REQ( get_mapping_committed_range )
933 req->handle = wine_server_obj_handle( view->mapping );
934 req->offset = start << page_shift;
935 if (!wine_server_call( req ))
937 ret = reply->size;
938 if (reply->committed)
940 *vprot |= VPROT_COMMITTED;
941 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
945 SERVER_END_REQ;
946 return ret;
948 for (i = start + 1; i < view->size >> page_shift; i++)
949 if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
950 return (i - start) << page_shift;
954 /***********************************************************************
955 * decommit_view
957 * Decommit some pages of a given view.
958 * The csVirtual section must be held by caller.
960 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
962 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
964 BYTE *p = view->prot + (start >> page_shift);
965 size >>= page_shift;
966 while (size--) *p++ &= ~VPROT_COMMITTED;
967 return STATUS_SUCCESS;
969 return FILE_GetNtStatus();
973 /***********************************************************************
974 * allocate_dos_memory
976 * Allocate the DOS memory range.
978 static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
980 size_t size;
981 void *addr = NULL;
982 void * const low_64k = (void *)0x10000;
983 const size_t dosmem_size = 0x110000;
984 int unix_prot = VIRTUAL_GetUnixProt( vprot );
985 struct list *ptr;
987 /* check for existing view */
989 if ((ptr = list_head( &views_list )))
991 struct file_view *first_view = LIST_ENTRY( ptr, struct file_view, entry );
992 if (first_view->base < (void *)dosmem_size) return STATUS_CONFLICTING_ADDRESSES;
995 /* check without the first 64K */
997 if (wine_mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
999 addr = wine_anon_mmap( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
1000 if (addr != low_64k)
1002 if (addr != (void *)-1) munmap( addr, dosmem_size - 0x10000 );
1003 return map_view( view, NULL, dosmem_size, 0xffff, 0, vprot );
1007 /* now try to allocate the low 64K too */
1009 if (wine_mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
1011 addr = wine_anon_mmap( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
1012 if (addr == (void *)page_size)
1014 if (!wine_anon_mmap( NULL, page_size, unix_prot, MAP_FIXED ))
1016 addr = NULL;
1017 TRACE( "successfully mapped low 64K range\n" );
1019 else TRACE( "failed to map page 0\n" );
1021 else
1023 if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
1024 addr = low_64k;
1025 TRACE( "failed to map low 64K range\n" );
1029 /* now reserve the whole range */
1031 size = (char *)dosmem_size - (char *)addr;
1032 wine_anon_mmap( addr, size, unix_prot, MAP_FIXED );
1033 return create_view( view, addr, size, vprot );
1037 /***********************************************************************
1038 * stat_mapping_file
1040 * Stat the underlying file for a memory view.
1042 static NTSTATUS stat_mapping_file( struct file_view *view, struct stat *st )
1044 NTSTATUS status;
1045 int unix_fd, needs_close;
1047 if (!view->mapping) return STATUS_NOT_MAPPED_VIEW;
1048 if (!(status = server_get_unix_fd( view->mapping, 0, &unix_fd, &needs_close, NULL, NULL )))
1050 if (fstat( unix_fd, st ) == -1) status = FILE_GetNtStatus();
1051 if (needs_close) close( unix_fd );
1053 return status;
1057 /***********************************************************************
1058 * map_image
1060 * Map an executable (PE format) image into memory.
1062 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
1063 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, unsigned int map_vprot, PVOID *addr_ptr )
1065 IMAGE_DOS_HEADER *dos;
1066 IMAGE_NT_HEADERS *nt;
1067 IMAGE_SECTION_HEADER sections[96];
1068 IMAGE_SECTION_HEADER *sec;
1069 IMAGE_DATA_DIRECTORY *imports;
1070 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
1071 int i;
1072 off_t pos;
1073 sigset_t sigset;
1074 struct stat st;
1075 struct file_view *view = NULL;
1076 char *ptr, *header_end, *header_start;
1077 INT_PTR delta = 0;
1079 /* zero-map the whole range */
1081 server_enter_uninterrupted_section( &csVirtual, &sigset );
1083 if (base >= (char *)address_space_start) /* make sure the DOS area remains free */
1084 status = map_view( &view, base, total_size, mask, FALSE,
1085 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1087 if (status != STATUS_SUCCESS)
1088 status = map_view( &view, NULL, total_size, mask, FALSE,
1089 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1091 if (status != STATUS_SUCCESS) goto error;
1093 ptr = view->base;
1094 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
1096 /* map the header */
1098 if (fstat( fd, &st ) == -1)
1100 status = FILE_GetNtStatus();
1101 goto error;
1103 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
1104 if (!st.st_size) goto error;
1105 header_size = min( header_size, st.st_size );
1106 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1107 !dup_mapping ) != STATUS_SUCCESS) goto error;
1108 dos = (IMAGE_DOS_HEADER *)ptr;
1109 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1110 header_end = ptr + ROUND_SIZE( 0, header_size );
1111 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1112 if ((char *)(nt + 1) > header_end) goto error;
1113 header_start = (char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader;
1114 if (nt->FileHeader.NumberOfSections > sizeof(sections)/sizeof(*sections)) goto error;
1115 if (header_start + sizeof(*sections) * nt->FileHeader.NumberOfSections > header_end) goto error;
1116 /* Some applications (e.g. the Steam version of Borderlands) map over the top of the section headers,
1117 * copying the headers into local memory is necessary to properly load such applications. */
1118 memcpy(sections, header_start, sizeof(*sections) * nt->FileHeader.NumberOfSections);
1119 sec = sections;
1121 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
1122 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
1124 /* check for non page-aligned binary */
1126 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1128 /* unaligned sections, this happens for native subsystem binaries */
1129 /* in that case Windows simply maps in the whole file */
1131 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1132 !dup_mapping ) != STATUS_SUCCESS) goto error;
1134 /* check that all sections are loaded at the right offset */
1135 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1136 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1138 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1139 goto error; /* Windows refuses to load in that case too */
1142 /* set the image protections */
1143 VIRTUAL_SetProt( view, ptr, total_size,
1144 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1146 /* no relocations are performed on non page-aligned binaries */
1147 goto done;
1151 /* map all the sections */
1153 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1155 static const SIZE_T sector_align = 0x1ff;
1156 SIZE_T map_size, file_start, file_size, end;
1158 if (!sec->Misc.VirtualSize)
1159 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1160 else
1161 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1163 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1164 file_start = sec->PointerToRawData & ~sector_align;
1165 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1166 if (file_size > map_size) file_size = map_size;
1168 /* a few sanity checks */
1169 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1170 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1172 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1173 sec->Name, sec->VirtualAddress, map_size, total_size );
1174 goto error;
1177 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1178 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1180 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1181 sec->Name, ptr + sec->VirtualAddress,
1182 sec->PointerToRawData, (int)pos, file_size, map_size,
1183 sec->Characteristics );
1184 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1185 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE, FALSE ) != STATUS_SUCCESS)
1187 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1188 goto error;
1191 /* check if the import directory falls inside this section */
1192 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1193 imports->VirtualAddress < sec->VirtualAddress + map_size)
1195 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1196 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1197 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1198 if (end > base)
1199 map_file_into_view( view, shared_fd, base, end - base,
1200 pos + (base - sec->VirtualAddress),
1201 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY, FALSE );
1203 pos += map_size;
1204 continue;
1207 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1208 sec->Name, ptr + sec->VirtualAddress,
1209 sec->PointerToRawData, sec->SizeOfRawData,
1210 sec->Misc.VirtualSize, sec->Characteristics );
1212 if (!sec->PointerToRawData || !file_size) continue;
1214 /* Note: if the section is not aligned properly map_file_into_view will magically
1215 * fall back to read(), so we don't need to check anything here.
1217 end = file_start + file_size;
1218 if (sec->PointerToRawData >= st.st_size ||
1219 end > ((st.st_size + sector_align) & ~sector_align) ||
1220 end < file_start ||
1221 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1222 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1223 !dup_mapping ) != STATUS_SUCCESS)
1225 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1226 goto error;
1229 if (file_size & page_mask)
1231 end = ROUND_SIZE( 0, file_size );
1232 if (end > map_size) end = map_size;
1233 TRACE_(module)("clearing %p - %p\n",
1234 ptr + sec->VirtualAddress + file_size,
1235 ptr + sec->VirtualAddress + end );
1236 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1241 /* perform base relocation, if necessary */
1243 if (ptr != base &&
1244 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1245 !NtCurrentTeb()->Peb->ImageBaseAddress) )
1247 IMAGE_BASE_RELOCATION *rel, *end;
1248 const IMAGE_DATA_DIRECTORY *relocs;
1250 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1252 WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1253 base, ptr );
1254 status = STATUS_CONFLICTING_ADDRESSES;
1255 goto error;
1258 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1259 base, base + total_size, ptr, ptr + total_size );
1261 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1262 rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1263 end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1264 delta = ptr - base;
1266 while (rel < end - 1 && rel->SizeOfBlock)
1268 if (rel->VirtualAddress >= total_size)
1270 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1271 status = STATUS_ACCESS_VIOLATION;
1272 goto error;
1274 rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1275 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1276 (USHORT *)(rel + 1), delta );
1277 if (!rel) goto error;
1281 /* set the image protections */
1283 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1285 sec = sections;
1286 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1288 SIZE_T size;
1289 BYTE vprot = VPROT_COMMITTED;
1291 if (sec->Misc.VirtualSize)
1292 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1293 else
1294 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1296 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1297 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_WRITECOPY;
1298 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1300 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1301 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1302 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1303 vprot |= VPROT_EXEC;
1305 if (!VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot ) && (vprot & VPROT_EXEC))
1306 ERR( "failed to set %08x protection on section %.8s, noexec filesystem?\n",
1307 sec->Characteristics, sec->Name );
1310 done:
1311 view->mapping = dup_mapping;
1312 view->map_protect = map_vprot;
1313 server_leave_uninterrupted_section( &csVirtual, &sigset );
1315 *addr_ptr = ptr;
1316 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1317 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1318 #endif
1319 if (ptr != base) return STATUS_IMAGE_NOT_AT_BASE;
1320 return STATUS_SUCCESS;
1322 error:
1323 if (view) delete_view( view );
1324 server_leave_uninterrupted_section( &csVirtual, &sigset );
1325 if (dup_mapping) NtClose( dup_mapping );
1326 return status;
1330 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1331 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1333 void **heap_base = arg;
1335 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1336 if (size < VIRTUAL_HEAP_SIZE) return 0;
1337 if (is_win64 && base < (void *)0x80000000) return 0;
1338 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1339 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1340 return (*heap_base != (void *)-1);
1343 /***********************************************************************
1344 * virtual_init
1346 void virtual_init(void)
1348 const char *preload;
1349 void *heap_base;
1350 size_t size;
1351 struct file_view *heap_view;
1353 #if !defined(__i386__) && !defined(__x86_64__)
1354 page_size = sysconf( _SC_PAGESIZE );
1355 page_mask = page_size - 1;
1356 /* Make sure we have a power of 2 */
1357 assert( !(page_size & page_mask) );
1358 page_shift = 0;
1359 while ((1 << page_shift) != page_size) page_shift++;
1360 user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1361 #endif /* page_mask */
1362 if ((preload = getenv("WINEPRELOADRESERVE")))
1364 unsigned long start, end;
1365 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1367 preload_reserve_start = (void *)start;
1368 preload_reserve_end = (void *)end;
1372 /* try to find space in a reserved area for the virtual heap */
1373 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1374 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1376 assert( heap_base != (void *)-1 );
1377 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1378 VIRTUAL_HEAP_SIZE, NULL, NULL );
1379 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1381 /* make the DOS area accessible (except the low 64K) to hide bugs in broken apps like Excel 2003 */
1382 size = (char *)address_space_start - (char *)0x10000;
1383 if (size && wine_mmap_is_in_reserved_area( (void*)0x10000, size ) == 1)
1384 wine_anon_mmap( (void *)0x10000, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1388 /***********************************************************************
1389 * virtual_init_threading
1391 void virtual_init_threading(void)
1393 use_locks = TRUE;
1397 /***********************************************************************
1398 * virtual_get_system_info
1400 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1402 info->unknown = 0;
1403 info->KeMaximumIncrement = 0; /* FIXME */
1404 info->PageSize = page_size;
1405 info->MmLowestPhysicalPage = 1;
1406 info->MmHighestPhysicalPage = 0x7fffffff / page_size;
1407 info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
1408 info->AllocationGranularity = get_mask(0) + 1;
1409 info->LowestUserAddress = (void *)0x10000;
1410 info->HighestUserAddress = (char *)user_space_limit - 1;
1411 info->ActiveProcessorsAffinityMask = get_system_affinity_mask();
1412 info->NumberOfProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1416 /***********************************************************************
1417 * virtual_create_builtin_view
1419 NTSTATUS virtual_create_builtin_view( void *module )
1421 NTSTATUS status;
1422 sigset_t sigset;
1423 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1424 SIZE_T size = nt->OptionalHeader.SizeOfImage;
1425 IMAGE_SECTION_HEADER *sec;
1426 struct file_view *view;
1427 void *base;
1428 int i;
1430 size = ROUND_SIZE( module, size );
1431 base = ROUND_ADDR( module, page_mask );
1432 server_enter_uninterrupted_section( &csVirtual, &sigset );
1433 status = create_view( &view, base, size, VPROT_SYSTEM | VPROT_IMAGE |
1434 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1435 if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
1436 server_leave_uninterrupted_section( &csVirtual, &sigset );
1438 if (status) return status;
1440 /* The PE header is always read-only, no write, no execute. */
1441 view->prot[0] = VPROT_COMMITTED | VPROT_READ;
1443 sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
1444 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1446 BYTE flags = VPROT_COMMITTED;
1448 if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
1449 if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
1450 if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
1451 memset (view->prot + (sec[i].VirtualAddress >> page_shift), flags,
1452 ROUND_SIZE( sec[i].VirtualAddress, sec[i].Misc.VirtualSize ) >> page_shift );
1455 return status;
1459 /***********************************************************************
1460 * virtual_alloc_thread_stack
1462 NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1464 struct file_view *view;
1465 NTSTATUS status;
1466 sigset_t sigset;
1467 SIZE_T size;
1469 if (!reserve_size || !commit_size)
1471 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1472 if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
1473 if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1476 size = max( reserve_size, commit_size );
1477 if (size < 1024 * 1024) size = 1024 * 1024; /* Xlib needs a large stack */
1478 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1480 server_enter_uninterrupted_section( &csVirtual, &sigset );
1482 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1483 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1484 goto done;
1486 #ifdef VALGRIND_STACK_REGISTER
1487 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1488 #endif
1490 /* setup no access guard page */
1491 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1492 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1493 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1495 /* note: limit is lower than base since the stack grows down */
1496 teb->DeallocationStack = view->base;
1497 teb->Tib.StackBase = (char *)view->base + view->size;
1498 teb->Tib.StackLimit = (char *)view->base + 2 * page_size;
1499 done:
1500 server_leave_uninterrupted_section( &csVirtual, &sigset );
1501 return status;
1505 /***********************************************************************
1506 * virtual_clear_thread_stack
1508 * Clear the stack contents before calling the main entry point, some broken apps need that.
1510 void virtual_clear_thread_stack(void)
1512 void *stack = NtCurrentTeb()->Tib.StackLimit;
1513 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1515 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1516 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1520 /***********************************************************************
1521 * virtual_handle_fault
1523 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err, BOOL on_signal_stack )
1525 struct file_view *view;
1526 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1527 sigset_t sigset;
1529 server_enter_uninterrupted_section( &csVirtual, &sigset );
1530 if ((view = VIRTUAL_FindView( addr, 0 )))
1532 void *page = ROUND_ADDR( addr, page_mask );
1533 BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1534 if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1536 if (*vprot & VPROT_WRITEWATCH)
1538 *vprot &= ~VPROT_WRITEWATCH;
1539 VIRTUAL_SetProt( view, page, page_size, *vprot );
1541 /* ignore fault if page is writable now */
1542 if (VIRTUAL_GetUnixProt( *vprot ) & PROT_WRITE) ret = STATUS_SUCCESS;
1544 if (!on_signal_stack && (*vprot & VPROT_GUARD))
1546 VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1547 ret = STATUS_GUARD_PAGE_VIOLATION;
1550 server_leave_uninterrupted_section( &csVirtual, &sigset );
1551 return ret;
1556 /***********************************************************************
1557 * virtual_is_valid_code_address
1559 BOOL virtual_is_valid_code_address( const void *addr, SIZE_T size )
1561 struct file_view *view;
1562 BOOL ret = FALSE;
1563 sigset_t sigset;
1565 server_enter_uninterrupted_section( &csVirtual, &sigset );
1566 if ((view = VIRTUAL_FindView( addr, size )))
1567 ret = !(view->protect & VPROT_SYSTEM); /* system views are not visible to the app */
1568 server_leave_uninterrupted_section( &csVirtual, &sigset );
1569 return ret;
1573 /***********************************************************************
1574 * virtual_handle_stack_fault
1576 * Handle an access fault inside the current thread stack.
1577 * Called from inside a signal handler.
1579 BOOL virtual_handle_stack_fault( void *addr )
1581 struct file_view *view;
1582 BOOL ret = FALSE;
1584 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1585 if ((view = VIRTUAL_FindView( addr, 0 )))
1587 void *page = ROUND_ADDR( addr, page_mask );
1588 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1589 if (vprot & VPROT_GUARD)
1591 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1592 NtCurrentTeb()->Tib.StackLimit = page;
1593 if ((char *)page >= (char *)NtCurrentTeb()->DeallocationStack + 2*page_size)
1595 vprot = view->prot[((char *)page - page_size - (char *)view->base) >> page_shift];
1596 VIRTUAL_SetProt( view, (char *)page - page_size, page_size, vprot | VPROT_GUARD );
1598 ret = TRUE;
1601 RtlLeaveCriticalSection( &csVirtual );
1602 return ret;
1606 /***********************************************************************
1607 * virtual_check_buffer_for_read
1609 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
1611 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
1613 if (!size) return TRUE;
1614 if (!ptr) return FALSE;
1616 __TRY
1618 volatile const char *p = ptr;
1619 char dummy __attribute__((unused));
1620 SIZE_T count = size;
1622 while (count > page_size)
1624 dummy = *p;
1625 p += page_size;
1626 count -= page_size;
1628 dummy = p[0];
1629 dummy = p[count - 1];
1631 __EXCEPT_PAGE_FAULT
1633 return FALSE;
1635 __ENDTRY
1636 return TRUE;
1640 /***********************************************************************
1641 * virtual_check_buffer_for_write
1643 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
1645 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
1647 if (!size) return TRUE;
1648 if (!ptr) return FALSE;
1650 __TRY
1652 volatile char *p = ptr;
1653 SIZE_T count = size;
1655 while (count > page_size)
1657 *p |= 0;
1658 p += page_size;
1659 count -= page_size;
1661 p[0] |= 0;
1662 p[count - 1] |= 0;
1664 __EXCEPT_PAGE_FAULT
1666 return FALSE;
1668 __ENDTRY
1669 return TRUE;
1673 /***********************************************************************
1674 * virtual_uninterrupted_read_memory
1676 * Similar to NtReadVirtualMemory, but without wineserver calls. Moreover
1677 * permissions are checked before accessing each page, to ensure that no
1678 * exceptions can happen.
1680 SIZE_T virtual_uninterrupted_read_memory( const void *addr, void *buffer, SIZE_T size )
1682 struct file_view *view;
1683 sigset_t sigset;
1684 SIZE_T bytes_read = 0;
1686 if (!size) return 0;
1688 server_enter_uninterrupted_section( &csVirtual, &sigset );
1689 if ((view = VIRTUAL_FindView( addr, size )))
1691 if (!(view->protect & VPROT_SYSTEM))
1693 void *page = ROUND_ADDR( addr, page_mask );
1694 BYTE *p = view->prot + (((const char *)page - (const char *)view->base) >> page_shift);
1696 while (bytes_read < size && (VIRTUAL_GetUnixProt( *p++ ) & PROT_READ))
1698 SIZE_T block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
1699 memcpy( buffer, addr, block_size );
1701 addr = (const void *)((const char *)addr + block_size);
1702 buffer = (void *)((char *)buffer + block_size);
1703 bytes_read += block_size;
1707 server_leave_uninterrupted_section( &csVirtual, &sigset );
1708 return bytes_read;
1712 /***********************************************************************
1713 * virtual_uninterrupted_write_memory
1715 * Similar to NtWriteVirtualMemory, but without wineserver calls. Moreover
1716 * permissions are checked before accessing each page, to ensure that no
1717 * exceptions can happen.
1719 SIZE_T virtual_uninterrupted_write_memory( void *addr, const void *buffer, SIZE_T size )
1721 struct file_view *view;
1722 sigset_t sigset;
1723 SIZE_T bytes_written = 0;
1725 if (!size) return 0;
1727 server_enter_uninterrupted_section( &csVirtual, &sigset );
1728 if ((view = VIRTUAL_FindView( addr, size )))
1730 if (!(view->protect & VPROT_SYSTEM))
1732 while (bytes_written < size)
1734 void *page = ROUND_ADDR( addr, page_mask );
1735 BYTE *p = view->prot + (((const char *)page - (const char *)view->base) >> page_shift);
1736 SIZE_T block_size;
1738 /* If the page is not writeable then check for write watches
1739 * before giving up. This can be done without raising a real
1740 * exception. Similar to virtual_handle_fault. */
1741 if (!(VIRTUAL_GetUnixProt( *p ) & PROT_WRITE))
1743 if (!(view->protect & VPROT_WRITEWATCH))
1744 break;
1746 if (*p & VPROT_WRITEWATCH)
1748 *p &= ~VPROT_WRITEWATCH;
1749 VIRTUAL_SetProt( view, page, page_size, *p );
1751 /* ignore fault if page is writable now */
1752 if (!(VIRTUAL_GetUnixProt( *p ) & PROT_WRITE))
1753 break;
1756 block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
1757 memcpy( addr, buffer, block_size );
1759 addr = (void *)((char *)addr + block_size);
1760 buffer = (const void *)((const char *)buffer + block_size);
1761 bytes_written += block_size;
1765 server_leave_uninterrupted_section( &csVirtual, &sigset );
1766 return bytes_written;
1770 /***********************************************************************
1771 * VIRTUAL_SetForceExec
1773 * Whether to force exec prot on all views.
1775 void VIRTUAL_SetForceExec( BOOL enable )
1777 struct file_view *view;
1778 sigset_t sigset;
1780 server_enter_uninterrupted_section( &csVirtual, &sigset );
1781 if (!force_exec_prot != !enable) /* change all existing views */
1783 force_exec_prot = enable;
1785 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1787 UINT i, count;
1788 char *addr = view->base;
1789 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1790 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1792 if (view->protect & VPROT_NOEXEC) continue;
1793 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1795 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1796 if (prot == unix_prot) continue;
1797 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1799 TRACE( "%s exec prot for %p-%p\n",
1800 force_exec_prot ? "enabling" : "disabling",
1801 addr, addr + (count << page_shift) - 1 );
1802 mprotect( addr, count << page_shift,
1803 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1805 addr += (count << page_shift);
1806 unix_prot = prot;
1807 count = 0;
1809 if (count)
1811 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1813 TRACE( "%s exec prot for %p-%p\n",
1814 force_exec_prot ? "enabling" : "disabling",
1815 addr, addr + (count << page_shift) - 1 );
1816 mprotect( addr, count << page_shift,
1817 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1822 server_leave_uninterrupted_section( &csVirtual, &sigset );
1825 struct free_range
1827 char *base;
1828 char *limit;
1831 /* free reserved areas above the limit; callback for wine_mmap_enum_reserved_areas */
1832 static int free_reserved_memory( void *base, size_t size, void *arg )
1834 struct free_range *range = arg;
1836 if ((char *)base >= range->limit) return 0;
1837 if ((char *)base + size <= range->base) return 0;
1838 if ((char *)base < range->base)
1840 size -= range->base - (char *)base;
1841 base = range->base;
1843 if ((char *)base + size > range->limit) size = range->limit - (char *)base;
1844 remove_reserved_area( base, size );
1845 return 1; /* stop enumeration since the list has changed */
1848 /***********************************************************************
1849 * virtual_release_address_space
1851 * Release some address space once we have loaded and initialized the app.
1853 void virtual_release_address_space(void)
1855 struct free_range range;
1856 sigset_t sigset;
1858 if (is_win64) return;
1860 server_enter_uninterrupted_section( &csVirtual, &sigset );
1862 range.base = (char *)0x82000000;
1863 range.limit = user_space_limit;
1865 if (range.limit > range.base)
1867 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
1869 else
1871 #ifndef __APPLE__ /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
1872 range.base = (char *)0x20000000;
1873 range.limit = (char *)0x7f000000;
1874 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
1875 #endif
1878 server_leave_uninterrupted_section( &csVirtual, &sigset );
1882 /***********************************************************************
1883 * virtual_set_large_address_space
1885 * Enable use of a large address space when allowed by the application.
1887 void virtual_set_large_address_space(void)
1889 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1891 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE)) return;
1892 /* no large address space on win9x */
1893 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1895 user_space_limit = working_set_limit = address_space_limit;
1899 /***********************************************************************
1900 * NtAllocateVirtualMemory (NTDLL.@)
1901 * ZwAllocateVirtualMemory (NTDLL.@)
1903 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1904 SIZE_T *size_ptr, ULONG type, ULONG protect )
1906 void *base;
1907 unsigned int vprot;
1908 SIZE_T size = *size_ptr;
1909 SIZE_T mask = get_mask( zero_bits );
1910 NTSTATUS status = STATUS_SUCCESS;
1911 struct file_view *view;
1912 sigset_t sigset;
1914 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1916 if (!size) return STATUS_INVALID_PARAMETER;
1918 if (process != NtCurrentProcess())
1920 apc_call_t call;
1921 apc_result_t result;
1923 memset( &call, 0, sizeof(call) );
1925 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1926 call.virtual_alloc.addr = wine_server_client_ptr( *ret );
1927 call.virtual_alloc.size = *size_ptr;
1928 call.virtual_alloc.zero_bits = zero_bits;
1929 call.virtual_alloc.op_type = type;
1930 call.virtual_alloc.prot = protect;
1931 status = server_queue_process_apc( process, &call, &result );
1932 if (status != STATUS_SUCCESS) return status;
1934 if (result.virtual_alloc.status == STATUS_SUCCESS)
1936 *ret = wine_server_get_ptr( result.virtual_alloc.addr );
1937 *size_ptr = result.virtual_alloc.size;
1939 return result.virtual_alloc.status;
1942 /* Round parameters to a page boundary */
1944 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1946 if ((status = get_vprot_flags( protect, &vprot, FALSE ))) return status;
1947 if (vprot & VPROT_WRITECOPY) return STATUS_INVALID_PAGE_PROTECTION;
1948 vprot |= VPROT_VALLOC;
1949 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1951 if (*ret)
1953 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1954 base = ROUND_ADDR( *ret, mask );
1955 else
1956 base = ROUND_ADDR( *ret, page_mask );
1957 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1959 /* address 1 is magic to mean DOS area */
1960 if (!base && *ret == (void *)1 && size == 0x110000)
1962 server_enter_uninterrupted_section( &csVirtual, &sigset );
1963 status = allocate_dos_memory( &view, vprot );
1964 if (status == STATUS_SUCCESS)
1966 *ret = view->base;
1967 *size_ptr = view->size;
1969 server_leave_uninterrupted_section( &csVirtual, &sigset );
1970 return status;
1973 /* disallow low 64k, wrap-around and kernel space */
1974 if (((char *)base < (char *)0x10000) ||
1975 ((char *)base + size < (char *)base) ||
1976 is_beyond_limit( base, size, address_space_limit ))
1977 return STATUS_INVALID_PARAMETER;
1979 else
1981 base = NULL;
1982 size = (size + page_mask) & ~page_mask;
1985 /* Compute the alloc type flags */
1987 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
1988 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1990 WARN("called with wrong alloc type flags (%08x) !\n", type);
1991 return STATUS_INVALID_PARAMETER;
1994 /* Reserve the memory */
1996 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1998 if ((type & MEM_RESERVE) || !base)
2000 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
2001 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
2002 if (status == STATUS_SUCCESS) base = view->base;
2004 else if (type & MEM_RESET)
2006 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
2007 else madvise( base, size, MADV_DONTNEED );
2009 else /* commit the pages */
2011 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
2012 else if (view->mapping && (view->protect & VPROT_COMMITTED)) status = STATUS_ALREADY_COMMITTED;
2013 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
2014 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
2016 SERVER_START_REQ( add_mapping_committed_range )
2018 req->handle = wine_server_obj_handle( view->mapping );
2019 req->offset = (char *)base - (char *)view->base;
2020 req->size = size;
2021 wine_server_call( req );
2023 SERVER_END_REQ;
2027 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
2029 if (status == STATUS_SUCCESS)
2031 *ret = base;
2032 *size_ptr = size;
2034 return status;
2038 /***********************************************************************
2039 * NtFreeVirtualMemory (NTDLL.@)
2040 * ZwFreeVirtualMemory (NTDLL.@)
2042 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
2044 struct file_view *view;
2045 char *base;
2046 sigset_t sigset;
2047 NTSTATUS status = STATUS_SUCCESS;
2048 LPVOID addr = *addr_ptr;
2049 SIZE_T size = *size_ptr;
2051 TRACE("%p %p %08lx %x\n", process, addr, size, type );
2053 if (process != NtCurrentProcess())
2055 apc_call_t call;
2056 apc_result_t result;
2058 memset( &call, 0, sizeof(call) );
2060 call.virtual_free.type = APC_VIRTUAL_FREE;
2061 call.virtual_free.addr = wine_server_client_ptr( addr );
2062 call.virtual_free.size = size;
2063 call.virtual_free.op_type = type;
2064 status = server_queue_process_apc( process, &call, &result );
2065 if (status != STATUS_SUCCESS) return status;
2067 if (result.virtual_free.status == STATUS_SUCCESS)
2069 *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
2070 *size_ptr = result.virtual_free.size;
2072 return result.virtual_free.status;
2075 /* Fix the parameters */
2077 size = ROUND_SIZE( addr, size );
2078 base = ROUND_ADDR( addr, page_mask );
2080 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
2081 if (!base) return STATUS_INVALID_PARAMETER;
2083 server_enter_uninterrupted_section( &csVirtual, &sigset );
2085 if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
2087 status = STATUS_INVALID_PARAMETER;
2089 else if (type == MEM_RELEASE)
2091 /* Free the pages */
2093 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
2094 else
2096 delete_view( view );
2097 *addr_ptr = base;
2098 *size_ptr = size;
2101 else if (type == MEM_DECOMMIT)
2103 status = decommit_pages( view, base - (char *)view->base, size );
2104 if (status == STATUS_SUCCESS)
2106 *addr_ptr = base;
2107 *size_ptr = size;
2110 else
2112 WARN("called with wrong free type flags (%08x) !\n", type);
2113 status = STATUS_INVALID_PARAMETER;
2116 server_leave_uninterrupted_section( &csVirtual, &sigset );
2117 return status;
2120 static ULONG map_protection_to_access( ULONG vprot )
2122 vprot &= VPROT_READ | VPROT_WRITE | VPROT_EXEC | VPROT_WRITECOPY;
2123 if (vprot & VPROT_EXEC)
2125 if (vprot & VPROT_WRITE) vprot |= VPROT_WRITECOPY;
2127 else vprot &= ~VPROT_WRITECOPY;
2128 return vprot;
2131 static BOOL is_compatible_protection( const struct file_view *view, ULONG new_prot )
2133 ULONG view_prot, map_prot;
2135 view_prot = map_protection_to_access( view->protect );
2136 new_prot = map_protection_to_access( new_prot );
2138 if (view_prot == new_prot) return TRUE;
2139 if (!view_prot) return FALSE;
2141 if ((view_prot & new_prot) != new_prot) return FALSE;
2143 map_prot = map_protection_to_access( view->map_protect );
2144 if ((map_prot & new_prot) == new_prot) return TRUE;
2146 return FALSE;
2149 /***********************************************************************
2150 * NtProtectVirtualMemory (NTDLL.@)
2151 * ZwProtectVirtualMemory (NTDLL.@)
2153 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
2154 ULONG new_prot, ULONG *old_prot )
2156 struct file_view *view;
2157 sigset_t sigset;
2158 NTSTATUS status = STATUS_SUCCESS;
2159 char *base;
2160 BYTE vprot;
2161 unsigned int new_vprot;
2162 SIZE_T size = *size_ptr;
2163 LPVOID addr = *addr_ptr;
2165 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
2167 if (!old_prot)
2168 return STATUS_ACCESS_VIOLATION;
2170 if (process != NtCurrentProcess())
2172 apc_call_t call;
2173 apc_result_t result;
2175 memset( &call, 0, sizeof(call) );
2177 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
2178 call.virtual_protect.addr = wine_server_client_ptr( addr );
2179 call.virtual_protect.size = size;
2180 call.virtual_protect.prot = new_prot;
2181 status = server_queue_process_apc( process, &call, &result );
2182 if (status != STATUS_SUCCESS) return status;
2184 if (result.virtual_protect.status == STATUS_SUCCESS)
2186 *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
2187 *size_ptr = result.virtual_protect.size;
2188 if (old_prot) *old_prot = result.virtual_protect.prot;
2190 return result.virtual_protect.status;
2193 /* Fix the parameters */
2195 size = ROUND_SIZE( addr, size );
2196 base = ROUND_ADDR( addr, page_mask );
2198 server_enter_uninterrupted_section( &csVirtual, &sigset );
2200 if ((view = VIRTUAL_FindView( base, size )))
2202 /* Make sure all the pages are committed */
2203 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2205 if (!(status = get_vprot_flags( new_prot, &new_vprot, view->protect & VPROT_IMAGE )))
2207 if ((new_vprot & VPROT_WRITECOPY) && (view->protect & VPROT_VALLOC))
2208 status = STATUS_INVALID_PAGE_PROTECTION;
2209 else
2211 if (!view->mapping || is_compatible_protection( view, new_vprot ))
2213 new_vprot |= VPROT_COMMITTED;
2214 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
2215 if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
2217 else status = STATUS_INVALID_PAGE_PROTECTION;
2221 else status = STATUS_NOT_COMMITTED;
2223 else status = STATUS_INVALID_PARAMETER;
2225 server_leave_uninterrupted_section( &csVirtual, &sigset );
2227 if (status == STATUS_SUCCESS)
2229 *addr_ptr = base;
2230 *size_ptr = size;
2232 return status;
2236 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
2237 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
2239 MEMORY_BASIC_INFORMATION *info = arg;
2240 void *end = (char *)start + size;
2242 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
2244 if (info->BaseAddress >= end)
2246 if (info->AllocationBase < end) info->AllocationBase = end;
2247 return 0;
2250 if (info->BaseAddress >= start || start <= address_space_start)
2252 /* it's a real free area */
2253 info->State = MEM_FREE;
2254 info->Protect = PAGE_NOACCESS;
2255 info->AllocationBase = 0;
2256 info->AllocationProtect = 0;
2257 info->Type = 0;
2258 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
2259 info->RegionSize = (char *)end - (char *)info->BaseAddress;
2261 else /* outside of the reserved area, pretend it's allocated */
2263 info->RegionSize = (char *)start - (char *)info->BaseAddress;
2264 info->State = MEM_RESERVE;
2265 info->Protect = PAGE_NOACCESS;
2266 info->AllocationProtect = PAGE_NOACCESS;
2267 info->Type = MEM_PRIVATE;
2269 return 1;
2272 #define UNIMPLEMENTED_INFO_CLASS(c) \
2273 case c: \
2274 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
2275 return STATUS_INVALID_INFO_CLASS
2277 /***********************************************************************
2278 * NtQueryVirtualMemory (NTDLL.@)
2279 * ZwQueryVirtualMemory (NTDLL.@)
2281 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
2282 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2283 SIZE_T len, SIZE_T *res_len )
2285 struct file_view *view;
2286 char *base, *alloc_base = 0;
2287 struct list *ptr;
2288 SIZE_T size = 0;
2289 MEMORY_BASIC_INFORMATION *info = buffer;
2290 sigset_t sigset;
2292 if (info_class != MemoryBasicInformation)
2294 switch(info_class)
2296 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
2297 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
2298 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
2300 default:
2301 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
2302 process, addr, info_class, buffer, len, res_len);
2303 return STATUS_INVALID_INFO_CLASS;
2307 if (process != NtCurrentProcess())
2309 NTSTATUS status;
2310 apc_call_t call;
2311 apc_result_t result;
2313 memset( &call, 0, sizeof(call) );
2315 call.virtual_query.type = APC_VIRTUAL_QUERY;
2316 call.virtual_query.addr = wine_server_client_ptr( addr );
2317 status = server_queue_process_apc( process, &call, &result );
2318 if (status != STATUS_SUCCESS) return status;
2320 if (result.virtual_query.status == STATUS_SUCCESS)
2322 info->BaseAddress = wine_server_get_ptr( result.virtual_query.base );
2323 info->AllocationBase = wine_server_get_ptr( result.virtual_query.alloc_base );
2324 info->RegionSize = result.virtual_query.size;
2325 info->Protect = result.virtual_query.prot;
2326 info->AllocationProtect = result.virtual_query.alloc_prot;
2327 info->State = (DWORD)result.virtual_query.state << 12;
2328 info->Type = (DWORD)result.virtual_query.alloc_type << 16;
2329 if (info->RegionSize != result.virtual_query.size) /* truncated */
2330 return STATUS_INVALID_PARAMETER; /* FIXME */
2331 if (res_len) *res_len = sizeof(*info);
2333 return result.virtual_query.status;
2336 base = ROUND_ADDR( addr, page_mask );
2338 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2340 /* Find the view containing the address */
2342 server_enter_uninterrupted_section( &csVirtual, &sigset );
2343 ptr = list_head( &views_list );
2344 for (;;)
2346 if (!ptr)
2348 size = (char *)working_set_limit - alloc_base;
2349 view = NULL;
2350 break;
2352 view = LIST_ENTRY( ptr, struct file_view, entry );
2353 if ((char *)view->base > base)
2355 size = (char *)view->base - alloc_base;
2356 view = NULL;
2357 break;
2359 if ((char *)view->base + view->size > base)
2361 alloc_base = view->base;
2362 size = view->size;
2363 break;
2365 alloc_base = (char *)view->base + view->size;
2366 ptr = list_next( &views_list, ptr );
2369 /* Fill the info structure */
2371 info->AllocationBase = alloc_base;
2372 info->BaseAddress = base;
2373 info->RegionSize = size - (base - alloc_base);
2375 if (!view)
2377 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2379 /* not in a reserved area at all, pretend it's allocated */
2380 #ifdef __i386__
2381 if (base >= (char *)address_space_start)
2383 info->State = MEM_RESERVE;
2384 info->Protect = PAGE_NOACCESS;
2385 info->AllocationProtect = PAGE_NOACCESS;
2386 info->Type = MEM_PRIVATE;
2388 else
2389 #endif
2391 info->State = MEM_FREE;
2392 info->Protect = PAGE_NOACCESS;
2393 info->AllocationBase = 0;
2394 info->AllocationProtect = 0;
2395 info->Type = 0;
2399 else
2401 BYTE vprot;
2402 SIZE_T range_size = get_committed_size( view, base, &vprot );
2404 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2405 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2406 info->AllocationBase = alloc_base;
2407 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2408 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2409 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2410 else info->Type = MEM_MAPPED;
2411 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2412 if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2413 info->RegionSize = size - (base - alloc_base);
2415 server_leave_uninterrupted_section( &csVirtual, &sigset );
2417 if (res_len) *res_len = sizeof(*info);
2418 return STATUS_SUCCESS;
2422 /***********************************************************************
2423 * NtLockVirtualMemory (NTDLL.@)
2424 * ZwLockVirtualMemory (NTDLL.@)
2426 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2428 NTSTATUS status = STATUS_SUCCESS;
2430 if (process != NtCurrentProcess())
2432 apc_call_t call;
2433 apc_result_t result;
2435 memset( &call, 0, sizeof(call) );
2437 call.virtual_lock.type = APC_VIRTUAL_LOCK;
2438 call.virtual_lock.addr = wine_server_client_ptr( *addr );
2439 call.virtual_lock.size = *size;
2440 status = server_queue_process_apc( process, &call, &result );
2441 if (status != STATUS_SUCCESS) return status;
2443 if (result.virtual_lock.status == STATUS_SUCCESS)
2445 *addr = wine_server_get_ptr( result.virtual_lock.addr );
2446 *size = result.virtual_lock.size;
2448 return result.virtual_lock.status;
2451 *size = ROUND_SIZE( *addr, *size );
2452 *addr = ROUND_ADDR( *addr, page_mask );
2454 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2455 return status;
2459 /***********************************************************************
2460 * NtUnlockVirtualMemory (NTDLL.@)
2461 * ZwUnlockVirtualMemory (NTDLL.@)
2463 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2465 NTSTATUS status = STATUS_SUCCESS;
2467 if (process != NtCurrentProcess())
2469 apc_call_t call;
2470 apc_result_t result;
2472 memset( &call, 0, sizeof(call) );
2474 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2475 call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2476 call.virtual_unlock.size = *size;
2477 status = server_queue_process_apc( process, &call, &result );
2478 if (status != STATUS_SUCCESS) return status;
2480 if (result.virtual_unlock.status == STATUS_SUCCESS)
2482 *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2483 *size = result.virtual_unlock.size;
2485 return result.virtual_unlock.status;
2488 *size = ROUND_SIZE( *addr, *size );
2489 *addr = ROUND_ADDR( *addr, page_mask );
2491 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2492 return status;
2496 /***********************************************************************
2497 * NtCreateSection (NTDLL.@)
2498 * ZwCreateSection (NTDLL.@)
2500 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2501 const LARGE_INTEGER *size, ULONG protect,
2502 ULONG sec_flags, HANDLE file )
2504 NTSTATUS ret;
2505 unsigned int vprot;
2506 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2507 struct security_descriptor *sd = NULL;
2508 struct object_attributes objattr;
2510 /* Check parameters */
2512 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2514 if ((ret = get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE ))) return ret;
2516 objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
2517 objattr.sd_len = 0;
2518 objattr.name_len = len;
2519 if (attr)
2521 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2522 if (ret != STATUS_SUCCESS) return ret;
2525 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2526 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2527 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2529 /* Create the server object */
2531 SERVER_START_REQ( create_mapping )
2533 req->access = access;
2534 req->attributes = (attr) ? attr->Attributes : 0;
2535 req->file_handle = wine_server_obj_handle( file );
2536 req->size = size ? size->QuadPart : 0;
2537 req->protect = vprot;
2538 wine_server_add_data( req, &objattr, sizeof(objattr) );
2539 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2540 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2541 ret = wine_server_call( req );
2542 *handle = wine_server_ptr_handle( reply->handle );
2544 SERVER_END_REQ;
2546 NTDLL_free_struct_sd( sd );
2548 return ret;
2552 /***********************************************************************
2553 * NtOpenSection (NTDLL.@)
2554 * ZwOpenSection (NTDLL.@)
2556 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2558 NTSTATUS ret;
2559 DWORD len = attr->ObjectName->Length;
2561 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2563 SERVER_START_REQ( open_mapping )
2565 req->access = access;
2566 req->attributes = attr->Attributes;
2567 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2568 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2569 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
2571 SERVER_END_REQ;
2572 return ret;
2576 /***********************************************************************
2577 * NtMapViewOfSection (NTDLL.@)
2578 * ZwMapViewOfSection (NTDLL.@)
2580 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2581 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2582 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2584 NTSTATUS res;
2585 mem_size_t full_size;
2586 ACCESS_MASK access;
2587 SIZE_T size, mask = get_mask( zero_bits );
2588 int unix_handle = -1, needs_close;
2589 unsigned int map_vprot, vprot;
2590 void *base;
2591 struct file_view *view;
2592 DWORD header_size;
2593 HANDLE dup_mapping, shared_file;
2594 LARGE_INTEGER offset;
2595 sigset_t sigset;
2597 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2599 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2600 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2602 /* Check parameters */
2604 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2605 return STATUS_MAPPED_ALIGNMENT;
2607 switch(protect)
2609 case PAGE_NOACCESS:
2610 access = SECTION_MAP_READ;
2611 break;
2612 case PAGE_READWRITE:
2613 case PAGE_EXECUTE_READWRITE:
2614 access = SECTION_MAP_WRITE;
2615 break;
2616 case PAGE_READONLY:
2617 case PAGE_WRITECOPY:
2618 case PAGE_EXECUTE:
2619 case PAGE_EXECUTE_READ:
2620 case PAGE_EXECUTE_WRITECOPY:
2621 access = SECTION_MAP_READ;
2622 break;
2623 default:
2624 return STATUS_INVALID_PAGE_PROTECTION;
2627 if (process != NtCurrentProcess())
2629 apc_call_t call;
2630 apc_result_t result;
2632 memset( &call, 0, sizeof(call) );
2634 call.map_view.type = APC_MAP_VIEW;
2635 call.map_view.handle = wine_server_obj_handle( handle );
2636 call.map_view.addr = wine_server_client_ptr( *addr_ptr );
2637 call.map_view.size = *size_ptr;
2638 call.map_view.offset = offset.QuadPart;
2639 call.map_view.zero_bits = zero_bits;
2640 call.map_view.alloc_type = alloc_type;
2641 call.map_view.prot = protect;
2642 res = server_queue_process_apc( process, &call, &result );
2643 if (res != STATUS_SUCCESS) return res;
2645 if ((NTSTATUS)result.map_view.status >= 0)
2647 *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2648 *size_ptr = result.map_view.size;
2650 return result.map_view.status;
2653 SERVER_START_REQ( get_mapping_info )
2655 req->handle = wine_server_obj_handle( handle );
2656 req->access = access;
2657 res = wine_server_call( req );
2658 map_vprot = reply->protect;
2659 base = wine_server_get_ptr( reply->base );
2660 full_size = reply->size;
2661 header_size = reply->header_size;
2662 dup_mapping = wine_server_ptr_handle( reply->mapping );
2663 shared_file = wine_server_ptr_handle( reply->shared_file );
2664 if ((ULONG_PTR)base != reply->base) base = NULL;
2666 SERVER_END_REQ;
2667 if (res) return res;
2669 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2671 if (map_vprot & VPROT_IMAGE)
2673 size = full_size;
2674 if (size != full_size) /* truncated */
2676 WARN( "Modules larger than 4Gb (%s) not supported\n", wine_dbgstr_longlong(full_size) );
2677 res = STATUS_INVALID_PARAMETER;
2678 goto done;
2680 if (shared_file)
2682 int shared_fd, shared_needs_close;
2684 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2685 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2686 res = map_image( handle, unix_handle, base, size, mask, header_size,
2687 shared_fd, dup_mapping, map_vprot, addr_ptr );
2688 if (shared_needs_close) close( shared_fd );
2689 NtClose( shared_file );
2691 else
2693 res = map_image( handle, unix_handle, base, size, mask, header_size,
2694 -1, dup_mapping, map_vprot, addr_ptr );
2696 if (needs_close) close( unix_handle );
2697 if (res >= 0) *size_ptr = size;
2698 return res;
2701 res = STATUS_INVALID_PARAMETER;
2702 if (offset.QuadPart >= full_size) goto done;
2703 if (*size_ptr)
2705 if (*size_ptr > full_size - offset.QuadPart) goto done;
2706 size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2707 if (size < *size_ptr) goto done; /* wrap-around */
2709 else
2711 size = full_size - offset.QuadPart;
2712 if (size != full_size - offset.QuadPart) /* truncated */
2714 WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2715 wine_dbgstr_longlong(full_size) );
2716 goto done;
2720 /* Reserve a properly aligned area */
2722 server_enter_uninterrupted_section( &csVirtual, &sigset );
2724 get_vprot_flags( protect, &vprot, map_vprot & VPROT_IMAGE );
2725 vprot |= (map_vprot & VPROT_COMMITTED);
2726 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2727 if (res)
2729 server_leave_uninterrupted_section( &csVirtual, &sigset );
2730 goto done;
2733 /* Map the file */
2735 TRACE("handle=%p size=%lx offset=%x%08x\n",
2736 handle, size, offset.u.HighPart, offset.u.LowPart );
2738 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2739 if (res == STATUS_SUCCESS)
2741 *addr_ptr = view->base;
2742 *size_ptr = size;
2743 view->mapping = dup_mapping;
2744 view->map_protect = map_vprot;
2745 dup_mapping = 0; /* don't close it */
2747 else
2749 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2750 view->base, size, offset.u.HighPart, offset.u.LowPart );
2751 delete_view( view );
2754 server_leave_uninterrupted_section( &csVirtual, &sigset );
2756 done:
2757 if (dup_mapping) NtClose( dup_mapping );
2758 if (needs_close) close( unix_handle );
2759 return res;
2763 /***********************************************************************
2764 * NtUnmapViewOfSection (NTDLL.@)
2765 * ZwUnmapViewOfSection (NTDLL.@)
2767 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2769 struct file_view *view;
2770 NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
2771 sigset_t sigset;
2772 void *base = ROUND_ADDR( addr, page_mask );
2774 if (process != NtCurrentProcess())
2776 apc_call_t call;
2777 apc_result_t result;
2779 memset( &call, 0, sizeof(call) );
2781 call.unmap_view.type = APC_UNMAP_VIEW;
2782 call.unmap_view.addr = wine_server_client_ptr( addr );
2783 status = server_queue_process_apc( process, &call, &result );
2784 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2785 return status;
2788 server_enter_uninterrupted_section( &csVirtual, &sigset );
2789 if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base) && !(view->protect & VPROT_VALLOC))
2791 delete_view( view );
2792 status = STATUS_SUCCESS;
2794 server_leave_uninterrupted_section( &csVirtual, &sigset );
2795 return status;
2799 /***********************************************************************
2800 * NtFlushVirtualMemory (NTDLL.@)
2801 * ZwFlushVirtualMemory (NTDLL.@)
2803 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2804 SIZE_T *size_ptr, ULONG unknown )
2806 struct file_view *view;
2807 NTSTATUS status = STATUS_SUCCESS;
2808 sigset_t sigset;
2809 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2811 if (process != NtCurrentProcess())
2813 apc_call_t call;
2814 apc_result_t result;
2816 memset( &call, 0, sizeof(call) );
2818 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2819 call.virtual_flush.addr = wine_server_client_ptr( addr );
2820 call.virtual_flush.size = *size_ptr;
2821 status = server_queue_process_apc( process, &call, &result );
2822 if (status != STATUS_SUCCESS) return status;
2824 if (result.virtual_flush.status == STATUS_SUCCESS)
2826 *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2827 *size_ptr = result.virtual_flush.size;
2829 return result.virtual_flush.status;
2832 server_enter_uninterrupted_section( &csVirtual, &sigset );
2833 if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2834 else
2836 if (!*size_ptr) *size_ptr = view->size;
2837 *addr_ptr = addr;
2838 #ifdef MS_ASYNC
2839 if (msync( addr, *size_ptr, MS_ASYNC )) status = STATUS_NOT_MAPPED_DATA;
2840 #endif
2842 server_leave_uninterrupted_section( &csVirtual, &sigset );
2843 return status;
2847 /***********************************************************************
2848 * NtGetWriteWatch (NTDLL.@)
2849 * ZwGetWriteWatch (NTDLL.@)
2851 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
2852 ULONG_PTR *count, ULONG *granularity )
2854 struct file_view *view;
2855 NTSTATUS status = STATUS_SUCCESS;
2856 sigset_t sigset;
2858 size = ROUND_SIZE( base, size );
2859 base = ROUND_ADDR( base, page_mask );
2861 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
2862 if (!*count || !size) return STATUS_INVALID_PARAMETER;
2863 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
2865 if (!addresses) return STATUS_ACCESS_VIOLATION;
2867 TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
2868 addresses, *count );
2870 server_enter_uninterrupted_section( &csVirtual, &sigset );
2872 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2874 ULONG_PTR pos = 0;
2875 char *addr = base;
2876 char *end = addr + size;
2878 while (pos < *count && addr < end)
2880 BYTE prot = view->prot[(addr - (char *)view->base) >> page_shift];
2881 if (!(prot & VPROT_WRITEWATCH)) addresses[pos++] = addr;
2882 addr += page_size;
2884 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( view, base, addr - (char *)base );
2885 *count = pos;
2886 *granularity = page_size;
2888 else status = STATUS_INVALID_PARAMETER;
2890 server_leave_uninterrupted_section( &csVirtual, &sigset );
2891 return status;
2895 /***********************************************************************
2896 * NtResetWriteWatch (NTDLL.@)
2897 * ZwResetWriteWatch (NTDLL.@)
2899 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
2901 struct file_view *view;
2902 NTSTATUS status = STATUS_SUCCESS;
2903 sigset_t sigset;
2905 size = ROUND_SIZE( base, size );
2906 base = ROUND_ADDR( base, page_mask );
2908 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
2910 if (!size) return STATUS_INVALID_PARAMETER;
2912 server_enter_uninterrupted_section( &csVirtual, &sigset );
2914 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2915 reset_write_watches( view, base, size );
2916 else
2917 status = STATUS_INVALID_PARAMETER;
2919 server_leave_uninterrupted_section( &csVirtual, &sigset );
2920 return status;
2924 /***********************************************************************
2925 * NtReadVirtualMemory (NTDLL.@)
2926 * ZwReadVirtualMemory (NTDLL.@)
2928 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2929 SIZE_T size, SIZE_T *bytes_read )
2931 NTSTATUS status;
2933 if (virtual_check_buffer_for_write( buffer, size ))
2935 SERVER_START_REQ( read_process_memory )
2937 req->handle = wine_server_obj_handle( process );
2938 req->addr = wine_server_client_ptr( addr );
2939 wine_server_set_reply( req, buffer, size );
2940 if ((status = wine_server_call( req ))) size = 0;
2942 SERVER_END_REQ;
2944 else
2946 status = STATUS_ACCESS_VIOLATION;
2947 size = 0;
2949 if (bytes_read) *bytes_read = size;
2950 return status;
2954 /***********************************************************************
2955 * NtWriteVirtualMemory (NTDLL.@)
2956 * ZwWriteVirtualMemory (NTDLL.@)
2958 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2959 SIZE_T size, SIZE_T *bytes_written )
2961 NTSTATUS status;
2963 if (virtual_check_buffer_for_read( buffer, size ))
2965 SERVER_START_REQ( write_process_memory )
2967 req->handle = wine_server_obj_handle( process );
2968 req->addr = wine_server_client_ptr( addr );
2969 wine_server_add_data( req, buffer, size );
2970 if ((status = wine_server_call( req ))) size = 0;
2972 SERVER_END_REQ;
2974 else
2976 status = STATUS_PARTIAL_COPY;
2977 size = 0;
2979 if (bytes_written) *bytes_written = size;
2980 return status;
2984 /***********************************************************************
2985 * NtAreMappedFilesTheSame (NTDLL.@)
2986 * ZwAreMappedFilesTheSame (NTDLL.@)
2988 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2990 struct file_view *view1, *view2;
2991 struct stat st1, st2;
2992 NTSTATUS status;
2993 sigset_t sigset;
2995 TRACE("%p %p\n", addr1, addr2);
2997 server_enter_uninterrupted_section( &csVirtual, &sigset );
2999 view1 = VIRTUAL_FindView( addr1, 0 );
3000 view2 = VIRTUAL_FindView( addr2, 0 );
3002 if (!view1 || !view2)
3003 status = STATUS_INVALID_ADDRESS;
3004 else if ((view1->protect & VPROT_VALLOC) || (view2->protect & VPROT_VALLOC))
3005 status = STATUS_CONFLICTING_ADDRESSES;
3006 else if (view1 == view2)
3007 status = STATUS_SUCCESS;
3008 else if (!(view1->protect & VPROT_IMAGE) || !(view2->protect & VPROT_IMAGE))
3009 status = STATUS_NOT_SAME_DEVICE;
3010 else if (!stat_mapping_file( view1, &st1 ) && !stat_mapping_file( view2, &st2 ) &&
3011 st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
3012 status = STATUS_SUCCESS;
3013 else
3014 status = STATUS_NOT_SAME_DEVICE;
3016 server_leave_uninterrupted_section( &csVirtual, &sigset );
3017 return status;