hidclass.sys: Correct input vs output parameters for IOCTL_HID_SET_FEATURE.
[wine.git] / dlls / ntdll / virtual.c
blob5c43d26d4eb04e07e32699808d6568770923f8fc
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;
1056 /***********************************************************************
1057 * map_image
1059 * Map an executable (PE format) image into memory.
1061 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
1062 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, unsigned int map_vprot, PVOID *addr_ptr )
1064 IMAGE_DOS_HEADER *dos;
1065 IMAGE_NT_HEADERS *nt;
1066 IMAGE_SECTION_HEADER sections[96];
1067 IMAGE_SECTION_HEADER *sec;
1068 IMAGE_DATA_DIRECTORY *imports;
1069 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
1070 int i;
1071 off_t pos;
1072 sigset_t sigset;
1073 struct stat st;
1074 struct file_view *view = NULL;
1075 char *ptr, *header_end, *header_start;
1077 /* zero-map the whole range */
1079 server_enter_uninterrupted_section( &csVirtual, &sigset );
1081 if (base >= (char *)address_space_start) /* make sure the DOS area remains free */
1082 status = map_view( &view, base, total_size, mask, FALSE,
1083 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1085 if (status != STATUS_SUCCESS)
1086 status = map_view( &view, NULL, total_size, mask, FALSE,
1087 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1089 if (status != STATUS_SUCCESS) goto error;
1091 ptr = view->base;
1092 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
1094 /* map the header */
1096 if (fstat( fd, &st ) == -1)
1098 status = FILE_GetNtStatus();
1099 goto error;
1101 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
1102 if (!st.st_size) goto error;
1103 header_size = min( header_size, st.st_size );
1104 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1105 !dup_mapping ) != STATUS_SUCCESS) goto error;
1106 dos = (IMAGE_DOS_HEADER *)ptr;
1107 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1108 header_end = ptr + ROUND_SIZE( 0, header_size );
1109 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1110 if ((char *)(nt + 1) > header_end) goto error;
1111 header_start = (char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader;
1112 if (nt->FileHeader.NumberOfSections > sizeof(sections)/sizeof(*sections)) goto error;
1113 if (header_start + sizeof(*sections) * nt->FileHeader.NumberOfSections > header_end) goto error;
1114 /* Some applications (e.g. the Steam version of Borderlands) map over the top of the section headers,
1115 * copying the headers into local memory is necessary to properly load such applications. */
1116 memcpy(sections, header_start, sizeof(*sections) * nt->FileHeader.NumberOfSections);
1117 sec = sections;
1119 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
1120 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
1122 /* check for non page-aligned binary */
1124 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1126 /* unaligned sections, this happens for native subsystem binaries */
1127 /* in that case Windows simply maps in the whole file */
1129 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1130 !dup_mapping ) != STATUS_SUCCESS) goto error;
1132 /* check that all sections are loaded at the right offset */
1133 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1134 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1136 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1137 goto error; /* Windows refuses to load in that case too */
1140 /* set the image protections */
1141 VIRTUAL_SetProt( view, ptr, total_size,
1142 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1144 /* no relocations are performed on non page-aligned binaries */
1145 goto done;
1149 /* map all the sections */
1151 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1153 static const SIZE_T sector_align = 0x1ff;
1154 SIZE_T map_size, file_start, file_size, end;
1156 if (!sec->Misc.VirtualSize)
1157 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1158 else
1159 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1161 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1162 file_start = sec->PointerToRawData & ~sector_align;
1163 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1164 if (file_size > map_size) file_size = map_size;
1166 /* a few sanity checks */
1167 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1168 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1170 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1171 sec->Name, sec->VirtualAddress, map_size, total_size );
1172 goto error;
1175 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1176 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1178 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1179 sec->Name, ptr + sec->VirtualAddress,
1180 sec->PointerToRawData, (int)pos, file_size, map_size,
1181 sec->Characteristics );
1182 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1183 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE, FALSE ) != STATUS_SUCCESS)
1185 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1186 goto error;
1189 /* check if the import directory falls inside this section */
1190 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1191 imports->VirtualAddress < sec->VirtualAddress + map_size)
1193 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1194 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1195 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1196 if (end > base)
1197 map_file_into_view( view, shared_fd, base, end - base,
1198 pos + (base - sec->VirtualAddress),
1199 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY, FALSE );
1201 pos += map_size;
1202 continue;
1205 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1206 sec->Name, ptr + sec->VirtualAddress,
1207 sec->PointerToRawData, sec->SizeOfRawData,
1208 sec->Misc.VirtualSize, sec->Characteristics );
1210 if (!sec->PointerToRawData || !file_size) continue;
1212 /* Note: if the section is not aligned properly map_file_into_view will magically
1213 * fall back to read(), so we don't need to check anything here.
1215 end = file_start + file_size;
1216 if (sec->PointerToRawData >= st.st_size ||
1217 end > ((st.st_size + sector_align) & ~sector_align) ||
1218 end < file_start ||
1219 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1220 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1221 !dup_mapping ) != STATUS_SUCCESS)
1223 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1224 goto error;
1227 if (file_size & page_mask)
1229 end = ROUND_SIZE( 0, file_size );
1230 if (end > map_size) end = map_size;
1231 TRACE_(module)("clearing %p - %p\n",
1232 ptr + sec->VirtualAddress + file_size,
1233 ptr + sec->VirtualAddress + end );
1234 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1238 /* set the image protections */
1240 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1242 sec = sections;
1243 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1245 SIZE_T size;
1246 BYTE vprot = VPROT_COMMITTED;
1248 if (sec->Misc.VirtualSize)
1249 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1250 else
1251 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1253 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1254 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_WRITECOPY;
1255 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1257 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1258 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1259 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1260 vprot |= VPROT_EXEC;
1262 if (!VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot ) && (vprot & VPROT_EXEC))
1263 ERR( "failed to set %08x protection on section %.8s, noexec filesystem?\n",
1264 sec->Characteristics, sec->Name );
1267 done:
1268 view->mapping = dup_mapping;
1269 view->map_protect = map_vprot;
1270 server_leave_uninterrupted_section( &csVirtual, &sigset );
1272 *addr_ptr = ptr;
1273 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1274 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, ptr - base);
1275 #endif
1276 if (ptr != base) return STATUS_IMAGE_NOT_AT_BASE;
1277 return STATUS_SUCCESS;
1279 error:
1280 if (view) delete_view( view );
1281 server_leave_uninterrupted_section( &csVirtual, &sigset );
1282 if (dup_mapping) close_handle( dup_mapping );
1283 return status;
1287 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1288 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1290 void **heap_base = arg;
1292 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1293 if (size < VIRTUAL_HEAP_SIZE) return 0;
1294 if (is_win64 && base < (void *)0x80000000) return 0;
1295 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1296 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1297 return (*heap_base != (void *)-1);
1300 /***********************************************************************
1301 * virtual_init
1303 void virtual_init(void)
1305 const char *preload;
1306 void *heap_base;
1307 size_t size;
1308 struct file_view *heap_view;
1310 #if !defined(__i386__) && !defined(__x86_64__)
1311 page_size = sysconf( _SC_PAGESIZE );
1312 page_mask = page_size - 1;
1313 /* Make sure we have a power of 2 */
1314 assert( !(page_size & page_mask) );
1315 page_shift = 0;
1316 while ((1 << page_shift) != page_size) page_shift++;
1317 user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1318 #endif /* page_mask */
1319 if ((preload = getenv("WINEPRELOADRESERVE")))
1321 unsigned long start, end;
1322 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1324 preload_reserve_start = (void *)start;
1325 preload_reserve_end = (void *)end;
1329 /* try to find space in a reserved area for the virtual heap */
1330 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1331 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1333 assert( heap_base != (void *)-1 );
1334 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1335 VIRTUAL_HEAP_SIZE, NULL, NULL );
1336 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1338 /* make the DOS area accessible (except the low 64K) to hide bugs in broken apps like Excel 2003 */
1339 size = (char *)address_space_start - (char *)0x10000;
1340 if (size && wine_mmap_is_in_reserved_area( (void*)0x10000, size ) == 1)
1341 wine_anon_mmap( (void *)0x10000, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1345 /***********************************************************************
1346 * virtual_init_threading
1348 void virtual_init_threading(void)
1350 use_locks = TRUE;
1354 /***********************************************************************
1355 * virtual_get_system_info
1357 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1359 info->unknown = 0;
1360 info->KeMaximumIncrement = 0; /* FIXME */
1361 info->PageSize = page_size;
1362 info->MmLowestPhysicalPage = 1;
1363 info->MmHighestPhysicalPage = 0x7fffffff / page_size;
1364 info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
1365 info->AllocationGranularity = get_mask(0) + 1;
1366 info->LowestUserAddress = (void *)0x10000;
1367 info->HighestUserAddress = (char *)user_space_limit - 1;
1368 info->ActiveProcessorsAffinityMask = get_system_affinity_mask();
1369 info->NumberOfProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1373 /***********************************************************************
1374 * virtual_create_builtin_view
1376 NTSTATUS virtual_create_builtin_view( void *module )
1378 NTSTATUS status;
1379 sigset_t sigset;
1380 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1381 SIZE_T size = nt->OptionalHeader.SizeOfImage;
1382 IMAGE_SECTION_HEADER *sec;
1383 struct file_view *view;
1384 void *base;
1385 int i;
1387 size = ROUND_SIZE( module, size );
1388 base = ROUND_ADDR( module, page_mask );
1389 server_enter_uninterrupted_section( &csVirtual, &sigset );
1390 status = create_view( &view, base, size, VPROT_SYSTEM | VPROT_IMAGE |
1391 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1392 if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
1393 server_leave_uninterrupted_section( &csVirtual, &sigset );
1395 if (status) return status;
1397 /* The PE header is always read-only, no write, no execute. */
1398 view->prot[0] = VPROT_COMMITTED | VPROT_READ;
1400 sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
1401 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1403 BYTE flags = VPROT_COMMITTED;
1405 if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
1406 if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
1407 if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
1408 memset (view->prot + (sec[i].VirtualAddress >> page_shift), flags,
1409 ROUND_SIZE( sec[i].VirtualAddress, sec[i].Misc.VirtualSize ) >> page_shift );
1412 return status;
1416 /***********************************************************************
1417 * virtual_alloc_thread_stack
1419 NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1421 struct file_view *view;
1422 NTSTATUS status;
1423 sigset_t sigset;
1424 SIZE_T size;
1426 if (!reserve_size || !commit_size)
1428 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1429 if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
1430 if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1433 size = max( reserve_size, commit_size );
1434 if (size < 1024 * 1024) size = 1024 * 1024; /* Xlib needs a large stack */
1435 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1437 server_enter_uninterrupted_section( &csVirtual, &sigset );
1439 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1440 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1441 goto done;
1443 #ifdef VALGRIND_STACK_REGISTER
1444 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1445 #endif
1447 /* setup no access guard page */
1448 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1449 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1450 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1452 /* note: limit is lower than base since the stack grows down */
1453 teb->DeallocationStack = view->base;
1454 teb->Tib.StackBase = (char *)view->base + view->size;
1455 teb->Tib.StackLimit = (char *)view->base + 2 * page_size;
1456 done:
1457 server_leave_uninterrupted_section( &csVirtual, &sigset );
1458 return status;
1462 /***********************************************************************
1463 * virtual_clear_thread_stack
1465 * Clear the stack contents before calling the main entry point, some broken apps need that.
1467 void virtual_clear_thread_stack(void)
1469 void *stack = NtCurrentTeb()->Tib.StackLimit;
1470 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1472 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1473 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1477 /***********************************************************************
1478 * virtual_handle_fault
1480 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err, BOOL on_signal_stack )
1482 struct file_view *view;
1483 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1484 sigset_t sigset;
1486 server_enter_uninterrupted_section( &csVirtual, &sigset );
1487 if ((view = VIRTUAL_FindView( addr, 0 )))
1489 void *page = ROUND_ADDR( addr, page_mask );
1490 BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1491 if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1493 if (*vprot & VPROT_WRITEWATCH)
1495 *vprot &= ~VPROT_WRITEWATCH;
1496 VIRTUAL_SetProt( view, page, page_size, *vprot );
1498 /* ignore fault if page is writable now */
1499 if (VIRTUAL_GetUnixProt( *vprot ) & PROT_WRITE) ret = STATUS_SUCCESS;
1501 if (!on_signal_stack && (*vprot & VPROT_GUARD))
1503 VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1504 ret = STATUS_GUARD_PAGE_VIOLATION;
1507 server_leave_uninterrupted_section( &csVirtual, &sigset );
1508 return ret;
1513 /***********************************************************************
1514 * virtual_is_valid_code_address
1516 BOOL virtual_is_valid_code_address( const void *addr, SIZE_T size )
1518 struct file_view *view;
1519 BOOL ret = FALSE;
1520 sigset_t sigset;
1522 server_enter_uninterrupted_section( &csVirtual, &sigset );
1523 if ((view = VIRTUAL_FindView( addr, size )))
1524 ret = !(view->protect & VPROT_SYSTEM); /* system views are not visible to the app */
1525 server_leave_uninterrupted_section( &csVirtual, &sigset );
1526 return ret;
1530 /***********************************************************************
1531 * virtual_handle_stack_fault
1533 * Handle an access fault inside the current thread stack.
1534 * Called from inside a signal handler.
1536 BOOL virtual_handle_stack_fault( void *addr )
1538 struct file_view *view;
1539 BOOL ret = FALSE;
1541 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1542 if ((view = VIRTUAL_FindView( addr, 0 )))
1544 void *page = ROUND_ADDR( addr, page_mask );
1545 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1546 if (vprot & VPROT_GUARD)
1548 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1549 NtCurrentTeb()->Tib.StackLimit = page;
1550 if ((char *)page >= (char *)NtCurrentTeb()->DeallocationStack + 2*page_size)
1552 vprot = view->prot[((char *)page - page_size - (char *)view->base) >> page_shift];
1553 VIRTUAL_SetProt( view, (char *)page - page_size, page_size, vprot | VPROT_COMMITTED | VPROT_GUARD );
1555 ret = TRUE;
1558 RtlLeaveCriticalSection( &csVirtual );
1559 return ret;
1563 /***********************************************************************
1564 * virtual_check_buffer_for_read
1566 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
1568 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
1570 if (!size) return TRUE;
1571 if (!ptr) return FALSE;
1573 __TRY
1575 volatile const char *p = ptr;
1576 char dummy __attribute__((unused));
1577 SIZE_T count = size;
1579 while (count > page_size)
1581 dummy = *p;
1582 p += page_size;
1583 count -= page_size;
1585 dummy = p[0];
1586 dummy = p[count - 1];
1588 __EXCEPT_PAGE_FAULT
1590 return FALSE;
1592 __ENDTRY
1593 return TRUE;
1597 /***********************************************************************
1598 * virtual_check_buffer_for_write
1600 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
1602 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
1604 if (!size) return TRUE;
1605 if (!ptr) return FALSE;
1607 __TRY
1609 volatile char *p = ptr;
1610 SIZE_T count = size;
1612 while (count > page_size)
1614 *p |= 0;
1615 p += page_size;
1616 count -= page_size;
1618 p[0] |= 0;
1619 p[count - 1] |= 0;
1621 __EXCEPT_PAGE_FAULT
1623 return FALSE;
1625 __ENDTRY
1626 return TRUE;
1630 /***********************************************************************
1631 * virtual_uninterrupted_read_memory
1633 * Similar to NtReadVirtualMemory, but without wineserver calls. Moreover
1634 * permissions are checked before accessing each page, to ensure that no
1635 * exceptions can happen.
1637 SIZE_T virtual_uninterrupted_read_memory( const void *addr, void *buffer, SIZE_T size )
1639 struct file_view *view;
1640 sigset_t sigset;
1641 SIZE_T bytes_read = 0;
1643 if (!size) return 0;
1645 server_enter_uninterrupted_section( &csVirtual, &sigset );
1646 if ((view = VIRTUAL_FindView( addr, size )))
1648 if (!(view->protect & VPROT_SYSTEM))
1650 void *page = ROUND_ADDR( addr, page_mask );
1651 BYTE *p = view->prot + (((const char *)page - (const char *)view->base) >> page_shift);
1653 while (bytes_read < size && (VIRTUAL_GetUnixProt( *p++ ) & PROT_READ))
1655 SIZE_T block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
1656 memcpy( buffer, addr, block_size );
1658 addr = (const void *)((const char *)addr + block_size);
1659 buffer = (void *)((char *)buffer + block_size);
1660 bytes_read += block_size;
1664 server_leave_uninterrupted_section( &csVirtual, &sigset );
1665 return bytes_read;
1669 /***********************************************************************
1670 * virtual_uninterrupted_write_memory
1672 * Similar to NtWriteVirtualMemory, but without wineserver calls. Moreover
1673 * permissions are checked before accessing each page, to ensure that no
1674 * exceptions can happen.
1676 SIZE_T virtual_uninterrupted_write_memory( void *addr, const void *buffer, SIZE_T size )
1678 struct file_view *view;
1679 sigset_t sigset;
1680 SIZE_T bytes_written = 0;
1682 if (!size) return 0;
1684 server_enter_uninterrupted_section( &csVirtual, &sigset );
1685 if ((view = VIRTUAL_FindView( addr, size )))
1687 if (!(view->protect & VPROT_SYSTEM))
1689 while (bytes_written < size)
1691 void *page = ROUND_ADDR( addr, page_mask );
1692 BYTE *p = view->prot + (((const char *)page - (const char *)view->base) >> page_shift);
1693 SIZE_T block_size;
1695 /* If the page is not writable then check for write watches
1696 * before giving up. This can be done without raising a real
1697 * exception. Similar to virtual_handle_fault. */
1698 if (!(VIRTUAL_GetUnixProt( *p ) & PROT_WRITE))
1700 if (!(view->protect & VPROT_WRITEWATCH))
1701 break;
1703 if (*p & VPROT_WRITEWATCH)
1705 *p &= ~VPROT_WRITEWATCH;
1706 VIRTUAL_SetProt( view, page, page_size, *p );
1708 /* ignore fault if page is writable now */
1709 if (!(VIRTUAL_GetUnixProt( *p ) & PROT_WRITE))
1710 break;
1713 block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
1714 memcpy( addr, buffer, block_size );
1716 addr = (void *)((char *)addr + block_size);
1717 buffer = (const void *)((const char *)buffer + block_size);
1718 bytes_written += block_size;
1722 server_leave_uninterrupted_section( &csVirtual, &sigset );
1723 return bytes_written;
1727 /***********************************************************************
1728 * VIRTUAL_SetForceExec
1730 * Whether to force exec prot on all views.
1732 void VIRTUAL_SetForceExec( BOOL enable )
1734 struct file_view *view;
1735 sigset_t sigset;
1737 server_enter_uninterrupted_section( &csVirtual, &sigset );
1738 if (!force_exec_prot != !enable) /* change all existing views */
1740 force_exec_prot = enable;
1742 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1744 UINT i, count;
1745 char *addr = view->base;
1746 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1747 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1749 if (view->protect & VPROT_NOEXEC) continue;
1750 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1752 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1753 if (prot == unix_prot) continue;
1754 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1756 TRACE( "%s exec prot for %p-%p\n",
1757 force_exec_prot ? "enabling" : "disabling",
1758 addr, addr + (count << page_shift) - 1 );
1759 mprotect( addr, count << page_shift,
1760 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1762 addr += (count << page_shift);
1763 unix_prot = prot;
1764 count = 0;
1766 if (count)
1768 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1770 TRACE( "%s exec prot for %p-%p\n",
1771 force_exec_prot ? "enabling" : "disabling",
1772 addr, addr + (count << page_shift) - 1 );
1773 mprotect( addr, count << page_shift,
1774 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1779 server_leave_uninterrupted_section( &csVirtual, &sigset );
1782 struct free_range
1784 char *base;
1785 char *limit;
1788 /* free reserved areas above the limit; callback for wine_mmap_enum_reserved_areas */
1789 static int free_reserved_memory( void *base, size_t size, void *arg )
1791 struct free_range *range = arg;
1793 if ((char *)base >= range->limit) return 0;
1794 if ((char *)base + size <= range->base) return 0;
1795 if ((char *)base < range->base)
1797 size -= range->base - (char *)base;
1798 base = range->base;
1800 if ((char *)base + size > range->limit) size = range->limit - (char *)base;
1801 remove_reserved_area( base, size );
1802 return 1; /* stop enumeration since the list has changed */
1805 /***********************************************************************
1806 * virtual_release_address_space
1808 * Release some address space once we have loaded and initialized the app.
1810 void virtual_release_address_space(void)
1812 struct free_range range;
1813 sigset_t sigset;
1815 if (is_win64) return;
1817 server_enter_uninterrupted_section( &csVirtual, &sigset );
1819 range.base = (char *)0x82000000;
1820 range.limit = user_space_limit;
1822 if (range.limit > range.base)
1824 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
1826 else
1828 #ifndef __APPLE__ /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
1829 range.base = (char *)0x20000000;
1830 range.limit = (char *)0x7f000000;
1831 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
1832 #endif
1835 server_leave_uninterrupted_section( &csVirtual, &sigset );
1839 /***********************************************************************
1840 * virtual_set_large_address_space
1842 * Enable use of a large address space when allowed by the application.
1844 void virtual_set_large_address_space(void)
1846 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1848 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE)) return;
1849 /* no large address space on win9x */
1850 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1852 user_space_limit = working_set_limit = address_space_limit;
1856 /***********************************************************************
1857 * NtAllocateVirtualMemory (NTDLL.@)
1858 * ZwAllocateVirtualMemory (NTDLL.@)
1860 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1861 SIZE_T *size_ptr, ULONG type, ULONG protect )
1863 void *base;
1864 unsigned int vprot;
1865 SIZE_T size = *size_ptr;
1866 SIZE_T mask = get_mask( zero_bits );
1867 NTSTATUS status = STATUS_SUCCESS;
1868 struct file_view *view;
1869 sigset_t sigset;
1871 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1873 if (!size) return STATUS_INVALID_PARAMETER;
1875 if (process != NtCurrentProcess())
1877 apc_call_t call;
1878 apc_result_t result;
1880 memset( &call, 0, sizeof(call) );
1882 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1883 call.virtual_alloc.addr = wine_server_client_ptr( *ret );
1884 call.virtual_alloc.size = *size_ptr;
1885 call.virtual_alloc.zero_bits = zero_bits;
1886 call.virtual_alloc.op_type = type;
1887 call.virtual_alloc.prot = protect;
1888 status = server_queue_process_apc( process, &call, &result );
1889 if (status != STATUS_SUCCESS) return status;
1891 if (result.virtual_alloc.status == STATUS_SUCCESS)
1893 *ret = wine_server_get_ptr( result.virtual_alloc.addr );
1894 *size_ptr = result.virtual_alloc.size;
1896 return result.virtual_alloc.status;
1899 /* Round parameters to a page boundary */
1901 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1903 if ((status = get_vprot_flags( protect, &vprot, FALSE ))) return status;
1904 if (vprot & VPROT_WRITECOPY) return STATUS_INVALID_PAGE_PROTECTION;
1905 vprot |= VPROT_VALLOC;
1906 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1908 if (*ret)
1910 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1911 base = ROUND_ADDR( *ret, mask );
1912 else
1913 base = ROUND_ADDR( *ret, page_mask );
1914 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1916 /* address 1 is magic to mean DOS area */
1917 if (!base && *ret == (void *)1 && size == 0x110000)
1919 server_enter_uninterrupted_section( &csVirtual, &sigset );
1920 status = allocate_dos_memory( &view, vprot );
1921 if (status == STATUS_SUCCESS)
1923 *ret = view->base;
1924 *size_ptr = view->size;
1926 server_leave_uninterrupted_section( &csVirtual, &sigset );
1927 return status;
1930 /* disallow low 64k, wrap-around and kernel space */
1931 if (((char *)base < (char *)0x10000) ||
1932 ((char *)base + size < (char *)base) ||
1933 is_beyond_limit( base, size, address_space_limit ))
1934 return STATUS_INVALID_PARAMETER;
1936 else
1938 base = NULL;
1939 size = (size + page_mask) & ~page_mask;
1942 /* Compute the alloc type flags */
1944 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
1945 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1947 WARN("called with wrong alloc type flags (%08x) !\n", type);
1948 return STATUS_INVALID_PARAMETER;
1951 /* Reserve the memory */
1953 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1955 if ((type & MEM_RESERVE) || !base)
1957 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
1958 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1959 if (status == STATUS_SUCCESS) base = view->base;
1961 else if (type & MEM_RESET)
1963 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1964 else madvise( base, size, MADV_DONTNEED );
1966 else /* commit the pages */
1968 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1969 else if (view->mapping && (view->protect & VPROT_COMMITTED)) status = STATUS_ALREADY_COMMITTED;
1970 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1971 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1973 SERVER_START_REQ( add_mapping_committed_range )
1975 req->handle = wine_server_obj_handle( view->mapping );
1976 req->offset = (char *)base - (char *)view->base;
1977 req->size = size;
1978 wine_server_call( req );
1980 SERVER_END_REQ;
1984 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1986 if (status == STATUS_SUCCESS)
1988 *ret = base;
1989 *size_ptr = size;
1991 return status;
1995 /***********************************************************************
1996 * NtFreeVirtualMemory (NTDLL.@)
1997 * ZwFreeVirtualMemory (NTDLL.@)
1999 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
2001 struct file_view *view;
2002 char *base;
2003 sigset_t sigset;
2004 NTSTATUS status = STATUS_SUCCESS;
2005 LPVOID addr = *addr_ptr;
2006 SIZE_T size = *size_ptr;
2008 TRACE("%p %p %08lx %x\n", process, addr, size, type );
2010 if (process != NtCurrentProcess())
2012 apc_call_t call;
2013 apc_result_t result;
2015 memset( &call, 0, sizeof(call) );
2017 call.virtual_free.type = APC_VIRTUAL_FREE;
2018 call.virtual_free.addr = wine_server_client_ptr( addr );
2019 call.virtual_free.size = size;
2020 call.virtual_free.op_type = type;
2021 status = server_queue_process_apc( process, &call, &result );
2022 if (status != STATUS_SUCCESS) return status;
2024 if (result.virtual_free.status == STATUS_SUCCESS)
2026 *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
2027 *size_ptr = result.virtual_free.size;
2029 return result.virtual_free.status;
2032 /* Fix the parameters */
2034 size = ROUND_SIZE( addr, size );
2035 base = ROUND_ADDR( addr, page_mask );
2037 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
2038 if (!base) return STATUS_INVALID_PARAMETER;
2040 server_enter_uninterrupted_section( &csVirtual, &sigset );
2042 if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
2044 status = STATUS_INVALID_PARAMETER;
2046 else if (type == MEM_RELEASE)
2048 /* Free the pages */
2050 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
2051 else
2053 delete_view( view );
2054 *addr_ptr = base;
2055 *size_ptr = size;
2058 else if (type == MEM_DECOMMIT)
2060 status = decommit_pages( view, base - (char *)view->base, size );
2061 if (status == STATUS_SUCCESS)
2063 *addr_ptr = base;
2064 *size_ptr = size;
2067 else
2069 WARN("called with wrong free type flags (%08x) !\n", type);
2070 status = STATUS_INVALID_PARAMETER;
2073 server_leave_uninterrupted_section( &csVirtual, &sigset );
2074 return status;
2077 static ULONG map_protection_to_access( ULONG vprot )
2079 vprot &= VPROT_READ | VPROT_WRITE | VPROT_EXEC | VPROT_WRITECOPY;
2080 if (vprot & VPROT_EXEC)
2082 if (vprot & VPROT_WRITE) vprot |= VPROT_WRITECOPY;
2084 else vprot &= ~VPROT_WRITECOPY;
2085 return vprot;
2088 static BOOL is_compatible_protection( const struct file_view *view, ULONG new_prot )
2090 ULONG view_prot, map_prot;
2092 view_prot = map_protection_to_access( view->protect );
2093 new_prot = map_protection_to_access( new_prot );
2095 if (view_prot == new_prot) return TRUE;
2096 if (!view_prot) return FALSE;
2098 if ((view_prot & new_prot) != new_prot) return FALSE;
2100 map_prot = map_protection_to_access( view->map_protect );
2101 if ((map_prot & new_prot) == new_prot) return TRUE;
2103 return FALSE;
2106 /***********************************************************************
2107 * NtProtectVirtualMemory (NTDLL.@)
2108 * ZwProtectVirtualMemory (NTDLL.@)
2110 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
2111 ULONG new_prot, ULONG *old_prot )
2113 struct file_view *view;
2114 sigset_t sigset;
2115 NTSTATUS status = STATUS_SUCCESS;
2116 char *base;
2117 BYTE vprot;
2118 unsigned int new_vprot;
2119 SIZE_T size = *size_ptr;
2120 LPVOID addr = *addr_ptr;
2122 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
2124 if (!old_prot)
2125 return STATUS_ACCESS_VIOLATION;
2127 if (process != NtCurrentProcess())
2129 apc_call_t call;
2130 apc_result_t result;
2132 memset( &call, 0, sizeof(call) );
2134 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
2135 call.virtual_protect.addr = wine_server_client_ptr( addr );
2136 call.virtual_protect.size = size;
2137 call.virtual_protect.prot = new_prot;
2138 status = server_queue_process_apc( process, &call, &result );
2139 if (status != STATUS_SUCCESS) return status;
2141 if (result.virtual_protect.status == STATUS_SUCCESS)
2143 *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
2144 *size_ptr = result.virtual_protect.size;
2145 if (old_prot) *old_prot = result.virtual_protect.prot;
2147 return result.virtual_protect.status;
2150 /* Fix the parameters */
2152 size = ROUND_SIZE( addr, size );
2153 base = ROUND_ADDR( addr, page_mask );
2155 server_enter_uninterrupted_section( &csVirtual, &sigset );
2157 if ((view = VIRTUAL_FindView( base, size )))
2159 /* Make sure all the pages are committed */
2160 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2162 if (!(status = get_vprot_flags( new_prot, &new_vprot, view->protect & VPROT_IMAGE )))
2164 if ((new_vprot & VPROT_WRITECOPY) && (view->protect & VPROT_VALLOC))
2165 status = STATUS_INVALID_PAGE_PROTECTION;
2166 else
2168 if (!view->mapping || is_compatible_protection( view, new_vprot ))
2170 new_vprot |= VPROT_COMMITTED;
2171 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
2172 if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
2174 else status = STATUS_INVALID_PAGE_PROTECTION;
2178 else status = STATUS_NOT_COMMITTED;
2180 else status = STATUS_INVALID_PARAMETER;
2182 server_leave_uninterrupted_section( &csVirtual, &sigset );
2184 if (status == STATUS_SUCCESS)
2186 *addr_ptr = base;
2187 *size_ptr = size;
2189 return status;
2193 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
2194 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
2196 MEMORY_BASIC_INFORMATION *info = arg;
2197 void *end = (char *)start + size;
2199 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
2201 if (info->BaseAddress >= end)
2203 if (info->AllocationBase < end) info->AllocationBase = end;
2204 return 0;
2207 if (info->BaseAddress >= start || start <= address_space_start)
2209 /* it's a real free area */
2210 info->State = MEM_FREE;
2211 info->Protect = PAGE_NOACCESS;
2212 info->AllocationBase = 0;
2213 info->AllocationProtect = 0;
2214 info->Type = 0;
2215 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
2216 info->RegionSize = (char *)end - (char *)info->BaseAddress;
2218 else /* outside of the reserved area, pretend it's allocated */
2220 info->RegionSize = (char *)start - (char *)info->BaseAddress;
2221 info->State = MEM_RESERVE;
2222 info->Protect = PAGE_NOACCESS;
2223 info->AllocationProtect = PAGE_NOACCESS;
2224 info->Type = MEM_PRIVATE;
2226 return 1;
2229 #define UNIMPLEMENTED_INFO_CLASS(c) \
2230 case c: \
2231 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
2232 return STATUS_INVALID_INFO_CLASS
2234 /***********************************************************************
2235 * NtQueryVirtualMemory (NTDLL.@)
2236 * ZwQueryVirtualMemory (NTDLL.@)
2238 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
2239 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2240 SIZE_T len, SIZE_T *res_len )
2242 struct file_view *view;
2243 char *base, *alloc_base = 0;
2244 struct list *ptr;
2245 SIZE_T size = 0;
2246 MEMORY_BASIC_INFORMATION *info = buffer;
2247 sigset_t sigset;
2249 if (info_class != MemoryBasicInformation)
2251 switch(info_class)
2253 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
2254 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
2255 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
2257 default:
2258 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
2259 process, addr, info_class, buffer, len, res_len);
2260 return STATUS_INVALID_INFO_CLASS;
2264 if (process != NtCurrentProcess())
2266 NTSTATUS status;
2267 apc_call_t call;
2268 apc_result_t result;
2270 memset( &call, 0, sizeof(call) );
2272 call.virtual_query.type = APC_VIRTUAL_QUERY;
2273 call.virtual_query.addr = wine_server_client_ptr( addr );
2274 status = server_queue_process_apc( process, &call, &result );
2275 if (status != STATUS_SUCCESS) return status;
2277 if (result.virtual_query.status == STATUS_SUCCESS)
2279 info->BaseAddress = wine_server_get_ptr( result.virtual_query.base );
2280 info->AllocationBase = wine_server_get_ptr( result.virtual_query.alloc_base );
2281 info->RegionSize = result.virtual_query.size;
2282 info->Protect = result.virtual_query.prot;
2283 info->AllocationProtect = result.virtual_query.alloc_prot;
2284 info->State = (DWORD)result.virtual_query.state << 12;
2285 info->Type = (DWORD)result.virtual_query.alloc_type << 16;
2286 if (info->RegionSize != result.virtual_query.size) /* truncated */
2287 return STATUS_INVALID_PARAMETER; /* FIXME */
2288 if (res_len) *res_len = sizeof(*info);
2290 return result.virtual_query.status;
2293 base = ROUND_ADDR( addr, page_mask );
2295 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2297 /* Find the view containing the address */
2299 server_enter_uninterrupted_section( &csVirtual, &sigset );
2300 ptr = list_head( &views_list );
2301 for (;;)
2303 if (!ptr)
2305 size = (char *)working_set_limit - alloc_base;
2306 view = NULL;
2307 break;
2309 view = LIST_ENTRY( ptr, struct file_view, entry );
2310 if ((char *)view->base > base)
2312 size = (char *)view->base - alloc_base;
2313 view = NULL;
2314 break;
2316 if ((char *)view->base + view->size > base)
2318 alloc_base = view->base;
2319 size = view->size;
2320 break;
2322 alloc_base = (char *)view->base + view->size;
2323 ptr = list_next( &views_list, ptr );
2326 /* Fill the info structure */
2328 info->AllocationBase = alloc_base;
2329 info->BaseAddress = base;
2330 info->RegionSize = size - (base - alloc_base);
2332 if (!view)
2334 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2336 /* not in a reserved area at all, pretend it's allocated */
2337 #ifdef __i386__
2338 if (base >= (char *)address_space_start)
2340 info->State = MEM_RESERVE;
2341 info->Protect = PAGE_NOACCESS;
2342 info->AllocationProtect = PAGE_NOACCESS;
2343 info->Type = MEM_PRIVATE;
2345 else
2346 #endif
2348 info->State = MEM_FREE;
2349 info->Protect = PAGE_NOACCESS;
2350 info->AllocationBase = 0;
2351 info->AllocationProtect = 0;
2352 info->Type = 0;
2356 else
2358 BYTE vprot;
2359 SIZE_T range_size = get_committed_size( view, base, &vprot );
2361 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2362 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2363 info->AllocationBase = alloc_base;
2364 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2365 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2366 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2367 else info->Type = MEM_MAPPED;
2368 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2369 if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2370 info->RegionSize = size - (base - alloc_base);
2372 server_leave_uninterrupted_section( &csVirtual, &sigset );
2374 if (res_len) *res_len = sizeof(*info);
2375 return STATUS_SUCCESS;
2379 /***********************************************************************
2380 * NtLockVirtualMemory (NTDLL.@)
2381 * ZwLockVirtualMemory (NTDLL.@)
2383 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2385 NTSTATUS status = STATUS_SUCCESS;
2387 if (process != NtCurrentProcess())
2389 apc_call_t call;
2390 apc_result_t result;
2392 memset( &call, 0, sizeof(call) );
2394 call.virtual_lock.type = APC_VIRTUAL_LOCK;
2395 call.virtual_lock.addr = wine_server_client_ptr( *addr );
2396 call.virtual_lock.size = *size;
2397 status = server_queue_process_apc( process, &call, &result );
2398 if (status != STATUS_SUCCESS) return status;
2400 if (result.virtual_lock.status == STATUS_SUCCESS)
2402 *addr = wine_server_get_ptr( result.virtual_lock.addr );
2403 *size = result.virtual_lock.size;
2405 return result.virtual_lock.status;
2408 *size = ROUND_SIZE( *addr, *size );
2409 *addr = ROUND_ADDR( *addr, page_mask );
2411 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2412 return status;
2416 /***********************************************************************
2417 * NtUnlockVirtualMemory (NTDLL.@)
2418 * ZwUnlockVirtualMemory (NTDLL.@)
2420 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2422 NTSTATUS status = STATUS_SUCCESS;
2424 if (process != NtCurrentProcess())
2426 apc_call_t call;
2427 apc_result_t result;
2429 memset( &call, 0, sizeof(call) );
2431 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2432 call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2433 call.virtual_unlock.size = *size;
2434 status = server_queue_process_apc( process, &call, &result );
2435 if (status != STATUS_SUCCESS) return status;
2437 if (result.virtual_unlock.status == STATUS_SUCCESS)
2439 *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2440 *size = result.virtual_unlock.size;
2442 return result.virtual_unlock.status;
2445 *size = ROUND_SIZE( *addr, *size );
2446 *addr = ROUND_ADDR( *addr, page_mask );
2448 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2449 return status;
2453 /***********************************************************************
2454 * NtCreateSection (NTDLL.@)
2455 * ZwCreateSection (NTDLL.@)
2457 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2458 const LARGE_INTEGER *size, ULONG protect,
2459 ULONG sec_flags, HANDLE file )
2461 NTSTATUS ret;
2462 unsigned int vprot;
2463 data_size_t len;
2464 struct object_attributes *objattr;
2466 /* Check parameters */
2468 if ((ret = get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE ))) return ret;
2469 if ((ret = alloc_object_attributes( attr, &objattr, &len ))) return ret;
2471 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2472 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2473 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2475 /* Create the server object */
2477 SERVER_START_REQ( create_mapping )
2479 req->access = access;
2480 req->file_handle = wine_server_obj_handle( file );
2481 req->size = size ? size->QuadPart : 0;
2482 req->protect = vprot;
2483 wine_server_add_data( req, objattr, len );
2484 ret = wine_server_call( req );
2485 *handle = wine_server_ptr_handle( reply->handle );
2487 SERVER_END_REQ;
2489 RtlFreeHeap( GetProcessHeap(), 0, objattr );
2490 return ret;
2494 /***********************************************************************
2495 * NtOpenSection (NTDLL.@)
2496 * ZwOpenSection (NTDLL.@)
2498 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2500 NTSTATUS ret;
2502 if ((ret = validate_open_object_attributes( attr ))) return ret;
2504 SERVER_START_REQ( open_mapping )
2506 req->access = access;
2507 req->attributes = attr->Attributes;
2508 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2509 if (attr->ObjectName)
2510 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
2511 ret = wine_server_call( req );
2512 *handle = wine_server_ptr_handle( reply->handle );
2514 SERVER_END_REQ;
2515 return ret;
2519 /***********************************************************************
2520 * NtMapViewOfSection (NTDLL.@)
2521 * ZwMapViewOfSection (NTDLL.@)
2523 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2524 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2525 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2527 NTSTATUS res;
2528 mem_size_t full_size;
2529 ACCESS_MASK access;
2530 SIZE_T size, mask = get_mask( zero_bits );
2531 int unix_handle = -1, needs_close;
2532 unsigned int map_vprot, vprot;
2533 void *base;
2534 struct file_view *view;
2535 DWORD header_size;
2536 HANDLE dup_mapping, shared_file;
2537 LARGE_INTEGER offset;
2538 sigset_t sigset;
2540 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2542 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2543 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2545 /* Check parameters */
2547 if (*addr_ptr && zero_bits)
2548 return STATUS_INVALID_PARAMETER_4;
2550 #ifndef _WIN64
2551 if (!is_wow64 && (alloc_type & AT_ROUND_TO_PAGE))
2553 *addr_ptr = ROUND_ADDR( *addr_ptr, page_mask );
2554 mask = page_mask;
2556 #endif
2558 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2559 return STATUS_MAPPED_ALIGNMENT;
2561 switch(protect)
2563 case PAGE_NOACCESS:
2564 access = SECTION_MAP_READ;
2565 break;
2566 case PAGE_READWRITE:
2567 case PAGE_EXECUTE_READWRITE:
2568 access = SECTION_MAP_WRITE;
2569 break;
2570 case PAGE_READONLY:
2571 case PAGE_WRITECOPY:
2572 case PAGE_EXECUTE:
2573 case PAGE_EXECUTE_READ:
2574 case PAGE_EXECUTE_WRITECOPY:
2575 access = SECTION_MAP_READ;
2576 break;
2577 default:
2578 return STATUS_INVALID_PAGE_PROTECTION;
2581 if (process != NtCurrentProcess())
2583 apc_call_t call;
2584 apc_result_t result;
2586 memset( &call, 0, sizeof(call) );
2588 call.map_view.type = APC_MAP_VIEW;
2589 call.map_view.handle = wine_server_obj_handle( handle );
2590 call.map_view.addr = wine_server_client_ptr( *addr_ptr );
2591 call.map_view.size = *size_ptr;
2592 call.map_view.offset = offset.QuadPart;
2593 call.map_view.zero_bits = zero_bits;
2594 call.map_view.alloc_type = alloc_type;
2595 call.map_view.prot = protect;
2596 res = server_queue_process_apc( process, &call, &result );
2597 if (res != STATUS_SUCCESS) return res;
2599 if ((NTSTATUS)result.map_view.status >= 0)
2601 *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2602 *size_ptr = result.map_view.size;
2604 return result.map_view.status;
2607 SERVER_START_REQ( get_mapping_info )
2609 req->handle = wine_server_obj_handle( handle );
2610 req->access = access;
2611 res = wine_server_call( req );
2612 map_vprot = reply->protect;
2613 base = wine_server_get_ptr( reply->base );
2614 full_size = reply->size;
2615 header_size = reply->header_size;
2616 dup_mapping = wine_server_ptr_handle( reply->mapping );
2617 shared_file = wine_server_ptr_handle( reply->shared_file );
2618 if ((ULONG_PTR)base != reply->base) base = NULL;
2620 SERVER_END_REQ;
2621 if (res) return res;
2623 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2625 if (map_vprot & VPROT_IMAGE)
2627 size = full_size;
2628 if (size != full_size) /* truncated */
2630 WARN( "Modules larger than 4Gb (%s) not supported\n", wine_dbgstr_longlong(full_size) );
2631 res = STATUS_INVALID_PARAMETER;
2632 goto done;
2634 if (shared_file)
2636 int shared_fd, shared_needs_close;
2638 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2639 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2640 res = map_image( handle, unix_handle, base, size, mask, header_size,
2641 shared_fd, dup_mapping, map_vprot, addr_ptr );
2642 if (shared_needs_close) close( shared_fd );
2643 close_handle( shared_file );
2645 else
2647 res = map_image( handle, unix_handle, base, size, mask, header_size,
2648 -1, dup_mapping, map_vprot, addr_ptr );
2650 if (needs_close) close( unix_handle );
2651 if (res >= 0) *size_ptr = size;
2652 return res;
2655 res = STATUS_INVALID_PARAMETER;
2656 if (offset.QuadPart >= full_size) goto done;
2657 if (*size_ptr)
2659 if (*size_ptr > full_size - offset.QuadPart) goto done;
2660 size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2661 if (size < *size_ptr) goto done; /* wrap-around */
2663 else
2665 size = full_size - offset.QuadPart;
2666 if (size != full_size - offset.QuadPart) /* truncated */
2668 WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2669 wine_dbgstr_longlong(full_size) );
2670 goto done;
2674 /* Reserve a properly aligned area */
2676 server_enter_uninterrupted_section( &csVirtual, &sigset );
2678 get_vprot_flags( protect, &vprot, map_vprot & VPROT_IMAGE );
2679 vprot |= (map_vprot & VPROT_COMMITTED);
2680 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2681 if (res)
2683 server_leave_uninterrupted_section( &csVirtual, &sigset );
2684 goto done;
2687 /* Map the file */
2689 TRACE("handle=%p size=%lx offset=%x%08x\n",
2690 handle, size, offset.u.HighPart, offset.u.LowPart );
2692 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2693 if (res == STATUS_SUCCESS)
2695 *addr_ptr = view->base;
2696 *size_ptr = size;
2697 view->mapping = dup_mapping;
2698 view->map_protect = map_vprot;
2699 dup_mapping = 0; /* don't close it */
2701 else
2703 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2704 view->base, size, offset.u.HighPart, offset.u.LowPart );
2705 delete_view( view );
2708 server_leave_uninterrupted_section( &csVirtual, &sigset );
2710 done:
2711 if (dup_mapping) close_handle( dup_mapping );
2712 if (needs_close) close( unix_handle );
2713 return res;
2717 /***********************************************************************
2718 * NtUnmapViewOfSection (NTDLL.@)
2719 * ZwUnmapViewOfSection (NTDLL.@)
2721 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2723 struct file_view *view;
2724 NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
2725 sigset_t sigset;
2726 void *base = ROUND_ADDR( addr, page_mask );
2728 if (process != NtCurrentProcess())
2730 apc_call_t call;
2731 apc_result_t result;
2733 memset( &call, 0, sizeof(call) );
2735 call.unmap_view.type = APC_UNMAP_VIEW;
2736 call.unmap_view.addr = wine_server_client_ptr( addr );
2737 status = server_queue_process_apc( process, &call, &result );
2738 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2739 return status;
2742 server_enter_uninterrupted_section( &csVirtual, &sigset );
2743 if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base) && !(view->protect & VPROT_VALLOC))
2745 delete_view( view );
2746 status = STATUS_SUCCESS;
2748 server_leave_uninterrupted_section( &csVirtual, &sigset );
2749 return status;
2753 /***********************************************************************
2754 * NtFlushVirtualMemory (NTDLL.@)
2755 * ZwFlushVirtualMemory (NTDLL.@)
2757 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2758 SIZE_T *size_ptr, ULONG unknown )
2760 struct file_view *view;
2761 NTSTATUS status = STATUS_SUCCESS;
2762 sigset_t sigset;
2763 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2765 if (process != NtCurrentProcess())
2767 apc_call_t call;
2768 apc_result_t result;
2770 memset( &call, 0, sizeof(call) );
2772 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2773 call.virtual_flush.addr = wine_server_client_ptr( addr );
2774 call.virtual_flush.size = *size_ptr;
2775 status = server_queue_process_apc( process, &call, &result );
2776 if (status != STATUS_SUCCESS) return status;
2778 if (result.virtual_flush.status == STATUS_SUCCESS)
2780 *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2781 *size_ptr = result.virtual_flush.size;
2783 return result.virtual_flush.status;
2786 server_enter_uninterrupted_section( &csVirtual, &sigset );
2787 if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2788 else
2790 if (!*size_ptr) *size_ptr = view->size;
2791 *addr_ptr = addr;
2792 #ifdef MS_ASYNC
2793 if (msync( addr, *size_ptr, MS_ASYNC )) status = STATUS_NOT_MAPPED_DATA;
2794 #endif
2796 server_leave_uninterrupted_section( &csVirtual, &sigset );
2797 return status;
2801 /***********************************************************************
2802 * NtGetWriteWatch (NTDLL.@)
2803 * ZwGetWriteWatch (NTDLL.@)
2805 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
2806 ULONG_PTR *count, ULONG *granularity )
2808 struct file_view *view;
2809 NTSTATUS status = STATUS_SUCCESS;
2810 sigset_t sigset;
2812 size = ROUND_SIZE( base, size );
2813 base = ROUND_ADDR( base, page_mask );
2815 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
2816 if (!*count || !size) return STATUS_INVALID_PARAMETER;
2817 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
2819 if (!addresses) return STATUS_ACCESS_VIOLATION;
2821 TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
2822 addresses, *count );
2824 server_enter_uninterrupted_section( &csVirtual, &sigset );
2826 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2828 ULONG_PTR pos = 0;
2829 char *addr = base;
2830 char *end = addr + size;
2832 while (pos < *count && addr < end)
2834 BYTE prot = view->prot[(addr - (char *)view->base) >> page_shift];
2835 if (!(prot & VPROT_WRITEWATCH)) addresses[pos++] = addr;
2836 addr += page_size;
2838 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( view, base, addr - (char *)base );
2839 *count = pos;
2840 *granularity = page_size;
2842 else status = STATUS_INVALID_PARAMETER;
2844 server_leave_uninterrupted_section( &csVirtual, &sigset );
2845 return status;
2849 /***********************************************************************
2850 * NtResetWriteWatch (NTDLL.@)
2851 * ZwResetWriteWatch (NTDLL.@)
2853 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
2855 struct file_view *view;
2856 NTSTATUS status = STATUS_SUCCESS;
2857 sigset_t sigset;
2859 size = ROUND_SIZE( base, size );
2860 base = ROUND_ADDR( base, page_mask );
2862 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
2864 if (!size) return STATUS_INVALID_PARAMETER;
2866 server_enter_uninterrupted_section( &csVirtual, &sigset );
2868 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2869 reset_write_watches( view, base, size );
2870 else
2871 status = STATUS_INVALID_PARAMETER;
2873 server_leave_uninterrupted_section( &csVirtual, &sigset );
2874 return status;
2878 /***********************************************************************
2879 * NtReadVirtualMemory (NTDLL.@)
2880 * ZwReadVirtualMemory (NTDLL.@)
2882 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2883 SIZE_T size, SIZE_T *bytes_read )
2885 NTSTATUS status;
2887 if (virtual_check_buffer_for_write( buffer, size ))
2889 SERVER_START_REQ( read_process_memory )
2891 req->handle = wine_server_obj_handle( process );
2892 req->addr = wine_server_client_ptr( addr );
2893 wine_server_set_reply( req, buffer, size );
2894 if ((status = wine_server_call( req ))) size = 0;
2896 SERVER_END_REQ;
2898 else
2900 status = STATUS_ACCESS_VIOLATION;
2901 size = 0;
2903 if (bytes_read) *bytes_read = size;
2904 return status;
2908 /***********************************************************************
2909 * NtWriteVirtualMemory (NTDLL.@)
2910 * ZwWriteVirtualMemory (NTDLL.@)
2912 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2913 SIZE_T size, SIZE_T *bytes_written )
2915 NTSTATUS status;
2917 if (virtual_check_buffer_for_read( buffer, size ))
2919 SERVER_START_REQ( write_process_memory )
2921 req->handle = wine_server_obj_handle( process );
2922 req->addr = wine_server_client_ptr( addr );
2923 wine_server_add_data( req, buffer, size );
2924 if ((status = wine_server_call( req ))) size = 0;
2926 SERVER_END_REQ;
2928 else
2930 status = STATUS_PARTIAL_COPY;
2931 size = 0;
2933 if (bytes_written) *bytes_written = size;
2934 return status;
2938 /***********************************************************************
2939 * NtAreMappedFilesTheSame (NTDLL.@)
2940 * ZwAreMappedFilesTheSame (NTDLL.@)
2942 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2944 struct file_view *view1, *view2;
2945 struct stat st1, st2;
2946 NTSTATUS status;
2947 sigset_t sigset;
2949 TRACE("%p %p\n", addr1, addr2);
2951 server_enter_uninterrupted_section( &csVirtual, &sigset );
2953 view1 = VIRTUAL_FindView( addr1, 0 );
2954 view2 = VIRTUAL_FindView( addr2, 0 );
2956 if (!view1 || !view2)
2957 status = STATUS_INVALID_ADDRESS;
2958 else if ((view1->protect & VPROT_VALLOC) || (view2->protect & VPROT_VALLOC))
2959 status = STATUS_CONFLICTING_ADDRESSES;
2960 else if (view1 == view2)
2961 status = STATUS_SUCCESS;
2962 else if (!(view1->protect & VPROT_IMAGE) || !(view2->protect & VPROT_IMAGE))
2963 status = STATUS_NOT_SAME_DEVICE;
2964 else if (!stat_mapping_file( view1, &st1 ) && !stat_mapping_file( view2, &st2 ) &&
2965 st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2966 status = STATUS_SUCCESS;
2967 else
2968 status = STATUS_NOT_SAME_DEVICE;
2970 server_leave_uninterrupted_section( &csVirtual, &sigset );
2971 return status;