Added TEB in init_thread request.
[wine/multimedia.git] / memory / virtual.c
blob5e810e0aa54c9c493f6e791d0661a37bc4cd31a4
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 DEFAULT_DEBUG_CHANNEL(virtual)
28 #ifndef MS_SYNC
29 #define MS_SYNC 0
30 #endif
32 /* File view */
33 typedef struct _FV
35 struct _FV *next; /* Next view */
36 struct _FV *prev; /* Prev view */
37 UINT base; /* Base address */
38 UINT size; /* Size in bytes */
39 UINT flags; /* Allocation flags */
40 UINT offset; /* Offset from start of mapped file */
41 HANDLE mapping; /* Handle to the file mapping */
42 HANDLERPROC handlerProc; /* Fault handler */
43 LPVOID handlerArg; /* Fault handler argument */
44 BYTE protect; /* Protection for all pages at allocation time */
45 BYTE prot[1]; /* Protection byte for each page */
46 } FILE_VIEW;
48 /* Per-view flags */
49 #define VFLAG_SYSTEM 0x01
51 /* Conversion from VPROT_* to Win32 flags */
52 static const BYTE VIRTUAL_Win32Flags[16] =
54 PAGE_NOACCESS, /* 0 */
55 PAGE_READONLY, /* READ */
56 PAGE_READWRITE, /* WRITE */
57 PAGE_READWRITE, /* READ | WRITE */
58 PAGE_EXECUTE, /* EXEC */
59 PAGE_EXECUTE_READ, /* READ | EXEC */
60 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
61 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
62 PAGE_WRITECOPY, /* WRITECOPY */
63 PAGE_WRITECOPY, /* READ | WRITECOPY */
64 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
65 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
66 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
67 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
68 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
69 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
73 static FILE_VIEW *VIRTUAL_FirstView;
75 #ifdef __i386__
76 /* These are always the same on an i386, and it will be faster this way */
77 # define page_mask 0xfff
78 # define page_shift 12
79 # define granularity_mask 0xffff
80 #else
81 static UINT page_shift;
82 static UINT page_mask;
83 static UINT granularity_mask; /* Allocation granularity (usually 64k) */
84 #endif /* __i386__ */
86 #define ROUND_ADDR(addr) \
87 ((UINT)(addr) & ~page_mask)
89 #define ROUND_SIZE(addr,size) \
90 (((UINT)(size) + ((UINT)(addr) & page_mask) + page_mask) & ~page_mask)
92 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
93 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
95 /***********************************************************************
96 * VIRTUAL_GetProtStr
98 static const char *VIRTUAL_GetProtStr( BYTE prot )
100 static char buffer[6];
101 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
102 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
103 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
104 buffer[3] = (prot & VPROT_WRITE) ?
105 ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
106 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
107 buffer[5] = 0;
108 return buffer;
112 /***********************************************************************
113 * VIRTUAL_DumpView
115 static void VIRTUAL_DumpView( FILE_VIEW *view )
117 UINT i, count;
118 UINT addr = view->base;
119 BYTE prot = view->prot[0];
121 DUMP( "View: %08x - %08x%s",
122 view->base, view->base + view->size - 1,
123 (view->flags & VFLAG_SYSTEM) ? " (system)" : "" );
124 if (view->mapping)
125 DUMP( " %d @ %08x\n", view->mapping, view->offset );
126 else
127 DUMP( " (anonymous)\n");
129 for (count = i = 1; i < view->size >> page_shift; i++, count++)
131 if (view->prot[i] == prot) continue;
132 DUMP( " %08x - %08x %s\n",
133 addr, addr + (count << page_shift) - 1,
134 VIRTUAL_GetProtStr(prot) );
135 addr += (count << page_shift);
136 prot = view->prot[i];
137 count = 0;
139 if (count)
140 DUMP( " %08x - %08x %s\n",
141 addr, addr + (count << page_shift) - 1,
142 VIRTUAL_GetProtStr(prot) );
146 /***********************************************************************
147 * VIRTUAL_Dump
149 void VIRTUAL_Dump(void)
151 FILE_VIEW *view = VIRTUAL_FirstView;
152 DUMP( "\nDump of all virtual memory views:\n\n" );
153 while (view)
155 VIRTUAL_DumpView( view );
156 view = view->next;
161 /***********************************************************************
162 * VIRTUAL_FindView
164 * Find the view containing a given address.
166 * RETURNS
167 * View: Success
168 * NULL: Failure
170 static FILE_VIEW *VIRTUAL_FindView(
171 UINT addr /* [in] Address */
173 FILE_VIEW *view = VIRTUAL_FirstView;
174 while (view)
176 if (view->base > addr) return NULL;
177 if (view->base + view->size > addr) return view;
178 view = view->next;
180 return NULL;
184 /***********************************************************************
185 * VIRTUAL_CreateView
187 * Create a new view and add it in the linked list.
189 static FILE_VIEW *VIRTUAL_CreateView( UINT base, UINT size, UINT offset,
190 UINT flags, BYTE vprot,
191 HANDLE mapping )
193 FILE_VIEW *view, *prev;
195 /* Create the view structure */
197 assert( !(base & page_mask) );
198 assert( !(size & page_mask) );
199 size >>= page_shift;
200 if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
201 view->base = base;
202 view->size = size << page_shift;
203 view->flags = flags;
204 view->offset = offset;
205 view->mapping = mapping;
206 view->protect = vprot;
207 view->handlerProc = NULL;
208 memset( view->prot, vprot, size );
210 /* Duplicate the mapping handle */
212 if ((view->mapping != -1) &&
213 !DuplicateHandle( GetCurrentProcess(), view->mapping,
214 GetCurrentProcess(), &view->mapping,
215 0, FALSE, DUPLICATE_SAME_ACCESS ))
217 free( view );
218 return NULL;
221 /* Insert it in the linked list */
223 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
225 view->next = VIRTUAL_FirstView;
226 view->prev = NULL;
227 if (view->next) view->next->prev = view;
228 VIRTUAL_FirstView = view;
230 else
232 prev = VIRTUAL_FirstView;
233 while (prev->next && (prev->next->base < base)) prev = prev->next;
234 view->next = prev->next;
235 view->prev = prev;
236 if (view->next) view->next->prev = view;
237 prev->next = view;
239 VIRTUAL_DEBUG_DUMP_VIEW( view );
240 return view;
244 /***********************************************************************
245 * VIRTUAL_DeleteView
246 * Deletes a view.
248 * RETURNS
249 * None
251 static void VIRTUAL_DeleteView(
252 FILE_VIEW *view /* [in] View */
254 FILE_munmap( (void *)view->base, 0, view->size );
255 if (view->next) view->next->prev = view->prev;
256 if (view->prev) view->prev->next = view->next;
257 else VIRTUAL_FirstView = view->next;
258 if (view->mapping) CloseHandle( view->mapping );
259 free( view );
263 /***********************************************************************
264 * VIRTUAL_GetUnixProt
266 * Convert page protections to protection for mmap/mprotect.
268 static int VIRTUAL_GetUnixProt( BYTE vprot )
270 int prot = 0;
271 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
273 if (vprot & VPROT_READ) prot |= PROT_READ;
274 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
275 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
277 return prot;
281 /***********************************************************************
282 * VIRTUAL_GetWin32Prot
284 * Convert page protections to Win32 flags.
286 * RETURNS
287 * None
289 static void VIRTUAL_GetWin32Prot(
290 BYTE vprot, /* [in] Page protection flags */
291 DWORD *protect, /* [out] Location to store Win32 protection flags */
292 DWORD *state /* [out] Location to store mem state flag */
294 if (protect) {
295 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
296 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
297 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
299 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
302 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
306 /***********************************************************************
307 * VIRTUAL_GetProt
309 * Build page protections from Win32 flags.
311 * RETURNS
312 * Value of page protection flags
314 static BYTE VIRTUAL_GetProt(
315 DWORD protect /* [in] Win32 protection flags */
317 BYTE vprot;
319 switch(protect & 0xff)
321 case PAGE_READONLY:
322 vprot = VPROT_READ;
323 break;
324 case PAGE_READWRITE:
325 vprot = VPROT_READ | VPROT_WRITE;
326 break;
327 case PAGE_WRITECOPY:
328 vprot = VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
329 break;
330 case PAGE_EXECUTE:
331 vprot = VPROT_EXEC;
332 break;
333 case PAGE_EXECUTE_READ:
334 vprot = VPROT_EXEC | VPROT_READ;
335 break;
336 case PAGE_EXECUTE_READWRITE:
337 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
338 break;
339 case PAGE_EXECUTE_WRITECOPY:
340 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
341 break;
342 case PAGE_NOACCESS:
343 default:
344 vprot = 0;
345 break;
347 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
348 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
349 return vprot;
353 /***********************************************************************
354 * VIRTUAL_SetProt
356 * Change the protection of a range of pages.
358 * RETURNS
359 * TRUE: Success
360 * FALSE: Failure
362 static BOOL VIRTUAL_SetProt(
363 FILE_VIEW *view, /* [in] Pointer to view */
364 UINT base, /* [in] Starting address */
365 UINT size, /* [in] Size in bytes */
366 BYTE vprot /* [in] Protections to use */
368 TRACE(virtual, "%08x-%08x %s\n",
369 base, base + size - 1, VIRTUAL_GetProtStr( vprot ) );
371 if (mprotect( (void *)base, size, VIRTUAL_GetUnixProt(vprot) ))
372 return FALSE; /* FIXME: last error */
374 memset( view->prot + ((base - view->base) >> page_shift),
375 vprot, size >> page_shift );
376 VIRTUAL_DEBUG_DUMP_VIEW( view );
377 return TRUE;
381 /***********************************************************************
382 * VIRTUAL_CheckFlags
384 * Check that all pages in a range have the given flags.
386 * RETURNS
387 * TRUE: They do
388 * FALSE: They do not
390 static BOOL VIRTUAL_CheckFlags(
391 UINT base, /* [in] Starting address */
392 UINT size, /* [in] Size in bytes */
393 BYTE flags /* [in] Flags to check for */
395 FILE_VIEW *view;
396 UINT page;
398 if (!size) return TRUE;
399 if (!(view = VIRTUAL_FindView( base ))) return FALSE;
400 if (view->base + view->size < base + size) return FALSE;
401 page = (base - view->base) >> page_shift;
402 size = ROUND_SIZE( base, size ) >> page_shift;
403 while (size--) if ((view->prot[page++] & flags) != flags) return FALSE;
404 return TRUE;
408 /***********************************************************************
409 * VIRTUAL_Init
411 BOOL VIRTUAL_Init(void)
413 #ifndef __i386__
414 DWORD page_size;
416 # ifdef HAVE_GETPAGESIZE
417 page_size = getpagesize();
418 # else
419 # ifdef __svr4__
420 page_size = sysconf(_SC_PAGESIZE);
421 # else
422 # error Cannot get the page size on this platform
423 # endif
424 # endif
425 page_mask = page_size - 1;
426 granularity_mask = 0xffff; /* hard-coded for now */
427 /* Make sure we have a power of 2 */
428 assert( !(page_size & page_mask) );
429 page_shift = 0;
430 while ((1 << page_shift) != page_size) page_shift++;
431 #endif /* !__i386__ */
433 #ifdef linux
435 /* Do not use stdio here since it may temporarily change the size
436 * of some segments (ie libc6 adds 0x1000 per open FILE)
438 int fd = open ("/proc/self/maps", O_RDONLY);
439 if (fd >= 0)
441 char buffer[512]; /* line might be rather long in 2.1 */
443 for (;;)
445 int start, end, offset;
446 char r, w, x, p;
447 BYTE vprot = VPROT_COMMITTED;
449 char * ptr = buffer;
450 int count = sizeof(buffer);
451 while (1 == read(fd, ptr, 1) && *ptr != '\n' && --count > 0)
452 ptr++;
454 if (*ptr != '\n') break;
455 *ptr = '\0';
457 sscanf( buffer, "%x-%x %c%c%c%c %x",
458 &start, &end, &r, &w, &x, &p, &offset );
459 if (r == 'r') vprot |= VPROT_READ;
460 if (w == 'w') vprot |= VPROT_WRITE;
461 if (x == 'x') vprot |= VPROT_EXEC;
462 if (p == 'p') vprot |= VPROT_WRITECOPY;
463 VIRTUAL_CreateView( start, end - start, 0,
464 VFLAG_SYSTEM, vprot, -1 );
466 close (fd);
469 #endif /* linux */
470 return TRUE;
474 /***********************************************************************
475 * VIRTUAL_GetPageSize
477 DWORD VIRTUAL_GetPageSize(void)
479 return 1 << page_shift;
483 /***********************************************************************
484 * VIRTUAL_GetGranularity
486 DWORD VIRTUAL_GetGranularity(void)
488 return granularity_mask + 1;
492 /***********************************************************************
493 * VIRTUAL_SetFaultHandler
495 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
497 FILE_VIEW *view;
499 if (!(view = VIRTUAL_FindView((UINT)addr))) return FALSE;
500 view->handlerProc = proc;
501 view->handlerArg = arg;
502 return TRUE;
505 /***********************************************************************
506 * VIRTUAL_HandleFault
508 BOOL VIRTUAL_HandleFault( LPCVOID addr )
510 FILE_VIEW *view = VIRTUAL_FindView((UINT)addr);
512 if (view && view->handlerProc)
513 return view->handlerProc(view->handlerArg, addr);
514 return FALSE;
518 /***********************************************************************
519 * VirtualAlloc (KERNEL32.548)
520 * Reserves or commits a region of pages in virtual address space
522 * RETURNS
523 * Base address of allocated region of pages
524 * NULL: Failure
526 LPVOID WINAPI VirtualAlloc(
527 LPVOID addr, /* [in] Address of region to reserve or commit */
528 DWORD size, /* [in] Size of region */
529 DWORD type, /* [in] Type of allocation */
530 DWORD protect /* [in] Type of access protection */
532 FILE_VIEW *view;
533 UINT base, ptr, view_size;
534 BYTE vprot;
536 TRACE(virtual, "%08x %08lx %lx %08lx\n",
537 (UINT)addr, size, type, protect );
539 /* Round parameters to a page boundary */
541 if (size > 0x7fc00000) /* 2Gb - 4Mb */
543 SetLastError( ERROR_OUTOFMEMORY );
544 return NULL;
546 if (addr)
548 if (type & MEM_RESERVE) /* Round down to 64k boundary */
549 base = ((UINT)addr + granularity_mask) & ~granularity_mask;
550 else
551 base = ROUND_ADDR( addr );
552 size = (((UINT)addr + size + page_mask) & ~page_mask) - base;
553 if (base + size < base) /* Disallow wrap-around */
555 SetLastError( ERROR_INVALID_PARAMETER );
556 return NULL;
559 else
561 base = 0;
562 size = (size + page_mask) & ~page_mask;
565 if (type & MEM_TOP_DOWN) {
566 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
567 * Is there _ANY_ way to do it with UNIX mmap()?
569 WARN(virtual,"MEM_TOP_DOWN ignored\n");
570 type &= ~MEM_TOP_DOWN;
572 /* Compute the protection flags */
574 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
575 (type & ~(MEM_COMMIT | MEM_RESERVE)))
577 SetLastError( ERROR_INVALID_PARAMETER );
578 return NULL;
580 if (type & MEM_COMMIT)
581 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
582 else vprot = 0;
584 /* Reserve the memory */
586 if ((type & MEM_RESERVE) || !base)
588 view_size = size + (base ? 0 : granularity_mask + 1);
589 ptr = (UINT)FILE_dommap( -1, (LPVOID)base, 0, view_size, 0, 0,
590 VIRTUAL_GetUnixProt( vprot ), MAP_PRIVATE );
591 if (ptr == (UINT)-1)
593 SetLastError( ERROR_OUTOFMEMORY );
594 return NULL;
596 if (!base)
598 /* Release the extra memory while keeping the range */
599 /* starting on a 64k boundary. */
601 if (ptr & granularity_mask)
603 UINT extra = granularity_mask + 1 - (ptr & granularity_mask);
604 FILE_munmap( (void *)ptr, 0, extra );
605 ptr += extra;
606 view_size -= extra;
608 if (view_size > size)
609 FILE_munmap( (void *)(ptr + size), 0, view_size - size );
611 else if (ptr != base)
613 /* We couldn't get the address we wanted */
614 FILE_munmap( (void *)ptr, 0, view_size );
615 SetLastError( ERROR_INVALID_ADDRESS );
616 return NULL;
618 if (!(view = VIRTUAL_CreateView( ptr, size, 0, 0, vprot, -1 )))
620 FILE_munmap( (void *)ptr, 0, size );
621 SetLastError( ERROR_OUTOFMEMORY );
622 return NULL;
624 VIRTUAL_DEBUG_DUMP_VIEW( view );
625 return (LPVOID)ptr;
628 /* Commit the pages */
630 if (!(view = VIRTUAL_FindView( base )) ||
631 (base + size > view->base + view->size))
633 SetLastError( ERROR_INVALID_PARAMETER );
634 return NULL;
637 if (!VIRTUAL_SetProt( view, base, size, vprot )) return NULL;
638 return (LPVOID)base;
642 /***********************************************************************
643 * VirtualFree (KERNEL32.550)
644 * Release or decommits a region of pages in virtual address space.
646 * RETURNS
647 * TRUE: Success
648 * FALSE: Failure
650 BOOL WINAPI VirtualFree(
651 LPVOID addr, /* [in] Address of region of committed pages */
652 DWORD size, /* [in] Size of region */
653 DWORD type /* [in] Type of operation */
655 FILE_VIEW *view;
656 UINT base;
658 TRACE(virtual, "%08x %08lx %lx\n",
659 (UINT)addr, size, type );
661 /* Fix the parameters */
663 size = ROUND_SIZE( addr, size );
664 base = ROUND_ADDR( addr );
666 if (!(view = VIRTUAL_FindView( base )) ||
667 (base + size > view->base + view->size))
669 SetLastError( ERROR_INVALID_PARAMETER );
670 return FALSE;
673 /* Compute the protection flags */
675 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
677 SetLastError( ERROR_INVALID_PARAMETER );
678 return FALSE;
681 /* Free the pages */
683 if (type == MEM_RELEASE)
685 if (size || (base != view->base))
687 SetLastError( ERROR_INVALID_PARAMETER );
688 return FALSE;
690 VIRTUAL_DeleteView( view );
691 return TRUE;
694 /* Decommit the pages */
695 return VIRTUAL_SetProt( view, base, size, 0 );
699 /***********************************************************************
700 * VirtualLock (KERNEL32.551)
701 * Locks the specified region of virtual address space
703 * NOTE
704 * Always returns TRUE
706 * RETURNS
707 * TRUE: Success
708 * FALSE: Failure
710 BOOL WINAPI VirtualLock(
711 LPVOID addr, /* [in] Address of first byte of range to lock */
712 DWORD size /* [in] Number of bytes in range to lock */
714 return TRUE;
718 /***********************************************************************
719 * VirtualUnlock (KERNEL32.556)
720 * Unlocks a range of pages in the virtual address space
722 * NOTE
723 * Always returns TRUE
725 * RETURNS
726 * TRUE: Success
727 * FALSE: Failure
729 BOOL WINAPI VirtualUnlock(
730 LPVOID addr, /* [in] Address of first byte of range */
731 DWORD size /* [in] Number of bytes in range */
733 return TRUE;
737 /***********************************************************************
738 * VirtualProtect (KERNEL32.552)
739 * Changes the access protection on a region of committed pages
741 * RETURNS
742 * TRUE: Success
743 * FALSE: Failure
745 BOOL WINAPI VirtualProtect(
746 LPVOID addr, /* [in] Address of region of committed pages */
747 DWORD size, /* [in] Size of region */
748 DWORD new_prot, /* [in] Desired access protection */
749 LPDWORD old_prot /* [out] Address of variable to get old protection */
751 FILE_VIEW *view;
752 UINT base, i;
753 BYTE vprot, *p;
755 TRACE(virtual, "%08x %08lx %08lx\n",
756 (UINT)addr, size, new_prot );
758 /* Fix the parameters */
760 size = ROUND_SIZE( addr, size );
761 base = ROUND_ADDR( addr );
763 if (!(view = VIRTUAL_FindView( base )) ||
764 (base + size > view->base + view->size))
766 SetLastError( ERROR_INVALID_PARAMETER );
767 return FALSE;
770 /* Make sure all the pages are committed */
772 p = view->prot + ((base - view->base) >> page_shift);
773 for (i = size >> page_shift; i; i--, p++)
775 if (!(*p & VPROT_COMMITTED))
777 SetLastError( ERROR_INVALID_PARAMETER );
778 return FALSE;
782 VIRTUAL_GetWin32Prot( view->prot[0], old_prot, NULL );
783 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
784 return VIRTUAL_SetProt( view, base, size, vprot );
788 /***********************************************************************
789 * VirtualProtectEx (KERNEL32.553)
790 * Changes the access protection on a region of committed pages in the
791 * virtual address space of a specified process
793 * RETURNS
794 * TRUE: Success
795 * FALSE: Failure
797 BOOL WINAPI VirtualProtectEx(
798 HANDLE handle, /* [in] Handle of process */
799 LPVOID addr, /* [in] Address of region of committed pages */
800 DWORD size, /* [in] Size of region */
801 DWORD new_prot, /* [in] Desired access protection */
802 LPDWORD old_prot /* [out] Address of variable to get old protection */ )
804 if (PROCESS_IsCurrent( handle ))
805 return VirtualProtect( addr, size, new_prot, old_prot );
806 ERR(virtual,"Unsupported on other process\n");
807 return FALSE;
811 /***********************************************************************
812 * VirtualQuery (KERNEL32.554)
813 * Provides info about a range of pages in virtual address space
815 * RETURNS
816 * Number of bytes returned in information buffer
818 DWORD WINAPI VirtualQuery(
819 LPCVOID addr, /* [in] Address of region */
820 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
821 DWORD len /* [in] Size of buffer */
823 FILE_VIEW *view = VIRTUAL_FirstView;
824 UINT base = ROUND_ADDR( addr );
825 UINT alloc_base = 0;
826 UINT size = 0;
828 /* Find the view containing the address */
830 for (;;)
832 if (!view)
834 size = 0xffff0000 - alloc_base;
835 break;
837 if (view->base > base)
839 size = view->base - alloc_base;
840 view = NULL;
841 break;
843 if (view->base + view->size > base)
845 alloc_base = view->base;
846 size = view->size;
847 break;
849 alloc_base = view->base + view->size;
850 view = view->next;
853 /* Fill the info structure */
855 if (!view)
857 info->State = MEM_FREE;
858 info->Protect = 0;
859 info->AllocationProtect = 0;
860 info->Type = 0;
862 else
864 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
865 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
866 for (size = base - alloc_base; size < view->size; size += page_mask+1)
867 if (view->prot[size >> page_shift] != vprot) break;
868 info->AllocationProtect = view->protect;
869 info->Type = MEM_PRIVATE; /* FIXME */
872 info->BaseAddress = (LPVOID)base;
873 info->AllocationBase = (LPVOID)alloc_base;
874 info->RegionSize = size - (base - alloc_base);
875 return sizeof(*info);
879 /***********************************************************************
880 * VirtualQueryEx (KERNEL32.555)
881 * Provides info about a range of pages in virtual address space of a
882 * specified process
884 * RETURNS
885 * Number of bytes returned in information buffer
887 DWORD WINAPI VirtualQueryEx(
888 HANDLE handle, /* [in] Handle of process */
889 LPCVOID addr, /* [in] Address of region */
890 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
891 DWORD len /* [in] Size of buffer */ )
893 if (PROCESS_IsCurrent( handle ))
894 return VirtualQuery( addr, info, len );
895 ERR(virtual,"Unsupported on other process\n");
896 return 0;
900 /***********************************************************************
901 * IsBadReadPtr32 (KERNEL32.354)
903 * RETURNS
904 * FALSE: Process has read access to entire block
905 * TRUE: Otherwise
907 BOOL WINAPI IsBadReadPtr(
908 LPCVOID ptr, /* Address of memory block */
909 UINT size /* Size of block */
911 return !VIRTUAL_CheckFlags( (UINT)ptr, size,
912 VPROT_READ | VPROT_COMMITTED );
916 /***********************************************************************
917 * IsBadWritePtr32 (KERNEL32.357)
919 * RETURNS
920 * FALSE: Process has write access to entire block
921 * TRUE: Otherwise
923 BOOL WINAPI IsBadWritePtr(
924 LPVOID ptr, /* [in] Address of memory block */
925 UINT size /* [in] Size of block in bytes */
927 return !VIRTUAL_CheckFlags( (UINT)ptr, size,
928 VPROT_WRITE | VPROT_COMMITTED );
932 /***********************************************************************
933 * IsBadHugeReadPtr32 (KERNEL32.352)
934 * RETURNS
935 * FALSE: Process has read access to entire block
936 * TRUE: Otherwise
938 BOOL WINAPI IsBadHugeReadPtr(
939 LPCVOID ptr, /* [in] Address of memory block */
940 UINT size /* [in] Size of block */
942 return IsBadReadPtr( ptr, size );
946 /***********************************************************************
947 * IsBadHugeWritePtr32 (KERNEL32.353)
948 * RETURNS
949 * FALSE: Process has write access to entire block
950 * TRUE: Otherwise
952 BOOL WINAPI IsBadHugeWritePtr(
953 LPVOID ptr, /* [in] Address of memory block */
954 UINT size /* [in] Size of block */
956 return IsBadWritePtr( ptr, size );
960 /***********************************************************************
961 * IsBadCodePtr32 (KERNEL32.351)
963 * RETURNS
964 * FALSE: Process has read access to specified memory
965 * TRUE: Otherwise
967 BOOL WINAPI IsBadCodePtr(
968 FARPROC ptr /* [in] Address of function */
970 return !VIRTUAL_CheckFlags( (UINT)ptr, 1, VPROT_EXEC | VPROT_COMMITTED );
974 /***********************************************************************
975 * IsBadStringPtr32A (KERNEL32.355)
977 * RETURNS
978 * FALSE: Read access to all bytes in string
979 * TRUE: Else
981 BOOL WINAPI IsBadStringPtrA(
982 LPCSTR str, /* [in] Address of string */
983 UINT max /* [in] Maximum size of string */
985 FILE_VIEW *view;
986 UINT page, count;
988 if (!max) return FALSE;
989 if (!(view = VIRTUAL_FindView( (UINT)str ))) return TRUE;
990 page = ((UINT)str - view->base) >> page_shift;
991 count = page_mask + 1 - ((UINT)str & page_mask);
993 while (max)
995 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
996 (VPROT_READ | VPROT_COMMITTED))
997 return TRUE;
998 if (count > max) count = max;
999 max -= count;
1000 while (count--) if (!*str++) return FALSE;
1001 if (++page >= view->size >> page_shift) return TRUE;
1002 count = page_mask + 1;
1004 return FALSE;
1008 /***********************************************************************
1009 * IsBadStringPtr32W (KERNEL32.356)
1010 * See IsBadStringPtr32A
1012 BOOL WINAPI IsBadStringPtrW( LPCWSTR str, UINT max )
1014 FILE_VIEW *view;
1015 UINT page, count;
1017 if (!max) return FALSE;
1018 if (!(view = VIRTUAL_FindView( (UINT)str ))) return TRUE;
1019 page = ((UINT)str - view->base) >> page_shift;
1020 count = (page_mask + 1 - ((UINT)str & page_mask)) / sizeof(WCHAR);
1022 while (max)
1024 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
1025 (VPROT_READ | VPROT_COMMITTED))
1026 return TRUE;
1027 if (count > max) count = max;
1028 max -= count;
1029 while (count--) if (!*str++) return FALSE;
1030 if (++page >= view->size >> page_shift) return TRUE;
1031 count = (page_mask + 1) / sizeof(WCHAR);
1033 return FALSE;
1037 /***********************************************************************
1038 * CreateFileMapping32A (KERNEL32.46)
1039 * Creates a named or unnamed file-mapping object for the specified file
1041 * RETURNS
1042 * Handle: Success
1043 * 0: Mapping object does not exist
1044 * NULL: Failure
1046 HANDLE WINAPI CreateFileMappingA(
1047 HFILE hFile, /* [in] Handle of file to map */
1048 SECURITY_ATTRIBUTES *sa, /* [in] Optional security attributes*/
1049 DWORD protect, /* [in] Protection for mapping object */
1050 DWORD size_high, /* [in] High-order 32 bits of object size */
1051 DWORD size_low, /* [in] Low-order 32 bits of object size */
1052 LPCSTR name /* [in] Name of file-mapping object */ )
1054 struct create_mapping_request req;
1055 struct create_mapping_reply reply;
1056 BYTE vprot;
1058 /* Check parameters */
1060 TRACE(virtual,"(%x,%p,%08lx,%08lx%08lx,%s)\n",
1061 hFile, sa, protect, size_high, size_low, debugstr_a(name) );
1063 vprot = VIRTUAL_GetProt( protect );
1064 if (protect & SEC_RESERVE)
1066 if (hFile != INVALID_HANDLE_VALUE)
1068 SetLastError( ERROR_INVALID_PARAMETER );
1069 return 0;
1072 else vprot |= VPROT_COMMITTED;
1073 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1075 /* Create the server object */
1077 req.handle = hFile;
1078 req.size_high = size_high;
1079 req.size_low = size_low;
1080 req.protect = vprot;
1081 req.inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1082 CLIENT_SendRequest( REQ_CREATE_MAPPING, -1, 2,
1083 &req, sizeof(req),
1084 name, name ? strlen(name) + 1 : 0 );
1085 SetLastError(0);
1086 CLIENT_WaitSimpleReply( &reply, sizeof(reply), NULL );
1087 if (reply.handle == -1) return 0;
1088 return reply.handle;
1092 /***********************************************************************
1093 * CreateFileMapping32W (KERNEL32.47)
1094 * See CreateFileMapping32A
1096 HANDLE WINAPI CreateFileMappingW( HFILE hFile, LPSECURITY_ATTRIBUTES attr,
1097 DWORD protect, DWORD size_high,
1098 DWORD size_low, LPCWSTR name )
1100 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1101 HANDLE ret = CreateFileMappingA( hFile, attr, protect,
1102 size_high, size_low, nameA );
1103 HeapFree( GetProcessHeap(), 0, nameA );
1104 return ret;
1108 /***********************************************************************
1109 * OpenFileMapping32A (KERNEL32.397)
1110 * Opens a named file-mapping object.
1112 * RETURNS
1113 * Handle: Success
1114 * NULL: Failure
1116 HANDLE WINAPI OpenFileMappingA(
1117 DWORD access, /* [in] Access mode */
1118 BOOL inherit, /* [in] Inherit flag */
1119 LPCSTR name ) /* [in] Name of file-mapping object */
1121 struct open_mapping_request req;
1122 struct open_mapping_reply reply;
1123 int len = name ? strlen(name) + 1 : 0;
1125 req.access = access;
1126 req.inherit = inherit;
1127 CLIENT_SendRequest( REQ_OPEN_MAPPING, -1, 2, &req, sizeof(req), name, len );
1128 CLIENT_WaitSimpleReply( &reply, sizeof(reply), NULL );
1129 if (reply.handle == -1) return 0; /* must return 0 on failure, not -1 */
1130 return reply.handle;
1134 /***********************************************************************
1135 * OpenFileMapping32W (KERNEL32.398)
1136 * See OpenFileMapping32A
1138 HANDLE WINAPI OpenFileMappingW( DWORD access, BOOL inherit, LPCWSTR name)
1140 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1141 HANDLE ret = OpenFileMappingA( access, inherit, nameA );
1142 HeapFree( GetProcessHeap(), 0, nameA );
1143 return ret;
1147 /***********************************************************************
1148 * MapViewOfFile (KERNEL32.385)
1149 * Maps a view of a file into the address space
1151 * RETURNS
1152 * Starting address of mapped view
1153 * NULL: Failure
1155 LPVOID WINAPI MapViewOfFile(
1156 HANDLE mapping, /* [in] File-mapping object to map */
1157 DWORD access, /* [in] Access mode */
1158 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1159 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1160 DWORD count /* [in] Number of bytes to map */
1162 return MapViewOfFileEx( mapping, access, offset_high,
1163 offset_low, count, NULL );
1167 /***********************************************************************
1168 * MapViewOfFileEx (KERNEL32.386)
1169 * Maps a view of a file into the address space
1171 * RETURNS
1172 * Starting address of mapped view
1173 * NULL: Failure
1175 LPVOID WINAPI MapViewOfFileEx(
1176 HANDLE handle, /* [in] File-mapping object to map */
1177 DWORD access, /* [in] Access mode */
1178 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1179 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1180 DWORD count, /* [in] Number of bytes to map */
1181 LPVOID addr /* [in] Suggested starting address for mapped view */
1183 FILE_VIEW *view;
1184 UINT ptr = (UINT)-1, size = 0;
1185 int flags = MAP_PRIVATE;
1186 int unix_handle = -1;
1187 struct get_mapping_info_request req;
1188 struct get_mapping_info_reply info;
1190 /* Check parameters */
1192 if ((offset_low & granularity_mask) ||
1193 (addr && ((UINT)addr & granularity_mask)))
1195 SetLastError( ERROR_INVALID_PARAMETER );
1196 return NULL;
1199 req.handle = handle;
1200 CLIENT_SendRequest( REQ_GET_MAPPING_INFO, -1, 1, &req, sizeof(req) );
1201 if (CLIENT_WaitSimpleReply( &info, sizeof(info), &unix_handle ))
1202 goto error;
1204 if (info.size_high || offset_high)
1205 ERR(virtual, "Offsets larger than 4Gb not supported\n");
1207 if ((offset_low >= info.size_low) ||
1208 (count > info.size_low - offset_low))
1210 SetLastError( ERROR_INVALID_PARAMETER );
1211 goto error;
1213 if (count) size = ROUND_SIZE( offset_low, count );
1214 else size = info.size_low - offset_low;
1216 switch(access)
1218 case FILE_MAP_ALL_ACCESS:
1219 case FILE_MAP_WRITE:
1220 case FILE_MAP_WRITE | FILE_MAP_READ:
1221 if (!(info.protect & VPROT_WRITE))
1223 SetLastError( ERROR_INVALID_PARAMETER );
1224 goto error;
1226 flags = MAP_SHARED;
1227 /* fall through */
1228 case FILE_MAP_READ:
1229 case FILE_MAP_COPY:
1230 case FILE_MAP_COPY | FILE_MAP_READ:
1231 if (info.protect & VPROT_READ) break;
1232 /* fall through */
1233 default:
1234 SetLastError( ERROR_INVALID_PARAMETER );
1235 goto error;
1238 /* Map the file */
1240 TRACE(virtual, "handle=%x size=%x offset=%lx\n",
1241 handle, size, offset_low );
1243 ptr = (UINT)FILE_dommap( unix_handle,
1244 addr, 0, size, 0, offset_low,
1245 VIRTUAL_GetUnixProt( info.protect ),
1246 flags );
1247 if (ptr == (UINT)-1) {
1248 /* KB: Q125713, 25-SEP-1995, "Common File Mapping Problems and
1249 * Platform Differences":
1250 * Windows NT: ERROR_INVALID_PARAMETER
1251 * Windows 95: ERROR_INVALID_ADDRESS.
1252 * FIXME: So should we add a module dependend check here? -MM
1254 if (errno==ENOMEM)
1255 SetLastError( ERROR_OUTOFMEMORY );
1256 else
1257 SetLastError( ERROR_INVALID_PARAMETER );
1258 goto error;
1261 if (!(view = VIRTUAL_CreateView( ptr, size, offset_low, 0,
1262 info.protect, handle )))
1264 SetLastError( ERROR_OUTOFMEMORY );
1265 goto error;
1267 if (unix_handle != -1) close( unix_handle );
1268 return (LPVOID)ptr;
1270 error:
1271 if (unix_handle != -1) close( unix_handle );
1272 if (ptr != (UINT)-1) FILE_munmap( (void *)ptr, 0, size );
1273 return NULL;
1277 /***********************************************************************
1278 * FlushViewOfFile (KERNEL32.262)
1279 * Writes to the disk a byte range within a mapped view of a file
1281 * RETURNS
1282 * TRUE: Success
1283 * FALSE: Failure
1285 BOOL WINAPI FlushViewOfFile(
1286 LPCVOID base, /* [in] Start address of byte range to flush */
1287 DWORD cbFlush /* [in] Number of bytes in range */
1289 FILE_VIEW *view;
1290 UINT addr = ROUND_ADDR( base );
1292 TRACE(virtual, "FlushViewOfFile at %p for %ld bytes\n",
1293 base, cbFlush );
1295 if (!(view = VIRTUAL_FindView( addr )))
1297 SetLastError( ERROR_INVALID_PARAMETER );
1298 return FALSE;
1300 if (!cbFlush) cbFlush = view->size;
1301 if (!msync( (void *)addr, cbFlush, MS_SYNC )) return TRUE;
1302 SetLastError( ERROR_INVALID_PARAMETER );
1303 return FALSE;
1307 /***********************************************************************
1308 * UnmapViewOfFile (KERNEL32.540)
1309 * Unmaps a mapped view of a file.
1311 * NOTES
1312 * Should addr be an LPCVOID?
1314 * RETURNS
1315 * TRUE: Success
1316 * FALSE: Failure
1318 BOOL WINAPI UnmapViewOfFile(
1319 LPVOID addr /* [in] Address where mapped view begins */
1321 FILE_VIEW *view;
1322 UINT base = ROUND_ADDR( addr );
1323 if (!(view = VIRTUAL_FindView( base )) || (base != view->base))
1325 SetLastError( ERROR_INVALID_PARAMETER );
1326 return FALSE;
1328 VIRTUAL_DeleteView( view );
1329 return TRUE;
1332 /***********************************************************************
1333 * VIRTUAL_MapFileW
1335 * Helper function to map a file to memory:
1336 * name - file name
1337 * [RETURN] ptr - pointer to mapped file
1339 LPVOID VIRTUAL_MapFileW( LPCWSTR name )
1341 HANDLE hFile, hMapping;
1342 LPVOID ptr = NULL;
1344 hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
1345 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0);
1346 if (hFile != INVALID_HANDLE_VALUE)
1348 hMapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1349 CloseHandle( hFile );
1350 if (hMapping)
1352 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
1353 CloseHandle( hMapping );
1356 return ptr;