source: trunk/src/kernel32/mmap.cpp@ 10566

Last change on this file since 10566 was 10566, checked in by sandervl, 21 years ago

bugfix

File size: 36.2 KB
Line 
1/* $Id: mmap.cpp,v 1.71 2004-04-02 15:46:33 sandervl Exp $ */
2
3/*
4 * Win32 Memory mapped file & view classes
5 *
6 * Copyright 1999-2003 Sander van Leeuwen (sandervl@xs4all.nl)
7 *
8 * NOTE: Memory mapping DOES NOT work when kernel-mode code causes
9 * a pagefault in the memory mapped object. (exceptions aren't
10 * dispatched to our exception handler until after the kernel mode
11 * call returns (too late))
12 *
13 * NOTE: Are apps allowed to change the protection flags of memory mapped pages?
14 * I'm assuming they aren't for now.
15 *
16 * TODO: Handles returned should be usable by all apis that accept file handles
17 * TODO: Sharing memory mapped files between multiple processes
18 * TODO: Memory mapped files with views that extend the file (not 100% correct now)
19 * TODO: Suspend all threads when a page is committed (possible that another thread
20 * accesses the same memory before the page is read from disk
21 * TODO: File maps for new files (must select an initial size)!
22 *
23 * Project Odin Software License can be found in LICENSE.TXT
24 *
25 */
26#include <os2win.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
30#include <win\virtual.h>
31#include <odincrt.h>
32#include <handlemanager.h>
33#include "mmap.h"
34#include "oslibdos.h"
35#include "oslibmem.h"
36#include <winimagepeldr.h>
37#include <custombuild.h>
38#include "asmutil.h"
39
40#define DBG_LOCALLOG DBG_mmap
41#include "dbglocal.h"
42
43
44
45//Global DLL Data
46#pragma data_seg(_GLOBALDATA)
47Win32MemMap *Win32MemMap::memmaps = NULL;
48CRITICAL_SECTION_OS2 globalmapcritsect = {0};
49#pragma data_seg()
50
51
52static char *pszMMapSemName = MEMMAP_CRITSECTION_NAME;
53
54//******************************************************************************
55//******************************************************************************
56void WIN32API SetCustomMMapSemName(LPSTR pszSemName)
57{
58 pszMMapSemName = pszSemName;
59}
60//******************************************************************************
61//******************************************************************************
62void InitializeMemMaps()
63{
64 if(globalmapcritsect.hevLock == 0) {
65 dprintf(("InitializeMemMaps -> create shared critical section"));
66 }
67 else {
68 dprintf(("InitializeMemMaps -> access shared critical section"));
69 }
70 DosAccessCriticalSection(&globalmapcritsect, pszMMapSemName);
71}
72//******************************************************************************
73//******************************************************************************
74void FinalizeMemMaps()
75{
76 DosDeleteCriticalSection(&globalmapcritsect);
77}
78//******************************************************************************
79//******************************************************************************
80Win32MemMap::Win32MemMap(HANDLE hfile, ULONG size, ULONG fdwProtect, LPSTR lpszName)
81 : nrMappings(0), pMapping(NULL), mMapAccess(0), referenced(0),
82 image(0), pWriteBitmap(NULL), lpszFileName(NULL)
83{
84 DosEnterCriticalSection(&globalmapcritsect);
85 next = memmaps;
86 memmaps = this;
87 DosLeaveCriticalSection(&globalmapcritsect);
88
89 hMemFile = hOrgMemFile = hfile;
90
91 mSize = size;
92 mProtFlags = fdwProtect;
93
94 mProcessId = GetCurrentProcessId();
95
96 if(lpszName) {
97 lpszMapName = (char *)_smalloc(strlen(lpszName)+1);
98 strcpy(lpszMapName, lpszName);
99 }
100 else lpszMapName = NULL;
101 AddRef();
102}
103//******************************************************************************
104//Map constructor used for executable image maps (only used internally)
105//******************************************************************************
106Win32MemMap::Win32MemMap(Win32PeLdrImage *pImage, ULONG baseAddress, ULONG size)
107 : nrMappings(0), pMapping(NULL), mMapAccess(0), referenced(0),
108 image(0), pWriteBitmap(NULL), lpszFileName(NULL)
109{
110 DosEnterCriticalSection(&globalmapcritsect);
111 next = memmaps;
112 memmaps = this;
113 DosLeaveCriticalSection(&globalmapcritsect);
114
115 hMemFile = hOrgMemFile = -1;
116
117 mSize = size;
118 mProtFlags = PAGE_READWRITE;
119 mProcessId = GetCurrentProcessId();
120
121 pMapping = (LPVOID)baseAddress;
122
123 image = pImage;
124 lpszMapName= NULL;
125 AddRef();
126}
127//******************************************************************************
128//******************************************************************************
129BOOL Win32MemMap::Init(DWORD aMSize)
130{
131 mapMutex.enter();
132 if(hMemFile != -1)
133 {
134 lpszFileName = (char *)_smalloc(MMAP_MAX_FILENAME_LENGTH);
135 if(HMGetFileNameFromHandle(hMemFile, lpszFileName, MMAP_MAX_FILENAME_LENGTH) == FALSE) {
136 return FALSE;
137 }
138#if 0
139 if(DuplicateHandle(GetCurrentProcess(), hMemFile, GetCurrentProcess(),
140 &hMemFile, 0, FALSE, DUPLICATE_SAME_ACCESS) == FALSE)
141#else
142 if(HMDuplicateHandle(GetCurrentProcess(), hMemFile, GetCurrentProcess(),
143 &hMemFile, 0, FALSE, DUPLICATE_SAME_ACCESS) == FALSE)
144#endif
145 {
146 dprintf(("Win32MemMap::Init: DuplicateHandle failed!"));
147 goto fail;
148 }
149 mSize = SetFilePointer(hMemFile, 0, NULL, FILE_BEGIN);
150 mSize = SetFilePointer(hMemFile, 0, NULL, FILE_END);
151 if(mSize == -1) {
152 dprintf(("Win32MemMap::init: SetFilePointer failed to set pos end"));
153 goto fail;
154 }
155 if (mSize < aMSize)
156 {
157 dprintf(("Win32MemMap::init: file size %d, memory map size %d", mSize, aMSize));
158 //Froloff: Need to check if exist the possibility of file to memory
159 // mapping not from the beginning of file
160 mSize = SetFilePointer(hMemFile, aMSize, NULL, FILE_BEGIN);
161 // Commit filesize changes onto disk
162 SetEndOfFile(hMemFile);
163 }
164#if 0
165 //SvL: Temporary limitation of size (Warp Server Advanced doesn't allow
166 // one to reserve more than 450 MB (unless you override the virtual
167 // memory max limit) of continuous memory; (Warp 4 much less))
168 if(mSize > 64*1024*1024) {
169 mSize = 64*1024*1024;
170 }
171#endif
172 }
173 // Allocate the memory for the map right now
174 if(allocateMap() == FALSE) {
175 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
176 goto fail;
177 }
178
179 dprintf(("CreateFileMappingA for file %x, prot %x size %d, name %s", hMemFile, mProtFlags, mSize, lpszMapName));
180 mapMutex.leave();
181 return TRUE;
182fail:
183 mapMutex.leave();
184 return FALSE;
185}
186//******************************************************************************
187//******************************************************************************
188Win32MemMap::~Win32MemMap()
189{
190 Win32MemMapView::deleteViews(this); //delete all views of our memory mapped file
191
192 dprintf(("Win32MemMap dtor: deleting map %x %x", pMapping, mSize));
193
194 mapMutex.enter();
195 if(lpszMapName) {
196 free(lpszMapName);
197 }
198 if(lpszFileName) {
199 free(lpszFileName);
200 }
201 if(pMapping && !image) {
202 dprintf(("Free map memory"));
203 if(lpszMapName) {
204 OSLibDosFreeMem(pMapping);
205 }
206 else VirtualFree(pMapping, 0, MEM_RELEASE);
207
208 pMapping = NULL;
209 }
210 if(hMemFile != -1) {
211 dprintf(("Win32MemMap dtor: closing memory file %x", hMemFile));
212 CloseHandle(hMemFile);
213 hMemFile = -1;
214 }
215 if(pWriteBitmap) free(pWriteBitmap);
216
217 mapMutex.leave();
218
219 DosEnterCriticalSection(&globalmapcritsect);
220 Win32MemMap *map = memmaps;
221
222 if(map == this) {
223 memmaps = next;
224 }
225 else {
226 while(map->next) {
227 if(map->next == this)
228 break;
229 map = map->next;
230 }
231 if(map->next) {
232 map->next = next;
233 }
234 else dprintf(("Win32MemMap::~Win32MemMap: map not found!! (%x)", this));
235 }
236 DosLeaveCriticalSection(&globalmapcritsect);
237}
238//******************************************************************************
239//******************************************************************************
240int Win32MemMap::Release()
241{
242 dprintf(("Win32MemMap::Release %s (%d)", lpszMapName, referenced-1));
243 --referenced;
244 if(referenced == 0) {
245 delete this;
246 return 0;
247 }
248 return referenced;
249}
250//******************************************************************************
251// Win32MemMap::commitRange
252//
253// Commit a range of pages
254//
255// Parameters:
256//
257// ULONG ulFaultAddr - exception address
258// ULONG ulOffset - offset in memory map
259// BOOL fWriteAccess - TRUE -> write exception
260// FALSE -> read exception
261// int nrpages - number of pages
262//
263// Returns:
264// TRUE - success
265// FALSE - failure
266//
267//******************************************************************************
268BOOL Win32MemMap::commitRange(ULONG ulFaultAddr, ULONG offset, BOOL fWriteAccess, int nrpages)
269{
270 LPVOID lpPageFaultAddr = (LPVOID)((ULONG)pMapping + offset);
271 DWORD pageAddr = (DWORD)lpPageFaultAddr & ~0xFFF;
272
273 dprintf(("Win32MemMap::commitRange %x (faultaddr %x)", pageAddr, lpPageFaultAddr));
274
275 if(fWriteAccess)
276 {//writes are handled on a per-page basis
277 for(int i=0;i<nrpages;i++)
278 {
279 if(commitPage(ulFaultAddr, offset, TRUE, 1) == FALSE) {
280 dprintf(("Win32MemMap::commit: commitPage failed!!"));
281 return FALSE;
282 }
283 ulFaultAddr += PAGE_SIZE;
284 offset += PAGE_SIZE;
285 }
286 return TRUE;
287 }
288 else return commitPage(ulFaultAddr, offset, FALSE, nrpages);
289}
290//******************************************************************************
291// Win32MemMap::commitPage
292//
293// Handle a pagefault for a memory map
294//
295// Parameters:
296//
297// ULONG ulFaultAddr - exception address
298// ULONG ulOffset - offset in memory map
299// BOOL fWriteAccess - TRUE -> write exception
300// FALSE -> read exception
301// int nrpages - number of pages
302//
303// Returns:
304// TRUE - success
305// FALSE - failure
306//
307// NOTE:
308// We handle only one pages for write access!
309//
310// REMARKS:
311// We determine whether a page has been modified by checking it's protection flags
312// If the write flag is set, this means commitPage had to enable this due to a pagefault
313// (all pages are readonly until the app tries to write to it)
314//******************************************************************************
315BOOL Win32MemMap::commitPage(ULONG ulFaultAddr, ULONG offset, BOOL fWriteAccess, int nrpages)
316{
317 MEMORY_BASIC_INFORMATION memInfo;
318 LPVOID lpPageFaultAddr = (LPVOID)((ULONG)pMapping + offset);
319 DWORD pageAddr = (DWORD)lpPageFaultAddr & ~0xFFF;
320 DWORD oldProt, newProt, nrBytesRead;
321 int i;
322
323// mapMutex.enter();
324
325 if(image) {
326 return image->commitPage(pageAddr, fWriteAccess);
327 }
328
329 if(fWriteAccess && (mProtFlags & PAGE_WRITECOPY))
330 {//this is a COW map, call commitGuardPage to handle write faults
331 return commitGuardPage(ulFaultAddr, offset, fWriteAccess);
332 }
333
334 dprintf(("Win32MemMap::commitPage %x (faultaddr %x)", pageAddr, lpPageFaultAddr));
335
336 //align at page boundary
337 offset &= ~0xFFF;
338
339 //If it's a write access violation and the view is readonly, then fail
340 if(fWriteAccess) {
341 Win32MemMapView *view = Win32MemMapView::findView(ulFaultAddr);
342 if(view) {
343 if(!(view->getAccessFlags() & MEMMAP_ACCESS_WRITE)) {
344 dprintf(("Write access for a readonly view!!"));
345 return FALSE;
346 }
347 }
348 else {
349 DebugInt3(); //can't happen
350 return FALSE;
351 }
352 }
353
354 int faultsize = nrpages*PAGE_SIZE;
355
356 if(fWriteAccess)
357 {//write access needs special care, so do that on a per page basis
358 dprintf(("Write access -> handle only one page"));
359 faultsize = PAGE_SIZE;
360 }
361
362 offset = pageAddr - (ULONG)pMapping;
363 if(offset + faultsize > mSize) {
364 faultsize = mSize - offset;
365 }
366
367 while(faultsize)
368 {
369 if(VirtualQuery((LPSTR)pageAddr, &memInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0) {
370 dprintf(("Win32MemMap::commitPage: VirtualQuery (%x,%x) failed for %x", pageAddr, nrpages*PAGE_SIZE));
371 goto fail;
372 }
373 memInfo.RegionSize = min(memInfo.RegionSize, faultsize);
374 //Only changes the state of the pages with the same attribute flags
375 //(returned in memInfo.RegionSize)
376 //If it's smaller than the mNrPages, it simply means one or more of the
377 //other pages have already been committed
378 if(!(memInfo.State & MEM_COMMIT))
379 {
380 if(VirtualAlloc((LPVOID)pageAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE) == FALSE) {
381 goto fail;
382 }
383
384 //Part of the memory map has been committed, so now we can change
385 //the protection flags of the aliases (DosSetMem fails for reserved pages)
386 updateViewPages(offset, memInfo.RegionSize, (fWriteAccess) ? PAGEVIEW_VIEW : PAGEVIEW_READONLY);
387
388 if(hMemFile != -1)
389 {//now read the page(s) from disk
390 DWORD size;
391
392 offset = pageAddr - (ULONG)pMapping;
393 size = memInfo.RegionSize;
394 if(offset + size > mSize) {
395 dprintf(("Adjusting size from %d to %d", size, mSize - offset));
396 size = mSize - offset;
397 }
398 if(SetFilePointer(hMemFile, offset, NULL, FILE_BEGIN) != offset) {
399 dprintf(("Win32MemMap::commitPage: SetFilePointer failed to set pos to %x", offset));
400 goto fail;
401 }
402 if(ReadFile(hMemFile, (LPSTR)pageAddr, size, &nrBytesRead, NULL) == FALSE) {
403 dprintf(("Win32MemMap::commitPage: ReadFile failed for %x", pageAddr));
404 goto fail;
405 }
406 if(nrBytesRead != size) {
407 dprintf(("Win32MemMap::commitPage: ReadFile didn't read all bytes for %x", pageAddr));
408 goto fail;
409 }
410 }
411 //We set the protection flags to PAGE_READONLY, unless this pagefault
412 //was due to a write access
413 //This way we can track dirty pages which need to be flushed to
414 //disk when FlushViewOfFile is called or the map is closed.
415 if(!fWriteAccess)
416 {
417 if(VirtualProtect((LPVOID)pageAddr, memInfo.RegionSize, PAGE_READONLY, &oldProt) == FALSE) {
418 dprintf(("VirtualProtect %x %x PAGE_READWRITE failed with %d!!", pageAddr, memInfo.RegionSize, GetLastError()));
419 goto fail;
420 }
421 }
422 else
423 {//make these pages as dirty
424 ULONG startPage = (pageAddr - (ULONG)pMapping) >> PAGE_SHIFT;
425 ULONG nrPages = memInfo.RegionSize >> PAGE_SHIFT;
426
427 if(memInfo.RegionSize & 0xFFF)
428 nrPages++;
429
430 dprintf(("Mark %d page(s) starting at %x as dirty", nrPages, pageAddr));
431 markDirtyPages(startPage, nrPages);
432
433 //Write access means that the next time the corresponding COW page
434 //is touched, we need to reload it. So set the GUARD flags.
435 updateViewPages(offset, memInfo.RegionSize, PAGEVIEW_GUARD);
436 }
437 }
438 else
439 if(fWriteAccess)
440 {
441 //mark these pages as dirty
442 ULONG startPage = (pageAddr - (ULONG)pMapping) >> PAGE_SHIFT;
443 ULONG nrPages = memInfo.RegionSize >> PAGE_SHIFT;
444
445 if(memInfo.RegionSize & 0xFFF)
446 nrPages++;
447
448 dprintf(("Mark %d page(s) starting at %x as dirty", nrPages, pageAddr));
449 markDirtyPages(startPage, nrPages);
450
451 //and turn on a write access
452 if(VirtualProtect((LPVOID)pageAddr, memInfo.RegionSize, PAGE_READWRITE, &oldProt) == FALSE) {
453 dprintf(("VirtualProtect %x %x PAGE_READWRITE failed with %d!!", pageAddr, memInfo.RegionSize, GetLastError()));
454 goto fail;
455 }
456 //Now change all the aliased pages according to their view protection flags
457 updateViewPages(offset, memInfo.RegionSize, PAGEVIEW_VIEW);
458
459 //Write access means that the next time the corresponding COW page
460 //is touched, we need to reload it. So set the GUARD flags.
461 updateViewPages(offset, memInfo.RegionSize, PAGEVIEW_GUARD);
462 }
463 faultsize -= memInfo.RegionSize;
464 pageAddr += memInfo.RegionSize;
465 }
466
467// mapMutex.leave();
468 return TRUE;
469fail:
470// mapMutex.leave();
471 return FALSE;
472}
473//******************************************************************************
474// Win32MemMap::commitGuardPage
475//
476// Handle a guard page exception for a copy-on-write view (one page only)
477//
478// Parameters:
479//
480// ULONG ulFaultAddr - exception address
481// ULONG ulOffset - offset in memory map
482// BOOL fWriteAccess - TRUE -> write exception
483// FALSE -> read exception
484//
485// Returns:
486// TRUE - success
487// FALSE - failure
488//
489//******************************************************************************
490BOOL Win32MemMap::commitGuardPage(ULONG ulFaultAddr, ULONG ulOffset, BOOL fWriteAccess)
491{
492 MEMORY_BASIC_INFORMATION memInfo;
493 BOOL ret;
494 DWORD pageAddr = ulFaultAddr & ~0xFFF;
495 DWORD dwNewProt, dwOldProt;
496
497 dprintf(("Win32MemMap::commitGuardPage %x (faultaddr %x)", pageAddr, ulFaultAddr));
498
499 //align at page boundary
500 ulOffset &= ~0xFFF;
501
502 //commit a single page in the original mapping (pretend read access)
503 ret = commitPage(ulFaultAddr, ulOffset, FALSE, 1);
504 if(ret == FALSE) {
505 DebugInt3();
506 goto fail;
507 }
508 //clear PAGE_GUARD flag, since this page must now be made accessible
509 dwNewProt = mProtFlags & (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY);
510 if(dwNewProt & PAGE_WRITECOPY) {
511 dwNewProt |= PAGE_GUARD;
512 }
513 dwNewProt &= ~PAGE_GUARD;
514 if(VirtualProtect((LPVOID)pageAddr, PAGE_SIZE, dwNewProt, &dwOldProt) == FALSE) {
515 dprintf(("Win32MemMap::commitGuardPage: VirtualProtect %x 0x1000 %x failed!!", pageAddr, dwNewProt));
516 goto fail;
517 }
518 //copy the data from the original mapping to the COW page
519 memcpy((LPVOID)pageAddr, (char *)pMapping+ulOffset, PAGE_SIZE);
520
521 if(fWriteAccess)
522 {//copy on write; mark pages as private
523 DWORD startpage = (ulOffset) >> PAGE_SHIFT;
524
525 dprintf(("Win32MemMap::commitGuardPage: write access -> mark page as private"));
526
527 Win32MemMapView *view = Win32MemMapView::findView(ulFaultAddr);
528 if(view)
529 {
530 view->markCOWPages(startpage, 1);
531 }
532 else DebugInt3(); //oh, oh
533 }
534 else
535 {//read access; must set the map + all views to READONLY to track write access
536
537 dprintf(("Win32MemMap::commitGuardPage: read access -> set page as READONLY in map + all views"));
538
539 //first the memory map page
540 if(VirtualProtect((LPVOID)pageAddr, PAGE_SIZE, PAGE_READONLY, &dwOldProt) == FALSE) {
541 dprintf(("Win32MemMap::commitGuardPage: VirtualProtect %x 0x1000 %x failed!!", pageAddr, dwNewProt));
542 goto fail;
543 }
544 //now for any views that exist
545 updateViewPages(ulOffset, PAGE_SIZE, PAGEVIEW_READONLY);
546 }
547
548 return TRUE;
549fail:
550 return FALSE;
551}
552//******************************************************************************
553// Win32MemMap::updateViewPages
554//
555// Update the page flags of all views
556//
557// Parameters:
558//
559// ULONG offset - offset in memory map
560// ULONG size - range size
561// PAGEVIEW flags - page flags
562// PAGEVIEW_READONLY -> set page flags to readonly
563// PAGEVIEW_VIEW -> set page flags to view default
564// PAGEVIEW_GUARD -> set page flags of COW view to GUARD
565//
566// Returns:
567// TRUE - success
568// FALSE - failure
569//
570//******************************************************************************
571BOOL Win32MemMap::updateViewPages(ULONG offset, ULONG size, PAGEVIEW flags)
572{
573 Win32MemMapView **views = (Win32MemMapView **)alloca(sizeof(Win32MemMapView*)*nrMappings);
574 if(views)
575 {
576 if(Win32MemMapView::findViews(this, nrMappings, views) == nrMappings)
577 {
578 for(int i=0;i<nrMappings;i++)
579 {
580 views[i]->changePageFlags(offset, size, flags);
581 }
582 }
583 else DebugInt3(); //oh, oh
584 }
585 return TRUE;
586}
587//******************************************************************************
588// Win32MemMap::invalidatePages
589//
590// Invalidate map pages. (called by WriteFile)
591//
592// Parameters:
593//
594// ULONG offset - offset in memory map
595// ULONG size - invalid range size
596//
597// Returns:
598// TRUE - success
599// FALSE - failure
600//
601//******************************************************************************
602BOOL Win32MemMap::invalidatePages(ULONG offset, ULONG size)
603{
604 ULONG diff = offset & 0xFFF;
605 BOOL ret;
606
607 offset &= ~0xFFF;
608 size += diff;
609
610 dprintf(("Win32MemMap::invalidatePages %x %x", offset, size));
611 ret = VirtualFree((LPSTR)pMapping + offset, size, MEM_DECOMMIT);
612 if(ret == FALSE) {
613 dprintf(("ERROR: Win32MemMap::invalidatePages: VirtualFree failed!!"));
614 }
615 //invalidate all shared COW pages too by setting the GUARD flag
616 //(which forces a resync the next time the app touches them)
617 return updateViewPages(offset, size, PAGEVIEW_GUARD);
618}
619//******************************************************************************
620// Win32MemMap::allocateMap
621//
622// Allocate memory for the map if not yet already done.
623//
624// Returns:
625// FALSE - success
626// TRUE - failure
627//
628//******************************************************************************
629BOOL Win32MemMap::allocateMap()
630{
631 ULONG fAlloc = 0;
632
633 fAlloc = MEM_RESERVE;
634
635 //Memory has already been allocated for executable image maps (only used internally)
636 if(!pMapping && nrMappings == 0)
637 {//if not mapped, reserve/commit entire view
638 //SvL: Always read/write access or else ReadFile will crash once we
639 // start committing pages.
640 // This is most likely an OS/2 bug and doesn't happen in Aurora
641 // when allocating memory with the PAG_ANY bit set. (without this
642 // flag it will also crash)
643 //NOTE: If this is ever changed, then we must update setProtFlags!!!!
644
645 //All named file mappings are shared (files & memory only)
646 if(lpszMapName) {
647 pMapping = VirtualAllocShared(mSize, fAlloc, PAGE_READWRITE, lpszMapName);
648 }
649 else {
650 pMapping = VirtualAlloc(0, mSize, fAlloc, PAGE_READWRITE);
651 }
652 if(pMapping == NULL) {
653 dprintf(("Win32MemMap::mapViewOfFile: VirtualAlloc %x %x failed!", mSize, fAlloc));
654 goto fail;
655 }
656 //Windows NT seems to commit memory for memory maps, regardsless of the SEC_COMMIT flag
657 if((hMemFile == -1 && !image)) {//commit memory
658 VirtualAlloc(pMapping, mSize, MEM_COMMIT, PAGE_READWRITE);
659 }
660
661 DWORD nrPages = mSize >> PAGE_SHIFT;
662 if(mSize & 0xFFF)
663 nrPages++;
664
665 if(hMemFile != -1 && (mProtFlags & SEC_COMMIT)) {
666 commitPage((ULONG)pMapping, 0, FALSE, nrPages);
667 }
668 //Allocate bitmap for all pages to keep track of write access (file maps only)
669 //Necessary for FlushViewOfFile.
670 if(hMemFile != -1) {
671 int sizebitmap = nrPages/8 + 1;
672
673 pWriteBitmap = (char *)_smalloc(sizebitmap);
674 if(pWriteBitmap == NULL) {
675 DebugInt3();
676 goto fail;
677 }
678 memset(pWriteBitmap, 0, sizebitmap);
679 }
680 }
681 return TRUE;
682
683fail:
684 return FALSE;
685}
686//******************************************************************************
687// Win32MemMap::mapViewOfFile
688//
689// Map the view identified by addr
690//
691// Parameters:
692//
693// ULONG size - size of view
694// ULONG offset - offset in memory map
695// ULONG fdwAccess - access flags
696// FILE_MAP_WRITE, FILE_MAP_READ, FILE_MAP_COPY
697// FILE_MAP_ALL_ACCESS
698//
699//
700// Returns:
701// <>NULL - success, view address
702// NULL - failure
703//
704//******************************************************************************
705LPVOID Win32MemMap::mapViewOfFile(ULONG size, ULONG offset, ULONG fdwAccess)
706{
707 DWORD processId = GetCurrentProcessId();
708
709 mapMutex.enter();
710 ULONG memFlags = (mProtFlags & (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY));
711 Win32MemMapView *mapview;
712
713 //@@@PH: if(fdwAccess & ~(FILE_MAP_WRITE|FILE_MAP_READ|FILE_MAP_COPY))
714 // Docs say FILE_MAP_ALL_ACCESS is same as FILE_MAP_WRITE. Doesn't match reality though.
715 if(fdwAccess & ~FILE_MAP_ALL_ACCESS)
716 goto parmfail;
717 if((fdwAccess & FILE_MAP_WRITE) && !(mProtFlags & PAGE_READWRITE))
718 goto parmfail;
719 if((fdwAccess & FILE_MAP_READ) && !(mProtFlags & (PAGE_READWRITE|PAGE_READONLY)))
720 goto parmfail;
721
722 if (fdwAccess != FILE_MAP_ALL_ACCESS)
723 if((fdwAccess & FILE_MAP_COPY) && !(mProtFlags & PAGE_WRITECOPY))
724 goto parmfail;
725
726 if(offset+size > mSize && (!(fdwAccess & FILE_MAP_WRITE) || hMemFile == -1))
727 goto parmfail;
728
729 //SvL: TODO: Doesn't work for multiple views
730 if(offset+size > mSize) {
731 mSize = offset+size;
732 }
733
734 mapview = new Win32MemMapView(this, offset, (size == 0) ? (mSize - offset) : size, fdwAccess);
735 if(mapview == NULL) {
736 goto fail;
737 }
738 if(mapview->everythingOk() == FALSE) {
739 dprintf(("Win32MemMap::mapViewOfFile: !mapview->everythingOk"));
740 delete mapview;
741 goto fail;
742 }
743 mapMutex.leave();
744 SetLastError(ERROR_SUCCESS);
745 return mapview->getViewAddr();
746
747parmfail:
748 dprintf(("Win32MemMap::mapViewOfFile: invalid parameter (ERROR_ACCESS_DENIED)"));
749 //NT4 SP6 returns ERROR_ACCESS_DENIED for most invalid parameters
750 SetLastError(ERROR_ACCESS_DENIED);
751fail:
752 mapMutex.leave();
753 return 0;
754}
755//******************************************************************************
756// Win32MemMap::unmapViewOfFile
757//
758// Unmap the view identified by addr
759//
760// Parameters:
761//
762// LPVOID addr - view address; doesn't need to be the address
763// returned by MapViewOfFile(Ex) (as MSDN clearly says);
764// can be any address within the view range
765//
766// Returns:
767// TRUE - success
768// FALSE - failure
769//
770//******************************************************************************
771BOOL Win32MemMap::unmapViewOfFile(LPVOID addr)
772{
773 Win32MemMapView *view;
774
775 dprintf(("Win32MemMap::unmapViewOfFile %x (nrmaps=%d)", addr, nrMappings));
776 mapMutex.enter();
777
778 if(nrMappings == 0)
779 goto fail;
780
781 view = Win32MemMapView::findView((ULONG)addr);
782 if(view == NULL)
783 goto fail;
784
785 delete view;
786
787 mapMutex.leave();
788
789 SetLastError(ERROR_SUCCESS);
790 return TRUE;
791fail:
792 mapMutex.leave();
793 SetLastError(ERROR_INVALID_ADDRESS);
794 return FALSE;
795}
796//******************************************************************************
797//We determine whether a page has been modified by checking it's protection flags
798//If the write flag is set, this means commitPage had to enable this due to a pagefault
799//(all pages are readonly until the app tries to modify the contents of the page)
800//
801//TODO: Are apps allowed to change the protection flags of memory mapped pages?
802// I'm assuming they aren't for now.
803//******************************************************************************
804BOOL Win32MemMap::flushView(ULONG viewaddr, ULONG offset, ULONG cbFlush)
805{
806 ULONG nrBytesWritten, size, accessflags, oldProt;
807 Win32MemMapView *view;
808 int i;
809
810 dprintf(("Win32MemMap::flushView: %x %x", (ULONG)pMapping+offset, cbFlush));
811
812 if(image) //no flushing for image maps
813 return TRUE;
814
815 if(hMemFile == -1)
816 goto success; //TODO: Return an error here?
817
818 if(offset > mSize)
819 goto parmfail;
820
821 if(viewaddr != MMAP_FLUSHVIEW_ALL)
822 {
823 view = Win32MemMapView::findView(viewaddr);
824 if(nrMappings == 0 || view == NULL) {
825 DebugInt3(); //should never happen
826 goto parmfail;
827 }
828 accessflags = view->getAccessFlags();
829 }
830 else {
831 //force a flush to disk; only those pages marked dirty are flushed anyway
832 accessflags = FILE_MAP_WRITE;
833 }
834 //If the view is readonly or copy on write, then the flush is ignored
835 if(!(accessflags & MEMMAP_ACCESS_WRITE) || (accessflags & MEMMAP_ACCESS_COPYONWRITE))
836 {
837 dprintf(("Readonly or Copy-On-Write memory map -> ignore flush"));
838 //this is not a failure; NT4 SP6 returns success
839 goto success;
840 }
841
842 if(cbFlush == 0)
843 cbFlush = mSize;
844
845 if(offset + cbFlush > mSize) {
846 cbFlush -= (offset + cbFlush - mSize);
847 }
848
849 //Check the write page bitmap for dirty pages and write them to disk
850 while(cbFlush)
851 {
852 int startPage = offset >> PAGE_SHIFT;
853 size = PAGE_SIZE;
854
855 if(isDirtyPage(startPage))
856 {
857 if(size > cbFlush) {
858 size = cbFlush;
859 }
860 dprintf(("Win32MemMap::flushView for offset %x, size %d", offset, size));
861
862 if(SetFilePointer(hMemFile, offset, NULL, FILE_BEGIN) != offset) {
863 dprintf(("Win32MemMap::flushView: SetFilePointer failed to set pos to %x", offset));
864 goto fail;
865 }
866 if(WriteFile(hMemFile, (LPSTR)((ULONG)pMapping + offset), size, &nrBytesWritten, NULL) == FALSE) {
867 dprintf(("Win32MemMap::flushView: WriteFile failed for %x", (ULONG)pMapping + offset));
868 goto fail;
869 }
870 if(nrBytesWritten != size) {
871 dprintf(("Win32MemMap::flushView: WriteFile didn't write all bytes for %x", (ULONG)pMapping + offset));
872 goto fail;
873 }
874 clearDirtyPages(startPage, 1);
875
876 //We've just flushed the page to disk, so we need to track future writes
877 //again; Set page to readonly (first memory map, then alias(es))
878 if(VirtualProtect((LPVOID)((ULONG)pMapping + offset), size, PAGE_READONLY, &oldProt) == FALSE) {
879 dprintf(("VirtualProtect %x %x PAGE_READWRITE failed with %d!!", (ULONG)pMapping + offset, size, GetLastError()));
880 goto fail;
881 }
882 updateViewPages(offset, size, PAGEVIEW_READONLY);
883 }
884
885 if(cbFlush < size)
886 break;
887
888 cbFlush -= size;
889 offset += size;
890 }
891success:
892 SetLastError(ERROR_SUCCESS);
893 return TRUE;
894
895parmfail:
896 SetLastError(ERROR_INVALID_PARAMETER);
897 return FALSE;
898fail:
899 return FALSE;
900}
901//******************************************************************************
902//******************************************************************************
903Win32MemMap *Win32MemMap::findMap(LPSTR lpszName)
904{
905 if(lpszName == NULL)
906 return NULL;
907
908 DosEnterCriticalSection(&globalmapcritsect);
909 Win32MemMap *map = memmaps;
910
911 if(map != NULL) {
912 while(map) {
913 if(map->lpszMapName && !strcmp(map->lpszMapName, lpszName))
914 break;
915 map = map->next;
916 }
917 }
918 if(map) map->AddRef();
919
920 DosLeaveCriticalSection(&globalmapcritsect);
921 if(!map) dprintf(("Win32MemMap::findMap: couldn't find map %s", lpszName));
922 return map;
923}
924//******************************************************************************
925//******************************************************************************
926Win32MemMap *Win32MemMap::findMapByFile(HANDLE hFile)
927{
928 DWORD processId = GetCurrentProcessId();
929 char szFileName[260];
930
931 if(hFile == -1)
932 return NULL;
933
934 if(HMGetFileNameFromHandle(hFile, szFileName, sizeof(szFileName)) == FALSE)
935 return NULL;
936
937 DosEnterCriticalSection(&globalmapcritsect);
938 Win32MemMap *map = memmaps;
939
940 if(map != NULL)
941 {
942 while(map) {
943 //TODO: we currently don't support sharing file maps between processes
944 if(map->mProcessId == processId && map->lpszFileName)
945 {
946 if(!strcmp(map->lpszFileName, szFileName))
947 break;
948 }
949 map = map->next;
950 }
951 }
952 if(map) map->AddRef();
953 DosLeaveCriticalSection(&globalmapcritsect);
954 if(!map) dprintf2(("Win32MemMap::findMapByFile: couldn't find map with file handle %x", hFile));
955 return map;
956}
957//******************************************************************************
958//******************************************************************************
959Win32MemMap *Win32MemMap::findMap(ULONG address)
960{
961 DosEnterCriticalSection(&globalmapcritsect);
962 Win32MemMap *map = memmaps;
963
964 if(map != NULL) {
965 while(map) {
966 if(map->pMapping && (ULONG)map->pMapping <= address &&
967 (ULONG)map->pMapping + map->mSize > address)
968 {
969 break;
970 }
971 map = map->next;
972 }
973 }
974 if(map) map->AddRef();
975 DosLeaveCriticalSection(&globalmapcritsect);
976 return map;
977}
978//******************************************************************************
979//******************************************************************************
980void Win32MemMap::deleteAll()
981{
982 Win32MemMap *map, *nextmap;
983 DWORD processId = GetCurrentProcessId();
984
985 //delete all maps created by this process
986 DosEnterCriticalSection(&globalmapcritsect);
987
988startdeleteviews:
989 map = memmaps;
990 while(map) {
991 map->AddRef(); //make sure it doesn't get deleted
992
993 //delete all views created by this process for this map
994 Win32MemMapView::deleteViews(map);
995
996 nextmap = map->next;
997
998 //map->Release can delete multiple objects (duplicate memory map), so make
999 //sure our nextmap pointer remains valid by increasing the refcount
1000 if(nextmap) nextmap->AddRef();
1001 map->Release();
1002
1003 if(nextmap && nextmap->Release() == 0) {
1004 //oops, nextmap was just deleted and is no longer valid
1005 //can't continue from here, so let's start again
1006 dprintf(("oops, nextmap is invalid -> start again (1)"));
1007 goto startdeleteviews;
1008 }
1009
1010 map = nextmap;
1011 }
1012startdelete:
1013 map = memmaps;
1014 while(map) {
1015 nextmap = map->next;
1016 if(map->getProcessId() == processId)
1017 {
1018 //delete map can delete multiple objects (duplicate memory map), so make
1019 //sure our nextmap pointer remains valid by increasing the refcount
1020 if(nextmap) nextmap->AddRef();
1021 delete map;
1022
1023 if(nextmap && nextmap->Release() == 0) {
1024 //oops, nextmap was just deleted and is no longer valid
1025 //can't continue from here, so let's start again
1026 dprintf(("oops, nextmap is invalid -> start again (2)"));
1027 goto startdelete;
1028 }
1029 }
1030 map = nextmap;
1031 }
1032 DosLeaveCriticalSection(&globalmapcritsect);
1033}
1034//******************************************************************************
1035// Win32MemMapView::markDirtyPages
1036//
1037// Mark pages as dirty (changed) in the write page bitmap
1038//
1039// Parameters:
1040//
1041// int startpage - start page
1042// int nrpages - number of pages
1043//
1044//
1045//******************************************************************************
1046void Win32MemMap::markDirtyPages(int startpage, int nrpages)
1047{
1048 if(pWriteBitmap == NULL) return; //can be NULL for non-file mappings
1049
1050 for(int i=startpage;i<startpage+nrpages;i++) {
1051 set_bit(i, pWriteBitmap);
1052 }
1053}
1054//******************************************************************************
1055// Win32MemMapView::clearDirtyPages
1056//
1057// Mark pages as clean in the write page bitmap
1058//
1059// Parameters:
1060//
1061// int startpage - start page
1062// int nrpages - number of pages
1063//
1064//
1065//******************************************************************************
1066void Win32MemMap::clearDirtyPages(int startpage, int nrpages)
1067{
1068 if(pWriteBitmap == NULL) return; //can be NULL for non-file mappings
1069
1070 for(int i=startpage;i<startpage+nrpages;i++) {
1071 clear_bit(i, pWriteBitmap);
1072 }
1073}
1074//******************************************************************************
1075//******************************************************************************
Note: See TracBrowser for help on using the repository browser.