Added winemine app.
[wine.git] / memory / virtual.c
blobe373ff4544ade627c10f84e739dc55bb0cbe5b10
1 /*
2 * Win32 virtual memory functions
4 * Copyright 1997 Alexandre Julliard
5 */
7 #include "config.h"
9 #include <assert.h>
10 #include <errno.h>
11 #ifdef HAVE_SYS_ERRNO_H
12 #include <sys/errno.h>
13 #endif
14 #include <fcntl.h>
15 #include <unistd.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <sys/types.h>
20 #ifdef HAVE_SYS_MMAN_H
21 #include <sys/mman.h>
22 #endif
23 #include "winbase.h"
24 #include "winerror.h"
25 #include "file.h"
26 #include "process.h"
27 #include "xmalloc.h"
28 #include "global.h"
29 #include "server.h"
30 #include "debugtools.h"
32 DEFAULT_DEBUG_CHANNEL(virtual);
34 #ifndef MS_SYNC
35 #define MS_SYNC 0
36 #endif
38 /* File view */
39 typedef struct _FV
41 struct _FV *next; /* Next view */
42 struct _FV *prev; /* Prev view */
43 UINT base; /* Base address */
44 UINT size; /* Size in bytes */
45 UINT flags; /* Allocation flags */
46 UINT offset; /* Offset from start of mapped file */
47 HANDLE mapping; /* Handle to the file mapping */
48 HANDLERPROC handlerProc; /* Fault handler */
49 LPVOID handlerArg; /* Fault handler argument */
50 BYTE protect; /* Protection for all pages at allocation time */
51 BYTE prot[1]; /* Protection byte for each page */
52 } FILE_VIEW;
54 /* Per-view flags */
55 #define VFLAG_SYSTEM 0x01
57 /* Conversion from VPROT_* to Win32 flags */
58 static const BYTE VIRTUAL_Win32Flags[16] =
60 PAGE_NOACCESS, /* 0 */
61 PAGE_READONLY, /* READ */
62 PAGE_READWRITE, /* WRITE */
63 PAGE_READWRITE, /* READ | WRITE */
64 PAGE_EXECUTE, /* EXEC */
65 PAGE_EXECUTE_READ, /* READ | EXEC */
66 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
67 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
68 PAGE_WRITECOPY, /* WRITECOPY */
69 PAGE_WRITECOPY, /* READ | WRITECOPY */
70 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
71 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
72 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
73 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
74 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
75 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
79 static FILE_VIEW *VIRTUAL_FirstView;
81 #ifdef __i386__
82 /* These are always the same on an i386, and it will be faster this way */
83 # define page_mask 0xfff
84 # define page_shift 12
85 # define granularity_mask 0xffff
86 #else
87 static UINT page_shift;
88 static UINT page_mask;
89 static UINT granularity_mask; /* Allocation granularity (usually 64k) */
90 #endif /* __i386__ */
92 #define ROUND_ADDR(addr) \
93 ((UINT)(addr) & ~page_mask)
95 #define ROUND_SIZE(addr,size) \
96 (((UINT)(size) + ((UINT)(addr) & page_mask) + page_mask) & ~page_mask)
98 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
99 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
101 /***********************************************************************
102 * VIRTUAL_GetProtStr
104 static const char *VIRTUAL_GetProtStr( BYTE prot )
106 static char buffer[6];
107 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
108 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
109 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
110 buffer[3] = (prot & VPROT_WRITE) ?
111 ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
112 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
113 buffer[5] = 0;
114 return buffer;
118 /***********************************************************************
119 * VIRTUAL_DumpView
121 static void VIRTUAL_DumpView( FILE_VIEW *view )
123 UINT i, count;
124 UINT addr = view->base;
125 BYTE prot = view->prot[0];
127 DPRINTF( "View: %08x - %08x%s",
128 view->base, view->base + view->size - 1,
129 (view->flags & VFLAG_SYSTEM) ? " (system)" : "" );
130 if (view->mapping)
131 DPRINTF( " %d @ %08x\n", view->mapping, view->offset );
132 else
133 DPRINTF( " (anonymous)\n");
135 for (count = i = 1; i < view->size >> page_shift; i++, count++)
137 if (view->prot[i] == prot) continue;
138 DPRINTF( " %08x - %08x %s\n",
139 addr, addr + (count << page_shift) - 1,
140 VIRTUAL_GetProtStr(prot) );
141 addr += (count << page_shift);
142 prot = view->prot[i];
143 count = 0;
145 if (count)
146 DPRINTF( " %08x - %08x %s\n",
147 addr, addr + (count << page_shift) - 1,
148 VIRTUAL_GetProtStr(prot) );
152 /***********************************************************************
153 * VIRTUAL_Dump
155 void VIRTUAL_Dump(void)
157 FILE_VIEW *view = VIRTUAL_FirstView;
158 DPRINTF( "\nDump of all virtual memory views:\n\n" );
159 while (view)
161 VIRTUAL_DumpView( view );
162 view = view->next;
167 /***********************************************************************
168 * VIRTUAL_FindView
170 * Find the view containing a given address.
172 * RETURNS
173 * View: Success
174 * NULL: Failure
176 static FILE_VIEW *VIRTUAL_FindView(
177 UINT addr /* [in] Address */
179 FILE_VIEW *view = VIRTUAL_FirstView;
180 while (view)
182 if (view->base > addr) return NULL;
183 if (view->base + view->size > addr) return view;
184 view = view->next;
186 return NULL;
190 /***********************************************************************
191 * VIRTUAL_CreateView
193 * Create a new view and add it in the linked list.
195 static FILE_VIEW *VIRTUAL_CreateView( UINT base, UINT size, UINT offset,
196 UINT flags, BYTE vprot,
197 HANDLE mapping )
199 FILE_VIEW *view, *prev;
201 /* Create the view structure */
203 assert( !(base & page_mask) );
204 assert( !(size & page_mask) );
205 size >>= page_shift;
206 if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
207 view->base = base;
208 view->size = size << page_shift;
209 view->flags = flags;
210 view->offset = offset;
211 view->mapping = mapping;
212 view->protect = vprot;
213 view->handlerProc = NULL;
214 memset( view->prot, vprot, size );
216 /* Duplicate the mapping handle */
218 if ((view->mapping != -1) &&
219 !DuplicateHandle( GetCurrentProcess(), view->mapping,
220 GetCurrentProcess(), &view->mapping,
221 0, FALSE, DUPLICATE_SAME_ACCESS ))
223 free( view );
224 return NULL;
227 /* Insert it in the linked list */
229 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
231 view->next = VIRTUAL_FirstView;
232 view->prev = NULL;
233 if (view->next) view->next->prev = view;
234 VIRTUAL_FirstView = view;
236 else
238 prev = VIRTUAL_FirstView;
239 while (prev->next && (prev->next->base < base)) prev = prev->next;
240 view->next = prev->next;
241 view->prev = prev;
242 if (view->next) view->next->prev = view;
243 prev->next = view;
245 VIRTUAL_DEBUG_DUMP_VIEW( view );
246 return view;
250 /***********************************************************************
251 * VIRTUAL_DeleteView
252 * Deletes a view.
254 * RETURNS
255 * None
257 static void VIRTUAL_DeleteView(
258 FILE_VIEW *view /* [in] View */
260 FILE_munmap( (void *)view->base, 0, view->size );
261 if (view->next) view->next->prev = view->prev;
262 if (view->prev) view->prev->next = view->next;
263 else VIRTUAL_FirstView = view->next;
264 if (view->mapping) CloseHandle( view->mapping );
265 free( view );
269 /***********************************************************************
270 * VIRTUAL_GetUnixProt
272 * Convert page protections to protection for mmap/mprotect.
274 static int VIRTUAL_GetUnixProt( BYTE vprot )
276 int prot = 0;
277 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
279 if (vprot & VPROT_READ) prot |= PROT_READ;
280 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
281 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
283 return prot;
287 /***********************************************************************
288 * VIRTUAL_GetWin32Prot
290 * Convert page protections to Win32 flags.
292 * RETURNS
293 * None
295 static void VIRTUAL_GetWin32Prot(
296 BYTE vprot, /* [in] Page protection flags */
297 DWORD *protect, /* [out] Location to store Win32 protection flags */
298 DWORD *state /* [out] Location to store mem state flag */
300 if (protect) {
301 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
302 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
303 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
305 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
308 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
312 /***********************************************************************
313 * VIRTUAL_GetProt
315 * Build page protections from Win32 flags.
317 * RETURNS
318 * Value of page protection flags
320 static BYTE VIRTUAL_GetProt(
321 DWORD protect /* [in] Win32 protection flags */
323 BYTE vprot;
325 switch(protect & 0xff)
327 case PAGE_READONLY:
328 vprot = VPROT_READ;
329 break;
330 case PAGE_READWRITE:
331 vprot = VPROT_READ | VPROT_WRITE;
332 break;
333 case PAGE_WRITECOPY:
334 vprot = VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
335 break;
336 case PAGE_EXECUTE:
337 vprot = VPROT_EXEC;
338 break;
339 case PAGE_EXECUTE_READ:
340 vprot = VPROT_EXEC | VPROT_READ;
341 break;
342 case PAGE_EXECUTE_READWRITE:
343 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
344 break;
345 case PAGE_EXECUTE_WRITECOPY:
346 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
347 break;
348 case PAGE_NOACCESS:
349 default:
350 vprot = 0;
351 break;
353 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
354 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
355 return vprot;
359 /***********************************************************************
360 * VIRTUAL_SetProt
362 * Change the protection of a range of pages.
364 * RETURNS
365 * TRUE: Success
366 * FALSE: Failure
368 static BOOL VIRTUAL_SetProt(
369 FILE_VIEW *view, /* [in] Pointer to view */
370 UINT base, /* [in] Starting address */
371 UINT size, /* [in] Size in bytes */
372 BYTE vprot /* [in] Protections to use */
374 TRACE("%08x-%08x %s\n",
375 base, base + size - 1, VIRTUAL_GetProtStr( vprot ) );
377 if (mprotect( (void *)base, size, VIRTUAL_GetUnixProt(vprot) ))
378 return FALSE; /* FIXME: last error */
380 memset( view->prot + ((base - view->base) >> page_shift),
381 vprot, size >> page_shift );
382 VIRTUAL_DEBUG_DUMP_VIEW( view );
383 return TRUE;
387 /***********************************************************************
388 * VIRTUAL_CheckFlags
390 * Check that all pages in a range have the given flags.
392 * RETURNS
393 * TRUE: They do
394 * FALSE: They do not
396 static BOOL VIRTUAL_CheckFlags(
397 UINT base, /* [in] Starting address */
398 UINT size, /* [in] Size in bytes */
399 BYTE flags /* [in] Flags to check for */
401 FILE_VIEW *view;
402 UINT page;
404 if (!size) return TRUE;
405 if (!(view = VIRTUAL_FindView( base ))) return FALSE;
406 if (view->base + view->size < base + size) return FALSE;
407 page = (base - view->base) >> page_shift;
408 size = ROUND_SIZE( base, size ) >> page_shift;
409 while (size--) if ((view->prot[page++] & flags) != flags) return FALSE;
410 return TRUE;
414 /***********************************************************************
415 * VIRTUAL_Init
417 BOOL VIRTUAL_Init(void)
419 #ifndef __i386__
420 DWORD page_size;
422 # ifdef HAVE_GETPAGESIZE
423 page_size = getpagesize();
424 # else
425 # ifdef __svr4__
426 page_size = sysconf(_SC_PAGESIZE);
427 # else
428 # error Cannot get the page size on this platform
429 # endif
430 # endif
431 page_mask = page_size - 1;
432 granularity_mask = 0xffff; /* hard-coded for now */
433 /* Make sure we have a power of 2 */
434 assert( !(page_size & page_mask) );
435 page_shift = 0;
436 while ((1 << page_shift) != page_size) page_shift++;
437 #endif /* !__i386__ */
439 #ifdef linux
441 /* Do not use stdio here since it may temporarily change the size
442 * of some segments (ie libc6 adds 0x1000 per open FILE)
444 int fd = open ("/proc/self/maps", O_RDONLY);
445 if (fd >= 0)
447 char buffer[512]; /* line might be rather long in 2.1 */
449 for (;;)
451 int start, end, offset;
452 char r, w, x, p;
453 BYTE vprot = VPROT_COMMITTED;
455 char * ptr = buffer;
456 int count = sizeof(buffer);
457 while (1 == read(fd, ptr, 1) && *ptr != '\n' && --count > 0)
458 ptr++;
460 if (*ptr != '\n') break;
461 *ptr = '\0';
463 sscanf( buffer, "%x-%x %c%c%c%c %x",
464 &start, &end, &r, &w, &x, &p, &offset );
465 if (r == 'r') vprot |= VPROT_READ;
466 if (w == 'w') vprot |= VPROT_WRITE;
467 if (x == 'x') vprot |= VPROT_EXEC;
468 if (p == 'p') vprot |= VPROT_WRITECOPY;
469 VIRTUAL_CreateView( start, end - start, 0,
470 VFLAG_SYSTEM, vprot, -1 );
472 close (fd);
475 #endif /* linux */
476 return TRUE;
480 /***********************************************************************
481 * VIRTUAL_GetPageSize
483 DWORD VIRTUAL_GetPageSize(void)
485 return 1 << page_shift;
489 /***********************************************************************
490 * VIRTUAL_GetGranularity
492 DWORD VIRTUAL_GetGranularity(void)
494 return granularity_mask + 1;
498 /***********************************************************************
499 * VIRTUAL_SetFaultHandler
501 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
503 FILE_VIEW *view;
505 if (!(view = VIRTUAL_FindView((UINT)addr))) return FALSE;
506 view->handlerProc = proc;
507 view->handlerArg = arg;
508 return TRUE;
511 /***********************************************************************
512 * VIRTUAL_HandleFault
514 BOOL VIRTUAL_HandleFault( LPCVOID addr )
516 FILE_VIEW *view = VIRTUAL_FindView((UINT)addr);
518 if (view && view->handlerProc)
519 return view->handlerProc(view->handlerArg, addr);
520 return FALSE;
524 /***********************************************************************
525 * VirtualAlloc (KERNEL32.548)
526 * Reserves or commits a region of pages in virtual address space
528 * RETURNS
529 * Base address of allocated region of pages
530 * NULL: Failure
532 LPVOID WINAPI VirtualAlloc(
533 LPVOID addr, /* [in] Address of region to reserve or commit */
534 DWORD size, /* [in] Size of region */
535 DWORD type, /* [in] Type of allocation */
536 DWORD protect /* [in] Type of access protection */
538 FILE_VIEW *view;
539 UINT base, ptr, view_size;
540 BYTE vprot;
542 TRACE("%08x %08lx %lx %08lx\n",
543 (UINT)addr, size, type, protect );
545 /* Round parameters to a page boundary */
547 if (size > 0x7fc00000) /* 2Gb - 4Mb */
549 SetLastError( ERROR_OUTOFMEMORY );
550 return NULL;
552 if (addr)
554 if (type & MEM_RESERVE) /* Round down to 64k boundary */
555 base = (UINT)addr & ~granularity_mask;
556 else
557 base = ROUND_ADDR( addr );
558 size = (((UINT)addr + size + page_mask) & ~page_mask) - base;
559 if ((base <= granularity_mask) || (base + size < base))
561 /* disallow low 64k and wrap-around */
562 SetLastError( ERROR_INVALID_PARAMETER );
563 return NULL;
566 else
568 base = 0;
569 size = (size + page_mask) & ~page_mask;
572 if (type & MEM_TOP_DOWN) {
573 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
574 * Is there _ANY_ way to do it with UNIX mmap()?
576 WARN("MEM_TOP_DOWN ignored\n");
577 type &= ~MEM_TOP_DOWN;
579 /* Compute the protection flags */
581 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
582 (type & ~(MEM_COMMIT | MEM_RESERVE)))
584 SetLastError( ERROR_INVALID_PARAMETER );
585 return NULL;
587 if (type & MEM_COMMIT)
588 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
589 else vprot = 0;
591 /* Reserve the memory */
593 if ((type & MEM_RESERVE) || !base)
595 view_size = size + (base ? 0 : granularity_mask + 1);
596 ptr = (UINT)FILE_dommap( -1, (LPVOID)base, 0, view_size, 0, 0,
597 VIRTUAL_GetUnixProt( vprot ), MAP_PRIVATE );
598 if (ptr == (UINT)-1)
600 SetLastError( ERROR_OUTOFMEMORY );
601 return NULL;
603 if (!base)
605 /* Release the extra memory while keeping the range */
606 /* starting on a 64k boundary. */
608 if (ptr & granularity_mask)
610 UINT extra = granularity_mask + 1 - (ptr & granularity_mask);
611 FILE_munmap( (void *)ptr, 0, extra );
612 ptr += extra;
613 view_size -= extra;
615 if (view_size > size)
616 FILE_munmap( (void *)(ptr + size), 0, view_size - size );
618 else if (ptr != base)
620 /* We couldn't get the address we wanted */
621 FILE_munmap( (void *)ptr, 0, view_size );
622 SetLastError( ERROR_INVALID_ADDRESS );
623 return NULL;
625 if (!(view = VIRTUAL_CreateView( ptr, size, 0, 0, vprot, -1 )))
627 FILE_munmap( (void *)ptr, 0, size );
628 SetLastError( ERROR_OUTOFMEMORY );
629 return NULL;
631 VIRTUAL_DEBUG_DUMP_VIEW( view );
632 return (LPVOID)ptr;
635 /* Commit the pages */
637 if (!(view = VIRTUAL_FindView( base )) ||
638 (base + size > view->base + view->size))
640 SetLastError( ERROR_INVALID_ADDRESS );
641 return NULL;
644 if (!VIRTUAL_SetProt( view, base, size, vprot )) return NULL;
645 return (LPVOID)base;
649 /***********************************************************************
650 * VirtualFree (KERNEL32.550)
651 * Release or decommits a region of pages in virtual address space.
653 * RETURNS
654 * TRUE: Success
655 * FALSE: Failure
657 BOOL WINAPI VirtualFree(
658 LPVOID addr, /* [in] Address of region of committed pages */
659 DWORD size, /* [in] Size of region */
660 DWORD type /* [in] Type of operation */
662 FILE_VIEW *view;
663 UINT base;
665 TRACE("%08x %08lx %lx\n",
666 (UINT)addr, size, type );
668 /* Fix the parameters */
670 size = ROUND_SIZE( addr, size );
671 base = ROUND_ADDR( addr );
673 if (!(view = VIRTUAL_FindView( base )) ||
674 (base + size > view->base + view->size))
676 SetLastError( ERROR_INVALID_PARAMETER );
677 return FALSE;
680 /* Compute the protection flags */
682 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
684 SetLastError( ERROR_INVALID_PARAMETER );
685 return FALSE;
688 /* Free the pages */
690 if (type == MEM_RELEASE)
692 if (size || (base != view->base))
694 SetLastError( ERROR_INVALID_PARAMETER );
695 return FALSE;
697 VIRTUAL_DeleteView( view );
698 return TRUE;
701 /* Decommit the pages by remapping zero-pages instead */
703 if (FILE_dommap( -1, (LPVOID)base, 0, size, 0, 0,
704 VIRTUAL_GetUnixProt( 0 ), MAP_PRIVATE|MAP_FIXED )
705 != (LPVOID)base)
706 ERR( "Could not remap pages, expect trouble\n" );
707 return VIRTUAL_SetProt( view, base, size, 0 );
711 /***********************************************************************
712 * VirtualLock (KERNEL32.551)
713 * Locks the specified region of virtual address space
715 * NOTE
716 * Always returns TRUE
718 * RETURNS
719 * TRUE: Success
720 * FALSE: Failure
722 BOOL WINAPI VirtualLock(
723 LPVOID addr, /* [in] Address of first byte of range to lock */
724 DWORD size /* [in] Number of bytes in range to lock */
726 return TRUE;
730 /***********************************************************************
731 * VirtualUnlock (KERNEL32.556)
732 * Unlocks a range of pages in the virtual address space
734 * NOTE
735 * Always returns TRUE
737 * RETURNS
738 * TRUE: Success
739 * FALSE: Failure
741 BOOL WINAPI VirtualUnlock(
742 LPVOID addr, /* [in] Address of first byte of range */
743 DWORD size /* [in] Number of bytes in range */
745 return TRUE;
749 /***********************************************************************
750 * VirtualProtect (KERNEL32.552)
751 * Changes the access protection on a region of committed pages
753 * RETURNS
754 * TRUE: Success
755 * FALSE: Failure
757 BOOL WINAPI VirtualProtect(
758 LPVOID addr, /* [in] Address of region of committed pages */
759 DWORD size, /* [in] Size of region */
760 DWORD new_prot, /* [in] Desired access protection */
761 LPDWORD old_prot /* [out] Address of variable to get old protection */
763 FILE_VIEW *view;
764 UINT base, i;
765 BYTE vprot, *p;
767 TRACE("%08x %08lx %08lx\n",
768 (UINT)addr, size, new_prot );
770 /* Fix the parameters */
772 size = ROUND_SIZE( addr, size );
773 base = ROUND_ADDR( addr );
775 if (!(view = VIRTUAL_FindView( base )) ||
776 (base + size > view->base + view->size))
778 SetLastError( ERROR_INVALID_PARAMETER );
779 return FALSE;
782 /* Make sure all the pages are committed */
784 p = view->prot + ((base - view->base) >> page_shift);
785 for (i = size >> page_shift; i; i--, p++)
787 if (!(*p & VPROT_COMMITTED))
789 SetLastError( ERROR_INVALID_PARAMETER );
790 return FALSE;
794 VIRTUAL_GetWin32Prot( view->prot[0], old_prot, NULL );
795 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
796 return VIRTUAL_SetProt( view, base, size, vprot );
800 /***********************************************************************
801 * VirtualProtectEx (KERNEL32.553)
802 * Changes the access protection on a region of committed pages in the
803 * virtual address space of a specified process
805 * RETURNS
806 * TRUE: Success
807 * FALSE: Failure
809 BOOL WINAPI VirtualProtectEx(
810 HANDLE handle, /* [in] Handle of process */
811 LPVOID addr, /* [in] Address of region of committed pages */
812 DWORD size, /* [in] Size of region */
813 DWORD new_prot, /* [in] Desired access protection */
814 LPDWORD old_prot /* [out] Address of variable to get old protection */ )
816 if (MapProcessHandle( handle ) == GetCurrentProcessId())
817 return VirtualProtect( addr, size, new_prot, old_prot );
818 ERR("Unsupported on other process\n");
819 return FALSE;
823 /***********************************************************************
824 * VirtualQuery (KERNEL32.554)
825 * Provides info about a range of pages in virtual address space
827 * RETURNS
828 * Number of bytes returned in information buffer
830 DWORD WINAPI VirtualQuery(
831 LPCVOID addr, /* [in] Address of region */
832 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
833 DWORD len /* [in] Size of buffer */
835 FILE_VIEW *view = VIRTUAL_FirstView;
836 UINT base = ROUND_ADDR( addr );
837 UINT alloc_base = 0;
838 UINT size = 0;
840 /* Find the view containing the address */
842 for (;;)
844 if (!view)
846 size = 0xffff0000 - alloc_base;
847 break;
849 if (view->base > base)
851 size = view->base - alloc_base;
852 view = NULL;
853 break;
855 if (view->base + view->size > base)
857 alloc_base = view->base;
858 size = view->size;
859 break;
861 alloc_base = view->base + view->size;
862 view = view->next;
865 /* Fill the info structure */
867 if (!view)
869 info->State = MEM_FREE;
870 info->Protect = 0;
871 info->AllocationProtect = 0;
872 info->Type = 0;
874 else
876 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
877 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
878 for (size = base - alloc_base; size < view->size; size += page_mask+1)
879 if (view->prot[size >> page_shift] != vprot) break;
880 info->AllocationProtect = view->protect;
881 info->Type = MEM_PRIVATE; /* FIXME */
884 info->BaseAddress = (LPVOID)base;
885 info->AllocationBase = (LPVOID)alloc_base;
886 info->RegionSize = size - (base - alloc_base);
887 return sizeof(*info);
891 /***********************************************************************
892 * VirtualQueryEx (KERNEL32.555)
893 * Provides info about a range of pages in virtual address space of a
894 * specified process
896 * RETURNS
897 * Number of bytes returned in information buffer
899 DWORD WINAPI VirtualQueryEx(
900 HANDLE handle, /* [in] Handle of process */
901 LPCVOID addr, /* [in] Address of region */
902 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
903 DWORD len /* [in] Size of buffer */ )
905 if (MapProcessHandle( handle ) == GetCurrentProcessId())
906 return VirtualQuery( addr, info, len );
907 ERR("Unsupported on other process\n");
908 return 0;
912 /***********************************************************************
913 * IsBadReadPtr32 (KERNEL32.354)
915 * RETURNS
916 * FALSE: Process has read access to entire block
917 * TRUE: Otherwise
919 BOOL WINAPI IsBadReadPtr(
920 LPCVOID ptr, /* Address of memory block */
921 UINT size /* Size of block */
923 return !VIRTUAL_CheckFlags( (UINT)ptr, size,
924 VPROT_READ | VPROT_COMMITTED );
928 /***********************************************************************
929 * IsBadWritePtr32 (KERNEL32.357)
931 * RETURNS
932 * FALSE: Process has write access to entire block
933 * TRUE: Otherwise
935 BOOL WINAPI IsBadWritePtr(
936 LPVOID ptr, /* [in] Address of memory block */
937 UINT size /* [in] Size of block in bytes */
939 return !VIRTUAL_CheckFlags( (UINT)ptr, size,
940 VPROT_WRITE | VPROT_COMMITTED );
944 /***********************************************************************
945 * IsBadHugeReadPtr32 (KERNEL32.352)
946 * RETURNS
947 * FALSE: Process has read access to entire block
948 * TRUE: Otherwise
950 BOOL WINAPI IsBadHugeReadPtr(
951 LPCVOID ptr, /* [in] Address of memory block */
952 UINT size /* [in] Size of block */
954 return IsBadReadPtr( ptr, size );
958 /***********************************************************************
959 * IsBadHugeWritePtr32 (KERNEL32.353)
960 * RETURNS
961 * FALSE: Process has write access to entire block
962 * TRUE: Otherwise
964 BOOL WINAPI IsBadHugeWritePtr(
965 LPVOID ptr, /* [in] Address of memory block */
966 UINT size /* [in] Size of block */
968 return IsBadWritePtr( ptr, size );
972 /***********************************************************************
973 * IsBadCodePtr32 (KERNEL32.351)
975 * RETURNS
976 * FALSE: Process has read access to specified memory
977 * TRUE: Otherwise
979 BOOL WINAPI IsBadCodePtr(
980 FARPROC ptr /* [in] Address of function */
982 return !VIRTUAL_CheckFlags( (UINT)ptr, 1, VPROT_EXEC | VPROT_COMMITTED );
986 /***********************************************************************
987 * IsBadStringPtr32A (KERNEL32.355)
989 * RETURNS
990 * FALSE: Read access to all bytes in string
991 * TRUE: Else
993 BOOL WINAPI IsBadStringPtrA(
994 LPCSTR str, /* [in] Address of string */
995 UINT max /* [in] Maximum size of string */
997 FILE_VIEW *view;
998 UINT page, count;
1000 if (!max) return FALSE;
1001 if (!(view = VIRTUAL_FindView( (UINT)str ))) return TRUE;
1002 page = ((UINT)str - view->base) >> page_shift;
1003 count = page_mask + 1 - ((UINT)str & page_mask);
1005 while (max)
1007 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
1008 (VPROT_READ | VPROT_COMMITTED))
1009 return TRUE;
1010 if (count > max) count = max;
1011 max -= count;
1012 while (count--) if (!*str++) return FALSE;
1013 if (++page >= view->size >> page_shift) return TRUE;
1014 count = page_mask + 1;
1016 return FALSE;
1020 /***********************************************************************
1021 * IsBadStringPtr32W (KERNEL32.356)
1022 * See IsBadStringPtr32A
1024 BOOL WINAPI IsBadStringPtrW( LPCWSTR str, UINT max )
1026 FILE_VIEW *view;
1027 UINT page, count;
1029 if (!max) return FALSE;
1030 if (!(view = VIRTUAL_FindView( (UINT)str ))) return TRUE;
1031 page = ((UINT)str - view->base) >> page_shift;
1032 count = (page_mask + 1 - ((UINT)str & page_mask)) / sizeof(WCHAR);
1034 while (max)
1036 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
1037 (VPROT_READ | VPROT_COMMITTED))
1038 return TRUE;
1039 if (count > max) count = max;
1040 max -= count;
1041 while (count--) if (!*str++) return FALSE;
1042 if (++page >= view->size >> page_shift) return TRUE;
1043 count = (page_mask + 1) / sizeof(WCHAR);
1045 return FALSE;
1049 /***********************************************************************
1050 * CreateFileMapping32A (KERNEL32.46)
1051 * Creates a named or unnamed file-mapping object for the specified file
1053 * RETURNS
1054 * Handle: Success
1055 * 0: Mapping object does not exist
1056 * NULL: Failure
1058 HANDLE WINAPI CreateFileMappingA(
1059 HFILE hFile, /* [in] Handle of file to map */
1060 SECURITY_ATTRIBUTES *sa, /* [in] Optional security attributes*/
1061 DWORD protect, /* [in] Protection for mapping object */
1062 DWORD size_high, /* [in] High-order 32 bits of object size */
1063 DWORD size_low, /* [in] Low-order 32 bits of object size */
1064 LPCSTR name /* [in] Name of file-mapping object */ )
1066 struct create_mapping_request *req = get_req_buffer();
1067 BYTE vprot;
1069 /* Check parameters */
1071 TRACE("(%x,%p,%08lx,%08lx%08lx,%s)\n",
1072 hFile, sa, protect, size_high, size_low, debugstr_a(name) );
1074 vprot = VIRTUAL_GetProt( protect );
1075 if (protect & SEC_RESERVE)
1077 if (hFile != INVALID_HANDLE_VALUE)
1079 SetLastError( ERROR_INVALID_PARAMETER );
1080 return 0;
1083 else vprot |= VPROT_COMMITTED;
1084 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1086 /* Create the server object */
1088 req->file_handle = hFile;
1089 req->size_high = size_high;
1090 req->size_low = size_low;
1091 req->protect = vprot;
1092 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1093 server_strcpyAtoW( req->name, name );
1094 SetLastError(0);
1095 server_call( REQ_CREATE_MAPPING );
1096 if (req->handle == -1) return 0;
1097 return req->handle;
1101 /***********************************************************************
1102 * CreateFileMapping32W (KERNEL32.47)
1103 * See CreateFileMapping32A
1105 HANDLE WINAPI CreateFileMappingW( HFILE hFile, LPSECURITY_ATTRIBUTES sa,
1106 DWORD protect, DWORD size_high,
1107 DWORD size_low, LPCWSTR name )
1109 struct create_mapping_request *req = get_req_buffer();
1110 BYTE vprot;
1112 /* Check parameters */
1114 TRACE("(%x,%p,%08lx,%08lx%08lx,%s)\n",
1115 hFile, sa, protect, size_high, size_low, debugstr_w(name) );
1117 vprot = VIRTUAL_GetProt( protect );
1118 if (protect & SEC_RESERVE)
1120 if (hFile != INVALID_HANDLE_VALUE)
1122 SetLastError( ERROR_INVALID_PARAMETER );
1123 return 0;
1126 else vprot |= VPROT_COMMITTED;
1127 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1129 /* Create the server object */
1131 req->file_handle = hFile;
1132 req->size_high = size_high;
1133 req->size_low = size_low;
1134 req->protect = vprot;
1135 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1136 server_strcpyW( req->name, name );
1137 SetLastError(0);
1138 server_call( REQ_CREATE_MAPPING );
1139 if (req->handle == -1) return 0;
1140 return req->handle;
1144 /***********************************************************************
1145 * OpenFileMapping32A (KERNEL32.397)
1146 * Opens a named file-mapping object.
1148 * RETURNS
1149 * Handle: Success
1150 * NULL: Failure
1152 HANDLE WINAPI OpenFileMappingA(
1153 DWORD access, /* [in] Access mode */
1154 BOOL inherit, /* [in] Inherit flag */
1155 LPCSTR name ) /* [in] Name of file-mapping object */
1157 struct open_mapping_request *req = get_req_buffer();
1159 req->access = access;
1160 req->inherit = inherit;
1161 server_strcpyAtoW( req->name, name );
1162 server_call( REQ_OPEN_MAPPING );
1163 if (req->handle == -1) return 0; /* must return 0 on failure, not -1 */
1164 return req->handle;
1168 /***********************************************************************
1169 * OpenFileMapping32W (KERNEL32.398)
1170 * See OpenFileMapping32A
1172 HANDLE WINAPI OpenFileMappingW( DWORD access, BOOL inherit, LPCWSTR name)
1174 struct open_mapping_request *req = get_req_buffer();
1176 req->access = access;
1177 req->inherit = inherit;
1178 server_strcpyW( req->name, name );
1179 server_call( REQ_OPEN_MAPPING );
1180 if (req->handle == -1) return 0; /* must return 0 on failure, not -1 */
1181 return req->handle;
1185 /***********************************************************************
1186 * MapViewOfFile (KERNEL32.385)
1187 * Maps a view of a file into the address space
1189 * RETURNS
1190 * Starting address of mapped view
1191 * NULL: Failure
1193 LPVOID WINAPI MapViewOfFile(
1194 HANDLE mapping, /* [in] File-mapping object to map */
1195 DWORD access, /* [in] Access mode */
1196 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1197 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1198 DWORD count /* [in] Number of bytes to map */
1200 return MapViewOfFileEx( mapping, access, offset_high,
1201 offset_low, count, NULL );
1205 /***********************************************************************
1206 * MapViewOfFileEx (KERNEL32.386)
1207 * Maps a view of a file into the address space
1209 * RETURNS
1210 * Starting address of mapped view
1211 * NULL: Failure
1213 LPVOID WINAPI MapViewOfFileEx(
1214 HANDLE handle, /* [in] File-mapping object to map */
1215 DWORD access, /* [in] Access mode */
1216 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1217 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1218 DWORD count, /* [in] Number of bytes to map */
1219 LPVOID addr /* [in] Suggested starting address for mapped view */
1221 FILE_VIEW *view;
1222 UINT ptr = (UINT)-1, size = 0;
1223 int flags = MAP_PRIVATE;
1224 int unix_handle = -1;
1225 int prot;
1226 struct get_mapping_info_request *req = get_req_buffer();
1228 /* Check parameters */
1230 if ((offset_low & granularity_mask) ||
1231 (addr && ((UINT)addr & granularity_mask)))
1233 SetLastError( ERROR_INVALID_PARAMETER );
1234 return NULL;
1237 req->handle = handle;
1238 if (server_call_fd( REQ_GET_MAPPING_INFO, -1, &unix_handle )) goto error;
1240 if (req->size_high || offset_high)
1241 ERR("Offsets larger than 4Gb not supported\n");
1243 if ((offset_low >= req->size_low) ||
1244 (count > req->size_low - offset_low))
1246 SetLastError( ERROR_INVALID_PARAMETER );
1247 goto error;
1249 if (count) size = ROUND_SIZE( offset_low, count );
1250 else size = req->size_low - offset_low;
1251 prot = req->protect;
1253 switch(access)
1255 case FILE_MAP_ALL_ACCESS:
1256 case FILE_MAP_WRITE:
1257 case FILE_MAP_WRITE | FILE_MAP_READ:
1258 if (!(prot & VPROT_WRITE))
1260 SetLastError( ERROR_INVALID_PARAMETER );
1261 goto error;
1263 flags = MAP_SHARED;
1264 /* fall through */
1265 case FILE_MAP_READ:
1266 case FILE_MAP_COPY:
1267 case FILE_MAP_COPY | FILE_MAP_READ:
1268 if (prot & VPROT_READ) break;
1269 /* fall through */
1270 default:
1271 SetLastError( ERROR_INVALID_PARAMETER );
1272 goto error;
1275 /* Map the file */
1277 TRACE("handle=%x size=%x offset=%lx\n", handle, size, offset_low );
1279 ptr = (UINT)FILE_dommap( unix_handle, addr, 0, size, 0, offset_low,
1280 VIRTUAL_GetUnixProt( prot ), flags );
1281 if (ptr == (UINT)-1) {
1282 /* KB: Q125713, 25-SEP-1995, "Common File Mapping Problems and
1283 * Platform Differences":
1284 * Windows NT: ERROR_INVALID_PARAMETER
1285 * Windows 95: ERROR_INVALID_ADDRESS.
1286 * FIXME: So should we add a module dependend check here? -MM
1288 if (errno==ENOMEM)
1289 SetLastError( ERROR_OUTOFMEMORY );
1290 else
1291 SetLastError( ERROR_INVALID_PARAMETER );
1292 goto error;
1295 if (!(view = VIRTUAL_CreateView( ptr, size, offset_low, 0, prot, handle )))
1297 SetLastError( ERROR_OUTOFMEMORY );
1298 goto error;
1300 if (unix_handle != -1) close( unix_handle );
1301 return (LPVOID)ptr;
1303 error:
1304 if (unix_handle != -1) close( unix_handle );
1305 if (ptr != (UINT)-1) FILE_munmap( (void *)ptr, 0, size );
1306 return NULL;
1310 /***********************************************************************
1311 * FlushViewOfFile (KERNEL32.262)
1312 * Writes to the disk a byte range within a mapped view of a file
1314 * RETURNS
1315 * TRUE: Success
1316 * FALSE: Failure
1318 BOOL WINAPI FlushViewOfFile(
1319 LPCVOID base, /* [in] Start address of byte range to flush */
1320 DWORD cbFlush /* [in] Number of bytes in range */
1322 FILE_VIEW *view;
1323 UINT addr = ROUND_ADDR( base );
1325 TRACE("FlushViewOfFile at %p for %ld bytes\n",
1326 base, cbFlush );
1328 if (!(view = VIRTUAL_FindView( addr )))
1330 SetLastError( ERROR_INVALID_PARAMETER );
1331 return FALSE;
1333 if (!cbFlush) cbFlush = view->size;
1334 if (!msync( (void *)addr, cbFlush, MS_SYNC )) return TRUE;
1335 SetLastError( ERROR_INVALID_PARAMETER );
1336 return FALSE;
1340 /***********************************************************************
1341 * UnmapViewOfFile (KERNEL32.540)
1342 * Unmaps a mapped view of a file.
1344 * NOTES
1345 * Should addr be an LPCVOID?
1347 * RETURNS
1348 * TRUE: Success
1349 * FALSE: Failure
1351 BOOL WINAPI UnmapViewOfFile(
1352 LPVOID addr /* [in] Address where mapped view begins */
1354 FILE_VIEW *view;
1355 UINT base = ROUND_ADDR( addr );
1356 if (!(view = VIRTUAL_FindView( base )) || (base != view->base))
1358 SetLastError( ERROR_INVALID_PARAMETER );
1359 return FALSE;
1361 VIRTUAL_DeleteView( view );
1362 return TRUE;
1365 /***********************************************************************
1366 * VIRTUAL_MapFileW
1368 * Helper function to map a file to memory:
1369 * name - file name
1370 * [RETURN] ptr - pointer to mapped file
1372 LPVOID VIRTUAL_MapFileW( LPCWSTR name )
1374 HANDLE hFile, hMapping;
1375 LPVOID ptr = NULL;
1377 hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
1378 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0);
1379 if (hFile != INVALID_HANDLE_VALUE)
1381 hMapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1382 CloseHandle( hFile );
1383 if (hMapping)
1385 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
1386 CloseHandle( hMapping );
1389 return ptr;