sync trunk head (r37928)
[reactos.git] / reactos / ntoskrnl / mm / section.c
1 /*
2 * Copyright (C) 1998-2005 ReactOS Team (and the authors from the programmers section)
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 *
18 *
19 * PROJECT: ReactOS kernel
20 * FILE: ntoskrnl/mm/section.c
21 * PURPOSE: Implements section objects
22 *
23 * PROGRAMMERS: Rex Jolliff
24 * David Welch
25 * Eric Kohl
26 * Emanuele Aliberti
27 * Eugene Ingerman
28 * Casper Hornstrup
29 * KJK::Hyperion
30 * Guido de Jong
31 * Ge van Geldorp
32 * Royce Mitchell III
33 * Filip Navara
34 * Aleksey Bragin
35 * Jason Filby
36 * Thomas Weidenmueller
37 * Gunnar Andre' Dalsnes
38 * Mike Nordell
39 * Alex Ionescu
40 * Gregor Anich
41 * Steven Edwards
42 * Herve Poussineau
43 */
44
45 /* INCLUDES *****************************************************************/
46
47 #include <ntoskrnl.h>
48 #define NDEBUG
49 #include <debug.h>
50 #include <reactos/exeformat.h>
51
52 #if defined (ALLOC_PRAGMA)
53 #pragma alloc_text(INIT, MmCreatePhysicalMemorySection)
54 #pragma alloc_text(INIT, MmInitSectionImplementation)
55 #endif
56
57
58 /* TYPES *********************************************************************/
59
60 typedef struct
61 {
62 PROS_SECTION_OBJECT Section;
63 PMM_SECTION_SEGMENT Segment;
64 ULONG Offset;
65 BOOLEAN WasDirty;
66 BOOLEAN Private;
67 }
68 MM_SECTION_PAGEOUT_CONTEXT;
69
70 /* GLOBALS *******************************************************************/
71
72 POBJECT_TYPE MmSectionObjectType = NULL;
73
74 static GENERIC_MAPPING MmpSectionMapping = {
75 STANDARD_RIGHTS_READ | SECTION_MAP_READ | SECTION_QUERY,
76 STANDARD_RIGHTS_WRITE | SECTION_MAP_WRITE,
77 STANDARD_RIGHTS_EXECUTE | SECTION_MAP_EXECUTE,
78 SECTION_ALL_ACCESS};
79
80 #define PAGE_FROM_SSE(E) ((E) & 0xFFFFF000)
81 #define PFN_FROM_SSE(E) ((E) >> PAGE_SHIFT)
82 #define SHARE_COUNT_FROM_SSE(E) (((E) & 0x00000FFE) >> 1)
83 #define IS_SWAP_FROM_SSE(E) ((E) & 0x00000001)
84 #define MAX_SHARE_COUNT 0x7FF
85 #define MAKE_SSE(P, C) ((P) | ((C) << 1))
86 #define SWAPENTRY_FROM_SSE(E) ((E) >> 1)
87 #define MAKE_SWAP_SSE(S) (((S) << 1) | 0x1)
88
89 static const INFORMATION_CLASS_INFO ExSectionInfoClass[] =
90 {
91 ICI_SQ_SAME( sizeof(SECTION_BASIC_INFORMATION), sizeof(ULONG), ICIF_QUERY ), /* SectionBasicInformation */
92 ICI_SQ_SAME( sizeof(SECTION_IMAGE_INFORMATION), sizeof(ULONG), ICIF_QUERY ), /* SectionImageInformation */
93 };
94
95 /* FUNCTIONS *****************************************************************/
96
97 PFILE_OBJECT
98 NTAPI
99 MmGetFileObjectForSection(IN PROS_SECTION_OBJECT Section)
100 {
101 PAGED_CODE();
102 ASSERT(Section);
103
104 /* Return the file object */
105 return Section->FileObject; // Section->ControlArea->FileObject on NT
106 }
107
108 NTSTATUS
109 NTAPI
110 MmGetFileNameForSection(IN PROS_SECTION_OBJECT Section,
111 OUT POBJECT_NAME_INFORMATION *ModuleName)
112 {
113 POBJECT_NAME_INFORMATION ObjectNameInfo;
114 NTSTATUS Status;
115 ULONG ReturnLength;
116
117 /* Make sure it's an image section */
118 *ModuleName = NULL;
119 if (!(Section->AllocationAttributes & SEC_IMAGE))
120 {
121 /* It's not, fail */
122 return STATUS_SECTION_NOT_IMAGE;
123 }
124
125 /* Allocate memory for our structure */
126 ObjectNameInfo = ExAllocatePoolWithTag(PagedPool,
127 1024,
128 TAG('M', 'm', ' ', ' '));
129 if (!ObjectNameInfo) return STATUS_NO_MEMORY;
130
131 /* Query the name */
132 Status = ObQueryNameString(Section->FileObject,
133 ObjectNameInfo,
134 1024,
135 &ReturnLength);
136 if (!NT_SUCCESS(Status))
137 {
138 /* Failed, free memory */
139 ExFreePoolWithTag(ObjectNameInfo, TAG('M', 'm', ' ', ' '));
140 return Status;
141 }
142
143 /* Success */
144 *ModuleName = ObjectNameInfo;
145 return STATUS_SUCCESS;
146 }
147
148 NTSTATUS
149 NTAPI
150 MmGetFileNameForAddress(IN PVOID Address,
151 OUT PUNICODE_STRING ModuleName)
152 {
153 PROS_SECTION_OBJECT Section;
154 PMEMORY_AREA MemoryArea;
155 PMM_AVL_TABLE AddressSpace;
156 POBJECT_NAME_INFORMATION ModuleNameInformation;
157 NTSTATUS Status = STATUS_ADDRESS_NOT_ASSOCIATED;
158
159 /* Get the MM_AVL_TABLE from EPROCESS */
160 if (Address >= MmSystemRangeStart)
161 {
162 AddressSpace = MmGetKernelAddressSpace();
163 }
164 else
165 {
166 AddressSpace = &PsGetCurrentProcess()->VadRoot;
167 }
168
169 /* Lock address space */
170 MmLockAddressSpace(AddressSpace);
171
172 /* Locate the memory area for the process by address */
173 MemoryArea = MmLocateMemoryAreaByAddress(AddressSpace, Address);
174
175 /* Make sure it's a section view type */
176 if ((MemoryArea != NULL) && (MemoryArea->Type == MEMORY_AREA_SECTION_VIEW))
177 {
178 /* Get the section pointer to the SECTION_OBJECT */
179 Section = MemoryArea->Data.SectionData.Section;
180
181 /* Unlock address space */
182 MmUnlockAddressSpace(AddressSpace);
183
184 /* Get the filename of the section */
185 Status = MmGetFileNameForSection(Section,&ModuleNameInformation);
186
187 if (NT_SUCCESS(Status))
188 {
189 /* Init modulename */
190 RtlCreateUnicodeString(ModuleName,
191 ModuleNameInformation->Name.Buffer);
192
193 /* Free temp taged buffer from MmGetFileNameForSection() */
194 ExFreePoolWithTag(ModuleNameInformation, TAG('M', 'm', ' ', ' '));
195 DPRINT("Found ModuleName %S by address %p\n",
196 ModuleName->Buffer,Address);
197 }
198 }
199 else
200 {
201 /* Unlock address space */
202 MmUnlockAddressSpace(AddressSpace);
203 }
204
205 return Status;
206 }
207
208 /* Note: Mmsp prefix denotes "Memory Manager Section Private". */
209
210 /*
211 * FUNCTION: Waits in kernel mode up to ten seconds for an MM_PAGEOP event.
212 * ARGUMENTS: PMM_PAGEOP which event we should wait for.
213 * RETURNS: Status of the wait.
214 */
215 static NTSTATUS
216 MmspWaitForPageOpCompletionEvent(PMM_PAGEOP PageOp)
217 {
218 LARGE_INTEGER Timeout;
219 #ifdef __GNUC__ /* TODO: Use other macro to check for suffix to use? */
220
221 Timeout.QuadPart = -100000000LL; // 10 sec
222 #else
223
224 Timeout.QuadPart = -100000000; // 10 sec
225 #endif
226
227 return KeWaitForSingleObject(&PageOp->CompletionEvent, 0, KernelMode, FALSE, &Timeout);
228 }
229
230
231 /*
232 * FUNCTION: Sets the page op completion event and releases the page op.
233 * ARGUMENTS: PMM_PAGEOP.
234 * RETURNS: In shorter time than it takes you to even read this
235 * description, so don't even think about geting a mug of coffee.
236 */
237 static void
238 MmspCompleteAndReleasePageOp(PMM_PAGEOP PageOp)
239 {
240 KeSetEvent(&PageOp->CompletionEvent, IO_NO_INCREMENT, FALSE);
241 MmReleasePageOp(PageOp);
242 }
243
244
245 /*
246 * FUNCTION: Waits in kernel mode indefinitely for a file object lock.
247 * ARGUMENTS: PFILE_OBJECT to wait for.
248 * RETURNS: Status of the wait.
249 */
250 static NTSTATUS
251 MmspWaitForFileLock(PFILE_OBJECT File)
252 {
253 return STATUS_SUCCESS;
254 //return KeWaitForSingleObject(&File->Lock, 0, KernelMode, FALSE, NULL);
255 }
256
257
258 VOID
259 MmFreePageTablesSectionSegment(PMM_SECTION_SEGMENT Segment)
260 {
261 ULONG i;
262 if (Segment->Length > NR_SECTION_PAGE_TABLES * PAGE_SIZE)
263 {
264 for (i = 0; i < NR_SECTION_PAGE_TABLES; i++)
265 {
266 if (Segment->PageDirectory.PageTables[i] != NULL)
267 {
268 ExFreePool(Segment->PageDirectory.PageTables[i]);
269 }
270 }
271 }
272 }
273
274 VOID
275 NTAPI
276 MmFreeSectionSegments(PFILE_OBJECT FileObject)
277 {
278 if (FileObject->SectionObjectPointer->ImageSectionObject != NULL)
279 {
280 PMM_IMAGE_SECTION_OBJECT ImageSectionObject;
281 PMM_SECTION_SEGMENT SectionSegments;
282 ULONG NrSegments;
283 ULONG i;
284
285 ImageSectionObject = (PMM_IMAGE_SECTION_OBJECT)FileObject->SectionObjectPointer->ImageSectionObject;
286 NrSegments = ImageSectionObject->NrSegments;
287 SectionSegments = ImageSectionObject->Segments;
288 for (i = 0; i < NrSegments; i++)
289 {
290 if (SectionSegments[i].ReferenceCount != 0)
291 {
292 DPRINT1("Image segment %d still referenced (was %d)\n", i,
293 SectionSegments[i].ReferenceCount);
294 KeBugCheck(MEMORY_MANAGEMENT);
295 }
296 MmFreePageTablesSectionSegment(&SectionSegments[i]);
297 }
298 ExFreePool(ImageSectionObject->Segments);
299 ExFreePool(ImageSectionObject);
300 FileObject->SectionObjectPointer->ImageSectionObject = NULL;
301 }
302 if (FileObject->SectionObjectPointer->DataSectionObject != NULL)
303 {
304 PMM_SECTION_SEGMENT Segment;
305
306 Segment = (PMM_SECTION_SEGMENT)FileObject->SectionObjectPointer->
307 DataSectionObject;
308
309 if (Segment->ReferenceCount != 0)
310 {
311 DPRINT1("Data segment still referenced\n");
312 KeBugCheck(MEMORY_MANAGEMENT);
313 }
314 MmFreePageTablesSectionSegment(Segment);
315 ExFreePool(Segment);
316 FileObject->SectionObjectPointer->DataSectionObject = NULL;
317 }
318 }
319
320 VOID
321 NTAPI
322 MmLockSectionSegment(PMM_SECTION_SEGMENT Segment)
323 {
324 ExAcquireFastMutex(&Segment->Lock);
325 }
326
327 VOID
328 NTAPI
329 MmUnlockSectionSegment(PMM_SECTION_SEGMENT Segment)
330 {
331 ExReleaseFastMutex(&Segment->Lock);
332 }
333
334 VOID
335 NTAPI
336 MmSetPageEntrySectionSegment(PMM_SECTION_SEGMENT Segment,
337 ULONG Offset,
338 ULONG Entry)
339 {
340 PSECTION_PAGE_TABLE Table;
341 ULONG DirectoryOffset;
342 ULONG TableOffset;
343
344 if (Segment->Length <= NR_SECTION_PAGE_TABLES * PAGE_SIZE)
345 {
346 Table = (PSECTION_PAGE_TABLE)&Segment->PageDirectory;
347 }
348 else
349 {
350 DirectoryOffset = PAGE_TO_SECTION_PAGE_DIRECTORY_OFFSET(Offset);
351 Table = Segment->PageDirectory.PageTables[DirectoryOffset];
352 if (Table == NULL)
353 {
354 Table =
355 Segment->PageDirectory.PageTables[DirectoryOffset] =
356 ExAllocatePoolWithTag(NonPagedPool, sizeof(SECTION_PAGE_TABLE),
357 TAG_SECTION_PAGE_TABLE);
358 if (Table == NULL)
359 {
360 KeBugCheck(MEMORY_MANAGEMENT);
361 }
362 memset(Table, 0, sizeof(SECTION_PAGE_TABLE));
363 DPRINT("Table %x\n", Table);
364 }
365 }
366 TableOffset = PAGE_TO_SECTION_PAGE_TABLE_OFFSET(Offset);
367 Table->Entry[TableOffset] = Entry;
368 }
369
370
371 ULONG
372 NTAPI
373 MmGetPageEntrySectionSegment(PMM_SECTION_SEGMENT Segment,
374 ULONG Offset)
375 {
376 PSECTION_PAGE_TABLE Table;
377 ULONG Entry;
378 ULONG DirectoryOffset;
379 ULONG TableOffset;
380
381 DPRINT("MmGetPageEntrySection(Segment %x, Offset %x)\n", Segment, Offset);
382
383 if (Segment->Length <= NR_SECTION_PAGE_TABLES * PAGE_SIZE)
384 {
385 Table = (PSECTION_PAGE_TABLE)&Segment->PageDirectory;
386 }
387 else
388 {
389 DirectoryOffset = PAGE_TO_SECTION_PAGE_DIRECTORY_OFFSET(Offset);
390 Table = Segment->PageDirectory.PageTables[DirectoryOffset];
391 DPRINT("Table %x\n", Table);
392 if (Table == NULL)
393 {
394 return(0);
395 }
396 }
397 TableOffset = PAGE_TO_SECTION_PAGE_TABLE_OFFSET(Offset);
398 Entry = Table->Entry[TableOffset];
399 return(Entry);
400 }
401
402 VOID
403 NTAPI
404 MmSharePageEntrySectionSegment(PMM_SECTION_SEGMENT Segment,
405 ULONG Offset)
406 {
407 ULONG Entry;
408
409 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
410 if (Entry == 0)
411 {
412 DPRINT1("Entry == 0 for MmSharePageEntrySectionSegment\n");
413 KeBugCheck(MEMORY_MANAGEMENT);
414 }
415 if (SHARE_COUNT_FROM_SSE(Entry) == MAX_SHARE_COUNT)
416 {
417 DPRINT1("Maximum share count reached\n");
418 KeBugCheck(MEMORY_MANAGEMENT);
419 }
420 if (IS_SWAP_FROM_SSE(Entry))
421 {
422 KeBugCheck(MEMORY_MANAGEMENT);
423 }
424 Entry = MAKE_SSE(PAGE_FROM_SSE(Entry), SHARE_COUNT_FROM_SSE(Entry) + 1);
425 MmSetPageEntrySectionSegment(Segment, Offset, Entry);
426 }
427
428 BOOLEAN
429 NTAPI
430 MmUnsharePageEntrySectionSegment(PROS_SECTION_OBJECT Section,
431 PMM_SECTION_SEGMENT Segment,
432 ULONG Offset,
433 BOOLEAN Dirty,
434 BOOLEAN PageOut)
435 {
436 ULONG Entry;
437 BOOLEAN IsDirectMapped = FALSE;
438
439 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
440 if (Entry == 0)
441 {
442 DPRINT1("Entry == 0 for MmUnsharePageEntrySectionSegment\n");
443 KeBugCheck(MEMORY_MANAGEMENT);
444 }
445 if (SHARE_COUNT_FROM_SSE(Entry) == 0)
446 {
447 DPRINT1("Zero share count for unshare\n");
448 KeBugCheck(MEMORY_MANAGEMENT);
449 }
450 if (IS_SWAP_FROM_SSE(Entry))
451 {
452 KeBugCheck(MEMORY_MANAGEMENT);
453 }
454 Entry = MAKE_SSE(PAGE_FROM_SSE(Entry), SHARE_COUNT_FROM_SSE(Entry) - 1);
455 /*
456 * If we reducing the share count of this entry to zero then set the entry
457 * to zero and tell the cache the page is no longer mapped.
458 */
459 if (SHARE_COUNT_FROM_SSE(Entry) == 0)
460 {
461 PFILE_OBJECT FileObject;
462 PBCB Bcb;
463 SWAPENTRY SavedSwapEntry;
464 PFN_TYPE Page;
465 BOOLEAN IsImageSection;
466 ULONG FileOffset;
467
468 FileOffset = Offset + Segment->FileOffset;
469
470 IsImageSection = Section->AllocationAttributes & SEC_IMAGE ? TRUE : FALSE;
471
472 Page = PFN_FROM_SSE(Entry);
473 FileObject = Section->FileObject;
474 if (FileObject != NULL &&
475 !(Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
476 {
477
478 if ((FileOffset % PAGE_SIZE) == 0 &&
479 (Offset + PAGE_SIZE <= Segment->RawLength || !IsImageSection))
480 {
481 NTSTATUS Status;
482 Bcb = FileObject->SectionObjectPointer->SharedCacheMap;
483 IsDirectMapped = TRUE;
484 Status = CcRosUnmapCacheSegment(Bcb, FileOffset, Dirty);
485 if (!NT_SUCCESS(Status))
486 {
487 DPRINT1("CcRosUnmapCacheSegment failed, status = %x\n", Status);
488 KeBugCheck(MEMORY_MANAGEMENT);
489 }
490 }
491 }
492
493 SavedSwapEntry = MmGetSavedSwapEntryPage(Page);
494 if (SavedSwapEntry == 0)
495 {
496 if (!PageOut &&
497 ((Segment->Flags & MM_PAGEFILE_SEGMENT) ||
498 (Segment->Characteristics & IMAGE_SCN_MEM_SHARED)))
499 {
500 /*
501 * FIXME:
502 * Try to page out this page and set the swap entry
503 * within the section segment. There exist no rmap entry
504 * for this page. The pager thread can't page out a
505 * page without a rmap entry.
506 */
507 MmSetPageEntrySectionSegment(Segment, Offset, Entry);
508 }
509 else
510 {
511 MmSetPageEntrySectionSegment(Segment, Offset, 0);
512 if (!IsDirectMapped)
513 {
514 MmReleasePageMemoryConsumer(MC_USER, Page);
515 }
516 }
517 }
518 else
519 {
520 if ((Segment->Flags & MM_PAGEFILE_SEGMENT) ||
521 (Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
522 {
523 if (!PageOut)
524 {
525 if (Dirty)
526 {
527 /*
528 * FIXME:
529 * We hold all locks. Nobody can do something with the current
530 * process and the current segment (also not within an other process).
531 */
532 NTSTATUS Status;
533 Status = MmWriteToSwapPage(SavedSwapEntry, Page);
534 if (!NT_SUCCESS(Status))
535 {
536 DPRINT1("MM: Failed to write to swap page (Status was 0x%.8X)\n", Status);
537 KeBugCheck(MEMORY_MANAGEMENT);
538 }
539 }
540 MmSetPageEntrySectionSegment(Segment, Offset, MAKE_SWAP_SSE(SavedSwapEntry));
541 MmSetSavedSwapEntryPage(Page, 0);
542 }
543 MmReleasePageMemoryConsumer(MC_USER, Page);
544 }
545 else
546 {
547 DPRINT1("Found a swapentry for a non private page in an image or data file sgment\n");
548 KeBugCheck(MEMORY_MANAGEMENT);
549 }
550 }
551 }
552 else
553 {
554 MmSetPageEntrySectionSegment(Segment, Offset, Entry);
555 }
556 return(SHARE_COUNT_FROM_SSE(Entry) > 0);
557 }
558
559 BOOLEAN MiIsPageFromCache(PMEMORY_AREA MemoryArea,
560 ULONG SegOffset)
561 {
562 if (!(MemoryArea->Data.SectionData.Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
563 {
564 PBCB Bcb;
565 PCACHE_SEGMENT CacheSeg;
566 Bcb = MemoryArea->Data.SectionData.Section->FileObject->SectionObjectPointer->SharedCacheMap;
567 CacheSeg = CcRosLookupCacheSegment(Bcb, SegOffset + MemoryArea->Data.SectionData.Segment->FileOffset);
568 if (CacheSeg)
569 {
570 CcRosReleaseCacheSegment(Bcb, CacheSeg, CacheSeg->Valid, FALSE, TRUE);
571 return TRUE;
572 }
573 }
574 return FALSE;
575 }
576
577 NTSTATUS
578 NTAPI
579 MiReadPage(PMEMORY_AREA MemoryArea,
580 ULONG SegOffset,
581 PPFN_TYPE Page)
582 /*
583 * FUNCTION: Read a page for a section backed memory area.
584 * PARAMETERS:
585 * MemoryArea - Memory area to read the page for.
586 * Offset - Offset of the page to read.
587 * Page - Variable that receives a page contains the read data.
588 */
589 {
590 ULONG BaseOffset;
591 ULONG FileOffset;
592 PVOID BaseAddress;
593 BOOLEAN UptoDate;
594 PCACHE_SEGMENT CacheSeg;
595 PFILE_OBJECT FileObject;
596 NTSTATUS Status;
597 ULONG RawLength;
598 PBCB Bcb;
599 BOOLEAN IsImageSection;
600 ULONG Length;
601
602 FileObject = MemoryArea->Data.SectionData.Section->FileObject;
603 Bcb = FileObject->SectionObjectPointer->SharedCacheMap;
604 RawLength = MemoryArea->Data.SectionData.Segment->RawLength;
605 FileOffset = SegOffset + MemoryArea->Data.SectionData.Segment->FileOffset;
606 IsImageSection = MemoryArea->Data.SectionData.Section->AllocationAttributes & SEC_IMAGE ? TRUE : FALSE;
607
608 ASSERT(Bcb);
609
610 DPRINT("%S %x\n", FileObject->FileName.Buffer, FileOffset);
611
612 /*
613 * If the file system is letting us go directly to the cache and the
614 * memory area was mapped at an offset in the file which is page aligned
615 * then get the related cache segment.
616 */
617 if ((FileOffset % PAGE_SIZE) == 0 &&
618 (SegOffset + PAGE_SIZE <= RawLength || !IsImageSection) &&
619 !(MemoryArea->Data.SectionData.Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
620 {
621
622 /*
623 * Get the related cache segment; we use a lower level interface than
624 * filesystems do because it is safe for us to use an offset with a
625 * alignment less than the file system block size.
626 */
627 Status = CcRosGetCacheSegment(Bcb,
628 FileOffset,
629 &BaseOffset,
630 &BaseAddress,
631 &UptoDate,
632 &CacheSeg);
633 if (!NT_SUCCESS(Status))
634 {
635 return(Status);
636 }
637 if (!UptoDate)
638 {
639 /*
640 * If the cache segment isn't up to date then call the file
641 * system to read in the data.
642 */
643 Status = ReadCacheSegment(CacheSeg);
644 if (!NT_SUCCESS(Status))
645 {
646 CcRosReleaseCacheSegment(Bcb, CacheSeg, FALSE, FALSE, FALSE);
647 return Status;
648 }
649 }
650 /*
651 * Retrieve the page from the cache segment that we actually want.
652 */
653 (*Page) = MmGetPhysicalAddress((char*)BaseAddress +
654 FileOffset - BaseOffset).LowPart >> PAGE_SHIFT;
655
656 CcRosReleaseCacheSegment(Bcb, CacheSeg, TRUE, FALSE, TRUE);
657 }
658 else
659 {
660 PVOID PageAddr;
661 ULONG CacheSegOffset;
662 /*
663 * Allocate a page, this is rather complicated by the possibility
664 * we might have to move other things out of memory
665 */
666 Status = MmRequestPageMemoryConsumer(MC_USER, TRUE, Page);
667 if (!NT_SUCCESS(Status))
668 {
669 return(Status);
670 }
671 Status = CcRosGetCacheSegment(Bcb,
672 FileOffset,
673 &BaseOffset,
674 &BaseAddress,
675 &UptoDate,
676 &CacheSeg);
677 if (!NT_SUCCESS(Status))
678 {
679 return(Status);
680 }
681 if (!UptoDate)
682 {
683 /*
684 * If the cache segment isn't up to date then call the file
685 * system to read in the data.
686 */
687 Status = ReadCacheSegment(CacheSeg);
688 if (!NT_SUCCESS(Status))
689 {
690 CcRosReleaseCacheSegment(Bcb, CacheSeg, FALSE, FALSE, FALSE);
691 return Status;
692 }
693 }
694 PageAddr = MmCreateHyperspaceMapping(*Page);
695 CacheSegOffset = BaseOffset + CacheSeg->Bcb->CacheSegmentSize - FileOffset;
696 Length = RawLength - SegOffset;
697 if (Length <= CacheSegOffset && Length <= PAGE_SIZE)
698 {
699 memcpy(PageAddr, (char*)BaseAddress + FileOffset - BaseOffset, Length);
700 }
701 else if (CacheSegOffset >= PAGE_SIZE)
702 {
703 memcpy(PageAddr, (char*)BaseAddress + FileOffset - BaseOffset, PAGE_SIZE);
704 }
705 else
706 {
707 memcpy(PageAddr, (char*)BaseAddress + FileOffset - BaseOffset, CacheSegOffset);
708 CcRosReleaseCacheSegment(Bcb, CacheSeg, TRUE, FALSE, FALSE);
709 Status = CcRosGetCacheSegment(Bcb,
710 FileOffset + CacheSegOffset,
711 &BaseOffset,
712 &BaseAddress,
713 &UptoDate,
714 &CacheSeg);
715 if (!NT_SUCCESS(Status))
716 {
717 MmDeleteHyperspaceMapping(PageAddr);
718 return(Status);
719 }
720 if (!UptoDate)
721 {
722 /*
723 * If the cache segment isn't up to date then call the file
724 * system to read in the data.
725 */
726 Status = ReadCacheSegment(CacheSeg);
727 if (!NT_SUCCESS(Status))
728 {
729 CcRosReleaseCacheSegment(Bcb, CacheSeg, FALSE, FALSE, FALSE);
730 MmDeleteHyperspaceMapping(PageAddr);
731 return Status;
732 }
733 }
734 if (Length < PAGE_SIZE)
735 {
736 memcpy((char*)PageAddr + CacheSegOffset, BaseAddress, Length - CacheSegOffset);
737 }
738 else
739 {
740 memcpy((char*)PageAddr + CacheSegOffset, BaseAddress, PAGE_SIZE - CacheSegOffset);
741 }
742 }
743 CcRosReleaseCacheSegment(Bcb, CacheSeg, TRUE, FALSE, FALSE);
744 MmDeleteHyperspaceMapping(PageAddr);
745 }
746 return(STATUS_SUCCESS);
747 }
748
749 NTSTATUS
750 NTAPI
751 MmNotPresentFaultSectionView(PMM_AVL_TABLE AddressSpace,
752 MEMORY_AREA* MemoryArea,
753 PVOID Address,
754 BOOLEAN Locked)
755 {
756 ULONG Offset;
757 PFN_TYPE Page;
758 NTSTATUS Status;
759 PVOID PAddress;
760 PROS_SECTION_OBJECT Section;
761 PMM_SECTION_SEGMENT Segment;
762 ULONG Entry;
763 ULONG Entry1;
764 ULONG Attributes;
765 PMM_PAGEOP PageOp;
766 PMM_REGION Region;
767 BOOLEAN HasSwapEntry;
768 PEPROCESS Process = MmGetAddressSpaceOwner(AddressSpace);
769
770 /*
771 * There is a window between taking the page fault and locking the
772 * address space when another thread could load the page so we check
773 * that.
774 */
775 if (MmIsPagePresent(Process, Address))
776 {
777 if (Locked)
778 {
779 MmLockPage(MmGetPfnForProcess(Process, Address));
780 }
781 return(STATUS_SUCCESS);
782 }
783
784 PAddress = MM_ROUND_DOWN(Address, PAGE_SIZE);
785 Offset = (ULONG_PTR)PAddress - (ULONG_PTR)MemoryArea->StartingAddress
786 + MemoryArea->Data.SectionData.ViewOffset;
787
788 Segment = MemoryArea->Data.SectionData.Segment;
789 Section = MemoryArea->Data.SectionData.Section;
790 Region = MmFindRegion(MemoryArea->StartingAddress,
791 &MemoryArea->Data.SectionData.RegionListHead,
792 Address, NULL);
793 /*
794 * Lock the segment
795 */
796 MmLockSectionSegment(Segment);
797
798 /*
799 * Check if this page needs to be mapped COW
800 */
801 if ((Segment->WriteCopy || MemoryArea->Data.SectionData.WriteCopyView) &&
802 (Region->Protect == PAGE_READWRITE ||
803 Region->Protect == PAGE_EXECUTE_READWRITE))
804 {
805 Attributes = Region->Protect == PAGE_READWRITE ? PAGE_READONLY : PAGE_EXECUTE_READ;
806 }
807 else
808 {
809 Attributes = Region->Protect;
810 }
811
812 /*
813 * Get or create a page operation descriptor
814 */
815 PageOp = MmGetPageOp(MemoryArea, NULL, 0, Segment, Offset, MM_PAGEOP_PAGEIN, FALSE);
816 if (PageOp == NULL)
817 {
818 DPRINT1("MmGetPageOp failed\n");
819 KeBugCheck(MEMORY_MANAGEMENT);
820 }
821
822 /*
823 * Check if someone else is already handling this fault, if so wait
824 * for them
825 */
826 if (PageOp->Thread != PsGetCurrentThread())
827 {
828 MmUnlockSectionSegment(Segment);
829 MmUnlockAddressSpace(AddressSpace);
830 Status = MmspWaitForPageOpCompletionEvent(PageOp);
831 /*
832 * Check for various strange conditions
833 */
834 if (Status != STATUS_SUCCESS)
835 {
836 DPRINT1("Failed to wait for page op, status = %x\n", Status);
837 KeBugCheck(MEMORY_MANAGEMENT);
838 }
839 if (PageOp->Status == STATUS_PENDING)
840 {
841 DPRINT1("Woke for page op before completion\n");
842 KeBugCheck(MEMORY_MANAGEMENT);
843 }
844 MmLockAddressSpace(AddressSpace);
845 /*
846 * If this wasn't a pagein then restart the operation
847 */
848 if (PageOp->OpType != MM_PAGEOP_PAGEIN)
849 {
850 MmspCompleteAndReleasePageOp(PageOp);
851 DPRINT("Address 0x%.8X\n", Address);
852 return(STATUS_MM_RESTART_OPERATION);
853 }
854
855 /*
856 * If the thread handling this fault has failed then we don't retry
857 */
858 if (!NT_SUCCESS(PageOp->Status))
859 {
860 Status = PageOp->Status;
861 MmspCompleteAndReleasePageOp(PageOp);
862 DPRINT("Address 0x%.8X\n", Address);
863 return(Status);
864 }
865 MmLockSectionSegment(Segment);
866 /*
867 * If the completed fault was for another address space then set the
868 * page in this one.
869 */
870 if (!MmIsPagePresent(Process, Address))
871 {
872 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
873 HasSwapEntry = MmIsPageSwapEntry(Process, (PVOID)PAddress);
874
875 if (PAGE_FROM_SSE(Entry) == 0 || HasSwapEntry)
876 {
877 /*
878 * The page was a private page in another or in our address space
879 */
880 MmUnlockSectionSegment(Segment);
881 MmspCompleteAndReleasePageOp(PageOp);
882 return(STATUS_MM_RESTART_OPERATION);
883 }
884
885 Page = PFN_FROM_SSE(Entry);
886
887 MmSharePageEntrySectionSegment(Segment, Offset);
888
889 /* FIXME: Should we call MmCreateVirtualMappingUnsafe if
890 * (Section->AllocationAttributes & SEC_PHYSICALMEMORY) is true?
891 */
892 Status = MmCreateVirtualMapping(Process,
893 Address,
894 Attributes,
895 &Page,
896 1);
897 if (!NT_SUCCESS(Status))
898 {
899 DPRINT1("Unable to create virtual mapping\n");
900 KeBugCheck(MEMORY_MANAGEMENT);
901 }
902 MmInsertRmap(Page, Process, (PVOID)PAddress);
903 }
904 if (Locked)
905 {
906 MmLockPage(Page);
907 }
908 MmUnlockSectionSegment(Segment);
909 PageOp->Status = STATUS_SUCCESS;
910 MmspCompleteAndReleasePageOp(PageOp);
911 DPRINT("Address 0x%.8X\n", Address);
912 return(STATUS_SUCCESS);
913 }
914
915 HasSwapEntry = MmIsPageSwapEntry(Process, (PVOID)PAddress);
916 if (HasSwapEntry)
917 {
918 /*
919 * Must be private page we have swapped out.
920 */
921 SWAPENTRY SwapEntry;
922
923 /*
924 * Sanity check
925 */
926 if (Segment->Flags & MM_PAGEFILE_SEGMENT)
927 {
928 DPRINT1("Found a swaped out private page in a pagefile section.\n");
929 KeBugCheck(MEMORY_MANAGEMENT);
930 }
931
932 MmUnlockSectionSegment(Segment);
933 MmDeletePageFileMapping(Process, (PVOID)PAddress, &SwapEntry);
934
935 MmUnlockAddressSpace(AddressSpace);
936 Status = MmRequestPageMemoryConsumer(MC_USER, TRUE, &Page);
937 if (!NT_SUCCESS(Status))
938 {
939 KeBugCheck(MEMORY_MANAGEMENT);
940 }
941
942 Status = MmReadFromSwapPage(SwapEntry, Page);
943 if (!NT_SUCCESS(Status))
944 {
945 DPRINT1("MmReadFromSwapPage failed, status = %x\n", Status);
946 KeBugCheck(MEMORY_MANAGEMENT);
947 }
948 MmLockAddressSpace(AddressSpace);
949 Status = MmCreateVirtualMapping(Process,
950 Address,
951 Region->Protect,
952 &Page,
953 1);
954 if (!NT_SUCCESS(Status))
955 {
956 DPRINT("MmCreateVirtualMapping failed, not out of memory\n");
957 KeBugCheck(MEMORY_MANAGEMENT);
958 return(Status);
959 }
960
961 /*
962 * Store the swap entry for later use.
963 */
964 MmSetSavedSwapEntryPage(Page, SwapEntry);
965
966 /*
967 * Add the page to the process's working set
968 */
969 MmInsertRmap(Page, Process, (PVOID)PAddress);
970
971 /*
972 * Finish the operation
973 */
974 if (Locked)
975 {
976 MmLockPage(Page);
977 }
978 PageOp->Status = STATUS_SUCCESS;
979 MmspCompleteAndReleasePageOp(PageOp);
980 DPRINT("Address 0x%.8X\n", Address);
981 return(STATUS_SUCCESS);
982 }
983
984 /*
985 * Satisfying a page fault on a map of /Device/PhysicalMemory is easy
986 */
987 if (Section->AllocationAttributes & SEC_PHYSICALMEMORY)
988 {
989 MmUnlockSectionSegment(Segment);
990 /*
991 * Just map the desired physical page
992 */
993 Page = Offset >> PAGE_SHIFT;
994 Status = MmCreateVirtualMappingUnsafe(Process,
995 Address,
996 Region->Protect,
997 &Page,
998 1);
999 if (!NT_SUCCESS(Status))
1000 {
1001 DPRINT("MmCreateVirtualMappingUnsafe failed, not out of memory\n");
1002 KeBugCheck(MEMORY_MANAGEMENT);
1003 return(Status);
1004 }
1005 /*
1006 * Don't add an rmap entry since the page mapped could be for
1007 * anything.
1008 */
1009 if (Locked)
1010 {
1011 MmLockPageUnsafe(Page);
1012 }
1013
1014 /*
1015 * Cleanup and release locks
1016 */
1017 PageOp->Status = STATUS_SUCCESS;
1018 MmspCompleteAndReleasePageOp(PageOp);
1019 DPRINT("Address 0x%.8X\n", Address);
1020 return(STATUS_SUCCESS);
1021 }
1022
1023 /*
1024 * Map anonymous memory for BSS sections
1025 */
1026 if (Segment->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
1027 {
1028 MmUnlockSectionSegment(Segment);
1029 Status = MmRequestPageMemoryConsumer(MC_USER, FALSE, &Page);
1030 if (!NT_SUCCESS(Status))
1031 {
1032 MmUnlockAddressSpace(AddressSpace);
1033 Status = MmRequestPageMemoryConsumer(MC_USER, TRUE, &Page);
1034 MmLockAddressSpace(AddressSpace);
1035 }
1036 if (!NT_SUCCESS(Status))
1037 {
1038 KeBugCheck(MEMORY_MANAGEMENT);
1039 }
1040 Status = MmCreateVirtualMapping(Process,
1041 Address,
1042 Region->Protect,
1043 &Page,
1044 1);
1045 if (!NT_SUCCESS(Status))
1046 {
1047 DPRINT("MmCreateVirtualMapping failed, not out of memory\n");
1048 KeBugCheck(MEMORY_MANAGEMENT);
1049 return(Status);
1050 }
1051 MmInsertRmap(Page, Process, (PVOID)PAddress);
1052 if (Locked)
1053 {
1054 MmLockPage(Page);
1055 }
1056
1057 /*
1058 * Cleanup and release locks
1059 */
1060 PageOp->Status = STATUS_SUCCESS;
1061 MmspCompleteAndReleasePageOp(PageOp);
1062 DPRINT("Address 0x%.8X\n", Address);
1063 return(STATUS_SUCCESS);
1064 }
1065
1066 /*
1067 * Get the entry corresponding to the offset within the section
1068 */
1069 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
1070
1071 if (Entry == 0)
1072 {
1073 /*
1074 * If the entry is zero (and it can't change because we have
1075 * locked the segment) then we need to load the page.
1076 */
1077
1078 /*
1079 * Release all our locks and read in the page from disk
1080 */
1081 MmUnlockSectionSegment(Segment);
1082 MmUnlockAddressSpace(AddressSpace);
1083
1084 if ((Segment->Flags & MM_PAGEFILE_SEGMENT) ||
1085 (Offset >= PAGE_ROUND_UP(Segment->RawLength) && Section->AllocationAttributes & SEC_IMAGE))
1086 {
1087 Status = MmRequestPageMemoryConsumer(MC_USER, TRUE, &Page);
1088 if (!NT_SUCCESS(Status))
1089 {
1090 DPRINT1("MmRequestPageMemoryConsumer failed (Status %x)\n", Status);
1091 }
1092 }
1093 else
1094 {
1095 Status = MiReadPage(MemoryArea, Offset, &Page);
1096 if (!NT_SUCCESS(Status))
1097 {
1098 DPRINT1("MiReadPage failed (Status %x)\n", Status);
1099 }
1100 }
1101 if (!NT_SUCCESS(Status))
1102 {
1103 /*
1104 * FIXME: What do we know in this case?
1105 */
1106 /*
1107 * Cleanup and release locks
1108 */
1109 MmLockAddressSpace(AddressSpace);
1110 PageOp->Status = Status;
1111 MmspCompleteAndReleasePageOp(PageOp);
1112 DPRINT("Address 0x%.8X\n", Address);
1113 return(Status);
1114 }
1115 /*
1116 * Relock the address space and segment
1117 */
1118 MmLockAddressSpace(AddressSpace);
1119 MmLockSectionSegment(Segment);
1120
1121 /*
1122 * Check the entry. No one should change the status of a page
1123 * that has a pending page-in.
1124 */
1125 Entry1 = MmGetPageEntrySectionSegment(Segment, Offset);
1126 if (Entry != Entry1)
1127 {
1128 DPRINT1("Someone changed ppte entry while we slept\n");
1129 KeBugCheck(MEMORY_MANAGEMENT);
1130 }
1131
1132 /*
1133 * Mark the offset within the section as having valid, in-memory
1134 * data
1135 */
1136 Entry = MAKE_SSE(Page << PAGE_SHIFT, 1);
1137 MmSetPageEntrySectionSegment(Segment, Offset, Entry);
1138 MmUnlockSectionSegment(Segment);
1139
1140 Status = MmCreateVirtualMapping(Process,
1141 Address,
1142 Attributes,
1143 &Page,
1144 1);
1145 if (!NT_SUCCESS(Status))
1146 {
1147 DPRINT1("Unable to create virtual mapping\n");
1148 KeBugCheck(MEMORY_MANAGEMENT);
1149 }
1150 MmInsertRmap(Page, Process, (PVOID)PAddress);
1151
1152 if (Locked)
1153 {
1154 MmLockPage(Page);
1155 }
1156 PageOp->Status = STATUS_SUCCESS;
1157 MmspCompleteAndReleasePageOp(PageOp);
1158 DPRINT("Address 0x%.8X\n", Address);
1159 return(STATUS_SUCCESS);
1160 }
1161 else if (IS_SWAP_FROM_SSE(Entry))
1162 {
1163 SWAPENTRY SwapEntry;
1164
1165 SwapEntry = SWAPENTRY_FROM_SSE(Entry);
1166
1167 /*
1168 * Release all our locks and read in the page from disk
1169 */
1170 MmUnlockSectionSegment(Segment);
1171
1172 MmUnlockAddressSpace(AddressSpace);
1173
1174 Status = MmRequestPageMemoryConsumer(MC_USER, TRUE, &Page);
1175 if (!NT_SUCCESS(Status))
1176 {
1177 KeBugCheck(MEMORY_MANAGEMENT);
1178 }
1179
1180 Status = MmReadFromSwapPage(SwapEntry, Page);
1181 if (!NT_SUCCESS(Status))
1182 {
1183 KeBugCheck(MEMORY_MANAGEMENT);
1184 }
1185
1186 /*
1187 * Relock the address space and segment
1188 */
1189 MmLockAddressSpace(AddressSpace);
1190 MmLockSectionSegment(Segment);
1191
1192 /*
1193 * Check the entry. No one should change the status of a page
1194 * that has a pending page-in.
1195 */
1196 Entry1 = MmGetPageEntrySectionSegment(Segment, Offset);
1197 if (Entry != Entry1)
1198 {
1199 DPRINT1("Someone changed ppte entry while we slept\n");
1200 KeBugCheck(MEMORY_MANAGEMENT);
1201 }
1202
1203 /*
1204 * Mark the offset within the section as having valid, in-memory
1205 * data
1206 */
1207 Entry = MAKE_SSE(Page << PAGE_SHIFT, 1);
1208 MmSetPageEntrySectionSegment(Segment, Offset, Entry);
1209 MmUnlockSectionSegment(Segment);
1210
1211 /*
1212 * Save the swap entry.
1213 */
1214 MmSetSavedSwapEntryPage(Page, SwapEntry);
1215 Status = MmCreateVirtualMapping(Process,
1216 Address,
1217 Region->Protect,
1218 &Page,
1219 1);
1220 if (!NT_SUCCESS(Status))
1221 {
1222 DPRINT1("Unable to create virtual mapping\n");
1223 KeBugCheck(MEMORY_MANAGEMENT);
1224 }
1225 MmInsertRmap(Page, Process, (PVOID)PAddress);
1226 if (Locked)
1227 {
1228 MmLockPage(Page);
1229 }
1230 PageOp->Status = STATUS_SUCCESS;
1231 MmspCompleteAndReleasePageOp(PageOp);
1232 DPRINT("Address 0x%.8X\n", Address);
1233 return(STATUS_SUCCESS);
1234 }
1235 else
1236 {
1237 /*
1238 * If the section offset is already in-memory and valid then just
1239 * take another reference to the page
1240 */
1241
1242 Page = PFN_FROM_SSE(Entry);
1243
1244 MmSharePageEntrySectionSegment(Segment, Offset);
1245 MmUnlockSectionSegment(Segment);
1246
1247 Status = MmCreateVirtualMapping(Process,
1248 Address,
1249 Attributes,
1250 &Page,
1251 1);
1252 if (!NT_SUCCESS(Status))
1253 {
1254 DPRINT1("Unable to create virtual mapping\n");
1255 KeBugCheck(MEMORY_MANAGEMENT);
1256 }
1257 MmInsertRmap(Page, Process, (PVOID)PAddress);
1258 if (Locked)
1259 {
1260 MmLockPage(Page);
1261 }
1262 PageOp->Status = STATUS_SUCCESS;
1263 MmspCompleteAndReleasePageOp(PageOp);
1264 DPRINT("Address 0x%.8X\n", Address);
1265 return(STATUS_SUCCESS);
1266 }
1267 }
1268
1269 NTSTATUS
1270 NTAPI
1271 MmAccessFaultSectionView(PMM_AVL_TABLE AddressSpace,
1272 MEMORY_AREA* MemoryArea,
1273 PVOID Address,
1274 BOOLEAN Locked)
1275 {
1276 PMM_SECTION_SEGMENT Segment;
1277 PROS_SECTION_OBJECT Section;
1278 PFN_TYPE OldPage;
1279 PFN_TYPE NewPage;
1280 NTSTATUS Status;
1281 PVOID PAddress;
1282 ULONG Offset;
1283 PMM_PAGEOP PageOp;
1284 PMM_REGION Region;
1285 ULONG Entry;
1286 PEPROCESS Process = MmGetAddressSpaceOwner(AddressSpace);
1287
1288 DPRINT("MmAccessFaultSectionView(%x, %x, %x, %x)\n", AddressSpace, MemoryArea, Address, Locked);
1289
1290 /*
1291 * Check if the page has been paged out or has already been set readwrite
1292 */
1293 if (!MmIsPagePresent(Process, Address) ||
1294 MmGetPageProtect(Process, Address) & PAGE_READWRITE)
1295 {
1296 DPRINT("Address 0x%.8X\n", Address);
1297 return(STATUS_SUCCESS);
1298 }
1299
1300 /*
1301 * Find the offset of the page
1302 */
1303 PAddress = MM_ROUND_DOWN(Address, PAGE_SIZE);
1304 Offset = (ULONG_PTR)PAddress - (ULONG_PTR)MemoryArea->StartingAddress
1305 + MemoryArea->Data.SectionData.ViewOffset;
1306
1307 Segment = MemoryArea->Data.SectionData.Segment;
1308 Section = MemoryArea->Data.SectionData.Section;
1309 Region = MmFindRegion(MemoryArea->StartingAddress,
1310 &MemoryArea->Data.SectionData.RegionListHead,
1311 Address, NULL);
1312 /*
1313 * Lock the segment
1314 */
1315 MmLockSectionSegment(Segment);
1316
1317 OldPage = MmGetPfnForProcess(NULL, Address);
1318 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
1319
1320 MmUnlockSectionSegment(Segment);
1321
1322 /*
1323 * Check if we are doing COW
1324 */
1325 if (!((Segment->WriteCopy || MemoryArea->Data.SectionData.WriteCopyView) &&
1326 (Region->Protect == PAGE_READWRITE ||
1327 Region->Protect == PAGE_EXECUTE_READWRITE)))
1328 {
1329 DPRINT("Address 0x%.8X\n", Address);
1330 return(STATUS_ACCESS_VIOLATION);
1331 }
1332
1333 if (IS_SWAP_FROM_SSE(Entry) ||
1334 PFN_FROM_SSE(Entry) != OldPage)
1335 {
1336 /* This is a private page. We must only change the page protection. */
1337 MmSetPageProtect(Process, PAddress, Region->Protect);
1338 return(STATUS_SUCCESS);
1339 }
1340
1341 /*
1342 * Get or create a pageop
1343 */
1344 PageOp = MmGetPageOp(MemoryArea, NULL, 0, Segment, Offset,
1345 MM_PAGEOP_ACCESSFAULT, FALSE);
1346 if (PageOp == NULL)
1347 {
1348 DPRINT1("MmGetPageOp failed\n");
1349 KeBugCheck(MEMORY_MANAGEMENT);
1350 }
1351
1352 /*
1353 * Wait for any other operations to complete
1354 */
1355 if (PageOp->Thread != PsGetCurrentThread())
1356 {
1357 MmUnlockAddressSpace(AddressSpace);
1358 Status = MmspWaitForPageOpCompletionEvent(PageOp);
1359 /*
1360 * Check for various strange conditions
1361 */
1362 if (Status == STATUS_TIMEOUT)
1363 {
1364 DPRINT1("Failed to wait for page op, status = %x\n", Status);
1365 KeBugCheck(MEMORY_MANAGEMENT);
1366 }
1367 if (PageOp->Status == STATUS_PENDING)
1368 {
1369 DPRINT1("Woke for page op before completion\n");
1370 KeBugCheck(MEMORY_MANAGEMENT);
1371 }
1372 /*
1373 * Restart the operation
1374 */
1375 MmLockAddressSpace(AddressSpace);
1376 MmspCompleteAndReleasePageOp(PageOp);
1377 DPRINT("Address 0x%.8X\n", Address);
1378 return(STATUS_MM_RESTART_OPERATION);
1379 }
1380
1381 /*
1382 * Release locks now we have the pageop
1383 */
1384 MmUnlockAddressSpace(AddressSpace);
1385
1386 /*
1387 * Allocate a page
1388 */
1389 Status = MmRequestPageMemoryConsumer(MC_USER, TRUE, &NewPage);
1390 if (!NT_SUCCESS(Status))
1391 {
1392 KeBugCheck(MEMORY_MANAGEMENT);
1393 }
1394
1395 /*
1396 * Copy the old page
1397 */
1398 MiCopyFromUserPage(NewPage, PAddress);
1399
1400 MmLockAddressSpace(AddressSpace);
1401 /*
1402 * Delete the old entry.
1403 */
1404 MmDeleteVirtualMapping(Process, Address, FALSE, NULL, NULL);
1405
1406 /*
1407 * Set the PTE to point to the new page
1408 */
1409 Status = MmCreateVirtualMapping(Process,
1410 Address,
1411 Region->Protect,
1412 &NewPage,
1413 1);
1414 if (!NT_SUCCESS(Status))
1415 {
1416 DPRINT("MmCreateVirtualMapping failed, not out of memory\n");
1417 KeBugCheck(MEMORY_MANAGEMENT);
1418 return(Status);
1419 }
1420 if (!NT_SUCCESS(Status))
1421 {
1422 DPRINT1("Unable to create virtual mapping\n");
1423 KeBugCheck(MEMORY_MANAGEMENT);
1424 }
1425 if (Locked)
1426 {
1427 MmLockPage(NewPage);
1428 MmUnlockPage(OldPage);
1429 }
1430
1431 /*
1432 * Unshare the old page.
1433 */
1434 MmDeleteRmap(OldPage, Process, PAddress);
1435 MmInsertRmap(NewPage, Process, PAddress);
1436 MmLockSectionSegment(Segment);
1437 MmUnsharePageEntrySectionSegment(Section, Segment, Offset, FALSE, FALSE);
1438 MmUnlockSectionSegment(Segment);
1439
1440 PageOp->Status = STATUS_SUCCESS;
1441 MmspCompleteAndReleasePageOp(PageOp);
1442 DPRINT("Address 0x%.8X\n", Address);
1443 return(STATUS_SUCCESS);
1444 }
1445
1446 VOID
1447 MmPageOutDeleteMapping(PVOID Context, PEPROCESS Process, PVOID Address)
1448 {
1449 MM_SECTION_PAGEOUT_CONTEXT* PageOutContext;
1450 BOOLEAN WasDirty;
1451 PFN_TYPE Page;
1452
1453 PageOutContext = (MM_SECTION_PAGEOUT_CONTEXT*)Context;
1454 if (Process)
1455 {
1456 MmLockAddressSpace(&Process->VadRoot);
1457 }
1458
1459 MmDeleteVirtualMapping(Process,
1460 Address,
1461 FALSE,
1462 &WasDirty,
1463 &Page);
1464 if (WasDirty)
1465 {
1466 PageOutContext->WasDirty = TRUE;
1467 }
1468 if (!PageOutContext->Private)
1469 {
1470 MmLockSectionSegment(PageOutContext->Segment);
1471 MmUnsharePageEntrySectionSegment((PROS_SECTION_OBJECT)PageOutContext->Section,
1472 PageOutContext->Segment,
1473 PageOutContext->Offset,
1474 PageOutContext->WasDirty,
1475 TRUE);
1476 MmUnlockSectionSegment(PageOutContext->Segment);
1477 }
1478 if (Process)
1479 {
1480 MmUnlockAddressSpace(&Process->VadRoot);
1481 }
1482
1483 if (PageOutContext->Private)
1484 {
1485 MmReleasePageMemoryConsumer(MC_USER, Page);
1486 }
1487
1488 DPRINT("PhysicalAddress %x, Address %x\n", Page << PAGE_SHIFT, Address);
1489 }
1490
1491 NTSTATUS
1492 NTAPI
1493 MmPageOutSectionView(PMM_AVL_TABLE AddressSpace,
1494 MEMORY_AREA* MemoryArea,
1495 PVOID Address,
1496 PMM_PAGEOP PageOp)
1497 {
1498 PFN_TYPE Page;
1499 MM_SECTION_PAGEOUT_CONTEXT Context;
1500 SWAPENTRY SwapEntry;
1501 ULONG Entry;
1502 ULONG FileOffset;
1503 NTSTATUS Status;
1504 PFILE_OBJECT FileObject;
1505 PBCB Bcb = NULL;
1506 BOOLEAN DirectMapped;
1507 BOOLEAN IsImageSection;
1508 PEPROCESS Process = MmGetAddressSpaceOwner(AddressSpace);
1509
1510 Address = (PVOID)PAGE_ROUND_DOWN(Address);
1511
1512 /*
1513 * Get the segment and section.
1514 */
1515 Context.Segment = MemoryArea->Data.SectionData.Segment;
1516 Context.Section = MemoryArea->Data.SectionData.Section;
1517
1518 Context.Offset = (ULONG_PTR)Address - (ULONG_PTR)MemoryArea->StartingAddress
1519 + MemoryArea->Data.SectionData.ViewOffset;
1520 FileOffset = Context.Offset + Context.Segment->FileOffset;
1521
1522 IsImageSection = Context.Section->AllocationAttributes & SEC_IMAGE ? TRUE : FALSE;
1523
1524 FileObject = Context.Section->FileObject;
1525 DirectMapped = FALSE;
1526 if (FileObject != NULL &&
1527 !(Context.Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
1528 {
1529 Bcb = FileObject->SectionObjectPointer->SharedCacheMap;
1530
1531 /*
1532 * If the file system is letting us go directly to the cache and the
1533 * memory area was mapped at an offset in the file which is page aligned
1534 * then note this is a direct mapped page.
1535 */
1536 if ((FileOffset % PAGE_SIZE) == 0 &&
1537 (Context.Offset + PAGE_SIZE <= Context.Segment->RawLength || !IsImageSection))
1538 {
1539 DirectMapped = TRUE;
1540 }
1541 }
1542
1543
1544 /*
1545 * This should never happen since mappings of physical memory are never
1546 * placed in the rmap lists.
1547 */
1548 if (Context.Section->AllocationAttributes & SEC_PHYSICALMEMORY)
1549 {
1550 DPRINT1("Trying to page out from physical memory section address 0x%X "
1551 "process %d\n", Address,
1552 Process ? Process->UniqueProcessId : 0);
1553 KeBugCheck(MEMORY_MANAGEMENT);
1554 }
1555
1556 /*
1557 * Get the section segment entry and the physical address.
1558 */
1559 Entry = MmGetPageEntrySectionSegment(Context.Segment, Context.Offset);
1560 if (!MmIsPagePresent(Process, Address))
1561 {
1562 DPRINT1("Trying to page out not-present page at (%d,0x%.8X).\n",
1563 Process ? Process->UniqueProcessId : 0, Address);
1564 KeBugCheck(MEMORY_MANAGEMENT);
1565 }
1566 Page = MmGetPfnForProcess(Process, Address);
1567 SwapEntry = MmGetSavedSwapEntryPage(Page);
1568
1569 /*
1570 * Prepare the context structure for the rmap delete call.
1571 */
1572 Context.WasDirty = FALSE;
1573 if (Context.Segment->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA ||
1574 IS_SWAP_FROM_SSE(Entry) ||
1575 PFN_FROM_SSE(Entry) != Page)
1576 {
1577 Context.Private = TRUE;
1578 }
1579 else
1580 {
1581 Context.Private = FALSE;
1582 }
1583
1584 /*
1585 * Take an additional reference to the page or the cache segment.
1586 */
1587 if (DirectMapped && !Context.Private)
1588 {
1589 if(!MiIsPageFromCache(MemoryArea, Context.Offset))
1590 {
1591 DPRINT1("Direct mapped non private page is not associated with the cache.\n");
1592 KeBugCheck(MEMORY_MANAGEMENT);
1593 }
1594 }
1595 else
1596 {
1597 MmReferencePage(Page);
1598 }
1599
1600 MmDeleteAllRmaps(Page, (PVOID)&Context, MmPageOutDeleteMapping);
1601
1602 /*
1603 * If this wasn't a private page then we should have reduced the entry to
1604 * zero by deleting all the rmaps.
1605 */
1606 if (!Context.Private && MmGetPageEntrySectionSegment(Context.Segment, Context.Offset) != 0)
1607 {
1608 if (!(Context.Segment->Flags & MM_PAGEFILE_SEGMENT) &&
1609 !(Context.Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
1610 {
1611 KeBugCheck(MEMORY_MANAGEMENT);
1612 }
1613 }
1614
1615 /*
1616 * If the page wasn't dirty then we can just free it as for a readonly page.
1617 * Since we unmapped all the mappings above we know it will not suddenly
1618 * become dirty.
1619 * If the page is from a pagefile section and has no swap entry,
1620 * we can't free the page at this point.
1621 */
1622 SwapEntry = MmGetSavedSwapEntryPage(Page);
1623 if (Context.Segment->Flags & MM_PAGEFILE_SEGMENT)
1624 {
1625 if (Context.Private)
1626 {
1627 DPRINT1("Found a %s private page (address %x) in a pagefile segment.\n",
1628 Context.WasDirty ? "dirty" : "clean", Address);
1629 KeBugCheck(MEMORY_MANAGEMENT);
1630 }
1631 if (!Context.WasDirty && SwapEntry != 0)
1632 {
1633 MmSetSavedSwapEntryPage(Page, 0);
1634 MmSetPageEntrySectionSegment(Context.Segment, Context.Offset, MAKE_SWAP_SSE(SwapEntry));
1635 MmReleasePageMemoryConsumer(MC_USER, Page);
1636 PageOp->Status = STATUS_SUCCESS;
1637 MmspCompleteAndReleasePageOp(PageOp);
1638 return(STATUS_SUCCESS);
1639 }
1640 }
1641 else if (Context.Segment->Characteristics & IMAGE_SCN_MEM_SHARED)
1642 {
1643 if (Context.Private)
1644 {
1645 DPRINT1("Found a %s private page (address %x) in a shared section segment.\n",
1646 Context.WasDirty ? "dirty" : "clean", Address);
1647 KeBugCheck(MEMORY_MANAGEMENT);
1648 }
1649 if (!Context.WasDirty || SwapEntry != 0)
1650 {
1651 MmSetSavedSwapEntryPage(Page, 0);
1652 if (SwapEntry != 0)
1653 {
1654 MmSetPageEntrySectionSegment(Context.Segment, Context.Offset, MAKE_SWAP_SSE(SwapEntry));
1655 }
1656 MmReleasePageMemoryConsumer(MC_USER, Page);
1657 PageOp->Status = STATUS_SUCCESS;
1658 MmspCompleteAndReleasePageOp(PageOp);
1659 return(STATUS_SUCCESS);
1660 }
1661 }
1662 else if (!Context.Private && DirectMapped)
1663 {
1664 if (SwapEntry != 0)
1665 {
1666 DPRINT1("Found a swapentry for a non private and direct mapped page (address %x)\n",
1667 Address);
1668 KeBugCheck(MEMORY_MANAGEMENT);
1669 }
1670 Status = CcRosUnmapCacheSegment(Bcb, FileOffset, FALSE);
1671 if (!NT_SUCCESS(Status))
1672 {
1673 DPRINT1("CCRosUnmapCacheSegment failed, status = %x\n", Status);
1674 KeBugCheck(MEMORY_MANAGEMENT);
1675 }
1676 PageOp->Status = STATUS_SUCCESS;
1677 MmspCompleteAndReleasePageOp(PageOp);
1678 return(STATUS_SUCCESS);
1679 }
1680 else if (!Context.WasDirty && !DirectMapped && !Context.Private)
1681 {
1682 if (SwapEntry != 0)
1683 {
1684 DPRINT1("Found a swap entry for a non dirty, non private and not direct mapped page (address %x)\n",
1685 Address);
1686 KeBugCheck(MEMORY_MANAGEMENT);
1687 }
1688 MmReleasePageMemoryConsumer(MC_USER, Page);
1689 PageOp->Status = STATUS_SUCCESS;
1690 MmspCompleteAndReleasePageOp(PageOp);
1691 return(STATUS_SUCCESS);
1692 }
1693 else if (!Context.WasDirty && Context.Private && SwapEntry != 0)
1694 {
1695 MmSetSavedSwapEntryPage(Page, 0);
1696 MmLockAddressSpace(AddressSpace);
1697 Status = MmCreatePageFileMapping(Process,
1698 Address,
1699 SwapEntry);
1700 MmUnlockAddressSpace(AddressSpace);
1701 if (!NT_SUCCESS(Status))
1702 {
1703 KeBugCheck(MEMORY_MANAGEMENT);
1704 }
1705 MmReleasePageMemoryConsumer(MC_USER, Page);
1706 PageOp->Status = STATUS_SUCCESS;
1707 MmspCompleteAndReleasePageOp(PageOp);
1708 return(STATUS_SUCCESS);
1709 }
1710
1711 /*
1712 * If necessary, allocate an entry in the paging file for this page
1713 */
1714 if (SwapEntry == 0)
1715 {
1716 SwapEntry = MmAllocSwapPage();
1717 if (SwapEntry == 0)
1718 {
1719 MmShowOutOfSpaceMessagePagingFile();
1720 MmLockAddressSpace(AddressSpace);
1721 /*
1722 * For private pages restore the old mappings.
1723 */
1724 if (Context.Private)
1725 {
1726 Status = MmCreateVirtualMapping(Process,
1727 Address,
1728 MemoryArea->Protect,
1729 &Page,
1730 1);
1731 MmSetDirtyPage(Process, Address);
1732 MmInsertRmap(Page,
1733 Process,
1734 Address);
1735 }
1736 else
1737 {
1738 /*
1739 * For non-private pages if the page wasn't direct mapped then
1740 * set it back into the section segment entry so we don't loose
1741 * our copy. Otherwise it will be handled by the cache manager.
1742 */
1743 Status = MmCreateVirtualMapping(Process,
1744 Address,
1745 MemoryArea->Protect,
1746 &Page,
1747 1);
1748 MmSetDirtyPage(Process, Address);
1749 MmInsertRmap(Page,
1750 Process,
1751 Address);
1752 Entry = MAKE_SSE(Page << PAGE_SHIFT, 1);
1753 MmSetPageEntrySectionSegment(Context.Segment, Context.Offset, Entry);
1754 }
1755 MmUnlockAddressSpace(AddressSpace);
1756 PageOp->Status = STATUS_UNSUCCESSFUL;
1757 MmspCompleteAndReleasePageOp(PageOp);
1758 return(STATUS_PAGEFILE_QUOTA);
1759 }
1760 }
1761
1762 /*
1763 * Write the page to the pagefile
1764 */
1765 Status = MmWriteToSwapPage(SwapEntry, Page);
1766 if (!NT_SUCCESS(Status))
1767 {
1768 DPRINT1("MM: Failed to write to swap page (Status was 0x%.8X)\n",
1769 Status);
1770 /*
1771 * As above: undo our actions.
1772 * FIXME: Also free the swap page.
1773 */
1774 MmLockAddressSpace(AddressSpace);
1775 if (Context.Private)
1776 {
1777 Status = MmCreateVirtualMapping(Process,
1778 Address,
1779 MemoryArea->Protect,
1780 &Page,
1781 1);
1782 MmSetDirtyPage(Process, Address);
1783 MmInsertRmap(Page,
1784 Process,
1785 Address);
1786 }
1787 else
1788 {
1789 Status = MmCreateVirtualMapping(Process,
1790 Address,
1791 MemoryArea->Protect,
1792 &Page,
1793 1);
1794 MmSetDirtyPage(Process, Address);
1795 MmInsertRmap(Page,
1796 Process,
1797 Address);
1798 Entry = MAKE_SSE(Page << PAGE_SHIFT, 1);
1799 MmSetPageEntrySectionSegment(Context.Segment, Context.Offset, Entry);
1800 }
1801 MmUnlockAddressSpace(AddressSpace);
1802 PageOp->Status = STATUS_UNSUCCESSFUL;
1803 MmspCompleteAndReleasePageOp(PageOp);
1804 return(STATUS_UNSUCCESSFUL);
1805 }
1806
1807 /*
1808 * Otherwise we have succeeded.
1809 */
1810 DPRINT("MM: Wrote section page 0x%.8X to swap!\n", Page << PAGE_SHIFT);
1811 MmSetSavedSwapEntryPage(Page, 0);
1812 if (Context.Segment->Flags & MM_PAGEFILE_SEGMENT ||
1813 Context.Segment->Characteristics & IMAGE_SCN_MEM_SHARED)
1814 {
1815 MmSetPageEntrySectionSegment(Context.Segment, Context.Offset, MAKE_SWAP_SSE(SwapEntry));
1816 }
1817 else
1818 {
1819 MmReleasePageMemoryConsumer(MC_USER, Page);
1820 }
1821
1822 if (Context.Private)
1823 {
1824 MmLockAddressSpace(AddressSpace);
1825 Status = MmCreatePageFileMapping(Process,
1826 Address,
1827 SwapEntry);
1828 MmUnlockAddressSpace(AddressSpace);
1829 if (!NT_SUCCESS(Status))
1830 {
1831 KeBugCheck(MEMORY_MANAGEMENT);
1832 }
1833 }
1834 else
1835 {
1836 Entry = MAKE_SWAP_SSE(SwapEntry);
1837 MmSetPageEntrySectionSegment(Context.Segment, Context.Offset, Entry);
1838 }
1839
1840 PageOp->Status = STATUS_SUCCESS;
1841 MmspCompleteAndReleasePageOp(PageOp);
1842 return(STATUS_SUCCESS);
1843 }
1844
1845 NTSTATUS
1846 NTAPI
1847 MmWritePageSectionView(PMM_AVL_TABLE AddressSpace,
1848 PMEMORY_AREA MemoryArea,
1849 PVOID Address,
1850 PMM_PAGEOP PageOp)
1851 {
1852 ULONG Offset;
1853 PROS_SECTION_OBJECT Section;
1854 PMM_SECTION_SEGMENT Segment;
1855 PFN_TYPE Page;
1856 SWAPENTRY SwapEntry;
1857 ULONG Entry;
1858 BOOLEAN Private;
1859 NTSTATUS Status;
1860 PFILE_OBJECT FileObject;
1861 PBCB Bcb = NULL;
1862 BOOLEAN DirectMapped;
1863 BOOLEAN IsImageSection;
1864 PEPROCESS Process = MmGetAddressSpaceOwner(AddressSpace);
1865
1866 Address = (PVOID)PAGE_ROUND_DOWN(Address);
1867
1868 Offset = (ULONG_PTR)Address - (ULONG_PTR)MemoryArea->StartingAddress
1869 + MemoryArea->Data.SectionData.ViewOffset;
1870
1871 /*
1872 * Get the segment and section.
1873 */
1874 Segment = MemoryArea->Data.SectionData.Segment;
1875 Section = MemoryArea->Data.SectionData.Section;
1876 IsImageSection = Section->AllocationAttributes & SEC_IMAGE ? TRUE : FALSE;
1877
1878 FileObject = Section->FileObject;
1879 DirectMapped = FALSE;
1880 if (FileObject != NULL &&
1881 !(Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
1882 {
1883 Bcb = FileObject->SectionObjectPointer->SharedCacheMap;
1884
1885 /*
1886 * If the file system is letting us go directly to the cache and the
1887 * memory area was mapped at an offset in the file which is page aligned
1888 * then note this is a direct mapped page.
1889 */
1890 if (((Offset + Segment->FileOffset) % PAGE_SIZE) == 0 &&
1891 (Offset + PAGE_SIZE <= Segment->RawLength || !IsImageSection))
1892 {
1893 DirectMapped = TRUE;
1894 }
1895 }
1896
1897 /*
1898 * This should never happen since mappings of physical memory are never
1899 * placed in the rmap lists.
1900 */
1901 if (Section->AllocationAttributes & SEC_PHYSICALMEMORY)
1902 {
1903 DPRINT1("Trying to write back page from physical memory mapped at %X "
1904 "process %d\n", Address,
1905 Process ? Process->UniqueProcessId : 0);
1906 KeBugCheck(MEMORY_MANAGEMENT);
1907 }
1908
1909 /*
1910 * Get the section segment entry and the physical address.
1911 */
1912 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
1913 if (!MmIsPagePresent(Process, Address))
1914 {
1915 DPRINT1("Trying to page out not-present page at (%d,0x%.8X).\n",
1916 Process ? Process->UniqueProcessId : 0, Address);
1917 KeBugCheck(MEMORY_MANAGEMENT);
1918 }
1919 Page = MmGetPfnForProcess(Process, Address);
1920 SwapEntry = MmGetSavedSwapEntryPage(Page);
1921
1922 /*
1923 * Check for a private (COWed) page.
1924 */
1925 if (Segment->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA ||
1926 IS_SWAP_FROM_SSE(Entry) ||
1927 PFN_FROM_SSE(Entry) != Page)
1928 {
1929 Private = TRUE;
1930 }
1931 else
1932 {
1933 Private = FALSE;
1934 }
1935
1936 /*
1937 * Speculatively set all mappings of the page to clean.
1938 */
1939 MmSetCleanAllRmaps(Page);
1940
1941 /*
1942 * If this page was direct mapped from the cache then the cache manager
1943 * will take care of writing it back to disk.
1944 */
1945 if (DirectMapped && !Private)
1946 {
1947 ASSERT(SwapEntry == 0);
1948 CcRosMarkDirtyCacheSegment(Bcb, Offset + Segment->FileOffset);
1949 PageOp->Status = STATUS_SUCCESS;
1950 MmspCompleteAndReleasePageOp(PageOp);
1951 return(STATUS_SUCCESS);
1952 }
1953
1954 /*
1955 * If necessary, allocate an entry in the paging file for this page
1956 */
1957 if (SwapEntry == 0)
1958 {
1959 SwapEntry = MmAllocSwapPage();
1960 if (SwapEntry == 0)
1961 {
1962 MmSetDirtyAllRmaps(Page);
1963 PageOp->Status = STATUS_UNSUCCESSFUL;
1964 MmspCompleteAndReleasePageOp(PageOp);
1965 return(STATUS_PAGEFILE_QUOTA);
1966 }
1967 MmSetSavedSwapEntryPage(Page, SwapEntry);
1968 }
1969
1970 /*
1971 * Write the page to the pagefile
1972 */
1973 Status = MmWriteToSwapPage(SwapEntry, Page);
1974 if (!NT_SUCCESS(Status))
1975 {
1976 DPRINT1("MM: Failed to write to swap page (Status was 0x%.8X)\n",
1977 Status);
1978 MmSetDirtyAllRmaps(Page);
1979 PageOp->Status = STATUS_UNSUCCESSFUL;
1980 MmspCompleteAndReleasePageOp(PageOp);
1981 return(STATUS_UNSUCCESSFUL);
1982 }
1983
1984 /*
1985 * Otherwise we have succeeded.
1986 */
1987 DPRINT("MM: Wrote section page 0x%.8X to swap!\n", Page << PAGE_SHIFT);
1988 PageOp->Status = STATUS_SUCCESS;
1989 MmspCompleteAndReleasePageOp(PageOp);
1990 return(STATUS_SUCCESS);
1991 }
1992
1993 static VOID
1994 MmAlterViewAttributes(PMM_AVL_TABLE AddressSpace,
1995 PVOID BaseAddress,
1996 ULONG RegionSize,
1997 ULONG OldType,
1998 ULONG OldProtect,
1999 ULONG NewType,
2000 ULONG NewProtect)
2001 {
2002 PMEMORY_AREA MemoryArea;
2003 PMM_SECTION_SEGMENT Segment;
2004 BOOLEAN DoCOW = FALSE;
2005 ULONG i;
2006 PEPROCESS Process = MmGetAddressSpaceOwner(AddressSpace);
2007
2008 MemoryArea = MmLocateMemoryAreaByAddress(AddressSpace, BaseAddress);
2009 Segment = MemoryArea->Data.SectionData.Segment;
2010
2011 if ((Segment->WriteCopy || MemoryArea->Data.SectionData.WriteCopyView) &&
2012 (NewProtect == PAGE_READWRITE || NewProtect == PAGE_EXECUTE_READWRITE))
2013 {
2014 DoCOW = TRUE;
2015 }
2016
2017 if (OldProtect != NewProtect)
2018 {
2019 for (i = 0; i < PAGE_ROUND_UP(RegionSize) / PAGE_SIZE; i++)
2020 {
2021 PVOID Address = (char*)BaseAddress + (i * PAGE_SIZE);
2022 ULONG Protect = NewProtect;
2023
2024 /*
2025 * If we doing COW for this segment then check if the page is
2026 * already private.
2027 */
2028 if (DoCOW && MmIsPagePresent(Process, Address))
2029 {
2030 ULONG Offset;
2031 ULONG Entry;
2032 PFN_TYPE Page;
2033
2034 Offset = (ULONG_PTR)Address - (ULONG_PTR)MemoryArea->StartingAddress
2035 + MemoryArea->Data.SectionData.ViewOffset;
2036 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
2037 Page = MmGetPfnForProcess(Process, Address);
2038
2039 Protect = PAGE_READONLY;
2040 if (Segment->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA ||
2041 IS_SWAP_FROM_SSE(Entry) ||
2042 PFN_FROM_SSE(Entry) != Page)
2043 {
2044 Protect = NewProtect;
2045 }
2046 }
2047
2048 if (MmIsPagePresent(Process, Address))
2049 {
2050 MmSetPageProtect(Process, Address,
2051 Protect);
2052 }
2053 }
2054 }
2055 }
2056
2057 NTSTATUS
2058 NTAPI
2059 MmProtectSectionView(PMM_AVL_TABLE AddressSpace,
2060 PMEMORY_AREA MemoryArea,
2061 PVOID BaseAddress,
2062 ULONG Length,
2063 ULONG Protect,
2064 PULONG OldProtect)
2065 {
2066 PMM_REGION Region;
2067 NTSTATUS Status;
2068 ULONG_PTR MaxLength;
2069
2070 MaxLength = (ULONG_PTR)MemoryArea->EndingAddress - (ULONG_PTR)BaseAddress;
2071 if (Length > MaxLength)
2072 Length = MaxLength;
2073
2074 Region = MmFindRegion(MemoryArea->StartingAddress,
2075 &MemoryArea->Data.SectionData.RegionListHead,
2076 BaseAddress, NULL);
2077 if ((MemoryArea->Flags & SEC_NO_CHANGE) &&
2078 Region->Protect != Protect)
2079 {
2080 return STATUS_INVALID_PAGE_PROTECTION;
2081 }
2082
2083 *OldProtect = Region->Protect;
2084 Status = MmAlterRegion(AddressSpace, MemoryArea->StartingAddress,
2085 &MemoryArea->Data.SectionData.RegionListHead,
2086 BaseAddress, Length, Region->Type, Protect,
2087 MmAlterViewAttributes);
2088
2089 return(Status);
2090 }
2091
2092 NTSTATUS NTAPI
2093 MmQuerySectionView(PMEMORY_AREA MemoryArea,
2094 PVOID Address,
2095 PMEMORY_BASIC_INFORMATION Info,
2096 PSIZE_T ResultLength)
2097 {
2098 PMM_REGION Region;
2099 PVOID RegionBaseAddress;
2100 PROS_SECTION_OBJECT Section;
2101 PMM_SECTION_SEGMENT Segment;
2102
2103 Region = MmFindRegion((PVOID)MemoryArea->StartingAddress,
2104 &MemoryArea->Data.SectionData.RegionListHead,
2105 Address, &RegionBaseAddress);
2106 if (Region == NULL)
2107 {
2108 return STATUS_UNSUCCESSFUL;
2109 }
2110
2111 Section = MemoryArea->Data.SectionData.Section;
2112 if (Section->AllocationAttributes & SEC_IMAGE)
2113 {
2114 Segment = MemoryArea->Data.SectionData.Segment;
2115 Info->AllocationBase = (PUCHAR)MemoryArea->StartingAddress - Segment->VirtualAddress;
2116 Info->Type = MEM_IMAGE;
2117 }
2118 else
2119 {
2120 Info->AllocationBase = MemoryArea->StartingAddress;
2121 Info->Type = MEM_MAPPED;
2122 }
2123 Info->BaseAddress = RegionBaseAddress;
2124 Info->AllocationProtect = MemoryArea->Protect;
2125 Info->RegionSize = Region->Length;
2126 Info->State = MEM_COMMIT;
2127 Info->Protect = Region->Protect;
2128
2129 *ResultLength = sizeof(MEMORY_BASIC_INFORMATION);
2130 return(STATUS_SUCCESS);
2131 }
2132
2133 VOID
2134 NTAPI
2135 MmpFreePageFileSegment(PMM_SECTION_SEGMENT Segment)
2136 {
2137 ULONG Length;
2138 ULONG Offset;
2139 ULONG Entry;
2140 ULONG SavedSwapEntry;
2141 PFN_TYPE Page;
2142
2143 Page = 0;
2144
2145 Length = PAGE_ROUND_UP(Segment->Length);
2146 for (Offset = 0; Offset < Length; Offset += PAGE_SIZE)
2147 {
2148 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
2149 if (Entry)
2150 {
2151 if (IS_SWAP_FROM_SSE(Entry))
2152 {
2153 MmFreeSwapPage(SWAPENTRY_FROM_SSE(Entry));
2154 }
2155 else
2156 {
2157 Page = PFN_FROM_SSE(Entry);
2158 SavedSwapEntry = MmGetSavedSwapEntryPage(Page);
2159 if (SavedSwapEntry != 0)
2160 {
2161 MmSetSavedSwapEntryPage(Page, 0);
2162 MmFreeSwapPage(SavedSwapEntry);
2163 }
2164 MmReleasePageMemoryConsumer(MC_USER, Page);
2165 }
2166 MmSetPageEntrySectionSegment(Segment, Offset, 0);
2167 }
2168 }
2169 }
2170
2171 VOID NTAPI
2172 MmpDeleteSection(PVOID ObjectBody)
2173 {
2174 PROS_SECTION_OBJECT Section = (PROS_SECTION_OBJECT)ObjectBody;
2175
2176 DPRINT("MmpDeleteSection(ObjectBody %x)\n", ObjectBody);
2177 if (Section->AllocationAttributes & SEC_IMAGE)
2178 {
2179 ULONG i;
2180 ULONG NrSegments;
2181 ULONG RefCount;
2182 PMM_SECTION_SEGMENT SectionSegments;
2183
2184 /*
2185 * NOTE: Section->ImageSection can be NULL for short time
2186 * during the section creating. If we fail for some reason
2187 * until the image section is properly initialized we shouldn't
2188 * process further here.
2189 */
2190 if (Section->ImageSection == NULL)
2191 return;
2192
2193 SectionSegments = Section->ImageSection->Segments;
2194 NrSegments = Section->ImageSection->NrSegments;
2195
2196 for (i = 0; i < NrSegments; i++)
2197 {
2198 if (SectionSegments[i].Characteristics & IMAGE_SCN_MEM_SHARED)
2199 {
2200 MmLockSectionSegment(&SectionSegments[i]);
2201 }
2202 RefCount = InterlockedDecrementUL(&SectionSegments[i].ReferenceCount);
2203 if (SectionSegments[i].Characteristics & IMAGE_SCN_MEM_SHARED)
2204 {
2205 if (RefCount == 0)
2206 {
2207 MmpFreePageFileSegment(&SectionSegments[i]);
2208 }
2209 MmUnlockSectionSegment(&SectionSegments[i]);
2210 }
2211 }
2212 }
2213 else
2214 {
2215 /*
2216 * NOTE: Section->Segment can be NULL for short time
2217 * during the section creating.
2218 */
2219 if (Section->Segment == NULL)
2220 return;
2221
2222 if (Section->Segment->Flags & MM_PAGEFILE_SEGMENT)
2223 {
2224 MmpFreePageFileSegment(Section->Segment);
2225 MmFreePageTablesSectionSegment(Section->Segment);
2226 ExFreePool(Section->Segment);
2227 Section->Segment = NULL;
2228 }
2229 else
2230 {
2231 (void)InterlockedDecrementUL(&Section->Segment->ReferenceCount);
2232 }
2233 }
2234 if (Section->FileObject != NULL)
2235 {
2236 CcRosDereferenceCache(Section->FileObject);
2237 ObDereferenceObject(Section->FileObject);
2238 Section->FileObject = NULL;
2239 }
2240 }
2241
2242 VOID NTAPI
2243 MmpCloseSection(IN PEPROCESS Process OPTIONAL,
2244 IN PVOID Object,
2245 IN ACCESS_MASK GrantedAccess,
2246 IN ULONG ProcessHandleCount,
2247 IN ULONG SystemHandleCount)
2248 {
2249 DPRINT("MmpCloseSection(OB %x, HC %d)\n",
2250 Object, ProcessHandleCount);
2251 }
2252
2253 NTSTATUS
2254 INIT_FUNCTION
2255 NTAPI
2256 MmCreatePhysicalMemorySection(VOID)
2257 {
2258 PROS_SECTION_OBJECT PhysSection;
2259 NTSTATUS Status;
2260 OBJECT_ATTRIBUTES Obj;
2261 UNICODE_STRING Name = RTL_CONSTANT_STRING(L"\\Device\\PhysicalMemory");
2262 LARGE_INTEGER SectionSize;
2263 HANDLE Handle;
2264
2265 /*
2266 * Create the section mapping physical memory
2267 */
2268 SectionSize.QuadPart = 0xFFFFFFFF;
2269 InitializeObjectAttributes(&Obj,
2270 &Name,
2271 OBJ_PERMANENT,
2272 NULL,
2273 NULL);
2274 Status = MmCreateSection((PVOID)&PhysSection,
2275 SECTION_ALL_ACCESS,
2276 &Obj,
2277 &SectionSize,
2278 PAGE_EXECUTE_READWRITE,
2279 0,
2280 NULL,
2281 NULL);
2282 if (!NT_SUCCESS(Status))
2283 {
2284 DPRINT1("Failed to create PhysicalMemory section\n");
2285 KeBugCheck(MEMORY_MANAGEMENT);
2286 }
2287 Status = ObInsertObject(PhysSection,
2288 NULL,
2289 SECTION_ALL_ACCESS,
2290 0,
2291 NULL,
2292 &Handle);
2293 if (!NT_SUCCESS(Status))
2294 {
2295 ObDereferenceObject(PhysSection);
2296 }
2297 ObCloseHandle(Handle, KernelMode);
2298 PhysSection->AllocationAttributes |= SEC_PHYSICALMEMORY;
2299 PhysSection->Segment->Flags &= ~MM_PAGEFILE_SEGMENT;
2300
2301 return(STATUS_SUCCESS);
2302 }
2303
2304 NTSTATUS
2305 INIT_FUNCTION
2306 NTAPI
2307 MmInitSectionImplementation(VOID)
2308 {
2309 OBJECT_TYPE_INITIALIZER ObjectTypeInitializer;
2310 UNICODE_STRING Name;
2311
2312 DPRINT("Creating Section Object Type\n");
2313
2314 /* Initialize the Section object type */
2315 RtlZeroMemory(&ObjectTypeInitializer, sizeof(ObjectTypeInitializer));
2316 RtlInitUnicodeString(&Name, L"Section");
2317 ObjectTypeInitializer.Length = sizeof(ObjectTypeInitializer);
2318 ObjectTypeInitializer.DefaultPagedPoolCharge = sizeof(ROS_SECTION_OBJECT);
2319 ObjectTypeInitializer.PoolType = PagedPool;
2320 ObjectTypeInitializer.UseDefaultObject = TRUE;
2321 ObjectTypeInitializer.GenericMapping = MmpSectionMapping;
2322 ObjectTypeInitializer.DeleteProcedure = MmpDeleteSection;
2323 ObjectTypeInitializer.CloseProcedure = MmpCloseSection;
2324 ObjectTypeInitializer.ValidAccessMask = SECTION_ALL_ACCESS;
2325 ObCreateObjectType(&Name, &ObjectTypeInitializer, NULL, &MmSectionObjectType);
2326
2327 return(STATUS_SUCCESS);
2328 }
2329
2330 NTSTATUS
2331 NTAPI
2332 MmCreatePageFileSection(PROS_SECTION_OBJECT *SectionObject,
2333 ACCESS_MASK DesiredAccess,
2334 POBJECT_ATTRIBUTES ObjectAttributes,
2335 PLARGE_INTEGER UMaximumSize,
2336 ULONG SectionPageProtection,
2337 ULONG AllocationAttributes)
2338 /*
2339 * Create a section which is backed by the pagefile
2340 */
2341 {
2342 LARGE_INTEGER MaximumSize;
2343 PROS_SECTION_OBJECT Section;
2344 PMM_SECTION_SEGMENT Segment;
2345 NTSTATUS Status;
2346
2347 if (UMaximumSize == NULL)
2348 {
2349 return(STATUS_UNSUCCESSFUL);
2350 }
2351 MaximumSize = *UMaximumSize;
2352
2353 /*
2354 * Create the section
2355 */
2356 Status = ObCreateObject(ExGetPreviousMode(),
2357 MmSectionObjectType,
2358 ObjectAttributes,
2359 ExGetPreviousMode(),
2360 NULL,
2361 sizeof(ROS_SECTION_OBJECT),
2362 0,
2363 0,
2364 (PVOID*)(PVOID)&Section);
2365 if (!NT_SUCCESS(Status))
2366 {
2367 return(Status);
2368 }
2369
2370 /*
2371 * Initialize it
2372 */
2373 Section->SectionPageProtection = SectionPageProtection;
2374 Section->AllocationAttributes = AllocationAttributes;
2375 Section->Segment = NULL;
2376 Section->FileObject = NULL;
2377 Section->MaximumSize = MaximumSize;
2378 Segment = ExAllocatePoolWithTag(NonPagedPool, sizeof(MM_SECTION_SEGMENT),
2379 TAG_MM_SECTION_SEGMENT);
2380 if (Segment == NULL)
2381 {
2382 ObDereferenceObject(Section);
2383 return(STATUS_NO_MEMORY);
2384 }
2385 Section->Segment = Segment;
2386 Segment->ReferenceCount = 1;
2387 ExInitializeFastMutex(&Segment->Lock);
2388 Segment->FileOffset = 0;
2389 Segment->Protection = SectionPageProtection;
2390 Segment->RawLength = MaximumSize.u.LowPart;
2391 Segment->Length = PAGE_ROUND_UP(MaximumSize.u.LowPart);
2392 Segment->Flags = MM_PAGEFILE_SEGMENT;
2393 Segment->WriteCopy = FALSE;
2394 RtlZeroMemory(&Segment->PageDirectory, sizeof(SECTION_PAGE_DIRECTORY));
2395 Segment->VirtualAddress = 0;
2396 Segment->Characteristics = 0;
2397 *SectionObject = Section;
2398 return(STATUS_SUCCESS);
2399 }
2400
2401
2402 NTSTATUS
2403 NTAPI
2404 MmCreateDataFileSection(PROS_SECTION_OBJECT *SectionObject,
2405 ACCESS_MASK DesiredAccess,
2406 POBJECT_ATTRIBUTES ObjectAttributes,
2407 PLARGE_INTEGER UMaximumSize,
2408 ULONG SectionPageProtection,
2409 ULONG AllocationAttributes,
2410 HANDLE FileHandle)
2411 /*
2412 * Create a section backed by a data file
2413 */
2414 {
2415 PROS_SECTION_OBJECT Section;
2416 NTSTATUS Status;
2417 LARGE_INTEGER MaximumSize;
2418 PFILE_OBJECT FileObject;
2419 PMM_SECTION_SEGMENT Segment;
2420 ULONG FileAccess;
2421 IO_STATUS_BLOCK Iosb;
2422 LARGE_INTEGER Offset;
2423 CHAR Buffer;
2424 FILE_STANDARD_INFORMATION FileInfo;
2425 ULONG Length;
2426
2427 /*
2428 * Create the section
2429 */
2430 Status = ObCreateObject(ExGetPreviousMode(),
2431 MmSectionObjectType,
2432 ObjectAttributes,
2433 ExGetPreviousMode(),
2434 NULL,
2435 sizeof(ROS_SECTION_OBJECT),
2436 0,
2437 0,
2438 (PVOID*)(PVOID)&Section);
2439 if (!NT_SUCCESS(Status))
2440 {
2441 return(Status);
2442 }
2443 /*
2444 * Initialize it
2445 */
2446 Section->SectionPageProtection = SectionPageProtection;
2447 Section->AllocationAttributes = AllocationAttributes;
2448 Section->Segment = NULL;
2449
2450 /*
2451 * Check file access required
2452 */
2453 if (SectionPageProtection & PAGE_READWRITE ||
2454 SectionPageProtection & PAGE_EXECUTE_READWRITE)
2455 {
2456 FileAccess = FILE_READ_DATA | FILE_WRITE_DATA;
2457 }
2458 else
2459 {
2460 FileAccess = FILE_READ_DATA;
2461 }
2462
2463 /*
2464 * Reference the file handle
2465 */
2466 Status = ObReferenceObjectByHandle(FileHandle,
2467 FileAccess,
2468 IoFileObjectType,
2469 ExGetPreviousMode(),
2470 (PVOID*)(PVOID)&FileObject,
2471 NULL);
2472 if (!NT_SUCCESS(Status))
2473 {
2474 ObDereferenceObject(Section);
2475 return(Status);
2476 }
2477
2478 /*
2479 * FIXME: This is propably not entirely correct. We can't look into
2480 * the standard FCB header because it might not be initialized yet
2481 * (as in case of the EXT2FS driver by Manoj Paul Joseph where the
2482 * standard file information is filled on first request).
2483 */
2484 Status = IoQueryFileInformation(FileObject,
2485 FileStandardInformation,
2486 sizeof(FILE_STANDARD_INFORMATION),
2487 &FileInfo,
2488 &Length);
2489 Iosb.Information = Length;
2490 if (!NT_SUCCESS(Status))
2491 {
2492 ObDereferenceObject(Section);
2493 ObDereferenceObject(FileObject);
2494 return Status;
2495 }
2496
2497 /*
2498 * FIXME: Revise this once a locking order for file size changes is
2499 * decided
2500 */
2501 if ((UMaximumSize != NULL) && (UMaximumSize->QuadPart != 0))
2502 {
2503 MaximumSize = *UMaximumSize;
2504 }
2505 else
2506 {
2507 MaximumSize = FileInfo.EndOfFile;
2508 /* Mapping zero-sized files isn't allowed. */
2509 if (MaximumSize.QuadPart == 0)
2510 {
2511 ObDereferenceObject(Section);
2512 ObDereferenceObject(FileObject);
2513 return STATUS_FILE_INVALID;
2514 }
2515 }
2516
2517 if (MaximumSize.QuadPart > FileInfo.EndOfFile.QuadPart)
2518 {
2519 Status = IoSetInformation(FileObject,
2520 FileAllocationInformation,
2521 sizeof(LARGE_INTEGER),
2522 &MaximumSize);
2523 if (!NT_SUCCESS(Status))
2524 {
2525 ObDereferenceObject(Section);
2526 ObDereferenceObject(FileObject);
2527 return(STATUS_SECTION_NOT_EXTENDED);
2528 }
2529 }
2530
2531 if (FileObject->SectionObjectPointer == NULL ||
2532 FileObject->SectionObjectPointer->SharedCacheMap == NULL)
2533 {
2534 /*
2535 * Read a bit so caching is initiated for the file object.
2536 * This is only needed because MiReadPage currently cannot
2537 * handle non-cached streams.
2538 */
2539 Offset.QuadPart = 0;
2540 Status = ZwReadFile(FileHandle,
2541 NULL,
2542 NULL,
2543 NULL,
2544 &Iosb,
2545 &Buffer,
2546 sizeof (Buffer),
2547 &Offset,
2548 0);
2549 if (!NT_SUCCESS(Status) && (Status != STATUS_END_OF_FILE))
2550 {
2551 ObDereferenceObject(Section);
2552 ObDereferenceObject(FileObject);
2553 return(Status);
2554 }
2555 if (FileObject->SectionObjectPointer == NULL ||
2556 FileObject->SectionObjectPointer->SharedCacheMap == NULL)
2557 {
2558 /* FIXME: handle this situation */
2559 ObDereferenceObject(Section);
2560 ObDereferenceObject(FileObject);
2561 return STATUS_INVALID_PARAMETER;
2562 }
2563 }
2564
2565 /*
2566 * Lock the file
2567 */
2568 Status = MmspWaitForFileLock(FileObject);
2569 if (Status != STATUS_SUCCESS)
2570 {
2571 ObDereferenceObject(Section);
2572 ObDereferenceObject(FileObject);
2573 return(Status);
2574 }
2575
2576 /*
2577 * If this file hasn't been mapped as a data file before then allocate a
2578 * section segment to describe the data file mapping
2579 */
2580 if (FileObject->SectionObjectPointer->DataSectionObject == NULL)
2581 {
2582 Segment = ExAllocatePoolWithTag(NonPagedPool, sizeof(MM_SECTION_SEGMENT),
2583 TAG_MM_SECTION_SEGMENT);
2584 if (Segment == NULL)
2585 {
2586 //KeSetEvent((PVOID)&FileObject->Lock, IO_NO_INCREMENT, FALSE);
2587 ObDereferenceObject(Section);
2588 ObDereferenceObject(FileObject);
2589 return(STATUS_NO_MEMORY);
2590 }
2591 Section->Segment = Segment;
2592 Segment->ReferenceCount = 1;
2593 ExInitializeFastMutex(&Segment->Lock);
2594 /*
2595 * Set the lock before assigning the segment to the file object
2596 */
2597 ExAcquireFastMutex(&Segment->Lock);
2598 FileObject->SectionObjectPointer->DataSectionObject = (PVOID)Segment;
2599
2600 Segment->FileOffset = 0;
2601 Segment->Protection = SectionPageProtection;
2602 Segment->Flags = MM_DATAFILE_SEGMENT;
2603 Segment->Characteristics = 0;
2604 Segment->WriteCopy = FALSE;
2605 if (AllocationAttributes & SEC_RESERVE)
2606 {
2607 Segment->Length = Segment->RawLength = 0;
2608 }
2609 else
2610 {
2611 Segment->RawLength = MaximumSize.u.LowPart;
2612 Segment->Length = PAGE_ROUND_UP(Segment->RawLength);
2613 }
2614 Segment->VirtualAddress = 0;
2615 RtlZeroMemory(&Segment->PageDirectory, sizeof(SECTION_PAGE_DIRECTORY));
2616 }
2617 else
2618 {
2619 /*
2620 * If the file is already mapped as a data file then we may need
2621 * to extend it
2622 */
2623 Segment =
2624 (PMM_SECTION_SEGMENT)FileObject->SectionObjectPointer->
2625 DataSectionObject;
2626 Section->Segment = Segment;
2627 (void)InterlockedIncrementUL(&Segment->ReferenceCount);
2628 MmLockSectionSegment(Segment);
2629
2630 if (MaximumSize.u.LowPart > Segment->RawLength &&
2631 !(AllocationAttributes & SEC_RESERVE))
2632 {
2633 Segment->RawLength = MaximumSize.u.LowPart;
2634 Segment->Length = PAGE_ROUND_UP(Segment->RawLength);
2635 }
2636 }
2637 MmUnlockSectionSegment(Segment);
2638 Section->FileObject = FileObject;
2639 Section->MaximumSize = MaximumSize;
2640 CcRosReferenceCache(FileObject);
2641 //KeSetEvent((PVOID)&FileObject->Lock, IO_NO_INCREMENT, FALSE);
2642 *SectionObject = Section;
2643 return(STATUS_SUCCESS);
2644 }
2645
2646 /*
2647 TODO: not that great (declaring loaders statically, having to declare all of
2648 them, having to keep them extern, etc.), will fix in the future
2649 */
2650 extern NTSTATUS NTAPI PeFmtCreateSection
2651 (
2652 IN CONST VOID * FileHeader,
2653 IN SIZE_T FileHeaderSize,
2654 IN PVOID File,
2655 OUT PMM_IMAGE_SECTION_OBJECT ImageSectionObject,
2656 OUT PULONG Flags,
2657 IN PEXEFMT_CB_READ_FILE ReadFileCb,
2658 IN PEXEFMT_CB_ALLOCATE_SEGMENTS AllocateSegmentsCb
2659 );
2660
2661 extern NTSTATUS NTAPI ElfFmtCreateSection
2662 (
2663 IN CONST VOID * FileHeader,
2664 IN SIZE_T FileHeaderSize,
2665 IN PVOID File,
2666 OUT PMM_IMAGE_SECTION_OBJECT ImageSectionObject,
2667 OUT PULONG Flags,
2668 IN PEXEFMT_CB_READ_FILE ReadFileCb,
2669 IN PEXEFMT_CB_ALLOCATE_SEGMENTS AllocateSegmentsCb
2670 );
2671
2672 /* TODO: this is a standard DDK/PSDK macro */
2673 #ifndef RTL_NUMBER_OF
2674 #define RTL_NUMBER_OF(ARR_) (sizeof(ARR_) / sizeof((ARR_)[0]))
2675 #endif
2676
2677 static PEXEFMT_LOADER ExeFmtpLoaders[] =
2678 {
2679 PeFmtCreateSection,
2680 #ifdef __ELF
2681 ElfFmtCreateSection
2682 #endif
2683 };
2684
2685 static
2686 PMM_SECTION_SEGMENT
2687 NTAPI
2688 ExeFmtpAllocateSegments(IN ULONG NrSegments)
2689 {
2690 SIZE_T SizeOfSegments;
2691 PMM_SECTION_SEGMENT Segments;
2692
2693 /* TODO: check for integer overflow */
2694 SizeOfSegments = sizeof(MM_SECTION_SEGMENT) * NrSegments;
2695
2696 Segments = ExAllocatePoolWithTag(NonPagedPool,
2697 SizeOfSegments,
2698 TAG_MM_SECTION_SEGMENT);
2699
2700 if(Segments)
2701 RtlZeroMemory(Segments, SizeOfSegments);
2702
2703 return Segments;
2704 }
2705
2706 static
2707 NTSTATUS
2708 NTAPI
2709 ExeFmtpReadFile(IN PVOID File,
2710 IN PLARGE_INTEGER Offset,
2711 IN ULONG Length,
2712 OUT PVOID * Data,
2713 OUT PVOID * AllocBase,
2714 OUT PULONG ReadSize)
2715 {
2716 NTSTATUS Status;
2717 LARGE_INTEGER FileOffset;
2718 ULONG AdjustOffset;
2719 ULONG OffsetAdjustment;
2720 ULONG BufferSize;
2721 ULONG UsedSize;
2722 PVOID Buffer;
2723
2724 ASSERT_IRQL_LESS(DISPATCH_LEVEL);
2725
2726 if(Length == 0)
2727 {
2728 KeBugCheck(MEMORY_MANAGEMENT);
2729 }
2730
2731 FileOffset = *Offset;
2732
2733 /* Negative/special offset: it cannot be used in this context */
2734 if(FileOffset.u.HighPart < 0)
2735 {
2736 KeBugCheck(MEMORY_MANAGEMENT);
2737 }
2738
2739 AdjustOffset = PAGE_ROUND_DOWN(FileOffset.u.LowPart);
2740 OffsetAdjustment = FileOffset.u.LowPart - AdjustOffset;
2741 FileOffset.u.LowPart = AdjustOffset;
2742
2743 BufferSize = Length + OffsetAdjustment;
2744 BufferSize = PAGE_ROUND_UP(BufferSize);
2745
2746 /*
2747 * It's ok to use paged pool, because this is a temporary buffer only used in
2748 * the loading of executables. The assumption is that MmCreateSection is
2749 * always called at low IRQLs and that these buffers don't survive a brief
2750 * initialization phase
2751 */
2752 Buffer = ExAllocatePoolWithTag(PagedPool,
2753 BufferSize,
2754 TAG('M', 'm', 'X', 'r'));
2755
2756 UsedSize = 0;
2757
2758 #if 0
2759 Status = MmspPageRead(File,
2760 Buffer,
2761 BufferSize,
2762 &FileOffset,
2763 &UsedSize);
2764 #else
2765 /*
2766 * FIXME: if we don't use ZwReadFile, caching is not enabled for the file and
2767 * nothing will work. But using ZwReadFile is wrong, and using its side effects
2768 * to initialize internal state is even worse. Our cache manager is in need of
2769 * professional help
2770 */
2771 {
2772 IO_STATUS_BLOCK Iosb;
2773
2774 Status = ZwReadFile(File,
2775 NULL,
2776 NULL,
2777 NULL,
2778 &Iosb,
2779 Buffer,
2780 BufferSize,
2781 &FileOffset,
2782 NULL);
2783
2784 if(NT_SUCCESS(Status))
2785 {
2786 UsedSize = Iosb.Information;
2787 }
2788 }
2789 #endif
2790
2791 if(NT_SUCCESS(Status) && UsedSize < OffsetAdjustment)
2792 {
2793 Status = STATUS_IN_PAGE_ERROR;
2794 ASSERT(!NT_SUCCESS(Status));
2795 }
2796
2797 if(NT_SUCCESS(Status))
2798 {
2799 *Data = (PVOID)((ULONG_PTR)Buffer + OffsetAdjustment);
2800 *AllocBase = Buffer;
2801 *ReadSize = UsedSize - OffsetAdjustment;
2802 }
2803 else
2804 {
2805 ExFreePoolWithTag(Buffer, TAG('M', 'm', 'X', 'r'));
2806 }
2807
2808 return Status;
2809 }
2810
2811 #ifdef NASSERT
2812 # define MmspAssertSegmentsSorted(OBJ_) ((void)0)
2813 # define MmspAssertSegmentsNoOverlap(OBJ_) ((void)0)
2814 # define MmspAssertSegmentsPageAligned(OBJ_) ((void)0)
2815 #else
2816 static
2817 VOID
2818 NTAPI
2819 MmspAssertSegmentsSorted(IN PMM_IMAGE_SECTION_OBJECT ImageSectionObject)
2820 {
2821 ULONG i;
2822
2823 for( i = 1; i < ImageSectionObject->NrSegments; ++ i )
2824 {
2825 ASSERT(ImageSectionObject->Segments[i].VirtualAddress >=
2826 ImageSectionObject->Segments[i - 1].VirtualAddress);
2827 }
2828 }
2829
2830 static
2831 VOID
2832 NTAPI
2833 MmspAssertSegmentsNoOverlap(IN PMM_IMAGE_SECTION_OBJECT ImageSectionObject)
2834 {
2835 ULONG i;
2836
2837 MmspAssertSegmentsSorted(ImageSectionObject);
2838
2839 for( i = 0; i < ImageSectionObject->NrSegments; ++ i )
2840 {
2841 ASSERT(ImageSectionObject->Segments[i].Length > 0);
2842
2843 if(i > 0)
2844 {
2845 ASSERT(ImageSectionObject->Segments[i].VirtualAddress >=
2846 (ImageSectionObject->Segments[i - 1].VirtualAddress +
2847 ImageSectionObject->Segments[i - 1].Length));
2848 }
2849 }
2850 }
2851
2852 static
2853 VOID
2854 NTAPI
2855 MmspAssertSegmentsPageAligned(IN PMM_IMAGE_SECTION_OBJECT ImageSectionObject)
2856 {
2857 ULONG i;
2858
2859 for( i = 0; i < ImageSectionObject->NrSegments; ++ i )
2860 {
2861 ASSERT((ImageSectionObject->Segments[i].VirtualAddress % PAGE_SIZE) == 0);
2862 ASSERT((ImageSectionObject->Segments[i].Length % PAGE_SIZE) == 0);
2863 }
2864 }
2865 #endif
2866
2867 static
2868 int
2869 __cdecl
2870 MmspCompareSegments(const void * x,
2871 const void * y)
2872 {
2873 const MM_SECTION_SEGMENT *Segment1 = (const MM_SECTION_SEGMENT *)x;
2874 const MM_SECTION_SEGMENT *Segment2 = (const MM_SECTION_SEGMENT *)y;
2875
2876 return
2877 (Segment1->VirtualAddress - Segment2->VirtualAddress) >>
2878 ((sizeof(ULONG_PTR) - sizeof(int)) * 8);
2879 }
2880
2881 /*
2882 * Ensures an image section's segments are sorted in memory
2883 */
2884 static
2885 VOID
2886 NTAPI
2887 MmspSortSegments(IN OUT PMM_IMAGE_SECTION_OBJECT ImageSectionObject,
2888 IN ULONG Flags)
2889 {
2890 if (Flags & EXEFMT_LOAD_ASSUME_SEGMENTS_SORTED)
2891 {
2892 MmspAssertSegmentsSorted(ImageSectionObject);
2893 }
2894 else
2895 {
2896 qsort(ImageSectionObject->Segments,
2897 ImageSectionObject->NrSegments,
2898 sizeof(ImageSectionObject->Segments[0]),
2899 MmspCompareSegments);
2900 }
2901 }
2902
2903
2904 /*
2905 * Ensures an image section's segments don't overlap in memory and don't have
2906 * gaps and don't have a null size. We let them map to overlapping file regions,
2907 * though - that's not necessarily an error
2908 */
2909 static
2910 BOOLEAN
2911 NTAPI
2912 MmspCheckSegmentBounds
2913 (
2914 IN OUT PMM_IMAGE_SECTION_OBJECT ImageSectionObject,
2915 IN ULONG Flags
2916 )
2917 {
2918 ULONG i;
2919
2920 if (Flags & EXEFMT_LOAD_ASSUME_SEGMENTS_NO_OVERLAP)
2921 {
2922 MmspAssertSegmentsNoOverlap(ImageSectionObject);
2923 return TRUE;
2924 }
2925
2926 ASSERT(ImageSectionObject->NrSegments >= 1);
2927
2928 for ( i = 0; i < ImageSectionObject->NrSegments; ++ i )
2929 {
2930 if(ImageSectionObject->Segments[i].Length == 0)
2931 {
2932 return FALSE;
2933 }
2934
2935 if(i > 0)
2936 {
2937 /*
2938 * TODO: relax the limitation on gaps. For example, gaps smaller than a
2939 * page could be OK (Windows seems to be OK with them), and larger gaps
2940 * could lead to image sections spanning several discontiguous regions
2941 * (NtMapViewOfSection could then refuse to map them, and they could
2942 * e.g. only be allowed as parameters to NtCreateProcess, like on UNIX)
2943 */
2944 if ((ImageSectionObject->Segments[i - 1].VirtualAddress +
2945 ImageSectionObject->Segments[i - 1].Length) !=
2946 ImageSectionObject->Segments[i].VirtualAddress)
2947 {
2948 return FALSE;
2949 }
2950 }
2951 }
2952
2953 return TRUE;
2954 }
2955
2956 /*
2957 * Merges and pads an image section's segments until they all are page-aligned
2958 * and have a size that is a multiple of the page size
2959 */
2960 static
2961 BOOLEAN
2962 NTAPI
2963 MmspPageAlignSegments
2964 (
2965 IN OUT PMM_IMAGE_SECTION_OBJECT ImageSectionObject,
2966 IN ULONG Flags
2967 )
2968 {
2969 ULONG i;
2970 ULONG LastSegment;
2971 BOOLEAN Initialized;
2972 PMM_SECTION_SEGMENT EffectiveSegment;
2973
2974 if (Flags & EXEFMT_LOAD_ASSUME_SEGMENTS_PAGE_ALIGNED)
2975 {
2976 MmspAssertSegmentsPageAligned(ImageSectionObject);
2977 return TRUE;
2978 }
2979
2980 Initialized = FALSE;
2981 LastSegment = 0;
2982 EffectiveSegment = &ImageSectionObject->Segments[LastSegment];
2983
2984 for ( i = 0; i < ImageSectionObject->NrSegments; ++ i )
2985 {
2986 /*
2987 * The first segment requires special handling
2988 */
2989 if (i == 0)
2990 {
2991 ULONG_PTR VirtualAddress;
2992 ULONG_PTR VirtualOffset;
2993
2994 VirtualAddress = EffectiveSegment->VirtualAddress;
2995
2996 /* Round down the virtual address to the nearest page */
2997 EffectiveSegment->VirtualAddress = PAGE_ROUND_DOWN(VirtualAddress);
2998
2999 /* Round up the virtual size to the nearest page */
3000 EffectiveSegment->Length = PAGE_ROUND_UP(VirtualAddress + EffectiveSegment->Length) -
3001 EffectiveSegment->VirtualAddress;
3002
3003 /* Adjust the raw address and size */
3004 VirtualOffset = VirtualAddress - EffectiveSegment->VirtualAddress;
3005
3006 if (EffectiveSegment->FileOffset < VirtualOffset)
3007 {
3008 return FALSE;
3009 }
3010
3011 /*
3012 * Garbage in, garbage out: unaligned base addresses make the file
3013 * offset point in curious and odd places, but that's what we were
3014 * asked for
3015 */
3016 EffectiveSegment->FileOffset -= VirtualOffset;
3017 EffectiveSegment->RawLength += VirtualOffset;
3018 }
3019 else
3020 {
3021 PMM_SECTION_SEGMENT Segment = &ImageSectionObject->Segments[i];
3022 ULONG_PTR EndOfEffectiveSegment;
3023
3024 EndOfEffectiveSegment = EffectiveSegment->VirtualAddress + EffectiveSegment->Length;
3025 ASSERT((EndOfEffectiveSegment % PAGE_SIZE) == 0);
3026
3027 /*
3028 * The current segment begins exactly where the current effective
3029 * segment ended, therefore beginning a new effective segment
3030 */
3031 if (EndOfEffectiveSegment == Segment->VirtualAddress)
3032 {
3033 LastSegment ++;
3034 ASSERT(LastSegment <= i);
3035 ASSERT(LastSegment < ImageSectionObject->NrSegments);
3036
3037 EffectiveSegment = &ImageSectionObject->Segments[LastSegment];
3038
3039 if (LastSegment != i)
3040 {
3041 /*
3042 * Copy the current segment. If necessary, the effective segment
3043 * will be expanded later
3044 */
3045 *EffectiveSegment = *Segment;
3046 }
3047
3048 /*
3049 * Page-align the virtual size. We know for sure the virtual address
3050 * already is
3051 */
3052 ASSERT((EffectiveSegment->VirtualAddress % PAGE_SIZE) == 0);
3053 EffectiveSegment->Length = PAGE_ROUND_UP(EffectiveSegment->Length);
3054 }
3055 /*
3056 * The current segment is still part of the current effective segment:
3057 * extend the effective segment to reflect this
3058 */
3059 else if (EndOfEffectiveSegment > Segment->VirtualAddress)
3060 {
3061 static const ULONG FlagsToProtection[16] =
3062 {
3063 PAGE_NOACCESS,
3064 PAGE_READONLY,
3065 PAGE_READWRITE,
3066 PAGE_READWRITE,
3067 PAGE_EXECUTE_READ,
3068 PAGE_EXECUTE_READ,
3069 PAGE_EXECUTE_READWRITE,
3070 PAGE_EXECUTE_READWRITE,
3071 PAGE_WRITECOPY,
3072 PAGE_WRITECOPY,
3073 PAGE_WRITECOPY,
3074 PAGE_WRITECOPY,
3075 PAGE_EXECUTE_WRITECOPY,
3076 PAGE_EXECUTE_WRITECOPY,
3077 PAGE_EXECUTE_WRITECOPY,
3078 PAGE_EXECUTE_WRITECOPY
3079 };
3080
3081 unsigned ProtectionFlags;
3082
3083 /*
3084 * Extend the file size
3085 */
3086
3087 /* Unaligned segments must be contiguous within the file */
3088 if (Segment->FileOffset != (EffectiveSegment->FileOffset +
3089 EffectiveSegment->RawLength))
3090 {
3091 return FALSE;
3092 }
3093
3094 EffectiveSegment->RawLength += Segment->RawLength;
3095
3096 /*
3097 * Extend the virtual size
3098 */
3099 ASSERT(PAGE_ROUND_UP(Segment->VirtualAddress + Segment->Length) >= EndOfEffectiveSegment);
3100
3101 EffectiveSegment->Length = PAGE_ROUND_UP(Segment->VirtualAddress + Segment->Length) -
3102 EffectiveSegment->VirtualAddress;
3103
3104 /*
3105 * Merge the protection
3106 */
3107 EffectiveSegment->Protection |= Segment->Protection;
3108
3109 /* Clean up redundance */
3110 ProtectionFlags = 0;
3111
3112 if(EffectiveSegment->Protection & PAGE_IS_READABLE)
3113 ProtectionFlags |= 1 << 0;
3114
3115 if(EffectiveSegment->Protection & PAGE_IS_WRITABLE)
3116 ProtectionFlags |= 1 << 1;
3117
3118 if(EffectiveSegment->Protection & PAGE_IS_EXECUTABLE)
3119 ProtectionFlags |= 1 << 2;
3120
3121 if(EffectiveSegment->Protection & PAGE_IS_WRITECOPY)
3122 ProtectionFlags |= 1 << 3;
3123
3124 ASSERT(ProtectionFlags < 16);
3125 EffectiveSegment->Protection = FlagsToProtection[ProtectionFlags];
3126
3127 /* If a segment was required to be shared and cannot, fail */
3128 if(!(Segment->Protection & PAGE_IS_WRITECOPY) &&
3129 EffectiveSegment->Protection & PAGE_IS_WRITECOPY)
3130 {
3131 return FALSE;
3132 }
3133 }
3134 /*
3135 * We assume no holes between segments at this point
3136 */
3137 else
3138 {
3139 KeBugCheck(MEMORY_MANAGEMENT);
3140 }
3141 }
3142 }
3143 ImageSectionObject->NrSegments = LastSegment + 1;
3144
3145 return TRUE;
3146 }
3147
3148 NTSTATUS
3149 ExeFmtpCreateImageSection(HANDLE FileHandle,
3150 PMM_IMAGE_SECTION_OBJECT ImageSectionObject)
3151 {
3152 LARGE_INTEGER Offset;
3153 PVOID FileHeader;
3154 PVOID FileHeaderBuffer;
3155 ULONG FileHeaderSize;
3156 ULONG Flags;
3157 ULONG OldNrSegments;
3158 NTSTATUS Status;
3159 ULONG i;
3160
3161 /*
3162 * Read the beginning of the file (2 pages). Should be enough to contain
3163 * all (or most) of the headers
3164 */
3165 Offset.QuadPart = 0;
3166
3167 /* FIXME: use FileObject instead of FileHandle */
3168 Status = ExeFmtpReadFile (FileHandle,
3169 &Offset,
3170 PAGE_SIZE * 2,
3171 &FileHeader,
3172 &FileHeaderBuffer,
3173 &FileHeaderSize);
3174
3175 if (!NT_SUCCESS(Status))
3176 return Status;
3177
3178 if (FileHeaderSize == 0)
3179 {
3180 ExFreePool(FileHeaderBuffer);
3181 return STATUS_UNSUCCESSFUL;
3182 }
3183
3184 /*
3185 * Look for a loader that can handle this executable
3186 */
3187 for (i = 0; i < RTL_NUMBER_OF(ExeFmtpLoaders); ++ i)
3188 {
3189 RtlZeroMemory(ImageSectionObject, sizeof(*ImageSectionObject));
3190 Flags = 0;
3191
3192 /* FIXME: use FileObject instead of FileHandle */
3193 Status = ExeFmtpLoaders[i](FileHeader,
3194 FileHeaderSize,
3195 FileHandle,
3196 ImageSectionObject,
3197 &Flags,
3198 ExeFmtpReadFile,
3199 ExeFmtpAllocateSegments);
3200
3201 if (!NT_SUCCESS(Status))
3202 {
3203 if (ImageSectionObject->Segments)
3204 {
3205 ExFreePool(ImageSectionObject->Segments);
3206 ImageSectionObject->Segments = NULL;
3207 }
3208 }
3209
3210 if (Status != STATUS_ROS_EXEFMT_UNKNOWN_FORMAT)
3211 break;
3212 }
3213
3214 ExFreePoolWithTag(FileHeaderBuffer, TAG('M', 'm', 'X', 'r'));
3215
3216 /*
3217 * No loader handled the format
3218 */
3219 if (Status == STATUS_ROS_EXEFMT_UNKNOWN_FORMAT)
3220 {
3221 Status = STATUS_INVALID_IMAGE_NOT_MZ;
3222 ASSERT(!NT_SUCCESS(Status));
3223 }
3224
3225 if (!NT_SUCCESS(Status))
3226 return Status;
3227
3228 ASSERT(ImageSectionObject->Segments != NULL);
3229
3230 /*
3231 * Some defaults
3232 */
3233 /* FIXME? are these values platform-dependent? */
3234 if(ImageSectionObject->StackReserve == 0)
3235 ImageSectionObject->StackReserve = 0x40000;
3236
3237 if(ImageSectionObject->StackCommit == 0)
3238 ImageSectionObject->StackCommit = 0x1000;
3239
3240 if(ImageSectionObject->ImageBase == 0)
3241 {
3242 if(ImageSectionObject->ImageCharacteristics & IMAGE_FILE_DLL)
3243 ImageSectionObject->ImageBase = 0x10000000;
3244 else
3245 ImageSectionObject->ImageBase = 0x00400000;
3246 }
3247
3248 /*
3249 * And now the fun part: fixing the segments
3250 */
3251
3252 /* Sort them by virtual address */
3253 MmspSortSegments(ImageSectionObject, Flags);
3254
3255 /* Ensure they don't overlap in memory */
3256 if (!MmspCheckSegmentBounds(ImageSectionObject, Flags))
3257 return STATUS_INVALID_IMAGE_FORMAT;
3258
3259 /* Ensure they are aligned */
3260 OldNrSegments = ImageSectionObject->NrSegments;
3261
3262 if (!MmspPageAlignSegments(ImageSectionObject, Flags))
3263 return STATUS_INVALID_IMAGE_FORMAT;
3264
3265 /* Trim them if the alignment phase merged some of them */
3266 if (ImageSectionObject->NrSegments < OldNrSegments)
3267 {
3268 PMM_SECTION_SEGMENT Segments;
3269 SIZE_T SizeOfSegments;
3270
3271 SizeOfSegments = sizeof(MM_SECTION_SEGMENT) * ImageSectionObject->NrSegments;
3272
3273 Segments = ExAllocatePoolWithTag(PagedPool,
3274 SizeOfSegments,
3275 TAG_MM_SECTION_SEGMENT);
3276
3277 if (Segments == NULL)
3278 return STATUS_INSUFFICIENT_RESOURCES;
3279
3280 RtlCopyMemory(Segments, ImageSectionObject->Segments, SizeOfSegments);
3281 ExFreePool(ImageSectionObject->Segments);
3282 ImageSectionObject->Segments = Segments;
3283 }
3284
3285 /* And finish their initialization */
3286 for ( i = 0; i < ImageSectionObject->NrSegments; ++ i )
3287 {
3288 ExInitializeFastMutex(&ImageSectionObject->Segments[i].Lock);
3289 ImageSectionObject->Segments[i].ReferenceCount = 1;
3290
3291 RtlZeroMemory(&ImageSectionObject->Segments[i].PageDirectory,
3292 sizeof(ImageSectionObject->Segments[i].PageDirectory));
3293 }
3294
3295 ASSERT(NT_SUCCESS(Status));
3296 return Status;
3297 }
3298
3299 NTSTATUS
3300 MmCreateImageSection(PROS_SECTION_OBJECT *SectionObject,
3301 ACCESS_MASK DesiredAccess,
3302 POBJECT_ATTRIBUTES ObjectAttributes,
3303 PLARGE_INTEGER UMaximumSize,
3304 ULONG SectionPageProtection,
3305 ULONG AllocationAttributes,
3306 HANDLE FileHandle)
3307 {
3308 PROS_SECTION_OBJECT Section;
3309 NTSTATUS Status;
3310 PFILE_OBJECT FileObject;
3311 PMM_SECTION_SEGMENT SectionSegments;
3312 PMM_IMAGE_SECTION_OBJECT ImageSectionObject;
3313 ULONG i;
3314 ULONG FileAccess = 0;
3315
3316 /*
3317 * Specifying a maximum size is meaningless for an image section
3318 */
3319 if (UMaximumSize != NULL)
3320 {
3321 return(STATUS_INVALID_PARAMETER_4);
3322 }
3323
3324 /*
3325 * Check file access required
3326 */
3327 if (SectionPageProtection & PAGE_READWRITE ||
3328 SectionPageProtection & PAGE_EXECUTE_READWRITE)
3329 {
3330 FileAccess = FILE_READ_DATA | FILE_WRITE_DATA;
3331 }
3332 else
3333 {
3334 FileAccess = FILE_READ_DATA;
3335 }
3336
3337 /*
3338 * Reference the file handle
3339 */
3340 Status = ObReferenceObjectByHandle(FileHandle,
3341 FileAccess,
3342 IoFileObjectType,
3343 ExGetPreviousMode(),
3344 (PVOID*)(PVOID)&FileObject,
3345 NULL);
3346
3347 if (!NT_SUCCESS(Status))
3348 {
3349 return Status;
3350 }
3351
3352 /*
3353 * Create the section
3354 */
3355 Status = ObCreateObject (ExGetPreviousMode(),
3356 MmSectionObjectType,
3357 ObjectAttributes,
3358 ExGetPreviousMode(),
3359 NULL,
3360 sizeof(ROS_SECTION_OBJECT),
3361 0,
3362 0,
3363 (PVOID*)(PVOID)&Section);
3364 if (!NT_SUCCESS(Status))
3365 {
3366 ObDereferenceObject(FileObject);
3367 return(Status);
3368 }
3369
3370 /*
3371 * Initialize it
3372 */
3373 Section->SectionPageProtection = SectionPageProtection;
3374 Section->AllocationAttributes = AllocationAttributes;
3375
3376 /*
3377 * Initialized caching for this file object if previously caching
3378 * was initialized for the same on disk file
3379 */
3380 Status = CcTryToInitializeFileCache(FileObject);
3381
3382 if (!NT_SUCCESS(Status) || FileObject->SectionObjectPointer->ImageSectionObject == NULL)
3383 {
3384 NTSTATUS StatusExeFmt;
3385
3386 ImageSectionObject = ExAllocatePoolWithTag(PagedPool, sizeof(MM_IMAGE_SECTION_OBJECT), TAG_MM_SECTION_SEGMENT);
3387 if (ImageSectionObject == NULL)
3388 {
3389 ObDereferenceObject(FileObject);
3390 ObDereferenceObject(Section);
3391 return(STATUS_NO_MEMORY);
3392 }
3393
3394 RtlZeroMemory(ImageSectionObject, sizeof(MM_IMAGE_SECTION_OBJECT));
3395
3396 StatusExeFmt = ExeFmtpCreateImageSection(FileHandle, ImageSectionObject);
3397
3398 if (!NT_SUCCESS(StatusExeFmt))
3399 {
3400 if(ImageSectionObject->Segments != NULL)
3401 ExFreePool(ImageSectionObject->Segments);
3402
3403 ExFreePool(ImageSectionObject);
3404 ObDereferenceObject(Section);
3405 ObDereferenceObject(FileObject);
3406 return(StatusExeFmt);
3407 }
3408
3409 Section->ImageSection = ImageSectionObject;
3410 ASSERT(ImageSectionObject->Segments);
3411
3412 /*
3413 * Lock the file
3414 */
3415 Status = MmspWaitForFileLock(FileObject);
3416 if (!NT_SUCCESS(Status))
3417 {
3418 ExFreePool(ImageSectionObject->Segments);
3419 ExFreePool(ImageSectionObject);
3420 ObDereferenceObject(Section);
3421 ObDereferenceObject(FileObject);
3422 return(Status);
3423 }
3424
3425 if (NULL != InterlockedCompareExchangePointer(&FileObject->SectionObjectPointer->ImageSectionObject,
3426 ImageSectionObject, NULL))
3427 {
3428 /*
3429 * An other thread has initialized the same image in the background
3430 */
3431 ExFreePool(ImageSectionObject->Segments);
3432 ExFreePool(ImageSectionObject);
3433 ImageSectionObject = FileObject->SectionObjectPointer->ImageSectionObject;
3434 Section->ImageSection = ImageSectionObject;
3435 SectionSegments = ImageSectionObject->Segments;
3436
3437 for (i = 0; i < ImageSectionObject->NrSegments; i++)
3438 {
3439 (void)InterlockedIncrementUL(&SectionSegments[i].ReferenceCount);
3440 }
3441 }
3442
3443 Status = StatusExeFmt;
3444 }
3445 else
3446 {
3447 /*
3448 * Lock the file
3449 */
3450 Status = MmspWaitForFileLock(FileObject);
3451 if (Status != STATUS_SUCCESS)
3452 {
3453 ObDereferenceObject(Section);
3454 ObDereferenceObject(FileObject);
3455 return(Status);
3456 }
3457
3458 ImageSectionObject = FileObject->SectionObjectPointer->ImageSectionObject;
3459 Section->ImageSection = ImageSectionObject;
3460 SectionSegments = ImageSectionObject->Segments;
3461
3462 /*
3463 * Otherwise just reference all the section segments
3464 */
3465 for (i = 0; i < ImageSectionObject->NrSegments; i++)
3466 {
3467 (void)InterlockedIncrementUL(&SectionSegments[i].ReferenceCount);
3468 }
3469
3470 Status = STATUS_SUCCESS;
3471 }
3472 Section->FileObject = FileObject;
3473 CcRosReferenceCache(FileObject);
3474 //KeSetEvent((PVOID)&FileObject->Lock, IO_NO_INCREMENT, FALSE);
3475 *SectionObject = Section;
3476 return(Status);
3477 }
3478
3479 /*
3480 * @implemented
3481 */
3482 NTSTATUS NTAPI
3483 NtCreateSection (OUT PHANDLE SectionHandle,
3484 IN ACCESS_MASK DesiredAccess,
3485 IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
3486 IN PLARGE_INTEGER MaximumSize OPTIONAL,
3487 IN ULONG SectionPageProtection OPTIONAL,
3488 IN ULONG AllocationAttributes,
3489 IN HANDLE FileHandle OPTIONAL)
3490 {
3491 LARGE_INTEGER SafeMaximumSize;
3492 PVOID SectionObject;
3493 KPROCESSOR_MODE PreviousMode;
3494 NTSTATUS Status = STATUS_SUCCESS;
3495
3496 PreviousMode = ExGetPreviousMode();
3497
3498 if(MaximumSize != NULL && PreviousMode != KernelMode)
3499 {
3500 _SEH2_TRY
3501 {
3502 /* make a copy on the stack */
3503 SafeMaximumSize = ProbeForReadLargeInteger(MaximumSize);
3504 MaximumSize = &SafeMaximumSize;
3505 }
3506 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
3507 {
3508 Status = _SEH2_GetExceptionCode();
3509 }
3510 _SEH2_END;
3511
3512 if(!NT_SUCCESS(Status))
3513 {
3514 return Status;
3515 }
3516 }
3517
3518 Status = MmCreateSection(&SectionObject,
3519 DesiredAccess,
3520 ObjectAttributes,
3521 MaximumSize,
3522 SectionPageProtection,
3523 AllocationAttributes,
3524 FileHandle,
3525 NULL);
3526 if (NT_SUCCESS(Status))
3527 {
3528 Status = ObInsertObject ((PVOID)SectionObject,
3529 NULL,
3530 DesiredAccess,
3531 0,
3532 NULL,
3533 SectionHandle);
3534 }
3535
3536 return Status;
3537 }
3538
3539
3540 /**********************************************************************
3541 * NAME
3542 * NtOpenSection
3543 *
3544 * DESCRIPTION
3545 *
3546 * ARGUMENTS
3547 * SectionHandle
3548 *
3549 * DesiredAccess
3550 *
3551 * ObjectAttributes
3552 *
3553 * RETURN VALUE
3554 *
3555 * REVISIONS
3556 */
3557 NTSTATUS NTAPI
3558 NtOpenSection(PHANDLE SectionHandle,
3559 ACCESS_MASK DesiredAccess,
3560 POBJECT_ATTRIBUTES ObjectAttributes)
3561 {
3562 HANDLE hSection;
3563 KPROCESSOR_MODE PreviousMode;
3564 NTSTATUS Status = STATUS_SUCCESS;
3565
3566 PreviousMode = ExGetPreviousMode();
3567
3568 if(PreviousMode != KernelMode)
3569 {
3570 _SEH2_TRY
3571 {
3572 ProbeForWriteHandle(SectionHandle);
3573 }
3574 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
3575 {
3576 Status = _SEH2_GetExceptionCode();
3577 }
3578 _SEH2_END;
3579
3580 if(!NT_SUCCESS(Status))
3581 {
3582 return Status;
3583 }
3584 }
3585
3586 Status = ObOpenObjectByName(ObjectAttributes,
3587 MmSectionObjectType,
3588 PreviousMode,
3589 NULL,
3590 DesiredAccess,
3591 NULL,
3592 &hSection);
3593
3594 if(NT_SUCCESS(Status))
3595 {
3596 _SEH2_TRY
3597 {
3598 *SectionHandle = hSection;
3599 }
3600 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
3601 {
3602 Status = _SEH2_GetExceptionCode();
3603 }
3604 _SEH2_END;
3605 }
3606
3607 return(Status);
3608 }
3609
3610 static NTSTATUS
3611 MmMapViewOfSegment(PMM_AVL_TABLE AddressSpace,
3612 PROS_SECTION_OBJECT Section,
3613 PMM_SECTION_SEGMENT Segment,
3614 PVOID* BaseAddress,
3615 SIZE_T ViewSize,
3616 ULONG Protect,
3617 ULONG ViewOffset,
3618 ULONG AllocationType)
3619 {
3620 PMEMORY_AREA MArea;
3621 NTSTATUS Status;
3622 PHYSICAL_ADDRESS BoundaryAddressMultiple;
3623
3624 BoundaryAddressMultiple.QuadPart = 0;
3625
3626 Status = MmCreateMemoryArea(AddressSpace,
3627 MEMORY_AREA_SECTION_VIEW,
3628 BaseAddress,
3629 ViewSize,
3630 Protect,
3631 &MArea,
3632 FALSE,
3633 AllocationType,
3634 BoundaryAddressMultiple);
3635 if (!NT_SUCCESS(Status))
3636 {
3637 DPRINT1("Mapping between 0x%.8X and 0x%.8X failed (%X).\n",
3638 (*BaseAddress), (char*)(*BaseAddress) + ViewSize, Status);
3639 return(Status);
3640 }
3641
3642 ObReferenceObject((PVOID)Section);
3643
3644 MArea->Data.SectionData.Segment = Segment;
3645 MArea->Data.SectionData.Section = Section;
3646 MArea->Data.SectionData.ViewOffset = ViewOffset;
3647 MArea->Data.SectionData.WriteCopyView = FALSE;
3648 MmInitializeRegion(&MArea->Data.SectionData.RegionListHead,
3649 ViewSize, 0, Protect);
3650
3651 return(STATUS_SUCCESS);
3652 }
3653
3654
3655 /**********************************************************************
3656 * NAME EXPORTED
3657 * NtMapViewOfSection
3658 *
3659 * DESCRIPTION
3660 * Maps a view of a section into the virtual address space of a
3661 * process.
3662 *
3663 * ARGUMENTS
3664 * SectionHandle
3665 * Handle of the section.
3666 *
3667 * ProcessHandle
3668 * Handle of the process.
3669 *
3670 * BaseAddress
3671 * Desired base address (or NULL) on entry;
3672 * Actual base address of the view on exit.
3673 *
3674 * ZeroBits
3675 * Number of high order address bits that must be zero.
3676 *
3677 * CommitSize
3678 * Size in bytes of the initially committed section of
3679 * the view.
3680 *
3681 * SectionOffset
3682 * Offset in bytes from the beginning of the section
3683 * to the beginning of the view.
3684 *
3685 * ViewSize
3686 * Desired length of map (or zero to map all) on entry
3687 * Actual length mapped on exit.
3688 *
3689 * InheritDisposition
3690 * Specified how the view is to be shared with
3691 * child processes.
3692 *
3693 * AllocateType
3694 * Type of allocation for the pages.
3695 *
3696 * Protect
3697 * Protection for the committed region of the view.
3698 *
3699 * RETURN VALUE
3700 * Status.
3701 *
3702 * @implemented
3703 */
3704 NTSTATUS NTAPI
3705 NtMapViewOfSection(IN HANDLE SectionHandle,
3706 IN HANDLE ProcessHandle,
3707 IN OUT PVOID* BaseAddress OPTIONAL,
3708 IN ULONG_PTR ZeroBits OPTIONAL,
3709 IN SIZE_T CommitSize,
3710 IN OUT PLARGE_INTEGER SectionOffset OPTIONAL,
3711 IN OUT PSIZE_T ViewSize,
3712 IN SECTION_INHERIT InheritDisposition,
3713 IN ULONG AllocationType OPTIONAL,
3714 IN ULONG Protect)
3715 {
3716 PVOID SafeBaseAddress;
3717 LARGE_INTEGER SafeSectionOffset;
3718 SIZE_T SafeViewSize;
3719 PROS_SECTION_OBJECT Section;
3720 PEPROCESS Process;
3721 KPROCESSOR_MODE PreviousMode;
3722 PMM_AVL_TABLE AddressSpace;
3723 NTSTATUS Status = STATUS_SUCCESS;
3724 ULONG tmpProtect;
3725
3726 /*
3727 * Check the protection
3728 */
3729 if (Protect & ~PAGE_FLAGS_VALID_FROM_USER_MODE)
3730 {
3731 return STATUS_INVALID_PARAMETER_10;
3732 }
3733
3734 tmpProtect = Protect & ~(PAGE_GUARD|PAGE_NOCACHE);
3735 if (tmpProtect != PAGE_NOACCESS &&
3736 tmpProtect != PAGE_READONLY &&
3737 tmpProtect != PAGE_READWRITE &&
3738 tmpProtect != PAGE_WRITECOPY &&
3739 tmpProtect != PAGE_EXECUTE &&
3740 tmpProtect != PAGE_EXECUTE_READ &&
3741 tmpProtect != PAGE_EXECUTE_READWRITE &&
3742 tmpProtect != PAGE_EXECUTE_WRITECOPY)
3743 {
3744 return STATUS_INVALID_PAGE_PROTECTION;
3745 }
3746
3747 PreviousMode = ExGetPreviousMode();
3748
3749 if(PreviousMode != KernelMode)
3750 {
3751 SafeBaseAddress = NULL;
3752 SafeSectionOffset.QuadPart = 0;
3753 SafeViewSize = 0;
3754
3755 _SEH2_TRY
3756 {
3757 if(BaseAddress != NULL)
3758 {
3759 ProbeForWritePointer(BaseAddress);
3760 SafeBaseAddress = *BaseAddress;
3761 }
3762 if(SectionOffset != NULL)
3763 {
3764 ProbeForWriteLargeInteger(SectionOffset);
3765 SafeSectionOffset = *SectionOffset;
3766 }
3767 ProbeForWriteSize_t(ViewSize);
3768 SafeViewSize = *ViewSize;
3769 }
3770 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
3771 {
3772 Status = _SEH2_GetExceptionCode();
3773 }
3774 _SEH2_END;
3775
3776 if(!NT_SUCCESS(Status))
3777 {
3778 return Status;
3779 }
3780 }
3781 else
3782 {
3783 SafeBaseAddress = (BaseAddress != NULL ? *BaseAddress : NULL);
3784 SafeSectionOffset.QuadPart = (SectionOffset != NULL ? SectionOffset->QuadPart : 0);
3785 SafeViewSize = (ViewSize != NULL ? *ViewSize : 0);
3786 }
3787
3788 SafeSectionOffset.LowPart = PAGE_ROUND_DOWN(SafeSectionOffset.LowPart);
3789
3790 Status = ObReferenceObjectByHandle(ProcessHandle,
3791 PROCESS_VM_OPERATION,
3792 PsProcessType,
3793 PreviousMode,
3794 (PVOID*)(PVOID)&Process,
3795 NULL);
3796 if (!NT_SUCCESS(Status))
3797 {
3798 return(Status);
3799 }
3800
3801 AddressSpace = &Process->VadRoot;
3802
3803 Status = ObReferenceObjectByHandle(SectionHandle,
3804 SECTION_MAP_READ,
3805 MmSectionObjectType,
3806 PreviousMode,
3807 (PVOID*)(PVOID)&Section,
3808 NULL);
3809 if (!(NT_SUCCESS(Status)))
3810 {
3811 DPRINT("ObReference failed rc=%x\n",Status);
3812 ObDereferenceObject(Process);
3813 return(Status);
3814 }
3815
3816 Status = MmMapViewOfSection(Section,
3817 (PEPROCESS)Process,
3818 (BaseAddress != NULL ? &SafeBaseAddress : NULL),
3819 ZeroBits,
3820 CommitSize,
3821 (SectionOffset != NULL ? &SafeSectionOffset : NULL),
3822 (ViewSize != NULL ? &SafeViewSize : NULL),
3823 InheritDisposition,
3824 AllocationType,
3825 Protect);
3826
3827 /* Check if this is an image for the current process */
3828 if ((Section->AllocationAttributes & SEC_IMAGE) &&
3829 (Process == PsGetCurrentProcess()) &&
3830 (Status != STATUS_IMAGE_NOT_AT_BASE))
3831 {
3832 /* Notify the debugger */
3833 DbgkMapViewOfSection(Section,
3834 SafeBaseAddress,
3835 SafeSectionOffset.LowPart,
3836 SafeViewSize);
3837 }
3838
3839 ObDereferenceObject(Section);
3840 ObDereferenceObject(Process);
3841
3842 if(NT_SUCCESS(Status))
3843 {
3844 /* copy parameters back to the caller */
3845 _SEH2_TRY
3846 {
3847 if(BaseAddress != NULL)
3848 {
3849 *BaseAddress = SafeBaseAddress;
3850 }
3851 if(SectionOffset != NULL)
3852 {
3853 *SectionOffset = SafeSectionOffset;
3854 }
3855 if(ViewSize != NULL)
3856 {
3857 *ViewSize = SafeViewSize;
3858 }
3859 }
3860 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
3861 {
3862 Status = _SEH2_GetExceptionCode();
3863 }
3864 _SEH2_END;
3865 }
3866
3867 return(Status);
3868 }
3869
3870 static VOID
3871 MmFreeSectionPage(PVOID Context, MEMORY_AREA* MemoryArea, PVOID Address,
3872 PFN_TYPE Page, SWAPENTRY SwapEntry, BOOLEAN Dirty)
3873 {
3874 ULONG Entry;
3875 PFILE_OBJECT FileObject;
3876 PBCB Bcb;
3877 ULONG Offset;
3878 SWAPENTRY SavedSwapEntry;
3879 PMM_PAGEOP PageOp;
3880 NTSTATUS Status;
3881 PROS_SECTION_OBJECT Section;
3882 PMM_SECTION_SEGMENT Segment;
3883 PMM_AVL_TABLE AddressSpace;
3884 PEPROCESS Process;
3885
3886 AddressSpace = (PMM_AVL_TABLE)Context;
3887 Process = MmGetAddressSpaceOwner(AddressSpace);
3888
3889 Address = (PVOID)PAGE_ROUND_DOWN(Address);
3890
3891 Offset = ((ULONG_PTR)Address - (ULONG_PTR)MemoryArea->StartingAddress) +
3892 MemoryArea->Data.SectionData.ViewOffset;
3893
3894 Section = MemoryArea->Data.SectionData.Section;
3895 Segment = MemoryArea->Data.SectionData.Segment;
3896
3897 PageOp = MmCheckForPageOp(MemoryArea, NULL, NULL, Segment, Offset);
3898
3899 while (PageOp)
3900 {
3901 MmUnlockSectionSegment(Segment);
3902 MmUnlockAddressSpace(AddressSpace);
3903
3904 Status = MmspWaitForPageOpCompletionEvent(PageOp);
3905 if (Status != STATUS_SUCCESS)
3906 {
3907 DPRINT1("Failed to wait for page op, status = %x\n", Status);
3908 KeBugCheck(MEMORY_MANAGEMENT);
3909 }
3910
3911 MmLockAddressSpace(AddressSpace);
3912 MmLockSectionSegment(Segment);
3913 MmspCompleteAndReleasePageOp(PageOp);
3914 PageOp = MmCheckForPageOp(MemoryArea, NULL, NULL, Segment, Offset);
3915 }
3916
3917 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
3918
3919 /*
3920 * For a dirty, datafile, non-private page mark it as dirty in the
3921 * cache manager.
3922 */
3923 if (Segment->Flags & MM_DATAFILE_SEGMENT)
3924 {
3925 if (Page == PFN_FROM_SSE(Entry) && Dirty)
3926 {
3927 FileObject = MemoryArea->Data.SectionData.Section->FileObject;
3928 Bcb = FileObject->SectionObjectPointer->SharedCacheMap;
3929 CcRosMarkDirtyCacheSegment(Bcb, Offset + Segment->FileOffset);
3930 ASSERT(SwapEntry == 0);
3931 }
3932 }
3933
3934 if (SwapEntry != 0)
3935 {
3936 /*
3937 * Sanity check
3938 */
3939 if (Segment->Flags & MM_PAGEFILE_SEGMENT)
3940 {
3941 DPRINT1("Found a swap entry for a page in a pagefile section.\n");
3942 KeBugCheck(MEMORY_MANAGEMENT);
3943 }
3944 MmFreeSwapPage(SwapEntry);
3945 }
3946 else if (Page != 0)
3947 {
3948 if (IS_SWAP_FROM_SSE(Entry) ||
3949 Page != PFN_FROM_SSE(Entry))
3950 {
3951 /*
3952 * Sanity check
3953 */
3954 if (Segment->Flags & MM_PAGEFILE_SEGMENT)
3955 {
3956 DPRINT1("Found a private page in a pagefile section.\n");
3957 KeBugCheck(MEMORY_MANAGEMENT);
3958 }
3959 /*
3960 * Just dereference private pages
3961 */
3962 SavedSwapEntry = MmGetSavedSwapEntryPage(Page);
3963 if (SavedSwapEntry != 0)
3964 {
3965 MmFreeSwapPage(SavedSwapEntry);
3966 MmSetSavedSwapEntryPage(Page, 0);
3967 }
3968 MmDeleteRmap(Page, Process, Address);
3969 MmReleasePageMemoryConsumer(MC_USER, Page);
3970 }
3971 else
3972 {
3973 MmDeleteRmap(Page, Process, Address);
3974 MmUnsharePageEntrySectionSegment(Section, Segment, Offset, Dirty, FALSE);
3975 }
3976 }
3977 }
3978
3979 static NTSTATUS
3980 MmUnmapViewOfSegment(PMM_AVL_TABLE AddressSpace,
3981 PVOID BaseAddress)
3982 {
3983 NTSTATUS Status;
3984 PMEMORY_AREA MemoryArea;
3985 PROS_SECTION_OBJECT Section;
3986 PMM_SECTION_SEGMENT Segment;
3987 PLIST_ENTRY CurrentEntry;
3988 PMM_REGION CurrentRegion;
3989 PLIST_ENTRY RegionListHead;
3990
3991 MemoryArea = MmLocateMemoryAreaByAddress(AddressSpace,
3992 BaseAddress);
3993 if (MemoryArea == NULL)
3994 {
3995 return(STATUS_UNSUCCESSFUL);
3996 }
3997
3998 MemoryArea->DeleteInProgress = TRUE;
3999 Section = MemoryArea->Data.SectionData.Section;
4000 Segment = MemoryArea->Data.SectionData.Segment;
4001
4002 MmLockSectionSegment(Segment);
4003
4004 RegionListHead = &MemoryArea->Data.SectionData.RegionListHead;
4005 while (!IsListEmpty(RegionListHead))
4006 {
4007 CurrentEntry = RemoveHeadList(RegionListHead);
4008 CurrentRegion = CONTAINING_RECORD(CurrentEntry, MM_REGION, RegionListEntry);
4009 ExFreePoolWithTag(CurrentRegion, TAG_MM_REGION);
4010 }
4011
4012 if (Section->AllocationAttributes & SEC_PHYSICALMEMORY)
4013 {
4014 Status = MmFreeMemoryArea(AddressSpace,
4015 MemoryArea,
4016 NULL,
4017 NULL);
4018 }
4019 else
4020 {
4021 Status = MmFreeMemoryArea(AddressSpace,
4022 MemoryArea,
4023 MmFreeSectionPage,
4024 AddressSpace);
4025 }
4026 MmUnlockSectionSegment(Segment);
4027 ObDereferenceObject(Section);
4028 return(STATUS_SUCCESS);
4029 }
4030
4031 /*
4032 * @implemented
4033 */
4034 NTSTATUS NTAPI
4035 MmUnmapViewOfSection(PEPROCESS Process,
4036 PVOID BaseAddress)
4037 {
4038 NTSTATUS Status;
4039 PMEMORY_AREA MemoryArea;
4040 PMM_AVL_TABLE AddressSpace;
4041 PROS_SECTION_OBJECT Section;
4042 PMM_PAGEOP PageOp;
4043 ULONG_PTR Offset;
4044 PVOID ImageBaseAddress = 0;
4045
4046 DPRINT("Opening memory area Process %x BaseAddress %x\n",
4047 Process, BaseAddress);
4048
4049 ASSERT(Process);
4050
4051 AddressSpace = &Process->VadRoot;
4052
4053 MmLockAddressSpace(AddressSpace);
4054 MemoryArea = MmLocateMemoryAreaByAddress(AddressSpace,
4055 BaseAddress);
4056 if (MemoryArea == NULL ||
4057 MemoryArea->Type != MEMORY_AREA_SECTION_VIEW ||
4058 MemoryArea->DeleteInProgress)
4059 {
4060 MmUnlockAddressSpace(AddressSpace);
4061 return STATUS_NOT_MAPPED_VIEW;
4062 }
4063
4064 MemoryArea->DeleteInProgress = TRUE;
4065
4066 while (MemoryArea->PageOpCount)
4067 {
4068 Offset = PAGE_ROUND_UP((ULONG_PTR)MemoryArea->EndingAddress - (ULONG_PTR)MemoryArea->StartingAddress);
4069
4070 while (Offset)
4071 {
4072 Offset -= PAGE_SIZE;
4073 PageOp = MmCheckForPageOp(MemoryArea, NULL, NULL,
4074 MemoryArea->Data.SectionData.Segment,
4075 Offset + MemoryArea->Data.SectionData.ViewOffset);
4076 if (PageOp)
4077 {
4078 MmUnlockAddressSpace(AddressSpace);
4079 Status = MmspWaitForPageOpCompletionEvent(PageOp);
4080 if (Status != STATUS_SUCCESS)
4081 {
4082 DPRINT1("Failed to wait for page op, status = %x\n", Status);
4083 KeBugCheck(MEMORY_MANAGEMENT);
4084 }
4085 MmLockAddressSpace(AddressSpace);
4086 MemoryArea = MmLocateMemoryAreaByAddress(AddressSpace,
4087 BaseAddress);
4088 if (MemoryArea == NULL ||
4089 MemoryArea->Type != MEMORY_AREA_SECTION_VIEW)
4090 {
4091 MmUnlockAddressSpace(AddressSpace);
4092 return STATUS_NOT_MAPPED_VIEW;
4093 }
4094 break;
4095 }
4096 }
4097 }
4098
4099 Section = MemoryArea->Data.SectionData.Section;
4100
4101 if (Section->AllocationAttributes & SEC_IMAGE)
4102 {
4103 ULONG i;
4104 ULONG NrSegments;
4105 PMM_IMAGE_SECTION_OBJECT ImageSectionObject;
4106 PMM_SECTION_SEGMENT SectionSegments;
4107 PMM_SECTION_SEGMENT Segment;
4108
4109 Segment = MemoryArea->Data.SectionData.Segment;
4110 ImageSectionObject = Section->ImageSection;
4111 SectionSegments = ImageSectionObject->Segments;
4112 NrSegments = ImageSectionObject->NrSegments;
4113
4114 /* Search for the current segment within the section segments
4115 * and calculate the image base address */
4116 for (i = 0; i < NrSegments; i++)
4117 {
4118 if (!(SectionSegments[i].Characteristics & IMAGE_SCN_TYPE_NOLOAD))
4119 {
4120 if (Segment == &SectionSegments[i])
4121 {
4122 ImageBaseAddress = (char*)BaseAddress - (ULONG_PTR)SectionSegments[i].VirtualAddress;
4123 break;
4124 }
4125 }
4126 }
4127 if (i >= NrSegments)
4128 {
4129 KeBugCheck(MEMORY_MANAGEMENT);
4130 }
4131
4132 for (i = 0; i < NrSegments; i++)
4133 {
4134 if (!(SectionSegments[i].Characteristics & IMAGE_SCN_TYPE_NOLOAD))
4135 {
4136 PVOID SBaseAddress = (PVOID)
4137 ((char*)ImageBaseAddress + (ULONG_PTR)SectionSegments[i].VirtualAddress);
4138
4139 Status = MmUnmapViewOfSegment(AddressSpace, SBaseAddress);
4140 }
4141 }
4142 }
4143 else
4144 {
4145 Status = MmUnmapViewOfSegment(AddressSpace, BaseAddress);
4146 }
4147
4148 /* Notify debugger */
4149 if (ImageBaseAddress) DbgkUnMapViewOfSection(ImageBaseAddress);
4150
4151 MmUnlockAddressSpace(AddressSpace);
4152 return(STATUS_SUCCESS);
4153 }
4154
4155 /**********************************************************************
4156 * NAME EXPORTED
4157 * NtUnmapViewOfSection
4158 *
4159 * DESCRIPTION
4160 *
4161 * ARGUMENTS
4162 * ProcessHandle
4163 *
4164 * BaseAddress
4165 *
4166 * RETURN VALUE
4167 * Status.
4168 *
4169 * REVISIONS
4170 */
4171 NTSTATUS NTAPI
4172 NtUnmapViewOfSection (HANDLE ProcessHandle,
4173 PVOID BaseAddress)
4174 {
4175 PEPROCESS Process;
4176 KPROCESSOR_MODE PreviousMode;
4177 NTSTATUS Status;
4178
4179 DPRINT("NtUnmapViewOfSection(ProcessHandle %x, BaseAddress %x)\n",
4180 ProcessHandle, BaseAddress);
4181
4182 PreviousMode = ExGetPreviousMode();
4183
4184 DPRINT("Referencing process\n");
4185 Status = ObReferenceObjectByHandle(ProcessHandle,
4186 PROCESS_VM_OPERATION,
4187 PsProcessType,
4188 PreviousMode,
4189 (PVOID*)(PVOID)&Process,
4190 NULL);
4191 if (!NT_SUCCESS(Status))
4192 {
4193 DPRINT("ObReferenceObjectByHandle failed (Status %x)\n", Status);
4194 return(Status);
4195 }
4196
4197 Status = MmUnmapViewOfSection(Process, BaseAddress);
4198
4199 ObDereferenceObject(Process);
4200
4201 return Status;
4202 }
4203
4204
4205 /**
4206 * Queries the information of a section object.
4207 *
4208 * @param SectionHandle
4209 * Handle to the section object. It must be opened with SECTION_QUERY
4210 * access.
4211 * @param SectionInformationClass
4212 * Index to a certain information structure. Can be either
4213 * SectionBasicInformation or SectionImageInformation. The latter
4214 * is valid only for sections that were created with the SEC_IMAGE
4215 * flag.
4216 * @param SectionInformation
4217 * Caller supplies storage for resulting information.
4218 * @param Length
4219 * Size of the supplied storage.
4220 * @param ResultLength
4221 * Data written.
4222 *
4223 * @return Status.
4224 *
4225 * @implemented
4226 */
4227 NTSTATUS NTAPI
4228 NtQuerySection(IN HANDLE SectionHandle,
4229 IN SECTION_INFORMATION_CLASS SectionInformationClass,
4230 OUT PVOID SectionInformation,
4231 IN SIZE_T SectionInformationLength,
4232 OUT PSIZE_T ResultLength OPTIONAL)
4233 {
4234 PROS_SECTION_OBJECT Section;
4235 KPROCESSOR_MODE PreviousMode;
4236 NTSTATUS Status = STATUS_SUCCESS;
4237
4238 PreviousMode = ExGetPreviousMode();
4239
4240 Status = DefaultQueryInfoBufferCheck(SectionInformationClass,
4241 ExSectionInfoClass,
4242 sizeof(ExSectionInfoClass) / sizeof(ExSectionInfoClass[0]),
4243 SectionInformation,
4244 SectionInformationLength,
4245 NULL,
4246 ResultLength,
4247 PreviousMode);
4248
4249 if(!NT_SUCCESS(Status))
4250 {
4251 DPRINT1("NtQuerySection() failed, Status: 0x%x\n", Status);
4252 return Status;
4253 }
4254
4255 Status = ObReferenceObjectByHandle(SectionHandle,
4256 SECTION_QUERY,
4257 MmSectionObjectType,
4258 PreviousMode,
4259 (PVOID*)(PVOID)&Section,
4260 NULL);
4261 if (NT_SUCCESS(Status))
4262 {
4263 switch (SectionInformationClass)
4264 {
4265 case SectionBasicInformation:
4266 {
4267 PSECTION_BASIC_INFORMATION Sbi = (PSECTION_BASIC_INFORMATION)SectionInformation;
4268
4269 _SEH2_TRY
4270 {
4271 Sbi->Attributes = Section->AllocationAttributes;
4272 if (Section->AllocationAttributes & SEC_IMAGE)
4273 {
4274 Sbi->BaseAddress = 0;
4275 Sbi->Size.QuadPart = 0;
4276 }
4277 else
4278 {
4279 Sbi->BaseAddress = (PVOID)Section->Segment->VirtualAddress;
4280 Sbi->Size.QuadPart = Section->Segment->Length;
4281 }
4282
4283 if (ResultLength != NULL)
4284 {
4285 *ResultLength = sizeof(SECTION_BASIC_INFORMATION);
4286 }
4287 Status = STATUS_SUCCESS;
4288 }
4289 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
4290 {
4291 Status = _SEH2_GetExceptionCode();
4292 }
4293 _SEH2_END;
4294
4295 break;
4296 }
4297
4298 case SectionImageInformation:
4299 {
4300 PSECTION_IMAGE_INFORMATION Sii = (PSECTION_IMAGE_INFORMATION)SectionInformation;
4301
4302 _SEH2_TRY
4303 {
4304 memset(Sii, 0, sizeof(SECTION_IMAGE_INFORMATION));
4305 if (Section->AllocationAttributes & SEC_IMAGE)
4306 {
4307 PMM_IMAGE_SECTION_OBJECT ImageSectionObject;
4308 ImageSectionObject = Section->ImageSection;
4309
4310 Sii->TransferAddress = (PVOID)ImageSectionObject->EntryPoint;
4311 Sii->MaximumStackSize = ImageSectionObject->StackReserve;
4312 Sii->CommittedStackSize = ImageSectionObject->StackCommit;
4313 Sii->SubSystemType = ImageSectionObject->Subsystem;
4314 Sii->SubSystemMinorVersion = ImageSectionObject->MinorSubsystemVersion;
4315 Sii->SubSystemMajorVersion = ImageSectionObject->MajorSubsystemVersion;
4316 Sii->ImageCharacteristics = ImageSectionObject->ImageCharacteristics;
4317 Sii->Machine = ImageSectionObject->Machine;
4318 Sii->ImageContainsCode = ImageSectionObject->Executable;
4319 }
4320
4321 if (ResultLength != NULL)
4322 {
4323 *ResultLength = sizeof(SECTION_IMAGE_INFORMATION);
4324 }
4325 Status = STATUS_SUCCESS;
4326 }
4327 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
4328 {
4329 Status = _SEH2_GetExceptionCode();
4330 }
4331 _SEH2_END;
4332
4333 break;
4334 }
4335 }
4336
4337 ObDereferenceObject(Section);
4338 }
4339
4340 return(Status);
4341 }
4342
4343
4344 /**
4345 * Extends size of file backed section.
4346 *
4347 * @param SectionHandle
4348 * Handle to the section object. It must be opened with
4349 * SECTION_EXTEND_SIZE access.
4350 * @param NewMaximumSize
4351 * New maximum size of the section in bytes.
4352 *
4353 * @return Status.
4354 *
4355 * @todo Move the actual code to internal function MmExtendSection.
4356 * @unimplemented
4357 */
4358 NTSTATUS NTAPI
4359 NtExtendSection(IN HANDLE SectionHandle,
4360 IN PLARGE_INTEGER NewMaximumSize)
4361 {
4362 LARGE_INTEGER SafeNewMaximumSize;
4363 PROS_SECTION_OBJECT Section;
4364 KPROCESSOR_MODE PreviousMode;
4365 NTSTATUS Status = STATUS_SUCCESS;
4366
4367 PreviousMode = ExGetPreviousMode();
4368
4369 if(PreviousMode != KernelMode)
4370 {
4371 _SEH2_TRY
4372 {
4373 /* make a copy on the stack */
4374 SafeNewMaximumSize = ProbeForReadLargeInteger(NewMaximumSize);
4375 NewMaximumSize = &SafeNewMaximumSize;
4376 }
4377 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
4378 {
4379 Status = _SEH2_GetExceptionCode();
4380 }
4381 _SEH2_END;
4382
4383 if(!NT_SUCCESS(Status))
4384 {
4385 return Status;
4386 }
4387 }
4388
4389 Status = ObReferenceObjectByHandle(SectionHandle,
4390 SECTION_EXTEND_SIZE,
4391 MmSectionObjectType,
4392 PreviousMode,
4393 (PVOID*)&Section,
4394 NULL);
4395 if (!NT_SUCCESS(Status))
4396 {
4397 return Status;
4398 }
4399
4400 if (!(Section->AllocationAttributes & SEC_FILE))
4401 {
4402 ObfDereferenceObject(Section);
4403 return STATUS_INVALID_PARAMETER;
4404 }
4405
4406 /*
4407 * - Acquire file extneding resource.
4408 * - Check if we're not resizing the section below it's actual size!
4409 * - Extend segments if needed.
4410 * - Set file information (FileAllocationInformation) to the new size.
4411 * - Release file extending resource.
4412 */
4413
4414 ObDereferenceObject(Section);
4415
4416 return STATUS_NOT_IMPLEMENTED;
4417 }
4418
4419
4420 /**********************************************************************
4421 * NAME INTERNAL
4422 * MmAllocateSection@4
4423 *
4424 * DESCRIPTION
4425 *
4426 * ARGUMENTS
4427 * Length
4428 *
4429 * RETURN VALUE
4430 *
4431 * NOTE
4432 * Code taken from ntoskrnl/mm/special.c.
4433 *
4434 * REVISIONS
4435 */
4436 PVOID NTAPI
4437 MmAllocateSection (IN ULONG Length, PVOID BaseAddress)
4438 {
4439 PVOID Result;
4440 MEMORY_AREA* marea;
4441 NTSTATUS Status;
4442 PMM_AVL_TABLE AddressSpace;
4443 PHYSICAL_ADDRESS BoundaryAddressMultiple;
4444
4445 DPRINT("MmAllocateSection(Length %x)\n",Length);
4446
4447 BoundaryAddressMultiple.QuadPart = 0;
4448
4449 AddressSpace = MmGetKernelAddressSpace();
4450 Result = BaseAddress;
4451 MmLockAddressSpace(AddressSpace);
4452 Status = MmCreateMemoryArea (AddressSpace,
4453 MEMORY_AREA_SYSTEM,
4454 &Result,
4455 Length,
4456 0,
4457 &marea,
4458 FALSE,
4459 0,
4460 BoundaryAddressMultiple);
4461 MmUnlockAddressSpace(AddressSpace);
4462
4463 if (!NT_SUCCESS(Status))
4464 {
4465 return (NULL);
4466 }
4467 DPRINT("Result %p\n",Result);
4468
4469 /* Create a virtual mapping for this memory area */
4470 MmMapMemoryArea(Result, Length, MC_NPPOOL, PAGE_READWRITE);
4471
4472 return ((PVOID)Result);
4473 }
4474
4475
4476 /**********************************************************************
4477 * NAME EXPORTED
4478 * MmMapViewOfSection
4479 *
4480 * DESCRIPTION
4481 * Maps a view of a section into the virtual address space of a
4482 * process.
4483 *
4484 * ARGUMENTS
4485 * Section
4486 * Pointer to the section object.
4487 *
4488 * ProcessHandle
4489 * Pointer to the process.
4490 *
4491 * BaseAddress
4492 * Desired base address (or NULL) on entry;
4493 * Actual base address of the view on exit.
4494 *
4495 * ZeroBits
4496 * Number of high order address bits that must be zero.
4497 *
4498 * CommitSize
4499 * Size in bytes of the initially committed section of
4500 * the view.
4501 *
4502 * SectionOffset
4503 * Offset in bytes from the beginning of the section
4504 * to the beginning of the view.
4505 *
4506 * ViewSize
4507 * Desired length of map (or zero to map all) on entry
4508 * Actual length mapped on exit.
4509 *
4510 * InheritDisposition
4511 * Specified how the view is to be shared with
4512 * child processes.
4513 *
4514 * AllocationType
4515 * Type of allocation for the pages.
4516 *
4517 * Protect
4518 * Protection for the committed region of the view.
4519 *
4520 * RETURN VALUE
4521 * Status.
4522 *
4523 * @implemented
4524 */
4525 NTSTATUS NTAPI
4526 MmMapViewOfSection(IN PVOID SectionObject,
4527 IN PEPROCESS Process,
4528 IN OUT PVOID *BaseAddress,
4529 IN ULONG_PTR ZeroBits,
4530 IN SIZE_T CommitSize,
4531 IN OUT PLARGE_INTEGER SectionOffset OPTIONAL,
4532 IN OUT PSIZE_T ViewSize,
4533 IN SECTION_INHERIT InheritDisposition,
4534 IN ULONG AllocationType,
4535 IN ULONG Protect)
4536 {
4537 PROS_SECTION_OBJECT Section;
4538 PMM_AVL_TABLE AddressSpace;
4539 ULONG ViewOffset;
4540 NTSTATUS Status = STATUS_SUCCESS;
4541
4542 ASSERT(Process);
4543
4544 if (Protect != PAGE_READONLY &&
4545 Protect != PAGE_READWRITE &&
4546 Protect != PAGE_WRITECOPY &&
4547 Protect != PAGE_EXECUTE &&
4548 Protect != PAGE_EXECUTE_READ &&
4549 Protect != PAGE_EXECUTE_READWRITE &&
4550 Protect != PAGE_EXECUTE_WRITECOPY)
4551 {
4552 return STATUS_INVALID_PAGE_PROTECTION;
4553 }
4554
4555
4556 Section = (PROS_SECTION_OBJECT)SectionObject;
4557 AddressSpace = &Process->VadRoot;
4558
4559 AllocationType |= (Section->AllocationAttributes & SEC_NO_CHANGE);
4560
4561 MmLockAddressSpace(AddressSpace);
4562
4563 if (Section->AllocationAttributes & SEC_IMAGE)
4564 {
4565 ULONG i;
4566 ULONG NrSegments;
4567 ULONG_PTR ImageBase;
4568 ULONG ImageSize;
4569 PMM_IMAGE_SECTION_OBJECT ImageSectionObject;
4570 PMM_SECTION_SEGMENT SectionSegments;
4571
4572 ImageSectionObject = Section->ImageSection;
4573 SectionSegments = ImageSectionObject->Segments;
4574 NrSegments = ImageSectionObject->NrSegments;
4575
4576
4577 ImageBase = (ULONG_PTR)*BaseAddress;
4578 if (ImageBase == 0)
4579 {
4580 ImageBase = ImageSectionObject->ImageBase;
4581 }
4582
4583 ImageSize = 0;
4584 for (i = 0; i < NrSegments; i++)
4585 {
4586 if (!(SectionSegments[i].Characteristics & IMAGE_SCN_TYPE_NOLOAD))
4587 {
4588 ULONG_PTR MaxExtent;
4589 MaxExtent = (ULONG_PTR)SectionSegments[i].VirtualAddress +
4590 SectionSegments[i].Length;
4591 ImageSize = max(ImageSize, MaxExtent);
4592 }
4593 }
4594
4595 ImageSectionObject->ImageSize = ImageSize;
4596
4597 /* Check there is enough space to map the section at that point. */
4598 if (MmLocateMemoryAreaByRegion(AddressSpace, (PVOID)ImageBase,
4599 PAGE_ROUND_UP(ImageSize)) != NULL)
4600 {
4601 /* Fail if the user requested a fixed base address. */
4602 if ((*BaseAddress) != NULL)
4603 {
4604 MmUnlockAddressSpace(AddressSpace);
4605 return(STATUS_UNSUCCESSFUL);
4606 }
4607 /* Otherwise find a gap to map the image. */
4608 ImageBase = (ULONG_PTR)MmFindGap(AddressSpace, PAGE_ROUND_UP(ImageSize), PAGE_SIZE, FALSE);
4609 if (ImageBase == 0)
4610 {
4611 MmUnlockAddressSpace(AddressSpace);
4612 return(STATUS_UNSUCCESSFUL);
4613 }
4614 }
4615
4616 for (i = 0; i < NrSegments; i++)
4617 {
4618 if (!(SectionSegments[i].Characteristics & IMAGE_SCN_TYPE_NOLOAD))
4619 {
4620 PVOID SBaseAddress = (PVOID)
4621 ((char*)ImageBase + (ULONG_PTR)SectionSegments[i].VirtualAddress);
4622 MmLockSectionSegment(&SectionSegments[i]);
4623 Status = MmMapViewOfSegment(AddressSpace,
4624 Section,
4625 &SectionSegments[i],
4626 &SBaseAddress,
4627 SectionSegments[i].Length,
4628 SectionSegments[i].Protection,
4629 0,
4630 0);
4631 MmUnlockSectionSegment(&SectionSegments[i]);
4632 if (!NT_SUCCESS(Status))
4633 {
4634 MmUnlockAddressSpace(AddressSpace);
4635 return(Status);
4636 }
4637 }
4638 }
4639
4640 *BaseAddress = (PVOID)ImageBase;
4641 }
4642 else
4643 {
4644 /* check for write access */
4645 if ((Protect & (PAGE_READWRITE|PAGE_EXECUTE_READWRITE)) &&
4646 !(Section->SectionPageProtection & (PAGE_READWRITE|PAGE_EXECUTE_READWRITE)))
4647 {
4648 MmUnlockAddressSpace(AddressSpace);
4649 return STATUS_SECTION_PROTECTION;
4650 }
4651 /* check for read access */
4652 if ((Protect & (PAGE_READONLY|PAGE_WRITECOPY|PAGE_EXECUTE_READ|PAGE_EXECUTE_WRITECOPY)) &&
4653 !(Section->SectionPageProtection & (PAGE_READONLY|PAGE_READWRITE|PAGE_WRITECOPY|PAGE_EXECUTE_READ|PAGE_EXECUTE_READWRITE|PAGE_EXECUTE_WRITECOPY)))
4654 {
4655 MmUnlockAddressSpace(AddressSpace);
4656 return STATUS_SECTION_PROTECTION;
4657 }
4658 /* check for execute access */
4659 if ((Protect & (PAGE_EXECUTE|PAGE_EXECUTE_READ|PAGE_EXECUTE_READWRITE|PAGE_EXECUTE_WRITECOPY)) &&
4660 !(Section->SectionPageProtection & (PAGE_EXECUTE|PAGE_EXECUTE_READ|PAGE_EXECUTE_READWRITE|PAGE_EXECUTE_WRITECOPY)))
4661 {
4662 MmUnlockAddressSpace(AddressSpace);
4663 return STATUS_SECTION_PROTECTION;
4664 }
4665
4666 if (ViewSize == NULL)
4667 {
4668 /* Following this pointer would lead to us to the dark side */
4669 /* What to do? Bugcheck? Return status? Do the mambo? */
4670 KeBugCheck(MEMORY_MANAGEMENT);
4671 }
4672
4673 if (SectionOffset == NULL)
4674 {
4675 ViewOffset = 0;
4676 }
4677 else
4678 {
4679 ViewOffset = SectionOffset->u.LowPart;
4680 }
4681
4682 if ((ViewOffset % PAGE_SIZE) != 0)
4683 {
4684 MmUnlockAddressSpace(AddressSpace);
4685 return(STATUS_MAPPED_ALIGNMENT);
4686 }
4687
4688 if ((*ViewSize) == 0)
4689 {
4690 (*ViewSize) = Section->MaximumSize.u.LowPart - ViewOffset;
4691 }
4692 else if (((*ViewSize)+ViewOffset) > Section->MaximumSize.u.LowPart)
4693 {
4694 (*ViewSize) = Section->MaximumSize.u.LowPart - ViewOffset;
4695 }
4696
4697 MmLockSectionSegment(Section->Segment);
4698 Status = MmMapViewOfSegment(AddressSpace,
4699 Section,
4700 Section->Segment,
4701 BaseAddress,
4702 *ViewSize,
4703 Protect,
4704 ViewOffset,
4705 AllocationType & (MEM_TOP_DOWN|SEC_NO_CHANGE));
4706 MmUnlockSectionSegment(Section->Segment);
4707 if (!NT_SUCCESS(Status))
4708 {
4709 MmUnlockAddressSpace(AddressSpace);
4710 return(Status);
4711 }
4712 }
4713
4714 MmUnlockAddressSpace(AddressSpace);
4715
4716 return(STATUS_SUCCESS);
4717 }
4718
4719 /*
4720 * @unimplemented
4721 */
4722 BOOLEAN NTAPI
4723 MmCanFileBeTruncated (IN PSECTION_OBJECT_POINTERS SectionObjectPointer,
4724 IN PLARGE_INTEGER NewFileSize)
4725 {
4726 UNIMPLEMENTED;
4727 return (FALSE);
4728 }
4729
4730
4731 /*
4732 * @unimplemented
4733 */
4734 BOOLEAN NTAPI
4735 MmDisableModifiedWriteOfSection (ULONG Unknown0)
4736 {
4737 UNIMPLEMENTED;
4738 return (FALSE);
4739 }
4740
4741 /*
4742 * @implemented
4743 */
4744 BOOLEAN NTAPI
4745 MmFlushImageSection (IN PSECTION_OBJECT_POINTERS SectionObjectPointer,
4746 IN MMFLUSH_TYPE FlushType)
4747 {
4748 switch(FlushType)
4749 {
4750 case MmFlushForDelete:
4751 if (SectionObjectPointer->ImageSectionObject ||
4752 SectionObjectPointer->DataSectionObject)
4753 {
4754 return FALSE;
4755 }
4756 CcRosSetRemoveOnClose(SectionObjectPointer);
4757 return TRUE;
4758 case MmFlushForWrite:
4759 break;
4760 }
4761 return FALSE;
4762 }
4763
4764 /*
4765 * @unimplemented
4766 */
4767 BOOLEAN NTAPI
4768 MmForceSectionClosed (
4769 IN PSECTION_OBJECT_POINTERS SectionObjectPointer,
4770 IN BOOLEAN DelayClose)
4771 {
4772 UNIMPLEMENTED;
4773 return (FALSE);
4774 }
4775
4776
4777 /*
4778 * @implemented
4779 */
4780 NTSTATUS NTAPI
4781 MmMapViewInSystemSpace (IN PVOID SectionObject,
4782 OUT PVOID * MappedBase,
4783 IN OUT PSIZE_T ViewSize)
4784 {
4785 PROS_SECTION_OBJECT Section;
4786 PMM_AVL_TABLE AddressSpace;
4787 NTSTATUS Status;
4788
4789 DPRINT("MmMapViewInSystemSpace() called\n");
4790
4791 Section = (PROS_SECTION_OBJECT)SectionObject;
4792 AddressSpace = MmGetKernelAddressSpace();
4793
4794 MmLockAddressSpace(AddressSpace);
4795
4796
4797 if ((*ViewSize) == 0)
4798 {
4799 (*ViewSize) = Section->MaximumSize.u.LowPart;
4800 }
4801 else if ((*ViewSize) > Section->MaximumSize.u.LowPart)
4802 {
4803 (*ViewSize) = Section->MaximumSize.u.LowPart;
4804 }
4805
4806 MmLockSectionSegment(Section->Segment);
4807
4808
4809 Status = MmMapViewOfSegment(AddressSpace,
4810 Section,
4811 Section->Segment,
4812 MappedBase,
4813 *ViewSize,
4814 PAGE_READWRITE,
4815 0,
4816 0);
4817
4818 MmUnlockSectionSegment(Section->Segment);
4819 MmUnlockAddressSpace(AddressSpace);
4820
4821 return Status;
4822 }
4823
4824 /*
4825 * @unimplemented
4826 */
4827 NTSTATUS
4828 NTAPI
4829 MmMapViewInSessionSpace (
4830 IN PVOID Section,
4831 OUT PVOID *MappedBase,
4832 IN OUT PSIZE_T ViewSize
4833 )
4834 {
4835 UNIMPLEMENTED;
4836 return STATUS_NOT_IMPLEMENTED;
4837 }
4838
4839
4840 /*
4841 * @implemented
4842 */
4843 NTSTATUS NTAPI
4844 MmUnmapViewInSystemSpace (IN PVOID MappedBase)
4845 {
4846 PMM_AVL_TABLE AddressSpace;
4847 NTSTATUS Status;
4848
4849 DPRINT("MmUnmapViewInSystemSpace() called\n");
4850
4851 AddressSpace = MmGetKernelAddressSpace();
4852
4853 Status = MmUnmapViewOfSegment(AddressSpace, MappedBase);
4854
4855 return Status;
4856 }
4857
4858 /*
4859 * @unimplemented
4860 */
4861 NTSTATUS
4862 NTAPI
4863 MmUnmapViewInSessionSpace (
4864 IN PVOID MappedBase
4865 )
4866 {
4867 UNIMPLEMENTED;
4868 return STATUS_NOT_IMPLEMENTED;
4869 }
4870
4871 /*
4872 * @unimplemented
4873 */
4874 NTSTATUS NTAPI
4875 MmSetBankedSection (ULONG Unknown0,
4876 ULONG Unknown1,
4877 ULONG Unknown2,
4878 ULONG Unknown3,
4879 ULONG Unknown4,
4880 ULONG Unknown5)
4881 {
4882 UNIMPLEMENTED;
4883 return (STATUS_NOT_IMPLEMENTED);
4884 }
4885
4886
4887 /**********************************************************************
4888 * NAME EXPORTED
4889 * MmCreateSection@
4890 *
4891 * DESCRIPTION
4892 * Creates a section object.
4893 *
4894 * ARGUMENTS
4895 * SectionObject (OUT)
4896 * Caller supplied storage for the resulting pointer
4897 * to a SECTION_OBJECT instance;
4898 *
4899 * DesiredAccess
4900 * Specifies the desired access to the section can be a
4901 * combination of:
4902 * STANDARD_RIGHTS_REQUIRED |
4903 * SECTION_QUERY |
4904 * SECTION_MAP_WRITE |
4905 * SECTION_MAP_READ |
4906 * SECTION_MAP_EXECUTE
4907 *
4908 * ObjectAttributes [OPTIONAL]
4909 * Initialized attributes for the object can be used
4910 * to create a named section;
4911 *
4912 * MaximumSize
4913 * Maximizes the size of the memory section. Must be
4914 * non-NULL for a page-file backed section.
4915 * If value specified for a mapped file and the file is
4916 * not large enough, file will be extended.
4917 *
4918 * SectionPageProtection
4919 * Can be a combination of:
4920 * PAGE_READONLY |
4921 * PAGE_READWRITE |
4922 * PAGE_WRITEONLY |
4923 * PAGE_WRITECOPY
4924 *
4925 * AllocationAttributes
4926 * Can be a combination of:
4927 * SEC_IMAGE |
4928 * SEC_RESERVE
4929 *
4930 * FileHandle
4931 * Handle to a file to create a section mapped to a file
4932 * instead of a memory backed section;
4933 *
4934 * File
4935 * Unknown.
4936 *
4937 * RETURN VALUE
4938 * Status.
4939 *
4940 * @implemented
4941 */
4942 NTSTATUS NTAPI
4943 MmCreateSection (OUT PVOID * Section,
4944 IN ACCESS_MASK DesiredAccess,
4945 IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
4946 IN PLARGE_INTEGER MaximumSize,
4947 IN ULONG SectionPageProtection,
4948 IN ULONG AllocationAttributes,
4949 IN HANDLE FileHandle OPTIONAL,
4950 IN PFILE_OBJECT File OPTIONAL)
4951 {
4952 ULONG Protection;
4953 PROS_SECTION_OBJECT *SectionObject = (PROS_SECTION_OBJECT *)Section;
4954
4955 /*
4956 * Check the protection
4957 */
4958 Protection = SectionPageProtection & ~(PAGE_GUARD|PAGE_NOCACHE);
4959 if (Protection != PAGE_NOACCESS &&
4960 Protection != PAGE_READONLY &&
4961 Protection != PAGE_READWRITE &&
4962 Protection != PAGE_WRITECOPY &&
4963 Protection != PAGE_EXECUTE &&
4964 Protection != PAGE_EXECUTE_READ &&
4965 Protection != PAGE_EXECUTE_READWRITE &&
4966 Protection != PAGE_EXECUTE_WRITECOPY)
4967 {
4968 return STATUS_INVALID_PAGE_PROTECTION;
4969 }
4970
4971 if (AllocationAttributes & SEC_IMAGE)
4972 {
4973 return(MmCreateImageSection(SectionObject,
4974 DesiredAccess,
4975 ObjectAttributes,
4976 MaximumSize,
4977 SectionPageProtection,
4978 AllocationAttributes,
4979 FileHandle));
4980 }
4981
4982 if (FileHandle != NULL)
4983 {
4984 return(MmCreateDataFileSection(SectionObject,
4985 DesiredAccess,
4986 ObjectAttributes,
4987 MaximumSize,
4988 SectionPageProtection,
4989 AllocationAttributes,
4990 FileHandle));
4991 }
4992
4993 return(MmCreatePageFileSection(SectionObject,
4994 DesiredAccess,
4995 ObjectAttributes,
4996 MaximumSize,
4997 SectionPageProtection,
4998 AllocationAttributes));
4999 }
5000
5001 NTSTATUS
5002 NTAPI
5003 NtAllocateUserPhysicalPages(IN HANDLE ProcessHandle,
5004 IN OUT PULONG_PTR NumberOfPages,
5005 IN OUT PULONG_PTR UserPfnArray)
5006 {
5007 UNIMPLEMENTED;
5008 return STATUS_NOT_IMPLEMENTED;
5009 }
5010
5011 NTSTATUS
5012 NTAPI
5013 NtMapUserPhysicalPages(IN PVOID VirtualAddresses,
5014 IN ULONG_PTR NumberOfPages,
5015 IN OUT PULONG_PTR UserPfnArray)
5016 {
5017 UNIMPLEMENTED;
5018 return STATUS_NOT_IMPLEMENTED;
5019 }
5020
5021 NTSTATUS
5022 NTAPI
5023 NtMapUserPhysicalPagesScatter(IN PVOID *VirtualAddresses,
5024 IN ULONG_PTR NumberOfPages,
5025 IN OUT PULONG_PTR UserPfnArray)
5026 {
5027 UNIMPLEMENTED;
5028 return STATUS_NOT_IMPLEMENTED;
5029 }
5030
5031 NTSTATUS
5032 NTAPI
5033 NtFreeUserPhysicalPages(IN HANDLE ProcessHandle,
5034 IN OUT PULONG_PTR NumberOfPages,
5035 IN OUT PULONG_PTR UserPfnArray)
5036 {
5037 UNIMPLEMENTED;
5038 return STATUS_NOT_IMPLEMENTED;
5039 }
5040
5041 NTSTATUS
5042 NTAPI
5043 NtAreMappedFilesTheSame(IN PVOID File1MappedAsAnImage,
5044 IN PVOID File2MappedAsFile)
5045 {
5046 UNIMPLEMENTED;
5047 return STATUS_NOT_IMPLEMENTED;
5048 }
5049
5050
5051 /* EOF */