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