Fix ambiguous else warning.
[wine/wine-kai.git] / memory / virtual.c
blob0b57c5eb03335d660b208ee12143e21411b2b96e
1 /*
2 * Win32 virtual memory functions
4 * Copyright 1997 Alexandre Julliard
5 */
7 #include <assert.h>
8 #include <errno.h>
9 #include <sys/errno.h>
10 #include <fcntl.h>
11 #include <unistd.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/types.h>
15 #include <sys/mman.h>
16 #include "winbase.h"
17 #include "winerror.h"
18 #include "file.h"
19 #include "heap.h"
20 #include "process.h"
21 #include "xmalloc.h"
22 #include "global.h"
23 #include "server.h"
24 #include "debug.h"
26 #ifndef MS_SYNC
27 #define MS_SYNC 0
28 #endif
30 /* File view */
31 typedef struct _FV
33 struct _FV *next; /* Next view */
34 struct _FV *prev; /* Prev view */
35 UINT base; /* Base address */
36 UINT size; /* Size in bytes */
37 UINT flags; /* Allocation flags */
38 UINT offset; /* Offset from start of mapped file */
39 HANDLE mapping; /* Handle to the file mapping */
40 HANDLERPROC handlerProc; /* Fault handler */
41 LPVOID handlerArg; /* Fault handler argument */
42 BYTE protect; /* Protection for all pages at allocation time */
43 BYTE prot[1]; /* Protection byte for each page */
44 } FILE_VIEW;
46 /* Per-view flags */
47 #define VFLAG_SYSTEM 0x01
49 /* Conversion from VPROT_* to Win32 flags */
50 static const BYTE VIRTUAL_Win32Flags[16] =
52 PAGE_NOACCESS, /* 0 */
53 PAGE_READONLY, /* READ */
54 PAGE_READWRITE, /* WRITE */
55 PAGE_READWRITE, /* READ | WRITE */
56 PAGE_EXECUTE, /* EXEC */
57 PAGE_EXECUTE_READ, /* READ | EXEC */
58 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
59 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
60 PAGE_WRITECOPY, /* WRITECOPY */
61 PAGE_WRITECOPY, /* READ | WRITECOPY */
62 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
63 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
64 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
65 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
66 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
67 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
71 static FILE_VIEW *VIRTUAL_FirstView;
73 #ifdef __i386__
74 /* These are always the same on an i386, and it will be faster this way */
75 # define page_mask 0xfff
76 # define page_shift 12
77 # define granularity_mask 0xffff
78 #else
79 static UINT page_shift;
80 static UINT page_mask;
81 static UINT granularity_mask; /* Allocation granularity (usually 64k) */
82 #endif /* __i386__ */
84 #define ROUND_ADDR(addr) \
85 ((UINT)(addr) & ~page_mask)
87 #define ROUND_SIZE(addr,size) \
88 (((UINT)(size) + ((UINT)(addr) & page_mask) + page_mask) & ~page_mask)
90 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
91 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
93 /***********************************************************************
94 * VIRTUAL_GetProtStr
96 static const char *VIRTUAL_GetProtStr( BYTE prot )
98 static char buffer[6];
99 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
100 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
101 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
102 buffer[3] = (prot & VPROT_WRITE) ?
103 ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
104 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
105 buffer[5] = 0;
106 return buffer;
110 /***********************************************************************
111 * VIRTUAL_DumpView
113 static void VIRTUAL_DumpView( FILE_VIEW *view )
115 UINT i, count;
116 UINT addr = view->base;
117 BYTE prot = view->prot[0];
119 DUMP( "View: %08x - %08x%s",
120 view->base, view->base + view->size - 1,
121 (view->flags & VFLAG_SYSTEM) ? " (system)" : "" );
122 if (view->mapping)
123 DUMP( " %d @ %08x\n", view->mapping, view->offset );
124 else
125 DUMP( " (anonymous)\n");
127 for (count = i = 1; i < view->size >> page_shift; i++, count++)
129 if (view->prot[i] == prot) continue;
130 DUMP( " %08x - %08x %s\n",
131 addr, addr + (count << page_shift) - 1,
132 VIRTUAL_GetProtStr(prot) );
133 addr += (count << page_shift);
134 prot = view->prot[i];
135 count = 0;
137 if (count)
138 DUMP( " %08x - %08x %s\n",
139 addr, addr + (count << page_shift) - 1,
140 VIRTUAL_GetProtStr(prot) );
144 /***********************************************************************
145 * VIRTUAL_Dump
147 void VIRTUAL_Dump(void)
149 FILE_VIEW *view = VIRTUAL_FirstView;
150 DUMP( "\nDump of all virtual memory views:\n\n" );
151 while (view)
153 VIRTUAL_DumpView( view );
154 view = view->next;
159 /***********************************************************************
160 * VIRTUAL_FindView
162 * Find the view containing a given address.
164 * RETURNS
165 * View: Success
166 * NULL: Failure
168 static FILE_VIEW *VIRTUAL_FindView(
169 UINT addr /* [in] Address */
171 FILE_VIEW *view = VIRTUAL_FirstView;
172 while (view)
174 if (view->base > addr) return NULL;
175 if (view->base + view->size > addr) return view;
176 view = view->next;
178 return NULL;
182 /***********************************************************************
183 * VIRTUAL_CreateView
185 * Create a new view and add it in the linked list.
187 static FILE_VIEW *VIRTUAL_CreateView( UINT base, UINT size, UINT offset,
188 UINT flags, BYTE vprot,
189 HANDLE mapping )
191 FILE_VIEW *view, *prev;
193 /* Create the view structure */
195 assert( !(base & page_mask) );
196 assert( !(size & page_mask) );
197 size >>= page_shift;
198 if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
199 view->base = base;
200 view->size = size << page_shift;
201 view->flags = flags;
202 view->offset = offset;
203 view->mapping = mapping;
204 view->protect = vprot;
205 view->handlerProc = NULL;
206 memset( view->prot, vprot, size );
208 /* Duplicate the mapping handle */
210 if ((view->mapping != -1) &&
211 !DuplicateHandle( GetCurrentProcess(), view->mapping,
212 GetCurrentProcess(), &view->mapping,
213 0, FALSE, DUPLICATE_SAME_ACCESS ))
215 free( view );
216 return NULL;
219 /* Insert it in the linked list */
221 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
223 view->next = VIRTUAL_FirstView;
224 view->prev = NULL;
225 if (view->next) view->next->prev = view;
226 VIRTUAL_FirstView = view;
228 else
230 prev = VIRTUAL_FirstView;
231 while (prev->next && (prev->next->base < base)) prev = prev->next;
232 view->next = prev->next;
233 view->prev = prev;
234 if (view->next) view->next->prev = view;
235 prev->next = view;
237 VIRTUAL_DEBUG_DUMP_VIEW( view );
238 return view;
242 /***********************************************************************
243 * VIRTUAL_DeleteView
244 * Deletes a view.
246 * RETURNS
247 * None
249 static void VIRTUAL_DeleteView(
250 FILE_VIEW *view /* [in] View */
252 FILE_munmap( (void *)view->base, 0, view->size );
253 if (view->next) view->next->prev = view->prev;
254 if (view->prev) view->prev->next = view->next;
255 else VIRTUAL_FirstView = view->next;
256 if (view->mapping) CloseHandle( view->mapping );
257 free( view );
261 /***********************************************************************
262 * VIRTUAL_GetUnixProt
264 * Convert page protections to protection for mmap/mprotect.
266 static int VIRTUAL_GetUnixProt( BYTE vprot )
268 int prot = 0;
269 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
271 if (vprot & VPROT_READ) prot |= PROT_READ;
272 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
273 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
275 return prot;
279 /***********************************************************************
280 * VIRTUAL_GetWin32Prot
282 * Convert page protections to Win32 flags.
284 * RETURNS
285 * None
287 static void VIRTUAL_GetWin32Prot(
288 BYTE vprot, /* [in] Page protection flags */
289 DWORD *protect, /* [out] Location to store Win32 protection flags */
290 DWORD *state /* [out] Location to store mem state flag */
292 if (protect) {
293 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
294 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
295 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
297 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
300 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
304 /***********************************************************************
305 * VIRTUAL_GetProt
307 * Build page protections from Win32 flags.
309 * RETURNS
310 * Value of page protection flags
312 static BYTE VIRTUAL_GetProt(
313 DWORD protect /* [in] Win32 protection flags */
315 BYTE vprot;
317 switch(protect & 0xff)
319 case PAGE_READONLY:
320 vprot = VPROT_READ;
321 break;
322 case PAGE_READWRITE:
323 vprot = VPROT_READ | VPROT_WRITE;
324 break;
325 case PAGE_WRITECOPY:
326 vprot = VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
327 break;
328 case PAGE_EXECUTE:
329 vprot = VPROT_EXEC;
330 break;
331 case PAGE_EXECUTE_READ:
332 vprot = VPROT_EXEC | VPROT_READ;
333 break;
334 case PAGE_EXECUTE_READWRITE:
335 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
336 break;
337 case PAGE_EXECUTE_WRITECOPY:
338 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
339 break;
340 case PAGE_NOACCESS:
341 default:
342 vprot = 0;
343 break;
345 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
346 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
347 return vprot;
351 /***********************************************************************
352 * VIRTUAL_SetProt
354 * Change the protection of a range of pages.
356 * RETURNS
357 * TRUE: Success
358 * FALSE: Failure
360 static BOOL VIRTUAL_SetProt(
361 FILE_VIEW *view, /* [in] Pointer to view */
362 UINT base, /* [in] Starting address */
363 UINT size, /* [in] Size in bytes */
364 BYTE vprot /* [in] Protections to use */
366 TRACE(virtual, "%08x-%08x %s\n",
367 base, base + size - 1, VIRTUAL_GetProtStr( vprot ) );
369 if (mprotect( (void *)base, size, VIRTUAL_GetUnixProt(vprot) ))
370 return FALSE; /* FIXME: last error */
372 memset( view->prot + ((base - view->base) >> page_shift),
373 vprot, size >> page_shift );
374 VIRTUAL_DEBUG_DUMP_VIEW( view );
375 return TRUE;
379 /***********************************************************************
380 * VIRTUAL_CheckFlags
382 * Check that all pages in a range have the given flags.
384 * RETURNS
385 * TRUE: They do
386 * FALSE: They do not
388 static BOOL VIRTUAL_CheckFlags(
389 UINT base, /* [in] Starting address */
390 UINT size, /* [in] Size in bytes */
391 BYTE flags /* [in] Flags to check for */
393 FILE_VIEW *view;
394 UINT page;
396 if (!size) return TRUE;
397 if (!(view = VIRTUAL_FindView( base ))) return FALSE;
398 if (view->base + view->size < base + size) return FALSE;
399 page = (base - view->base) >> page_shift;
400 size = ROUND_SIZE( base, size ) >> page_shift;
401 while (size--) if ((view->prot[page++] & flags) != flags) return FALSE;
402 return TRUE;
406 /***********************************************************************
407 * VIRTUAL_Init
409 BOOL VIRTUAL_Init(void)
411 #ifndef __i386__
412 DWORD page_size;
414 # ifdef HAVE_GETPAGESIZE
415 page_size = getpagesize();
416 # else
417 # ifdef __svr4__
418 page_size = sysconf(_SC_PAGESIZE);
419 # else
420 # error Cannot get the page size on this platform
421 # endif
422 # endif
423 page_mask = page_size - 1;
424 granularity_mask = 0xffff; /* hard-coded for now */
425 /* Make sure we have a power of 2 */
426 assert( !(page_size & page_mask) );
427 page_shift = 0;
428 while ((1 << page_shift) != page_size) page_shift++;
429 #endif /* !__i386__ */
431 #ifdef linux
433 /* Do not use stdio here since it may temporarily change the size
434 * of some segments (ie libc6 adds 0x1000 per open FILE)
436 int fd = open ("/proc/self/maps", O_RDONLY);
437 if (fd >= 0)
439 char buffer[512]; /* line might be rather long in 2.1 */
441 for (;;)
443 int start, end, offset;
444 char r, w, x, p;
445 BYTE vprot = VPROT_COMMITTED;
447 char * ptr = buffer;
448 int count = sizeof(buffer);
449 while (1 == read(fd, ptr, 1) && *ptr != '\n' && --count > 0)
450 ptr++;
452 if (*ptr != '\n') break;
453 *ptr = '\0';
455 sscanf( buffer, "%x-%x %c%c%c%c %x",
456 &start, &end, &r, &w, &x, &p, &offset );
457 if (r == 'r') vprot |= VPROT_READ;
458 if (w == 'w') vprot |= VPROT_WRITE;
459 if (x == 'x') vprot |= VPROT_EXEC;
460 if (p == 'p') vprot |= VPROT_WRITECOPY;
461 VIRTUAL_CreateView( start, end - start, 0,
462 VFLAG_SYSTEM, vprot, -1 );
464 close (fd);
467 #endif /* linux */
468 return TRUE;
472 /***********************************************************************
473 * VIRTUAL_GetPageSize
475 DWORD VIRTUAL_GetPageSize(void)
477 return 1 << page_shift;
481 /***********************************************************************
482 * VIRTUAL_GetGranularity
484 DWORD VIRTUAL_GetGranularity(void)
486 return granularity_mask + 1;
490 /***********************************************************************
491 * VIRTUAL_SetFaultHandler
493 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
495 FILE_VIEW *view;
497 if (!(view = VIRTUAL_FindView((UINT)addr))) return FALSE;
498 view->handlerProc = proc;
499 view->handlerArg = arg;
500 return TRUE;
503 /***********************************************************************
504 * VIRTUAL_HandleFault
506 BOOL VIRTUAL_HandleFault( LPCVOID addr )
508 FILE_VIEW *view = VIRTUAL_FindView((UINT)addr);
510 if (view && view->handlerProc)
511 return view->handlerProc(view->handlerArg, addr);
512 return FALSE;
516 /***********************************************************************
517 * VirtualAlloc (KERNEL32.548)
518 * Reserves or commits a region of pages in virtual address space
520 * RETURNS
521 * Base address of allocated region of pages
522 * NULL: Failure
524 LPVOID WINAPI VirtualAlloc(
525 LPVOID addr, /* [in] Address of region to reserve or commit */
526 DWORD size, /* [in] Size of region */
527 DWORD type, /* [in] Type of allocation */
528 DWORD protect /* [in] Type of access protection */
530 FILE_VIEW *view;
531 UINT base, ptr, view_size;
532 BYTE vprot;
534 TRACE(virtual, "%08x %08lx %lx %08lx\n",
535 (UINT)addr, size, type, protect );
537 /* Round parameters to a page boundary */
539 if (size > 0x7fc00000) /* 2Gb - 4Mb */
541 SetLastError( ERROR_OUTOFMEMORY );
542 return NULL;
544 if (addr)
546 if (type & MEM_RESERVE) /* Round down to 64k boundary */
547 base = ((UINT)addr + granularity_mask) & ~granularity_mask;
548 else
549 base = ROUND_ADDR( addr );
550 size = (((UINT)addr + size + page_mask) & ~page_mask) - base;
551 if (base + size < base) /* Disallow wrap-around */
553 SetLastError( ERROR_INVALID_PARAMETER );
554 return NULL;
557 else
559 base = 0;
560 size = (size + page_mask) & ~page_mask;
563 if (type & MEM_TOP_DOWN) {
564 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
565 * Is there _ANY_ way to do it with UNIX mmap()?
567 WARN(virtual,"MEM_TOP_DOWN ignored\n");
568 type &= ~MEM_TOP_DOWN;
570 /* Compute the protection flags */
572 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
573 (type & ~(MEM_COMMIT | MEM_RESERVE)))
575 SetLastError( ERROR_INVALID_PARAMETER );
576 return NULL;
578 if (type & MEM_COMMIT)
579 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
580 else vprot = 0;
582 /* Reserve the memory */
584 if ((type & MEM_RESERVE) || !base)
586 view_size = size + (base ? 0 : granularity_mask + 1);
587 ptr = (UINT)FILE_dommap( -1, (LPVOID)base, 0, view_size, 0, 0,
588 VIRTUAL_GetUnixProt( vprot ), MAP_PRIVATE );
589 if (ptr == (UINT)-1)
591 SetLastError( ERROR_OUTOFMEMORY );
592 return NULL;
594 if (!base)
596 /* Release the extra memory while keeping the range */
597 /* starting on a 64k boundary. */
599 if (ptr & granularity_mask)
601 UINT extra = granularity_mask + 1 - (ptr & granularity_mask);
602 FILE_munmap( (void *)ptr, 0, extra );
603 ptr += extra;
604 view_size -= extra;
606 if (view_size > size)
607 FILE_munmap( (void *)(ptr + size), 0, view_size - size );
609 else if (ptr != base)
611 /* We couldn't get the address we wanted */
612 FILE_munmap( (void *)ptr, 0, view_size );
613 SetLastError( ERROR_INVALID_ADDRESS );
614 return NULL;
616 if (!(view = VIRTUAL_CreateView( ptr, size, 0, 0, vprot, -1 )))
618 FILE_munmap( (void *)ptr, 0, size );
619 SetLastError( ERROR_OUTOFMEMORY );
620 return NULL;
622 VIRTUAL_DEBUG_DUMP_VIEW( view );
623 return (LPVOID)ptr;
626 /* Commit the pages */
628 if (!(view = VIRTUAL_FindView( base )) ||
629 (base + size > view->base + view->size))
631 SetLastError( ERROR_INVALID_PARAMETER );
632 return NULL;
635 if (!VIRTUAL_SetProt( view, base, size, vprot )) return NULL;
636 return (LPVOID)base;
640 /***********************************************************************
641 * VirtualFree (KERNEL32.550)
642 * Release or decommits a region of pages in virtual address space.
644 * RETURNS
645 * TRUE: Success
646 * FALSE: Failure
648 BOOL WINAPI VirtualFree(
649 LPVOID addr, /* [in] Address of region of committed pages */
650 DWORD size, /* [in] Size of region */
651 DWORD type /* [in] Type of operation */
653 FILE_VIEW *view;
654 UINT base;
656 TRACE(virtual, "%08x %08lx %lx\n",
657 (UINT)addr, size, type );
659 /* Fix the parameters */
661 size = ROUND_SIZE( addr, size );
662 base = ROUND_ADDR( addr );
664 if (!(view = VIRTUAL_FindView( base )) ||
665 (base + size > view->base + view->size))
667 SetLastError( ERROR_INVALID_PARAMETER );
668 return FALSE;
671 /* Compute the protection flags */
673 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
675 SetLastError( ERROR_INVALID_PARAMETER );
676 return FALSE;
679 /* Free the pages */
681 if (type == MEM_RELEASE)
683 if (size || (base != view->base))
685 SetLastError( ERROR_INVALID_PARAMETER );
686 return FALSE;
688 VIRTUAL_DeleteView( view );
689 return TRUE;
692 /* Decommit the pages */
693 return VIRTUAL_SetProt( view, base, size, 0 );
697 /***********************************************************************
698 * VirtualLock (KERNEL32.551)
699 * Locks the specified region of virtual address space
701 * NOTE
702 * Always returns TRUE
704 * RETURNS
705 * TRUE: Success
706 * FALSE: Failure
708 BOOL WINAPI VirtualLock(
709 LPVOID addr, /* [in] Address of first byte of range to lock */
710 DWORD size /* [in] Number of bytes in range to lock */
712 return TRUE;
716 /***********************************************************************
717 * VirtualUnlock (KERNEL32.556)
718 * Unlocks a range of pages in the virtual address space
720 * NOTE
721 * Always returns TRUE
723 * RETURNS
724 * TRUE: Success
725 * FALSE: Failure
727 BOOL WINAPI VirtualUnlock(
728 LPVOID addr, /* [in] Address of first byte of range */
729 DWORD size /* [in] Number of bytes in range */
731 return TRUE;
735 /***********************************************************************
736 * VirtualProtect (KERNEL32.552)
737 * Changes the access protection on a region of committed pages
739 * RETURNS
740 * TRUE: Success
741 * FALSE: Failure
743 BOOL WINAPI VirtualProtect(
744 LPVOID addr, /* [in] Address of region of committed pages */
745 DWORD size, /* [in] Size of region */
746 DWORD new_prot, /* [in] Desired access protection */
747 LPDWORD old_prot /* [out] Address of variable to get old protection */
749 FILE_VIEW *view;
750 UINT base, i;
751 BYTE vprot, *p;
753 TRACE(virtual, "%08x %08lx %08lx\n",
754 (UINT)addr, size, new_prot );
756 /* Fix the parameters */
758 size = ROUND_SIZE( addr, size );
759 base = ROUND_ADDR( addr );
761 if (!(view = VIRTUAL_FindView( base )) ||
762 (base + size > view->base + view->size))
764 SetLastError( ERROR_INVALID_PARAMETER );
765 return FALSE;
768 /* Make sure all the pages are committed */
770 p = view->prot + ((base - view->base) >> page_shift);
771 for (i = size >> page_shift; i; i--, p++)
773 if (!(*p & VPROT_COMMITTED))
775 SetLastError( ERROR_INVALID_PARAMETER );
776 return FALSE;
780 VIRTUAL_GetWin32Prot( view->prot[0], old_prot, NULL );
781 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
782 return VIRTUAL_SetProt( view, base, size, vprot );
786 /***********************************************************************
787 * VirtualProtectEx (KERNEL32.553)
788 * Changes the access protection on a region of committed pages in the
789 * virtual address space of a specified process
791 * RETURNS
792 * TRUE: Success
793 * FALSE: Failure
795 BOOL WINAPI VirtualProtectEx(
796 HANDLE handle, /* [in] Handle of process */
797 LPVOID addr, /* [in] Address of region of committed pages */
798 DWORD size, /* [in] Size of region */
799 DWORD new_prot, /* [in] Desired access protection */
800 LPDWORD old_prot /* [out] Address of variable to get old protection */ )
802 if (PROCESS_IsCurrent( handle ))
803 return VirtualProtect( addr, size, new_prot, old_prot );
804 ERR(virtual,"Unsupported on other process\n");
805 return FALSE;
809 /***********************************************************************
810 * VirtualQuery (KERNEL32.554)
811 * Provides info about a range of pages in virtual address space
813 * RETURNS
814 * Number of bytes returned in information buffer
816 DWORD WINAPI VirtualQuery(
817 LPCVOID addr, /* [in] Address of region */
818 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
819 DWORD len /* [in] Size of buffer */
821 FILE_VIEW *view = VIRTUAL_FirstView;
822 UINT base = ROUND_ADDR( addr );
823 UINT alloc_base = 0;
824 UINT size = 0;
826 /* Find the view containing the address */
828 for (;;)
830 if (!view)
832 size = 0xffff0000 - alloc_base;
833 break;
835 if (view->base > base)
837 size = view->base - alloc_base;
838 view = NULL;
839 break;
841 if (view->base + view->size > base)
843 alloc_base = view->base;
844 size = view->size;
845 break;
847 alloc_base = view->base + view->size;
848 view = view->next;
851 /* Fill the info structure */
853 if (!view)
855 info->State = MEM_FREE;
856 info->Protect = 0;
857 info->AllocationProtect = 0;
858 info->Type = 0;
860 else
862 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
863 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
864 for (size = base - alloc_base; size < view->size; size += page_mask+1)
865 if (view->prot[size >> page_shift] != vprot) break;
866 info->AllocationProtect = view->protect;
867 info->Type = MEM_PRIVATE; /* FIXME */
870 info->BaseAddress = (LPVOID)base;
871 info->AllocationBase = (LPVOID)alloc_base;
872 info->RegionSize = size - (base - alloc_base);
873 return sizeof(*info);
877 /***********************************************************************
878 * VirtualQueryEx (KERNEL32.555)
879 * Provides info about a range of pages in virtual address space of a
880 * specified process
882 * RETURNS
883 * Number of bytes returned in information buffer
885 DWORD WINAPI VirtualQueryEx(
886 HANDLE handle, /* [in] Handle of process */
887 LPCVOID addr, /* [in] Address of region */
888 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
889 DWORD len /* [in] Size of buffer */ )
891 if (PROCESS_IsCurrent( handle ))
892 return VirtualQuery( addr, info, len );
893 ERR(virtual,"Unsupported on other process\n");
894 return 0;
898 /***********************************************************************
899 * IsBadReadPtr32 (KERNEL32.354)
901 * RETURNS
902 * FALSE: Process has read access to entire block
903 * TRUE: Otherwise
905 BOOL WINAPI IsBadReadPtr(
906 LPCVOID ptr, /* Address of memory block */
907 UINT size /* Size of block */
909 return !VIRTUAL_CheckFlags( (UINT)ptr, size,
910 VPROT_READ | VPROT_COMMITTED );
914 /***********************************************************************
915 * IsBadWritePtr32 (KERNEL32.357)
917 * RETURNS
918 * FALSE: Process has write access to entire block
919 * TRUE: Otherwise
921 BOOL WINAPI IsBadWritePtr(
922 LPVOID ptr, /* [in] Address of memory block */
923 UINT size /* [in] Size of block in bytes */
925 return !VIRTUAL_CheckFlags( (UINT)ptr, size,
926 VPROT_WRITE | VPROT_COMMITTED );
930 /***********************************************************************
931 * IsBadHugeReadPtr32 (KERNEL32.352)
932 * RETURNS
933 * FALSE: Process has read access to entire block
934 * TRUE: Otherwise
936 BOOL WINAPI IsBadHugeReadPtr(
937 LPCVOID ptr, /* [in] Address of memory block */
938 UINT size /* [in] Size of block */
940 return IsBadReadPtr( ptr, size );
944 /***********************************************************************
945 * IsBadHugeWritePtr32 (KERNEL32.353)
946 * RETURNS
947 * FALSE: Process has write access to entire block
948 * TRUE: Otherwise
950 BOOL WINAPI IsBadHugeWritePtr(
951 LPVOID ptr, /* [in] Address of memory block */
952 UINT size /* [in] Size of block */
954 return IsBadWritePtr( ptr, size );
958 /***********************************************************************
959 * IsBadCodePtr32 (KERNEL32.351)
961 * RETURNS
962 * FALSE: Process has read access to specified memory
963 * TRUE: Otherwise
965 BOOL WINAPI IsBadCodePtr(
966 FARPROC ptr /* [in] Address of function */
968 return !VIRTUAL_CheckFlags( (UINT)ptr, 1, VPROT_EXEC | VPROT_COMMITTED );
972 /***********************************************************************
973 * IsBadStringPtr32A (KERNEL32.355)
975 * RETURNS
976 * FALSE: Read access to all bytes in string
977 * TRUE: Else
979 BOOL WINAPI IsBadStringPtrA(
980 LPCSTR str, /* [in] Address of string */
981 UINT max /* [in] Maximum size of string */
983 FILE_VIEW *view;
984 UINT page, count;
986 if (!max) return FALSE;
987 if (!(view = VIRTUAL_FindView( (UINT)str ))) return TRUE;
988 page = ((UINT)str - view->base) >> page_shift;
989 count = page_mask + 1 - ((UINT)str & page_mask);
991 while (max)
993 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
994 (VPROT_READ | VPROT_COMMITTED))
995 return TRUE;
996 if (count > max) count = max;
997 max -= count;
998 while (count--) if (!*str++) return FALSE;
999 if (++page >= view->size >> page_shift) return TRUE;
1000 count = page_mask + 1;
1002 return FALSE;
1006 /***********************************************************************
1007 * IsBadStringPtr32W (KERNEL32.356)
1008 * See IsBadStringPtr32A
1010 BOOL WINAPI IsBadStringPtrW( LPCWSTR str, UINT max )
1012 FILE_VIEW *view;
1013 UINT page, count;
1015 if (!max) return FALSE;
1016 if (!(view = VIRTUAL_FindView( (UINT)str ))) return TRUE;
1017 page = ((UINT)str - view->base) >> page_shift;
1018 count = (page_mask + 1 - ((UINT)str & page_mask)) / sizeof(WCHAR);
1020 while (max)
1022 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
1023 (VPROT_READ | VPROT_COMMITTED))
1024 return TRUE;
1025 if (count > max) count = max;
1026 max -= count;
1027 while (count--) if (!*str++) return FALSE;
1028 if (++page >= view->size >> page_shift) return TRUE;
1029 count = (page_mask + 1) / sizeof(WCHAR);
1031 return FALSE;
1035 /***********************************************************************
1036 * CreateFileMapping32A (KERNEL32.46)
1037 * Creates a named or unnamed file-mapping object for the specified file
1039 * RETURNS
1040 * Handle: Success
1041 * 0: Mapping object does not exist
1042 * NULL: Failure
1044 HANDLE WINAPI CreateFileMappingA(
1045 HFILE hFile, /* [in] Handle of file to map */
1046 SECURITY_ATTRIBUTES *sa, /* [in] Optional security attributes*/
1047 DWORD protect, /* [in] Protection for mapping object */
1048 DWORD size_high, /* [in] High-order 32 bits of object size */
1049 DWORD size_low, /* [in] Low-order 32 bits of object size */
1050 LPCSTR name /* [in] Name of file-mapping object */ )
1052 struct create_mapping_request req;
1053 struct create_mapping_reply reply;
1054 BYTE vprot;
1056 /* Check parameters */
1058 TRACE(virtual,"(%x,%p,%08lx,%08lx%08lx,%s)\n",
1059 hFile, sa, protect, size_high, size_low, debugstr_a(name) );
1061 vprot = VIRTUAL_GetProt( protect );
1062 if (protect & SEC_RESERVE)
1064 if (hFile != INVALID_HANDLE_VALUE)
1066 SetLastError( ERROR_INVALID_PARAMETER );
1067 return 0;
1070 else vprot |= VPROT_COMMITTED;
1071 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1073 /* Create the server object */
1075 req.handle = hFile;
1076 req.size_high = size_high;
1077 req.size_low = size_low;
1078 req.protect = vprot;
1079 req.inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1080 CLIENT_SendRequest( REQ_CREATE_MAPPING, -1, 2,
1081 &req, sizeof(req),
1082 name, name ? strlen(name) + 1 : 0 );
1083 SetLastError(0);
1084 CLIENT_WaitSimpleReply( &reply, sizeof(reply), NULL );
1085 if (reply.handle == -1) return 0;
1086 return reply.handle;
1090 /***********************************************************************
1091 * CreateFileMapping32W (KERNEL32.47)
1092 * See CreateFileMapping32A
1094 HANDLE WINAPI CreateFileMappingW( HFILE hFile, LPSECURITY_ATTRIBUTES attr,
1095 DWORD protect, DWORD size_high,
1096 DWORD size_low, LPCWSTR name )
1098 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1099 HANDLE ret = CreateFileMappingA( hFile, attr, protect,
1100 size_high, size_low, nameA );
1101 HeapFree( GetProcessHeap(), 0, nameA );
1102 return ret;
1106 /***********************************************************************
1107 * OpenFileMapping32A (KERNEL32.397)
1108 * Opens a named file-mapping object.
1110 * RETURNS
1111 * Handle: Success
1112 * NULL: Failure
1114 HANDLE WINAPI OpenFileMappingA(
1115 DWORD access, /* [in] Access mode */
1116 BOOL inherit, /* [in] Inherit flag */
1117 LPCSTR name ) /* [in] Name of file-mapping object */
1119 struct open_named_obj_request req;
1120 struct open_named_obj_reply reply;
1121 int len = name ? strlen(name) + 1 : 0;
1123 req.type = OPEN_MAPPING;
1124 req.access = access;
1125 req.inherit = inherit;
1126 CLIENT_SendRequest( REQ_OPEN_NAMED_OBJ, -1, 2, &req, sizeof(req), name, len );
1127 CLIENT_WaitSimpleReply( &reply, sizeof(reply), NULL );
1128 if (reply.handle == -1) return 0; /* must return 0 on failure, not -1 */
1129 return reply.handle;
1133 /***********************************************************************
1134 * OpenFileMapping32W (KERNEL32.398)
1135 * See OpenFileMapping32A
1137 HANDLE WINAPI OpenFileMappingW( DWORD access, BOOL inherit, LPCWSTR name)
1139 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1140 HANDLE ret = OpenFileMappingA( access, inherit, nameA );
1141 HeapFree( GetProcessHeap(), 0, nameA );
1142 return ret;
1146 /***********************************************************************
1147 * MapViewOfFile (KERNEL32.385)
1148 * Maps a view of a file into the address space
1150 * RETURNS
1151 * Starting address of mapped view
1152 * NULL: Failure
1154 LPVOID WINAPI MapViewOfFile(
1155 HANDLE mapping, /* [in] File-mapping object to map */
1156 DWORD access, /* [in] Access mode */
1157 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1158 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1159 DWORD count /* [in] Number of bytes to map */
1161 return MapViewOfFileEx( mapping, access, offset_high,
1162 offset_low, count, NULL );
1166 /***********************************************************************
1167 * MapViewOfFileEx (KERNEL32.386)
1168 * Maps a view of a file into the address space
1170 * RETURNS
1171 * Starting address of mapped view
1172 * NULL: Failure
1174 LPVOID WINAPI MapViewOfFileEx(
1175 HANDLE handle, /* [in] File-mapping object to map */
1176 DWORD access, /* [in] Access mode */
1177 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1178 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1179 DWORD count, /* [in] Number of bytes to map */
1180 LPVOID addr /* [in] Suggested starting address for mapped view */
1182 FILE_VIEW *view;
1183 UINT ptr = (UINT)-1, size = 0;
1184 int flags = MAP_PRIVATE;
1185 int unix_handle = -1;
1186 struct get_mapping_info_request req;
1187 struct get_mapping_info_reply info;
1189 /* Check parameters */
1191 if ((offset_low & granularity_mask) ||
1192 (addr && ((UINT)addr & granularity_mask)))
1194 SetLastError( ERROR_INVALID_PARAMETER );
1195 return NULL;
1198 req.handle = handle;
1199 CLIENT_SendRequest( REQ_GET_MAPPING_INFO, -1, 1, &req, sizeof(req) );
1200 if (CLIENT_WaitSimpleReply( &info, sizeof(info), &unix_handle ))
1201 goto error;
1203 if (info.size_high || offset_high)
1204 ERR(virtual, "Offsets larger than 4Gb not supported\n");
1206 if ((offset_low >= info.size_low) ||
1207 (count > info.size_low - offset_low))
1209 SetLastError( ERROR_INVALID_PARAMETER );
1210 goto error;
1212 if (count) size = ROUND_SIZE( offset_low, count );
1213 else size = info.size_low - offset_low;
1215 switch(access)
1217 case FILE_MAP_ALL_ACCESS:
1218 case FILE_MAP_WRITE:
1219 case FILE_MAP_WRITE | FILE_MAP_READ:
1220 if (!(info.protect & VPROT_WRITE))
1222 SetLastError( ERROR_INVALID_PARAMETER );
1223 goto error;
1225 flags = MAP_SHARED;
1226 /* fall through */
1227 case FILE_MAP_READ:
1228 case FILE_MAP_COPY:
1229 case FILE_MAP_COPY | FILE_MAP_READ:
1230 if (info.protect & VPROT_READ) break;
1231 /* fall through */
1232 default:
1233 SetLastError( ERROR_INVALID_PARAMETER );
1234 goto error;
1237 /* Map the file */
1239 TRACE(virtual, "handle=%x size=%x offset=%lx\n",
1240 handle, size, offset_low );
1242 ptr = (UINT)FILE_dommap( unix_handle,
1243 addr, 0, size, 0, offset_low,
1244 VIRTUAL_GetUnixProt( info.protect ),
1245 flags );
1246 if (ptr == (UINT)-1) {
1247 /* KB: Q125713, 25-SEP-1995, "Common File Mapping Problems and
1248 * Platform Differences":
1249 * Windows NT: ERROR_INVALID_PARAMETER
1250 * Windows 95: ERROR_INVALID_ADDRESS.
1251 * FIXME: So should we add a module dependend check here? -MM
1253 if (errno==ENOMEM)
1254 SetLastError( ERROR_OUTOFMEMORY );
1255 else
1256 SetLastError( ERROR_INVALID_PARAMETER );
1257 goto error;
1260 if (!(view = VIRTUAL_CreateView( ptr, size, offset_low, 0,
1261 info.protect, handle )))
1263 SetLastError( ERROR_OUTOFMEMORY );
1264 goto error;
1266 if (unix_handle != -1) close( unix_handle );
1267 return (LPVOID)ptr;
1269 error:
1270 if (unix_handle != -1) close( unix_handle );
1271 if (ptr != (UINT)-1) FILE_munmap( (void *)ptr, 0, size );
1272 return NULL;
1276 /***********************************************************************
1277 * FlushViewOfFile (KERNEL32.262)
1278 * Writes to the disk a byte range within a mapped view of a file
1280 * RETURNS
1281 * TRUE: Success
1282 * FALSE: Failure
1284 BOOL WINAPI FlushViewOfFile(
1285 LPCVOID base, /* [in] Start address of byte range to flush */
1286 DWORD cbFlush /* [in] Number of bytes in range */
1288 FILE_VIEW *view;
1289 UINT addr = ROUND_ADDR( base );
1291 TRACE(virtual, "FlushViewOfFile at %p for %ld bytes\n",
1292 base, cbFlush );
1294 if (!(view = VIRTUAL_FindView( addr )))
1296 SetLastError( ERROR_INVALID_PARAMETER );
1297 return FALSE;
1299 if (!cbFlush) cbFlush = view->size;
1300 if (!msync( (void *)addr, cbFlush, MS_SYNC )) return TRUE;
1301 SetLastError( ERROR_INVALID_PARAMETER );
1302 return FALSE;
1306 /***********************************************************************
1307 * UnmapViewOfFile (KERNEL32.540)
1308 * Unmaps a mapped view of a file.
1310 * NOTES
1311 * Should addr be an LPCVOID?
1313 * RETURNS
1314 * TRUE: Success
1315 * FALSE: Failure
1317 BOOL WINAPI UnmapViewOfFile(
1318 LPVOID addr /* [in] Address where mapped view begins */
1320 FILE_VIEW *view;
1321 UINT base = ROUND_ADDR( addr );
1322 if (!(view = VIRTUAL_FindView( base )) || (base != view->base))
1324 SetLastError( ERROR_INVALID_PARAMETER );
1325 return FALSE;
1327 VIRTUAL_DeleteView( view );
1328 return TRUE;
1331 /***********************************************************************
1332 * VIRTUAL_MapFileW
1334 * Helper function to map a file to memory:
1335 * name - file name
1336 * [RETURN] ptr - pointer to mapped file
1338 LPVOID VIRTUAL_MapFileW( LPCWSTR name )
1340 HANDLE hFile, hMapping;
1341 LPVOID ptr = NULL;
1343 hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
1344 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0);
1345 if (hFile != INVALID_HANDLE_VALUE)
1347 hMapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1348 CloseHandle( hFile );
1349 if (hMapping)
1351 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
1352 CloseHandle( hMapping );
1355 return ptr;