push 9758e6fe7ae8fbab538c98c718d6619029bb3457
[wine/hacks.git] / dlls / ntdll / virtual.c
blob78e38dc924946592c6c402b7d303919516b64963
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 #ifdef HAVE_SYS_ERRNO_H
27 #include <sys/errno.h>
28 #endif
29 #include <fcntl.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include <stdarg.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
40 #endif
41 #ifdef HAVE_SYS_MMAN_H
42 # include <sys/mman.h>
43 #endif
44 #ifdef HAVE_VALGRIND_VALGRIND_H
45 # include <valgrind/valgrind.h>
46 #endif
48 #define NONAMELESSUNION
49 #define NONAMELESSSTRUCT
50 #include "ntstatus.h"
51 #define WIN32_NO_STATUS
52 #include "windef.h"
53 #include "winternl.h"
54 #include "wine/library.h"
55 #include "wine/server.h"
56 #include "wine/list.h"
57 #include "wine/debug.h"
58 #include "ntdll_misc.h"
60 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
61 WINE_DECLARE_DEBUG_CHANNEL(module);
63 #ifndef MS_SYNC
64 #define MS_SYNC 0
65 #endif
67 #ifndef MAP_NORESERVE
68 #define MAP_NORESERVE 0
69 #endif
71 /* File view */
72 typedef struct file_view
74 struct list entry; /* Entry in global view list */
75 void *base; /* Base address */
76 size_t size; /* Size in bytes */
77 HANDLE mapping; /* Handle to the file mapping */
78 BYTE flags; /* Allocation flags (VFLAG_*) */
79 BYTE protect; /* Protection for all pages at allocation time */
80 BYTE prot[1]; /* Protection byte for each page */
81 } FILE_VIEW;
83 /* Per-view flags */
84 #define VFLAG_SYSTEM 0x01 /* system view (underlying mmap not under our control) */
85 #define VFLAG_VALLOC 0x02 /* allocated by VirtualAlloc */
87 /* Conversion from VPROT_* to Win32 flags */
88 static const BYTE VIRTUAL_Win32Flags[16] =
90 PAGE_NOACCESS, /* 0 */
91 PAGE_READONLY, /* READ */
92 PAGE_READWRITE, /* WRITE */
93 PAGE_READWRITE, /* READ | WRITE */
94 PAGE_EXECUTE, /* EXEC */
95 PAGE_EXECUTE_READ, /* READ | EXEC */
96 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
97 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
98 PAGE_WRITECOPY, /* WRITECOPY */
99 PAGE_WRITECOPY, /* READ | WRITECOPY */
100 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
101 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
102 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
103 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
104 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
105 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
108 static struct list views_list = LIST_INIT(views_list);
110 static RTL_CRITICAL_SECTION csVirtual;
111 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
113 0, 0, &csVirtual,
114 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
115 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
117 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
119 #ifdef __i386__
120 /* These are always the same on an i386, and it will be faster this way */
121 # define page_mask 0xfff
122 # define page_shift 12
123 # define page_size 0x1000
124 /* Note: these are Windows limits, you cannot change them. */
125 # define ADDRESS_SPACE_LIMIT ((void *)0xc0000000) /* top of the total available address space */
126 # define USER_SPACE_LIMIT ((void *)0x7fff0000) /* top of the user address space */
127 #else
128 static UINT page_shift;
129 static UINT page_size;
130 static UINT_PTR page_mask;
131 # define ADDRESS_SPACE_LIMIT 0 /* no limit needed on other platforms */
132 # define USER_SPACE_LIMIT 0 /* no limit needed on other platforms */
133 #endif /* __i386__ */
135 #define ROUND_ADDR(addr,mask) \
136 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
138 #define ROUND_SIZE(addr,size) \
139 (((UINT)(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 static void *user_space_limit = USER_SPACE_LIMIT;
145 static void *preload_reserve_start;
146 static void *preload_reserve_end;
147 static int use_locks;
148 static int force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
151 /***********************************************************************
152 * VIRTUAL_GetProtStr
154 static const char *VIRTUAL_GetProtStr( BYTE prot )
156 static char buffer[6];
157 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
158 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
159 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
160 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
161 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
162 buffer[5] = 0;
163 return buffer;
167 /***********************************************************************
168 * VIRTUAL_GetUnixProt
170 * Convert page protections to protection for mmap/mprotect.
172 static int VIRTUAL_GetUnixProt( BYTE vprot )
174 int prot = 0;
175 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
177 if (vprot & VPROT_READ) prot |= PROT_READ;
178 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
179 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
180 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
182 if (!prot) prot = PROT_NONE;
183 return prot;
187 /***********************************************************************
188 * VIRTUAL_DumpView
190 static void VIRTUAL_DumpView( FILE_VIEW *view )
192 UINT i, count;
193 char *addr = view->base;
194 BYTE prot = view->prot[0];
196 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
197 if (view->flags & VFLAG_SYSTEM)
198 TRACE( " (system)\n" );
199 else if (view->flags & VFLAG_VALLOC)
200 TRACE( " (valloc)\n" );
201 else if (view->mapping)
202 TRACE( " %p\n", view->mapping );
203 else
204 TRACE( " (anonymous)\n");
206 for (count = i = 1; i < view->size >> page_shift; i++, count++)
208 if (view->prot[i] == prot) continue;
209 TRACE( " %p - %p %s\n",
210 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
211 addr += (count << page_shift);
212 prot = view->prot[i];
213 count = 0;
215 if (count)
216 TRACE( " %p - %p %s\n",
217 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
221 /***********************************************************************
222 * VIRTUAL_Dump
224 #if WINE_VM_DEBUG
225 static void VIRTUAL_Dump(void)
227 sigset_t sigset;
228 struct file_view *view;
230 TRACE( "Dump of all virtual memory views:\n" );
231 server_enter_uninterrupted_section( &csVirtual, &sigset );
232 LIST_FOR_EACH_ENTRY( view, &views_list, FILE_VIEW, entry )
234 VIRTUAL_DumpView( view );
236 server_leave_uninterrupted_section( &csVirtual, &sigset );
238 #endif
241 /***********************************************************************
242 * VIRTUAL_FindView
244 * Find the view containing a given address. The csVirtual section must be held by caller.
246 * PARAMS
247 * addr [I] Address
249 * RETURNS
250 * View: Success
251 * NULL: Failure
253 static struct file_view *VIRTUAL_FindView( const void *addr )
255 struct file_view *view;
257 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
259 if (view->base > addr) break;
260 if ((const char*)view->base + view->size > (const char*)addr) return view;
262 return NULL;
266 /***********************************************************************
267 * get_mask
269 static inline UINT_PTR get_mask( ULONG zero_bits )
271 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
272 if (zero_bits < page_shift) zero_bits = page_shift;
273 return (1 << zero_bits) - 1;
277 /***********************************************************************
278 * find_view_range
280 * Find the first view overlapping at least part of the specified range.
281 * The csVirtual section must be held by caller.
283 static struct file_view *find_view_range( const void *addr, size_t size )
285 struct file_view *view;
287 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
289 if ((const char *)view->base >= (const char *)addr + size) break;
290 if ((const char *)view->base + view->size > (const char *)addr) return view;
292 return NULL;
296 /***********************************************************************
297 * find_free_area
299 * Find a free area between views inside the specified range.
300 * The csVirtual section must be held by caller.
302 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
304 struct list *ptr;
305 void *start;
307 if (top_down)
309 start = ROUND_ADDR( (char *)end - size, mask );
310 if (start >= end || start < base) return NULL;
312 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
314 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
316 if ((char *)view->base + view->size <= (char *)start) break;
317 if ((char *)view->base >= (char *)start + size) continue;
318 start = ROUND_ADDR( (char *)view->base - size, mask );
319 /* stop if remaining space is not large enough */
320 if (!start || start >= end || start < base) return NULL;
323 else
325 start = ROUND_ADDR( (char *)base + mask, mask );
326 if (start >= end || (char *)end - (char *)start < size) return NULL;
328 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
330 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
332 if ((char *)view->base >= (char *)start + size) break;
333 if ((char *)view->base + view->size <= (char *)start) continue;
334 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
335 /* stop if remaining space is not large enough */
336 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
339 return start;
343 /***********************************************************************
344 * add_reserved_area
346 * Add a reserved area to the list maintained by libwine.
347 * The csVirtual section must be held by caller.
349 static void add_reserved_area( void *addr, size_t size )
351 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
353 if (addr < user_space_limit)
355 /* unmap the part of the area that is below the limit */
356 assert( (char *)addr + size > (char *)user_space_limit );
357 munmap( addr, (char *)user_space_limit - (char *)addr );
358 size -= (char *)user_space_limit - (char *)addr;
359 addr = user_space_limit;
361 /* blow away existing mappings */
362 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
363 wine_mmap_add_reserved_area( addr, size );
367 /***********************************************************************
368 * is_beyond_limit
370 * Check if an address range goes beyond a given limit.
372 static inline int is_beyond_limit( const void *addr, size_t size, const void *limit )
374 return (limit && (addr >= limit || (const char *)addr + size > (const char *)limit));
378 /***********************************************************************
379 * unmap_area
381 * Unmap an area, or simply replace it by an empty mapping if it is
382 * in a reserved area. The csVirtual section must be held by caller.
384 static inline void unmap_area( void *addr, size_t size )
386 if (wine_mmap_is_in_reserved_area( addr, size ))
387 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
388 else if (is_beyond_limit( addr, size, user_space_limit ))
389 add_reserved_area( addr, size );
390 else
391 munmap( addr, size );
395 /***********************************************************************
396 * delete_view
398 * Deletes a view. The csVirtual section must be held by caller.
400 static void delete_view( struct file_view *view ) /* [in] View */
402 if (!(view->flags & VFLAG_SYSTEM)) unmap_area( view->base, view->size );
403 list_remove( &view->entry );
404 if (view->mapping) NtClose( view->mapping );
405 free( view );
409 /***********************************************************************
410 * create_view
412 * Create a view. The csVirtual section must be held by caller.
414 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, BYTE vprot )
416 struct file_view *view;
417 struct list *ptr;
418 int unix_prot = VIRTUAL_GetUnixProt( vprot );
420 assert( !((UINT_PTR)base & page_mask) );
421 assert( !(size & page_mask) );
423 /* Create the view structure */
425 if (!(view = malloc( sizeof(*view) + (size >> page_shift) - 1 ))) return STATUS_NO_MEMORY;
427 view->base = base;
428 view->size = size;
429 view->flags = 0;
430 view->mapping = 0;
431 view->protect = vprot;
432 memset( view->prot, vprot & ~VPROT_IMAGE, size >> page_shift );
434 /* Insert it in the linked list */
436 LIST_FOR_EACH( ptr, &views_list )
438 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
439 if (next->base > base) break;
441 list_add_before( ptr, &view->entry );
443 /* Check for overlapping views. This can happen if the previous view
444 * was a system view that got unmapped behind our back. In that case
445 * we recover by simply deleting it. */
447 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
449 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
450 if ((char *)prev->base + prev->size > (char *)base)
452 TRACE( "overlapping prev view %p-%p for %p-%p\n",
453 prev->base, (char *)prev->base + prev->size,
454 base, (char *)base + view->size );
455 assert( prev->flags & VFLAG_SYSTEM );
456 delete_view( prev );
459 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
461 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
462 if ((char *)base + view->size > (char *)next->base)
464 TRACE( "overlapping next view %p-%p for %p-%p\n",
465 next->base, (char *)next->base + next->size,
466 base, (char *)base + view->size );
467 assert( next->flags & VFLAG_SYSTEM );
468 delete_view( next );
472 *view_ret = view;
473 VIRTUAL_DEBUG_DUMP_VIEW( view );
475 if (force_exec_prot && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
477 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
478 mprotect( base, size, unix_prot | PROT_EXEC );
480 return STATUS_SUCCESS;
484 /***********************************************************************
485 * VIRTUAL_GetWin32Prot
487 * Convert page protections to Win32 flags.
489 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
491 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
492 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
493 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
494 return ret;
498 /***********************************************************************
499 * VIRTUAL_GetProt
501 * Build page protections from Win32 flags.
503 * PARAMS
504 * protect [I] Win32 protection flags
506 * RETURNS
507 * Value of page protection flags
509 static BYTE VIRTUAL_GetProt( DWORD protect )
511 BYTE vprot;
513 switch(protect & 0xff)
515 case PAGE_READONLY:
516 vprot = VPROT_READ;
517 break;
518 case PAGE_READWRITE:
519 vprot = VPROT_READ | VPROT_WRITE;
520 break;
521 case PAGE_WRITECOPY:
522 /* MSDN CreateFileMapping() states that if PAGE_WRITECOPY is given,
523 * that the hFile must have been opened with GENERIC_READ and
524 * GENERIC_WRITE access. This is WRONG as tests show that you
525 * only need GENERIC_READ access (at least for Win9x,
526 * FIXME: what about NT?). Thus, we don't put VPROT_WRITE in
527 * PAGE_WRITECOPY and PAGE_EXECUTE_WRITECOPY.
529 vprot = VPROT_READ | VPROT_WRITECOPY;
530 break;
531 case PAGE_EXECUTE:
532 vprot = VPROT_EXEC;
533 break;
534 case PAGE_EXECUTE_READ:
535 vprot = VPROT_EXEC | VPROT_READ;
536 break;
537 case PAGE_EXECUTE_READWRITE:
538 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
539 break;
540 case PAGE_EXECUTE_WRITECOPY:
541 /* See comment for PAGE_WRITECOPY above */
542 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
543 break;
544 case PAGE_NOACCESS:
545 default:
546 vprot = 0;
547 break;
549 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
550 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
551 return vprot;
555 /***********************************************************************
556 * VIRTUAL_SetProt
558 * Change the protection of a range of pages.
560 * RETURNS
561 * TRUE: Success
562 * FALSE: Failure
564 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
565 void *base, /* [in] Starting address */
566 size_t size, /* [in] Size in bytes */
567 BYTE vprot ) /* [in] Protections to use */
569 int unix_prot = VIRTUAL_GetUnixProt(vprot);
571 TRACE("%p-%p %s\n",
572 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
574 /* if setting stack guard pages, store the permissions first, as the guard may be
575 * triggered at any point after mprotect and change the permissions again */
576 if ((vprot & VPROT_GUARD) &&
577 ((char *)base >= (char *)NtCurrentTeb()->DeallocationStack) &&
578 ((char *)base < (char *)NtCurrentTeb()->Tib.StackBase))
580 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
581 vprot, size >> page_shift );
582 mprotect( base, size, unix_prot );
583 VIRTUAL_DEBUG_DUMP_VIEW( view );
584 return TRUE;
587 if (force_exec_prot && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
589 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
590 if (!mprotect( base, size, unix_prot | PROT_EXEC )) goto done;
591 /* exec + write may legitimately fail, in that case fall back to write only */
592 if (!(unix_prot & PROT_WRITE)) return FALSE;
595 if (mprotect( base, size, unix_prot )) return FALSE; /* FIXME: last error */
597 done:
598 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
599 vprot, size >> page_shift );
600 VIRTUAL_DEBUG_DUMP_VIEW( view );
601 return TRUE;
605 /***********************************************************************
606 * unmap_extra_space
608 * Release the extra memory while keeping the range starting on the granularity boundary.
610 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
612 if ((ULONG_PTR)ptr & mask)
614 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
615 munmap( ptr, extra );
616 ptr = (char *)ptr + extra;
617 total_size -= extra;
619 if (total_size > wanted_size)
620 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
621 return ptr;
625 struct alloc_area
627 size_t size;
628 size_t mask;
629 int top_down;
630 void *result;
633 /***********************************************************************
634 * alloc_reserved_area_callback
636 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
638 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
640 static void * const address_space_start = (void *)0x110000;
641 struct alloc_area *alloc = arg;
642 void *end = (char *)start + size;
644 if (start < address_space_start) start = address_space_start;
645 if (user_space_limit && end > user_space_limit) end = user_space_limit;
646 if (start >= end) return 0;
648 /* make sure we don't touch the preloader reserved range */
649 if (preload_reserve_end >= start)
651 if (preload_reserve_end >= end)
653 if (preload_reserve_start <= start) return 0; /* no space in that area */
654 if (preload_reserve_start < end) end = preload_reserve_start;
656 else if (preload_reserve_start <= start) start = preload_reserve_end;
657 else
659 /* range is split in two by the preloader reservation, try first part */
660 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
661 alloc->mask, alloc->top_down )))
662 return 1;
663 /* then fall through to try second part */
664 start = preload_reserve_end;
667 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
668 return 1;
670 return 0;
674 /***********************************************************************
675 * map_view
677 * Create a view and mmap the corresponding memory area.
678 * The csVirtual section must be held by caller.
680 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
681 int top_down, BYTE vprot )
683 void *ptr;
684 NTSTATUS status;
686 if (base)
688 if (is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
689 return STATUS_WORKING_SET_LIMIT_RANGE;
691 switch (wine_mmap_is_in_reserved_area( base, size ))
693 case -1: /* partially in a reserved area */
694 return STATUS_CONFLICTING_ADDRESSES;
696 case 0: /* not in a reserved area, do a normal allocation */
697 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
699 if (errno == ENOMEM) return STATUS_NO_MEMORY;
700 return STATUS_INVALID_PARAMETER;
702 if (ptr != base)
704 /* We couldn't get the address we wanted */
705 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
706 else munmap( ptr, size );
707 return STATUS_CONFLICTING_ADDRESSES;
709 break;
711 default:
712 case 1: /* in a reserved area, make sure the address is available */
713 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
714 /* replace the reserved area by our mapping */
715 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
716 return STATUS_INVALID_PARAMETER;
717 break;
720 else
722 size_t view_size = size + mask + 1;
723 struct alloc_area alloc;
725 alloc.size = size;
726 alloc.mask = mask;
727 alloc.top_down = top_down;
728 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
730 ptr = alloc.result;
731 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
732 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
733 return STATUS_INVALID_PARAMETER;
734 goto done;
737 for (;;)
739 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
741 if (errno == ENOMEM) return STATUS_NO_MEMORY;
742 return STATUS_INVALID_PARAMETER;
744 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
745 /* if we got something beyond the user limit, unmap it and retry */
746 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
747 else break;
749 ptr = unmap_extra_space( ptr, view_size, size, mask );
751 done:
752 status = create_view( view_ret, ptr, size, vprot );
753 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
754 return status;
758 /***********************************************************************
759 * unaligned_mmap
761 * Linux kernels before 2.4.x can support non page-aligned offsets, as
762 * long as the offset is aligned to the filesystem block size. This is
763 * a big performance gain so we want to take advantage of it.
765 * However, when we use 64-bit file support this doesn't work because
766 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
767 * in that it rounds unaligned offsets down to a page boundary. For
768 * these reasons we do a direct system call here.
770 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
771 unsigned int flags, int fd, off_t offset )
773 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
774 if (!(offset >> 32) && (offset & page_mask))
776 int ret;
778 struct
780 void *addr;
781 unsigned int length;
782 unsigned int prot;
783 unsigned int flags;
784 unsigned int fd;
785 unsigned int offset;
786 } args;
788 args.addr = addr;
789 args.length = length;
790 args.prot = prot;
791 args.flags = flags;
792 args.fd = fd;
793 args.offset = offset;
795 __asm__ __volatile__("push %%ebx\n\t"
796 "movl %2,%%ebx\n\t"
797 "int $0x80\n\t"
798 "popl %%ebx"
799 : "=a" (ret)
800 : "0" (90), /* SYS_mmap */
801 "q" (&args)
802 : "memory" );
803 if (ret < 0 && ret > -4096)
805 errno = -ret;
806 ret = -1;
808 return (void *)ret;
810 #endif
811 return mmap( addr, length, prot, flags, fd, offset );
815 /***********************************************************************
816 * map_file_into_view
818 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
819 * The csVirtual section must be held by caller.
821 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
822 off_t offset, BYTE vprot, BOOL removable )
824 void *ptr;
825 int prot = VIRTUAL_GetUnixProt( vprot );
826 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
828 assert( start < view->size );
829 assert( start + size <= view->size );
831 /* only try mmap if media is not removable (or if we require write access) */
832 if (!removable || shared_write)
834 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
836 if (unaligned_mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
837 goto done;
839 /* mmap() failed; if this is because the file offset is not */
840 /* page-aligned (EINVAL), or because the underlying filesystem */
841 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
842 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
843 if (shared_write) /* we cannot fake shared write mappings */
845 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
846 ERR( "shared writable mmap not supported, broken filesystem?\n" );
847 return STATUS_NOT_SUPPORTED;
851 /* Reserve the memory with an anonymous mmap */
852 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
853 if (ptr == (void *)-1) return FILE_GetNtStatus();
854 /* Now read in the file */
855 pread( fd, ptr, size, offset );
856 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
857 done:
858 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
859 return STATUS_SUCCESS;
863 /***********************************************************************
864 * decommit_view
866 * Decommit some pages of a given view.
867 * The csVirtual section must be held by caller.
869 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
871 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
873 BYTE *p = view->prot + (start >> page_shift);
874 size >>= page_shift;
875 while (size--) *p++ &= ~VPROT_COMMITTED;
876 return STATUS_SUCCESS;
878 return FILE_GetNtStatus();
882 /***********************************************************************
883 * map_image
885 * Map an executable (PE format) image into memory.
887 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
888 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, PVOID *addr_ptr )
890 IMAGE_DOS_HEADER *dos;
891 IMAGE_NT_HEADERS *nt;
892 IMAGE_SECTION_HEADER *sec;
893 IMAGE_DATA_DIRECTORY *imports;
894 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
895 int i;
896 off_t pos;
897 sigset_t sigset;
898 struct stat st;
899 struct file_view *view = NULL;
900 char *ptr, *header_end;
901 int delta = 0;
903 /* zero-map the whole range */
905 server_enter_uninterrupted_section( &csVirtual, &sigset );
907 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
908 status = map_view( &view, base, total_size, mask, FALSE,
909 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
911 if (status == STATUS_CONFLICTING_ADDRESSES)
912 status = map_view( &view, NULL, total_size, mask, FALSE,
913 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
915 if (status != STATUS_SUCCESS) goto error;
917 ptr = view->base;
918 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
920 /* map the header */
922 if (fstat( fd, &st ) == -1)
924 status = FILE_GetNtStatus();
925 goto error;
927 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
928 if (!st.st_size) goto error;
929 header_size = min( header_size, st.st_size );
930 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
931 !dup_mapping ) != STATUS_SUCCESS) goto error;
932 dos = (IMAGE_DOS_HEADER *)ptr;
933 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
934 header_end = ptr + ROUND_SIZE( 0, header_size );
935 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
936 if ((char *)(nt + 1) > header_end) goto error;
937 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
938 if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
940 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
941 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
943 /* check the architecture */
945 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
947 MESSAGE("Trying to load PE image for unsupported architecture (");
948 switch (nt->FileHeader.Machine)
950 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
951 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
952 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
953 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
954 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
955 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
956 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
957 case IMAGE_FILE_MACHINE_IA64: MESSAGE("IA-64"); break;
958 case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
959 case IMAGE_FILE_MACHINE_AMD64: MESSAGE("AMD-64"); break;
960 case IMAGE_FILE_MACHINE_ARM: MESSAGE("ARM"); break;
961 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
963 MESSAGE(")\n");
964 goto error;
967 /* check for non page-aligned binary */
969 if (nt->OptionalHeader.SectionAlignment <= page_mask)
971 /* unaligned sections, this happens for native subsystem binaries */
972 /* in that case Windows simply maps in the whole file */
974 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
975 !dup_mapping ) != STATUS_SUCCESS) goto error;
977 /* check that all sections are loaded at the right offset */
978 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
979 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
981 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
982 goto error; /* Windows refuses to load in that case too */
985 /* set the image protections */
986 VIRTUAL_SetProt( view, ptr, total_size,
987 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
989 /* no relocations are performed on non page-aligned binaries */
990 goto done;
994 /* map all the sections */
996 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
998 static const SIZE_T sector_align = 0x1ff;
999 SIZE_T map_size, file_start, file_size, end;
1001 if (!sec->Misc.VirtualSize)
1002 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1003 else
1004 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1006 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1007 file_start = sec->PointerToRawData & ~sector_align;
1008 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1009 if (file_size > map_size) file_size = map_size;
1011 /* a few sanity checks */
1012 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1013 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1015 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1016 sec->Name, sec->VirtualAddress, map_size, total_size );
1017 goto error;
1020 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1021 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1023 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1024 sec->Name, ptr + sec->VirtualAddress,
1025 sec->PointerToRawData, (int)pos, file_size, map_size,
1026 sec->Characteristics );
1027 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1028 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1029 FALSE ) != STATUS_SUCCESS)
1031 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1032 goto error;
1035 /* check if the import directory falls inside this section */
1036 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1037 imports->VirtualAddress < sec->VirtualAddress + map_size)
1039 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1040 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1041 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1042 if (end > base)
1043 map_file_into_view( view, shared_fd, base, end - base,
1044 pos + (base - sec->VirtualAddress),
1045 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1046 FALSE );
1048 pos += map_size;
1049 continue;
1052 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1053 sec->Name, ptr + sec->VirtualAddress,
1054 sec->PointerToRawData, sec->SizeOfRawData,
1055 sec->Misc.VirtualSize, sec->Characteristics );
1057 if (!sec->PointerToRawData || !file_size) continue;
1059 /* Note: if the section is not aligned properly map_file_into_view will magically
1060 * fall back to read(), so we don't need to check anything here.
1062 end = file_start + file_size;
1063 if (sec->PointerToRawData >= st.st_size ||
1064 end > ((st.st_size + sector_align) & ~sector_align) ||
1065 end < file_start ||
1066 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1067 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1068 !dup_mapping ) != STATUS_SUCCESS)
1070 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1071 goto error;
1074 if (file_size & page_mask)
1076 end = ROUND_SIZE( 0, file_size );
1077 if (end > map_size) end = map_size;
1078 TRACE_(module)("clearing %p - %p\n",
1079 ptr + sec->VirtualAddress + file_size,
1080 ptr + sec->VirtualAddress + end );
1081 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1086 /* perform base relocation, if necessary */
1088 if (ptr != base &&
1089 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1090 !NtCurrentTeb()->Peb->ImageBaseAddress) )
1092 IMAGE_BASE_RELOCATION *rel, *end;
1093 const IMAGE_DATA_DIRECTORY *relocs;
1095 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1097 WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1098 base, ptr );
1099 status = STATUS_CONFLICTING_ADDRESSES;
1100 goto error;
1103 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1104 base, base + total_size, ptr, ptr + total_size );
1106 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1107 rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1108 end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1109 delta = ptr - base;
1111 while (rel <= end - 1 && rel->SizeOfBlock)
1113 if (rel->VirtualAddress >= total_size)
1115 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1116 status = STATUS_ACCESS_VIOLATION;
1117 goto error;
1119 rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1120 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1121 (USHORT *)(rel + 1), delta );
1122 if (!rel) goto error;
1126 /* set the image protections */
1128 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1130 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1131 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1133 SIZE_T size;
1134 BYTE vprot = VPROT_COMMITTED;
1136 if (sec->Misc.VirtualSize)
1137 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1138 else
1139 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1141 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1142 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
1143 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1145 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1146 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1147 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1148 vprot |= VPROT_EXEC;
1150 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
1153 done:
1154 view->mapping = dup_mapping;
1155 server_leave_uninterrupted_section( &csVirtual, &sigset );
1157 *addr_ptr = ptr;
1158 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1159 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1160 #endif
1161 return STATUS_SUCCESS;
1163 error:
1164 if (view) delete_view( view );
1165 server_leave_uninterrupted_section( &csVirtual, &sigset );
1166 if (dup_mapping) NtClose( dup_mapping );
1167 return status;
1171 /***********************************************************************
1172 * virtual_init
1174 void virtual_init(void)
1176 const char *preload;
1177 #ifndef page_mask
1178 page_size = getpagesize();
1179 page_mask = page_size - 1;
1180 /* Make sure we have a power of 2 */
1181 assert( !(page_size & page_mask) );
1182 page_shift = 0;
1183 while ((1 << page_shift) != page_size) page_shift++;
1184 #endif /* page_mask */
1185 if ((preload = getenv("WINEPRELOADRESERVE")))
1187 unsigned long start, end;
1188 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1190 preload_reserve_start = (void *)start;
1191 preload_reserve_end = (void *)end;
1197 /***********************************************************************
1198 * virtual_init_threading
1200 void virtual_init_threading(void)
1202 use_locks = 1;
1206 /***********************************************************************
1207 * virtual_alloc_thread_stack
1209 NTSTATUS virtual_alloc_thread_stack( void *base, SIZE_T size )
1211 FILE_VIEW *view;
1212 NTSTATUS status;
1213 sigset_t sigset;
1215 server_enter_uninterrupted_section( &csVirtual, &sigset );
1217 if (base) /* already allocated, create a system view */
1219 size = ROUND_SIZE( base, size );
1220 base = ROUND_ADDR( base, page_mask );
1221 if ((status = create_view( &view, base, size,
1222 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED )) != STATUS_SUCCESS)
1223 goto done;
1224 view->flags |= VFLAG_VALLOC | VFLAG_SYSTEM;
1226 else
1228 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1229 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1230 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED )) != STATUS_SUCCESS)
1231 goto done;
1232 view->flags |= VFLAG_VALLOC;
1233 #ifdef VALGRIND_STACK_REGISTER
1234 /* no need to de-register the stack as it's the one of the main thread */
1235 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1236 #endif
1239 /* setup no access guard page */
1240 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1241 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1242 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1244 /* note: limit is lower than base since the stack grows down */
1245 NtCurrentTeb()->DeallocationStack = view->base;
1246 NtCurrentTeb()->Tib.StackBase = (char *)view->base + view->size;
1247 NtCurrentTeb()->Tib.StackLimit = (char *)view->base + 2 * page_size;
1249 done:
1250 server_leave_uninterrupted_section( &csVirtual, &sigset );
1251 return status;
1255 /***********************************************************************
1256 * virtual_clear_thread_stack
1258 * Clear the stack contents before calling the main entry point, some broken apps need that.
1260 void virtual_clear_thread_stack(void)
1262 void *stack = NtCurrentTeb()->Tib.StackLimit;
1263 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1265 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1266 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1270 /***********************************************************************
1271 * VIRTUAL_HandleFault
1273 NTSTATUS VIRTUAL_HandleFault( LPCVOID addr )
1275 FILE_VIEW *view;
1276 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1277 sigset_t sigset;
1279 server_enter_uninterrupted_section( &csVirtual, &sigset );
1280 if ((view = VIRTUAL_FindView( addr )))
1282 void *page = ROUND_ADDR( addr, page_mask );
1283 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1284 if (vprot & VPROT_GUARD)
1286 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1287 ret = STATUS_GUARD_PAGE_VIOLATION;
1290 server_leave_uninterrupted_section( &csVirtual, &sigset );
1291 return ret;
1296 /***********************************************************************
1297 * virtual_handle_stack_fault
1299 * Handle an access fault inside the current thread stack.
1300 * Called from inside a signal handler.
1302 BOOL virtual_handle_stack_fault( void *addr )
1304 FILE_VIEW *view;
1305 BOOL ret = FALSE;
1307 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1308 if ((view = VIRTUAL_FindView( addr )))
1310 void *page = ROUND_ADDR( addr, page_mask );
1311 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1312 if (vprot & VPROT_GUARD)
1314 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1315 if ((char *)page + page_size == NtCurrentTeb()->Tib.StackLimit)
1316 NtCurrentTeb()->Tib.StackLimit = page;
1317 ret = TRUE;
1320 RtlLeaveCriticalSection( &csVirtual );
1321 return ret;
1325 /***********************************************************************
1326 * VIRTUAL_SetForceExec
1328 * Whether to force exec prot on all views.
1330 void VIRTUAL_SetForceExec( BOOL enable )
1332 struct file_view *view;
1333 sigset_t sigset;
1335 server_enter_uninterrupted_section( &csVirtual, &sigset );
1336 if (!force_exec_prot != !enable) /* change all existing views */
1338 force_exec_prot = enable;
1340 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1342 UINT i, count;
1343 int unix_prot;
1344 char *addr = view->base;
1345 BYTE prot = view->prot[0];
1347 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1349 if (view->prot[i] == prot) continue;
1350 unix_prot = VIRTUAL_GetUnixProt( prot );
1351 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1353 TRACE( "%s exec prot for %p-%p\n",
1354 force_exec_prot ? "enabling" : "disabling",
1355 addr, addr + (count << page_shift) - 1 );
1356 mprotect( addr, count << page_shift,
1357 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1359 addr += (count << page_shift);
1360 prot = view->prot[i];
1361 count = 0;
1363 if (count)
1365 unix_prot = VIRTUAL_GetUnixProt( prot );
1366 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1368 TRACE( "%s exec prot for %p-%p\n",
1369 force_exec_prot ? "enabling" : "disabling",
1370 addr, addr + (count << page_shift) - 1 );
1371 mprotect( addr, count << page_shift,
1372 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1377 server_leave_uninterrupted_section( &csVirtual, &sigset );
1381 /***********************************************************************
1382 * VIRTUAL_UseLargeAddressSpace
1384 * Increase the address space size for apps that support it.
1386 void VIRTUAL_UseLargeAddressSpace(void)
1388 /* no large address space on win9x */
1389 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1390 user_space_limit = ADDRESS_SPACE_LIMIT;
1394 /***********************************************************************
1395 * NtAllocateVirtualMemory (NTDLL.@)
1396 * ZwAllocateVirtualMemory (NTDLL.@)
1398 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1399 SIZE_T *size_ptr, ULONG type, ULONG protect )
1401 void *base;
1402 BYTE vprot;
1403 SIZE_T size = *size_ptr;
1404 SIZE_T mask = get_mask( zero_bits );
1405 NTSTATUS status = STATUS_SUCCESS;
1406 struct file_view *view;
1407 sigset_t sigset;
1409 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1411 if (!size) return STATUS_INVALID_PARAMETER;
1413 if (process != NtCurrentProcess())
1415 apc_call_t call;
1416 apc_result_t result;
1418 memset( &call, 0, sizeof(call) );
1420 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1421 call.virtual_alloc.addr = *ret;
1422 call.virtual_alloc.size = *size_ptr;
1423 call.virtual_alloc.zero_bits = zero_bits;
1424 call.virtual_alloc.op_type = type;
1425 call.virtual_alloc.prot = protect;
1426 status = NTDLL_queue_process_apc( process, &call, &result );
1427 if (status != STATUS_SUCCESS) return status;
1429 if (result.virtual_alloc.status == STATUS_SUCCESS)
1431 *ret = result.virtual_alloc.addr;
1432 *size_ptr = result.virtual_alloc.size;
1434 return result.virtual_alloc.status;
1437 /* Round parameters to a page boundary */
1439 if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
1441 if (*ret)
1443 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1444 base = ROUND_ADDR( *ret, mask );
1445 else
1446 base = ROUND_ADDR( *ret, page_mask );
1447 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1449 /* disallow low 64k, wrap-around and kernel space */
1450 if (((char *)base < (char *)0x10000) ||
1451 ((char *)base + size < (char *)base) ||
1452 is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
1453 return STATUS_INVALID_PARAMETER;
1455 else
1457 base = NULL;
1458 size = (size + page_mask) & ~page_mask;
1461 /* Compute the alloc type flags */
1463 if (!(type & MEM_SYSTEM))
1465 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
1466 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1468 WARN("called with wrong alloc type flags (%08x) !\n", type);
1469 return STATUS_INVALID_PARAMETER;
1471 if (type & MEM_WRITE_WATCH)
1473 FIXME("MEM_WRITE_WATCH type not supported\n");
1474 return STATUS_NOT_SUPPORTED;
1477 vprot = VIRTUAL_GetProt( protect );
1478 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1480 /* Reserve the memory */
1482 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1484 if (type & MEM_SYSTEM)
1486 if (type & MEM_IMAGE) vprot |= VPROT_IMAGE;
1487 status = create_view( &view, base, size, vprot | VPROT_COMMITTED );
1488 if (status == STATUS_SUCCESS)
1490 view->flags |= VFLAG_VALLOC | VFLAG_SYSTEM;
1491 base = view->base;
1494 else if ((type & MEM_RESERVE) || !base)
1496 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1497 if (status == STATUS_SUCCESS)
1499 view->flags |= VFLAG_VALLOC;
1500 base = view->base;
1503 else /* commit the pages */
1505 if (!(view = VIRTUAL_FindView( base )) ||
1506 ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
1507 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1510 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1512 if (status == STATUS_SUCCESS)
1514 *ret = base;
1515 *size_ptr = size;
1517 return status;
1521 /***********************************************************************
1522 * NtFreeVirtualMemory (NTDLL.@)
1523 * ZwFreeVirtualMemory (NTDLL.@)
1525 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1527 FILE_VIEW *view;
1528 char *base;
1529 sigset_t sigset;
1530 NTSTATUS status = STATUS_SUCCESS;
1531 LPVOID addr = *addr_ptr;
1532 SIZE_T size = *size_ptr;
1534 TRACE("%p %p %08lx %x\n", process, addr, size, type );
1536 if (process != NtCurrentProcess())
1538 apc_call_t call;
1539 apc_result_t result;
1541 memset( &call, 0, sizeof(call) );
1543 call.virtual_free.type = APC_VIRTUAL_FREE;
1544 call.virtual_free.addr = addr;
1545 call.virtual_free.size = size;
1546 call.virtual_free.op_type = type;
1547 status = NTDLL_queue_process_apc( process, &call, &result );
1548 if (status != STATUS_SUCCESS) return status;
1550 if (result.virtual_free.status == STATUS_SUCCESS)
1552 *addr_ptr = result.virtual_free.addr;
1553 *size_ptr = result.virtual_free.size;
1555 return result.virtual_free.status;
1558 /* Fix the parameters */
1560 size = ROUND_SIZE( addr, size );
1561 base = ROUND_ADDR( addr, page_mask );
1563 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
1564 if (!base && !(type & MEM_SYSTEM)) return STATUS_INVALID_PARAMETER;
1566 server_enter_uninterrupted_section( &csVirtual, &sigset );
1568 if (!(view = VIRTUAL_FindView( base )) ||
1569 (base + size > (char *)view->base + view->size) ||
1570 !(view->flags & VFLAG_VALLOC))
1572 status = STATUS_INVALID_PARAMETER;
1574 else if (type & MEM_SYSTEM)
1576 /* return the values that the caller should use to unmap the area */
1577 *addr_ptr = view->base;
1578 if (!wine_mmap_is_in_reserved_area( view->base, view->size )) *size_ptr = view->size;
1579 else *size_ptr = 0; /* make sure we don't munmap anything from a reserved area */
1580 view->flags |= VFLAG_SYSTEM;
1581 delete_view( view );
1583 else if (type == MEM_RELEASE)
1585 /* Free the pages */
1587 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1588 else
1590 delete_view( view );
1591 *addr_ptr = base;
1592 *size_ptr = size;
1595 else if (type == MEM_DECOMMIT)
1597 status = decommit_pages( view, base - (char *)view->base, size );
1598 if (status == STATUS_SUCCESS)
1600 *addr_ptr = base;
1601 *size_ptr = size;
1604 else
1606 WARN("called with wrong free type flags (%08x) !\n", type);
1607 status = STATUS_INVALID_PARAMETER;
1610 server_leave_uninterrupted_section( &csVirtual, &sigset );
1611 return status;
1615 /***********************************************************************
1616 * NtProtectVirtualMemory (NTDLL.@)
1617 * ZwProtectVirtualMemory (NTDLL.@)
1619 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1620 ULONG new_prot, ULONG *old_prot )
1622 FILE_VIEW *view;
1623 sigset_t sigset;
1624 NTSTATUS status = STATUS_SUCCESS;
1625 char *base;
1626 UINT i;
1627 BYTE vprot, *p;
1628 ULONG prot;
1629 SIZE_T size = *size_ptr;
1630 LPVOID addr = *addr_ptr;
1632 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
1634 if (process != NtCurrentProcess())
1636 apc_call_t call;
1637 apc_result_t result;
1639 memset( &call, 0, sizeof(call) );
1641 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
1642 call.virtual_protect.addr = addr;
1643 call.virtual_protect.size = size;
1644 call.virtual_protect.prot = new_prot;
1645 status = NTDLL_queue_process_apc( process, &call, &result );
1646 if (status != STATUS_SUCCESS) return status;
1648 if (result.virtual_protect.status == STATUS_SUCCESS)
1650 *addr_ptr = result.virtual_protect.addr;
1651 *size_ptr = result.virtual_protect.size;
1652 if (old_prot) *old_prot = result.virtual_protect.prot;
1654 return result.virtual_protect.status;
1657 /* Fix the parameters */
1659 size = ROUND_SIZE( addr, size );
1660 base = ROUND_ADDR( addr, page_mask );
1662 server_enter_uninterrupted_section( &csVirtual, &sigset );
1664 if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1666 status = STATUS_INVALID_PARAMETER;
1668 else
1670 /* Make sure all the pages are committed */
1672 p = view->prot + ((base - (char *)view->base) >> page_shift);
1673 prot = VIRTUAL_GetWin32Prot( *p );
1674 for (i = size >> page_shift; i; i--, p++)
1676 if (!(*p & VPROT_COMMITTED))
1678 status = STATUS_NOT_COMMITTED;
1679 break;
1682 if (!i)
1684 if (old_prot) *old_prot = prot;
1685 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1686 if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1689 server_leave_uninterrupted_section( &csVirtual, &sigset );
1691 if (status == STATUS_SUCCESS)
1693 *addr_ptr = base;
1694 *size_ptr = size;
1696 return status;
1699 #define UNIMPLEMENTED_INFO_CLASS(c) \
1700 case c: \
1701 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
1702 return STATUS_INVALID_INFO_CLASS
1704 /***********************************************************************
1705 * NtQueryVirtualMemory (NTDLL.@)
1706 * ZwQueryVirtualMemory (NTDLL.@)
1708 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1709 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1710 SIZE_T len, SIZE_T *res_len )
1712 FILE_VIEW *view;
1713 char *base, *alloc_base = 0;
1714 struct list *ptr;
1715 SIZE_T size = 0;
1716 MEMORY_BASIC_INFORMATION *info = buffer;
1717 sigset_t sigset;
1719 if (info_class != MemoryBasicInformation)
1721 switch(info_class)
1723 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
1724 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
1725 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
1727 default:
1728 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
1729 process, addr, info_class, buffer, len, res_len);
1730 return STATUS_INVALID_INFO_CLASS;
1733 if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1734 return STATUS_WORKING_SET_LIMIT_RANGE;
1736 if (process != NtCurrentProcess())
1738 NTSTATUS status;
1739 apc_call_t call;
1740 apc_result_t result;
1742 memset( &call, 0, sizeof(call) );
1744 call.virtual_query.type = APC_VIRTUAL_QUERY;
1745 call.virtual_query.addr = addr;
1746 status = NTDLL_queue_process_apc( process, &call, &result );
1747 if (status != STATUS_SUCCESS) return status;
1749 if (result.virtual_query.status == STATUS_SUCCESS)
1751 info->BaseAddress = result.virtual_query.base;
1752 info->AllocationBase = result.virtual_query.alloc_base;
1753 info->RegionSize = result.virtual_query.size;
1754 info->State = result.virtual_query.state;
1755 info->Protect = result.virtual_query.prot;
1756 info->AllocationProtect = result.virtual_query.alloc_prot;
1757 info->Type = result.virtual_query.alloc_type;
1758 if (res_len) *res_len = sizeof(*info);
1760 return result.virtual_query.status;
1763 base = ROUND_ADDR( addr, page_mask );
1765 /* Find the view containing the address */
1767 server_enter_uninterrupted_section( &csVirtual, &sigset );
1768 ptr = list_head( &views_list );
1769 for (;;)
1771 if (!ptr)
1773 /* make the address space end at the user limit, except if
1774 * the last view was mapped beyond that */
1775 if (alloc_base <= (char *)user_space_limit)
1777 if (user_space_limit && base >= (char *)user_space_limit)
1779 server_leave_uninterrupted_section( &csVirtual, &sigset );
1780 return STATUS_WORKING_SET_LIMIT_RANGE;
1782 size = (char *)user_space_limit - alloc_base;
1784 else size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1785 view = NULL;
1786 break;
1788 view = LIST_ENTRY( ptr, struct file_view, entry );
1789 if ((char *)view->base > base)
1791 size = (char *)view->base - alloc_base;
1792 view = NULL;
1793 break;
1795 if ((char *)view->base + view->size > base)
1797 alloc_base = view->base;
1798 size = view->size;
1799 break;
1801 alloc_base = (char *)view->base + view->size;
1802 ptr = list_next( &views_list, ptr );
1805 /* Fill the info structure */
1807 if (!view)
1809 info->State = MEM_FREE;
1810 info->Protect = PAGE_NOACCESS;
1811 info->AllocationBase = 0;
1812 info->AllocationProtect = 0;
1813 info->Type = 0;
1815 else
1817 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1818 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
1819 info->Protect = VIRTUAL_GetWin32Prot( vprot );
1820 info->AllocationBase = alloc_base;
1821 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
1822 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1823 else if (view->flags & VFLAG_VALLOC) info->Type = MEM_PRIVATE;
1824 else info->Type = MEM_MAPPED;
1825 for (size = base - alloc_base; size < view->size; size += page_size)
1826 if (view->prot[size >> page_shift] != vprot) break;
1828 server_leave_uninterrupted_section( &csVirtual, &sigset );
1830 info->BaseAddress = base;
1831 info->RegionSize = size - (base - alloc_base);
1832 if (res_len) *res_len = sizeof(*info);
1833 return STATUS_SUCCESS;
1837 /***********************************************************************
1838 * NtLockVirtualMemory (NTDLL.@)
1839 * ZwLockVirtualMemory (NTDLL.@)
1841 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1843 NTSTATUS status = STATUS_SUCCESS;
1845 if (process != NtCurrentProcess())
1847 apc_call_t call;
1848 apc_result_t result;
1850 memset( &call, 0, sizeof(call) );
1852 call.virtual_lock.type = APC_VIRTUAL_LOCK;
1853 call.virtual_lock.addr = *addr;
1854 call.virtual_lock.size = *size;
1855 status = NTDLL_queue_process_apc( process, &call, &result );
1856 if (status != STATUS_SUCCESS) return status;
1858 if (result.virtual_lock.status == STATUS_SUCCESS)
1860 *addr = result.virtual_lock.addr;
1861 *size = result.virtual_lock.size;
1863 return result.virtual_lock.status;
1866 *size = ROUND_SIZE( *addr, *size );
1867 *addr = ROUND_ADDR( *addr, page_mask );
1869 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
1870 return status;
1874 /***********************************************************************
1875 * NtUnlockVirtualMemory (NTDLL.@)
1876 * ZwUnlockVirtualMemory (NTDLL.@)
1878 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1880 NTSTATUS status = STATUS_SUCCESS;
1882 if (process != NtCurrentProcess())
1884 apc_call_t call;
1885 apc_result_t result;
1887 memset( &call, 0, sizeof(call) );
1889 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
1890 call.virtual_unlock.addr = *addr;
1891 call.virtual_unlock.size = *size;
1892 status = NTDLL_queue_process_apc( process, &call, &result );
1893 if (status != STATUS_SUCCESS) return status;
1895 if (result.virtual_unlock.status == STATUS_SUCCESS)
1897 *addr = result.virtual_unlock.addr;
1898 *size = result.virtual_unlock.size;
1900 return result.virtual_unlock.status;
1903 *size = ROUND_SIZE( *addr, *size );
1904 *addr = ROUND_ADDR( *addr, page_mask );
1906 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
1907 return status;
1911 /***********************************************************************
1912 * NtCreateSection (NTDLL.@)
1913 * ZwCreateSection (NTDLL.@)
1915 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1916 const LARGE_INTEGER *size, ULONG protect,
1917 ULONG sec_flags, HANDLE file )
1919 NTSTATUS ret;
1920 BYTE vprot;
1921 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
1922 struct security_descriptor *sd = NULL;
1923 struct object_attributes objattr;
1925 /* Check parameters */
1927 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1929 objattr.rootdir = attr ? attr->RootDirectory : 0;
1930 objattr.sd_len = 0;
1931 objattr.name_len = len;
1932 if (attr)
1934 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
1935 if (ret != STATUS_SUCCESS) return ret;
1938 vprot = VIRTUAL_GetProt( protect );
1939 if (sec_flags & SEC_RESERVE)
1941 if (file) return STATUS_INVALID_PARAMETER;
1943 else vprot |= VPROT_COMMITTED;
1944 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1945 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
1947 /* Create the server object */
1949 SERVER_START_REQ( create_mapping )
1951 req->access = access;
1952 req->attributes = (attr) ? attr->Attributes : 0;
1953 req->file_handle = file;
1954 req->size = size ? size->QuadPart : 0;
1955 req->protect = vprot;
1956 wine_server_add_data( req, &objattr, sizeof(objattr) );
1957 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
1958 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
1959 ret = wine_server_call( req );
1960 *handle = reply->handle;
1962 SERVER_END_REQ;
1964 NTDLL_free_struct_sd( sd );
1966 return ret;
1970 /***********************************************************************
1971 * NtOpenSection (NTDLL.@)
1972 * ZwOpenSection (NTDLL.@)
1974 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1976 NTSTATUS ret;
1977 DWORD len = attr->ObjectName->Length;
1979 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1981 SERVER_START_REQ( open_mapping )
1983 req->access = access;
1984 req->attributes = attr->Attributes;
1985 req->rootdir = attr->RootDirectory;
1986 wine_server_add_data( req, attr->ObjectName->Buffer, len );
1987 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
1989 SERVER_END_REQ;
1990 return ret;
1994 /***********************************************************************
1995 * NtMapViewOfSection (NTDLL.@)
1996 * ZwMapViewOfSection (NTDLL.@)
1998 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
1999 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2000 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2002 NTSTATUS res;
2003 ULONGLONG full_size;
2004 SIZE_T size = 0;
2005 SIZE_T mask = get_mask( zero_bits );
2006 int unix_handle = -1, needs_close;
2007 int prot;
2008 void *base;
2009 struct file_view *view;
2010 DWORD header_size;
2011 HANDLE dup_mapping, shared_file;
2012 LARGE_INTEGER offset;
2013 sigset_t sigset;
2015 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2017 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2018 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, size, protect );
2020 /* Check parameters */
2022 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2023 return STATUS_INVALID_PARAMETER;
2025 if (process != NtCurrentProcess())
2027 apc_call_t call;
2028 apc_result_t result;
2030 memset( &call, 0, sizeof(call) );
2032 call.map_view.type = APC_MAP_VIEW;
2033 call.map_view.handle = handle;
2034 call.map_view.addr = *addr_ptr;
2035 call.map_view.size = *size_ptr;
2036 call.map_view.offset = offset.QuadPart;
2037 call.map_view.zero_bits = zero_bits;
2038 call.map_view.alloc_type = alloc_type;
2039 call.map_view.prot = protect;
2040 res = NTDLL_queue_process_apc( process, &call, &result );
2041 if (res != STATUS_SUCCESS) return res;
2043 if (result.map_view.status == STATUS_SUCCESS)
2045 *addr_ptr = result.map_view.addr;
2046 *size_ptr = result.map_view.size;
2048 return result.map_view.status;
2051 SERVER_START_REQ( get_mapping_info )
2053 req->handle = handle;
2054 res = wine_server_call( req );
2055 prot = reply->protect;
2056 base = reply->base;
2057 full_size = reply->size;
2058 header_size = reply->header_size;
2059 dup_mapping = reply->mapping;
2060 shared_file = reply->shared_file;
2062 SERVER_END_REQ;
2063 if (res) return res;
2065 size = full_size;
2066 if (sizeof(size) < sizeof(full_size) && (size != full_size))
2067 ERR( "Sizes larger than 4Gb (%x%08x) not supported on this platform\n",
2068 (DWORD)(full_size >> 32), (DWORD)full_size );
2070 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2072 if (prot & VPROT_IMAGE)
2074 if (shared_file)
2076 int shared_fd, shared_needs_close;
2078 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2079 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2080 res = map_image( handle, unix_handle, base, size, mask, header_size,
2081 shared_fd, dup_mapping, addr_ptr );
2082 if (shared_needs_close) close( shared_fd );
2083 NtClose( shared_file );
2085 else
2087 res = map_image( handle, unix_handle, base, size, mask, header_size,
2088 -1, dup_mapping, addr_ptr );
2090 if (needs_close) close( unix_handle );
2091 if (!res) *size_ptr = size;
2092 return res;
2095 if ((offset.QuadPart >= size) || (*size_ptr > size - offset.QuadPart))
2097 res = STATUS_INVALID_PARAMETER;
2098 goto done;
2100 if (*size_ptr) size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2101 else size = size - offset.QuadPart;
2103 switch(protect)
2105 case PAGE_NOACCESS:
2106 break;
2107 case PAGE_READWRITE:
2108 case PAGE_EXECUTE_READWRITE:
2109 if (!(prot & VPROT_WRITE))
2111 res = STATUS_INVALID_PARAMETER;
2112 goto done;
2114 /* fall through */
2115 case PAGE_READONLY:
2116 case PAGE_WRITECOPY:
2117 case PAGE_EXECUTE:
2118 case PAGE_EXECUTE_READ:
2119 case PAGE_EXECUTE_WRITECOPY:
2120 if (prot & VPROT_READ) break;
2121 /* fall through */
2122 default:
2123 res = STATUS_INVALID_PARAMETER;
2124 goto done;
2127 /* FIXME: If a mapping is created with SEC_RESERVE and a process,
2128 * which has a view of this mapping commits some pages, they will
2129 * appear committed in all other processes, which have the same
2130 * view created. Since we don't support this yet, we create the
2131 * whole mapping committed.
2133 prot |= VPROT_COMMITTED;
2135 /* Reserve a properly aligned area */
2137 server_enter_uninterrupted_section( &csVirtual, &sigset );
2139 res = map_view( &view, *addr_ptr, size, mask, FALSE, prot );
2140 if (res)
2142 server_leave_uninterrupted_section( &csVirtual, &sigset );
2143 goto done;
2146 /* Map the file */
2148 TRACE("handle=%p size=%lx offset=%x%08x\n",
2149 handle, size, offset.u.HighPart, offset.u.LowPart );
2151 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, prot, !dup_mapping );
2152 if (res == STATUS_SUCCESS)
2154 *addr_ptr = view->base;
2155 *size_ptr = size;
2156 view->mapping = dup_mapping;
2157 dup_mapping = 0; /* don't close it */
2159 else
2161 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2162 view->base, size, offset.u.HighPart, offset.u.LowPart );
2163 delete_view( view );
2166 server_leave_uninterrupted_section( &csVirtual, &sigset );
2168 done:
2169 if (dup_mapping) NtClose( dup_mapping );
2170 if (needs_close) close( unix_handle );
2171 return res;
2175 /***********************************************************************
2176 * NtUnmapViewOfSection (NTDLL.@)
2177 * ZwUnmapViewOfSection (NTDLL.@)
2179 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2181 FILE_VIEW *view;
2182 NTSTATUS status = STATUS_INVALID_PARAMETER;
2183 sigset_t sigset;
2184 void *base = ROUND_ADDR( addr, page_mask );
2186 if (process != NtCurrentProcess())
2188 apc_call_t call;
2189 apc_result_t result;
2191 memset( &call, 0, sizeof(call) );
2193 call.unmap_view.type = APC_UNMAP_VIEW;
2194 call.unmap_view.addr = addr;
2195 status = NTDLL_queue_process_apc( process, &call, &result );
2196 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2197 return status;
2200 server_enter_uninterrupted_section( &csVirtual, &sigset );
2201 if ((view = VIRTUAL_FindView( base )) && (base == view->base))
2203 delete_view( view );
2204 status = STATUS_SUCCESS;
2206 server_leave_uninterrupted_section( &csVirtual, &sigset );
2207 return status;
2211 /***********************************************************************
2212 * NtFlushVirtualMemory (NTDLL.@)
2213 * ZwFlushVirtualMemory (NTDLL.@)
2215 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2216 SIZE_T *size_ptr, ULONG unknown )
2218 FILE_VIEW *view;
2219 NTSTATUS status = STATUS_SUCCESS;
2220 sigset_t sigset;
2221 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2223 if (process != NtCurrentProcess())
2225 apc_call_t call;
2226 apc_result_t result;
2228 memset( &call, 0, sizeof(call) );
2230 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2231 call.virtual_flush.addr = addr;
2232 call.virtual_flush.size = *size_ptr;
2233 status = NTDLL_queue_process_apc( process, &call, &result );
2234 if (status != STATUS_SUCCESS) return status;
2236 if (result.virtual_flush.status == STATUS_SUCCESS)
2238 *addr_ptr = result.virtual_flush.addr;
2239 *size_ptr = result.virtual_flush.size;
2241 return result.virtual_flush.status;
2244 server_enter_uninterrupted_section( &csVirtual, &sigset );
2245 if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
2246 else
2248 if (!*size_ptr) *size_ptr = view->size;
2249 *addr_ptr = addr;
2250 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2252 server_leave_uninterrupted_section( &csVirtual, &sigset );
2253 return status;
2257 /***********************************************************************
2258 * NtReadVirtualMemory (NTDLL.@)
2259 * ZwReadVirtualMemory (NTDLL.@)
2261 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2262 SIZE_T size, SIZE_T *bytes_read )
2264 NTSTATUS status;
2266 SERVER_START_REQ( read_process_memory )
2268 req->handle = process;
2269 req->addr = (void *)addr;
2270 wine_server_set_reply( req, buffer, size );
2271 if ((status = wine_server_call( req ))) size = 0;
2273 SERVER_END_REQ;
2274 if (bytes_read) *bytes_read = size;
2275 return status;
2279 /***********************************************************************
2280 * NtWriteVirtualMemory (NTDLL.@)
2281 * ZwWriteVirtualMemory (NTDLL.@)
2283 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2284 SIZE_T size, SIZE_T *bytes_written )
2286 NTSTATUS status;
2288 SERVER_START_REQ( write_process_memory )
2290 req->handle = process;
2291 req->addr = addr;
2292 wine_server_add_data( req, buffer, size );
2293 if ((status = wine_server_call( req ))) size = 0;
2295 SERVER_END_REQ;
2296 if (bytes_written) *bytes_written = size;
2297 return status;
2301 /***********************************************************************
2302 * NtAreMappedFilesTheSame (NTDLL.@)
2303 * ZwAreMappedFilesTheSame (NTDLL.@)
2305 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2307 TRACE("%p %p\n", addr1, addr2);
2309 return STATUS_NOT_SAME_DEVICE;