winejoystick: Fix a crash on accessing a CFArray past its end due to an off-by-one...
[wine/multimedia.git] / dlls / ntdll / virtual.c
blobab6bf9b27a6dd7c758ca07ba4d878055724abe18
1 /*
2 * Win32 virtual memory functions
4 * Copyright 1997, 2002 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <sys/types.h>
35 #ifdef HAVE_SYS_STAT_H
36 # include <sys/stat.h>
37 #endif
38 #ifdef HAVE_SYS_MMAN_H
39 # include <sys/mman.h>
40 #endif
41 #ifdef HAVE_VALGRIND_VALGRIND_H
42 # include <valgrind/valgrind.h>
43 #endif
45 #include "ntstatus.h"
46 #define WIN32_NO_STATUS
47 #define NONAMELESSUNION
48 #include "windef.h"
49 #include "winternl.h"
50 #include "wine/library.h"
51 #include "wine/server.h"
52 #include "wine/exception.h"
53 #include "wine/list.h"
54 #include "wine/debug.h"
55 #include "ntdll_misc.h"
57 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
58 WINE_DECLARE_DEBUG_CHANNEL(module);
60 #ifndef MAP_NORESERVE
61 #define MAP_NORESERVE 0
62 #endif
64 /* File view */
65 struct file_view
67 struct list entry; /* Entry in global view list */
68 void *base; /* Base address */
69 size_t size; /* Size in bytes */
70 HANDLE mapping; /* Handle to the file mapping */
71 unsigned int map_protect; /* Mapping protection */
72 unsigned int protect; /* Protection for all pages at allocation time */
73 BYTE prot[1]; /* Protection byte for each page */
77 /* Conversion from VPROT_* to Win32 flags */
78 static const BYTE VIRTUAL_Win32Flags[16] =
80 PAGE_NOACCESS, /* 0 */
81 PAGE_READONLY, /* READ */
82 PAGE_READWRITE, /* WRITE */
83 PAGE_READWRITE, /* READ | WRITE */
84 PAGE_EXECUTE, /* EXEC */
85 PAGE_EXECUTE_READ, /* READ | EXEC */
86 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
87 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
88 PAGE_WRITECOPY, /* WRITECOPY */
89 PAGE_WRITECOPY, /* READ | WRITECOPY */
90 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
91 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
92 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
93 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
94 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
95 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
98 static struct list views_list = LIST_INIT(views_list);
100 static RTL_CRITICAL_SECTION csVirtual;
101 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
103 0, 0, &csVirtual,
104 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
105 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
107 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
109 #ifdef __i386__
110 static const UINT page_shift = 12;
111 static const UINT_PTR page_mask = 0xfff;
112 /* Note: these are Windows limits, you cannot change them. */
113 static void *address_space_limit = (void *)0xc0000000; /* top of the total available address space */
114 static void *user_space_limit = (void *)0x7fff0000; /* top of the user address space */
115 static void *working_set_limit = (void *)0x7fff0000; /* top of the current working set */
116 static void *address_space_start = (void *)0x110000; /* keep DOS area clear */
117 #elif defined(__x86_64__)
118 static const UINT page_shift = 12;
119 static const UINT_PTR page_mask = 0xfff;
120 static void *address_space_limit = (void *)0x7fffffff0000;
121 static void *user_space_limit = (void *)0x7fffffff0000;
122 static void *working_set_limit = (void *)0x7fffffff0000;
123 static void *address_space_start = (void *)0x10000;
124 #else
125 UINT_PTR page_size = 0;
126 static UINT page_shift;
127 static UINT_PTR page_mask;
128 static void *address_space_limit;
129 static void *user_space_limit;
130 static void *working_set_limit;
131 static void *address_space_start = (void *)0x10000;
132 #endif /* __i386__ */
133 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
135 #define ROUND_ADDR(addr,mask) \
136 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
138 #define ROUND_SIZE(addr,size) \
139 (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
141 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
142 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
144 #define VIRTUAL_HEAP_SIZE (sizeof(void*)*1024*1024)
146 static HANDLE virtual_heap;
147 static void *preload_reserve_start;
148 static void *preload_reserve_end;
149 static BOOL use_locks;
150 static BOOL force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
153 /***********************************************************************
154 * VIRTUAL_GetProtStr
156 static const char *VIRTUAL_GetProtStr( BYTE prot )
158 static char buffer[6];
159 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
160 buffer[1] = (prot & VPROT_GUARD) ? 'g' : ((prot & VPROT_WRITEWATCH) ? 'H' : '-');
161 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
162 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
163 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
164 buffer[5] = 0;
165 return buffer;
169 /***********************************************************************
170 * VIRTUAL_GetUnixProt
172 * Convert page protections to protection for mmap/mprotect.
174 static int VIRTUAL_GetUnixProt( BYTE vprot )
176 int prot = 0;
177 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
179 if (vprot & VPROT_READ) prot |= PROT_READ;
180 if (vprot & VPROT_WRITE) prot |= PROT_WRITE | PROT_READ;
181 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE | PROT_READ;
182 if (vprot & VPROT_EXEC) prot |= PROT_EXEC | PROT_READ;
183 if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
185 if (!prot) prot = PROT_NONE;
186 return prot;
190 /***********************************************************************
191 * VIRTUAL_DumpView
193 static void VIRTUAL_DumpView( struct file_view *view )
195 UINT i, count;
196 char *addr = view->base;
197 BYTE prot = view->prot[0];
199 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
200 if (view->protect & VPROT_SYSTEM)
201 TRACE( " (system)\n" );
202 else if (view->protect & VPROT_VALLOC)
203 TRACE( " (valloc)\n" );
204 else if (view->mapping)
205 TRACE( " %p\n", view->mapping );
206 else
207 TRACE( " (anonymous)\n");
209 for (count = i = 1; i < view->size >> page_shift; i++, count++)
211 if (view->prot[i] == prot) continue;
212 TRACE( " %p - %p %s\n",
213 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
214 addr += (count << page_shift);
215 prot = view->prot[i];
216 count = 0;
218 if (count)
219 TRACE( " %p - %p %s\n",
220 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
224 /***********************************************************************
225 * VIRTUAL_Dump
227 #ifdef WINE_VM_DEBUG
228 static void VIRTUAL_Dump(void)
230 sigset_t sigset;
231 struct file_view *view;
233 TRACE( "Dump of all virtual memory views:\n" );
234 server_enter_uninterrupted_section( &csVirtual, &sigset );
235 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
237 VIRTUAL_DumpView( view );
239 server_leave_uninterrupted_section( &csVirtual, &sigset );
241 #endif
244 /***********************************************************************
245 * VIRTUAL_FindView
247 * Find the view containing a given address. The csVirtual section must be held by caller.
249 * PARAMS
250 * addr [I] Address
252 * RETURNS
253 * View: Success
254 * NULL: Failure
256 static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
258 struct file_view *view;
260 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
262 if (view->base > addr) break; /* no matching view */
263 if ((const char *)view->base + view->size <= (const char *)addr) continue;
264 if ((const char *)view->base + view->size < (const char *)addr + size) break; /* size too large */
265 if ((const char *)addr + size < (const char *)addr) break; /* overflow */
266 return view;
268 return NULL;
272 /***********************************************************************
273 * get_mask
275 static inline UINT_PTR get_mask( ULONG zero_bits )
277 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
278 if (zero_bits < page_shift) zero_bits = page_shift;
279 return (1 << zero_bits) - 1;
283 /***********************************************************************
284 * find_view_range
286 * Find the first view overlapping at least part of the specified range.
287 * The csVirtual section must be held by caller.
289 static struct file_view *find_view_range( const void *addr, size_t size )
291 struct file_view *view;
293 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
295 if ((const char *)view->base >= (const char *)addr + size) break;
296 if ((const char *)view->base + view->size > (const char *)addr) return view;
298 return NULL;
302 /***********************************************************************
303 * find_free_area
305 * Find a free area between views inside the specified range.
306 * The csVirtual section must be held by caller.
308 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
310 struct list *ptr;
311 void *start;
313 if (top_down)
315 start = ROUND_ADDR( (char *)end - size, mask );
316 if (start >= end || start < base) return NULL;
318 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
320 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
322 if ((char *)view->base + view->size <= (char *)start) break;
323 if ((char *)view->base >= (char *)start + size) continue;
324 start = ROUND_ADDR( (char *)view->base - size, mask );
325 /* stop if remaining space is not large enough */
326 if (!start || start >= end || start < base) return NULL;
329 else
331 start = ROUND_ADDR( (char *)base + mask, mask );
332 if (start >= end || (char *)end - (char *)start < size) return NULL;
334 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
336 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
338 if ((char *)view->base >= (char *)start + size) break;
339 if ((char *)view->base + view->size <= (char *)start) continue;
340 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
341 /* stop if remaining space is not large enough */
342 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
345 return start;
349 /***********************************************************************
350 * add_reserved_area
352 * Add a reserved area to the list maintained by libwine.
353 * The csVirtual section must be held by caller.
355 static void add_reserved_area( void *addr, size_t size )
357 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
359 if (addr < user_space_limit)
361 /* unmap the part of the area that is below the limit */
362 assert( (char *)addr + size > (char *)user_space_limit );
363 munmap( addr, (char *)user_space_limit - (char *)addr );
364 size -= (char *)user_space_limit - (char *)addr;
365 addr = user_space_limit;
367 /* blow away existing mappings */
368 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
369 wine_mmap_add_reserved_area( addr, size );
373 /***********************************************************************
374 * remove_reserved_area
376 * Remove a reserved area from the list maintained by libwine.
377 * The csVirtual section must be held by caller.
379 static void remove_reserved_area( void *addr, size_t size )
381 struct file_view *view;
383 TRACE( "removing %p-%p\n", addr, (char *)addr + size );
384 wine_mmap_remove_reserved_area( addr, size, 0 );
386 /* unmap areas not covered by an existing view */
387 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
389 if ((char *)view->base >= (char *)addr + size)
391 munmap( addr, size );
392 break;
394 if ((char *)view->base + view->size <= (char *)addr) continue;
395 if (view->base > addr) munmap( addr, (char *)view->base - (char *)addr );
396 if ((char *)view->base + view->size > (char *)addr + size) break;
397 size = (char *)addr + size - ((char *)view->base + view->size);
398 addr = (char *)view->base + view->size;
403 /***********************************************************************
404 * is_beyond_limit
406 * Check if an address range goes beyond a given limit.
408 static inline BOOL is_beyond_limit( const void *addr, size_t size, const void *limit )
410 return (addr >= limit || (const char *)addr + size > (const char *)limit);
414 /***********************************************************************
415 * unmap_area
417 * Unmap an area, or simply replace it by an empty mapping if it is
418 * in a reserved area. The csVirtual section must be held by caller.
420 static inline void unmap_area( void *addr, size_t size )
422 if (wine_mmap_is_in_reserved_area( addr, size ))
423 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
424 else if (is_beyond_limit( addr, size, user_space_limit ))
425 add_reserved_area( addr, size );
426 else
427 munmap( addr, size );
431 /***********************************************************************
432 * delete_view
434 * Deletes a view. The csVirtual section must be held by caller.
436 static void delete_view( struct file_view *view ) /* [in] View */
438 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
439 list_remove( &view->entry );
440 if (view->mapping) close_handle( view->mapping );
441 RtlFreeHeap( virtual_heap, 0, view );
445 /***********************************************************************
446 * create_view
448 * Create a view. The csVirtual section must be held by caller.
450 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
452 struct file_view *view;
453 struct list *ptr;
454 int unix_prot = VIRTUAL_GetUnixProt( vprot );
456 assert( !((UINT_PTR)base & page_mask) );
457 assert( !(size & page_mask) );
459 /* Create the view structure */
461 if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
463 FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
464 return STATUS_NO_MEMORY;
467 view->base = base;
468 view->size = size;
469 view->mapping = 0;
470 view->map_protect = 0;
471 view->protect = vprot;
472 memset( view->prot, vprot, size >> page_shift );
474 /* Insert it in the linked list */
476 LIST_FOR_EACH( ptr, &views_list )
478 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
479 if (next->base > base) break;
481 list_add_before( ptr, &view->entry );
483 /* Check for overlapping views. This can happen if the previous view
484 * was a system view that got unmapped behind our back. In that case
485 * we recover by simply deleting it. */
487 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
489 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
490 if ((char *)prev->base + prev->size > (char *)base)
492 TRACE( "overlapping prev view %p-%p for %p-%p\n",
493 prev->base, (char *)prev->base + prev->size,
494 base, (char *)base + view->size );
495 assert( prev->protect & VPROT_SYSTEM );
496 delete_view( prev );
499 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
501 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
502 if ((char *)base + view->size > (char *)next->base)
504 TRACE( "overlapping next view %p-%p for %p-%p\n",
505 next->base, (char *)next->base + next->size,
506 base, (char *)base + view->size );
507 assert( next->protect & VPROT_SYSTEM );
508 delete_view( next );
512 *view_ret = view;
513 VIRTUAL_DEBUG_DUMP_VIEW( view );
515 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
517 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
518 mprotect( base, size, unix_prot | PROT_EXEC );
520 return STATUS_SUCCESS;
524 /***********************************************************************
525 * VIRTUAL_GetWin32Prot
527 * Convert page protections to Win32 flags.
529 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
531 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
532 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
533 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
534 return ret;
538 /***********************************************************************
539 * get_vprot_flags
541 * Build page protections from Win32 flags.
543 * PARAMS
544 * protect [I] Win32 protection flags
546 * RETURNS
547 * Value of page protection flags
549 static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot, BOOL image )
551 switch(protect & 0xff)
553 case PAGE_READONLY:
554 *vprot = VPROT_READ;
555 break;
556 case PAGE_READWRITE:
557 if (image)
558 *vprot = VPROT_READ | VPROT_WRITECOPY;
559 else
560 *vprot = VPROT_READ | VPROT_WRITE;
561 break;
562 case PAGE_WRITECOPY:
563 *vprot = VPROT_READ | VPROT_WRITECOPY;
564 break;
565 case PAGE_EXECUTE:
566 *vprot = VPROT_EXEC;
567 break;
568 case PAGE_EXECUTE_READ:
569 *vprot = VPROT_EXEC | VPROT_READ;
570 break;
571 case PAGE_EXECUTE_READWRITE:
572 if (image)
573 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
574 else
575 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
576 break;
577 case PAGE_EXECUTE_WRITECOPY:
578 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
579 break;
580 case PAGE_NOACCESS:
581 *vprot = 0;
582 break;
583 default:
584 return STATUS_INVALID_PAGE_PROTECTION;
586 if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
587 if (protect & PAGE_NOCACHE) *vprot |= VPROT_NOCACHE;
588 return STATUS_SUCCESS;
592 /***********************************************************************
593 * mprotect_exec
595 * Wrapper for mprotect, adds PROT_EXEC if forced by force_exec_prot
597 static inline int mprotect_exec( void *base, size_t size, int unix_prot, unsigned int view_protect )
599 if (force_exec_prot && !(view_protect & VPROT_NOEXEC) &&
600 (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
602 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
603 if (!mprotect( base, size, unix_prot | PROT_EXEC )) return 0;
604 /* exec + write may legitimately fail, in that case fall back to write only */
605 if (!(unix_prot & PROT_WRITE)) return -1;
608 return mprotect( base, size, unix_prot );
611 /***********************************************************************
612 * VIRTUAL_SetProt
614 * Change the protection of a range of pages.
616 * RETURNS
617 * TRUE: Success
618 * FALSE: Failure
620 static BOOL VIRTUAL_SetProt( struct file_view *view, /* [in] Pointer to view */
621 void *base, /* [in] Starting address */
622 size_t size, /* [in] Size in bytes */
623 BYTE vprot ) /* [in] Protections to use */
625 int unix_prot = VIRTUAL_GetUnixProt(vprot);
626 BYTE *p = view->prot + (((char *)base - (char *)view->base) >> page_shift);
628 TRACE("%p-%p %s\n",
629 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
631 if (view->protect & VPROT_WRITEWATCH)
633 /* each page may need different protections depending on write watch flag */
634 UINT i, count;
635 char *addr = base;
636 int prot;
638 p[0] = vprot | (p[0] & VPROT_WRITEWATCH);
639 unix_prot = VIRTUAL_GetUnixProt( p[0] );
640 for (count = i = 1; i < size >> page_shift; i++, count++)
642 p[i] = vprot | (p[i] & VPROT_WRITEWATCH);
643 prot = VIRTUAL_GetUnixProt( p[i] );
644 if (prot == unix_prot) continue;
645 mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
646 addr += count << page_shift;
647 unix_prot = prot;
648 count = 0;
650 if (count) mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
651 VIRTUAL_DEBUG_DUMP_VIEW( view );
652 return TRUE;
655 /* if setting stack guard pages, store the permissions first, as the guard may be
656 * triggered at any point after mprotect and change the permissions again */
657 if ((vprot & VPROT_GUARD) &&
658 (base >= NtCurrentTeb()->DeallocationStack) &&
659 (base < NtCurrentTeb()->Tib.StackBase))
661 memset( p, vprot, size >> page_shift );
662 mprotect( base, size, unix_prot );
663 VIRTUAL_DEBUG_DUMP_VIEW( view );
664 return TRUE;
667 if (mprotect_exec( base, size, unix_prot, view->protect )) /* FIXME: last error */
668 return FALSE;
670 memset( p, vprot, size >> page_shift );
671 VIRTUAL_DEBUG_DUMP_VIEW( view );
672 return TRUE;
676 /***********************************************************************
677 * reset_write_watches
679 * Reset write watches in a memory range.
681 static void reset_write_watches( struct file_view *view, void *base, SIZE_T size )
683 SIZE_T i, count;
684 int prot, unix_prot;
685 char *addr = base;
686 BYTE *p = view->prot + ((addr - (char *)view->base) >> page_shift);
688 p[0] |= VPROT_WRITEWATCH;
689 unix_prot = VIRTUAL_GetUnixProt( p[0] );
690 for (count = i = 1; i < size >> page_shift; i++, count++)
692 p[i] |= VPROT_WRITEWATCH;
693 prot = VIRTUAL_GetUnixProt( p[i] );
694 if (prot == unix_prot) continue;
695 mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
696 addr += count << page_shift;
697 unix_prot = prot;
698 count = 0;
700 if (count) mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
704 /***********************************************************************
705 * unmap_extra_space
707 * Release the extra memory while keeping the range starting on the granularity boundary.
709 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
711 if ((ULONG_PTR)ptr & mask)
713 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
714 munmap( ptr, extra );
715 ptr = (char *)ptr + extra;
716 total_size -= extra;
718 if (total_size > wanted_size)
719 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
720 return ptr;
724 struct alloc_area
726 size_t size;
727 size_t mask;
728 int top_down;
729 void *limit;
730 void *result;
733 /***********************************************************************
734 * alloc_reserved_area_callback
736 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
738 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
740 struct alloc_area *alloc = arg;
741 void *end = (char *)start + size;
743 if (start < address_space_start) start = address_space_start;
744 if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
745 if (start >= end) return 0;
747 /* make sure we don't touch the preloader reserved range */
748 if (preload_reserve_end >= start)
750 if (preload_reserve_end >= end)
752 if (preload_reserve_start <= start) return 0; /* no space in that area */
753 if (preload_reserve_start < end) end = preload_reserve_start;
755 else if (preload_reserve_start <= start) start = preload_reserve_end;
756 else
758 /* range is split in two by the preloader reservation, try first part */
759 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
760 alloc->mask, alloc->top_down )))
761 return 1;
762 /* then fall through to try second part */
763 start = preload_reserve_end;
766 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
767 return 1;
769 return 0;
773 /***********************************************************************
774 * map_view
776 * Create a view and mmap the corresponding memory area.
777 * The csVirtual section must be held by caller.
779 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
780 int top_down, unsigned int vprot )
782 void *ptr;
783 NTSTATUS status;
785 if (base)
787 if (is_beyond_limit( base, size, address_space_limit ))
788 return STATUS_WORKING_SET_LIMIT_RANGE;
790 switch (wine_mmap_is_in_reserved_area( base, size ))
792 case -1: /* partially in a reserved area */
793 return STATUS_CONFLICTING_ADDRESSES;
795 case 0: /* not in a reserved area, do a normal allocation */
796 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
798 if (errno == ENOMEM) return STATUS_NO_MEMORY;
799 return STATUS_INVALID_PARAMETER;
801 if (ptr != base)
803 /* We couldn't get the address we wanted */
804 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
805 else munmap( ptr, size );
806 return STATUS_CONFLICTING_ADDRESSES;
808 break;
810 default:
811 case 1: /* in a reserved area, make sure the address is available */
812 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
813 /* replace the reserved area by our mapping */
814 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
815 return STATUS_INVALID_PARAMETER;
816 break;
818 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
820 else
822 size_t view_size = size + mask + 1;
823 struct alloc_area alloc;
825 alloc.size = size;
826 alloc.mask = mask;
827 alloc.top_down = top_down;
828 alloc.limit = user_space_limit;
829 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
831 ptr = alloc.result;
832 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
833 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
834 return STATUS_INVALID_PARAMETER;
835 goto done;
838 for (;;)
840 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
842 if (errno == ENOMEM) return STATUS_NO_MEMORY;
843 return STATUS_INVALID_PARAMETER;
845 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
846 /* if we got something beyond the user limit, unmap it and retry */
847 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
848 else break;
850 ptr = unmap_extra_space( ptr, view_size, size, mask );
852 done:
853 status = create_view( view_ret, ptr, size, vprot );
854 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
855 return status;
859 /***********************************************************************
860 * map_file_into_view
862 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
863 * The csVirtual section must be held by caller.
865 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
866 off_t offset, unsigned int vprot, BOOL removable )
868 void *ptr;
869 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
870 unsigned int flags = MAP_FIXED | ((vprot & VPROT_WRITECOPY) ? MAP_PRIVATE : MAP_SHARED);
872 assert( start < view->size );
873 assert( start + size <= view->size );
875 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (vprot & VPROT_READ))
877 TRACE( "forcing exec permission on mapping %p-%p\n",
878 (char *)view->base + start, (char *)view->base + start + size - 1 );
879 prot |= PROT_EXEC;
882 /* only try mmap if media is not removable (or if we require write access) */
883 if (!removable || (flags & MAP_SHARED))
885 if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
886 goto done;
888 if ((errno == EPERM) && (prot & PROT_EXEC))
889 ERR( "failed to set %08x protection on file map, noexec filesystem?\n", prot );
891 /* mmap() failed; if this is because the file offset is not */
892 /* page-aligned (EINVAL), or because the underlying filesystem */
893 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
894 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
895 if (flags & MAP_SHARED) /* we cannot fake shared mappings */
897 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
898 ERR( "shared writable mmap not supported, broken filesystem?\n" );
899 return STATUS_NOT_SUPPORTED;
903 /* Reserve the memory with an anonymous mmap */
904 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
905 if (ptr == (void *)-1) return FILE_GetNtStatus();
906 /* Now read in the file */
907 pread( fd, ptr, size, offset );
908 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
909 done:
910 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
911 return STATUS_SUCCESS;
915 /***********************************************************************
916 * get_committed_size
918 * Get the size of the committed range starting at base.
919 * Also return the protections for the first page.
921 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
923 SIZE_T i, start;
925 start = ((char *)base - (char *)view->base) >> page_shift;
926 *vprot = view->prot[start];
928 if (view->mapping && !(view->protect & VPROT_COMMITTED))
930 SIZE_T ret = 0;
931 SERVER_START_REQ( get_mapping_committed_range )
933 req->handle = wine_server_obj_handle( view->mapping );
934 req->offset = start << page_shift;
935 if (!wine_server_call( req ))
937 ret = reply->size;
938 if (reply->committed)
940 *vprot |= VPROT_COMMITTED;
941 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
945 SERVER_END_REQ;
946 return ret;
948 for (i = start + 1; i < view->size >> page_shift; i++)
949 if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
950 return (i - start) << page_shift;
954 /***********************************************************************
955 * decommit_view
957 * Decommit some pages of a given view.
958 * The csVirtual section must be held by caller.
960 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
962 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
964 BYTE *p = view->prot + (start >> page_shift);
965 size >>= page_shift;
966 while (size--) *p++ &= ~VPROT_COMMITTED;
967 return STATUS_SUCCESS;
969 return FILE_GetNtStatus();
973 /***********************************************************************
974 * allocate_dos_memory
976 * Allocate the DOS memory range.
978 static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
980 size_t size;
981 void *addr = NULL;
982 void * const low_64k = (void *)0x10000;
983 const size_t dosmem_size = 0x110000;
984 int unix_prot = VIRTUAL_GetUnixProt( vprot );
985 struct list *ptr;
987 /* check for existing view */
989 if ((ptr = list_head( &views_list )))
991 struct file_view *first_view = LIST_ENTRY( ptr, struct file_view, entry );
992 if (first_view->base < (void *)dosmem_size) return STATUS_CONFLICTING_ADDRESSES;
995 /* check without the first 64K */
997 if (wine_mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
999 addr = wine_anon_mmap( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
1000 if (addr != low_64k)
1002 if (addr != (void *)-1) munmap( addr, dosmem_size - 0x10000 );
1003 return map_view( view, NULL, dosmem_size, 0xffff, 0, vprot );
1007 /* now try to allocate the low 64K too */
1009 if (wine_mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
1011 addr = wine_anon_mmap( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
1012 if (addr == (void *)page_size)
1014 if (!wine_anon_mmap( NULL, page_size, unix_prot, MAP_FIXED ))
1016 addr = NULL;
1017 TRACE( "successfully mapped low 64K range\n" );
1019 else TRACE( "failed to map page 0\n" );
1021 else
1023 if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
1024 addr = low_64k;
1025 TRACE( "failed to map low 64K range\n" );
1029 /* now reserve the whole range */
1031 size = (char *)dosmem_size - (char *)addr;
1032 wine_anon_mmap( addr, size, unix_prot, MAP_FIXED );
1033 return create_view( view, addr, size, vprot );
1037 /***********************************************************************
1038 * stat_mapping_file
1040 * Stat the underlying file for a memory view.
1042 static NTSTATUS stat_mapping_file( struct file_view *view, struct stat *st )
1044 NTSTATUS status;
1045 int unix_fd, needs_close;
1047 if (!view->mapping) return STATUS_NOT_MAPPED_VIEW;
1048 if (!(status = server_get_unix_fd( view->mapping, 0, &unix_fd, &needs_close, NULL, NULL )))
1050 if (fstat( unix_fd, st ) == -1) status = FILE_GetNtStatus();
1051 if (needs_close) close( unix_fd );
1053 return status;
1057 /***********************************************************************
1058 * map_image
1060 * Map an executable (PE format) image into memory.
1062 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
1063 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, unsigned int map_vprot, PVOID *addr_ptr )
1065 IMAGE_DOS_HEADER *dos;
1066 IMAGE_NT_HEADERS *nt;
1067 IMAGE_SECTION_HEADER sections[96];
1068 IMAGE_SECTION_HEADER *sec;
1069 IMAGE_DATA_DIRECTORY *imports;
1070 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
1071 int i;
1072 off_t pos;
1073 sigset_t sigset;
1074 struct stat st;
1075 struct file_view *view = NULL;
1076 char *ptr, *header_end, *header_start;
1077 INT_PTR delta = 0;
1079 /* zero-map the whole range */
1081 server_enter_uninterrupted_section( &csVirtual, &sigset );
1083 if (base >= (char *)address_space_start) /* make sure the DOS area remains free */
1084 status = map_view( &view, base, total_size, mask, FALSE,
1085 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1087 if (status != STATUS_SUCCESS)
1088 status = map_view( &view, NULL, total_size, mask, FALSE,
1089 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1091 if (status != STATUS_SUCCESS) goto error;
1093 ptr = view->base;
1094 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
1096 /* map the header */
1098 if (fstat( fd, &st ) == -1)
1100 status = FILE_GetNtStatus();
1101 goto error;
1103 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
1104 if (!st.st_size) goto error;
1105 header_size = min( header_size, st.st_size );
1106 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1107 !dup_mapping ) != STATUS_SUCCESS) goto error;
1108 dos = (IMAGE_DOS_HEADER *)ptr;
1109 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1110 header_end = ptr + ROUND_SIZE( 0, header_size );
1111 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1112 if ((char *)(nt + 1) > header_end) goto error;
1113 header_start = (char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader;
1114 if (nt->FileHeader.NumberOfSections > sizeof(sections)/sizeof(*sections)) goto error;
1115 if (header_start + sizeof(*sections) * nt->FileHeader.NumberOfSections > header_end) goto error;
1116 /* Some applications (e.g. the Steam version of Borderlands) map over the top of the section headers,
1117 * copying the headers into local memory is necessary to properly load such applications. */
1118 memcpy(sections, header_start, sizeof(*sections) * nt->FileHeader.NumberOfSections);
1119 sec = sections;
1121 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
1122 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
1124 /* check for non page-aligned binary */
1126 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1128 /* unaligned sections, this happens for native subsystem binaries */
1129 /* in that case Windows simply maps in the whole file */
1131 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1132 !dup_mapping ) != STATUS_SUCCESS) goto error;
1134 /* check that all sections are loaded at the right offset */
1135 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1136 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1138 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1139 goto error; /* Windows refuses to load in that case too */
1142 /* set the image protections */
1143 VIRTUAL_SetProt( view, ptr, total_size,
1144 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1146 /* no relocations are performed on non page-aligned binaries */
1147 goto done;
1151 /* map all the sections */
1153 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1155 static const SIZE_T sector_align = 0x1ff;
1156 SIZE_T map_size, file_start, file_size, end;
1158 if (!sec->Misc.VirtualSize)
1159 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1160 else
1161 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1163 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1164 file_start = sec->PointerToRawData & ~sector_align;
1165 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1166 if (file_size > map_size) file_size = map_size;
1168 /* a few sanity checks */
1169 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1170 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1172 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1173 sec->Name, sec->VirtualAddress, map_size, total_size );
1174 goto error;
1177 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1178 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1180 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1181 sec->Name, ptr + sec->VirtualAddress,
1182 sec->PointerToRawData, (int)pos, file_size, map_size,
1183 sec->Characteristics );
1184 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1185 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE, FALSE ) != STATUS_SUCCESS)
1187 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1188 goto error;
1191 /* check if the import directory falls inside this section */
1192 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1193 imports->VirtualAddress < sec->VirtualAddress + map_size)
1195 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1196 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1197 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1198 if (end > base)
1199 map_file_into_view( view, shared_fd, base, end - base,
1200 pos + (base - sec->VirtualAddress),
1201 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY, FALSE );
1203 pos += map_size;
1204 continue;
1207 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1208 sec->Name, ptr + sec->VirtualAddress,
1209 sec->PointerToRawData, sec->SizeOfRawData,
1210 sec->Misc.VirtualSize, sec->Characteristics );
1212 if (!sec->PointerToRawData || !file_size) continue;
1214 /* Note: if the section is not aligned properly map_file_into_view will magically
1215 * fall back to read(), so we don't need to check anything here.
1217 end = file_start + file_size;
1218 if (sec->PointerToRawData >= st.st_size ||
1219 end > ((st.st_size + sector_align) & ~sector_align) ||
1220 end < file_start ||
1221 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1222 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1223 !dup_mapping ) != STATUS_SUCCESS)
1225 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1226 goto error;
1229 if (file_size & page_mask)
1231 end = ROUND_SIZE( 0, file_size );
1232 if (end > map_size) end = map_size;
1233 TRACE_(module)("clearing %p - %p\n",
1234 ptr + sec->VirtualAddress + file_size,
1235 ptr + sec->VirtualAddress + end );
1236 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1241 /* perform base relocation, if necessary */
1243 if (ptr != base &&
1244 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1245 !NtCurrentTeb()->Peb->ImageBaseAddress) )
1247 IMAGE_BASE_RELOCATION *rel, *end;
1248 const IMAGE_DATA_DIRECTORY *relocs;
1250 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1252 WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1253 base, ptr );
1254 status = STATUS_CONFLICTING_ADDRESSES;
1255 goto error;
1258 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1259 base, base + total_size, ptr, ptr + total_size );
1261 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1262 rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1263 end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1264 delta = ptr - base;
1266 while (rel < end - 1 && rel->SizeOfBlock)
1268 if (rel->VirtualAddress >= total_size)
1270 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1271 status = STATUS_ACCESS_VIOLATION;
1272 goto error;
1274 rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1275 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1276 (USHORT *)(rel + 1), delta );
1277 if (!rel) goto error;
1281 /* set the image protections */
1283 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1285 sec = sections;
1286 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1288 SIZE_T size;
1289 BYTE vprot = VPROT_COMMITTED;
1291 if (sec->Misc.VirtualSize)
1292 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1293 else
1294 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1296 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1297 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_WRITECOPY;
1298 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1300 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1301 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1302 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1303 vprot |= VPROT_EXEC;
1305 if (!VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot ) && (vprot & VPROT_EXEC))
1306 ERR( "failed to set %08x protection on section %.8s, noexec filesystem?\n",
1307 sec->Characteristics, sec->Name );
1310 done:
1311 view->mapping = dup_mapping;
1312 view->map_protect = map_vprot;
1313 server_leave_uninterrupted_section( &csVirtual, &sigset );
1315 *addr_ptr = ptr;
1316 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1317 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1318 #endif
1319 if (ptr != base) return STATUS_IMAGE_NOT_AT_BASE;
1320 return STATUS_SUCCESS;
1322 error:
1323 if (view) delete_view( view );
1324 server_leave_uninterrupted_section( &csVirtual, &sigset );
1325 if (dup_mapping) NtClose( dup_mapping );
1326 return status;
1330 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1331 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1333 void **heap_base = arg;
1335 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1336 if (size < VIRTUAL_HEAP_SIZE) return 0;
1337 if (is_win64 && base < (void *)0x80000000) return 0;
1338 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1339 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1340 return (*heap_base != (void *)-1);
1343 /***********************************************************************
1344 * virtual_init
1346 void virtual_init(void)
1348 const char *preload;
1349 void *heap_base;
1350 size_t size;
1351 struct file_view *heap_view;
1353 #if !defined(__i386__) && !defined(__x86_64__)
1354 page_size = sysconf( _SC_PAGESIZE );
1355 page_mask = page_size - 1;
1356 /* Make sure we have a power of 2 */
1357 assert( !(page_size & page_mask) );
1358 page_shift = 0;
1359 while ((1 << page_shift) != page_size) page_shift++;
1360 user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1361 #endif /* page_mask */
1362 if ((preload = getenv("WINEPRELOADRESERVE")))
1364 unsigned long start, end;
1365 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1367 preload_reserve_start = (void *)start;
1368 preload_reserve_end = (void *)end;
1372 /* try to find space in a reserved area for the virtual heap */
1373 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1374 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1376 assert( heap_base != (void *)-1 );
1377 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1378 VIRTUAL_HEAP_SIZE, NULL, NULL );
1379 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1381 /* make the DOS area accessible (except the low 64K) to hide bugs in broken apps like Excel 2003 */
1382 size = (char *)address_space_start - (char *)0x10000;
1383 if (size && wine_mmap_is_in_reserved_area( (void*)0x10000, size ) == 1)
1384 wine_anon_mmap( (void *)0x10000, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1388 /***********************************************************************
1389 * virtual_init_threading
1391 void virtual_init_threading(void)
1393 use_locks = TRUE;
1397 /***********************************************************************
1398 * virtual_get_system_info
1400 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1402 info->unknown = 0;
1403 info->KeMaximumIncrement = 0; /* FIXME */
1404 info->PageSize = page_size;
1405 info->MmLowestPhysicalPage = 1;
1406 info->MmHighestPhysicalPage = 0x7fffffff / page_size;
1407 info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
1408 info->AllocationGranularity = get_mask(0) + 1;
1409 info->LowestUserAddress = (void *)0x10000;
1410 info->HighestUserAddress = (char *)user_space_limit - 1;
1411 info->ActiveProcessorsAffinityMask = get_system_affinity_mask();
1412 info->NumberOfProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1416 /***********************************************************************
1417 * virtual_create_builtin_view
1419 NTSTATUS virtual_create_builtin_view( void *module )
1421 NTSTATUS status;
1422 sigset_t sigset;
1423 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1424 SIZE_T size = nt->OptionalHeader.SizeOfImage;
1425 IMAGE_SECTION_HEADER *sec;
1426 struct file_view *view;
1427 void *base;
1428 int i;
1430 size = ROUND_SIZE( module, size );
1431 base = ROUND_ADDR( module, page_mask );
1432 server_enter_uninterrupted_section( &csVirtual, &sigset );
1433 status = create_view( &view, base, size, VPROT_SYSTEM | VPROT_IMAGE |
1434 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1435 if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
1436 server_leave_uninterrupted_section( &csVirtual, &sigset );
1438 if (status) return status;
1440 /* The PE header is always read-only, no write, no execute. */
1441 view->prot[0] = VPROT_COMMITTED | VPROT_READ;
1443 sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
1444 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1446 BYTE flags = VPROT_COMMITTED;
1448 if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
1449 if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
1450 if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
1451 memset (view->prot + (sec[i].VirtualAddress >> page_shift), flags,
1452 ROUND_SIZE( sec[i].VirtualAddress, sec[i].Misc.VirtualSize ) >> page_shift );
1455 return status;
1459 /***********************************************************************
1460 * virtual_alloc_thread_stack
1462 NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1464 struct file_view *view;
1465 NTSTATUS status;
1466 sigset_t sigset;
1467 SIZE_T size;
1469 if (!reserve_size || !commit_size)
1471 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1472 if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
1473 if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1476 size = max( reserve_size, commit_size );
1477 if (size < 1024 * 1024) size = 1024 * 1024; /* Xlib needs a large stack */
1478 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1480 server_enter_uninterrupted_section( &csVirtual, &sigset );
1482 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1483 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1484 goto done;
1486 #ifdef VALGRIND_STACK_REGISTER
1487 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1488 #endif
1490 /* setup no access guard page */
1491 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1492 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1493 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1495 /* note: limit is lower than base since the stack grows down */
1496 teb->DeallocationStack = view->base;
1497 teb->Tib.StackBase = (char *)view->base + view->size;
1498 teb->Tib.StackLimit = (char *)view->base + 2 * page_size;
1499 done:
1500 server_leave_uninterrupted_section( &csVirtual, &sigset );
1501 return status;
1505 /***********************************************************************
1506 * virtual_clear_thread_stack
1508 * Clear the stack contents before calling the main entry point, some broken apps need that.
1510 void virtual_clear_thread_stack(void)
1512 void *stack = NtCurrentTeb()->Tib.StackLimit;
1513 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1515 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1516 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1520 /***********************************************************************
1521 * virtual_handle_fault
1523 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err, BOOL on_signal_stack )
1525 struct file_view *view;
1526 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1527 sigset_t sigset;
1529 server_enter_uninterrupted_section( &csVirtual, &sigset );
1530 if ((view = VIRTUAL_FindView( addr, 0 )))
1532 void *page = ROUND_ADDR( addr, page_mask );
1533 BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1534 if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1536 if (*vprot & VPROT_WRITEWATCH)
1538 *vprot &= ~VPROT_WRITEWATCH;
1539 VIRTUAL_SetProt( view, page, page_size, *vprot );
1541 /* ignore fault if page is writable now */
1542 if (VIRTUAL_GetUnixProt( *vprot ) & PROT_WRITE) ret = STATUS_SUCCESS;
1544 if (!on_signal_stack && (*vprot & VPROT_GUARD))
1546 VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1547 ret = STATUS_GUARD_PAGE_VIOLATION;
1550 server_leave_uninterrupted_section( &csVirtual, &sigset );
1551 return ret;
1556 /***********************************************************************
1557 * virtual_is_valid_code_address
1559 BOOL virtual_is_valid_code_address( const void *addr, SIZE_T size )
1561 struct file_view *view;
1562 BOOL ret = FALSE;
1563 sigset_t sigset;
1565 server_enter_uninterrupted_section( &csVirtual, &sigset );
1566 if ((view = VIRTUAL_FindView( addr, size )))
1567 ret = !(view->protect & VPROT_SYSTEM); /* system views are not visible to the app */
1568 server_leave_uninterrupted_section( &csVirtual, &sigset );
1569 return ret;
1573 /***********************************************************************
1574 * virtual_handle_stack_fault
1576 * Handle an access fault inside the current thread stack.
1577 * Called from inside a signal handler.
1579 BOOL virtual_handle_stack_fault( void *addr )
1581 struct file_view *view;
1582 BOOL ret = FALSE;
1584 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1585 if ((view = VIRTUAL_FindView( addr, 0 )))
1587 void *page = ROUND_ADDR( addr, page_mask );
1588 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1589 if (vprot & VPROT_GUARD)
1591 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1592 NtCurrentTeb()->Tib.StackLimit = page;
1593 if ((char *)page >= (char *)NtCurrentTeb()->DeallocationStack + 2*page_size)
1595 vprot = view->prot[((char *)page - page_size - (char *)view->base) >> page_shift];
1596 VIRTUAL_SetProt( view, (char *)page - page_size, page_size, vprot | VPROT_GUARD );
1598 ret = TRUE;
1601 RtlLeaveCriticalSection( &csVirtual );
1602 return ret;
1606 /***********************************************************************
1607 * virtual_check_buffer_for_read
1609 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
1611 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
1613 if (!size) return TRUE;
1614 if (!ptr) return FALSE;
1616 __TRY
1618 volatile const char *p = ptr;
1619 char dummy __attribute__((unused));
1620 SIZE_T count = size;
1622 while (count > page_size)
1624 dummy = *p;
1625 p += page_size;
1626 count -= page_size;
1628 dummy = p[0];
1629 dummy = p[count - 1];
1631 __EXCEPT_PAGE_FAULT
1633 return FALSE;
1635 __ENDTRY
1636 return TRUE;
1640 /***********************************************************************
1641 * virtual_check_buffer_for_write
1643 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
1645 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
1647 if (!size) return TRUE;
1648 if (!ptr) return FALSE;
1650 __TRY
1652 volatile char *p = ptr;
1653 SIZE_T count = size;
1655 while (count > page_size)
1657 *p |= 0;
1658 p += page_size;
1659 count -= page_size;
1661 p[0] |= 0;
1662 p[count - 1] |= 0;
1664 __EXCEPT_PAGE_FAULT
1666 return FALSE;
1668 __ENDTRY
1669 return TRUE;
1673 /***********************************************************************
1674 * virtual_uninterrupted_read_memory
1676 * Similar to NtReadVirtualMemory, but without wineserver calls. Moreover
1677 * permissions are checked before accessing each page, to ensure that no
1678 * exceptions can happen.
1680 SIZE_T virtual_uninterrupted_read_memory( const void *addr, void *buffer, SIZE_T size )
1682 struct file_view *view;
1683 sigset_t sigset;
1684 SIZE_T bytes_read = 0;
1686 if (!size) return 0;
1688 server_enter_uninterrupted_section( &csVirtual, &sigset );
1689 if ((view = VIRTUAL_FindView( addr, size )))
1691 if (!(view->protect & VPROT_SYSTEM))
1693 void *page = ROUND_ADDR( addr, page_mask );
1694 BYTE *p = view->prot + (((const char *)page - (const char *)view->base) >> page_shift);
1696 while (bytes_read < size && (VIRTUAL_GetUnixProt( *p++ ) & PROT_READ))
1698 SIZE_T block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
1699 memcpy( buffer, addr, block_size );
1701 addr = (const void *)((const char *)addr + block_size);
1702 buffer = (void *)((char *)buffer + block_size);
1703 bytes_read += block_size;
1707 server_leave_uninterrupted_section( &csVirtual, &sigset );
1708 return bytes_read;
1712 /***********************************************************************
1713 * virtual_uninterrupted_write_memory
1715 * Similar to NtWriteVirtualMemory, but without wineserver calls. Moreover
1716 * permissions are checked before accessing each page, to ensure that no
1717 * exceptions can happen.
1719 SIZE_T virtual_uninterrupted_write_memory( void *addr, const void *buffer, SIZE_T size )
1721 struct file_view *view;
1722 sigset_t sigset;
1723 SIZE_T bytes_written = 0;
1725 if (!size) return 0;
1727 server_enter_uninterrupted_section( &csVirtual, &sigset );
1728 if ((view = VIRTUAL_FindView( addr, size )))
1730 if (!(view->protect & VPROT_SYSTEM))
1732 void *page = ROUND_ADDR( addr, page_mask );
1733 BYTE *p = view->prot + (((const char *)page - (const char *)view->base) >> page_shift);
1735 while (bytes_written < size && (VIRTUAL_GetUnixProt( *p++ ) & PROT_WRITE))
1737 SIZE_T block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
1738 memcpy( addr, buffer, block_size );
1740 addr = (void *)((char *)addr + block_size);
1741 buffer = (const void *)((const char *)buffer + block_size);
1742 bytes_written += block_size;
1746 server_leave_uninterrupted_section( &csVirtual, &sigset );
1747 return bytes_written;
1751 /***********************************************************************
1752 * VIRTUAL_SetForceExec
1754 * Whether to force exec prot on all views.
1756 void VIRTUAL_SetForceExec( BOOL enable )
1758 struct file_view *view;
1759 sigset_t sigset;
1761 server_enter_uninterrupted_section( &csVirtual, &sigset );
1762 if (!force_exec_prot != !enable) /* change all existing views */
1764 force_exec_prot = enable;
1766 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1768 UINT i, count;
1769 char *addr = view->base;
1770 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1771 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1773 if (view->protect & VPROT_NOEXEC) continue;
1774 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1776 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1777 if (prot == unix_prot) continue;
1778 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1780 TRACE( "%s exec prot for %p-%p\n",
1781 force_exec_prot ? "enabling" : "disabling",
1782 addr, addr + (count << page_shift) - 1 );
1783 mprotect( addr, count << page_shift,
1784 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1786 addr += (count << page_shift);
1787 unix_prot = prot;
1788 count = 0;
1790 if (count)
1792 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1794 TRACE( "%s exec prot for %p-%p\n",
1795 force_exec_prot ? "enabling" : "disabling",
1796 addr, addr + (count << page_shift) - 1 );
1797 mprotect( addr, count << page_shift,
1798 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1803 server_leave_uninterrupted_section( &csVirtual, &sigset );
1806 struct free_range
1808 char *base;
1809 char *limit;
1812 /* free reserved areas above the limit; callback for wine_mmap_enum_reserved_areas */
1813 static int free_reserved_memory( void *base, size_t size, void *arg )
1815 struct free_range *range = arg;
1817 if ((char *)base >= range->limit) return 0;
1818 if ((char *)base + size <= range->base) return 0;
1819 if ((char *)base < range->base)
1821 size -= range->base - (char *)base;
1822 base = range->base;
1824 if ((char *)base + size > range->limit) size = range->limit - (char *)base;
1825 remove_reserved_area( base, size );
1826 return 1; /* stop enumeration since the list has changed */
1829 /***********************************************************************
1830 * virtual_release_address_space
1832 * Release some address space once we have loaded and initialized the app.
1834 void virtual_release_address_space(void)
1836 struct free_range range;
1837 sigset_t sigset;
1839 if (is_win64) return;
1841 server_enter_uninterrupted_section( &csVirtual, &sigset );
1843 range.base = (char *)0x82000000;
1844 range.limit = user_space_limit;
1846 if (range.limit > range.base)
1848 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
1850 else
1852 #ifndef __APPLE__ /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
1853 range.base = (char *)0x20000000;
1854 range.limit = (char *)0x7f000000;
1855 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
1856 #endif
1859 server_leave_uninterrupted_section( &csVirtual, &sigset );
1863 /***********************************************************************
1864 * virtual_set_large_address_space
1866 * Enable use of a large address space when allowed by the application.
1868 void virtual_set_large_address_space(void)
1870 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1872 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE)) return;
1873 /* no large address space on win9x */
1874 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1876 user_space_limit = working_set_limit = address_space_limit;
1880 /***********************************************************************
1881 * NtAllocateVirtualMemory (NTDLL.@)
1882 * ZwAllocateVirtualMemory (NTDLL.@)
1884 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1885 SIZE_T *size_ptr, ULONG type, ULONG protect )
1887 void *base;
1888 unsigned int vprot;
1889 SIZE_T size = *size_ptr;
1890 SIZE_T mask = get_mask( zero_bits );
1891 NTSTATUS status = STATUS_SUCCESS;
1892 struct file_view *view;
1893 sigset_t sigset;
1895 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1897 if (!size) return STATUS_INVALID_PARAMETER;
1899 if (process != NtCurrentProcess())
1901 apc_call_t call;
1902 apc_result_t result;
1904 memset( &call, 0, sizeof(call) );
1906 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1907 call.virtual_alloc.addr = wine_server_client_ptr( *ret );
1908 call.virtual_alloc.size = *size_ptr;
1909 call.virtual_alloc.zero_bits = zero_bits;
1910 call.virtual_alloc.op_type = type;
1911 call.virtual_alloc.prot = protect;
1912 status = server_queue_process_apc( process, &call, &result );
1913 if (status != STATUS_SUCCESS) return status;
1915 if (result.virtual_alloc.status == STATUS_SUCCESS)
1917 *ret = wine_server_get_ptr( result.virtual_alloc.addr );
1918 *size_ptr = result.virtual_alloc.size;
1920 return result.virtual_alloc.status;
1923 /* Round parameters to a page boundary */
1925 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1927 if ((status = get_vprot_flags( protect, &vprot, FALSE ))) return status;
1928 if (vprot & VPROT_WRITECOPY) return STATUS_INVALID_PAGE_PROTECTION;
1929 vprot |= VPROT_VALLOC;
1930 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1932 if (*ret)
1934 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1935 base = ROUND_ADDR( *ret, mask );
1936 else
1937 base = ROUND_ADDR( *ret, page_mask );
1938 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1940 /* address 1 is magic to mean DOS area */
1941 if (!base && *ret == (void *)1 && size == 0x110000)
1943 server_enter_uninterrupted_section( &csVirtual, &sigset );
1944 status = allocate_dos_memory( &view, vprot );
1945 if (status == STATUS_SUCCESS)
1947 *ret = view->base;
1948 *size_ptr = view->size;
1950 server_leave_uninterrupted_section( &csVirtual, &sigset );
1951 return status;
1954 /* disallow low 64k, wrap-around and kernel space */
1955 if (((char *)base < (char *)0x10000) ||
1956 ((char *)base + size < (char *)base) ||
1957 is_beyond_limit( base, size, address_space_limit ))
1958 return STATUS_INVALID_PARAMETER;
1960 else
1962 base = NULL;
1963 size = (size + page_mask) & ~page_mask;
1966 /* Compute the alloc type flags */
1968 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
1969 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1971 WARN("called with wrong alloc type flags (%08x) !\n", type);
1972 return STATUS_INVALID_PARAMETER;
1975 /* Reserve the memory */
1977 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1979 if ((type & MEM_RESERVE) || !base)
1981 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
1982 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1983 if (status == STATUS_SUCCESS) base = view->base;
1985 else if (type & MEM_RESET)
1987 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1988 else madvise( base, size, MADV_DONTNEED );
1990 else /* commit the pages */
1992 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1993 else if (view->mapping && (view->protect & VPROT_COMMITTED)) status = STATUS_ALREADY_COMMITTED;
1994 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1995 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1997 SERVER_START_REQ( add_mapping_committed_range )
1999 req->handle = wine_server_obj_handle( view->mapping );
2000 req->offset = (char *)base - (char *)view->base;
2001 req->size = size;
2002 wine_server_call( req );
2004 SERVER_END_REQ;
2008 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
2010 if (status == STATUS_SUCCESS)
2012 *ret = base;
2013 *size_ptr = size;
2015 return status;
2019 /***********************************************************************
2020 * NtFreeVirtualMemory (NTDLL.@)
2021 * ZwFreeVirtualMemory (NTDLL.@)
2023 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
2025 struct file_view *view;
2026 char *base;
2027 sigset_t sigset;
2028 NTSTATUS status = STATUS_SUCCESS;
2029 LPVOID addr = *addr_ptr;
2030 SIZE_T size = *size_ptr;
2032 TRACE("%p %p %08lx %x\n", process, addr, size, type );
2034 if (process != NtCurrentProcess())
2036 apc_call_t call;
2037 apc_result_t result;
2039 memset( &call, 0, sizeof(call) );
2041 call.virtual_free.type = APC_VIRTUAL_FREE;
2042 call.virtual_free.addr = wine_server_client_ptr( addr );
2043 call.virtual_free.size = size;
2044 call.virtual_free.op_type = type;
2045 status = server_queue_process_apc( process, &call, &result );
2046 if (status != STATUS_SUCCESS) return status;
2048 if (result.virtual_free.status == STATUS_SUCCESS)
2050 *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
2051 *size_ptr = result.virtual_free.size;
2053 return result.virtual_free.status;
2056 /* Fix the parameters */
2058 size = ROUND_SIZE( addr, size );
2059 base = ROUND_ADDR( addr, page_mask );
2061 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
2062 if (!base) return STATUS_INVALID_PARAMETER;
2064 server_enter_uninterrupted_section( &csVirtual, &sigset );
2066 if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
2068 status = STATUS_INVALID_PARAMETER;
2070 else if (type == MEM_RELEASE)
2072 /* Free the pages */
2074 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
2075 else
2077 delete_view( view );
2078 *addr_ptr = base;
2079 *size_ptr = size;
2082 else if (type == MEM_DECOMMIT)
2084 status = decommit_pages( view, base - (char *)view->base, size );
2085 if (status == STATUS_SUCCESS)
2087 *addr_ptr = base;
2088 *size_ptr = size;
2091 else
2093 WARN("called with wrong free type flags (%08x) !\n", type);
2094 status = STATUS_INVALID_PARAMETER;
2097 server_leave_uninterrupted_section( &csVirtual, &sigset );
2098 return status;
2101 static ULONG map_protection_to_access( ULONG vprot )
2103 vprot &= VPROT_READ | VPROT_WRITE | VPROT_EXEC | VPROT_WRITECOPY;
2104 if (vprot & VPROT_EXEC)
2106 if (vprot & VPROT_WRITE) vprot |= VPROT_WRITECOPY;
2108 else vprot &= ~VPROT_WRITECOPY;
2109 return vprot;
2112 static BOOL is_compatible_protection( const struct file_view *view, ULONG new_prot )
2114 ULONG view_prot, map_prot;
2116 view_prot = map_protection_to_access( view->protect );
2117 new_prot = map_protection_to_access( new_prot );
2119 if (view_prot == new_prot) return TRUE;
2120 if (!view_prot) return FALSE;
2122 if ((view_prot & new_prot) != new_prot) return FALSE;
2124 map_prot = map_protection_to_access( view->map_protect );
2125 if ((map_prot & new_prot) == new_prot) return TRUE;
2127 return FALSE;
2130 /***********************************************************************
2131 * NtProtectVirtualMemory (NTDLL.@)
2132 * ZwProtectVirtualMemory (NTDLL.@)
2134 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
2135 ULONG new_prot, ULONG *old_prot )
2137 struct file_view *view;
2138 sigset_t sigset;
2139 NTSTATUS status = STATUS_SUCCESS;
2140 char *base;
2141 BYTE vprot;
2142 unsigned int new_vprot;
2143 SIZE_T size = *size_ptr;
2144 LPVOID addr = *addr_ptr;
2146 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
2148 if (process != NtCurrentProcess())
2150 apc_call_t call;
2151 apc_result_t result;
2153 memset( &call, 0, sizeof(call) );
2155 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
2156 call.virtual_protect.addr = wine_server_client_ptr( addr );
2157 call.virtual_protect.size = size;
2158 call.virtual_protect.prot = new_prot;
2159 status = server_queue_process_apc( process, &call, &result );
2160 if (status != STATUS_SUCCESS) return status;
2162 if (result.virtual_protect.status == STATUS_SUCCESS)
2164 *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
2165 *size_ptr = result.virtual_protect.size;
2166 if (old_prot) *old_prot = result.virtual_protect.prot;
2168 return result.virtual_protect.status;
2171 /* Fix the parameters */
2173 size = ROUND_SIZE( addr, size );
2174 base = ROUND_ADDR( addr, page_mask );
2176 server_enter_uninterrupted_section( &csVirtual, &sigset );
2178 if ((view = VIRTUAL_FindView( base, size )))
2180 /* Make sure all the pages are committed */
2181 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2183 if (!(status = get_vprot_flags( new_prot, &new_vprot, view->protect & VPROT_IMAGE )))
2185 if ((new_vprot & VPROT_WRITECOPY) && (view->protect & VPROT_VALLOC))
2186 status = STATUS_INVALID_PAGE_PROTECTION;
2187 else
2189 if (!view->mapping || is_compatible_protection( view, new_vprot ))
2191 new_vprot |= VPROT_COMMITTED;
2192 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
2193 if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
2195 else status = STATUS_INVALID_PAGE_PROTECTION;
2199 else status = STATUS_NOT_COMMITTED;
2201 else status = STATUS_INVALID_PARAMETER;
2203 server_leave_uninterrupted_section( &csVirtual, &sigset );
2205 if (status == STATUS_SUCCESS)
2207 *addr_ptr = base;
2208 *size_ptr = size;
2210 return status;
2214 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
2215 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
2217 MEMORY_BASIC_INFORMATION *info = arg;
2218 void *end = (char *)start + size;
2220 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
2222 if (info->BaseAddress >= end)
2224 if (info->AllocationBase < end) info->AllocationBase = end;
2225 return 0;
2228 if (info->BaseAddress >= start || start <= address_space_start)
2230 /* it's a real free area */
2231 info->State = MEM_FREE;
2232 info->Protect = PAGE_NOACCESS;
2233 info->AllocationBase = 0;
2234 info->AllocationProtect = 0;
2235 info->Type = 0;
2236 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
2237 info->RegionSize = (char *)end - (char *)info->BaseAddress;
2239 else /* outside of the reserved area, pretend it's allocated */
2241 info->RegionSize = (char *)start - (char *)info->BaseAddress;
2242 info->State = MEM_RESERVE;
2243 info->Protect = PAGE_NOACCESS;
2244 info->AllocationProtect = PAGE_NOACCESS;
2245 info->Type = MEM_PRIVATE;
2247 return 1;
2250 #define UNIMPLEMENTED_INFO_CLASS(c) \
2251 case c: \
2252 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
2253 return STATUS_INVALID_INFO_CLASS
2255 /***********************************************************************
2256 * NtQueryVirtualMemory (NTDLL.@)
2257 * ZwQueryVirtualMemory (NTDLL.@)
2259 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
2260 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2261 SIZE_T len, SIZE_T *res_len )
2263 struct file_view *view;
2264 char *base, *alloc_base = 0;
2265 struct list *ptr;
2266 SIZE_T size = 0;
2267 MEMORY_BASIC_INFORMATION *info = buffer;
2268 sigset_t sigset;
2270 if (info_class != MemoryBasicInformation)
2272 switch(info_class)
2274 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
2275 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
2276 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
2278 default:
2279 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
2280 process, addr, info_class, buffer, len, res_len);
2281 return STATUS_INVALID_INFO_CLASS;
2285 if (process != NtCurrentProcess())
2287 NTSTATUS status;
2288 apc_call_t call;
2289 apc_result_t result;
2291 memset( &call, 0, sizeof(call) );
2293 call.virtual_query.type = APC_VIRTUAL_QUERY;
2294 call.virtual_query.addr = wine_server_client_ptr( addr );
2295 status = server_queue_process_apc( process, &call, &result );
2296 if (status != STATUS_SUCCESS) return status;
2298 if (result.virtual_query.status == STATUS_SUCCESS)
2300 info->BaseAddress = wine_server_get_ptr( result.virtual_query.base );
2301 info->AllocationBase = wine_server_get_ptr( result.virtual_query.alloc_base );
2302 info->RegionSize = result.virtual_query.size;
2303 info->Protect = result.virtual_query.prot;
2304 info->AllocationProtect = result.virtual_query.alloc_prot;
2305 info->State = (DWORD)result.virtual_query.state << 12;
2306 info->Type = (DWORD)result.virtual_query.alloc_type << 16;
2307 if (info->RegionSize != result.virtual_query.size) /* truncated */
2308 return STATUS_INVALID_PARAMETER; /* FIXME */
2309 if (res_len) *res_len = sizeof(*info);
2311 return result.virtual_query.status;
2314 base = ROUND_ADDR( addr, page_mask );
2316 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2318 /* Find the view containing the address */
2320 server_enter_uninterrupted_section( &csVirtual, &sigset );
2321 ptr = list_head( &views_list );
2322 for (;;)
2324 if (!ptr)
2326 size = (char *)working_set_limit - alloc_base;
2327 view = NULL;
2328 break;
2330 view = LIST_ENTRY( ptr, struct file_view, entry );
2331 if ((char *)view->base > base)
2333 size = (char *)view->base - alloc_base;
2334 view = NULL;
2335 break;
2337 if ((char *)view->base + view->size > base)
2339 alloc_base = view->base;
2340 size = view->size;
2341 break;
2343 alloc_base = (char *)view->base + view->size;
2344 ptr = list_next( &views_list, ptr );
2347 /* Fill the info structure */
2349 info->AllocationBase = alloc_base;
2350 info->BaseAddress = base;
2351 info->RegionSize = size - (base - alloc_base);
2353 if (!view)
2355 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2357 /* not in a reserved area at all, pretend it's allocated */
2358 #ifdef __i386__
2359 if (base >= (char *)address_space_start)
2361 info->State = MEM_RESERVE;
2362 info->Protect = PAGE_NOACCESS;
2363 info->AllocationProtect = PAGE_NOACCESS;
2364 info->Type = MEM_PRIVATE;
2366 else
2367 #endif
2369 info->State = MEM_FREE;
2370 info->Protect = PAGE_NOACCESS;
2371 info->AllocationBase = 0;
2372 info->AllocationProtect = 0;
2373 info->Type = 0;
2377 else
2379 BYTE vprot;
2380 SIZE_T range_size = get_committed_size( view, base, &vprot );
2382 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2383 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2384 info->AllocationBase = alloc_base;
2385 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2386 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2387 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2388 else info->Type = MEM_MAPPED;
2389 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2390 if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2391 info->RegionSize = size - (base - alloc_base);
2393 server_leave_uninterrupted_section( &csVirtual, &sigset );
2395 if (res_len) *res_len = sizeof(*info);
2396 return STATUS_SUCCESS;
2400 /***********************************************************************
2401 * NtLockVirtualMemory (NTDLL.@)
2402 * ZwLockVirtualMemory (NTDLL.@)
2404 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2406 NTSTATUS status = STATUS_SUCCESS;
2408 if (process != NtCurrentProcess())
2410 apc_call_t call;
2411 apc_result_t result;
2413 memset( &call, 0, sizeof(call) );
2415 call.virtual_lock.type = APC_VIRTUAL_LOCK;
2416 call.virtual_lock.addr = wine_server_client_ptr( *addr );
2417 call.virtual_lock.size = *size;
2418 status = server_queue_process_apc( process, &call, &result );
2419 if (status != STATUS_SUCCESS) return status;
2421 if (result.virtual_lock.status == STATUS_SUCCESS)
2423 *addr = wine_server_get_ptr( result.virtual_lock.addr );
2424 *size = result.virtual_lock.size;
2426 return result.virtual_lock.status;
2429 *size = ROUND_SIZE( *addr, *size );
2430 *addr = ROUND_ADDR( *addr, page_mask );
2432 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2433 return status;
2437 /***********************************************************************
2438 * NtUnlockVirtualMemory (NTDLL.@)
2439 * ZwUnlockVirtualMemory (NTDLL.@)
2441 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2443 NTSTATUS status = STATUS_SUCCESS;
2445 if (process != NtCurrentProcess())
2447 apc_call_t call;
2448 apc_result_t result;
2450 memset( &call, 0, sizeof(call) );
2452 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2453 call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2454 call.virtual_unlock.size = *size;
2455 status = server_queue_process_apc( process, &call, &result );
2456 if (status != STATUS_SUCCESS) return status;
2458 if (result.virtual_unlock.status == STATUS_SUCCESS)
2460 *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2461 *size = result.virtual_unlock.size;
2463 return result.virtual_unlock.status;
2466 *size = ROUND_SIZE( *addr, *size );
2467 *addr = ROUND_ADDR( *addr, page_mask );
2469 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2470 return status;
2474 /***********************************************************************
2475 * NtCreateSection (NTDLL.@)
2476 * ZwCreateSection (NTDLL.@)
2478 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2479 const LARGE_INTEGER *size, ULONG protect,
2480 ULONG sec_flags, HANDLE file )
2482 NTSTATUS ret;
2483 unsigned int vprot;
2484 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2485 struct security_descriptor *sd = NULL;
2486 struct object_attributes objattr;
2488 /* Check parameters */
2490 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2492 if ((ret = get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE ))) return ret;
2494 objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
2495 objattr.sd_len = 0;
2496 objattr.name_len = len;
2497 if (attr)
2499 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2500 if (ret != STATUS_SUCCESS) return ret;
2503 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2504 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2505 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2507 /* Create the server object */
2509 SERVER_START_REQ( create_mapping )
2511 req->access = access;
2512 req->attributes = (attr) ? attr->Attributes : 0;
2513 req->file_handle = wine_server_obj_handle( file );
2514 req->size = size ? size->QuadPart : 0;
2515 req->protect = vprot;
2516 wine_server_add_data( req, &objattr, sizeof(objattr) );
2517 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2518 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2519 ret = wine_server_call( req );
2520 *handle = wine_server_ptr_handle( reply->handle );
2522 SERVER_END_REQ;
2524 NTDLL_free_struct_sd( sd );
2526 return ret;
2530 /***********************************************************************
2531 * NtOpenSection (NTDLL.@)
2532 * ZwOpenSection (NTDLL.@)
2534 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2536 NTSTATUS ret;
2537 DWORD len = attr->ObjectName->Length;
2539 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2541 SERVER_START_REQ( open_mapping )
2543 req->access = access;
2544 req->attributes = attr->Attributes;
2545 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2546 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2547 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
2549 SERVER_END_REQ;
2550 return ret;
2554 /***********************************************************************
2555 * NtMapViewOfSection (NTDLL.@)
2556 * ZwMapViewOfSection (NTDLL.@)
2558 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2559 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2560 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2562 NTSTATUS res;
2563 mem_size_t full_size;
2564 ACCESS_MASK access;
2565 SIZE_T size, mask = get_mask( zero_bits );
2566 int unix_handle = -1, needs_close;
2567 unsigned int map_vprot, vprot;
2568 void *base;
2569 struct file_view *view;
2570 DWORD header_size;
2571 HANDLE dup_mapping, shared_file;
2572 LARGE_INTEGER offset;
2573 sigset_t sigset;
2575 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2577 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2578 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2580 /* Check parameters */
2582 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2583 return STATUS_INVALID_PARAMETER;
2585 switch(protect)
2587 case PAGE_NOACCESS:
2588 access = SECTION_MAP_READ;
2589 break;
2590 case PAGE_READWRITE:
2591 case PAGE_EXECUTE_READWRITE:
2592 access = SECTION_MAP_WRITE;
2593 break;
2594 case PAGE_READONLY:
2595 case PAGE_WRITECOPY:
2596 case PAGE_EXECUTE:
2597 case PAGE_EXECUTE_READ:
2598 case PAGE_EXECUTE_WRITECOPY:
2599 access = SECTION_MAP_READ;
2600 break;
2601 default:
2602 return STATUS_INVALID_PAGE_PROTECTION;
2605 if (process != NtCurrentProcess())
2607 apc_call_t call;
2608 apc_result_t result;
2610 memset( &call, 0, sizeof(call) );
2612 call.map_view.type = APC_MAP_VIEW;
2613 call.map_view.handle = wine_server_obj_handle( handle );
2614 call.map_view.addr = wine_server_client_ptr( *addr_ptr );
2615 call.map_view.size = *size_ptr;
2616 call.map_view.offset = offset.QuadPart;
2617 call.map_view.zero_bits = zero_bits;
2618 call.map_view.alloc_type = alloc_type;
2619 call.map_view.prot = protect;
2620 res = server_queue_process_apc( process, &call, &result );
2621 if (res != STATUS_SUCCESS) return res;
2623 if ((NTSTATUS)result.map_view.status >= 0)
2625 *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2626 *size_ptr = result.map_view.size;
2628 return result.map_view.status;
2631 SERVER_START_REQ( get_mapping_info )
2633 req->handle = wine_server_obj_handle( handle );
2634 req->access = access;
2635 res = wine_server_call( req );
2636 map_vprot = reply->protect;
2637 base = wine_server_get_ptr( reply->base );
2638 full_size = reply->size;
2639 header_size = reply->header_size;
2640 dup_mapping = wine_server_ptr_handle( reply->mapping );
2641 shared_file = wine_server_ptr_handle( reply->shared_file );
2642 if ((ULONG_PTR)base != reply->base) base = NULL;
2644 SERVER_END_REQ;
2645 if (res) return res;
2647 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2649 if (map_vprot & VPROT_IMAGE)
2651 size = full_size;
2652 if (size != full_size) /* truncated */
2654 WARN( "Modules larger than 4Gb (%s) not supported\n", wine_dbgstr_longlong(full_size) );
2655 res = STATUS_INVALID_PARAMETER;
2656 goto done;
2658 if (shared_file)
2660 int shared_fd, shared_needs_close;
2662 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2663 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2664 res = map_image( handle, unix_handle, base, size, mask, header_size,
2665 shared_fd, dup_mapping, map_vprot, addr_ptr );
2666 if (shared_needs_close) close( shared_fd );
2667 NtClose( shared_file );
2669 else
2671 res = map_image( handle, unix_handle, base, size, mask, header_size,
2672 -1, dup_mapping, map_vprot, addr_ptr );
2674 if (needs_close) close( unix_handle );
2675 if (res >= 0) *size_ptr = size;
2676 return res;
2679 res = STATUS_INVALID_PARAMETER;
2680 if (offset.QuadPart >= full_size) goto done;
2681 if (*size_ptr)
2683 if (*size_ptr > full_size - offset.QuadPart) goto done;
2684 size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2685 if (size < *size_ptr) goto done; /* wrap-around */
2687 else
2689 size = full_size - offset.QuadPart;
2690 if (size != full_size - offset.QuadPart) /* truncated */
2692 WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2693 wine_dbgstr_longlong(full_size) );
2694 goto done;
2698 /* Reserve a properly aligned area */
2700 server_enter_uninterrupted_section( &csVirtual, &sigset );
2702 get_vprot_flags( protect, &vprot, map_vprot & VPROT_IMAGE );
2703 vprot |= (map_vprot & VPROT_COMMITTED);
2704 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2705 if (res)
2707 server_leave_uninterrupted_section( &csVirtual, &sigset );
2708 goto done;
2711 /* Map the file */
2713 TRACE("handle=%p size=%lx offset=%x%08x\n",
2714 handle, size, offset.u.HighPart, offset.u.LowPart );
2716 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2717 if (res == STATUS_SUCCESS)
2719 *addr_ptr = view->base;
2720 *size_ptr = size;
2721 view->mapping = dup_mapping;
2722 view->map_protect = map_vprot;
2723 dup_mapping = 0; /* don't close it */
2725 else
2727 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2728 view->base, size, offset.u.HighPart, offset.u.LowPart );
2729 delete_view( view );
2732 server_leave_uninterrupted_section( &csVirtual, &sigset );
2734 done:
2735 if (dup_mapping) NtClose( dup_mapping );
2736 if (needs_close) close( unix_handle );
2737 return res;
2741 /***********************************************************************
2742 * NtUnmapViewOfSection (NTDLL.@)
2743 * ZwUnmapViewOfSection (NTDLL.@)
2745 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2747 struct file_view *view;
2748 NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
2749 sigset_t sigset;
2750 void *base = ROUND_ADDR( addr, page_mask );
2752 if (process != NtCurrentProcess())
2754 apc_call_t call;
2755 apc_result_t result;
2757 memset( &call, 0, sizeof(call) );
2759 call.unmap_view.type = APC_UNMAP_VIEW;
2760 call.unmap_view.addr = wine_server_client_ptr( addr );
2761 status = server_queue_process_apc( process, &call, &result );
2762 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2763 return status;
2766 server_enter_uninterrupted_section( &csVirtual, &sigset );
2767 if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base) && !(view->protect & VPROT_VALLOC))
2769 delete_view( view );
2770 status = STATUS_SUCCESS;
2772 server_leave_uninterrupted_section( &csVirtual, &sigset );
2773 return status;
2777 /***********************************************************************
2778 * NtFlushVirtualMemory (NTDLL.@)
2779 * ZwFlushVirtualMemory (NTDLL.@)
2781 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2782 SIZE_T *size_ptr, ULONG unknown )
2784 struct file_view *view;
2785 NTSTATUS status = STATUS_SUCCESS;
2786 sigset_t sigset;
2787 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2789 if (process != NtCurrentProcess())
2791 apc_call_t call;
2792 apc_result_t result;
2794 memset( &call, 0, sizeof(call) );
2796 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2797 call.virtual_flush.addr = wine_server_client_ptr( addr );
2798 call.virtual_flush.size = *size_ptr;
2799 status = server_queue_process_apc( process, &call, &result );
2800 if (status != STATUS_SUCCESS) return status;
2802 if (result.virtual_flush.status == STATUS_SUCCESS)
2804 *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2805 *size_ptr = result.virtual_flush.size;
2807 return result.virtual_flush.status;
2810 server_enter_uninterrupted_section( &csVirtual, &sigset );
2811 if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2812 else
2814 if (!*size_ptr) *size_ptr = view->size;
2815 *addr_ptr = addr;
2816 #ifdef MS_ASYNC
2817 if (msync( addr, *size_ptr, MS_ASYNC )) status = STATUS_NOT_MAPPED_DATA;
2818 #endif
2820 server_leave_uninterrupted_section( &csVirtual, &sigset );
2821 return status;
2825 /***********************************************************************
2826 * NtGetWriteWatch (NTDLL.@)
2827 * ZwGetWriteWatch (NTDLL.@)
2829 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
2830 ULONG_PTR *count, ULONG *granularity )
2832 struct file_view *view;
2833 NTSTATUS status = STATUS_SUCCESS;
2834 sigset_t sigset;
2836 size = ROUND_SIZE( base, size );
2837 base = ROUND_ADDR( base, page_mask );
2839 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
2840 if (!*count || !size) return STATUS_INVALID_PARAMETER;
2841 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
2843 if (!addresses) return STATUS_ACCESS_VIOLATION;
2845 TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
2846 addresses, *count );
2848 server_enter_uninterrupted_section( &csVirtual, &sigset );
2850 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2852 ULONG_PTR pos = 0;
2853 char *addr = base;
2854 char *end = addr + size;
2856 while (pos < *count && addr < end)
2858 BYTE prot = view->prot[(addr - (char *)view->base) >> page_shift];
2859 if (!(prot & VPROT_WRITEWATCH)) addresses[pos++] = addr;
2860 addr += page_size;
2862 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( view, base, addr - (char *)base );
2863 *count = pos;
2864 *granularity = page_size;
2866 else status = STATUS_INVALID_PARAMETER;
2868 server_leave_uninterrupted_section( &csVirtual, &sigset );
2869 return status;
2873 /***********************************************************************
2874 * NtResetWriteWatch (NTDLL.@)
2875 * ZwResetWriteWatch (NTDLL.@)
2877 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
2879 struct file_view *view;
2880 NTSTATUS status = STATUS_SUCCESS;
2881 sigset_t sigset;
2883 size = ROUND_SIZE( base, size );
2884 base = ROUND_ADDR( base, page_mask );
2886 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
2888 if (!size) return STATUS_INVALID_PARAMETER;
2890 server_enter_uninterrupted_section( &csVirtual, &sigset );
2892 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2893 reset_write_watches( view, base, size );
2894 else
2895 status = STATUS_INVALID_PARAMETER;
2897 server_leave_uninterrupted_section( &csVirtual, &sigset );
2898 return status;
2902 /***********************************************************************
2903 * NtReadVirtualMemory (NTDLL.@)
2904 * ZwReadVirtualMemory (NTDLL.@)
2906 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2907 SIZE_T size, SIZE_T *bytes_read )
2909 NTSTATUS status;
2911 if (virtual_check_buffer_for_write( buffer, size ))
2913 SERVER_START_REQ( read_process_memory )
2915 req->handle = wine_server_obj_handle( process );
2916 req->addr = wine_server_client_ptr( addr );
2917 wine_server_set_reply( req, buffer, size );
2918 if ((status = wine_server_call( req ))) size = 0;
2920 SERVER_END_REQ;
2922 else
2924 status = STATUS_ACCESS_VIOLATION;
2925 size = 0;
2927 if (bytes_read) *bytes_read = size;
2928 return status;
2932 /***********************************************************************
2933 * NtWriteVirtualMemory (NTDLL.@)
2934 * ZwWriteVirtualMemory (NTDLL.@)
2936 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2937 SIZE_T size, SIZE_T *bytes_written )
2939 NTSTATUS status;
2941 if (virtual_check_buffer_for_read( buffer, size ))
2943 SERVER_START_REQ( write_process_memory )
2945 req->handle = wine_server_obj_handle( process );
2946 req->addr = wine_server_client_ptr( addr );
2947 wine_server_add_data( req, buffer, size );
2948 if ((status = wine_server_call( req ))) size = 0;
2950 SERVER_END_REQ;
2952 else
2954 status = STATUS_PARTIAL_COPY;
2955 size = 0;
2957 if (bytes_written) *bytes_written = size;
2958 return status;
2962 /***********************************************************************
2963 * NtAreMappedFilesTheSame (NTDLL.@)
2964 * ZwAreMappedFilesTheSame (NTDLL.@)
2966 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2968 struct file_view *view1, *view2;
2969 struct stat st1, st2;
2970 NTSTATUS status;
2971 sigset_t sigset;
2973 TRACE("%p %p\n", addr1, addr2);
2975 server_enter_uninterrupted_section( &csVirtual, &sigset );
2977 view1 = VIRTUAL_FindView( addr1, 0 );
2978 view2 = VIRTUAL_FindView( addr2, 0 );
2980 if (!view1 || !view2)
2981 status = STATUS_INVALID_ADDRESS;
2982 else if ((view1->protect & VPROT_VALLOC) || (view2->protect & VPROT_VALLOC))
2983 status = STATUS_CONFLICTING_ADDRESSES;
2984 else if (view1 == view2)
2985 status = STATUS_SUCCESS;
2986 else if (!(view1->protect & VPROT_IMAGE) || !(view2->protect & VPROT_IMAGE))
2987 status = STATUS_NOT_SAME_DEVICE;
2988 else if (!stat_mapping_file( view1, &st1 ) && !stat_mapping_file( view2, &st2 ) &&
2989 st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2990 status = STATUS_SUCCESS;
2991 else
2992 status = STATUS_NOT_SAME_DEVICE;
2994 server_leave_uninterrupted_section( &csVirtual, &sigset );
2995 return status;