Release 980503
[wine/hacks.git] / memory / virtual.c
blobd2759e6b61db0bf494fdad800bd6a8d3e4e4ebe2
1 /*
2 * Win32 virtual memory functions
4 * Copyright 1997 Alexandre Julliard
5 */
7 #include <assert.h>
8 #include <fcntl.h>
9 #include <stdio.h>
10 #include <unistd.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <sys/types.h>
14 #include <sys/mman.h>
15 #include "winbase.h"
16 #include "winerror.h"
17 #include "file.h"
18 #include "heap.h"
19 #include "process.h"
20 #include "xmalloc.h"
21 #include "debug.h"
23 #ifndef MS_SYNC
24 #define MS_SYNC 0
25 #endif
27 /* File mapping */
28 typedef struct
30 K32OBJ header;
31 DWORD size_high;
32 DWORD size_low;
33 FILE_OBJECT *file;
34 BYTE protect;
35 } FILE_MAPPING;
37 /* File view */
38 typedef struct _FV
40 struct _FV *next; /* Next view */
41 struct _FV *prev; /* Prev view */
42 UINT32 base; /* Base address */
43 UINT32 size; /* Size in bytes */
44 UINT32 flags; /* Allocation flags */
45 UINT32 offset; /* Offset from start of mapped file */
46 FILE_MAPPING *mapping; /* File mapping */
47 BYTE protect; /* Protection for all pages at allocation time */
48 BYTE prot[1]; /* Protection byte for each page */
49 } FILE_VIEW;
51 /* Per-page protection byte values */
52 #define VPROT_READ 0x01
53 #define VPROT_WRITE 0x02
54 #define VPROT_EXEC 0x04
55 #define VPROT_WRITECOPY 0x08
56 #define VPROT_GUARD 0x10
57 #define VPROT_NOCACHE 0x20
58 #define VPROT_COMMITTED 0x40
60 /* Per-view flags */
61 #define VFLAG_SYSTEM 0x01
63 /* Conversion from VPROT_* to Win32 flags */
64 static const BYTE VIRTUAL_Win32Flags[16] =
66 PAGE_NOACCESS, /* 0 */
67 PAGE_READONLY, /* READ */
68 PAGE_READWRITE, /* WRITE */
69 PAGE_READWRITE, /* READ | WRITE */
70 PAGE_EXECUTE, /* EXEC */
71 PAGE_EXECUTE_READ, /* READ | EXEC */
72 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
73 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
74 PAGE_WRITECOPY, /* WRITECOPY */
75 PAGE_WRITECOPY, /* READ | WRITECOPY */
76 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
77 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
78 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
79 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
80 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
81 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
85 static FILE_VIEW *VIRTUAL_FirstView;
87 #ifdef __i386__
88 /* These are always the same on an i386, and it will be faster this way */
89 # define page_mask 0xfff
90 # define page_shift 12
91 # define granularity_mask 0xffff
92 #else
93 static UINT32 page_shift;
94 static UINT32 page_mask;
95 static UINT32 granularity_mask; /* Allocation granularity (usually 64k) */
96 #endif /* __i386__ */
98 #define ROUND_ADDR(addr) \
99 ((UINT32)(addr) & ~page_mask)
101 #define ROUND_SIZE(addr,size) \
102 (((UINT32)(size) + ((UINT32)(addr) & page_mask) + page_mask) & ~page_mask)
104 static void VIRTUAL_DestroyMapping( K32OBJ *obj );
106 const K32OBJ_OPS MEM_MAPPED_FILE_Ops =
108 /* Object cannot be waited upon, so we don't need these (except destroy) */
109 NULL, /* signaled */
110 NULL, /* satisfied */
111 NULL, /* add_wait */
112 NULL, /* remove_wait */
113 NULL, /* read */
114 NULL, /* write */
115 VIRTUAL_DestroyMapping /* destroy */
118 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
119 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
121 /***********************************************************************
122 * VIRTUAL_GetProtStr
124 static const char *VIRTUAL_GetProtStr( BYTE prot )
126 static char buffer[6];
127 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
128 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
129 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
130 buffer[3] = (prot & VPROT_WRITE) ?
131 ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
132 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
133 buffer[5] = 0;
134 return buffer;
138 /***********************************************************************
139 * VIRTUAL_DumpView
141 static void VIRTUAL_DumpView( FILE_VIEW *view )
143 UINT32 i, count;
144 UINT32 addr = view->base;
145 BYTE prot = view->prot[0];
147 DUMP( "View: %08x - %08x%s",
148 view->base, view->base + view->size - 1,
149 (view->flags & VFLAG_SYSTEM) ? " (system)" : "" );
150 if (view->mapping && view->mapping->file)
151 DUMP( " %s @ %08x\n", view->mapping->file->unix_name, view->offset );
152 else
153 DUMP( " (anonymous)\n");
155 for (count = i = 1; i < view->size >> page_shift; i++, count++)
157 if (view->prot[i] == prot) continue;
158 DUMP( " %08x - %08x %s\n",
159 addr, addr + (count << page_shift) - 1,
160 VIRTUAL_GetProtStr(prot) );
161 addr += (count << page_shift);
162 prot = view->prot[i];
163 count = 0;
165 if (count)
166 DUMP( " %08x - %08x %s\n",
167 addr, addr + (count << page_shift) - 1,
168 VIRTUAL_GetProtStr(prot) );
172 /***********************************************************************
173 * VIRTUAL_Dump
175 void VIRTUAL_Dump(void)
177 FILE_VIEW *view = VIRTUAL_FirstView;
178 DUMP( "\nDump of all virtual memory views:\n\n" );
179 while (view)
181 VIRTUAL_DumpView( view );
182 view = view->next;
187 /***********************************************************************
188 * VIRTUAL_FindView
190 * Find the view containing a given address.
192 * RETURNS
193 * View: Success
194 * NULL: Failure
196 static FILE_VIEW *VIRTUAL_FindView(
197 UINT32 addr /* [in] Address */
199 FILE_VIEW *view = VIRTUAL_FirstView;
200 while (view)
202 if (view->base > addr) return NULL;
203 if (view->base + view->size > addr) return view;
204 view = view->next;
206 return NULL;
210 /***********************************************************************
211 * VIRTUAL_CreateView
213 * Create a new view and add it in the linked list.
215 static FILE_VIEW *VIRTUAL_CreateView( UINT32 base, UINT32 size, UINT32 offset,
216 UINT32 flags, BYTE vprot,
217 FILE_MAPPING *mapping )
219 FILE_VIEW *view, *prev;
221 /* Create the view structure */
223 assert( !(base & page_mask) );
224 assert( !(size & page_mask) );
225 size >>= page_shift;
226 if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
227 view->base = base;
228 view->size = size << page_shift;
229 view->flags = flags;
230 view->offset = offset;
231 view->mapping = mapping;
232 view->protect = vprot;
233 memset( view->prot, vprot, size );
235 /* Insert it in the linked list */
237 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
239 view->next = VIRTUAL_FirstView;
240 view->prev = NULL;
241 if (view->next) view->next->prev = view;
242 VIRTUAL_FirstView = view;
244 else
246 prev = VIRTUAL_FirstView;
247 while (prev->next && (prev->next->base < base)) prev = prev->next;
248 view->next = prev->next;
249 view->prev = prev;
250 if (view->next) view->next->prev = view;
251 prev->next = view;
253 VIRTUAL_DEBUG_DUMP_VIEW( view );
254 return view;
258 /***********************************************************************
259 * VIRTUAL_DeleteView
260 * Deletes a view.
262 * RETURNS
263 * None
265 static void VIRTUAL_DeleteView(
266 FILE_VIEW *view /* [in] View */
268 FILE_munmap( (void *)view->base, 0, view->size );
269 if (view->next) view->next->prev = view->prev;
270 if (view->prev) view->prev->next = view->next;
271 else VIRTUAL_FirstView = view->next;
272 if (view->mapping) K32OBJ_DecCount( &view->mapping->header );
273 free( view );
277 /***********************************************************************
278 * VIRTUAL_GetUnixProt
280 * Convert page protections to protection for mmap/mprotect.
282 static int VIRTUAL_GetUnixProt( BYTE vprot )
284 int prot = 0;
285 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
287 if (vprot & VPROT_READ) prot |= PROT_READ;
288 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
289 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
291 return prot;
295 /***********************************************************************
296 * VIRTUAL_GetWin32Prot
298 * Convert page protections to Win32 flags.
300 * RETURNS
301 * None
303 static void VIRTUAL_GetWin32Prot(
304 BYTE vprot, /* [in] Page protection flags */
305 DWORD *protect, /* [out] Location to store Win32 protection flags */
306 DWORD *state /* [out] Location to store mem state flag */
308 if (protect) {
309 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
310 if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;
311 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
314 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
318 /***********************************************************************
319 * VIRTUAL_GetProt
321 * Build page protections from Win32 flags.
323 * RETURNS
324 * Value of page protection flags
326 static BYTE VIRTUAL_GetProt(
327 DWORD protect /* [in] Win32 protection flags */
329 BYTE vprot;
331 switch(protect & 0xff)
333 case PAGE_READONLY:
334 vprot = VPROT_READ;
335 break;
336 case PAGE_READWRITE:
337 vprot = VPROT_READ | VPROT_WRITE;
338 break;
339 case PAGE_WRITECOPY:
340 vprot = VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
341 break;
342 case PAGE_EXECUTE:
343 vprot = VPROT_EXEC;
344 break;
345 case PAGE_EXECUTE_READ:
346 vprot = VPROT_EXEC | VPROT_READ;
347 break;
348 case PAGE_EXECUTE_READWRITE:
349 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
350 break;
351 case PAGE_EXECUTE_WRITECOPY:
352 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
353 break;
354 case PAGE_NOACCESS:
355 default:
356 vprot = 0;
357 break;
359 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
360 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
361 return vprot;
365 /***********************************************************************
366 * VIRTUAL_SetProt
368 * Change the protection of a range of pages.
370 * RETURNS
371 * TRUE: Success
372 * FALSE: Failure
374 static BOOL32 VIRTUAL_SetProt(
375 FILE_VIEW *view, /* [in] Pointer to view */
376 UINT32 base, /* [in] Starting address */
377 UINT32 size, /* [in] Size in bytes */
378 BYTE vprot /* [in] Protections to use */
380 TRACE(virtual, "%08x-%08x %s\n",
381 base, base + size - 1, VIRTUAL_GetProtStr( vprot ) );
383 if (mprotect( (void *)base, size, VIRTUAL_GetUnixProt(vprot) ))
384 return FALSE; /* FIXME: last error */
386 memset( view->prot + ((base - view->base) >> page_shift),
387 vprot, size >> page_shift );
388 VIRTUAL_DEBUG_DUMP_VIEW( view );
389 return TRUE;
393 /***********************************************************************
394 * VIRTUAL_CheckFlags
396 * Check that all pages in a range have the given flags.
398 * RETURNS
399 * TRUE: They do
400 * FALSE: They do not
402 static BOOL32 VIRTUAL_CheckFlags(
403 UINT32 base, /* [in] Starting address */
404 UINT32 size, /* [in] Size in bytes */
405 BYTE flags /* [in] Flags to check for */
407 FILE_VIEW *view;
408 UINT32 page;
410 if (!size) return TRUE;
411 if (!(view = VIRTUAL_FindView( base ))) return FALSE;
412 if (view->base + view->size < base + size) return FALSE;
413 page = (base - view->base) >> page_shift;
414 size = ROUND_SIZE( base, size ) >> page_shift;
415 while (size--) if ((view->prot[page++] & flags) != flags) return FALSE;
416 return TRUE;
420 /***********************************************************************
421 * VIRTUAL_Init
423 BOOL32 VIRTUAL_Init(void)
425 #ifndef __i386__
426 DWORD page_size;
428 # ifdef HAVE_GETPAGESIZE
429 page_size = getpagesize();
430 # else
431 # ifdef __svr4__
432 page_size = sysconf(_SC_PAGESIZE);
433 # else
434 # error Cannot get the page size on this platform
435 # endif
436 # endif
437 page_mask = page_size - 1;
438 granularity_mask = 0xffff; /* hard-coded for now */
439 /* Make sure we have a power of 2 */
440 assert( !(page_size & page_mask) );
441 page_shift = 0;
442 while ((1 << page_shift) != page_size) page_shift++;
443 #endif /* !__i386__ */
445 #ifdef linux
447 /* Do not use stdio here since it may temporarily change the size
448 * of some segments (ie libc6 adds 0x1000 per open FILE)
450 int fd = open ("/proc/self/maps", O_RDONLY);
451 if (fd >= 0)
453 char buffer[512]; /* line might be rather long in 2.1 */
455 for (;;)
457 int start, end, offset;
458 char r, w, x, p;
459 BYTE vprot = VPROT_COMMITTED;
461 char * ptr = buffer;
462 int count = sizeof(buffer);
463 while (1 == read(fd, ptr, 1) && *ptr != '\n' && --count > 0)
464 ptr++;
466 if (*ptr != '\n') break;
467 *ptr = '\0';
469 sscanf( buffer, "%x-%x %c%c%c%c %x",
470 &start, &end, &r, &w, &x, &p, &offset );
471 if (r == 'r') vprot |= VPROT_READ;
472 if (w == 'w') vprot |= VPROT_WRITE;
473 if (x == 'x') vprot |= VPROT_EXEC;
474 if (p == 'p') vprot |= VPROT_WRITECOPY;
475 VIRTUAL_CreateView( start, end - start, 0,
476 VFLAG_SYSTEM, vprot, NULL );
478 close (fd);
481 #endif /* linux */
482 return TRUE;
486 /***********************************************************************
487 * VIRTUAL_GetPageSize
489 DWORD VIRTUAL_GetPageSize(void)
491 return 1 << page_shift;
495 /***********************************************************************
496 * VIRTUAL_GetGranularity
498 DWORD VIRTUAL_GetGranularity(void)
500 return granularity_mask + 1;
504 /***********************************************************************
505 * VirtualAlloc (KERNEL32.548)
506 * Reserves or commits a region of pages in virtual address space
508 * RETURNS
509 * Base address of allocated region of pages
510 * NULL: Failure
512 LPVOID WINAPI VirtualAlloc(
513 LPVOID addr, /* [in] Address of region to reserve or commit */
514 DWORD size, /* [in] Size of region */
515 DWORD type, /* [in] Type of allocation */
516 DWORD protect /* [in] Type of access protection */
518 FILE_VIEW *view;
519 UINT32 base, ptr, view_size;
520 BYTE vprot;
522 TRACE(virtual, "%08x %08lx %lx %08lx\n",
523 (UINT32)addr, size, type, protect );
525 /* Round parameters to a page boundary */
527 if (size > 0x7fc00000) /* 2Gb - 4Mb */
529 SetLastError( ERROR_OUTOFMEMORY );
530 return NULL;
532 if (addr)
534 if (type & MEM_RESERVE) /* Round down to 64k boundary */
535 base = ((UINT32)addr + granularity_mask) & ~granularity_mask;
536 else
537 base = ROUND_ADDR( addr );
538 size = (((UINT32)addr + size + page_mask) & ~page_mask) - base;
539 if (base + size < base) /* Disallow wrap-around */
541 SetLastError( ERROR_INVALID_PARAMETER );
542 return NULL;
545 else
547 base = 0;
548 size = (size + page_mask) & ~page_mask;
551 if (type & MEM_TOP_DOWN) {
552 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
553 * Is there _ANY_ way to do it with UNIX mmap()?
555 WARN(virtual,"MEM_TOP_DOWN ignored\n");
556 type &= ~MEM_TOP_DOWN;
558 /* Compute the protection flags */
560 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
561 (type & ~(MEM_COMMIT | MEM_RESERVE)))
563 SetLastError( ERROR_INVALID_PARAMETER );
564 return NULL;
566 if (type & MEM_COMMIT)
567 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
568 else vprot = 0;
570 /* Reserve the memory */
572 if ((type & MEM_RESERVE) || !base)
574 view_size = size + (base ? 0 : granularity_mask + 1);
575 ptr = (UINT32)FILE_dommap( NULL, (LPVOID)base, 0, view_size, 0, 0,
576 VIRTUAL_GetUnixProt( vprot ), MAP_PRIVATE );
577 if (ptr == (UINT32)-1)
579 SetLastError( ERROR_OUTOFMEMORY );
580 return NULL;
582 if (!base)
584 /* Release the extra memory while keeping the range */
585 /* starting on a 64k boundary. */
587 if (ptr & granularity_mask)
589 UINT32 extra = granularity_mask + 1 - (ptr & granularity_mask);
590 FILE_munmap( (void *)ptr, 0, extra );
591 ptr += extra;
592 view_size -= extra;
594 if (view_size > size)
595 FILE_munmap( (void *)(ptr + size), 0, view_size - size );
597 else if (ptr != base)
599 /* We couldn't get the address we wanted */
600 FILE_munmap( (void *)ptr, 0, view_size );
601 SetLastError( ERROR_INVALID_ADDRESS );
602 return NULL;
604 if (!(view = VIRTUAL_CreateView( ptr, size, 0, 0, vprot, NULL )))
606 FILE_munmap( (void *)ptr, 0, size );
607 SetLastError( ERROR_OUTOFMEMORY );
608 return NULL;
610 VIRTUAL_DEBUG_DUMP_VIEW( view );
611 return (LPVOID)ptr;
614 /* Commit the pages */
616 if (!(view = VIRTUAL_FindView( base )) ||
617 (base + size > view->base + view->size))
619 SetLastError( ERROR_INVALID_PARAMETER );
620 return NULL;
623 if (!VIRTUAL_SetProt( view, base, size, vprot )) return NULL;
624 return (LPVOID)base;
628 /***********************************************************************
629 * VirtualFree (KERNEL32.550)
630 * Release or decommits a region of pages in virtual address space.
632 * RETURNS
633 * TRUE: Success
634 * FALSE: Failure
636 BOOL32 WINAPI VirtualFree(
637 LPVOID addr, /* [in] Address of region of committed pages */
638 DWORD size, /* [in] Size of region */
639 DWORD type /* [in] Type of operation */
641 FILE_VIEW *view;
642 UINT32 base;
644 TRACE(virtual, "%08x %08lx %lx\n",
645 (UINT32)addr, size, type );
647 /* Fix the parameters */
649 size = ROUND_SIZE( addr, size );
650 base = ROUND_ADDR( addr );
652 if (!(view = VIRTUAL_FindView( base )) ||
653 (base + size > view->base + view->size))
655 SetLastError( ERROR_INVALID_PARAMETER );
656 return FALSE;
659 /* Compute the protection flags */
661 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
663 SetLastError( ERROR_INVALID_PARAMETER );
664 return FALSE;
667 /* Free the pages */
669 if (type == MEM_RELEASE)
671 if (size || (base != view->base))
673 SetLastError( ERROR_INVALID_PARAMETER );
674 return FALSE;
676 VIRTUAL_DeleteView( view );
677 return TRUE;
680 /* Decommit the pages */
681 return VIRTUAL_SetProt( view, base, size, 0 );
685 /***********************************************************************
686 * VirtualLock (KERNEL32.551)
687 * Locks the specified region of virtual address space
689 * NOTE
690 * Always returns TRUE
692 * RETURNS
693 * TRUE: Success
694 * FALSE: Failure
696 BOOL32 WINAPI VirtualLock(
697 LPVOID addr, /* [in] Address of first byte of range to lock */
698 DWORD size /* [in] Number of bytes in range to lock */
700 return TRUE;
704 /***********************************************************************
705 * VirtualUnlock (KERNEL32.556)
706 * Unlocks a range of pages in the virtual address space
708 * NOTE
709 * Always returns TRUE
711 * RETURNS
712 * TRUE: Success
713 * FALSE: Failure
715 BOOL32 WINAPI VirtualUnlock(
716 LPVOID addr, /* [in] Address of first byte of range */
717 DWORD size /* [in] Number of bytes in range */
719 return TRUE;
723 /***********************************************************************
724 * VirtualProtect (KERNEL32.552)
725 * Changes the access protection on a region of committed pages
727 * RETURNS
728 * TRUE: Success
729 * FALSE: Failure
731 BOOL32 WINAPI VirtualProtect(
732 LPVOID addr, /* [in] Address of region of committed pages */
733 DWORD size, /* [in] Size of region */
734 DWORD new_prot, /* [in] Desired access protection */
735 LPDWORD old_prot /* [out] Address of variable to get old protection */
737 FILE_VIEW *view;
738 UINT32 base, i;
739 BYTE vprot, *p;
741 TRACE(virtual, "%08x %08lx %08lx\n",
742 (UINT32)addr, size, new_prot );
744 /* Fix the parameters */
746 size = ROUND_SIZE( addr, size );
747 base = ROUND_ADDR( addr );
749 if (!(view = VIRTUAL_FindView( base )) ||
750 (base + size > view->base + view->size))
752 SetLastError( ERROR_INVALID_PARAMETER );
753 return FALSE;
756 /* Make sure all the pages are committed */
758 p = view->prot + ((base - view->base) >> page_shift);
759 for (i = size >> page_shift; i; i--, p++)
761 if (!(*p & VPROT_COMMITTED))
763 SetLastError( ERROR_INVALID_PARAMETER );
764 return FALSE;
768 VIRTUAL_GetWin32Prot( view->prot[0], old_prot, NULL );
769 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
770 return VIRTUAL_SetProt( view, base, size, vprot );
774 /***********************************************************************
775 * VirtualProtectEx (KERNEL32.553)
776 * Changes the access protection on a region of committed pages in the
777 * virtual address space of a specified process
779 * RETURNS
780 * TRUE: Success
781 * FALSE: Failure
783 BOOL32 WINAPI VirtualProtectEx(
784 HANDLE32 handle, /* [in] Handle of process */
785 LPVOID addr, /* [in] Address of region of committed pages */
786 DWORD size, /* [in] Size of region */
787 DWORD new_prot, /* [in] Desired access protection */
788 LPDWORD old_prot /* [out] Address of variable to get old protection */
790 BOOL32 ret = FALSE;
792 PDB32 *pdb = PROCESS_GetPtr( handle, PROCESS_VM_OPERATION );
793 if (pdb)
795 if (pdb == PROCESS_Current())
796 ret = VirtualProtect( addr, size, new_prot, old_prot );
797 else
798 ERR(virtual,"Unsupported on other process\n");
799 K32OBJ_DecCount( &pdb->header );
801 return ret;
805 /***********************************************************************
806 * VirtualQuery (KERNEL32.554)
807 * Provides info about a range of pages in virtual address space
809 * RETURNS
810 * Number of bytes returned in information buffer
812 DWORD WINAPI VirtualQuery(
813 LPCVOID addr, /* [in] Address of region */
814 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
815 DWORD len /* [in] Size of buffer */
817 FILE_VIEW *view = VIRTUAL_FirstView;
818 UINT32 base = ROUND_ADDR( addr );
819 UINT32 alloc_base = 0;
820 UINT32 size = 0;
822 /* Find the view containing the address */
824 for (;;)
826 if (!view)
828 size = 0xffff0000 - alloc_base;
829 break;
831 if (view->base > base)
833 size = view->base - alloc_base;
834 view = NULL;
835 break;
837 if (view->base + view->size > base)
839 alloc_base = view->base;
840 size = view->size;
841 break;
843 alloc_base = view->base + view->size;
844 view = view->next;
847 /* Fill the info structure */
849 if (!view)
851 info->State = MEM_FREE;
852 info->Protect = 0;
853 info->AllocationProtect = 0;
854 info->Type = 0;
856 else
858 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
859 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
860 for (size = base - alloc_base; size < view->size; size += page_mask+1)
861 if (view->prot[size >> page_shift] != vprot) break;
862 info->AllocationProtect = view->protect;
863 info->Type = MEM_PRIVATE; /* FIXME */
866 info->BaseAddress = (LPVOID)base;
867 info->AllocationBase = (LPVOID)alloc_base;
868 info->RegionSize = size - (base - alloc_base);
869 return sizeof(*info);
873 /***********************************************************************
874 * VirtualQueryEx (KERNEL32.555)
875 * Provides info about a range of pages in virtual address space of a
876 * specified process
878 * RETURNS
879 * Number of bytes returned in information buffer
881 DWORD WINAPI VirtualQueryEx(
882 HANDLE32 handle, /* [in] Handle of process */
883 LPCVOID addr, /* [in] Address of region */
884 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
885 DWORD len /* [in] Size of buffer */
887 DWORD ret = len;
889 PDB32 *pdb = PROCESS_GetPtr( handle, PROCESS_QUERY_INFORMATION );
890 if (pdb)
892 if (pdb == PROCESS_Current())
893 ret = VirtualQuery( addr, info, len );
894 else
895 ERR(virtual,"Unsupported on other process\n");
896 K32OBJ_DecCount( &pdb->header );
898 return ret;
902 /***********************************************************************
903 * IsBadReadPtr32 (KERNEL32.354)
905 * RETURNS
906 * FALSE: Process has read access to entire block
907 * TRUE: Otherwise
909 BOOL32 WINAPI IsBadReadPtr32(
910 LPCVOID ptr, /* Address of memory block */
911 UINT32 size /* Size of block */
913 return !VIRTUAL_CheckFlags( (UINT32)ptr, size,
914 VPROT_READ | VPROT_COMMITTED );
918 /***********************************************************************
919 * IsBadWritePtr32 (KERNEL32.357)
921 * RETURNS
922 * FALSE: Process has write access to entire block
923 * TRUE: Otherwise
925 BOOL32 WINAPI IsBadWritePtr32(
926 LPVOID ptr, /* [in] Address of memory block */
927 UINT32 size /* [in] Size of block in bytes */
929 return !VIRTUAL_CheckFlags( (UINT32)ptr, size,
930 VPROT_WRITE | VPROT_COMMITTED );
934 /***********************************************************************
935 * IsBadHugeReadPtr32 (KERNEL32.352)
936 * RETURNS
937 * FALSE: Process has read access to entire block
938 * TRUE: Otherwise
940 BOOL32 WINAPI IsBadHugeReadPtr32(
941 LPCVOID ptr, /* [in] Address of memory block */
942 UINT32 size /* [in] Size of block */
944 return IsBadReadPtr32( ptr, size );
948 /***********************************************************************
949 * IsBadHugeWritePtr32 (KERNEL32.353)
950 * RETURNS
951 * FALSE: Process has write access to entire block
952 * TRUE: Otherwise
954 BOOL32 WINAPI IsBadHugeWritePtr32(
955 LPVOID ptr, /* [in] Address of memory block */
956 UINT32 size /* [in] Size of block */
958 return IsBadWritePtr32( ptr, size );
962 /***********************************************************************
963 * IsBadCodePtr32 (KERNEL32.351)
965 * RETURNS
966 * FALSE: Process has read access to specified memory
967 * TRUE: Otherwise
969 BOOL32 WINAPI IsBadCodePtr32(
970 FARPROC32 ptr /* [in] Address of function */
972 return !VIRTUAL_CheckFlags( (UINT32)ptr, 1, VPROT_EXEC | VPROT_COMMITTED );
976 /***********************************************************************
977 * IsBadStringPtr32A (KERNEL32.355)
979 * RETURNS
980 * FALSE: Read access to all bytes in string
981 * TRUE: Else
983 BOOL32 WINAPI IsBadStringPtr32A(
984 LPCSTR str, /* [in] Address of string */
985 UINT32 max /* [in] Maximum size of string */
987 FILE_VIEW *view;
988 UINT32 page, count;
990 if (!max) return FALSE;
991 if (!(view = VIRTUAL_FindView( (UINT32)str ))) return TRUE;
992 page = ((UINT32)str - view->base) >> page_shift;
993 count = page_mask + 1 - ((UINT32)str & page_mask);
995 while (max)
997 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
998 (VPROT_READ | VPROT_COMMITTED))
999 return TRUE;
1000 if (count > max) count = max;
1001 max -= count;
1002 while (count--) if (!*str++) return FALSE;
1003 if (++page >= view->size >> page_shift) return TRUE;
1004 count = page_mask + 1;
1006 return FALSE;
1010 /***********************************************************************
1011 * IsBadStringPtr32W (KERNEL32.356)
1012 * See IsBadStringPtr32A
1014 BOOL32 WINAPI IsBadStringPtr32W( LPCWSTR str, UINT32 max )
1016 FILE_VIEW *view;
1017 UINT32 page, count;
1019 if (!max) return FALSE;
1020 if (!(view = VIRTUAL_FindView( (UINT32)str ))) return TRUE;
1021 page = ((UINT32)str - view->base) >> page_shift;
1022 count = (page_mask + 1 - ((UINT32)str & page_mask)) / sizeof(WCHAR);
1024 while (max)
1026 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
1027 (VPROT_READ | VPROT_COMMITTED))
1028 return TRUE;
1029 if (count > max) count = max;
1030 max -= count;
1031 while (count--) if (!*str++) return FALSE;
1032 if (++page >= view->size >> page_shift) return TRUE;
1033 count = (page_mask + 1) / sizeof(WCHAR);
1035 return FALSE;
1039 /***********************************************************************
1040 * CreateFileMapping32A (KERNEL32.46)
1041 * Creates a named or unnamed file-mapping object for the specified file
1043 * RETURNS
1044 * Handle: Success
1045 * 0: Mapping object does not exist
1046 * NULL: Failure
1048 HANDLE32 WINAPI CreateFileMapping32A(
1049 HFILE32 hFile, /* [in] Handle of file to map */
1050 SECURITY_ATTRIBUTES *sa, /* [in] Optional security attributes*/
1051 DWORD protect, /* [in] Protection for mapping object */
1052 DWORD size_high, /* [in] High-order 32 bits of object size */
1053 DWORD size_low, /* [in] Low-order 32 bits of object size */
1054 LPCSTR name /* [in] Name of file-mapping object */ )
1056 FILE_MAPPING *mapping = NULL;
1057 HANDLE32 handle;
1058 BYTE vprot;
1059 BOOL32 inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1061 /* First search for an object with the same name */
1063 K32OBJ *obj = K32OBJ_FindName( name );
1064 if (obj)
1066 if (obj->type == K32OBJ_MEM_MAPPED_FILE)
1068 SetLastError( ERROR_ALREADY_EXISTS );
1069 handle = HANDLE_Alloc( PROCESS_Current(), obj,
1070 FILE_MAP_ALL_ACCESS /*FIXME*/, inherit );
1072 else
1074 SetLastError( ERROR_DUP_NAME );
1075 handle = 0;
1077 K32OBJ_DecCount( obj );
1078 return handle;
1081 /* Check parameters */
1083 TRACE(virtual,"(%x,%p,%08lx,%08lx%08lx,%s)\n",
1084 hFile, sa, protect, size_high, size_low, name );
1086 vprot = VIRTUAL_GetProt( protect );
1087 if (protect & SEC_RESERVE)
1089 if (hFile != INVALID_HANDLE_VALUE32)
1091 SetLastError( ERROR_INVALID_PARAMETER );
1092 return 0;
1095 else vprot |= VPROT_COMMITTED;
1096 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1098 /* Compute the size and extend the file if necessary */
1100 if (hFile == INVALID_HANDLE_VALUE32)
1102 if (!size_high && !size_low)
1104 SetLastError( ERROR_INVALID_PARAMETER );
1105 return 0;
1107 obj = NULL;
1109 else /* We have a file */
1111 BY_HANDLE_FILE_INFORMATION info;
1112 DWORD access = GENERIC_READ;
1114 if (((protect & 0xff) == PAGE_READWRITE) ||
1115 ((protect & 0xff) == PAGE_WRITECOPY) ||
1116 ((protect & 0xff) == PAGE_EXECUTE_READWRITE) ||
1117 ((protect & 0xff) == PAGE_EXECUTE_WRITECOPY))
1118 access |= GENERIC_WRITE;
1119 if (!(obj = HANDLE_GetObjPtr( PROCESS_Current(), hFile,
1120 K32OBJ_FILE, access )))
1121 goto error;
1123 if (!GetFileInformationByHandle( hFile, &info )) goto error;
1124 if (!size_high && !size_low)
1126 size_high = info.nFileSizeHigh;
1127 size_low = info.nFileSizeLow;
1129 else if ((size_high > info.nFileSizeHigh) ||
1130 ((size_high == info.nFileSizeHigh) &&
1131 (size_low > info.nFileSizeLow)))
1133 /* We have to grow the file */
1134 if (SetFilePointer( hFile, size_low, &size_high,
1135 FILE_BEGIN ) == 0xffffffff) goto error;
1136 if (!SetEndOfFile( hFile )) goto error;
1140 /* Allocate the mapping object */
1142 if (!(mapping = HeapAlloc( SystemHeap, 0, sizeof(*mapping) ))) goto error;
1143 mapping->header.type = K32OBJ_MEM_MAPPED_FILE;
1144 mapping->header.refcount = 1;
1145 mapping->protect = vprot;
1146 mapping->size_high = size_high;
1147 mapping->size_low = ROUND_SIZE( 0, size_low );
1148 mapping->file = (FILE_OBJECT *)obj;
1150 if (!K32OBJ_AddName( &mapping->header, name )) handle = 0;
1151 else handle = HANDLE_Alloc( PROCESS_Current(), &mapping->header,
1152 FILE_MAP_ALL_ACCESS /*FIXME*/, inherit );
1153 K32OBJ_DecCount( &mapping->header );
1154 return handle;
1156 error:
1157 if (obj) K32OBJ_DecCount( obj );
1158 if (mapping) HeapFree( SystemHeap, 0, mapping );
1159 return 0;
1163 /***********************************************************************
1164 * CreateFileMapping32W (KERNEL32.47)
1165 * See CreateFileMapping32A
1167 HANDLE32 WINAPI CreateFileMapping32W( HFILE32 hFile, LPSECURITY_ATTRIBUTES attr,
1168 DWORD protect, DWORD size_high,
1169 DWORD size_low, LPCWSTR name )
1171 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1172 HANDLE32 ret = CreateFileMapping32A( hFile, attr, protect,
1173 size_high, size_low, nameA );
1174 HeapFree( GetProcessHeap(), 0, nameA );
1175 return ret;
1179 /***********************************************************************
1180 * OpenFileMapping32A (KERNEL32.397)
1181 * Opens a named file-mapping object.
1183 * RETURNS
1184 * Handle: Success
1185 * NULL: Failure
1187 HANDLE32 WINAPI OpenFileMapping32A(
1188 DWORD access, /* [in] Access mode */
1189 BOOL32 inherit, /* [in] Inherit flag */
1190 LPCSTR name /* [in] Name of file-mapping object */
1192 HANDLE32 handle = 0;
1193 K32OBJ *obj;
1194 SYSTEM_LOCK();
1195 if ((obj = K32OBJ_FindNameType( name, K32OBJ_MEM_MAPPED_FILE )))
1197 handle = HANDLE_Alloc( PROCESS_Current(), obj, access, inherit );
1198 K32OBJ_DecCount( obj );
1200 SYSTEM_UNLOCK();
1201 return handle;
1205 /***********************************************************************
1206 * OpenFileMapping32W (KERNEL32.398)
1207 * See OpenFileMapping32A
1209 HANDLE32 WINAPI OpenFileMapping32W( DWORD access, BOOL32 inherit, LPCWSTR name)
1211 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1212 HANDLE32 ret = OpenFileMapping32A( access, inherit, nameA );
1213 HeapFree( GetProcessHeap(), 0, nameA );
1214 return ret;
1218 /***********************************************************************
1219 * VIRTUAL_DestroyMapping
1221 * Destroy a FILE_MAPPING object.
1223 static void VIRTUAL_DestroyMapping( K32OBJ *ptr )
1225 FILE_MAPPING *mapping = (FILE_MAPPING *)ptr;
1226 assert( ptr->type == K32OBJ_MEM_MAPPED_FILE );
1228 if (mapping->file) K32OBJ_DecCount( &mapping->file->header );
1229 ptr->type = K32OBJ_UNKNOWN;
1230 HeapFree( SystemHeap, 0, mapping );
1234 /***********************************************************************
1235 * MapViewOfFile (KERNEL32.385)
1236 * Maps a view of a file into the address space
1238 * RETURNS
1239 * Starting address of mapped view
1240 * NULL: Failure
1242 LPVOID WINAPI MapViewOfFile(
1243 HANDLE32 mapping, /* [in] File-mapping object to map */
1244 DWORD access, /* [in] Access mode */
1245 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1246 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1247 DWORD count /* [in] Number of bytes to map */
1249 return MapViewOfFileEx( mapping, access, offset_high,
1250 offset_low, count, NULL );
1254 /***********************************************************************
1255 * MapViewOfFileEx (KERNEL32.386)
1256 * Maps a view of a file into the address space
1258 * RETURNS
1259 * Starting address of mapped view
1260 * NULL: Failure
1262 LPVOID WINAPI MapViewOfFileEx(
1263 HANDLE32 handle, /* [in] File-mapping object to map */
1264 DWORD access, /* [in] Access mode */
1265 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1266 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1267 DWORD count, /* [in] Number of bytes to map */
1268 LPVOID addr /* [in] Suggested starting address for mapped view */
1270 FILE_MAPPING *mapping;
1271 FILE_VIEW *view;
1272 UINT32 ptr = (UINT32)-1, size = 0;
1273 int flags = MAP_PRIVATE;
1275 /* Check parameters */
1277 if ((offset_low & granularity_mask) ||
1278 (addr && ((UINT32)addr & granularity_mask)))
1280 SetLastError( ERROR_INVALID_PARAMETER );
1281 return NULL;
1284 if (!(mapping = (FILE_MAPPING *)HANDLE_GetObjPtr( PROCESS_Current(),
1285 handle,
1286 K32OBJ_MEM_MAPPED_FILE,
1287 0 /* FIXME */ )))
1288 return NULL;
1290 if (mapping->size_high || offset_high)
1291 ERR(virtual, "Offsets larger than 4Gb not supported\n");
1293 if ((offset_low >= mapping->size_low) ||
1294 (count > mapping->size_low - offset_low))
1296 SetLastError( ERROR_INVALID_PARAMETER );
1297 goto error;
1299 if (count) size = ROUND_SIZE( offset_low, count );
1300 else size = mapping->size_low - offset_low;
1302 switch(access)
1304 case FILE_MAP_ALL_ACCESS:
1305 case FILE_MAP_WRITE:
1306 case FILE_MAP_WRITE | FILE_MAP_READ:
1307 if (!(mapping->protect & VPROT_WRITE))
1309 SetLastError( ERROR_INVALID_PARAMETER );
1310 goto error;
1312 flags = MAP_SHARED;
1313 /* fall through */
1314 case FILE_MAP_READ:
1315 case FILE_MAP_COPY:
1316 case FILE_MAP_COPY | FILE_MAP_READ:
1317 if (mapping->protect & VPROT_READ) break;
1318 /* fall through */
1319 default:
1320 SetLastError( ERROR_INVALID_PARAMETER );
1321 goto error;
1324 /* Map the file */
1326 TRACE(virtual, "handle=%x size=%x offset=%lx\n",
1327 handle, size, offset_low );
1329 ptr = (UINT32)FILE_dommap( mapping->file, addr, 0, size, 0, offset_low,
1330 VIRTUAL_GetUnixProt( mapping->protect ),
1331 flags );
1332 if (ptr == (UINT32)-1)
1334 SetLastError( ERROR_OUTOFMEMORY );
1335 goto error;
1338 if (!(view = VIRTUAL_CreateView( ptr, size, offset_low, 0,
1339 mapping->protect, mapping )))
1341 SetLastError( ERROR_OUTOFMEMORY );
1342 goto error;
1344 return (LPVOID)ptr;
1346 error:
1347 if (ptr != (UINT32)-1) FILE_munmap( (void *)ptr, 0, size );
1348 K32OBJ_DecCount( &mapping->header );
1349 return NULL;
1353 /***********************************************************************
1354 * FlushViewOfFile (KERNEL32.262)
1355 * Writes to the disk a byte range within a mapped view of a file
1357 * RETURNS
1358 * TRUE: Success
1359 * FALSE: Failure
1361 BOOL32 WINAPI FlushViewOfFile(
1362 LPCVOID base, /* [in] Start address of byte range to flush */
1363 DWORD cbFlush /* [in] Number of bytes in range */
1365 FILE_VIEW *view;
1366 UINT32 addr = ROUND_ADDR( base );
1368 TRACE(virtual, "FlushViewOfFile at %p for %ld bytes\n",
1369 base, cbFlush );
1371 if (!(view = VIRTUAL_FindView( addr )))
1373 SetLastError( ERROR_INVALID_PARAMETER );
1374 return FALSE;
1376 if (!cbFlush) cbFlush = view->size;
1377 if (!msync( (void *)addr, cbFlush, MS_SYNC )) return TRUE;
1378 SetLastError( ERROR_INVALID_PARAMETER );
1379 return FALSE;
1383 /***********************************************************************
1384 * UnmapViewOfFile (KERNEL32.540)
1385 * Unmaps a mapped view of a file.
1387 * NOTES
1388 * Should addr be an LPCVOID?
1390 * RETURNS
1391 * TRUE: Success
1392 * FALSE: Failure
1394 BOOL32 WINAPI UnmapViewOfFile(
1395 LPVOID addr /* [in] Address where mapped view begins */
1397 FILE_VIEW *view;
1398 UINT32 base = ROUND_ADDR( addr );
1399 if (!(view = VIRTUAL_FindView( base )) || (base != view->base))
1401 SetLastError( ERROR_INVALID_PARAMETER );
1402 return FALSE;
1404 VIRTUAL_DeleteView( view );
1405 return TRUE;