winex11: Introduce a function to retrieve the glx drawable and have
[wine.git] / dlls / ntdll / virtual.c
blob5e7a15d80cb995e9cfa8ceb55ffca6c685a06afe
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
45 #define NONAMELESSUNION
46 #define NONAMELESSSTRUCT
47 #include "ntstatus.h"
48 #define WIN32_NO_STATUS
49 #include "windef.h"
50 #include "winternl.h"
51 #include "winioctl.h"
52 #include "wine/library.h"
53 #include "wine/server.h"
54 #include "wine/list.h"
55 #include "wine/debug.h"
56 #include "ntdll_misc.h"
58 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
59 WINE_DECLARE_DEBUG_CHANNEL(module);
61 #ifndef MS_SYNC
62 #define MS_SYNC 0
63 #endif
65 #ifndef MAP_NORESERVE
66 #define MAP_NORESERVE 0
67 #endif
69 /* File view */
70 typedef struct file_view
72 struct list entry; /* Entry in global view list */
73 void *base; /* Base address */
74 size_t size; /* Size in bytes */
75 HANDLE mapping; /* Handle to the file mapping */
76 BYTE flags; /* Allocation flags (VFLAG_*) */
77 BYTE protect; /* Protection for all pages at allocation time */
78 BYTE prot[1]; /* Protection byte for each page */
79 } FILE_VIEW;
81 /* Per-view flags */
82 #define VFLAG_SYSTEM 0x01 /* system view (underlying mmap not under our control) */
83 #define VFLAG_VALLOC 0x02 /* allocated by VirtualAlloc */
85 /* Conversion from VPROT_* to Win32 flags */
86 static const BYTE VIRTUAL_Win32Flags[16] =
88 PAGE_NOACCESS, /* 0 */
89 PAGE_READONLY, /* READ */
90 PAGE_READWRITE, /* WRITE */
91 PAGE_READWRITE, /* READ | WRITE */
92 PAGE_EXECUTE, /* EXEC */
93 PAGE_EXECUTE_READ, /* READ | EXEC */
94 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
95 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
96 PAGE_WRITECOPY, /* WRITECOPY */
97 PAGE_WRITECOPY, /* READ | WRITECOPY */
98 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
99 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
100 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
101 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
102 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
103 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
106 static struct list views_list = LIST_INIT(views_list);
108 static RTL_CRITICAL_SECTION csVirtual;
109 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
111 0, 0, &csVirtual,
112 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
113 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
115 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
117 #ifdef __i386__
118 /* These are always the same on an i386, and it will be faster this way */
119 # define page_mask 0xfff
120 # define page_shift 12
121 # define page_size 0x1000
122 /* Note: these are Windows limits, you cannot change them. */
123 # define ADDRESS_SPACE_LIMIT ((void *)0xc0000000) /* top of the total available address space */
124 # define USER_SPACE_LIMIT ((void *)0x7fff0000) /* top of the user address space */
125 #else
126 static UINT page_shift;
127 static UINT page_size;
128 static UINT_PTR page_mask;
129 # define ADDRESS_SPACE_LIMIT 0 /* no limit needed on other platforms */
130 # define USER_SPACE_LIMIT 0 /* no limit needed on other platforms */
131 #endif /* __i386__ */
132 static const UINT_PTR granularity_mask = 0xffff; /* Allocation granularity (usually 64k) */
134 #define ROUND_ADDR(addr,mask) \
135 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
137 #define ROUND_SIZE(addr,size) \
138 (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
140 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
141 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
143 static void *user_space_limit = USER_SPACE_LIMIT;
146 /***********************************************************************
147 * VIRTUAL_GetProtStr
149 static const char *VIRTUAL_GetProtStr( BYTE prot )
151 static char buffer[6];
152 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
153 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
154 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
155 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
156 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
157 buffer[5] = 0;
158 return buffer;
162 /***********************************************************************
163 * VIRTUAL_DumpView
165 static void VIRTUAL_DumpView( FILE_VIEW *view )
167 UINT i, count;
168 char *addr = view->base;
169 BYTE prot = view->prot[0];
171 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
172 if (view->flags & VFLAG_SYSTEM)
173 TRACE( " (system)\n" );
174 else if (view->flags & VFLAG_VALLOC)
175 TRACE( " (valloc)\n" );
176 else if (view->mapping)
177 TRACE( " %p\n", view->mapping );
178 else
179 TRACE( " (anonymous)\n");
181 for (count = i = 1; i < view->size >> page_shift; i++, count++)
183 if (view->prot[i] == prot) continue;
184 TRACE( " %p - %p %s\n",
185 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
186 addr += (count << page_shift);
187 prot = view->prot[i];
188 count = 0;
190 if (count)
191 TRACE( " %p - %p %s\n",
192 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
196 /***********************************************************************
197 * VIRTUAL_Dump
199 #if WINE_VM_DEBUG
200 static void VIRTUAL_Dump(void)
202 struct file_view *view;
204 TRACE( "Dump of all virtual memory views:\n" );
205 RtlEnterCriticalSection(&csVirtual);
206 LIST_FOR_EACH_ENTRY( view, &views_list, FILE_VIEW, entry )
208 VIRTUAL_DumpView( view );
210 RtlLeaveCriticalSection(&csVirtual);
212 #endif
215 /***********************************************************************
216 * VIRTUAL_FindView
218 * Find the view containing a given address. The csVirtual section must be held by caller.
220 * PARAMS
221 * addr [I] Address
223 * RETURNS
224 * View: Success
225 * NULL: Failure
227 static struct file_view *VIRTUAL_FindView( const void *addr )
229 struct file_view *view;
231 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
233 if (view->base > addr) break;
234 if ((const char*)view->base + view->size > (const char*)addr) return view;
236 return NULL;
240 /***********************************************************************
241 * find_view_range
243 * Find the first view overlapping at least part of the specified range.
244 * The csVirtual section must be held by caller.
246 static struct file_view *find_view_range( const void *addr, size_t size )
248 struct file_view *view;
250 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
252 if ((const char *)view->base >= (const char *)addr + size) break;
253 if ((const char *)view->base + view->size > (const char *)addr) return view;
255 return NULL;
259 /***********************************************************************
260 * add_reserved_area
262 * Add a reserved area to the list maintained by libwine.
263 * The csVirtual section must be held by caller.
265 static void add_reserved_area( void *addr, size_t size )
267 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
269 if (addr < user_space_limit)
271 /* unmap the part of the area that is below the limit */
272 assert( (char *)addr + size > (char *)user_space_limit );
273 munmap( addr, (char *)user_space_limit - (char *)addr );
274 size -= (char *)user_space_limit - (char *)addr;
275 addr = user_space_limit;
277 /* blow away existing mappings */
278 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
279 wine_mmap_add_reserved_area( addr, size );
283 /***********************************************************************
284 * remove_reserved_area
286 * Remove a reserved area from the list maintained by libwine.
287 * The csVirtual section must be held by caller.
289 static void remove_reserved_area( void *addr, size_t size )
291 struct file_view *view;
293 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
295 if ((char *)view->base >= (char *)addr + size) break;
296 if ((char *)view->base + view->size <= (char *)addr) continue;
297 /* now we have an overlapping view */
298 if (view->base > addr)
300 wine_mmap_remove_reserved_area( addr, (char *)view->base - (char *)addr, TRUE );
301 size -= (char *)view->base - (char *)addr;
302 addr = view->base;
304 if ((char *)view->base + view->size >= (char *)addr + size)
306 /* view covers all the remaining area */
307 wine_mmap_remove_reserved_area( addr, size, FALSE );
308 size = 0;
309 break;
311 else /* view covers only part of the area */
313 wine_mmap_remove_reserved_area( addr, (char *)view->base + view->size - (char *)addr, FALSE );
314 size -= (char *)view->base + view->size - (char *)addr;
315 addr = (char *)view->base + view->size;
318 /* remove remaining space */
319 if (size) wine_mmap_remove_reserved_area( addr, size, TRUE );
323 /***********************************************************************
324 * is_beyond_limit
326 * Check if an address range goes beyond a given limit.
328 static inline int is_beyond_limit( void *addr, size_t size, void *limit )
330 return (limit && (addr >= limit || (char *)addr + size > (char *)limit));
334 /***********************************************************************
335 * unmap_area
337 * Unmap an area, or simply replace it by an empty mapping if it is
338 * in a reserved area. The csVirtual section must be held by caller.
340 static inline void unmap_area( void *addr, size_t size )
342 if (wine_mmap_is_in_reserved_area( addr, size ))
343 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
344 else if (is_beyond_limit( addr, size, user_space_limit ))
345 add_reserved_area( addr, size );
346 else
347 munmap( addr, size );
351 /***********************************************************************
352 * delete_view
354 * Deletes a view. The csVirtual section must be held by caller.
356 static void delete_view( struct file_view *view ) /* [in] View */
358 if (!(view->flags & VFLAG_SYSTEM)) unmap_area( view->base, view->size );
359 list_remove( &view->entry );
360 if (view->mapping) NtClose( view->mapping );
361 free( view );
365 /***********************************************************************
366 * create_view
368 * Create a view. The csVirtual section must be held by caller.
370 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, BYTE vprot )
372 struct file_view *view;
373 struct list *ptr;
375 assert( !((UINT_PTR)base & page_mask) );
376 assert( !(size & page_mask) );
378 /* Create the view structure */
380 if (!(view = malloc( sizeof(*view) + (size >> page_shift) - 1 ))) return STATUS_NO_MEMORY;
382 view->base = base;
383 view->size = size;
384 view->flags = 0;
385 view->mapping = 0;
386 view->protect = vprot;
387 memset( view->prot, vprot & ~VPROT_IMAGE, size >> page_shift );
389 /* Insert it in the linked list */
391 LIST_FOR_EACH( ptr, &views_list )
393 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
394 if (next->base > base) break;
396 list_add_before( ptr, &view->entry );
398 /* Check for overlapping views. This can happen if the previous view
399 * was a system view that got unmapped behind our back. In that case
400 * we recover by simply deleting it. */
402 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
404 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
405 if ((char *)prev->base + prev->size > (char *)base)
407 TRACE( "overlapping prev view %p-%p for %p-%p\n",
408 prev->base, (char *)prev->base + prev->size,
409 base, (char *)base + view->size );
410 assert( prev->flags & VFLAG_SYSTEM );
411 delete_view( prev );
414 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
416 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
417 if ((char *)base + view->size > (char *)next->base)
419 TRACE( "overlapping next view %p-%p for %p-%p\n",
420 next->base, (char *)next->base + next->size,
421 base, (char *)base + view->size );
422 assert( next->flags & VFLAG_SYSTEM );
423 delete_view( next );
427 *view_ret = view;
428 VIRTUAL_DEBUG_DUMP_VIEW( view );
429 return STATUS_SUCCESS;
433 /***********************************************************************
434 * VIRTUAL_GetUnixProt
436 * Convert page protections to protection for mmap/mprotect.
438 static int VIRTUAL_GetUnixProt( BYTE vprot )
440 int prot = 0;
441 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
443 if (vprot & VPROT_READ) prot |= PROT_READ;
444 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
445 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
446 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
448 if (!prot) prot = PROT_NONE;
449 return prot;
453 /***********************************************************************
454 * VIRTUAL_GetWin32Prot
456 * Convert page protections to Win32 flags.
458 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
460 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
461 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
462 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
463 return ret;
467 /***********************************************************************
468 * VIRTUAL_GetProt
470 * Build page protections from Win32 flags.
472 * PARAMS
473 * protect [I] Win32 protection flags
475 * RETURNS
476 * Value of page protection flags
478 static BYTE VIRTUAL_GetProt( DWORD protect )
480 BYTE vprot;
482 switch(protect & 0xff)
484 case PAGE_READONLY:
485 vprot = VPROT_READ;
486 break;
487 case PAGE_READWRITE:
488 vprot = VPROT_READ | VPROT_WRITE;
489 break;
490 case PAGE_WRITECOPY:
491 /* MSDN CreateFileMapping() states that if PAGE_WRITECOPY is given,
492 * that the hFile must have been opened with GENERIC_READ and
493 * GENERIC_WRITE access. This is WRONG as tests show that you
494 * only need GENERIC_READ access (at least for Win9x,
495 * FIXME: what about NT?). Thus, we don't put VPROT_WRITE in
496 * PAGE_WRITECOPY and PAGE_EXECUTE_WRITECOPY.
498 vprot = VPROT_READ | VPROT_WRITECOPY;
499 break;
500 case PAGE_EXECUTE:
501 vprot = VPROT_EXEC;
502 break;
503 case PAGE_EXECUTE_READ:
504 vprot = VPROT_EXEC | VPROT_READ;
505 break;
506 case PAGE_EXECUTE_READWRITE:
507 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
508 break;
509 case PAGE_EXECUTE_WRITECOPY:
510 /* See comment for PAGE_WRITECOPY above */
511 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
512 break;
513 case PAGE_NOACCESS:
514 default:
515 vprot = 0;
516 break;
518 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
519 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
520 return vprot;
524 /***********************************************************************
525 * VIRTUAL_SetProt
527 * Change the protection of a range of pages.
529 * RETURNS
530 * TRUE: Success
531 * FALSE: Failure
533 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
534 void *base, /* [in] Starting address */
535 size_t size, /* [in] Size in bytes */
536 BYTE vprot ) /* [in] Protections to use */
538 TRACE("%p-%p %s\n",
539 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
541 if (mprotect( base, size, VIRTUAL_GetUnixProt(vprot) ))
542 return FALSE; /* FIXME: last error */
544 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
545 vprot, size >> page_shift );
546 VIRTUAL_DEBUG_DUMP_VIEW( view );
547 return TRUE;
551 /***********************************************************************
552 * unmap_extra_space
554 * Release the extra memory while keeping the range starting on the granularity boundary.
556 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
558 if ((ULONG_PTR)ptr & mask)
560 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
561 munmap( ptr, extra );
562 ptr = (char *)ptr + extra;
563 total_size -= extra;
565 if (total_size > wanted_size)
566 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
567 return ptr;
571 /***********************************************************************
572 * map_view
574 * Create a view and mmap the corresponding memory area.
575 * The csVirtual section must be held by caller.
577 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, BYTE vprot )
579 void *ptr;
580 NTSTATUS status;
582 if (base)
584 if (is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
585 return STATUS_WORKING_SET_LIMIT_RANGE;
587 switch (wine_mmap_is_in_reserved_area( base, size ))
589 case -1: /* partially in a reserved area */
590 return STATUS_CONFLICTING_ADDRESSES;
592 case 0: /* not in a reserved area, do a normal allocation */
593 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
595 if (errno == ENOMEM) return STATUS_NO_MEMORY;
596 return STATUS_INVALID_PARAMETER;
598 if (ptr != base)
600 /* We couldn't get the address we wanted */
601 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
602 else munmap( ptr, size );
603 return STATUS_CONFLICTING_ADDRESSES;
605 break;
607 default:
608 case 1: /* in a reserved area, make sure the address is available */
609 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
610 /* replace the reserved area by our mapping */
611 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
612 return STATUS_INVALID_PARAMETER;
613 break;
616 else
618 size_t view_size = size + granularity_mask + 1;
620 for (;;)
622 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
624 if (errno == ENOMEM) return STATUS_NO_MEMORY;
625 return STATUS_INVALID_PARAMETER;
627 /* if we got something beyond the user limit, unmap it and retry */
628 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
629 else break;
631 ptr = unmap_extra_space( ptr, view_size, size, granularity_mask );
634 status = create_view( view_ret, ptr, size, vprot );
635 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
636 return status;
640 /***********************************************************************
641 * unaligned_mmap
643 * Linux kernels before 2.4.x can support non page-aligned offsets, as
644 * long as the offset is aligned to the filesystem block size. This is
645 * a big performance gain so we want to take advantage of it.
647 * However, when we use 64-bit file support this doesn't work because
648 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
649 * in that it rounds unaligned offsets down to a page boundary. For
650 * these reasons we do a direct system call here.
652 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
653 unsigned int flags, int fd, off_t offset )
655 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
656 if (!(offset >> 32) && (offset & page_mask))
658 int ret;
660 struct
662 void *addr;
663 unsigned int length;
664 unsigned int prot;
665 unsigned int flags;
666 unsigned int fd;
667 unsigned int offset;
668 } args;
670 args.addr = addr;
671 args.length = length;
672 args.prot = prot;
673 args.flags = flags;
674 args.fd = fd;
675 args.offset = offset;
677 __asm__ __volatile__("push %%ebx\n\t"
678 "movl %2,%%ebx\n\t"
679 "int $0x80\n\t"
680 "popl %%ebx"
681 : "=a" (ret)
682 : "0" (90), /* SYS_mmap */
683 "q" (&args)
684 : "memory" );
685 if (ret < 0 && ret > -4096)
687 errno = -ret;
688 ret = -1;
690 return (void *)ret;
692 #endif
693 return mmap( addr, length, prot, flags, fd, offset );
697 /***********************************************************************
698 * map_file_into_view
700 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
701 * The csVirtual section must be held by caller.
703 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
704 off_t offset, BYTE vprot, BOOL removable )
706 void *ptr;
707 int prot = VIRTUAL_GetUnixProt( vprot );
708 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
710 assert( start < view->size );
711 assert( start + size <= view->size );
713 /* only try mmap if media is not removable (or if we require write access) */
714 if (!removable || shared_write)
716 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
718 if (unaligned_mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
719 goto done;
721 /* mmap() failed; if this is because the file offset is not */
722 /* page-aligned (EINVAL), or because the underlying filesystem */
723 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
724 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
725 if (shared_write) return FILE_GetNtStatus(); /* we cannot fake shared write mappings */
728 /* Reserve the memory with an anonymous mmap */
729 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
730 if (ptr == (void *)-1) return FILE_GetNtStatus();
731 /* Now read in the file */
732 pread( fd, ptr, size, offset );
733 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
734 done:
735 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
736 return STATUS_SUCCESS;
740 /***********************************************************************
741 * decommit_view
743 * Decommit some pages of a given view.
744 * The csVirtual section must be held by caller.
746 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
748 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
750 BYTE *p = view->prot + (start >> page_shift);
751 size >>= page_shift;
752 while (size--) *p++ &= ~VPROT_COMMITTED;
753 return STATUS_SUCCESS;
755 return FILE_GetNtStatus();
759 /***********************************************************************
760 * do_relocations
762 * Apply the relocations to a mapped PE image
764 static int do_relocations( char *base, const IMAGE_DATA_DIRECTORY *dir,
765 int delta, SIZE_T total_size )
767 IMAGE_BASE_RELOCATION *rel;
769 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
770 base - delta, base - delta + total_size, base, base + total_size );
772 for (rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
773 ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
774 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock) )
776 char *page = base + rel->VirtualAddress;
777 WORD *TypeOffset = (WORD *)(rel + 1);
778 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
780 if (!count) continue;
782 /* sanity checks */
783 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size)
785 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
786 rel, rel->VirtualAddress, rel->SizeOfBlock,
787 base, dir->VirtualAddress, dir->Size );
788 return 0;
791 if (page > base + total_size)
793 WARN_(module)("skipping %d relocations for page %p beyond module %p-%p\n",
794 count, page, base, base + total_size );
795 continue;
798 TRACE_(module)("%d relocations for page %lx\n", count, rel->VirtualAddress);
800 /* patching in reverse order */
801 for (i = 0 ; i < count; i++)
803 int offset = TypeOffset[i] & 0xFFF;
804 int type = TypeOffset[i] >> 12;
805 switch(type)
807 case IMAGE_REL_BASED_ABSOLUTE:
808 break;
809 case IMAGE_REL_BASED_HIGH:
810 *(short*)(page+offset) += HIWORD(delta);
811 break;
812 case IMAGE_REL_BASED_LOW:
813 *(short*)(page+offset) += LOWORD(delta);
814 break;
815 case IMAGE_REL_BASED_HIGHLOW:
816 *(int*)(page+offset) += delta;
817 /* FIXME: if this is an exported address, fire up enhanced logic */
818 break;
819 default:
820 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
821 break;
825 return 1;
829 /***********************************************************************
830 * map_image
832 * Map an executable (PE format) image into memory.
834 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size,
835 SIZE_T header_size, int shared_fd, BOOL removable, PVOID *addr_ptr )
837 IMAGE_DOS_HEADER *dos;
838 IMAGE_NT_HEADERS *nt;
839 IMAGE_SECTION_HEADER *sec;
840 IMAGE_DATA_DIRECTORY *imports;
841 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
842 int i;
843 off_t pos;
844 struct stat st;
845 struct file_view *view = NULL;
846 char *ptr, *header_end;
848 /* zero-map the whole range */
850 RtlEnterCriticalSection( &csVirtual );
852 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
853 status = map_view( &view, base, total_size,
854 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
856 if (status == STATUS_CONFLICTING_ADDRESSES)
857 status = map_view( &view, NULL, total_size,
858 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
860 if (status != STATUS_SUCCESS) goto error;
862 ptr = view->base;
863 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
865 /* map the header */
867 if (fstat( fd, &st ) == -1)
869 status = FILE_GetNtStatus();
870 goto error;
872 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
873 if (!st.st_size) goto error;
874 header_size = min( header_size, st.st_size );
875 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ,
876 removable ) != STATUS_SUCCESS) goto error;
877 dos = (IMAGE_DOS_HEADER *)ptr;
878 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
879 header_end = ptr + ROUND_SIZE( 0, header_size );
880 if ((char *)(nt + 1) > header_end) goto error;
881 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
882 if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
884 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
885 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
887 /* check the architecture */
889 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
891 MESSAGE("Trying to load PE image for unsupported architecture (");
892 switch (nt->FileHeader.Machine)
894 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
895 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
896 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
897 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
898 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
899 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
900 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
901 case IMAGE_FILE_MACHINE_IA64: MESSAGE("IA-64"); break;
902 case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
903 case IMAGE_FILE_MACHINE_AMD64: MESSAGE("AMD-64"); break;
904 case IMAGE_FILE_MACHINE_ARM: MESSAGE("ARM"); break;
905 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
907 MESSAGE(")\n");
908 goto error;
911 /* check for non page-aligned binary */
913 if (nt->OptionalHeader.SectionAlignment <= page_mask)
915 /* unaligned sections, this happens for native subsystem binaries */
916 /* in that case Windows simply maps in the whole file */
918 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
919 removable ) != STATUS_SUCCESS) goto error;
921 /* check that all sections are loaded at the right offset */
922 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
924 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
925 goto error; /* Windows refuses to load in that case too */
928 /* set the image protections */
929 VIRTUAL_SetProt( view, ptr, total_size,
930 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
932 /* perform relocations if necessary */
933 /* FIXME: not 100% compatible, Windows doesn't do this for non page-aligned binaries */
934 if (ptr != base)
936 const IMAGE_DATA_DIRECTORY *relocs;
937 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
938 if (relocs->VirtualAddress && relocs->Size)
939 do_relocations( ptr, relocs, ptr - base, total_size );
942 goto done;
946 /* map all the sections */
948 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
950 SIZE_T map_size, file_size, end;
952 if (!sec->Misc.VirtualSize)
954 file_size = sec->SizeOfRawData;
955 map_size = ROUND_SIZE( 0, file_size );
957 else
959 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
960 file_size = min( sec->SizeOfRawData, map_size );
963 /* a few sanity checks */
964 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
965 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
967 ERR_(module)( "Section %.8s too large (%lx+%lx/%lx)\n",
968 sec->Name, sec->VirtualAddress, map_size, total_size );
969 goto error;
972 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
973 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
975 TRACE_(module)( "mapping shared section %.8s at %p off %lx (%x) size %lx (%lx) flags %lx\n",
976 sec->Name, ptr + sec->VirtualAddress,
977 sec->PointerToRawData, (int)pos, file_size, map_size,
978 sec->Characteristics );
979 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
980 VPROT_COMMITTED | VPROT_READ | PROT_WRITE,
981 FALSE ) != STATUS_SUCCESS)
983 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
984 goto error;
987 /* check if the import directory falls inside this section */
988 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
989 imports->VirtualAddress < sec->VirtualAddress + map_size)
991 UINT_PTR base = imports->VirtualAddress & ~page_mask;
992 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
993 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
994 if (end > base)
995 map_file_into_view( view, shared_fd, base, end - base,
996 pos + (base - sec->VirtualAddress),
997 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
998 FALSE );
1000 pos += map_size;
1001 continue;
1004 TRACE_(module)( "mapping section %.8s at %p off %lx size %lx virt %lx flags %lx\n",
1005 sec->Name, ptr + sec->VirtualAddress,
1006 sec->PointerToRawData, sec->SizeOfRawData,
1007 sec->Misc.VirtualSize, sec->Characteristics );
1009 if (!sec->PointerToRawData || !file_size) continue;
1011 /* Note: if the section is not aligned properly map_file_into_view will magically
1012 * fall back to read(), so we don't need to check anything here.
1014 end = sec->PointerToRawData + file_size;
1015 if (sec->PointerToRawData >= st.st_size || end > st.st_size || end < sec->PointerToRawData ||
1016 map_file_into_view( view, fd, sec->VirtualAddress, file_size, sec->PointerToRawData,
1017 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1018 removable ) != STATUS_SUCCESS)
1020 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1021 goto error;
1024 if (file_size & page_mask)
1026 end = ROUND_SIZE( 0, file_size );
1027 if (end > map_size) end = map_size;
1028 TRACE_(module)("clearing %p - %p\n",
1029 ptr + sec->VirtualAddress + file_size,
1030 ptr + sec->VirtualAddress + end );
1031 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1036 /* perform base relocation, if necessary */
1038 if (ptr != base)
1040 const IMAGE_DATA_DIRECTORY *relocs;
1042 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1043 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1045 if (nt->OptionalHeader.ImageBase == 0x400000) {
1046 ERR("Image was mapped at %p: standard load address for a Win32 program (0x00400000) not available\n", ptr);
1047 ERR("Do you have exec-shield or prelink active?\n");
1048 } else
1049 ERR( "FATAL: Need to relocate module from addr %lx, but there are no relocation records\n",
1050 nt->OptionalHeader.ImageBase );
1051 goto error;
1054 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
1055 * really make sure that the *new* base address is also > 2GB.
1056 * Some DLLs really check the MSB of the module handle :-/
1058 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((ULONG_PTR)base & 0x80000000))
1059 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
1061 if (!do_relocations( ptr, relocs, ptr - base, total_size ))
1063 goto error;
1067 /* set the image protections */
1069 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1070 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1072 SIZE_T size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1073 BYTE vprot = VPROT_COMMITTED;
1074 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1075 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
1076 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1078 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1079 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1080 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1081 vprot |= VPROT_EXEC;
1083 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
1086 done:
1087 if (!removable) /* don't keep handle open on removable media */
1088 NtDuplicateObject( NtCurrentProcess(), hmapping,
1089 NtCurrentProcess(), &view->mapping,
1090 0, 0, DUPLICATE_SAME_ACCESS );
1092 RtlLeaveCriticalSection( &csVirtual );
1094 *addr_ptr = ptr;
1095 return STATUS_SUCCESS;
1097 error:
1098 if (view) delete_view( view );
1099 RtlLeaveCriticalSection( &csVirtual );
1100 return status;
1104 /***********************************************************************
1105 * is_current_process
1107 * Check whether a process handle is for the current process.
1109 BOOL is_current_process( HANDLE handle )
1111 BOOL ret = FALSE;
1113 if (handle == NtCurrentProcess()) return TRUE;
1114 SERVER_START_REQ( get_process_info )
1116 req->handle = handle;
1117 if (!wine_server_call( req ))
1118 ret = ((DWORD)reply->pid == GetCurrentProcessId());
1120 SERVER_END_REQ;
1121 return ret;
1125 /***********************************************************************
1126 * virtual_init
1128 static inline void virtual_init(void)
1130 #ifndef page_mask
1131 page_size = getpagesize();
1132 page_mask = page_size - 1;
1133 /* Make sure we have a power of 2 */
1134 assert( !(page_size & page_mask) );
1135 page_shift = 0;
1136 while ((1 << page_shift) != page_size) page_shift++;
1137 #endif /* page_mask */
1141 /***********************************************************************
1142 * VIRTUAL_alloc_teb
1144 * Allocate a memory view for a new TEB, properly aligned to a multiple of the size.
1146 NTSTATUS VIRTUAL_alloc_teb( void **ret, size_t size, BOOL first )
1148 void *ptr;
1149 NTSTATUS status;
1150 struct file_view *view;
1151 size_t align_size;
1152 BYTE vprot = VPROT_READ | VPROT_WRITE | VPROT_COMMITTED;
1154 if (first) virtual_init();
1156 *ret = NULL;
1157 size = ROUND_SIZE( 0, size );
1158 align_size = page_size;
1159 while (align_size < size) align_size *= 2;
1161 for (;;)
1163 if ((ptr = wine_anon_mmap( NULL, 2 * align_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
1165 if (errno == ENOMEM) return STATUS_NO_MEMORY;
1166 return STATUS_INVALID_PARAMETER;
1168 if (!is_beyond_limit( ptr, 2 * align_size, user_space_limit ))
1170 ptr = unmap_extra_space( ptr, 2 * align_size, align_size, align_size - 1 );
1171 break;
1173 /* if we got something beyond the user limit, unmap it and retry */
1174 add_reserved_area( ptr, 2 * align_size );
1177 if (!first) RtlEnterCriticalSection( &csVirtual );
1179 status = create_view( &view, ptr, size, vprot );
1180 if (status == STATUS_SUCCESS)
1182 view->flags |= VFLAG_VALLOC;
1183 *ret = ptr;
1185 else unmap_area( ptr, size );
1187 if (!first) RtlLeaveCriticalSection( &csVirtual );
1189 return status;
1193 /***********************************************************************
1194 * VIRTUAL_HandleFault
1196 NTSTATUS VIRTUAL_HandleFault( LPCVOID addr )
1198 FILE_VIEW *view;
1199 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1201 RtlEnterCriticalSection( &csVirtual );
1202 if ((view = VIRTUAL_FindView( addr )))
1204 void *page = ROUND_ADDR( addr, page_mask );
1205 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1206 if (vprot & VPROT_GUARD)
1208 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1209 ret = STATUS_GUARD_PAGE_VIOLATION;
1212 RtlLeaveCriticalSection( &csVirtual );
1213 return ret;
1216 /***********************************************************************
1217 * VIRTUAL_HasMapping
1219 * Check if the specified view has an associated file mapping.
1221 BOOL VIRTUAL_HasMapping( LPCVOID addr )
1223 FILE_VIEW *view;
1224 BOOL ret = FALSE;
1226 RtlEnterCriticalSection( &csVirtual );
1227 if ((view = VIRTUAL_FindView( addr ))) ret = (view->mapping != 0);
1228 RtlLeaveCriticalSection( &csVirtual );
1229 return ret;
1233 /***********************************************************************
1234 * VIRTUAL_UseLargeAddressSpace
1236 * Increase the address space size for apps that support it.
1238 void VIRTUAL_UseLargeAddressSpace(void)
1240 if (user_space_limit >= ADDRESS_SPACE_LIMIT) return;
1241 /* no large address space on win9x */
1242 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1244 RtlEnterCriticalSection( &csVirtual );
1245 remove_reserved_area( user_space_limit, (char *)ADDRESS_SPACE_LIMIT - (char *)user_space_limit );
1246 user_space_limit = ADDRESS_SPACE_LIMIT;
1247 RtlLeaveCriticalSection( &csVirtual );
1251 /***********************************************************************
1252 * NtAllocateVirtualMemory (NTDLL.@)
1253 * ZwAllocateVirtualMemory (NTDLL.@)
1255 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1256 SIZE_T *size_ptr, ULONG type, ULONG protect )
1258 void *base;
1259 BYTE vprot;
1260 SIZE_T size = *size_ptr;
1261 NTSTATUS status = STATUS_SUCCESS;
1262 struct file_view *view;
1264 TRACE("%p %p %08lx %lx %08lx\n", process, *ret, size, type, protect );
1266 if (!size) return STATUS_INVALID_PARAMETER;
1268 if (!is_current_process( process ))
1270 ERR("Unsupported on other process\n");
1271 return STATUS_ACCESS_DENIED;
1274 /* Round parameters to a page boundary */
1276 if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
1278 if (*ret)
1280 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1281 base = ROUND_ADDR( *ret, granularity_mask );
1282 else
1283 base = ROUND_ADDR( *ret, page_mask );
1284 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1286 /* disallow low 64k, wrap-around and kernel space */
1287 if (((char *)base <= (char *)granularity_mask) ||
1288 ((char *)base + size < (char *)base) ||
1289 is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
1290 return STATUS_INVALID_PARAMETER;
1292 else
1294 base = NULL;
1295 size = (size + page_mask) & ~page_mask;
1298 if (type & MEM_TOP_DOWN) {
1299 /* FIXME: MEM_TOP_DOWN allocates the largest possible address. */
1300 WARN("MEM_TOP_DOWN ignored\n");
1301 type &= ~MEM_TOP_DOWN;
1304 if (zero_bits)
1305 WARN("zero_bits %lu ignored\n", zero_bits);
1307 /* Compute the alloc type flags */
1309 if (!(type & MEM_SYSTEM))
1311 if (!(type & (MEM_COMMIT | MEM_RESERVE)) || (type & ~(MEM_COMMIT | MEM_RESERVE)))
1313 WARN("called with wrong alloc type flags (%08lx) !\n", type);
1314 return STATUS_INVALID_PARAMETER;
1317 vprot = VIRTUAL_GetProt( protect );
1318 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1320 /* Reserve the memory */
1322 RtlEnterCriticalSection( &csVirtual );
1324 if (type & MEM_SYSTEM)
1326 if (type & MEM_IMAGE) vprot |= VPROT_IMAGE;
1327 status = create_view( &view, base, size, vprot | VPROT_COMMITTED );
1328 if (status == STATUS_SUCCESS)
1330 view->flags |= VFLAG_VALLOC | VFLAG_SYSTEM;
1331 base = view->base;
1334 else if ((type & MEM_RESERVE) || !base)
1336 status = map_view( &view, base, size, vprot );
1337 if (status == STATUS_SUCCESS)
1339 view->flags |= VFLAG_VALLOC;
1340 base = view->base;
1343 else /* commit the pages */
1345 if (!(view = VIRTUAL_FindView( base )) ||
1346 ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
1347 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1350 RtlLeaveCriticalSection( &csVirtual );
1352 if (status == STATUS_SUCCESS)
1354 *ret = base;
1355 *size_ptr = size;
1357 return status;
1361 /***********************************************************************
1362 * NtFreeVirtualMemory (NTDLL.@)
1363 * ZwFreeVirtualMemory (NTDLL.@)
1365 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1367 FILE_VIEW *view;
1368 char *base;
1369 NTSTATUS status = STATUS_SUCCESS;
1370 LPVOID addr = *addr_ptr;
1371 SIZE_T size = *size_ptr;
1373 TRACE("%p %p %08lx %lx\n", process, addr, size, type );
1375 if (!is_current_process( process ))
1377 ERR("Unsupported on other process\n");
1378 return STATUS_ACCESS_DENIED;
1381 /* Fix the parameters */
1383 size = ROUND_SIZE( addr, size );
1384 base = ROUND_ADDR( addr, page_mask );
1386 RtlEnterCriticalSection(&csVirtual);
1388 if (!(view = VIRTUAL_FindView( base )) ||
1389 (base + size > (char *)view->base + view->size) ||
1390 !(view->flags & VFLAG_VALLOC))
1392 status = STATUS_INVALID_PARAMETER;
1394 else if (type & MEM_SYSTEM)
1396 /* return the values that the caller should use to unmap the area */
1397 *addr_ptr = view->base;
1398 *size_ptr = view->size;
1399 view->flags |= VFLAG_SYSTEM;
1400 delete_view( view );
1402 else if (type == MEM_RELEASE)
1404 /* Free the pages */
1406 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1407 else
1409 delete_view( view );
1410 *addr_ptr = base;
1411 *size_ptr = size;
1414 else if (type == MEM_DECOMMIT)
1416 status = decommit_pages( view, base - (char *)view->base, size );
1417 if (status == STATUS_SUCCESS)
1419 *addr_ptr = base;
1420 *size_ptr = size;
1423 else
1425 WARN("called with wrong free type flags (%08lx) !\n", type);
1426 status = STATUS_INVALID_PARAMETER;
1429 RtlLeaveCriticalSection(&csVirtual);
1430 return status;
1434 /***********************************************************************
1435 * NtProtectVirtualMemory (NTDLL.@)
1436 * ZwProtectVirtualMemory (NTDLL.@)
1438 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1439 ULONG new_prot, ULONG *old_prot )
1441 FILE_VIEW *view;
1442 NTSTATUS status = STATUS_SUCCESS;
1443 char *base;
1444 UINT i;
1445 BYTE vprot, *p;
1446 ULONG prot;
1447 SIZE_T size = *size_ptr;
1448 LPVOID addr = *addr_ptr;
1450 TRACE("%p %p %08lx %08lx\n", process, addr, size, new_prot );
1452 if (!is_current_process( process ))
1454 ERR("Unsupported on other process\n");
1455 return STATUS_ACCESS_DENIED;
1458 /* Fix the parameters */
1460 size = ROUND_SIZE( addr, size );
1461 base = ROUND_ADDR( addr, page_mask );
1463 RtlEnterCriticalSection( &csVirtual );
1465 if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1467 status = STATUS_INVALID_PARAMETER;
1469 else
1471 /* Make sure all the pages are committed */
1473 p = view->prot + ((base - (char *)view->base) >> page_shift);
1474 prot = VIRTUAL_GetWin32Prot( *p );
1475 for (i = size >> page_shift; i; i--, p++)
1477 if (!(*p & VPROT_COMMITTED))
1479 status = STATUS_NOT_COMMITTED;
1480 break;
1483 if (!i)
1485 if (old_prot) *old_prot = prot;
1486 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1487 if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1490 RtlLeaveCriticalSection( &csVirtual );
1492 if (status == STATUS_SUCCESS)
1494 *addr_ptr = base;
1495 *size_ptr = size;
1497 return status;
1500 #define UNIMPLEMENTED_INFO_CLASS(c) \
1501 case c: \
1502 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
1503 return STATUS_INVALID_INFO_CLASS
1505 /***********************************************************************
1506 * NtQueryVirtualMemory (NTDLL.@)
1507 * ZwQueryVirtualMemory (NTDLL.@)
1509 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1510 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1511 SIZE_T len, SIZE_T *res_len )
1513 FILE_VIEW *view;
1514 char *base, *alloc_base = 0;
1515 struct list *ptr;
1516 SIZE_T size = 0;
1517 MEMORY_BASIC_INFORMATION *info = buffer;
1519 if (info_class != MemoryBasicInformation)
1521 switch(info_class)
1523 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
1524 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
1525 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
1527 default:
1528 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
1529 process, addr, info_class, buffer, len, res_len);
1530 return STATUS_INVALID_INFO_CLASS;
1533 if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1534 return STATUS_WORKING_SET_LIMIT_RANGE;
1536 if (!is_current_process( process ))
1538 ERR("Unsupported on other process\n");
1539 return STATUS_ACCESS_DENIED;
1542 base = ROUND_ADDR( addr, page_mask );
1544 /* Find the view containing the address */
1546 RtlEnterCriticalSection(&csVirtual);
1547 ptr = list_head( &views_list );
1548 for (;;)
1550 if (!ptr)
1552 /* make the address space end at the user limit, except if
1553 * the last view was mapped beyond that */
1554 if (alloc_base <= (char *)user_space_limit)
1556 if (user_space_limit && base >= (char *)user_space_limit)
1558 RtlLeaveCriticalSection( &csVirtual );
1559 return STATUS_WORKING_SET_LIMIT_RANGE;
1561 size = (char *)user_space_limit - alloc_base;
1563 else size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1564 view = NULL;
1565 break;
1567 view = LIST_ENTRY( ptr, struct file_view, entry );
1568 if ((char *)view->base > base)
1570 size = (char *)view->base - alloc_base;
1571 view = NULL;
1572 break;
1574 if ((char *)view->base + view->size > base)
1576 alloc_base = view->base;
1577 size = view->size;
1578 break;
1580 alloc_base = (char *)view->base + view->size;
1581 ptr = list_next( &views_list, ptr );
1584 /* Fill the info structure */
1586 if (!view)
1588 info->State = MEM_FREE;
1589 info->Protect = 0;
1590 info->AllocationProtect = 0;
1591 info->Type = 0;
1593 else
1595 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1596 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
1597 info->Protect = VIRTUAL_GetWin32Prot( vprot );
1598 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
1599 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1600 else if (view->flags & VFLAG_VALLOC) info->Type = MEM_PRIVATE;
1601 else info->Type = MEM_MAPPED;
1602 for (size = base - alloc_base; size < view->size; size += page_size)
1603 if (view->prot[size >> page_shift] != vprot) break;
1605 RtlLeaveCriticalSection(&csVirtual);
1607 info->BaseAddress = (LPVOID)base;
1608 info->AllocationBase = (LPVOID)alloc_base;
1609 info->RegionSize = size - (base - alloc_base);
1610 if (res_len) *res_len = sizeof(*info);
1611 return STATUS_SUCCESS;
1615 /***********************************************************************
1616 * NtLockVirtualMemory (NTDLL.@)
1617 * ZwLockVirtualMemory (NTDLL.@)
1619 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1621 if (!is_current_process( process ))
1623 ERR("Unsupported on other process\n");
1624 return STATUS_ACCESS_DENIED;
1626 return STATUS_SUCCESS;
1630 /***********************************************************************
1631 * NtUnlockVirtualMemory (NTDLL.@)
1632 * ZwUnlockVirtualMemory (NTDLL.@)
1634 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1636 if (!is_current_process( process ))
1638 ERR("Unsupported on other process\n");
1639 return STATUS_ACCESS_DENIED;
1641 return STATUS_SUCCESS;
1645 /***********************************************************************
1646 * NtCreateSection (NTDLL.@)
1647 * ZwCreateSection (NTDLL.@)
1649 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1650 const LARGE_INTEGER *size, ULONG protect,
1651 ULONG sec_flags, HANDLE file )
1653 NTSTATUS ret;
1654 BYTE vprot;
1655 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
1657 /* Check parameters */
1659 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1661 vprot = VIRTUAL_GetProt( protect );
1662 if (sec_flags & SEC_RESERVE)
1664 if (file) return STATUS_INVALID_PARAMETER;
1666 else vprot |= VPROT_COMMITTED;
1667 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1668 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
1670 /* Create the server object */
1672 SERVER_START_REQ( create_mapping )
1674 req->access = access;
1675 req->attributes = (attr) ? attr->Attributes : 0;
1676 req->rootdir = attr ? attr->RootDirectory : 0;
1677 req->file_handle = file;
1678 req->size_high = size ? size->u.HighPart : 0;
1679 req->size_low = size ? size->u.LowPart : 0;
1680 req->protect = vprot;
1681 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
1682 ret = wine_server_call( req );
1683 *handle = reply->handle;
1685 SERVER_END_REQ;
1686 return ret;
1690 /***********************************************************************
1691 * NtOpenSection (NTDLL.@)
1692 * ZwOpenSection (NTDLL.@)
1694 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1696 NTSTATUS ret;
1697 DWORD len = attr->ObjectName->Length;
1699 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1701 SERVER_START_REQ( open_mapping )
1703 req->access = access;
1704 req->attributes = (attr) ? attr->Attributes : 0;
1705 req->rootdir = attr ? attr->RootDirectory : 0;
1706 wine_server_add_data( req, attr->ObjectName->Buffer, len );
1707 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
1709 SERVER_END_REQ;
1710 return ret;
1714 /***********************************************************************
1715 * NtMapViewOfSection (NTDLL.@)
1716 * ZwMapViewOfSection (NTDLL.@)
1718 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
1719 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
1720 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
1722 FILE_FS_DEVICE_INFORMATION device_info;
1723 NTSTATUS res;
1724 SIZE_T size = 0;
1725 int unix_handle = -1;
1726 int prot;
1727 void *base;
1728 struct file_view *view;
1729 DWORD size_low, size_high, header_size, shared_size;
1730 HANDLE shared_file;
1731 BOOL removable = FALSE;
1732 LARGE_INTEGER offset;
1734 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
1736 TRACE("handle=%p process=%p addr=%p off=%lx%08lx size=%lx access=%lx\n",
1737 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, size, protect );
1739 if (!is_current_process( process ))
1741 ERR("Unsupported on other process\n");
1742 return STATUS_ACCESS_DENIED;
1745 /* Check parameters */
1747 if ((offset.u.LowPart & granularity_mask) ||
1748 (*addr_ptr && ((UINT_PTR)*addr_ptr & granularity_mask)))
1749 return STATUS_INVALID_PARAMETER;
1751 SERVER_START_REQ( get_mapping_info )
1753 req->handle = handle;
1754 res = wine_server_call( req );
1755 prot = reply->protect;
1756 base = reply->base;
1757 size_low = reply->size_low;
1758 size_high = reply->size_high;
1759 header_size = reply->header_size;
1760 shared_file = reply->shared_file;
1761 shared_size = reply->shared_size;
1763 SERVER_END_REQ;
1764 if (res) return res;
1766 if ((res = wine_server_handle_to_fd( handle, 0, &unix_handle, NULL ))) return res;
1768 if (FILE_GetDeviceInfo( unix_handle, &device_info ) == STATUS_SUCCESS)
1769 removable = device_info.Characteristics & FILE_REMOVABLE_MEDIA;
1771 if (prot & VPROT_IMAGE)
1773 if (shared_file)
1775 int shared_fd;
1777 if ((res = wine_server_handle_to_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
1778 &shared_fd, NULL ))) goto done;
1779 res = map_image( handle, unix_handle, base, size_low, header_size,
1780 shared_fd, removable, addr_ptr );
1781 wine_server_release_fd( shared_file, shared_fd );
1782 NtClose( shared_file );
1784 else
1786 res = map_image( handle, unix_handle, base, size_low, header_size,
1787 -1, removable, addr_ptr );
1789 wine_server_release_fd( handle, unix_handle );
1790 if (!res) *size_ptr = size_low;
1791 return res;
1794 if (size_high)
1795 ERR("Sizes larger than 4Gb not supported\n");
1797 if ((offset.u.LowPart >= size_low) ||
1798 (*size_ptr > size_low - offset.u.LowPart))
1800 res = STATUS_INVALID_PARAMETER;
1801 goto done;
1803 if (*size_ptr) size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
1804 else size = size_low - offset.u.LowPart;
1806 switch(protect)
1808 case PAGE_NOACCESS:
1809 break;
1810 case PAGE_READWRITE:
1811 case PAGE_EXECUTE_READWRITE:
1812 if (!(prot & VPROT_WRITE))
1814 res = STATUS_INVALID_PARAMETER;
1815 goto done;
1817 removable = FALSE;
1818 /* fall through */
1819 case PAGE_READONLY:
1820 case PAGE_WRITECOPY:
1821 case PAGE_EXECUTE:
1822 case PAGE_EXECUTE_READ:
1823 case PAGE_EXECUTE_WRITECOPY:
1824 if (prot & VPROT_READ) break;
1825 /* fall through */
1826 default:
1827 res = STATUS_INVALID_PARAMETER;
1828 goto done;
1831 /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1832 * which has a view of this mapping commits some pages, they will
1833 * appear commited in all other processes, which have the same
1834 * view created. Since we don`t support this yet, we create the
1835 * whole mapping commited.
1837 prot |= VPROT_COMMITTED;
1839 /* Reserve a properly aligned area */
1841 RtlEnterCriticalSection( &csVirtual );
1843 res = map_view( &view, *addr_ptr, size, prot );
1844 if (res)
1846 RtlLeaveCriticalSection( &csVirtual );
1847 goto done;
1850 /* Map the file */
1852 TRACE("handle=%p size=%lx offset=%lx%08lx\n",
1853 handle, size, offset.u.HighPart, offset.u.LowPart );
1855 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, prot, removable );
1856 if (res == STATUS_SUCCESS)
1858 if (!removable) /* don't keep handle open on removable media */
1859 NtDuplicateObject( NtCurrentProcess(), handle,
1860 NtCurrentProcess(), &view->mapping,
1861 0, 0, DUPLICATE_SAME_ACCESS );
1863 *addr_ptr = view->base;
1864 *size_ptr = size;
1866 else
1868 ERR( "map_file_into_view %p %lx %lx%08lx failed\n",
1869 view->base, size, offset.u.HighPart, offset.u.LowPart );
1870 delete_view( view );
1873 RtlLeaveCriticalSection( &csVirtual );
1875 done:
1876 wine_server_release_fd( handle, unix_handle );
1877 return res;
1881 /***********************************************************************
1882 * NtUnmapViewOfSection (NTDLL.@)
1883 * ZwUnmapViewOfSection (NTDLL.@)
1885 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
1887 FILE_VIEW *view;
1888 NTSTATUS status = STATUS_INVALID_PARAMETER;
1889 void *base = ROUND_ADDR( addr, page_mask );
1891 if (!is_current_process( process ))
1893 ERR("Unsupported on other process\n");
1894 return STATUS_ACCESS_DENIED;
1896 RtlEnterCriticalSection( &csVirtual );
1897 if ((view = VIRTUAL_FindView( base )) && (base == view->base))
1899 delete_view( view );
1900 status = STATUS_SUCCESS;
1902 RtlLeaveCriticalSection( &csVirtual );
1903 return status;
1907 /***********************************************************************
1908 * NtFlushVirtualMemory (NTDLL.@)
1909 * ZwFlushVirtualMemory (NTDLL.@)
1911 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
1912 SIZE_T *size_ptr, ULONG unknown )
1914 FILE_VIEW *view;
1915 NTSTATUS status = STATUS_SUCCESS;
1916 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
1918 if (!is_current_process( process ))
1920 ERR("Unsupported on other process\n");
1921 return STATUS_ACCESS_DENIED;
1923 RtlEnterCriticalSection( &csVirtual );
1924 if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
1925 else
1927 if (!*size_ptr) *size_ptr = view->size;
1928 *addr_ptr = addr;
1929 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
1931 RtlLeaveCriticalSection( &csVirtual );
1932 return status;
1936 /***********************************************************************
1937 * NtReadVirtualMemory (NTDLL.@)
1938 * ZwReadVirtualMemory (NTDLL.@)
1940 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
1941 SIZE_T size, SIZE_T *bytes_read )
1943 NTSTATUS status;
1945 SERVER_START_REQ( read_process_memory )
1947 req->handle = process;
1948 req->addr = (void *)addr;
1949 wine_server_set_reply( req, buffer, size );
1950 if ((status = wine_server_call( req ))) size = 0;
1952 SERVER_END_REQ;
1953 if (bytes_read) *bytes_read = size;
1954 return status;
1958 /***********************************************************************
1959 * NtWriteVirtualMemory (NTDLL.@)
1960 * ZwWriteVirtualMemory (NTDLL.@)
1962 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
1963 SIZE_T size, SIZE_T *bytes_written )
1965 NTSTATUS status;
1967 SERVER_START_REQ( write_process_memory )
1969 req->handle = process;
1970 req->addr = addr;
1971 wine_server_add_data( req, buffer, size );
1972 if ((status = wine_server_call( req ))) size = 0;
1974 SERVER_END_REQ;
1975 if (bytes_written) *bytes_written = size;
1976 return status;