- Return modified rectangle after layouting header control
[wine.git] / memory / virtual.c
blobf23bc3f7be5d6d09bbfcce43dec3ecca79a62f74
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 "global.h"
28 #include "server.h"
29 #include "debugtools.h"
31 DEFAULT_DEBUG_CHANNEL(virtual);
33 #ifndef MS_SYNC
34 #define MS_SYNC 0
35 #endif
37 /* File view */
38 typedef struct _FV
40 struct _FV *next; /* Next view */
41 struct _FV *prev; /* Prev view */
42 UINT base; /* Base address */
43 UINT size; /* Size in bytes */
44 UINT flags; /* Allocation flags */
45 UINT offset; /* Offset from start of mapped file */
46 HANDLE mapping; /* Handle to the file mapping */
47 HANDLERPROC handlerProc; /* Fault handler */
48 LPVOID handlerArg; /* Fault handler argument */
49 BYTE protect; /* Protection for all pages at allocation time */
50 BYTE prot[1]; /* Protection byte for each page */
51 } FILE_VIEW;
53 /* Per-view flags */
54 #define VFLAG_SYSTEM 0x01
56 /* Conversion from VPROT_* to Win32 flags */
57 static const BYTE VIRTUAL_Win32Flags[16] =
59 PAGE_NOACCESS, /* 0 */
60 PAGE_READONLY, /* READ */
61 PAGE_READWRITE, /* WRITE */
62 PAGE_READWRITE, /* READ | WRITE */
63 PAGE_EXECUTE, /* EXEC */
64 PAGE_EXECUTE_READ, /* READ | EXEC */
65 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
66 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
67 PAGE_WRITECOPY, /* WRITECOPY */
68 PAGE_WRITECOPY, /* READ | WRITECOPY */
69 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
70 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
71 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
72 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
73 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
74 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
78 static FILE_VIEW *VIRTUAL_FirstView;
80 #ifdef __i386__
81 /* These are always the same on an i386, and it will be faster this way */
82 # define page_mask 0xfff
83 # define page_shift 12
84 # define granularity_mask 0xffff
85 #else
86 static UINT page_shift;
87 static UINT page_mask;
88 static UINT granularity_mask; /* Allocation granularity (usually 64k) */
89 #endif /* __i386__ */
91 #define ROUND_ADDR(addr) \
92 ((UINT)(addr) & ~page_mask)
94 #define ROUND_SIZE(addr,size) \
95 (((UINT)(size) + ((UINT)(addr) & page_mask) + page_mask) & ~page_mask)
97 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
98 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
100 /***********************************************************************
101 * VIRTUAL_GetProtStr
103 static const char *VIRTUAL_GetProtStr( BYTE prot )
105 static char buffer[6];
106 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
107 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
108 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
109 buffer[3] = (prot & VPROT_WRITE) ?
110 ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
111 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
112 buffer[5] = 0;
113 return buffer;
117 /***********************************************************************
118 * VIRTUAL_DumpView
120 static void VIRTUAL_DumpView( FILE_VIEW *view )
122 UINT i, count;
123 UINT addr = view->base;
124 BYTE prot = view->prot[0];
126 DPRINTF( "View: %08x - %08x%s",
127 view->base, view->base + view->size - 1,
128 (view->flags & VFLAG_SYSTEM) ? " (system)" : "" );
129 if (view->mapping)
130 DPRINTF( " %d @ %08x\n", view->mapping, view->offset );
131 else
132 DPRINTF( " (anonymous)\n");
134 for (count = i = 1; i < view->size >> page_shift; i++, count++)
136 if (view->prot[i] == prot) continue;
137 DPRINTF( " %08x - %08x %s\n",
138 addr, addr + (count << page_shift) - 1,
139 VIRTUAL_GetProtStr(prot) );
140 addr += (count << page_shift);
141 prot = view->prot[i];
142 count = 0;
144 if (count)
145 DPRINTF( " %08x - %08x %s\n",
146 addr, addr + (count << page_shift) - 1,
147 VIRTUAL_GetProtStr(prot) );
151 /***********************************************************************
152 * VIRTUAL_Dump
154 void VIRTUAL_Dump(void)
156 FILE_VIEW *view = VIRTUAL_FirstView;
157 DPRINTF( "\nDump of all virtual memory views:\n\n" );
158 while (view)
160 VIRTUAL_DumpView( view );
161 view = view->next;
166 /***********************************************************************
167 * VIRTUAL_FindView
169 * Find the view containing a given address.
171 * RETURNS
172 * View: Success
173 * NULL: Failure
175 static FILE_VIEW *VIRTUAL_FindView(
176 UINT addr /* [in] Address */
178 FILE_VIEW *view = VIRTUAL_FirstView;
179 while (view)
181 if (view->base > addr) return NULL;
182 if (view->base + view->size > addr) return view;
183 view = view->next;
185 return NULL;
189 /***********************************************************************
190 * VIRTUAL_CreateView
192 * Create a new view and add it in the linked list.
194 static FILE_VIEW *VIRTUAL_CreateView( UINT base, UINT size, UINT offset,
195 UINT flags, BYTE vprot,
196 HANDLE mapping )
198 FILE_VIEW *view, *prev;
200 /* Create the view structure */
202 assert( !(base & page_mask) );
203 assert( !(size & page_mask) );
204 size >>= page_shift;
205 if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
206 view->base = base;
207 view->size = size << page_shift;
208 view->flags = flags;
209 view->offset = offset;
210 view->mapping = mapping;
211 view->protect = vprot;
212 view->handlerProc = NULL;
213 memset( view->prot, vprot, size );
215 /* Duplicate the mapping handle */
217 if ((view->mapping != -1) &&
218 !DuplicateHandle( GetCurrentProcess(), view->mapping,
219 GetCurrentProcess(), &view->mapping,
220 0, FALSE, DUPLICATE_SAME_ACCESS ))
222 free( view );
223 return NULL;
226 /* Insert it in the linked list */
228 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
230 view->next = VIRTUAL_FirstView;
231 view->prev = NULL;
232 if (view->next) view->next->prev = view;
233 VIRTUAL_FirstView = view;
235 else
237 prev = VIRTUAL_FirstView;
238 while (prev->next && (prev->next->base < base)) prev = prev->next;
239 view->next = prev->next;
240 view->prev = prev;
241 if (view->next) view->next->prev = view;
242 prev->next = view;
244 VIRTUAL_DEBUG_DUMP_VIEW( view );
245 return view;
249 /***********************************************************************
250 * VIRTUAL_DeleteView
251 * Deletes a view.
253 * RETURNS
254 * None
256 static void VIRTUAL_DeleteView(
257 FILE_VIEW *view /* [in] View */
259 FILE_munmap( (void *)view->base, 0, view->size );
260 if (view->next) view->next->prev = view->prev;
261 if (view->prev) view->prev->next = view->next;
262 else VIRTUAL_FirstView = view->next;
263 if (view->mapping) CloseHandle( view->mapping );
264 free( view );
268 /***********************************************************************
269 * VIRTUAL_GetUnixProt
271 * Convert page protections to protection for mmap/mprotect.
273 static int VIRTUAL_GetUnixProt( BYTE vprot )
275 int prot = 0;
276 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
278 if (vprot & VPROT_READ) prot |= PROT_READ;
279 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
280 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
282 return prot;
286 /***********************************************************************
287 * VIRTUAL_GetWin32Prot
289 * Convert page protections to Win32 flags.
291 * RETURNS
292 * None
294 static void VIRTUAL_GetWin32Prot(
295 BYTE vprot, /* [in] Page protection flags */
296 DWORD *protect, /* [out] Location to store Win32 protection flags */
297 DWORD *state /* [out] Location to store mem state flag */
299 if (protect) {
300 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
301 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
302 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
304 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
307 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
311 /***********************************************************************
312 * VIRTUAL_GetProt
314 * Build page protections from Win32 flags.
316 * RETURNS
317 * Value of page protection flags
319 static BYTE VIRTUAL_GetProt(
320 DWORD protect /* [in] Win32 protection flags */
322 BYTE vprot;
324 switch(protect & 0xff)
326 case PAGE_READONLY:
327 vprot = VPROT_READ;
328 break;
329 case PAGE_READWRITE:
330 vprot = VPROT_READ | VPROT_WRITE;
331 break;
332 case PAGE_WRITECOPY:
333 vprot = VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
334 break;
335 case PAGE_EXECUTE:
336 vprot = VPROT_EXEC;
337 break;
338 case PAGE_EXECUTE_READ:
339 vprot = VPROT_EXEC | VPROT_READ;
340 break;
341 case PAGE_EXECUTE_READWRITE:
342 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
343 break;
344 case PAGE_EXECUTE_WRITECOPY:
345 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
346 break;
347 case PAGE_NOACCESS:
348 default:
349 vprot = 0;
350 break;
352 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
353 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
354 return vprot;
358 /***********************************************************************
359 * VIRTUAL_SetProt
361 * Change the protection of a range of pages.
363 * RETURNS
364 * TRUE: Success
365 * FALSE: Failure
367 static BOOL VIRTUAL_SetProt(
368 FILE_VIEW *view, /* [in] Pointer to view */
369 UINT base, /* [in] Starting address */
370 UINT size, /* [in] Size in bytes */
371 BYTE vprot /* [in] Protections to use */
373 TRACE("%08x-%08x %s\n",
374 base, base + size - 1, VIRTUAL_GetProtStr( vprot ) );
376 if (mprotect( (void *)base, size, VIRTUAL_GetUnixProt(vprot) ))
377 return FALSE; /* FIXME: last error */
379 memset( view->prot + ((base - view->base) >> page_shift),
380 vprot, size >> page_shift );
381 VIRTUAL_DEBUG_DUMP_VIEW( view );
382 return TRUE;
386 /***********************************************************************
387 * VIRTUAL_CheckFlags
389 * Check that all pages in a range have the given flags.
391 * RETURNS
392 * TRUE: They do
393 * FALSE: They do not
395 static BOOL VIRTUAL_CheckFlags(
396 UINT base, /* [in] Starting address */
397 UINT size, /* [in] Size in bytes */
398 BYTE flags /* [in] Flags to check for */
400 FILE_VIEW *view;
401 UINT page;
403 if (!size) return TRUE;
404 if (!(view = VIRTUAL_FindView( base ))) return FALSE;
405 if (view->base + view->size < base + size) return FALSE;
406 page = (base - view->base) >> page_shift;
407 size = ROUND_SIZE( base, size ) >> page_shift;
408 while (size--) if ((view->prot[page++] & flags) != flags) return FALSE;
409 return TRUE;
413 /***********************************************************************
414 * VIRTUAL_Init
416 BOOL VIRTUAL_Init(void)
418 #ifndef __i386__
419 DWORD page_size;
421 # ifdef HAVE_GETPAGESIZE
422 page_size = getpagesize();
423 # else
424 # ifdef __svr4__
425 page_size = sysconf(_SC_PAGESIZE);
426 # else
427 # error Cannot get the page size on this platform
428 # endif
429 # endif
430 page_mask = page_size - 1;
431 granularity_mask = 0xffff; /* hard-coded for now */
432 /* Make sure we have a power of 2 */
433 assert( !(page_size & page_mask) );
434 page_shift = 0;
435 while ((1 << page_shift) != page_size) page_shift++;
436 #endif /* !__i386__ */
438 #ifdef linux
440 /* Do not use stdio here since it may temporarily change the size
441 * of some segments (ie libc6 adds 0x1000 per open FILE)
443 int fd = open ("/proc/self/maps", O_RDONLY);
444 if (fd >= 0)
446 char buffer[512]; /* line might be rather long in 2.1 */
448 for (;;)
450 int start, end, offset;
451 char r, w, x, p;
452 BYTE vprot = VPROT_COMMITTED;
454 char * ptr = buffer;
455 int count = sizeof(buffer);
456 while (1 == read(fd, ptr, 1) && *ptr != '\n' && --count > 0)
457 ptr++;
459 if (*ptr != '\n') break;
460 *ptr = '\0';
462 sscanf( buffer, "%x-%x %c%c%c%c %x",
463 &start, &end, &r, &w, &x, &p, &offset );
464 if (r == 'r') vprot |= VPROT_READ;
465 if (w == 'w') vprot |= VPROT_WRITE;
466 if (x == 'x') vprot |= VPROT_EXEC;
467 if (p == 'p') vprot |= VPROT_WRITECOPY;
468 VIRTUAL_CreateView( start, end - start, 0,
469 VFLAG_SYSTEM, vprot, -1 );
471 close (fd);
474 #endif /* linux */
475 return TRUE;
479 /***********************************************************************
480 * VIRTUAL_GetPageSize
482 DWORD VIRTUAL_GetPageSize(void)
484 return 1 << page_shift;
488 /***********************************************************************
489 * VIRTUAL_GetGranularity
491 DWORD VIRTUAL_GetGranularity(void)
493 return granularity_mask + 1;
497 /***********************************************************************
498 * VIRTUAL_SetFaultHandler
500 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
502 FILE_VIEW *view;
504 if (!(view = VIRTUAL_FindView((UINT)addr))) return FALSE;
505 view->handlerProc = proc;
506 view->handlerArg = arg;
507 return TRUE;
510 /***********************************************************************
511 * VIRTUAL_HandleFault
513 DWORD VIRTUAL_HandleFault( LPCVOID addr )
515 FILE_VIEW *view = VIRTUAL_FindView((UINT)addr);
516 DWORD ret = EXCEPTION_ACCESS_VIOLATION;
518 if (view)
520 if (view->handlerProc)
522 if (view->handlerProc(view->handlerArg, addr)) ret = 0; /* handled */
524 else
526 BYTE vprot = view->prot[((UINT)addr - view->base) >> page_shift];
527 UINT page = (UINT)addr & ~page_mask;
528 char *stack = (char *)NtCurrentTeb()->stack_base + SIGNAL_STACK_SIZE + page_mask + 1;
529 if (vprot & VPROT_GUARD)
531 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
532 ret = STATUS_GUARD_PAGE_VIOLATION;
534 /* is it inside the stack guard pages? */
535 if (((char *)addr >= stack) && ((char *)addr < stack + 2*(page_mask+1)))
536 ret = STATUS_STACK_OVERFLOW;
539 return ret;
543 /***********************************************************************
544 * VirtualAlloc (KERNEL32.548)
545 * Reserves or commits a region of pages in virtual address space
547 * RETURNS
548 * Base address of allocated region of pages
549 * NULL: Failure
551 LPVOID WINAPI VirtualAlloc(
552 LPVOID addr, /* [in] Address of region to reserve or commit */
553 DWORD size, /* [in] Size of region */
554 DWORD type, /* [in] Type of allocation */
555 DWORD protect /* [in] Type of access protection */
557 FILE_VIEW *view;
558 UINT base, ptr, view_size;
559 BYTE vprot;
561 TRACE("%08x %08lx %lx %08lx\n",
562 (UINT)addr, size, type, protect );
564 /* Round parameters to a page boundary */
566 if (size > 0x7fc00000) /* 2Gb - 4Mb */
568 SetLastError( ERROR_OUTOFMEMORY );
569 return NULL;
571 if (addr)
573 if (type & MEM_RESERVE) /* Round down to 64k boundary */
574 base = (UINT)addr & ~granularity_mask;
575 else
576 base = ROUND_ADDR( addr );
577 size = (((UINT)addr + size + page_mask) & ~page_mask) - base;
578 if ((base <= granularity_mask) || (base + size < base))
580 /* disallow low 64k and wrap-around */
581 SetLastError( ERROR_INVALID_PARAMETER );
582 return NULL;
585 else
587 base = 0;
588 size = (size + page_mask) & ~page_mask;
591 if (type & MEM_TOP_DOWN) {
592 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
593 * Is there _ANY_ way to do it with UNIX mmap()?
595 WARN("MEM_TOP_DOWN ignored\n");
596 type &= ~MEM_TOP_DOWN;
598 /* Compute the protection flags */
600 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
601 (type & ~(MEM_COMMIT | MEM_RESERVE)))
603 SetLastError( ERROR_INVALID_PARAMETER );
604 return NULL;
606 if (type & MEM_COMMIT)
607 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
608 else vprot = 0;
610 /* Reserve the memory */
612 if ((type & MEM_RESERVE) || !base)
614 view_size = size + (base ? 0 : granularity_mask + 1);
615 ptr = (UINT)FILE_dommap( -1, (LPVOID)base, 0, view_size, 0, 0,
616 VIRTUAL_GetUnixProt( vprot ), MAP_PRIVATE );
617 if (ptr == (UINT)-1)
619 SetLastError( ERROR_OUTOFMEMORY );
620 return NULL;
622 if (!base)
624 /* Release the extra memory while keeping the range */
625 /* starting on a 64k boundary. */
627 if (ptr & granularity_mask)
629 UINT extra = granularity_mask + 1 - (ptr & granularity_mask);
630 FILE_munmap( (void *)ptr, 0, extra );
631 ptr += extra;
632 view_size -= extra;
634 if (view_size > size)
635 FILE_munmap( (void *)(ptr + size), 0, view_size - size );
637 else if (ptr != base)
639 /* We couldn't get the address we wanted */
640 FILE_munmap( (void *)ptr, 0, view_size );
641 SetLastError( ERROR_INVALID_ADDRESS );
642 return NULL;
644 if (!(view = VIRTUAL_CreateView( ptr, size, 0, 0, vprot, -1 )))
646 FILE_munmap( (void *)ptr, 0, size );
647 SetLastError( ERROR_OUTOFMEMORY );
648 return NULL;
650 VIRTUAL_DEBUG_DUMP_VIEW( view );
651 return (LPVOID)ptr;
654 /* Commit the pages */
656 if (!(view = VIRTUAL_FindView( base )) ||
657 (base + size > view->base + view->size))
659 SetLastError( ERROR_INVALID_ADDRESS );
660 return NULL;
663 if (!VIRTUAL_SetProt( view, base, size, vprot )) return NULL;
664 return (LPVOID)base;
668 /***********************************************************************
669 * VirtualFree (KERNEL32.550)
670 * Release or decommits a region of pages in virtual address space.
672 * RETURNS
673 * TRUE: Success
674 * FALSE: Failure
676 BOOL WINAPI VirtualFree(
677 LPVOID addr, /* [in] Address of region of committed pages */
678 DWORD size, /* [in] Size of region */
679 DWORD type /* [in] Type of operation */
681 FILE_VIEW *view;
682 UINT base;
684 TRACE("%08x %08lx %lx\n",
685 (UINT)addr, size, type );
687 /* Fix the parameters */
689 size = ROUND_SIZE( addr, size );
690 base = ROUND_ADDR( addr );
692 if (!(view = VIRTUAL_FindView( base )) ||
693 (base + size > view->base + view->size))
695 SetLastError( ERROR_INVALID_PARAMETER );
696 return FALSE;
699 /* Compute the protection flags */
701 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
703 SetLastError( ERROR_INVALID_PARAMETER );
704 return FALSE;
707 /* Free the pages */
709 if (type == MEM_RELEASE)
711 if (size || (base != view->base))
713 SetLastError( ERROR_INVALID_PARAMETER );
714 return FALSE;
716 VIRTUAL_DeleteView( view );
717 return TRUE;
720 /* Decommit the pages by remapping zero-pages instead */
722 if (FILE_dommap( -1, (LPVOID)base, 0, size, 0, 0,
723 VIRTUAL_GetUnixProt( 0 ), MAP_PRIVATE|MAP_FIXED )
724 != (LPVOID)base)
725 ERR( "Could not remap pages, expect trouble\n" );
726 return VIRTUAL_SetProt( view, base, size, 0 );
730 /***********************************************************************
731 * VirtualLock (KERNEL32.551)
732 * Locks the specified region of virtual address space
734 * NOTE
735 * Always returns TRUE
737 * RETURNS
738 * TRUE: Success
739 * FALSE: Failure
741 BOOL WINAPI VirtualLock(
742 LPVOID addr, /* [in] Address of first byte of range to lock */
743 DWORD size /* [in] Number of bytes in range to lock */
745 return TRUE;
749 /***********************************************************************
750 * VirtualUnlock (KERNEL32.556)
751 * Unlocks a range of pages in the virtual address space
753 * NOTE
754 * Always returns TRUE
756 * RETURNS
757 * TRUE: Success
758 * FALSE: Failure
760 BOOL WINAPI VirtualUnlock(
761 LPVOID addr, /* [in] Address of first byte of range */
762 DWORD size /* [in] Number of bytes in range */
764 return TRUE;
768 /***********************************************************************
769 * VirtualProtect (KERNEL32.552)
770 * Changes the access protection on a region of committed pages
772 * RETURNS
773 * TRUE: Success
774 * FALSE: Failure
776 BOOL WINAPI VirtualProtect(
777 LPVOID addr, /* [in] Address of region of committed pages */
778 DWORD size, /* [in] Size of region */
779 DWORD new_prot, /* [in] Desired access protection */
780 LPDWORD old_prot /* [out] Address of variable to get old protection */
782 FILE_VIEW *view;
783 UINT base, i;
784 BYTE vprot, *p;
786 TRACE("%08x %08lx %08lx\n",
787 (UINT)addr, size, new_prot );
789 /* Fix the parameters */
791 size = ROUND_SIZE( addr, size );
792 base = ROUND_ADDR( addr );
794 if (!(view = VIRTUAL_FindView( base )) ||
795 (base + size > view->base + view->size))
797 SetLastError( ERROR_INVALID_PARAMETER );
798 return FALSE;
801 /* Make sure all the pages are committed */
803 p = view->prot + ((base - view->base) >> page_shift);
804 for (i = size >> page_shift; i; i--, p++)
806 if (!(*p & VPROT_COMMITTED))
808 SetLastError( ERROR_INVALID_PARAMETER );
809 return FALSE;
813 VIRTUAL_GetWin32Prot( view->prot[0], old_prot, NULL );
814 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
815 return VIRTUAL_SetProt( view, base, size, vprot );
819 /***********************************************************************
820 * VirtualProtectEx (KERNEL32.553)
821 * Changes the access protection on a region of committed pages in the
822 * virtual address space of a specified process
824 * RETURNS
825 * TRUE: Success
826 * FALSE: Failure
828 BOOL WINAPI VirtualProtectEx(
829 HANDLE handle, /* [in] Handle of process */
830 LPVOID addr, /* [in] Address of region of committed pages */
831 DWORD size, /* [in] Size of region */
832 DWORD new_prot, /* [in] Desired access protection */
833 LPDWORD old_prot /* [out] Address of variable to get old protection */ )
835 if (MapProcessHandle( handle ) == GetCurrentProcessId())
836 return VirtualProtect( addr, size, new_prot, old_prot );
837 ERR("Unsupported on other process\n");
838 return FALSE;
842 /***********************************************************************
843 * VirtualQuery (KERNEL32.554)
844 * Provides info about a range of pages in virtual address space
846 * RETURNS
847 * Number of bytes returned in information buffer
849 DWORD WINAPI VirtualQuery(
850 LPCVOID addr, /* [in] Address of region */
851 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
852 DWORD len /* [in] Size of buffer */
854 FILE_VIEW *view = VIRTUAL_FirstView;
855 UINT base = ROUND_ADDR( addr );
856 UINT alloc_base = 0;
857 UINT size = 0;
859 /* Find the view containing the address */
861 for (;;)
863 if (!view)
865 size = 0xffff0000 - alloc_base;
866 break;
868 if (view->base > base)
870 size = view->base - alloc_base;
871 view = NULL;
872 break;
874 if (view->base + view->size > base)
876 alloc_base = view->base;
877 size = view->size;
878 break;
880 alloc_base = view->base + view->size;
881 view = view->next;
884 /* Fill the info structure */
886 if (!view)
888 info->State = MEM_FREE;
889 info->Protect = 0;
890 info->AllocationProtect = 0;
891 info->Type = 0;
893 else
895 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
896 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
897 for (size = base - alloc_base; size < view->size; size += page_mask+1)
898 if (view->prot[size >> page_shift] != vprot) break;
899 info->AllocationProtect = view->protect;
900 info->Type = MEM_PRIVATE; /* FIXME */
903 info->BaseAddress = (LPVOID)base;
904 info->AllocationBase = (LPVOID)alloc_base;
905 info->RegionSize = size - (base - alloc_base);
906 return sizeof(*info);
910 /***********************************************************************
911 * VirtualQueryEx (KERNEL32.555)
912 * Provides info about a range of pages in virtual address space of a
913 * specified process
915 * RETURNS
916 * Number of bytes returned in information buffer
918 DWORD WINAPI VirtualQueryEx(
919 HANDLE handle, /* [in] Handle of process */
920 LPCVOID addr, /* [in] Address of region */
921 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
922 DWORD len /* [in] Size of buffer */ )
924 if (MapProcessHandle( handle ) == GetCurrentProcessId())
925 return VirtualQuery( addr, info, len );
926 ERR("Unsupported on other process\n");
927 return 0;
931 /***********************************************************************
932 * IsBadReadPtr (KERNEL32.354)
934 * RETURNS
935 * FALSE: Process has read access to entire block
936 * TRUE: Otherwise
938 BOOL WINAPI IsBadReadPtr(
939 LPCVOID ptr, /* Address of memory block */
940 UINT size /* Size of block */
942 return !VIRTUAL_CheckFlags( (UINT)ptr, size,
943 VPROT_READ | VPROT_COMMITTED );
947 /***********************************************************************
948 * IsBadWritePtr (KERNEL32.357)
950 * RETURNS
951 * FALSE: Process has write access to entire block
952 * TRUE: Otherwise
954 BOOL WINAPI IsBadWritePtr(
955 LPVOID ptr, /* [in] Address of memory block */
956 UINT size /* [in] Size of block in bytes */
958 return !VIRTUAL_CheckFlags( (UINT)ptr, size,
959 VPROT_WRITE | VPROT_COMMITTED );
963 /***********************************************************************
964 * IsBadHugeReadPtr (KERNEL32.352)
965 * RETURNS
966 * FALSE: Process has read access to entire block
967 * TRUE: Otherwise
969 BOOL WINAPI IsBadHugeReadPtr(
970 LPCVOID ptr, /* [in] Address of memory block */
971 UINT size /* [in] Size of block */
973 return IsBadReadPtr( ptr, size );
977 /***********************************************************************
978 * IsBadHugeWritePtr (KERNEL32.353)
979 * RETURNS
980 * FALSE: Process has write access to entire block
981 * TRUE: Otherwise
983 BOOL WINAPI IsBadHugeWritePtr(
984 LPVOID ptr, /* [in] Address of memory block */
985 UINT size /* [in] Size of block */
987 return IsBadWritePtr( ptr, size );
991 /***********************************************************************
992 * IsBadCodePtr (KERNEL32.351)
994 * RETURNS
995 * FALSE: Process has read access to specified memory
996 * TRUE: Otherwise
998 BOOL WINAPI IsBadCodePtr(
999 FARPROC ptr /* [in] Address of function */
1001 return !VIRTUAL_CheckFlags( (UINT)ptr, 1, VPROT_EXEC | VPROT_COMMITTED );
1005 /***********************************************************************
1006 * IsBadStringPtrA (KERNEL32.355)
1008 * RETURNS
1009 * FALSE: Read access to all bytes in string
1010 * TRUE: Else
1012 BOOL WINAPI IsBadStringPtrA(
1013 LPCSTR str, /* [in] Address of string */
1014 UINT max /* [in] Maximum size of string */
1016 FILE_VIEW *view;
1017 UINT page, count;
1019 if (!max) return FALSE;
1020 if (!(view = VIRTUAL_FindView( (UINT)str ))) return TRUE;
1021 page = ((UINT)str - view->base) >> page_shift;
1022 count = page_mask + 1 - ((UINT)str & page_mask);
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;
1035 return FALSE;
1039 /***********************************************************************
1040 * IsBadStringPtrW (KERNEL32.356)
1041 * See IsBadStringPtrA
1043 BOOL WINAPI IsBadStringPtrW( LPCWSTR str, UINT max )
1045 FILE_VIEW *view;
1046 UINT page, count;
1048 if (!max) return FALSE;
1049 if (!(view = VIRTUAL_FindView( (UINT)str ))) return TRUE;
1050 page = ((UINT)str - view->base) >> page_shift;
1051 count = (page_mask + 1 - ((UINT)str & page_mask)) / sizeof(WCHAR);
1053 while (max)
1055 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
1056 (VPROT_READ | VPROT_COMMITTED))
1057 return TRUE;
1058 if (count > max) count = max;
1059 max -= count;
1060 while (count--) if (!*str++) return FALSE;
1061 if (++page >= view->size >> page_shift) return TRUE;
1062 count = (page_mask + 1) / sizeof(WCHAR);
1064 return FALSE;
1068 /***********************************************************************
1069 * CreateFileMappingA (KERNEL32.46)
1070 * Creates a named or unnamed file-mapping object for the specified file
1072 * RETURNS
1073 * Handle: Success
1074 * 0: Mapping object does not exist
1075 * NULL: Failure
1077 HANDLE WINAPI CreateFileMappingA(
1078 HFILE hFile, /* [in] Handle of file to map */
1079 SECURITY_ATTRIBUTES *sa, /* [in] Optional security attributes*/
1080 DWORD protect, /* [in] Protection for mapping object */
1081 DWORD size_high, /* [in] High-order 32 bits of object size */
1082 DWORD size_low, /* [in] Low-order 32 bits of object size */
1083 LPCSTR name /* [in] Name of file-mapping object */ )
1085 struct create_mapping_request *req = get_req_buffer();
1086 BYTE vprot;
1088 /* Check parameters */
1090 TRACE("(%x,%p,%08lx,%08lx%08lx,%s)\n",
1091 hFile, sa, protect, size_high, size_low, debugstr_a(name) );
1093 vprot = VIRTUAL_GetProt( protect );
1094 if (protect & SEC_RESERVE)
1096 if (hFile != INVALID_HANDLE_VALUE)
1098 SetLastError( ERROR_INVALID_PARAMETER );
1099 return 0;
1102 else vprot |= VPROT_COMMITTED;
1103 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1105 /* Create the server object */
1107 req->file_handle = hFile;
1108 req->size_high = size_high;
1109 req->size_low = size_low;
1110 req->protect = vprot;
1111 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1112 server_strcpyAtoW( req->name, name );
1113 SetLastError(0);
1114 server_call( REQ_CREATE_MAPPING );
1115 if (req->handle == -1) return 0;
1116 return req->handle;
1120 /***********************************************************************
1121 * CreateFileMappingW (KERNEL32.47)
1122 * See CreateFileMappingA
1124 HANDLE WINAPI CreateFileMappingW( HFILE hFile, LPSECURITY_ATTRIBUTES sa,
1125 DWORD protect, DWORD size_high,
1126 DWORD size_low, LPCWSTR name )
1128 struct create_mapping_request *req = get_req_buffer();
1129 BYTE vprot;
1131 /* Check parameters */
1133 TRACE("(%x,%p,%08lx,%08lx%08lx,%s)\n",
1134 hFile, sa, protect, size_high, size_low, debugstr_w(name) );
1136 vprot = VIRTUAL_GetProt( protect );
1137 if (protect & SEC_RESERVE)
1139 if (hFile != INVALID_HANDLE_VALUE)
1141 SetLastError( ERROR_INVALID_PARAMETER );
1142 return 0;
1145 else vprot |= VPROT_COMMITTED;
1146 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1148 /* Create the server object */
1150 req->file_handle = hFile;
1151 req->size_high = size_high;
1152 req->size_low = size_low;
1153 req->protect = vprot;
1154 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1155 server_strcpyW( req->name, name );
1156 SetLastError(0);
1157 server_call( REQ_CREATE_MAPPING );
1158 if (req->handle == -1) return 0;
1159 return req->handle;
1163 /***********************************************************************
1164 * OpenFileMappingA (KERNEL32.397)
1165 * Opens a named file-mapping object.
1167 * RETURNS
1168 * Handle: Success
1169 * NULL: Failure
1171 HANDLE WINAPI OpenFileMappingA(
1172 DWORD access, /* [in] Access mode */
1173 BOOL inherit, /* [in] Inherit flag */
1174 LPCSTR name ) /* [in] Name of file-mapping object */
1176 struct open_mapping_request *req = get_req_buffer();
1178 req->access = access;
1179 req->inherit = inherit;
1180 server_strcpyAtoW( req->name, name );
1181 server_call( REQ_OPEN_MAPPING );
1182 if (req->handle == -1) return 0; /* must return 0 on failure, not -1 */
1183 return req->handle;
1187 /***********************************************************************
1188 * OpenFileMappingW (KERNEL32.398)
1189 * See OpenFileMappingA
1191 HANDLE WINAPI OpenFileMappingW( DWORD access, BOOL inherit, LPCWSTR name)
1193 struct open_mapping_request *req = get_req_buffer();
1195 req->access = access;
1196 req->inherit = inherit;
1197 server_strcpyW( req->name, name );
1198 server_call( REQ_OPEN_MAPPING );
1199 if (req->handle == -1) return 0; /* must return 0 on failure, not -1 */
1200 return req->handle;
1204 /***********************************************************************
1205 * MapViewOfFile (KERNEL32.385)
1206 * Maps a view of a file into the address space
1208 * RETURNS
1209 * Starting address of mapped view
1210 * NULL: Failure
1212 LPVOID WINAPI MapViewOfFile(
1213 HANDLE mapping, /* [in] File-mapping object to map */
1214 DWORD access, /* [in] Access mode */
1215 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1216 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1217 DWORD count /* [in] Number of bytes to map */
1219 return MapViewOfFileEx( mapping, access, offset_high,
1220 offset_low, count, NULL );
1224 /***********************************************************************
1225 * MapViewOfFileEx (KERNEL32.386)
1226 * Maps a view of a file into the address space
1228 * RETURNS
1229 * Starting address of mapped view
1230 * NULL: Failure
1232 LPVOID WINAPI MapViewOfFileEx(
1233 HANDLE handle, /* [in] File-mapping object to map */
1234 DWORD access, /* [in] Access mode */
1235 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1236 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1237 DWORD count, /* [in] Number of bytes to map */
1238 LPVOID addr /* [in] Suggested starting address for mapped view */
1240 FILE_VIEW *view;
1241 UINT ptr = (UINT)-1, size = 0;
1242 int flags = MAP_PRIVATE;
1243 int unix_handle = -1;
1244 int prot;
1245 struct get_mapping_info_request *req = get_req_buffer();
1247 /* Check parameters */
1249 if ((offset_low & granularity_mask) ||
1250 (addr && ((UINT)addr & granularity_mask)))
1252 SetLastError( ERROR_INVALID_PARAMETER );
1253 return NULL;
1256 req->handle = handle;
1257 if (server_call_fd( REQ_GET_MAPPING_INFO, -1, &unix_handle )) goto error;
1259 if (req->size_high || offset_high)
1260 ERR("Offsets larger than 4Gb not supported\n");
1262 if ((offset_low >= req->size_low) ||
1263 (count > req->size_low - offset_low))
1265 SetLastError( ERROR_INVALID_PARAMETER );
1266 goto error;
1268 if (count) size = ROUND_SIZE( offset_low, count );
1269 else size = req->size_low - offset_low;
1270 prot = req->protect;
1272 switch(access)
1274 case FILE_MAP_ALL_ACCESS:
1275 case FILE_MAP_WRITE:
1276 case FILE_MAP_WRITE | FILE_MAP_READ:
1277 if (!(prot & VPROT_WRITE))
1279 SetLastError( ERROR_INVALID_PARAMETER );
1280 goto error;
1282 flags = MAP_SHARED;
1283 /* fall through */
1284 case FILE_MAP_READ:
1285 case FILE_MAP_COPY:
1286 case FILE_MAP_COPY | FILE_MAP_READ:
1287 if (prot & VPROT_READ) break;
1288 /* fall through */
1289 default:
1290 SetLastError( ERROR_INVALID_PARAMETER );
1291 goto error;
1294 /* Map the file */
1296 TRACE("handle=%x size=%x offset=%lx\n", handle, size, offset_low );
1298 ptr = (UINT)FILE_dommap( unix_handle, addr, 0, size, 0, offset_low,
1299 VIRTUAL_GetUnixProt( prot ), flags );
1300 if (ptr == (UINT)-1) {
1301 /* KB: Q125713, 25-SEP-1995, "Common File Mapping Problems and
1302 * Platform Differences":
1303 * Windows NT: ERROR_INVALID_PARAMETER
1304 * Windows 95: ERROR_INVALID_ADDRESS.
1305 * FIXME: So should we add a module dependend check here? -MM
1307 if (errno==ENOMEM)
1308 SetLastError( ERROR_OUTOFMEMORY );
1309 else
1310 SetLastError( ERROR_INVALID_PARAMETER );
1311 goto error;
1314 if (!(view = VIRTUAL_CreateView( ptr, size, offset_low, 0, prot, handle )))
1316 SetLastError( ERROR_OUTOFMEMORY );
1317 goto error;
1319 if (unix_handle != -1) close( unix_handle );
1320 return (LPVOID)ptr;
1322 error:
1323 if (unix_handle != -1) close( unix_handle );
1324 if (ptr != (UINT)-1) FILE_munmap( (void *)ptr, 0, size );
1325 return NULL;
1329 /***********************************************************************
1330 * FlushViewOfFile (KERNEL32.262)
1331 * Writes to the disk a byte range within a mapped view of a file
1333 * RETURNS
1334 * TRUE: Success
1335 * FALSE: Failure
1337 BOOL WINAPI FlushViewOfFile(
1338 LPCVOID base, /* [in] Start address of byte range to flush */
1339 DWORD cbFlush /* [in] Number of bytes in range */
1341 FILE_VIEW *view;
1342 UINT addr = ROUND_ADDR( base );
1344 TRACE("FlushViewOfFile at %p for %ld bytes\n",
1345 base, cbFlush );
1347 if (!(view = VIRTUAL_FindView( addr )))
1349 SetLastError( ERROR_INVALID_PARAMETER );
1350 return FALSE;
1352 if (!cbFlush) cbFlush = view->size;
1353 if (!msync( (void *)addr, cbFlush, MS_SYNC )) return TRUE;
1354 SetLastError( ERROR_INVALID_PARAMETER );
1355 return FALSE;
1359 /***********************************************************************
1360 * UnmapViewOfFile (KERNEL32.540)
1361 * Unmaps a mapped view of a file.
1363 * NOTES
1364 * Should addr be an LPCVOID?
1366 * RETURNS
1367 * TRUE: Success
1368 * FALSE: Failure
1370 BOOL WINAPI UnmapViewOfFile(
1371 LPVOID addr /* [in] Address where mapped view begins */
1373 FILE_VIEW *view;
1374 UINT base = ROUND_ADDR( addr );
1375 if (!(view = VIRTUAL_FindView( base )) || (base != view->base))
1377 SetLastError( ERROR_INVALID_PARAMETER );
1378 return FALSE;
1380 VIRTUAL_DeleteView( view );
1381 return TRUE;
1384 /***********************************************************************
1385 * VIRTUAL_MapFileW
1387 * Helper function to map a file to memory:
1388 * name - file name
1389 * [RETURN] ptr - pointer to mapped file
1391 LPVOID VIRTUAL_MapFileW( LPCWSTR name )
1393 HANDLE hFile, hMapping;
1394 LPVOID ptr = NULL;
1396 hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
1397 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0);
1398 if (hFile != INVALID_HANDLE_VALUE)
1400 hMapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1401 CloseHandle( hFile );
1402 if (hMapping)
1404 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
1405 CloseHandle( hMapping );
1408 return ptr;