8c3aea9852b8dcdc4b06d213038ede6386d9008e
[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 #ifdef NEWCC
49 #include "../cache/section/newmm.h"
50 #endif
51 #define NDEBUG
52 #include <debug.h>
53 #include <reactos/exeformat.h>
54
55 #if defined (ALLOC_PRAGMA)
56 #pragma alloc_text(INIT, MmCreatePhysicalMemorySection)
57 #pragma alloc_text(INIT, MmInitSectionImplementation)
58 #endif
59
60 NTSTATUS
61 NTAPI
62 MiMapViewInSystemSpace(IN PVOID Section,
63 IN PVOID Session,
64 OUT PVOID *MappedBase,
65 IN OUT PSIZE_T ViewSize);
66
67 NTSTATUS
68 NTAPI
69 MmCreateArm3Section(OUT PVOID *SectionObject,
70 IN ACCESS_MASK DesiredAccess,
71 IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
72 IN PLARGE_INTEGER InputMaximumSize,
73 IN ULONG SectionPageProtection,
74 IN ULONG AllocationAttributes,
75 IN HANDLE FileHandle OPTIONAL,
76 IN PFILE_OBJECT FileObject OPTIONAL);
77
78 NTSTATUS
79 NTAPI
80 MmMapViewOfArm3Section(IN PVOID SectionObject,
81 IN PEPROCESS Process,
82 IN OUT PVOID *BaseAddress,
83 IN ULONG_PTR ZeroBits,
84 IN SIZE_T CommitSize,
85 IN OUT PLARGE_INTEGER SectionOffset OPTIONAL,
86 IN OUT PSIZE_T ViewSize,
87 IN SECTION_INHERIT InheritDisposition,
88 IN ULONG AllocationType,
89 IN ULONG Protect);
90
91 //
92 // PeFmtCreateSection depends on the following:
93 //
94 C_ASSERT(EXEFMT_LOAD_HEADER_SIZE >= sizeof(IMAGE_DOS_HEADER));
95 C_ASSERT(sizeof(IMAGE_NT_HEADERS32) <= sizeof(IMAGE_NT_HEADERS64));
96
97 C_ASSERT(TYPE_ALIGNMENT(IMAGE_NT_HEADERS32) == TYPE_ALIGNMENT(IMAGE_NT_HEADERS64));
98 C_ASSERT(RTL_SIZEOF_THROUGH_FIELD(IMAGE_NT_HEADERS32, FileHeader) == RTL_SIZEOF_THROUGH_FIELD(IMAGE_NT_HEADERS64, FileHeader));
99 C_ASSERT(FIELD_OFFSET(IMAGE_NT_HEADERS32, OptionalHeader) == FIELD_OFFSET(IMAGE_NT_HEADERS64, OptionalHeader));
100
101 C_ASSERT(PEFMT_FIELDS_EQUAL(IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, Magic));
102 C_ASSERT(PEFMT_FIELDS_EQUAL(IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, SectionAlignment));
103 C_ASSERT(PEFMT_FIELDS_EQUAL(IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, FileAlignment));
104 C_ASSERT(PEFMT_FIELDS_EQUAL(IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, Subsystem));
105 C_ASSERT(PEFMT_FIELDS_EQUAL(IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, MinorSubsystemVersion));
106 C_ASSERT(PEFMT_FIELDS_EQUAL(IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, MajorSubsystemVersion));
107 C_ASSERT(PEFMT_FIELDS_EQUAL(IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, AddressOfEntryPoint));
108 C_ASSERT(PEFMT_FIELDS_EQUAL(IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, SizeOfCode));
109 C_ASSERT(PEFMT_FIELDS_EQUAL(IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, SizeOfHeaders));
110
111 /* TYPES *********************************************************************/
112
113 typedef struct
114 {
115 PROS_SECTION_OBJECT Section;
116 PMM_SECTION_SEGMENT Segment;
117 ULONG Offset;
118 BOOLEAN WasDirty;
119 BOOLEAN Private;
120 }
121 MM_SECTION_PAGEOUT_CONTEXT;
122
123 /* GLOBALS *******************************************************************/
124
125 POBJECT_TYPE MmSectionObjectType = NULL;
126
127 ULONG_PTR MmSubsectionBase;
128
129 static ULONG SectionCharacteristicsToProtect[16] =
130 {
131 PAGE_NOACCESS, /* 0 = NONE */
132 PAGE_NOACCESS, /* 1 = SHARED */
133 PAGE_EXECUTE, /* 2 = EXECUTABLE */
134 PAGE_EXECUTE, /* 3 = EXECUTABLE, SHARED */
135 PAGE_READONLY, /* 4 = READABLE */
136 PAGE_READONLY, /* 5 = READABLE, SHARED */
137 PAGE_EXECUTE_READ, /* 6 = READABLE, EXECUTABLE */
138 PAGE_EXECUTE_READ, /* 7 = READABLE, EXECUTABLE, SHARED */
139 /*
140 * FIXME? do we really need the WriteCopy field in segments? can't we use
141 * PAGE_WRITECOPY here?
142 */
143 PAGE_READWRITE, /* 8 = WRITABLE */
144 PAGE_READWRITE, /* 9 = WRITABLE, SHARED */
145 PAGE_EXECUTE_READWRITE, /* 10 = WRITABLE, EXECUTABLE */
146 PAGE_EXECUTE_READWRITE, /* 11 = WRITABLE, EXECUTABLE, SHARED */
147 PAGE_READWRITE, /* 12 = WRITABLE, READABLE */
148 PAGE_READWRITE, /* 13 = WRITABLE, READABLE, SHARED */
149 PAGE_EXECUTE_READWRITE, /* 14 = WRITABLE, READABLE, EXECUTABLE */
150 PAGE_EXECUTE_READWRITE, /* 15 = WRITABLE, READABLE, EXECUTABLE, SHARED */
151 };
152
153 static GENERIC_MAPPING MmpSectionMapping = {
154 STANDARD_RIGHTS_READ | SECTION_MAP_READ | SECTION_QUERY,
155 STANDARD_RIGHTS_WRITE | SECTION_MAP_WRITE,
156 STANDARD_RIGHTS_EXECUTE | SECTION_MAP_EXECUTE,
157 SECTION_ALL_ACCESS};
158
159 #define PAGE_FROM_SSE(E) ((E) & 0xFFFFF000)
160 #define PFN_FROM_SSE(E) ((E) >> PAGE_SHIFT)
161 #define SHARE_COUNT_FROM_SSE(E) (((E) & 0x00000FFE) >> 1)
162 #define IS_SWAP_FROM_SSE(E) ((E) & 0x00000001)
163 #define MAX_SHARE_COUNT 0x7FF
164 #define MAKE_SSE(P, C) ((ULONG)(P) | ((C) << 1))
165 #define SWAPENTRY_FROM_SSE(E) ((E) >> 1)
166 #define MAKE_SWAP_SSE(S) (((ULONG)(S) << 1) | 0x1)
167
168 static const INFORMATION_CLASS_INFO ExSectionInfoClass[] =
169 {
170 ICI_SQ_SAME( sizeof(SECTION_BASIC_INFORMATION), sizeof(ULONG), ICIF_QUERY ), /* SectionBasicInformation */
171 ICI_SQ_SAME( sizeof(SECTION_IMAGE_INFORMATION), sizeof(ULONG), ICIF_QUERY ), /* SectionImageInformation */
172 };
173
174 /* FUNCTIONS *****************************************************************/
175
176
177 /*
178 References:
179 [1] Microsoft Corporation, "Microsoft Portable Executable and Common Object
180 File Format Specification", revision 6.0 (February 1999)
181 */
182 NTSTATUS NTAPI PeFmtCreateSection(IN CONST VOID * FileHeader,
183 IN SIZE_T FileHeaderSize,
184 IN PVOID File,
185 OUT PMM_IMAGE_SECTION_OBJECT ImageSectionObject,
186 OUT PULONG Flags,
187 IN PEXEFMT_CB_READ_FILE ReadFileCb,
188 IN PEXEFMT_CB_ALLOCATE_SEGMENTS AllocateSegmentsCb)
189 {
190 NTSTATUS nStatus;
191 ULONG cbFileHeaderOffsetSize = 0;
192 ULONG cbSectionHeadersOffset = 0;
193 ULONG cbSectionHeadersSize;
194 ULONG cbSectionHeadersOffsetSize = 0;
195 ULONG cbOptHeaderSize;
196 ULONG cbHeadersSize = 0;
197 ULONG nSectionAlignment;
198 ULONG nFileAlignment;
199 const IMAGE_DOS_HEADER * pidhDosHeader;
200 const IMAGE_NT_HEADERS32 * pinhNtHeader;
201 const IMAGE_OPTIONAL_HEADER32 * piohOptHeader;
202 const IMAGE_SECTION_HEADER * pishSectionHeaders;
203 PMM_SECTION_SEGMENT pssSegments;
204 LARGE_INTEGER lnOffset;
205 PVOID pBuffer;
206 SIZE_T nPrevVirtualEndOfSegment = 0;
207 ULONG nFileSizeOfHeaders = 0;
208 ULONG i;
209
210 ASSERT(FileHeader);
211 ASSERT(FileHeaderSize > 0);
212 ASSERT(File);
213 ASSERT(ImageSectionObject);
214 ASSERT(ReadFileCb);
215 ASSERT(AllocateSegmentsCb);
216
217 ASSERT(Intsafe_CanOffsetPointer(FileHeader, FileHeaderSize));
218
219 ASSERT(((UINT_PTR)FileHeader % TYPE_ALIGNMENT(IMAGE_DOS_HEADER)) == 0);
220
221 #define DIE(ARGS_) { DPRINT ARGS_; goto l_Return; }
222
223 pBuffer = NULL;
224 pidhDosHeader = FileHeader;
225
226 /* DOS HEADER */
227 nStatus = STATUS_ROS_EXEFMT_UNKNOWN_FORMAT;
228
229 /* image too small to be an MZ executable */
230 if(FileHeaderSize < sizeof(IMAGE_DOS_HEADER))
231 DIE(("Too small to be an MZ executable, size is %lu\n", FileHeaderSize));
232
233 /* no MZ signature */
234 if(pidhDosHeader->e_magic != IMAGE_DOS_SIGNATURE)
235 DIE(("No MZ signature found, e_magic is %hX\n", pidhDosHeader->e_magic));
236
237 /* not a Windows executable */
238 if(pidhDosHeader->e_lfanew <= 0)
239 DIE(("Not a Windows executable, e_lfanew is %d\n", pidhDosHeader->e_lfanew));
240
241 /* NT HEADER */
242 nStatus = STATUS_INVALID_IMAGE_FORMAT;
243
244 if(!Intsafe_AddULong32(&cbFileHeaderOffsetSize, pidhDosHeader->e_lfanew, RTL_SIZEOF_THROUGH_FIELD(IMAGE_NT_HEADERS32, FileHeader)))
245 DIE(("The DOS stub is too large, e_lfanew is %X\n", pidhDosHeader->e_lfanew));
246
247 if(FileHeaderSize < cbFileHeaderOffsetSize)
248 pinhNtHeader = NULL;
249 else
250 {
251 /*
252 * we already know that Intsafe_CanOffsetPointer(FileHeader, FileHeaderSize),
253 * and FileHeaderSize >= cbFileHeaderOffsetSize, so this holds true too
254 */
255 ASSERT(Intsafe_CanOffsetPointer(FileHeader, pidhDosHeader->e_lfanew));
256 pinhNtHeader = (PVOID)((UINT_PTR)FileHeader + pidhDosHeader->e_lfanew);
257 }
258
259 /*
260 * the buffer doesn't contain the NT file header, or the alignment is wrong: we
261 * need to read the header from the file
262 */
263 if(FileHeaderSize < cbFileHeaderOffsetSize ||
264 (UINT_PTR)pinhNtHeader % TYPE_ALIGNMENT(IMAGE_NT_HEADERS32) != 0)
265 {
266 ULONG cbNtHeaderSize;
267 ULONG cbReadSize;
268 PVOID pData;
269
270 l_ReadHeaderFromFile:
271 cbNtHeaderSize = 0;
272 lnOffset.QuadPart = pidhDosHeader->e_lfanew;
273
274 /* read the header from the file */
275 nStatus = ReadFileCb(File, &lnOffset, sizeof(IMAGE_NT_HEADERS64), &pData, &pBuffer, &cbReadSize);
276
277 if(!NT_SUCCESS(nStatus))
278 DIE(("ReadFile failed, status %08X\n", nStatus));
279
280 ASSERT(pData);
281 ASSERT(pBuffer);
282 ASSERT(cbReadSize > 0);
283
284 nStatus = STATUS_INVALID_IMAGE_FORMAT;
285
286 /* the buffer doesn't contain the file header */
287 if(cbReadSize < RTL_SIZEOF_THROUGH_FIELD(IMAGE_NT_HEADERS32, FileHeader))
288 DIE(("The file doesn't contain the PE file header\n"));
289
290 pinhNtHeader = pData;
291
292 /* object still not aligned: copy it to the beginning of the buffer */
293 if((UINT_PTR)pinhNtHeader % TYPE_ALIGNMENT(IMAGE_NT_HEADERS32) != 0)
294 {
295 ASSERT((UINT_PTR)pBuffer % TYPE_ALIGNMENT(IMAGE_NT_HEADERS32) == 0);
296 RtlMoveMemory(pBuffer, pData, cbReadSize);
297 pinhNtHeader = pBuffer;
298 }
299
300 /* invalid NT header */
301 nStatus = STATUS_INVALID_IMAGE_PROTECT;
302
303 if(pinhNtHeader->Signature != IMAGE_NT_SIGNATURE)
304 DIE(("The file isn't a PE executable, Signature is %X\n", pinhNtHeader->Signature));
305
306 nStatus = STATUS_INVALID_IMAGE_FORMAT;
307
308 if(!Intsafe_AddULong32(&cbNtHeaderSize, pinhNtHeader->FileHeader.SizeOfOptionalHeader, FIELD_OFFSET(IMAGE_NT_HEADERS32, OptionalHeader)))
309 DIE(("The full NT header is too large\n"));
310
311 /* the buffer doesn't contain the whole NT header */
312 if(cbReadSize < cbNtHeaderSize)
313 DIE(("The file doesn't contain the full NT header\n"));
314 }
315 else
316 {
317 ULONG cbOptHeaderOffsetSize = 0;
318
319 nStatus = STATUS_INVALID_IMAGE_FORMAT;
320
321 /* don't trust an invalid NT header */
322 if(pinhNtHeader->Signature != IMAGE_NT_SIGNATURE)
323 DIE(("The file isn't a PE executable, Signature is %X\n", pinhNtHeader->Signature));
324
325 if(!Intsafe_AddULong32(&cbOptHeaderOffsetSize, pidhDosHeader->e_lfanew, FIELD_OFFSET(IMAGE_NT_HEADERS32, OptionalHeader)))
326 DIE(("The DOS stub is too large, e_lfanew is %X\n", pidhDosHeader->e_lfanew));
327
328 if(!Intsafe_AddULong32(&cbOptHeaderOffsetSize, cbOptHeaderOffsetSize, pinhNtHeader->FileHeader.SizeOfOptionalHeader))
329 DIE(("The NT header is too large, SizeOfOptionalHeader is %X\n", pinhNtHeader->FileHeader.SizeOfOptionalHeader));
330
331 /* the buffer doesn't contain the whole NT header: read it from the file */
332 if(cbOptHeaderOffsetSize > FileHeaderSize)
333 goto l_ReadHeaderFromFile;
334 }
335
336 /* read information from the NT header */
337 piohOptHeader = &pinhNtHeader->OptionalHeader;
338 cbOptHeaderSize = pinhNtHeader->FileHeader.SizeOfOptionalHeader;
339
340 nStatus = STATUS_INVALID_IMAGE_FORMAT;
341
342 if(!RTL_CONTAINS_FIELD(piohOptHeader, cbOptHeaderSize, Magic))
343 DIE(("The optional header doesn't contain the Magic field, SizeOfOptionalHeader is %X\n", cbOptHeaderSize));
344
345 /* ASSUME: RtlZeroMemory(ImageSectionObject, sizeof(*ImageSectionObject)); */
346
347 switch(piohOptHeader->Magic)
348 {
349 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
350 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
351 break;
352
353 default:
354 DIE(("Unrecognized optional header, Magic is %X\n", piohOptHeader->Magic));
355 }
356
357 if (RTL_CONTAINS_FIELD(piohOptHeader, cbOptHeaderSize, SectionAlignment) &&
358 RTL_CONTAINS_FIELD(piohOptHeader, cbOptHeaderSize, FileAlignment))
359 {
360 /* See [1], section 3.4.2 */
361 if(piohOptHeader->SectionAlignment < PAGE_SIZE)
362 {
363 if(piohOptHeader->FileAlignment != piohOptHeader->SectionAlignment)
364 DIE(("Sections aren't page-aligned and the file alignment isn't the same\n"));
365 }
366 else if(piohOptHeader->SectionAlignment < piohOptHeader->FileAlignment)
367 DIE(("The section alignment is smaller than the file alignment\n"));
368
369 nSectionAlignment = piohOptHeader->SectionAlignment;
370 nFileAlignment = piohOptHeader->FileAlignment;
371
372 if(!IsPowerOf2(nSectionAlignment) || !IsPowerOf2(nFileAlignment))
373 DIE(("The section alignment (%u) and file alignment (%u) aren't both powers of 2\n", nSectionAlignment, nFileAlignment));
374 }
375 else
376 {
377 nSectionAlignment = PAGE_SIZE;
378 nFileAlignment = PAGE_SIZE;
379 }
380
381 ASSERT(IsPowerOf2(nSectionAlignment));
382 ASSERT(IsPowerOf2(nFileAlignment));
383
384 switch(piohOptHeader->Magic)
385 {
386 /* PE32 */
387 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
388 {
389 if(RTL_CONTAINS_FIELD(piohOptHeader, cbOptHeaderSize, ImageBase))
390 ImageSectionObject->ImageBase = piohOptHeader->ImageBase;
391
392 if(RTL_CONTAINS_FIELD(piohOptHeader, cbOptHeaderSize, SizeOfImage))
393 ImageSectionObject->ImageSize = piohOptHeader->SizeOfImage;
394
395 if(RTL_CONTAINS_FIELD(piohOptHeader, cbOptHeaderSize, SizeOfStackReserve))
396 ImageSectionObject->StackReserve = piohOptHeader->SizeOfStackReserve;
397
398 if(RTL_CONTAINS_FIELD(piohOptHeader, cbOptHeaderSize, SizeOfStackCommit))
399 ImageSectionObject->StackCommit = piohOptHeader->SizeOfStackCommit;
400
401 break;
402 }
403
404 /* PE32+ */
405 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
406 {
407 const IMAGE_OPTIONAL_HEADER64 * pioh64OptHeader;
408
409 pioh64OptHeader = (const IMAGE_OPTIONAL_HEADER64 *)piohOptHeader;
410
411 if(RTL_CONTAINS_FIELD(pioh64OptHeader, cbOptHeaderSize, ImageBase))
412 {
413 if(pioh64OptHeader->ImageBase > MAXULONG_PTR)
414 DIE(("ImageBase exceeds the address space\n"));
415
416 ImageSectionObject->ImageBase = (ULONG_PTR)pioh64OptHeader->ImageBase;
417 }
418
419 if(RTL_CONTAINS_FIELD(pioh64OptHeader, cbOptHeaderSize, SizeOfImage))
420 {
421 if(pioh64OptHeader->SizeOfImage > MAXULONG_PTR)
422 DIE(("SizeOfImage exceeds the address space\n"));
423
424 ImageSectionObject->ImageSize = pioh64OptHeader->SizeOfImage;
425 }
426
427 if(RTL_CONTAINS_FIELD(pioh64OptHeader, cbOptHeaderSize, SizeOfStackReserve))
428 {
429 if(pioh64OptHeader->SizeOfStackReserve > MAXULONG_PTR)
430 DIE(("SizeOfStackReserve exceeds the address space\n"));
431
432 ImageSectionObject->StackReserve = (ULONG_PTR)pioh64OptHeader->SizeOfStackReserve;
433 }
434
435 if(RTL_CONTAINS_FIELD(pioh64OptHeader, cbOptHeaderSize, SizeOfStackCommit))
436 {
437 if(pioh64OptHeader->SizeOfStackCommit > MAXULONG_PTR)
438 DIE(("SizeOfStackCommit exceeds the address space\n"));
439
440 ImageSectionObject->StackCommit = (ULONG_PTR)pioh64OptHeader->SizeOfStackCommit;
441 }
442
443 break;
444 }
445 }
446
447 /* [1], section 3.4.2 */
448 if((ULONG_PTR)ImageSectionObject->ImageBase % 0x10000)
449 DIE(("ImageBase is not aligned on a 64KB boundary"));
450
451 if(RTL_CONTAINS_FIELD(piohOptHeader, cbOptHeaderSize, Subsystem))
452 {
453 ImageSectionObject->Subsystem = piohOptHeader->Subsystem;
454
455 if(RTL_CONTAINS_FIELD(piohOptHeader, cbOptHeaderSize, MinorSubsystemVersion) &&
456 RTL_CONTAINS_FIELD(piohOptHeader, cbOptHeaderSize, MajorSubsystemVersion))
457 {
458 ImageSectionObject->MinorSubsystemVersion = piohOptHeader->MinorSubsystemVersion;
459 ImageSectionObject->MajorSubsystemVersion = piohOptHeader->MajorSubsystemVersion;
460 }
461 }
462
463 if(RTL_CONTAINS_FIELD(piohOptHeader, cbOptHeaderSize, AddressOfEntryPoint))
464 {
465 ImageSectionObject->EntryPoint = piohOptHeader->ImageBase +
466 piohOptHeader->AddressOfEntryPoint;
467 }
468
469 if(RTL_CONTAINS_FIELD(piohOptHeader, cbOptHeaderSize, SizeOfCode))
470 ImageSectionObject->Executable = piohOptHeader->SizeOfCode != 0;
471 else
472 ImageSectionObject->Executable = TRUE;
473
474 ImageSectionObject->ImageCharacteristics = pinhNtHeader->FileHeader.Characteristics;
475 ImageSectionObject->Machine = pinhNtHeader->FileHeader.Machine;
476
477 /* SECTION HEADERS */
478 nStatus = STATUS_INVALID_IMAGE_FORMAT;
479
480 /* see [1], section 3.3 */
481 if(pinhNtHeader->FileHeader.NumberOfSections > 96)
482 DIE(("Too many sections, NumberOfSections is %u\n", pinhNtHeader->FileHeader.NumberOfSections));
483
484 /*
485 * the additional segment is for the file's headers. They need to be present for
486 * the benefit of the dynamic loader (to locate exports, defaults for thread
487 * parameters, resources, etc.)
488 */
489 ImageSectionObject->NrSegments = pinhNtHeader->FileHeader.NumberOfSections + 1;
490
491 /* file offset for the section headers */
492 if(!Intsafe_AddULong32(&cbSectionHeadersOffset, pidhDosHeader->e_lfanew, FIELD_OFFSET(IMAGE_NT_HEADERS32, OptionalHeader)))
493 DIE(("Offset overflow\n"));
494
495 if(!Intsafe_AddULong32(&cbSectionHeadersOffset, cbSectionHeadersOffset, pinhNtHeader->FileHeader.SizeOfOptionalHeader))
496 DIE(("Offset overflow\n"));
497
498 /* size of the section headers */
499 ASSERT(Intsafe_CanMulULong32(pinhNtHeader->FileHeader.NumberOfSections, sizeof(IMAGE_SECTION_HEADER)));
500 cbSectionHeadersSize = pinhNtHeader->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER);
501
502 if(!Intsafe_AddULong32(&cbSectionHeadersOffsetSize, cbSectionHeadersOffset, cbSectionHeadersSize))
503 DIE(("Section headers too large\n"));
504
505 /* size of the executable's headers */
506 if(RTL_CONTAINS_FIELD(piohOptHeader, cbOptHeaderSize, SizeOfHeaders))
507 {
508 // if(!IsAligned(piohOptHeader->SizeOfHeaders, nFileAlignment))
509 // DIE(("SizeOfHeaders is not aligned\n"));
510
511 if(cbSectionHeadersSize > piohOptHeader->SizeOfHeaders)
512 DIE(("The section headers overflow SizeOfHeaders\n"));
513
514 cbHeadersSize = piohOptHeader->SizeOfHeaders;
515 }
516 else if(!AlignUp(&cbHeadersSize, cbSectionHeadersOffsetSize, nFileAlignment))
517 DIE(("Overflow aligning the size of headers\n"));
518
519 if(pBuffer)
520 {
521 ExFreePool(pBuffer);
522 pBuffer = NULL;
523 }
524 /* WARNING: pinhNtHeader IS NO LONGER USABLE */
525 /* WARNING: piohOptHeader IS NO LONGER USABLE */
526 /* WARNING: pioh64OptHeader IS NO LONGER USABLE */
527
528 if(FileHeaderSize < cbSectionHeadersOffsetSize)
529 pishSectionHeaders = NULL;
530 else
531 {
532 /*
533 * we already know that Intsafe_CanOffsetPointer(FileHeader, FileHeaderSize),
534 * and FileHeaderSize >= cbSectionHeadersOffsetSize, so this holds true too
535 */
536 ASSERT(Intsafe_CanOffsetPointer(FileHeader, cbSectionHeadersOffset));
537 pishSectionHeaders = (PVOID)((UINT_PTR)FileHeader + cbSectionHeadersOffset);
538 }
539
540 /*
541 * the buffer doesn't contain the section headers, or the alignment is wrong:
542 * read the headers from the file
543 */
544 if(FileHeaderSize < cbSectionHeadersOffsetSize ||
545 (UINT_PTR)pishSectionHeaders % TYPE_ALIGNMENT(IMAGE_SECTION_HEADER) != 0)
546 {
547 PVOID pData;
548 ULONG cbReadSize;
549
550 lnOffset.QuadPart = cbSectionHeadersOffset;
551
552 /* read the header from the file */
553 nStatus = ReadFileCb(File, &lnOffset, cbSectionHeadersSize, &pData, &pBuffer, &cbReadSize);
554
555 if(!NT_SUCCESS(nStatus))
556 DIE(("ReadFile failed with status %08X\n", nStatus));
557
558 ASSERT(pData);
559 ASSERT(pBuffer);
560 ASSERT(cbReadSize > 0);
561
562 nStatus = STATUS_INVALID_IMAGE_FORMAT;
563
564 /* the buffer doesn't contain all the section headers */
565 if(cbReadSize < cbSectionHeadersSize)
566 DIE(("The file doesn't contain all of the section headers\n"));
567
568 pishSectionHeaders = pData;
569
570 /* object still not aligned: copy it to the beginning of the buffer */
571 if((UINT_PTR)pishSectionHeaders % TYPE_ALIGNMENT(IMAGE_SECTION_HEADER) != 0)
572 {
573 ASSERT((UINT_PTR)pBuffer % TYPE_ALIGNMENT(IMAGE_SECTION_HEADER) == 0);
574 RtlMoveMemory(pBuffer, pData, cbReadSize);
575 pishSectionHeaders = pBuffer;
576 }
577 }
578
579 /* SEGMENTS */
580 /* allocate the segments */
581 nStatus = STATUS_INSUFFICIENT_RESOURCES;
582 ImageSectionObject->Segments = AllocateSegmentsCb(ImageSectionObject->NrSegments);
583
584 if(ImageSectionObject->Segments == NULL)
585 DIE(("AllocateSegments failed\n"));
586
587 /* initialize the headers segment */
588 pssSegments = ImageSectionObject->Segments;
589
590 // ASSERT(IsAligned(cbHeadersSize, nFileAlignment));
591
592 if(!AlignUp(&nFileSizeOfHeaders, cbHeadersSize, nFileAlignment))
593 DIE(("Cannot align the size of the section headers\n"));
594
595 nPrevVirtualEndOfSegment = ALIGN_UP_BY(cbHeadersSize, nSectionAlignment);
596 if (nPrevVirtualEndOfSegment < cbHeadersSize)
597 DIE(("Cannot align the size of the section headers\n"));
598
599 pssSegments[0].FileOffset = 0;
600 pssSegments[0].Protection = PAGE_READONLY;
601 pssSegments[0].Length = nPrevVirtualEndOfSegment;
602 pssSegments[0].RawLength = nFileSizeOfHeaders;
603 pssSegments[0].VirtualAddress = 0;
604 pssSegments[0].Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA;
605 pssSegments[0].WriteCopy = TRUE;
606
607 /* skip the headers segment */
608 ++ pssSegments;
609
610 nStatus = STATUS_INVALID_IMAGE_FORMAT;
611
612 /* convert the executable sections into segments. See also [1], section 4 */
613 for(i = 0; i < ImageSectionObject->NrSegments - 1; ++ i)
614 {
615 ULONG nCharacteristics;
616
617 /* validate the alignment */
618 if(!IsAligned(pishSectionHeaders[i].VirtualAddress, nSectionAlignment))
619 DIE(("VirtualAddress[%u] is not aligned\n", i));
620
621 /* sections must be contiguous, ordered by base address and non-overlapping */
622 if(pishSectionHeaders[i].VirtualAddress != nPrevVirtualEndOfSegment)
623 DIE(("Memory gap between section %u and the previous\n", i));
624
625 /* ignore explicit BSS sections */
626 if(pishSectionHeaders[i].SizeOfRawData != 0)
627 {
628 /* validate the alignment */
629 #if 0
630 /* Yes, this should be a multiple of FileAlignment, but there's
631 * stuff out there that isn't. We can cope with that
632 */
633 if(!IsAligned(pishSectionHeaders[i].SizeOfRawData, nFileAlignment))
634 DIE(("SizeOfRawData[%u] is not aligned\n", i));
635 #endif
636
637 // if(!IsAligned(pishSectionHeaders[i].PointerToRawData, nFileAlignment))
638 // DIE(("PointerToRawData[%u] is not aligned\n", i));
639
640 /* conversion */
641 pssSegments[i].FileOffset = pishSectionHeaders[i].PointerToRawData;
642 pssSegments[i].RawLength = pishSectionHeaders[i].SizeOfRawData;
643 }
644 else
645 {
646 ASSERT(pssSegments[i].FileOffset == 0);
647 ASSERT(pssSegments[i].RawLength == 0);
648 }
649
650 ASSERT(Intsafe_CanAddLong64(pssSegments[i].FileOffset, pssSegments[i].RawLength));
651
652 nCharacteristics = pishSectionHeaders[i].Characteristics;
653
654 /* no explicit protection */
655 if((nCharacteristics & (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE)) == 0)
656 {
657 if(nCharacteristics & IMAGE_SCN_CNT_CODE)
658 nCharacteristics |= IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ;
659
660 if(nCharacteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
661 nCharacteristics |= IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE;
662
663 if(nCharacteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
664 nCharacteristics |= IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE;
665 }
666
667 /* see table above */
668 pssSegments[i].Protection = SectionCharacteristicsToProtect[nCharacteristics >> 28];
669 pssSegments[i].WriteCopy = !(nCharacteristics & IMAGE_SCN_MEM_SHARED);
670
671 if(pishSectionHeaders[i].Misc.VirtualSize == 0 || pishSectionHeaders[i].Misc.VirtualSize < pishSectionHeaders[i].SizeOfRawData)
672 pssSegments[i].Length = pishSectionHeaders[i].SizeOfRawData;
673 else
674 pssSegments[i].Length = pishSectionHeaders[i].Misc.VirtualSize;
675
676 pssSegments[i].Length = ALIGN_UP_BY(pssSegments[i].Length, nSectionAlignment);
677 if (pssSegments[i].Length < pssSegments[i].Length)
678 DIE(("Cannot align the virtual size of section %u\n", i));
679
680 if(pssSegments[i].Length == 0)
681 DIE(("Virtual size of section %u is null\n", i));
682
683 pssSegments[i].VirtualAddress = pishSectionHeaders[i].VirtualAddress;
684 pssSegments[i].Characteristics = pishSectionHeaders[i].Characteristics;
685
686 /* ensure the memory image is no larger than 4GB */
687 nPrevVirtualEndOfSegment = pssSegments[i].VirtualAddress + pssSegments[i].Length;
688 if (nPrevVirtualEndOfSegment < pssSegments[i].VirtualAddress)
689 DIE(("The image is too large\n"));
690 }
691
692 if(nSectionAlignment >= PAGE_SIZE)
693 *Flags |= EXEFMT_LOAD_ASSUME_SEGMENTS_PAGE_ALIGNED;
694
695 /* Success */
696 nStatus = STATUS_ROS_EXEFMT_LOADED_FORMAT | EXEFMT_LOADED_PE32;
697
698 l_Return:
699 if(pBuffer)
700 ExFreePool(pBuffer);
701
702 return nStatus;
703 }
704
705 /* Note: Mmsp prefix denotes "Memory Manager Section Private". */
706
707 /*
708 * FUNCTION: Waits in kernel mode up to ten seconds for an MM_PAGEOP event.
709 * ARGUMENTS: PMM_PAGEOP which event we should wait for.
710 * RETURNS: Status of the wait.
711 */
712 static NTSTATUS
713 MmspWaitForPageOpCompletionEvent(PMM_PAGEOP PageOp)
714 {
715 LARGE_INTEGER Timeout;
716 #ifdef __GNUC__ /* TODO: Use other macro to check for suffix to use? */
717
718 Timeout.QuadPart = -100000000LL; // 10 sec
719 #else
720
721 Timeout.QuadPart = -100000000; // 10 sec
722 #endif
723
724 return KeWaitForSingleObject(&PageOp->CompletionEvent, 0, KernelMode, FALSE, &Timeout);
725 }
726
727
728 /*
729 * FUNCTION: Sets the page op completion event and releases the page op.
730 * ARGUMENTS: PMM_PAGEOP.
731 * RETURNS: In shorter time than it takes you to even read this
732 * description, so don't even think about geting a mug of coffee.
733 */
734 static void
735 MmspCompleteAndReleasePageOp(PMM_PAGEOP PageOp)
736 {
737 KeSetEvent(&PageOp->CompletionEvent, IO_NO_INCREMENT, FALSE);
738 MmReleasePageOp(PageOp);
739 }
740
741
742 /*
743 * FUNCTION: Waits in kernel mode indefinitely for a file object lock.
744 * ARGUMENTS: PFILE_OBJECT to wait for.
745 * RETURNS: Status of the wait.
746 */
747 NTSTATUS
748 MmspWaitForFileLock(PFILE_OBJECT File)
749 {
750 return STATUS_SUCCESS;
751 //return KeWaitForSingleObject(&File->Lock, 0, KernelMode, FALSE, NULL);
752 }
753
754
755 VOID
756 MmFreePageTablesSectionSegment(PMM_SECTION_SEGMENT Segment)
757 {
758 ULONG i;
759 if (Segment->Length > NR_SECTION_PAGE_TABLES * PAGE_SIZE)
760 {
761 for (i = 0; i < NR_SECTION_PAGE_TABLES; i++)
762 {
763 if (Segment->PageDirectory.PageTables[i] != NULL)
764 {
765 ExFreePool(Segment->PageDirectory.PageTables[i]);
766 }
767 }
768 }
769 }
770
771 VOID
772 NTAPI
773 MmFreeSectionSegments(PFILE_OBJECT FileObject)
774 {
775 if (FileObject->SectionObjectPointer->ImageSectionObject != NULL)
776 {
777 PMM_IMAGE_SECTION_OBJECT ImageSectionObject;
778 PMM_SECTION_SEGMENT SectionSegments;
779 ULONG NrSegments;
780 ULONG i;
781
782 ImageSectionObject = (PMM_IMAGE_SECTION_OBJECT)FileObject->SectionObjectPointer->ImageSectionObject;
783 NrSegments = ImageSectionObject->NrSegments;
784 SectionSegments = ImageSectionObject->Segments;
785 for (i = 0; i < NrSegments; i++)
786 {
787 if (SectionSegments[i].ReferenceCount != 0)
788 {
789 DPRINT1("Image segment %d still referenced (was %d)\n", i,
790 SectionSegments[i].ReferenceCount);
791 KeBugCheck(MEMORY_MANAGEMENT);
792 }
793 MmFreePageTablesSectionSegment(&SectionSegments[i]);
794 }
795 ExFreePool(ImageSectionObject->Segments);
796 ExFreePool(ImageSectionObject);
797 FileObject->SectionObjectPointer->ImageSectionObject = NULL;
798 }
799 if (FileObject->SectionObjectPointer->DataSectionObject != NULL)
800 {
801 PMM_SECTION_SEGMENT Segment;
802
803 Segment = (PMM_SECTION_SEGMENT)FileObject->SectionObjectPointer->
804 DataSectionObject;
805
806 if (Segment->ReferenceCount != 0)
807 {
808 DPRINT1("Data segment still referenced\n");
809 KeBugCheck(MEMORY_MANAGEMENT);
810 }
811 MmFreePageTablesSectionSegment(Segment);
812 ExFreePool(Segment);
813 FileObject->SectionObjectPointer->DataSectionObject = NULL;
814 }
815 }
816
817 VOID
818 NTAPI
819 MmLockSectionSegment(PMM_SECTION_SEGMENT Segment)
820 {
821 ExAcquireFastMutex(&Segment->Lock);
822 }
823
824 VOID
825 NTAPI
826 MmUnlockSectionSegment(PMM_SECTION_SEGMENT Segment)
827 {
828 ExReleaseFastMutex(&Segment->Lock);
829 }
830
831 VOID
832 NTAPI
833 MmSetPageEntrySectionSegment(PMM_SECTION_SEGMENT Segment,
834 ULONG_PTR Offset,
835 ULONG_PTR Entry)
836 {
837 PSECTION_PAGE_TABLE Table;
838 ULONG_PTR DirectoryOffset;
839 ULONG_PTR TableOffset;
840
841 if (Segment->Length <= NR_SECTION_PAGE_TABLES * PAGE_SIZE)
842 {
843 Table = (PSECTION_PAGE_TABLE)&Segment->PageDirectory;
844 }
845 else
846 {
847 DirectoryOffset = PAGE_TO_SECTION_PAGE_DIRECTORY_OFFSET(Offset);
848 Table = Segment->PageDirectory.PageTables[DirectoryOffset];
849 if (Table == NULL)
850 {
851 Table =
852 Segment->PageDirectory.PageTables[DirectoryOffset] =
853 ExAllocatePoolWithTag(NonPagedPool, sizeof(SECTION_PAGE_TABLE),
854 TAG_SECTION_PAGE_TABLE);
855 if (Table == NULL)
856 {
857 KeBugCheck(MEMORY_MANAGEMENT);
858 }
859 memset(Table, 0, sizeof(SECTION_PAGE_TABLE));
860 DPRINT("Table %x\n", Table);
861 }
862 }
863 TableOffset = PAGE_TO_SECTION_PAGE_TABLE_OFFSET(Offset);
864 Table->Entry[TableOffset] = (ULONG)Entry;
865 }
866
867
868 ULONG
869 NTAPI
870 MmGetPageEntrySectionSegment(PMM_SECTION_SEGMENT Segment,
871 ULONG_PTR Offset)
872 {
873 PSECTION_PAGE_TABLE Table;
874 ULONG Entry;
875 ULONG_PTR DirectoryOffset;
876 ULONG_PTR TableOffset;
877
878 DPRINT("MmGetPageEntrySection(Segment %x, Offset %x)\n", Segment, Offset);
879
880 if (Segment->Length <= NR_SECTION_PAGE_TABLES * PAGE_SIZE)
881 {
882 Table = (PSECTION_PAGE_TABLE)&Segment->PageDirectory;
883 }
884 else
885 {
886 DirectoryOffset = PAGE_TO_SECTION_PAGE_DIRECTORY_OFFSET(Offset);
887 Table = Segment->PageDirectory.PageTables[DirectoryOffset];
888 DPRINT("Table %x\n", Table);
889 if (Table == NULL)
890 {
891 return(0);
892 }
893 }
894 TableOffset = PAGE_TO_SECTION_PAGE_TABLE_OFFSET(Offset);
895 Entry = Table->Entry[TableOffset];
896 return(Entry);
897 }
898
899 VOID
900 NTAPI
901 MmSharePageEntrySectionSegment(PMM_SECTION_SEGMENT Segment,
902 ULONG_PTR Offset)
903 {
904 ULONG Entry;
905
906 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
907 if (Entry == 0)
908 {
909 DPRINT1("Entry == 0 for MmSharePageEntrySectionSegment\n");
910 KeBugCheck(MEMORY_MANAGEMENT);
911 }
912 if (SHARE_COUNT_FROM_SSE(Entry) == MAX_SHARE_COUNT)
913 {
914 DPRINT1("Maximum share count reached\n");
915 KeBugCheck(MEMORY_MANAGEMENT);
916 }
917 if (IS_SWAP_FROM_SSE(Entry))
918 {
919 KeBugCheck(MEMORY_MANAGEMENT);
920 }
921 Entry = MAKE_SSE(PAGE_FROM_SSE(Entry), SHARE_COUNT_FROM_SSE(Entry) + 1);
922 MmSetPageEntrySectionSegment(Segment, Offset, Entry);
923 }
924
925 BOOLEAN
926 NTAPI
927 MmUnsharePageEntrySectionSegment(PROS_SECTION_OBJECT Section,
928 PMM_SECTION_SEGMENT Segment,
929 ULONG Offset,
930 BOOLEAN Dirty,
931 BOOLEAN PageOut)
932 {
933 ULONG Entry;
934 BOOLEAN IsDirectMapped = FALSE;
935
936 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
937 if (Entry == 0)
938 {
939 DPRINT1("Entry == 0 for MmUnsharePageEntrySectionSegment\n");
940 KeBugCheck(MEMORY_MANAGEMENT);
941 }
942 if (SHARE_COUNT_FROM_SSE(Entry) == 0)
943 {
944 DPRINT1("Zero share count for unshare\n");
945 KeBugCheck(MEMORY_MANAGEMENT);
946 }
947 if (IS_SWAP_FROM_SSE(Entry))
948 {
949 KeBugCheck(MEMORY_MANAGEMENT);
950 }
951 Entry = MAKE_SSE(PAGE_FROM_SSE(Entry), SHARE_COUNT_FROM_SSE(Entry) - 1);
952 /*
953 * If we reducing the share count of this entry to zero then set the entry
954 * to zero and tell the cache the page is no longer mapped.
955 */
956 if (SHARE_COUNT_FROM_SSE(Entry) == 0)
957 {
958 PFILE_OBJECT FileObject;
959 PBCB Bcb;
960 SWAPENTRY SavedSwapEntry;
961 PFN_NUMBER Page;
962 BOOLEAN IsImageSection;
963 ULONG FileOffset;
964
965 FileOffset = Offset + Segment->FileOffset;
966
967 IsImageSection = Section->AllocationAttributes & SEC_IMAGE ? TRUE : FALSE;
968
969 Page = PFN_FROM_SSE(Entry);
970 FileObject = Section->FileObject;
971 if (FileObject != NULL &&
972 !(Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
973 {
974
975 if ((FileOffset % PAGE_SIZE) == 0 &&
976 (Offset + PAGE_SIZE <= Segment->RawLength || !IsImageSection))
977 {
978 NTSTATUS Status;
979 Bcb = FileObject->SectionObjectPointer->SharedCacheMap;
980 IsDirectMapped = TRUE;
981 #ifndef NEWCC
982 Status = CcRosUnmapCacheSegment(Bcb, FileOffset, Dirty);
983 #else
984 Status = STATUS_SUCCESS;
985 #endif
986 if (!NT_SUCCESS(Status))
987 {
988 DPRINT1("CcRosUnmapCacheSegment failed, status = %x\n", Status);
989 KeBugCheck(MEMORY_MANAGEMENT);
990 }
991 }
992 }
993
994 SavedSwapEntry = MmGetSavedSwapEntryPage(Page);
995 if (SavedSwapEntry == 0)
996 {
997 if (!PageOut &&
998 ((Segment->Flags & MM_PAGEFILE_SEGMENT) ||
999 (Segment->Characteristics & IMAGE_SCN_MEM_SHARED)))
1000 {
1001 /*
1002 * FIXME:
1003 * Try to page out this page and set the swap entry
1004 * within the section segment. There exist no rmap entry
1005 * for this page. The pager thread can't page out a
1006 * page without a rmap entry.
1007 */
1008 MmSetPageEntrySectionSegment(Segment, Offset, Entry);
1009 }
1010 else
1011 {
1012 MmSetPageEntrySectionSegment(Segment, Offset, 0);
1013 if (!IsDirectMapped)
1014 {
1015 MmReleasePageMemoryConsumer(MC_USER, Page);
1016 }
1017 }
1018 }
1019 else
1020 {
1021 if ((Segment->Flags & MM_PAGEFILE_SEGMENT) ||
1022 (Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
1023 {
1024 if (!PageOut)
1025 {
1026 if (Dirty)
1027 {
1028 /*
1029 * FIXME:
1030 * We hold all locks. Nobody can do something with the current
1031 * process and the current segment (also not within an other process).
1032 */
1033 NTSTATUS Status;
1034 Status = MmWriteToSwapPage(SavedSwapEntry, Page);
1035 if (!NT_SUCCESS(Status))
1036 {
1037 DPRINT1("MM: Failed to write to swap page (Status was 0x%.8X)\n", Status);
1038 KeBugCheck(MEMORY_MANAGEMENT);
1039 }
1040 }
1041 MmSetPageEntrySectionSegment(Segment, Offset, MAKE_SWAP_SSE(SavedSwapEntry));
1042 MmSetSavedSwapEntryPage(Page, 0);
1043 }
1044 MmReleasePageMemoryConsumer(MC_USER, Page);
1045 }
1046 else
1047 {
1048 DPRINT1("Found a swapentry for a non private page in an image or data file sgment\n");
1049 KeBugCheck(MEMORY_MANAGEMENT);
1050 }
1051 }
1052 }
1053 else
1054 {
1055 MmSetPageEntrySectionSegment(Segment, Offset, Entry);
1056 }
1057 return(SHARE_COUNT_FROM_SSE(Entry) > 0);
1058 }
1059
1060 BOOLEAN MiIsPageFromCache(PMEMORY_AREA MemoryArea,
1061 ULONG SegOffset)
1062 {
1063 #ifndef NEWCC
1064 if (!(MemoryArea->Data.SectionData.Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
1065 {
1066 PBCB Bcb;
1067 PCACHE_SEGMENT CacheSeg;
1068 Bcb = MemoryArea->Data.SectionData.Section->FileObject->SectionObjectPointer->SharedCacheMap;
1069 CacheSeg = CcRosLookupCacheSegment(Bcb, SegOffset + MemoryArea->Data.SectionData.Segment->FileOffset);
1070 if (CacheSeg)
1071 {
1072 CcRosReleaseCacheSegment(Bcb, CacheSeg, CacheSeg->Valid, FALSE, TRUE);
1073 return TRUE;
1074 }
1075 }
1076 #endif
1077 return FALSE;
1078 }
1079
1080 NTSTATUS
1081 NTAPI
1082 MiCopyFromUserPage(PFN_NUMBER DestPage, PVOID SourceAddress)
1083 {
1084 PEPROCESS Process;
1085 KIRQL Irql;
1086 PVOID TempAddress;
1087
1088 Process = PsGetCurrentProcess();
1089 TempAddress = MiMapPageInHyperSpace(Process, DestPage, &Irql);
1090 if (TempAddress == NULL)
1091 {
1092 return(STATUS_NO_MEMORY);
1093 }
1094 memcpy(TempAddress, SourceAddress, PAGE_SIZE);
1095 MiUnmapPageInHyperSpace(Process, TempAddress, Irql);
1096 return(STATUS_SUCCESS);
1097 }
1098
1099 #ifndef NEWCC
1100 NTSTATUS
1101 NTAPI
1102 MiReadPage(PMEMORY_AREA MemoryArea,
1103 ULONG_PTR SegOffset,
1104 PPFN_NUMBER Page)
1105 /*
1106 * FUNCTION: Read a page for a section backed memory area.
1107 * PARAMETERS:
1108 * MemoryArea - Memory area to read the page for.
1109 * Offset - Offset of the page to read.
1110 * Page - Variable that receives a page contains the read data.
1111 */
1112 {
1113 ULONG BaseOffset;
1114 ULONG_PTR FileOffset;
1115 PVOID BaseAddress;
1116 BOOLEAN UptoDate;
1117 PCACHE_SEGMENT CacheSeg;
1118 PFILE_OBJECT FileObject;
1119 NTSTATUS Status;
1120 ULONG_PTR RawLength;
1121 PBCB Bcb;
1122 BOOLEAN IsImageSection;
1123 ULONG_PTR Length;
1124
1125 FileObject = MemoryArea->Data.SectionData.Section->FileObject;
1126 Bcb = FileObject->SectionObjectPointer->SharedCacheMap;
1127 RawLength = MemoryArea->Data.SectionData.Segment->RawLength;
1128 FileOffset = SegOffset + MemoryArea->Data.SectionData.Segment->FileOffset;
1129 IsImageSection = MemoryArea->Data.SectionData.Section->AllocationAttributes & SEC_IMAGE ? TRUE : FALSE;
1130
1131 ASSERT(Bcb);
1132
1133 DPRINT("%S %x\n", FileObject->FileName.Buffer, FileOffset);
1134
1135 /*
1136 * If the file system is letting us go directly to the cache and the
1137 * memory area was mapped at an offset in the file which is page aligned
1138 * then get the related cache segment.
1139 */
1140 if ((FileOffset % PAGE_SIZE) == 0 &&
1141 (SegOffset + PAGE_SIZE <= RawLength || !IsImageSection) &&
1142 !(MemoryArea->Data.SectionData.Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
1143 {
1144
1145 /*
1146 * Get the related cache segment; we use a lower level interface than
1147 * filesystems do because it is safe for us to use an offset with a
1148 * alignment less than the file system block size.
1149 */
1150 Status = CcRosGetCacheSegment(Bcb,
1151 (ULONG)FileOffset,
1152 &BaseOffset,
1153 &BaseAddress,
1154 &UptoDate,
1155 &CacheSeg);
1156 if (!NT_SUCCESS(Status))
1157 {
1158 return(Status);
1159 }
1160 if (!UptoDate)
1161 {
1162 /*
1163 * If the cache segment isn't up to date then call the file
1164 * system to read in the data.
1165 */
1166 Status = ReadCacheSegment(CacheSeg);
1167 if (!NT_SUCCESS(Status))
1168 {
1169 CcRosReleaseCacheSegment(Bcb, CacheSeg, FALSE, FALSE, FALSE);
1170 return Status;
1171 }
1172 }
1173 /*
1174 * Retrieve the page from the cache segment that we actually want.
1175 */
1176 (*Page) = MmGetPhysicalAddress((char*)BaseAddress +
1177 FileOffset - BaseOffset).LowPart >> PAGE_SHIFT;
1178
1179 CcRosReleaseCacheSegment(Bcb, CacheSeg, TRUE, FALSE, TRUE);
1180 }
1181 else
1182 {
1183 PEPROCESS Process;
1184 KIRQL Irql;
1185 PVOID PageAddr;
1186 ULONG_PTR CacheSegOffset;
1187
1188 /*
1189 * Allocate a page, this is rather complicated by the possibility
1190 * we might have to move other things out of memory
1191 */
1192 MI_SET_USAGE(MI_USAGE_SECTION);
1193 MI_SET_PROCESS2(PsGetCurrentProcess()->ImageFileName);
1194 Status = MmRequestPageMemoryConsumer(MC_USER, TRUE, Page);
1195 if (!NT_SUCCESS(Status))
1196 {
1197 return(Status);
1198 }
1199 Status = CcRosGetCacheSegment(Bcb,
1200 (ULONG)FileOffset,
1201 &BaseOffset,
1202 &BaseAddress,
1203 &UptoDate,
1204 &CacheSeg);
1205 if (!NT_SUCCESS(Status))
1206 {
1207 return(Status);
1208 }
1209 if (!UptoDate)
1210 {
1211 /*
1212 * If the cache segment isn't up to date then call the file
1213 * system to read in the data.
1214 */
1215 Status = ReadCacheSegment(CacheSeg);
1216 if (!NT_SUCCESS(Status))
1217 {
1218 CcRosReleaseCacheSegment(Bcb, CacheSeg, FALSE, FALSE, FALSE);
1219 return Status;
1220 }
1221 }
1222
1223 Process = PsGetCurrentProcess();
1224 PageAddr = MiMapPageInHyperSpace(Process, *Page, &Irql);
1225 CacheSegOffset = BaseOffset + CacheSeg->Bcb->CacheSegmentSize - FileOffset;
1226 Length = RawLength - SegOffset;
1227 if (Length <= CacheSegOffset && Length <= PAGE_SIZE)
1228 {
1229 memcpy(PageAddr, (char*)BaseAddress + FileOffset - BaseOffset, Length);
1230 }
1231 else if (CacheSegOffset >= PAGE_SIZE)
1232 {
1233 memcpy(PageAddr, (char*)BaseAddress + FileOffset - BaseOffset, PAGE_SIZE);
1234 }
1235 else
1236 {
1237 memcpy(PageAddr, (char*)BaseAddress + FileOffset - BaseOffset, CacheSegOffset);
1238 MiUnmapPageInHyperSpace(Process, PageAddr, Irql);
1239 CcRosReleaseCacheSegment(Bcb, CacheSeg, TRUE, FALSE, FALSE);
1240 Status = CcRosGetCacheSegment(Bcb,
1241 (ULONG)(FileOffset + CacheSegOffset),
1242 &BaseOffset,
1243 &BaseAddress,
1244 &UptoDate,
1245 &CacheSeg);
1246 if (!NT_SUCCESS(Status))
1247 {
1248 return(Status);
1249 }
1250 if (!UptoDate)
1251 {
1252 /*
1253 * If the cache segment isn't up to date then call the file
1254 * system to read in the data.
1255 */
1256 Status = ReadCacheSegment(CacheSeg);
1257 if (!NT_SUCCESS(Status))
1258 {
1259 CcRosReleaseCacheSegment(Bcb, CacheSeg, FALSE, FALSE, FALSE);
1260 return Status;
1261 }
1262 }
1263 PageAddr = MiMapPageInHyperSpace(Process, *Page, &Irql);
1264 if (Length < PAGE_SIZE)
1265 {
1266 memcpy((char*)PageAddr + CacheSegOffset, BaseAddress, Length - CacheSegOffset);
1267 }
1268 else
1269 {
1270 memcpy((char*)PageAddr + CacheSegOffset, BaseAddress, PAGE_SIZE - CacheSegOffset);
1271 }
1272 }
1273 MiUnmapPageInHyperSpace(Process, PageAddr, Irql);
1274 CcRosReleaseCacheSegment(Bcb, CacheSeg, TRUE, FALSE, FALSE);
1275 }
1276 return(STATUS_SUCCESS);
1277 }
1278 #else
1279 NTSTATUS
1280 NTAPI
1281 MiReadPage(PMEMORY_AREA MemoryArea,
1282 ULONG SegOffset,
1283 PPFN_NUMBER Page)
1284 /*
1285 * FUNCTION: Read a page for a section backed memory area.
1286 * PARAMETERS:
1287 * MemoryArea - Memory area to read the page for.
1288 * Offset - Offset of the page to read.
1289 * Page - Variable that receives a page contains the read data.
1290 */
1291 {
1292 MM_REQUIRED_RESOURCES Resources = { };
1293
1294 Resources.Context = MemoryArea->Data.SectionData.Section->FileObject;
1295 Resources.FileOffset.QuadPart = SegOffset +
1296 MemoryArea->Data.SectionData.Segment->FileOffset;
1297 Resources.Consumer = MC_USER;
1298 Resources.Amount = PAGE_SIZE;
1299
1300 DPRINT1("%S, offset %x, len %d, page %x\n", ((PFILE_OBJECT)Resources.Context)->FileName.Buffer, Resources.FileOffset.LowPart, Resources.Amount, Resources.Page[0]);
1301
1302 NTSTATUS Status = MiReadFilePage(NULL, NULL, &Resources);
1303 *Page = Resources.Page[0];
1304 return Status;
1305 }
1306 #endif
1307
1308 NTSTATUS
1309 NTAPI
1310 MmNotPresentFaultSectionView(PMMSUPPORT AddressSpace,
1311 MEMORY_AREA* MemoryArea,
1312 PVOID Address)
1313 {
1314 ULONG Offset;
1315 PFN_NUMBER Page;
1316 NTSTATUS Status;
1317 PROS_SECTION_OBJECT Section;
1318 PMM_SECTION_SEGMENT Segment;
1319 ULONG_PTR Entry;
1320 ULONG_PTR Entry1;
1321 ULONG Attributes;
1322 PMM_PAGEOP PageOp;
1323 PMM_REGION Region;
1324 BOOLEAN HasSwapEntry;
1325 PEPROCESS Process = MmGetAddressSpaceOwner(AddressSpace);
1326
1327 /*
1328 * There is a window between taking the page fault and locking the
1329 * address space when another thread could load the page so we check
1330 * that.
1331 */
1332 if (MmIsPagePresent(Process, Address))
1333 {
1334 return(STATUS_SUCCESS);
1335 }
1336
1337 /*
1338 * Check for the virtual memory area being deleted.
1339 */
1340 if (MemoryArea->DeleteInProgress)
1341 {
1342 return(STATUS_UNSUCCESSFUL);
1343 }
1344
1345 Address = MM_ROUND_DOWN(Address, PAGE_SIZE);
1346 Offset = (ULONG)((ULONG_PTR)Address - (ULONG_PTR)MemoryArea->StartingAddress
1347 + MemoryArea->Data.SectionData.ViewOffset);
1348
1349 Segment = MemoryArea->Data.SectionData.Segment;
1350 Section = MemoryArea->Data.SectionData.Section;
1351 Region = MmFindRegion(MemoryArea->StartingAddress,
1352 &MemoryArea->Data.SectionData.RegionListHead,
1353 Address, NULL);
1354 /*
1355 * Lock the segment
1356 */
1357 MmLockSectionSegment(Segment);
1358
1359 /*
1360 * Check if this page needs to be mapped COW
1361 */
1362 if ((Segment->WriteCopy) &&
1363 (Region->Protect == PAGE_READWRITE ||
1364 Region->Protect == PAGE_EXECUTE_READWRITE))
1365 {
1366 Attributes = Region->Protect == PAGE_READWRITE ? PAGE_READONLY : PAGE_EXECUTE_READ;
1367 }
1368 else
1369 {
1370 Attributes = Region->Protect;
1371 }
1372
1373 /*
1374 * Get or create a page operation descriptor
1375 */
1376 PageOp = MmGetPageOp(MemoryArea, NULL, 0, Segment, Offset, MM_PAGEOP_PAGEIN, FALSE);
1377 if (PageOp == NULL)
1378 {
1379 DPRINT1("MmGetPageOp failed\n");
1380 KeBugCheck(MEMORY_MANAGEMENT);
1381 }
1382
1383 /*
1384 * Check if someone else is already handling this fault, if so wait
1385 * for them
1386 */
1387 if (PageOp->Thread != PsGetCurrentThread())
1388 {
1389 MmUnlockSectionSegment(Segment);
1390 MmUnlockAddressSpace(AddressSpace);
1391 Status = MmspWaitForPageOpCompletionEvent(PageOp);
1392 /*
1393 * Check for various strange conditions
1394 */
1395 if (Status != STATUS_SUCCESS)
1396 {
1397 DPRINT1("Failed to wait for page op, status = %x\n", Status);
1398 KeBugCheck(MEMORY_MANAGEMENT);
1399 }
1400 if (PageOp->Status == STATUS_PENDING)
1401 {
1402 DPRINT1("Woke for page op before completion\n");
1403 KeBugCheck(MEMORY_MANAGEMENT);
1404 }
1405 MmLockAddressSpace(AddressSpace);
1406 /*
1407 * If this wasn't a pagein then restart the operation
1408 */
1409 if (PageOp->OpType != MM_PAGEOP_PAGEIN)
1410 {
1411 MmspCompleteAndReleasePageOp(PageOp);
1412 DPRINT("Address 0x%.8X\n", Address);
1413 return(STATUS_MM_RESTART_OPERATION);
1414 }
1415
1416 /*
1417 * If the thread handling this fault has failed then we don't retry
1418 */
1419 if (!NT_SUCCESS(PageOp->Status))
1420 {
1421 Status = PageOp->Status;
1422 MmspCompleteAndReleasePageOp(PageOp);
1423 DPRINT("Address 0x%.8X\n", Address);
1424 return(Status);
1425 }
1426 MmLockSectionSegment(Segment);
1427 /*
1428 * If the completed fault was for another address space then set the
1429 * page in this one.
1430 */
1431 if (!MmIsPagePresent(Process, Address))
1432 {
1433 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
1434 HasSwapEntry = MmIsPageSwapEntry(Process, (PVOID)Address);
1435
1436 if (PAGE_FROM_SSE(Entry) == 0 || HasSwapEntry)
1437 {
1438 /*
1439 * The page was a private page in another or in our address space
1440 */
1441 MmUnlockSectionSegment(Segment);
1442 MmspCompleteAndReleasePageOp(PageOp);
1443 return(STATUS_MM_RESTART_OPERATION);
1444 }
1445
1446 Page = PFN_FROM_SSE(Entry);
1447
1448 MmSharePageEntrySectionSegment(Segment, Offset);
1449
1450 /* FIXME: Should we call MmCreateVirtualMappingUnsafe if
1451 * (Section->AllocationAttributes & SEC_PHYSICALMEMORY) is true?
1452 */
1453 Status = MmCreateVirtualMapping(Process,
1454 Address,
1455 Attributes,
1456 &Page,
1457 1);
1458 if (!NT_SUCCESS(Status))
1459 {
1460 DPRINT1("Unable to create virtual mapping\n");
1461 KeBugCheck(MEMORY_MANAGEMENT);
1462 }
1463 MmInsertRmap(Page, Process, Address);
1464 }
1465 MmUnlockSectionSegment(Segment);
1466 PageOp->Status = STATUS_SUCCESS;
1467 MmspCompleteAndReleasePageOp(PageOp);
1468 DPRINT("Address 0x%.8X\n", Address);
1469 return(STATUS_SUCCESS);
1470 }
1471
1472 HasSwapEntry = MmIsPageSwapEntry(Process, Address);
1473 if (HasSwapEntry)
1474 {
1475 /*
1476 * Must be private page we have swapped out.
1477 */
1478 SWAPENTRY SwapEntry;
1479
1480 /*
1481 * Sanity check
1482 */
1483 if (Segment->Flags & MM_PAGEFILE_SEGMENT)
1484 {
1485 DPRINT1("Found a swaped out private page in a pagefile section.\n");
1486 KeBugCheck(MEMORY_MANAGEMENT);
1487 }
1488
1489 MmUnlockSectionSegment(Segment);
1490 MmDeletePageFileMapping(Process, Address, &SwapEntry);
1491
1492 MmUnlockAddressSpace(AddressSpace);
1493 MI_SET_USAGE(MI_USAGE_SECTION);
1494 if (Process) MI_SET_PROCESS2(Process->ImageFileName);
1495 if (!Process) MI_SET_PROCESS2("Kernel Section");
1496 Status = MmRequestPageMemoryConsumer(MC_USER, TRUE, &Page);
1497 if (!NT_SUCCESS(Status))
1498 {
1499 KeBugCheck(MEMORY_MANAGEMENT);
1500 }
1501
1502 Status = MmReadFromSwapPage(SwapEntry, Page);
1503 if (!NT_SUCCESS(Status))
1504 {
1505 DPRINT1("MmReadFromSwapPage failed, status = %x\n", Status);
1506 KeBugCheck(MEMORY_MANAGEMENT);
1507 }
1508 MmLockAddressSpace(AddressSpace);
1509 Status = MmCreateVirtualMapping(Process,
1510 Address,
1511 Region->Protect,
1512 &Page,
1513 1);
1514 if (!NT_SUCCESS(Status))
1515 {
1516 DPRINT("MmCreateVirtualMapping failed, not out of memory\n");
1517 KeBugCheck(MEMORY_MANAGEMENT);
1518 return(Status);
1519 }
1520
1521 /*
1522 * Store the swap entry for later use.
1523 */
1524 MmSetSavedSwapEntryPage(Page, SwapEntry);
1525
1526 /*
1527 * Add the page to the process's working set
1528 */
1529 MmInsertRmap(Page, Process, Address);
1530 /*
1531 * Finish the operation
1532 */
1533 PageOp->Status = STATUS_SUCCESS;
1534 MmspCompleteAndReleasePageOp(PageOp);
1535 DPRINT("Address 0x%.8X\n", Address);
1536 return(STATUS_SUCCESS);
1537 }
1538
1539 /*
1540 * Satisfying a page fault on a map of /Device/PhysicalMemory is easy
1541 */
1542 if (Section->AllocationAttributes & SEC_PHYSICALMEMORY)
1543 {
1544 MmUnlockSectionSegment(Segment);
1545 /*
1546 * Just map the desired physical page
1547 */
1548 Page = Offset >> PAGE_SHIFT;
1549 Status = MmCreateVirtualMappingUnsafe(Process,
1550 Address,
1551 Region->Protect,
1552 &Page,
1553 1);
1554 if (!NT_SUCCESS(Status))
1555 {
1556 DPRINT("MmCreateVirtualMappingUnsafe failed, not out of memory\n");
1557 KeBugCheck(MEMORY_MANAGEMENT);
1558 return(Status);
1559 }
1560
1561 /*
1562 * Cleanup and release locks
1563 */
1564 PageOp->Status = STATUS_SUCCESS;
1565 MmspCompleteAndReleasePageOp(PageOp);
1566 DPRINT("Address 0x%.8X\n", Address);
1567 return(STATUS_SUCCESS);
1568 }
1569
1570 /*
1571 * Map anonymous memory for BSS sections
1572 */
1573 if (Segment->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
1574 {
1575 MmUnlockSectionSegment(Segment);
1576 MI_SET_USAGE(MI_USAGE_SECTION);
1577 if (Process) MI_SET_PROCESS2(Process->ImageFileName);
1578 if (!Process) MI_SET_PROCESS2("Kernel Section");
1579 Status = MmRequestPageMemoryConsumer(MC_USER, FALSE, &Page);
1580 if (!NT_SUCCESS(Status))
1581 {
1582 MmUnlockAddressSpace(AddressSpace);
1583 Status = MmRequestPageMemoryConsumer(MC_USER, TRUE, &Page);
1584 MmLockAddressSpace(AddressSpace);
1585 }
1586 if (!NT_SUCCESS(Status))
1587 {
1588 KeBugCheck(MEMORY_MANAGEMENT);
1589 }
1590 Status = MmCreateVirtualMapping(Process,
1591 Address,
1592 Region->Protect,
1593 &Page,
1594 1);
1595 if (!NT_SUCCESS(Status))
1596 {
1597 DPRINT("MmCreateVirtualMapping failed, not out of memory\n");
1598 KeBugCheck(MEMORY_MANAGEMENT);
1599 return(Status);
1600 }
1601 MmInsertRmap(Page, Process, Address);
1602
1603 /*
1604 * Cleanup and release locks
1605 */
1606 PageOp->Status = STATUS_SUCCESS;
1607 MmspCompleteAndReleasePageOp(PageOp);
1608 DPRINT("Address 0x%.8X\n", Address);
1609 return(STATUS_SUCCESS);
1610 }
1611
1612 /*
1613 * Get the entry corresponding to the offset within the section
1614 */
1615 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
1616
1617 if (Entry == 0)
1618 {
1619 /*
1620 * If the entry is zero (and it can't change because we have
1621 * locked the segment) then we need to load the page.
1622 */
1623
1624 /*
1625 * Release all our locks and read in the page from disk
1626 */
1627 MmUnlockSectionSegment(Segment);
1628 MmUnlockAddressSpace(AddressSpace);
1629
1630 if ((Segment->Flags & MM_PAGEFILE_SEGMENT) ||
1631 (Offset >= PAGE_ROUND_UP(Segment->RawLength) && Section->AllocationAttributes & SEC_IMAGE))
1632 {
1633 MI_SET_USAGE(MI_USAGE_SECTION);
1634 if (Process) MI_SET_PROCESS2(Process->ImageFileName);
1635 if (!Process) MI_SET_PROCESS2("Kernel Section");
1636 Status = MmRequestPageMemoryConsumer(MC_USER, TRUE, &Page);
1637 if (!NT_SUCCESS(Status))
1638 {
1639 DPRINT1("MmRequestPageMemoryConsumer failed (Status %x)\n", Status);
1640 }
1641
1642 }
1643 else
1644 {
1645 Status = MiReadPage(MemoryArea, Offset, &Page);
1646 if (!NT_SUCCESS(Status))
1647 {
1648 DPRINT1("MiReadPage failed (Status %x)\n", Status);
1649 }
1650 }
1651 if (!NT_SUCCESS(Status))
1652 {
1653 /*
1654 * FIXME: What do we know in this case?
1655 */
1656 /*
1657 * Cleanup and release locks
1658 */
1659 MmLockAddressSpace(AddressSpace);
1660 PageOp->Status = Status;
1661 MmspCompleteAndReleasePageOp(PageOp);
1662 DPRINT("Address 0x%.8X\n", Address);
1663 return(Status);
1664 }
1665 /*
1666 * Relock the address space and segment
1667 */
1668 MmLockAddressSpace(AddressSpace);
1669 MmLockSectionSegment(Segment);
1670
1671 /*
1672 * Check the entry. No one should change the status of a page
1673 * that has a pending page-in.
1674 */
1675 Entry1 = MmGetPageEntrySectionSegment(Segment, Offset);
1676 if (Entry != Entry1)
1677 {
1678 DPRINT1("Someone changed ppte entry while we slept\n");
1679 KeBugCheck(MEMORY_MANAGEMENT);
1680 }
1681
1682 /*
1683 * Mark the offset within the section as having valid, in-memory
1684 * data
1685 */
1686 Entry = MAKE_SSE(Page << PAGE_SHIFT, 1);
1687 MmSetPageEntrySectionSegment(Segment, Offset, Entry);
1688 MmUnlockSectionSegment(Segment);
1689
1690 Status = MmCreateVirtualMapping(Process,
1691 Address,
1692 Attributes,
1693 &Page,
1694 1);
1695 if (!NT_SUCCESS(Status))
1696 {
1697 DPRINT1("Unable to create virtual mapping\n");
1698 KeBugCheck(MEMORY_MANAGEMENT);
1699 }
1700 MmInsertRmap(Page, Process, Address);
1701
1702 PageOp->Status = STATUS_SUCCESS;
1703 MmspCompleteAndReleasePageOp(PageOp);
1704 DPRINT("Address 0x%.8X\n", Address);
1705 return(STATUS_SUCCESS);
1706 }
1707 else if (IS_SWAP_FROM_SSE(Entry))
1708 {
1709 SWAPENTRY SwapEntry;
1710
1711 SwapEntry = SWAPENTRY_FROM_SSE(Entry);
1712
1713 /*
1714 * Release all our locks and read in the page from disk
1715 */
1716 MmUnlockSectionSegment(Segment);
1717
1718 MmUnlockAddressSpace(AddressSpace);
1719 MI_SET_USAGE(MI_USAGE_SECTION);
1720 if (Process) MI_SET_PROCESS2(Process->ImageFileName);
1721 if (!Process) MI_SET_PROCESS2("Kernel Section");
1722 Status = MmRequestPageMemoryConsumer(MC_USER, TRUE, &Page);
1723 if (!NT_SUCCESS(Status))
1724 {
1725 KeBugCheck(MEMORY_MANAGEMENT);
1726 }
1727
1728 Status = MmReadFromSwapPage(SwapEntry, Page);
1729 if (!NT_SUCCESS(Status))
1730 {
1731 KeBugCheck(MEMORY_MANAGEMENT);
1732 }
1733
1734 /*
1735 * Relock the address space and segment
1736 */
1737 MmLockAddressSpace(AddressSpace);
1738 MmLockSectionSegment(Segment);
1739
1740 /*
1741 * Check the entry. No one should change the status of a page
1742 * that has a pending page-in.
1743 */
1744 Entry1 = MmGetPageEntrySectionSegment(Segment, Offset);
1745 if (Entry != Entry1)
1746 {
1747 DPRINT1("Someone changed ppte entry while we slept\n");
1748 KeBugCheck(MEMORY_MANAGEMENT);
1749 }
1750
1751 /*
1752 * Mark the offset within the section as having valid, in-memory
1753 * data
1754 */
1755 Entry = MAKE_SSE(Page << PAGE_SHIFT, 1);
1756 MmSetPageEntrySectionSegment(Segment, Offset, Entry);
1757 MmUnlockSectionSegment(Segment);
1758
1759 /*
1760 * Save the swap entry.
1761 */
1762 MmSetSavedSwapEntryPage(Page, SwapEntry);
1763 Status = MmCreateVirtualMapping(Process,
1764 Address,
1765 Region->Protect,
1766 &Page,
1767 1);
1768 if (!NT_SUCCESS(Status))
1769 {
1770 DPRINT1("Unable to create virtual mapping\n");
1771 KeBugCheck(MEMORY_MANAGEMENT);
1772 }
1773 MmInsertRmap(Page, Process, Address);
1774 PageOp->Status = STATUS_SUCCESS;
1775 MmspCompleteAndReleasePageOp(PageOp);
1776 DPRINT("Address 0x%.8X\n", Address);
1777 return(STATUS_SUCCESS);
1778 }
1779 else
1780 {
1781 /*
1782 * If the section offset is already in-memory and valid then just
1783 * take another reference to the page
1784 */
1785
1786 Page = PFN_FROM_SSE(Entry);
1787
1788 MmSharePageEntrySectionSegment(Segment, Offset);
1789 MmUnlockSectionSegment(Segment);
1790
1791 Status = MmCreateVirtualMapping(Process,
1792 Address,
1793 Attributes,
1794 &Page,
1795 1);
1796 if (!NT_SUCCESS(Status))
1797 {
1798 DPRINT1("Unable to create virtual mapping\n");
1799 KeBugCheck(MEMORY_MANAGEMENT);
1800 }
1801 MmInsertRmap(Page, Process, Address);
1802 PageOp->Status = STATUS_SUCCESS;
1803 MmspCompleteAndReleasePageOp(PageOp);
1804 DPRINT("Address 0x%.8X\n", Address);
1805 return(STATUS_SUCCESS);
1806 }
1807 }
1808
1809 NTSTATUS
1810 NTAPI
1811 MmAccessFaultSectionView(PMMSUPPORT AddressSpace,
1812 MEMORY_AREA* MemoryArea,
1813 PVOID Address)
1814 {
1815 PMM_SECTION_SEGMENT Segment;
1816 PROS_SECTION_OBJECT Section;
1817 PFN_NUMBER OldPage;
1818 PFN_NUMBER NewPage;
1819 NTSTATUS Status;
1820 ULONG Offset;
1821 PMM_PAGEOP PageOp;
1822 PMM_REGION Region;
1823 ULONG Entry;
1824 PEPROCESS Process = MmGetAddressSpaceOwner(AddressSpace);
1825
1826 DPRINT("MmAccessFaultSectionView(%x, %x, %x, %x)\n", AddressSpace, MemoryArea, Address);
1827
1828 /*
1829 * Check if the page has already been set readwrite
1830 */
1831 if (MmGetPageProtect(Process, Address) & PAGE_READWRITE)
1832 {
1833 DPRINT("Address 0x%.8X\n", Address);
1834 return(STATUS_SUCCESS);
1835 }
1836
1837 /*
1838 * Find the offset of the page
1839 */
1840 Address = MM_ROUND_DOWN(Address, PAGE_SIZE);
1841 Offset = (ULONG)((ULONG_PTR)Address - (ULONG_PTR)MemoryArea->StartingAddress
1842 + MemoryArea->Data.SectionData.ViewOffset);
1843
1844 Segment = MemoryArea->Data.SectionData.Segment;
1845 Section = MemoryArea->Data.SectionData.Section;
1846 Region = MmFindRegion(MemoryArea->StartingAddress,
1847 &MemoryArea->Data.SectionData.RegionListHead,
1848 Address, NULL);
1849 /*
1850 * Lock the segment
1851 */
1852 MmLockSectionSegment(Segment);
1853
1854 OldPage = MmGetPfnForProcess(Process, Address);
1855 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
1856
1857 MmUnlockSectionSegment(Segment);
1858
1859 /*
1860 * Check if we are doing COW
1861 */
1862 if (!((Segment->WriteCopy) &&
1863 (Region->Protect == PAGE_READWRITE ||
1864 Region->Protect == PAGE_EXECUTE_READWRITE)))
1865 {
1866 DPRINT("Address 0x%.8X\n", Address);
1867 return(STATUS_ACCESS_VIOLATION);
1868 }
1869
1870 if (IS_SWAP_FROM_SSE(Entry) ||
1871 PFN_FROM_SSE(Entry) != OldPage)
1872 {
1873 /* This is a private page. We must only change the page protection. */
1874 MmSetPageProtect(Process, Address, Region->Protect);
1875 return(STATUS_SUCCESS);
1876 }
1877
1878 /*
1879 * Get or create a pageop
1880 */
1881 PageOp = MmGetPageOp(MemoryArea, NULL, 0, Segment, Offset,
1882 MM_PAGEOP_ACCESSFAULT, FALSE);
1883 if (PageOp == NULL)
1884 {
1885 DPRINT1("MmGetPageOp failed\n");
1886 KeBugCheck(MEMORY_MANAGEMENT);
1887 }
1888
1889 /*
1890 * Wait for any other operations to complete
1891 */
1892 if (PageOp->Thread != PsGetCurrentThread())
1893 {
1894 MmUnlockAddressSpace(AddressSpace);
1895 Status = MmspWaitForPageOpCompletionEvent(PageOp);
1896 /*
1897 * Check for various strange conditions
1898 */
1899 if (Status == STATUS_TIMEOUT)
1900 {
1901 DPRINT1("Failed to wait for page op, status = %x\n", Status);
1902 KeBugCheck(MEMORY_MANAGEMENT);
1903 }
1904 if (PageOp->Status == STATUS_PENDING)
1905 {
1906 DPRINT1("Woke for page op before completion\n");
1907 KeBugCheck(MEMORY_MANAGEMENT);
1908 }
1909 /*
1910 * Restart the operation
1911 */
1912 MmLockAddressSpace(AddressSpace);
1913 MmspCompleteAndReleasePageOp(PageOp);
1914 DPRINT("Address 0x%.8X\n", Address);
1915 return(STATUS_MM_RESTART_OPERATION);
1916 }
1917
1918 /*
1919 * Release locks now we have the pageop
1920 */
1921 MmUnlockAddressSpace(AddressSpace);
1922
1923 /*
1924 * Allocate a page
1925 */
1926 MI_SET_USAGE(MI_USAGE_SECTION);
1927 if (Process) MI_SET_PROCESS2(Process->ImageFileName);
1928 if (!Process) MI_SET_PROCESS2("Kernel Section");
1929 Status = MmRequestPageMemoryConsumer(MC_USER, TRUE, &NewPage);
1930 if (!NT_SUCCESS(Status))
1931 {
1932 KeBugCheck(MEMORY_MANAGEMENT);
1933 }
1934
1935 /*
1936 * Copy the old page
1937 */
1938 MiCopyFromUserPage(NewPage, Address);
1939
1940 MmLockAddressSpace(AddressSpace);
1941 /*
1942 * Delete the old entry.
1943 */
1944 MmDeleteVirtualMapping(Process, Address, FALSE, NULL, NULL);
1945
1946 /*
1947 * Set the PTE to point to the new page
1948 */
1949 Status = MmCreateVirtualMapping(Process,
1950 Address,
1951 Region->Protect,
1952 &NewPage,
1953 1);
1954 if (!NT_SUCCESS(Status))
1955 {
1956 DPRINT("MmCreateVirtualMapping failed, not out of memory\n");
1957 KeBugCheck(MEMORY_MANAGEMENT);
1958 return(Status);
1959 }
1960 if (!NT_SUCCESS(Status))
1961 {
1962 DPRINT1("Unable to create virtual mapping\n");
1963 KeBugCheck(MEMORY_MANAGEMENT);
1964 }
1965
1966 /*
1967 * Unshare the old page.
1968 */
1969 MmDeleteRmap(OldPage, Process, Address);
1970 MmInsertRmap(NewPage, Process, Address);
1971 MmLockSectionSegment(Segment);
1972 MmUnsharePageEntrySectionSegment(Section, Segment, Offset, FALSE, FALSE);
1973 MmUnlockSectionSegment(Segment);
1974
1975 PageOp->Status = STATUS_SUCCESS;
1976 MmspCompleteAndReleasePageOp(PageOp);
1977 DPRINT("Address 0x%.8X\n", Address);
1978 return(STATUS_SUCCESS);
1979 }
1980
1981 VOID
1982 MmPageOutDeleteMapping(PVOID Context, PEPROCESS Process, PVOID Address)
1983 {
1984 MM_SECTION_PAGEOUT_CONTEXT* PageOutContext;
1985 BOOLEAN WasDirty;
1986 PFN_NUMBER Page;
1987
1988 PageOutContext = (MM_SECTION_PAGEOUT_CONTEXT*)Context;
1989 if (Process)
1990 {
1991 MmLockAddressSpace(&Process->Vm);
1992 }
1993
1994 MmDeleteVirtualMapping(Process,
1995 Address,
1996 FALSE,
1997 &WasDirty,
1998 &Page);
1999 if (WasDirty)
2000 {
2001 PageOutContext->WasDirty = TRUE;
2002 }
2003 if (!PageOutContext->Private)
2004 {
2005 MmLockSectionSegment(PageOutContext->Segment);
2006 MmUnsharePageEntrySectionSegment((PROS_SECTION_OBJECT)PageOutContext->Section,
2007 PageOutContext->Segment,
2008 PageOutContext->Offset,
2009 PageOutContext->WasDirty,
2010 TRUE);
2011 MmUnlockSectionSegment(PageOutContext->Segment);
2012 }
2013 if (Process)
2014 {
2015 MmUnlockAddressSpace(&Process->Vm);
2016 }
2017
2018 if (PageOutContext->Private)
2019 {
2020 MmReleasePageMemoryConsumer(MC_USER, Page);
2021 }
2022
2023 DPRINT("PhysicalAddress %x, Address %x\n", Page << PAGE_SHIFT, Address);
2024 }
2025
2026 NTSTATUS
2027 NTAPI
2028 MmPageOutSectionView(PMMSUPPORT AddressSpace,
2029 MEMORY_AREA* MemoryArea,
2030 PVOID Address,
2031 PMM_PAGEOP PageOp)
2032 {
2033 PFN_NUMBER Page;
2034 MM_SECTION_PAGEOUT_CONTEXT Context;
2035 SWAPENTRY SwapEntry;
2036 ULONG Entry;
2037 ULONG FileOffset;
2038 NTSTATUS Status;
2039 PFILE_OBJECT FileObject;
2040 #ifndef NEWCC
2041 PBCB Bcb = NULL;
2042 #endif
2043 BOOLEAN DirectMapped;
2044 BOOLEAN IsImageSection;
2045 PEPROCESS Process = MmGetAddressSpaceOwner(AddressSpace);
2046 KIRQL OldIrql;
2047
2048 Address = (PVOID)PAGE_ROUND_DOWN(Address);
2049
2050 /*
2051 * Get the segment and section.
2052 */
2053 Context.Segment = MemoryArea->Data.SectionData.Segment;
2054 Context.Section = MemoryArea->Data.SectionData.Section;
2055
2056 Context.Offset = (ULONG)((ULONG_PTR)Address - (ULONG_PTR)MemoryArea->StartingAddress
2057 + MemoryArea->Data.SectionData.ViewOffset);
2058 FileOffset = Context.Offset + Context.Segment->FileOffset;
2059
2060 IsImageSection = Context.Section->AllocationAttributes & SEC_IMAGE ? TRUE : FALSE;
2061
2062 FileObject = Context.Section->FileObject;
2063 DirectMapped = FALSE;
2064 #ifndef NEWCC
2065 if (FileObject != NULL &&
2066 !(Context.Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
2067 {
2068 Bcb = FileObject->SectionObjectPointer->SharedCacheMap;
2069
2070 /*
2071 * If the file system is letting us go directly to the cache and the
2072 * memory area was mapped at an offset in the file which is page aligned
2073 * then note this is a direct mapped page.
2074 */
2075 if ((FileOffset % PAGE_SIZE) == 0 &&
2076 (Context.Offset + PAGE_SIZE <= Context.Segment->RawLength || !IsImageSection))
2077 {
2078 DirectMapped = TRUE;
2079 }
2080 }
2081 #endif
2082
2083
2084 /*
2085 * This should never happen since mappings of physical memory are never
2086 * placed in the rmap lists.
2087 */
2088 if (Context.Section->AllocationAttributes & SEC_PHYSICALMEMORY)
2089 {
2090 DPRINT1("Trying to page out from physical memory section address 0x%X "
2091 "process %d\n", Address,
2092 Process ? Process->UniqueProcessId : 0);
2093 KeBugCheck(MEMORY_MANAGEMENT);
2094 }
2095
2096 /*
2097 * Get the section segment entry and the physical address.
2098 */
2099 Entry = MmGetPageEntrySectionSegment(Context.Segment, Context.Offset);
2100 if (!MmIsPagePresent(Process, Address))
2101 {
2102 DPRINT1("Trying to page out not-present page at (%d,0x%.8X).\n",
2103 Process ? Process->UniqueProcessId : 0, Address);
2104 KeBugCheck(MEMORY_MANAGEMENT);
2105 }
2106 Page = MmGetPfnForProcess(Process, Address);
2107 SwapEntry = MmGetSavedSwapEntryPage(Page);
2108
2109 /*
2110 * Prepare the context structure for the rmap delete call.
2111 */
2112 Context.WasDirty = FALSE;
2113 if (Context.Segment->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA ||
2114 IS_SWAP_FROM_SSE(Entry) ||
2115 PFN_FROM_SSE(Entry) != Page)
2116 {
2117 Context.Private = TRUE;
2118 }
2119 else
2120 {
2121 Context.Private = FALSE;
2122 }
2123
2124 /*
2125 * Take an additional reference to the page or the cache segment.
2126 */
2127 if (DirectMapped && !Context.Private)
2128 {
2129 if(!MiIsPageFromCache(MemoryArea, Context.Offset))
2130 {
2131 DPRINT1("Direct mapped non private page is not associated with the cache.\n");
2132 KeBugCheck(MEMORY_MANAGEMENT);
2133 }
2134 }
2135 else
2136 {
2137 OldIrql = KeAcquireQueuedSpinLock(LockQueuePfnLock);
2138 MmReferencePage(Page);
2139 KeReleaseQueuedSpinLock(LockQueuePfnLock, OldIrql);
2140 }
2141
2142 MmDeleteAllRmaps(Page, (PVOID)&Context, MmPageOutDeleteMapping);
2143
2144 /*
2145 * If this wasn't a private page then we should have reduced the entry to
2146 * zero by deleting all the rmaps.
2147 */
2148 if (!Context.Private && MmGetPageEntrySectionSegment(Context.Segment, Context.Offset) != 0)
2149 {
2150 if (!(Context.Segment->Flags & MM_PAGEFILE_SEGMENT) &&
2151 !(Context.Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
2152 {
2153 KeBugCheck(MEMORY_MANAGEMENT);
2154 }
2155 }
2156
2157 /*
2158 * If the page wasn't dirty then we can just free it as for a readonly page.
2159 * Since we unmapped all the mappings above we know it will not suddenly
2160 * become dirty.
2161 * If the page is from a pagefile section and has no swap entry,
2162 * we can't free the page at this point.
2163 */
2164 SwapEntry = MmGetSavedSwapEntryPage(Page);
2165 if (Context.Segment->Flags & MM_PAGEFILE_SEGMENT)
2166 {
2167 if (Context.Private)
2168 {
2169 DPRINT1("Found a %s private page (address %x) in a pagefile segment.\n",
2170 Context.WasDirty ? "dirty" : "clean", Address);
2171 KeBugCheck(MEMORY_MANAGEMENT);
2172 }
2173 if (!Context.WasDirty && SwapEntry != 0)
2174 {
2175 MmSetSavedSwapEntryPage(Page, 0);
2176 MmSetPageEntrySectionSegment(Context.Segment, Context.Offset, MAKE_SWAP_SSE(SwapEntry));
2177 MmReleasePageMemoryConsumer(MC_USER, Page);
2178 PageOp->Status = STATUS_SUCCESS;
2179 MmspCompleteAndReleasePageOp(PageOp);
2180 return(STATUS_SUCCESS);
2181 }
2182 }
2183 else if (Context.Segment->Characteristics & IMAGE_SCN_MEM_SHARED)
2184 {
2185 if (Context.Private)
2186 {
2187 DPRINT1("Found a %s private page (address %x) in a shared section segment.\n",
2188 Context.WasDirty ? "dirty" : "clean", Address);
2189 KeBugCheck(MEMORY_MANAGEMENT);
2190 }
2191 if (!Context.WasDirty || SwapEntry != 0)
2192 {
2193 MmSetSavedSwapEntryPage(Page, 0);
2194 if (SwapEntry != 0)
2195 {
2196 MmSetPageEntrySectionSegment(Context.Segment, Context.Offset, MAKE_SWAP_SSE(SwapEntry));
2197 }
2198 MmReleasePageMemoryConsumer(MC_USER, Page);
2199 PageOp->Status = STATUS_SUCCESS;
2200 MmspCompleteAndReleasePageOp(PageOp);
2201 return(STATUS_SUCCESS);
2202 }
2203 }
2204 else if (!Context.Private && DirectMapped)
2205 {
2206 if (SwapEntry != 0)
2207 {
2208 DPRINT1("Found a swapentry for a non private and direct mapped page (address %x)\n",
2209 Address);
2210 KeBugCheck(MEMORY_MANAGEMENT);
2211 }
2212 #ifndef NEWCC
2213 Status = CcRosUnmapCacheSegment(Bcb, FileOffset, FALSE);
2214 #else
2215 Status = STATUS_SUCCESS;
2216 #endif
2217 if (!NT_SUCCESS(Status))
2218 {
2219 DPRINT1("CCRosUnmapCacheSegment failed, status = %x\n", Status);
2220 KeBugCheck(MEMORY_MANAGEMENT);
2221 }
2222 PageOp->Status = STATUS_SUCCESS;
2223 MmspCompleteAndReleasePageOp(PageOp);
2224 return(STATUS_SUCCESS);
2225 }
2226 else if (!Context.WasDirty && !DirectMapped && !Context.Private)
2227 {
2228 if (SwapEntry != 0)
2229 {
2230 DPRINT1("Found a swap entry for a non dirty, non private and not direct mapped page (address %x)\n",
2231 Address);
2232 KeBugCheck(MEMORY_MANAGEMENT);
2233 }
2234 MmReleasePageMemoryConsumer(MC_USER, Page);
2235 PageOp->Status = STATUS_SUCCESS;
2236 MmspCompleteAndReleasePageOp(PageOp);
2237 return(STATUS_SUCCESS);
2238 }
2239 else if (!Context.WasDirty && Context.Private && SwapEntry != 0)
2240 {
2241 MmSetSavedSwapEntryPage(Page, 0);
2242 MmLockAddressSpace(AddressSpace);
2243 Status = MmCreatePageFileMapping(Process,
2244 Address,
2245 SwapEntry);
2246 MmUnlockAddressSpace(AddressSpace);
2247 if (!NT_SUCCESS(Status))
2248 {
2249 KeBugCheck(MEMORY_MANAGEMENT);
2250 }
2251 MmReleasePageMemoryConsumer(MC_USER, Page);
2252 PageOp->Status = STATUS_SUCCESS;
2253 MmspCompleteAndReleasePageOp(PageOp);
2254 return(STATUS_SUCCESS);
2255 }
2256
2257 /*
2258 * If necessary, allocate an entry in the paging file for this page
2259 */
2260 if (SwapEntry == 0)
2261 {
2262 SwapEntry = MmAllocSwapPage();
2263 if (SwapEntry == 0)
2264 {
2265 MmShowOutOfSpaceMessagePagingFile();
2266 MmLockAddressSpace(AddressSpace);
2267 /*
2268 * For private pages restore the old mappings.
2269 */
2270 if (Context.Private)
2271 {
2272 Status = MmCreateVirtualMapping(Process,
2273 Address,
2274 MemoryArea->Protect,
2275 &Page,
2276 1);
2277 MmSetDirtyPage(Process, Address);
2278 MmInsertRmap(Page,
2279 Process,
2280 Address);
2281 }
2282 else
2283 {
2284 /*
2285 * For non-private pages if the page wasn't direct mapped then
2286 * set it back into the section segment entry so we don't loose
2287 * our copy. Otherwise it will be handled by the cache manager.
2288 */
2289 Status = MmCreateVirtualMapping(Process,
2290 Address,
2291 MemoryArea->Protect,
2292 &Page,
2293 1);
2294 MmSetDirtyPage(Process, Address);
2295 MmInsertRmap(Page,
2296 Process,
2297 Address);
2298 Entry = MAKE_SSE(Page << PAGE_SHIFT, 1);
2299 MmSetPageEntrySectionSegment(Context.Segment, Context.Offset, Entry);
2300 }
2301 MmUnlockAddressSpace(AddressSpace);
2302 PageOp->Status = STATUS_UNSUCCESSFUL;
2303 MmspCompleteAndReleasePageOp(PageOp);
2304 return(STATUS_PAGEFILE_QUOTA);
2305 }
2306 }
2307
2308 /*
2309 * Write the page to the pagefile
2310 */
2311 Status = MmWriteToSwapPage(SwapEntry, Page);
2312 if (!NT_SUCCESS(Status))
2313 {
2314 DPRINT1("MM: Failed to write to swap page (Status was 0x%.8X)\n",
2315 Status);
2316 /*
2317 * As above: undo our actions.
2318 * FIXME: Also free the swap page.
2319 */
2320 MmLockAddressSpace(AddressSpace);
2321 if (Context.Private)
2322 {
2323 Status = MmCreateVirtualMapping(Process,
2324 Address,
2325 MemoryArea->Protect,
2326 &Page,
2327 1);
2328 MmSetDirtyPage(Process, Address);
2329 MmInsertRmap(Page,
2330 Process,
2331 Address);
2332 }
2333 else
2334 {
2335 Status = MmCreateVirtualMapping(Process,
2336 Address,
2337 MemoryArea->Protect,
2338 &Page,
2339 1);
2340 MmSetDirtyPage(Process, Address);
2341 MmInsertRmap(Page,
2342 Process,
2343 Address);
2344 Entry = MAKE_SSE(Page << PAGE_SHIFT, 1);
2345 MmSetPageEntrySectionSegment(Context.Segment, Context.Offset, Entry);
2346 }
2347 MmUnlockAddressSpace(AddressSpace);
2348 PageOp->Status = STATUS_UNSUCCESSFUL;
2349 MmspCompleteAndReleasePageOp(PageOp);
2350 return(STATUS_UNSUCCESSFUL);
2351 }
2352
2353 /*
2354 * Otherwise we have succeeded.
2355 */
2356 DPRINT("MM: Wrote section page 0x%.8X to swap!\n", Page << PAGE_SHIFT);
2357 MmSetSavedSwapEntryPage(Page, 0);
2358 if (Context.Segment->Flags & MM_PAGEFILE_SEGMENT ||
2359 Context.Segment->Characteristics & IMAGE_SCN_MEM_SHARED)
2360 {
2361 MmSetPageEntrySectionSegment(Context.Segment, Context.Offset, MAKE_SWAP_SSE(SwapEntry));
2362 }
2363 else
2364 {
2365 MmReleasePageMemoryConsumer(MC_USER, Page);
2366 }
2367
2368 if (Context.Private)
2369 {
2370 MmLockAddressSpace(AddressSpace);
2371 Status = MmCreatePageFileMapping(Process,
2372 Address,
2373 SwapEntry);
2374 MmUnlockAddressSpace(AddressSpace);
2375 if (!NT_SUCCESS(Status))
2376 {
2377 KeBugCheck(MEMORY_MANAGEMENT);
2378 }
2379 }
2380 else
2381 {
2382 Entry = MAKE_SWAP_SSE(SwapEntry);
2383 MmSetPageEntrySectionSegment(Context.Segment, Context.Offset, Entry);
2384 }
2385
2386 PageOp->Status = STATUS_SUCCESS;
2387 MmspCompleteAndReleasePageOp(PageOp);
2388 return(STATUS_SUCCESS);
2389 }
2390
2391 NTSTATUS
2392 NTAPI
2393 MmWritePageSectionView(PMMSUPPORT AddressSpace,
2394 PMEMORY_AREA MemoryArea,
2395 PVOID Address,
2396 PMM_PAGEOP PageOp)
2397 {
2398 ULONG_PTR Offset;
2399 PROS_SECTION_OBJECT Section;
2400 PMM_SECTION_SEGMENT Segment;
2401 PFN_NUMBER Page;
2402 SWAPENTRY SwapEntry;
2403 ULONG Entry;
2404 BOOLEAN Private;
2405 NTSTATUS Status;
2406 PFILE_OBJECT FileObject;
2407 PBCB Bcb = NULL;
2408 BOOLEAN DirectMapped;
2409 BOOLEAN IsImageSection;
2410 PEPROCESS Process = MmGetAddressSpaceOwner(AddressSpace);
2411
2412 Address = (PVOID)PAGE_ROUND_DOWN(Address);
2413
2414 Offset = (ULONG_PTR)Address - (ULONG_PTR)MemoryArea->StartingAddress
2415 + MemoryArea->Data.SectionData.ViewOffset;
2416
2417 /*
2418 * Get the segment and section.
2419 */
2420 Segment = MemoryArea->Data.SectionData.Segment;
2421 Section = MemoryArea->Data.SectionData.Section;
2422 IsImageSection = Section->AllocationAttributes & SEC_IMAGE ? TRUE : FALSE;
2423
2424 FileObject = Section->FileObject;
2425 DirectMapped = FALSE;
2426 if (FileObject != NULL &&
2427 !(Segment->Characteristics & IMAGE_SCN_MEM_SHARED))
2428 {
2429 Bcb = FileObject->SectionObjectPointer->SharedCacheMap;
2430
2431 /*
2432 * If the file system is letting us go directly to the cache and the
2433 * memory area was mapped at an offset in the file which is page aligned
2434 * then note this is a direct mapped page.
2435 */
2436 if (((Offset + Segment->FileOffset) % PAGE_SIZE) == 0 &&
2437 (Offset + PAGE_SIZE <= Segment->RawLength || !IsImageSection))
2438 {
2439 DirectMapped = TRUE;
2440 }
2441 }
2442
2443 /*
2444 * This should never happen since mappings of physical memory are never
2445 * placed in the rmap lists.
2446 */
2447 if (Section->AllocationAttributes & SEC_PHYSICALMEMORY)
2448 {
2449 DPRINT1("Trying to write back page from physical memory mapped at %X "
2450 "process %d\n", Address,
2451 Process ? Process->UniqueProcessId : 0);
2452 KeBugCheck(MEMORY_MANAGEMENT);
2453 }
2454
2455 /*
2456 * Get the section segment entry and the physical address.
2457 */
2458 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
2459 if (!MmIsPagePresent(Process, Address))
2460 {
2461 DPRINT1("Trying to page out not-present page at (%d,0x%.8X).\n",
2462 Process ? Process->UniqueProcessId : 0, Address);
2463 KeBugCheck(MEMORY_MANAGEMENT);
2464 }
2465 Page = MmGetPfnForProcess(Process, Address);
2466 SwapEntry = MmGetSavedSwapEntryPage(Page);
2467
2468 /*
2469 * Check for a private (COWed) page.
2470 */
2471 if (Segment->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA ||
2472 IS_SWAP_FROM_SSE(Entry) ||
2473 PFN_FROM_SSE(Entry) != Page)
2474 {
2475 Private = TRUE;
2476 }
2477 else
2478 {
2479 Private = FALSE;
2480 }
2481
2482 /*
2483 * Speculatively set all mappings of the page to clean.
2484 */
2485 MmSetCleanAllRmaps(Page);
2486
2487 /*
2488 * If this page was direct mapped from the cache then the cache manager
2489 * will take care of writing it back to disk.
2490 */
2491 if (DirectMapped && !Private)
2492 {
2493 ASSERT(SwapEntry == 0);
2494 #ifndef NEWCC
2495 CcRosMarkDirtyCacheSegment(Bcb, (ULONG)Offset + Segment->FileOffset);
2496 #endif
2497 PageOp->Status = STATUS_SUCCESS;
2498 MmspCompleteAndReleasePageOp(PageOp);
2499 return(STATUS_SUCCESS);
2500 }
2501
2502 /*
2503 * If necessary, allocate an entry in the paging file for this page
2504 */
2505 if (SwapEntry == 0)
2506 {
2507 SwapEntry = MmAllocSwapPage();
2508 if (SwapEntry == 0)
2509 {
2510 MmSetDirtyAllRmaps(Page);
2511 PageOp->Status = STATUS_UNSUCCESSFUL;
2512 MmspCompleteAndReleasePageOp(PageOp);
2513 return(STATUS_PAGEFILE_QUOTA);
2514 }
2515 MmSetSavedSwapEntryPage(Page, SwapEntry);
2516 }
2517
2518 /*
2519 * Write the page to the pagefile
2520 */
2521 Status = MmWriteToSwapPage(SwapEntry, Page);
2522 if (!NT_SUCCESS(Status))
2523 {
2524 DPRINT1("MM: Failed to write to swap page (Status was 0x%.8X)\n",
2525 Status);
2526 MmSetDirtyAllRmaps(Page);
2527 PageOp->Status = STATUS_UNSUCCESSFUL;
2528 MmspCompleteAndReleasePageOp(PageOp);
2529 return(STATUS_UNSUCCESSFUL);
2530 }
2531
2532 /*
2533 * Otherwise we have succeeded.
2534 */
2535 DPRINT("MM: Wrote section page 0x%.8X to swap!\n", Page << PAGE_SHIFT);
2536 PageOp->Status = STATUS_SUCCESS;
2537 MmspCompleteAndReleasePageOp(PageOp);
2538 return(STATUS_SUCCESS);
2539 }
2540
2541 static VOID
2542 MmAlterViewAttributes(PMMSUPPORT AddressSpace,
2543 PVOID BaseAddress,
2544 SIZE_T RegionSize,
2545 ULONG OldType,
2546 ULONG OldProtect,
2547 ULONG NewType,
2548 ULONG NewProtect)
2549 {
2550 PMEMORY_AREA MemoryArea;
2551 PMM_SECTION_SEGMENT Segment;
2552 BOOLEAN DoCOW = FALSE;
2553 ULONG i;
2554 PEPROCESS Process = MmGetAddressSpaceOwner(AddressSpace);
2555
2556 MemoryArea = MmLocateMemoryAreaByAddress(AddressSpace, BaseAddress);
2557 ASSERT(MemoryArea);
2558 Segment = MemoryArea->Data.SectionData.Segment;
2559
2560 if ((Segment->WriteCopy) &&
2561 (NewProtect == PAGE_READWRITE || NewProtect == PAGE_EXECUTE_READWRITE))
2562 {
2563 DoCOW = TRUE;
2564 }
2565
2566 if (OldProtect != NewProtect)
2567 {
2568 for (i = 0; i < PAGE_ROUND_UP(RegionSize) / PAGE_SIZE; i++)
2569 {
2570 PVOID Address = (char*)BaseAddress + (i * PAGE_SIZE);
2571 ULONG Protect = NewProtect;
2572
2573 /*
2574 * If we doing COW for this segment then check if the page is
2575 * already private.
2576 */
2577 if (DoCOW && MmIsPagePresent(Process, Address))
2578 {
2579 ULONG_PTR Offset;
2580 ULONG Entry;
2581 PFN_NUMBER Page;
2582
2583 Offset = (ULONG_PTR)Address - (ULONG_PTR)MemoryArea->StartingAddress
2584 + MemoryArea->Data.SectionData.ViewOffset;
2585 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
2586 Page = MmGetPfnForProcess(Process, Address);
2587
2588 Protect = PAGE_READONLY;
2589 if (Segment->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA ||
2590 IS_SWAP_FROM_SSE(Entry) ||
2591 PFN_FROM_SSE(Entry) != Page)
2592 {
2593 Protect = NewProtect;
2594 }
2595 }
2596
2597 if (MmIsPagePresent(Process, Address))
2598 {
2599 MmSetPageProtect(Process, Address,
2600 Protect);
2601 }
2602 }
2603 }
2604 }
2605
2606 NTSTATUS
2607 NTAPI
2608 MmProtectSectionView(PMMSUPPORT AddressSpace,
2609 PMEMORY_AREA MemoryArea,
2610 PVOID BaseAddress,
2611 SIZE_T Length,
2612 ULONG Protect,
2613 PULONG OldProtect)
2614 {
2615 PMM_REGION Region;
2616 NTSTATUS Status;
2617 ULONG_PTR MaxLength;
2618
2619 MaxLength = (ULONG_PTR)MemoryArea->EndingAddress - (ULONG_PTR)BaseAddress;
2620 if (Length > MaxLength)
2621 Length = (ULONG)MaxLength;
2622
2623 Region = MmFindRegion(MemoryArea->StartingAddress,
2624 &MemoryArea->Data.SectionData.RegionListHead,
2625 BaseAddress, NULL);
2626 if ((MemoryArea->Flags & SEC_NO_CHANGE) &&
2627 Region->Protect != Protect)
2628 {
2629 return STATUS_INVALID_PAGE_PROTECTION;
2630 }
2631
2632 *OldProtect = Region->Protect;
2633 Status = MmAlterRegion(AddressSpace, MemoryArea->StartingAddress,
2634 &MemoryArea->Data.SectionData.RegionListHead,
2635 BaseAddress, Length, Region->Type, Protect,
2636 MmAlterViewAttributes);
2637
2638 return(Status);
2639 }
2640
2641 NTSTATUS NTAPI
2642 MmQuerySectionView(PMEMORY_AREA MemoryArea,
2643 PVOID Address,
2644 PMEMORY_BASIC_INFORMATION Info,
2645 PSIZE_T ResultLength)
2646 {
2647 PMM_REGION Region;
2648 PVOID RegionBaseAddress;
2649 PROS_SECTION_OBJECT Section;
2650 PMM_SECTION_SEGMENT Segment;
2651
2652 Region = MmFindRegion((PVOID)MemoryArea->StartingAddress,
2653 &MemoryArea->Data.SectionData.RegionListHead,
2654 Address, &RegionBaseAddress);
2655 if (Region == NULL)
2656 {
2657 return STATUS_UNSUCCESSFUL;
2658 }
2659
2660 Section = MemoryArea->Data.SectionData.Section;
2661 if (Section->AllocationAttributes & SEC_IMAGE)
2662 {
2663 Segment = MemoryArea->Data.SectionData.Segment;
2664 Info->AllocationBase = (PUCHAR)MemoryArea->StartingAddress - Segment->VirtualAddress;
2665 Info->Type = MEM_IMAGE;
2666 }
2667 else
2668 {
2669 Info->AllocationBase = MemoryArea->StartingAddress;
2670 Info->Type = MEM_MAPPED;
2671 }
2672 Info->BaseAddress = RegionBaseAddress;
2673 Info->AllocationProtect = MemoryArea->Protect;
2674 Info->RegionSize = Region->Length;
2675 Info->State = MEM_COMMIT;
2676 Info->Protect = Region->Protect;
2677
2678 *ResultLength = sizeof(MEMORY_BASIC_INFORMATION);
2679 return(STATUS_SUCCESS);
2680 }
2681
2682 VOID
2683 NTAPI
2684 MmpFreePageFileSegment(PMM_SECTION_SEGMENT Segment)
2685 {
2686 ULONG Length;
2687 ULONG Offset;
2688 ULONG Entry;
2689 SWAPENTRY SavedSwapEntry;
2690 PFN_NUMBER Page;
2691
2692 Page = 0;
2693
2694 Length = PAGE_ROUND_UP(Segment->Length);
2695 for (Offset = 0; Offset < Length; Offset += PAGE_SIZE)
2696 {
2697 Entry = MmGetPageEntrySectionSegment(Segment, Offset);
2698 if (Entry)
2699 {
2700 if (IS_SWAP_FROM_SSE(Entry))
2701 {
2702 MmFreeSwapPage(SWAPENTRY_FROM_SSE(Entry));
2703 }
2704 else
2705 {
2706 Page = PFN_FROM_SSE(Entry);
2707 SavedSwapEntry = MmGetSavedSwapEntryPage(Page);
2708 if (SavedSwapEntry != 0)
2709 {
2710 MmSetSavedSwapEntryPage(Page, 0);
2711 MmFreeSwapPage(SavedSwapEntry);
2712 }
2713 MmReleasePageMemoryConsumer(MC_USER, Page);
2714 }
2715 MmSetPageEntrySectionSegment(Segment, Offset, 0);
2716 }
2717 }
2718 }
2719
2720 VOID NTAPI
2721 MmpDeleteSection(PVOID ObjectBody)
2722 {
2723 PROS_SECTION_OBJECT Section = (PROS_SECTION_OBJECT)ObjectBody;
2724
2725 DPRINT("MmpDeleteSection(ObjectBody %x)\n", ObjectBody);
2726 if (Section->AllocationAttributes & SEC_IMAGE)
2727 {
2728 ULONG i;
2729 ULONG NrSegments;
2730 ULONG RefCount;
2731 PMM_SECTION_SEGMENT SectionSegments;
2732
2733 /*
2734 * NOTE: Section->ImageSection can be NULL for short time
2735 * during the section creating. If we fail for some reason
2736 * until the image section is properly initialized we shouldn't
2737 * process further here.
2738 */
2739 if (Section->ImageSection == NULL)
2740 return;
2741
2742 SectionSegments = Section->ImageSection->Segments;
2743 NrSegments = Section->ImageSection->NrSegments;
2744
2745 for (i = 0; i < NrSegments; i++)
2746 {
2747 if (SectionSegments[i].Characteristics & IMAGE_SCN_MEM_SHARED)
2748 {
2749 MmLockSectionSegment(&SectionSegments[i]);
2750 }
2751 RefCount = InterlockedDecrementUL(&SectionSegments[i].ReferenceCount);
2752 if (SectionSegments[i].Characteristics & IMAGE_SCN_MEM_SHARED)
2753 {
2754 if (RefCount == 0)
2755 {
2756 MmpFreePageFileSegment(&SectionSegments[i]);
2757 }
2758 MmUnlockSectionSegment(&SectionSegments[i]);
2759 }
2760 }
2761 }
2762 else
2763 {
2764 /*
2765 * NOTE: Section->Segment can be NULL for short time
2766 * during the section creating.
2767 */
2768 if (Section->Segment == NULL)
2769 return;
2770
2771 if (Section->Segment->Flags & MM_PAGEFILE_SEGMENT)
2772 {
2773 MmpFreePageFileSegment(Section->Segment);
2774 MmFreePageTablesSectionSegment(Section->Segment);
2775 ExFreePool(Section->Segment);
2776 Section->Segment = NULL;
2777 }
2778 else
2779 {
2780 (void)InterlockedDecrementUL(&Section->Segment->ReferenceCount);
2781 }
2782 }
2783 if (Section->FileObject != NULL)
2784 {
2785 #ifndef NEWCC
2786 CcRosDereferenceCache(Section->FileObject);
2787 #endif
2788 ObDereferenceObject(Section->FileObject);
2789 Section->FileObject = NULL;
2790 }
2791 }
2792
2793 VOID NTAPI
2794 MmpCloseSection(IN PEPROCESS Process OPTIONAL,
2795 IN PVOID Object,
2796 IN ACCESS_MASK GrantedAccess,
2797 IN ULONG ProcessHandleCount,
2798 IN ULONG SystemHandleCount)
2799 {
2800 DPRINT("MmpCloseSection(OB %x, HC %d)\n",
2801 Object, ProcessHandleCount);
2802 }
2803
2804 NTSTATUS
2805 INIT_FUNCTION
2806 NTAPI
2807 MmCreatePhysicalMemorySection(VOID)
2808 {
2809 PROS_SECTION_OBJECT PhysSection;
2810 NTSTATUS Status;
2811 OBJECT_ATTRIBUTES Obj;
2812 UNICODE_STRING Name = RTL_CONSTANT_STRING(L"\\Device\\PhysicalMemory");
2813 LARGE_INTEGER SectionSize;
2814 HANDLE Handle;
2815
2816 /*
2817 * Create the section mapping physical memory
2818 */
2819 SectionSize.QuadPart = 0xFFFFFFFF;
2820 InitializeObjectAttributes(&Obj,
2821 &Name,
2822 OBJ_PERMANENT,
2823 NULL,
2824 NULL);
2825 Status = MmCreateSection((PVOID)&PhysSection,
2826 SECTION_ALL_ACCESS,
2827 &Obj,
2828 &SectionSize,
2829 PAGE_EXECUTE_READWRITE,
2830 0,
2831 NULL,
2832 NULL);
2833 if (!NT_SUCCESS(Status))
2834 {
2835 DPRINT1("Failed to create PhysicalMemory section\n");
2836 KeBugCheck(MEMORY_MANAGEMENT);
2837 }
2838 Status = ObInsertObject(PhysSection,
2839 NULL,
2840 SECTION_ALL_ACCESS,
2841 0,
2842 NULL,
2843 &Handle);
2844 if (!NT_SUCCESS(Status))
2845 {
2846 ObDereferenceObject(PhysSection);
2847 }
2848 ObCloseHandle(Handle, KernelMode);
2849 PhysSection->AllocationAttributes |= SEC_PHYSICALMEMORY;
2850 PhysSection->Segment->Flags &= ~MM_PAGEFILE_SEGMENT;
2851
2852 return(STATUS_SUCCESS);
2853 }
2854
2855 NTSTATUS
2856 INIT_FUNCTION
2857 NTAPI
2858 MmInitSectionImplementation(VOID)
2859 {
2860 OBJECT_TYPE_INITIALIZER ObjectTypeInitializer;
2861 UNICODE_STRING Name;
2862
2863 DPRINT("Creating Section Object Type\n");
2864
2865 /* Initialize the Section object type */
2866 RtlZeroMemory(&ObjectTypeInitializer, sizeof(ObjectTypeInitializer));
2867 RtlInitUnicodeString(&Name, L"Section");
2868 ObjectTypeInitializer.Length = sizeof(ObjectTypeInitializer);
2869 ObjectTypeInitializer.DefaultPagedPoolCharge = sizeof(ROS_SECTION_OBJECT);
2870 ObjectTypeInitializer.PoolType = PagedPool;
2871 ObjectTypeInitializer.UseDefaultObject = TRUE;
2872 ObjectTypeInitializer.GenericMapping = MmpSectionMapping;
2873 ObjectTypeInitializer.DeleteProcedure = MmpDeleteSection;
2874 ObjectTypeInitializer.CloseProcedure = MmpCloseSection;
2875 ObjectTypeInitializer.ValidAccessMask = SECTION_ALL_ACCESS;
2876 ObCreateObjectType(&Name, &ObjectTypeInitializer, NULL, &MmSectionObjectType);
2877
2878 MmCreatePhysicalMemorySection();
2879
2880 return(STATUS_SUCCESS);
2881 }
2882
2883 NTSTATUS
2884 NTAPI
2885 MmCreatePageFileSection(PROS_SECTION_OBJECT *SectionObject,
2886 ACCESS_MASK DesiredAccess,
2887 POBJECT_ATTRIBUTES ObjectAttributes,
2888 PLARGE_INTEGER UMaximumSize,
2889 ULONG SectionPageProtection,
2890 ULONG AllocationAttributes)
2891 /*
2892 * Create a section which is backed by the pagefile
2893 */
2894 {
2895 LARGE_INTEGER MaximumSize;
2896 PROS_SECTION_OBJECT Section;
2897 PMM_SECTION_SEGMENT Segment;
2898 NTSTATUS Status;
2899
2900 if (UMaximumSize == NULL)
2901 {
2902 return(STATUS_UNSUCCESSFUL);
2903 }
2904 MaximumSize = *UMaximumSize;
2905
2906 /*
2907 * Create the section
2908 */
2909 Status = ObCreateObject(ExGetPreviousMode(),
2910 MmSectionObjectType,
2911 ObjectAttributes,
2912 ExGetPreviousMode(),
2913 NULL,
2914 sizeof(ROS_SECTION_OBJECT),
2915 0,
2916 0,
2917 (PVOID*)(PVOID)&Section);
2918 if (!NT_SUCCESS(Status))
2919 {
2920 return(Status);
2921 }
2922
2923 /*
2924 * Initialize it
2925 */
2926 RtlZeroMemory(Section, sizeof(ROS_SECTION_OBJECT));
2927 Section->SectionPageProtection = SectionPageProtection;
2928 Section->AllocationAttributes = AllocationAttributes;
2929 Section->MaximumSize = MaximumSize;
2930 Segment = ExAllocatePoolWithTag(NonPagedPool, sizeof(MM_SECTION_SEGMENT),
2931 TAG_MM_SECTION_SEGMENT);
2932 if (Segment == NULL)
2933 {
2934 ObDereferenceObject(Section);
2935 return(STATUS_NO_MEMORY);
2936 }
2937 Section->Segment = Segment;
2938 Segment->ReferenceCount = 1;
2939 ExInitializeFastMutex(&Segment->Lock);
2940 Segment->FileOffset = 0;
2941 Segment->Protection = SectionPageProtection;
2942 Segment->RawLength = MaximumSize.u.LowPart;
2943 Segment->Length = PAGE_ROUND_UP(MaximumSize.u.LowPart);
2944 Segment->Flags = MM_PAGEFILE_SEGMENT;
2945 Segment->WriteCopy = FALSE;
2946 RtlZeroMemory(&Segment->PageDirectory, sizeof(SECTION_PAGE_DIRECTORY));
2947 Segment->VirtualAddress = 0;
2948 Segment->Characteristics = 0;
2949 *SectionObject = Section;
2950 return(STATUS_SUCCESS);
2951 }
2952
2953
2954 NTSTATUS
2955 NTAPI
2956 MmCreateDataFileSection(PROS_SECTION_OBJECT *SectionObject,
2957 ACCESS_MASK DesiredAccess,
2958 POBJECT_ATTRIBUTES ObjectAttributes,
2959 PLARGE_INTEGER UMaximumSize,
2960 ULONG SectionPageProtection,
2961 ULONG AllocationAttributes,
2962 HANDLE FileHandle)
2963 /*
2964 * Create a section backed by a data file
2965 */
2966 {
2967 PROS_SECTION_OBJECT Section;
2968 NTSTATUS Status;
2969 LARGE_INTEGER MaximumSize;
2970 PFILE_OBJECT FileObject;
2971 PMM_SECTION_SEGMENT Segment;
2972 ULONG FileAccess;
2973 IO_STATUS_BLOCK Iosb;
2974 LARGE_INTEGER Offset;
2975 CHAR Buffer;
2976 FILE_STANDARD_INFORMATION FileInfo;
2977 ULONG Length;
2978
2979 /*
2980 * Create the section
2981 */
2982 Status = ObCreateObject(ExGetPreviousMode(),
2983 MmSectionObjectType,
2984 ObjectAttributes,
2985 ExGetPreviousMode(),
2986 NULL,
2987 sizeof(ROS_SECTION_OBJECT),
2988 0,
2989 0,
2990 (PVOID*)(PVOID)&Section);
2991 if (!NT_SUCCESS(Status))
2992 {
2993 return(Status);
2994 }
2995 /*
2996 * Initialize it
2997 */
2998 RtlZeroMemory(Section, sizeof(ROS_SECTION_OBJECT));
2999 Section->SectionPageProtection = SectionPageProtection;
3000 Section->AllocationAttributes = AllocationAttributes;
3001
3002 /*
3003 * Check file access required
3004 */
3005 if (SectionPageProtection & PAGE_READWRITE ||
3006 SectionPageProtection & PAGE_EXECUTE_READWRITE)
3007 {
3008 FileAccess = FILE_READ_DATA | FILE_WRITE_DATA;
3009 }
3010 else
3011 {
3012 FileAccess = FILE_READ_DATA;
3013 }
3014
3015 /*
3016 * Reference the file handle
3017 */
3018 Status = ObReferenceObjectByHandle(FileHandle,
3019 FileAccess,
3020 IoFileObjectType,
3021 ExGetPreviousMode(),
3022 (PVOID*)(PVOID)&FileObject,
3023 NULL);
3024 if (!NT_SUCCESS(Status))
3025 {
3026 ObDereferenceObject(Section);
3027 return(Status);
3028 }
3029
3030 /*
3031 * FIXME: This is propably not entirely correct. We can't look into
3032 * the standard FCB header because it might not be initialized yet
3033 * (as in case of the EXT2FS driver by Manoj Paul Joseph where the
3034 * standard file information is filled on first request).
3035 */
3036 Status = IoQueryFileInformation(FileObject,
3037 FileStandardInformation,
3038 sizeof(FILE_STANDARD_INFORMATION),
3039 &FileInfo,
3040 &Length);
3041 Iosb.Information = Length;
3042 if (!NT_SUCCESS(Status))
3043 {
3044 ObDereferenceObject(Section);
3045 ObDereferenceObject(FileObject);
3046 return Status;
3047 }
3048
3049 /*
3050 * FIXME: Revise this once a locking order for file size changes is
3051 * decided
3052 */
3053 if ((UMaximumSize != NULL) && (UMaximumSize->QuadPart != 0))
3054 {
3055 MaximumSize = *UMaximumSize;
3056 }
3057 else
3058 {
3059 MaximumSize = FileInfo.EndOfFile;
3060 /* Mapping zero-sized files isn't allowed. */
3061 if (MaximumSize.QuadPart == 0)
3062 {
3063 ObDereferenceObject(Section);
3064 ObDereferenceObject(FileObject);
3065 return STATUS_FILE_INVALID;
3066 }
3067 }
3068
3069 if (MaximumSize.QuadPart > FileInfo.EndOfFile.QuadPart)
3070 {
3071 Status = IoSetInformation(FileObject,
3072 FileAllocationInformation,
3073 sizeof(LARGE_INTEGER),
3074 &MaximumSize);
3075 if (!NT_SUCCESS(Status))
3076 {
3077 ObDereferenceObject(Section);
3078 ObDereferenceObject(FileObject);
3079 return(STATUS_SECTION_NOT_EXTENDED);
3080 }
3081 }
3082
3083 if (FileObject->SectionObjectPointer == NULL ||
3084 FileObject->SectionObjectPointer->SharedCacheMap == NULL)
3085 {
3086 /*
3087 * Read a bit so caching is initiated for the file object.
3088 * This is only needed because MiReadPage currently cannot
3089 * handle non-cached streams.
3090 */
3091 Offset.QuadPart = 0;
3092 Status = ZwReadFile(FileHandle,
3093 NULL,
3094 NULL,
3095 NULL,
3096 &Iosb,
3097 &Buffer,
3098 sizeof (Buffer),
3099 &Offset,
3100 0);
3101 if (!NT_SUCCESS(Status) && (Status != STATUS_END_OF_FILE))
3102 {
3103 ObDereferenceObject(Section);
3104 ObDereferenceObject(FileObject);
3105 return(Status);
3106 }
3107 if (FileObject->SectionObjectPointer == NULL ||
3108 FileObject->SectionObjectPointer->SharedCacheMap == NULL)
3109 {
3110 /* FIXME: handle this situation */
3111 ObDereferenceObject(Section);
3112 ObDereferenceObject(FileObject);
3113 return STATUS_INVALID_PARAMETER;
3114 }
3115 }
3116
3117 /*
3118 * Lock the file
3119 */
3120 Status = MmspWaitForFileLock(FileObject);
3121 if (Status != STATUS_SUCCESS)
3122 {
3123 ObDereferenceObject(Section);
3124 ObDereferenceObject(FileObject);
3125 return(Status);
3126 }
3127
3128 /*
3129 * If this file hasn't been mapped as a data file before then allocate a
3130 * section segment to describe the data file mapping
3131 */
3132 if (FileObject->SectionObjectPointer->DataSectionObject == NULL)
3133 {
3134 Segment = ExAllocatePoolWithTag(NonPagedPool, sizeof(MM_SECTION_SEGMENT),
3135 TAG_MM_SECTION_SEGMENT);
3136 if (Segment == NULL)
3137 {
3138 //KeSetEvent((PVOID)&FileObject->Lock, IO_NO_INCREMENT, FALSE);
3139 ObDereferenceObject(Section);
3140 ObDereferenceObject(FileObject);
3141 return(STATUS_NO_MEMORY);
3142 }
3143 Section->Segment = Segment;
3144 Segment->ReferenceCount = 1;
3145 ExInitializeFastMutex(&Segment->Lock);
3146 /*
3147 * Set the lock before assigning the segment to the file object
3148 */
3149 ExAcquireFastMutex(&Segment->Lock);
3150 FileObject->SectionObjectPointer->DataSectionObject = (PVOID)Segment;
3151
3152 Segment->FileOffset = 0;
3153 Segment->Protection = SectionPageProtection;
3154 Segment->Flags = MM_DATAFILE_SEGMENT;
3155 Segment->Characteristics = 0;
3156 Segment->WriteCopy = FALSE;
3157 if (AllocationAttributes & SEC_RESERVE)
3158 {
3159 Segment->Length = Segment->RawLength = 0;
3160 }
3161 else
3162 {
3163 Segment->RawLength = MaximumSize.u.LowPart;
3164 Segment->Length = PAGE_ROUND_UP(Segment->RawLength);
3165 }
3166 Segment->VirtualAddress = 0;
3167 RtlZeroMemory(&Segment->PageDirectory, sizeof(SECTION_PAGE_DIRECTORY));
3168 }
3169 else
3170 {
3171 /*
3172 * If the file is already mapped as a data file then we may need
3173 * to extend it
3174 */
3175 Segment =
3176 (PMM_SECTION_SEGMENT)FileObject->SectionObjectPointer->
3177 DataSectionObject;
3178 Section->Segment = Segment;
3179 (void)InterlockedIncrementUL(&Segment->ReferenceCount);
3180 MmLockSectionSegment(Segment);
3181
3182 if (MaximumSize.u.LowPart > Segment->RawLength &&
3183 !(AllocationAttributes & SEC_RESERVE))
3184 {
3185 Segment->RawLength = MaximumSize.u.LowPart;
3186 Segment->Length = PAGE_ROUND_UP(Segment->RawLength);
3187 }
3188 }
3189 MmUnlockSectionSegment(Segment);
3190 Section->FileObject = FileObject;
3191 Section->MaximumSize = MaximumSize;
3192 #ifndef NEWCC
3193 CcRosReferenceCache(FileObject);
3194 #endif
3195 //KeSetEvent((PVOID)&FileObject->Lock, IO_NO_INCREMENT, FALSE);
3196 *SectionObject = Section;
3197 return(STATUS_SUCCESS);
3198 }
3199
3200 /*
3201 TODO: not that great (declaring loaders statically, having to declare all of
3202 them, having to keep them extern, etc.), will fix in the future
3203 */
3204 extern NTSTATUS NTAPI PeFmtCreateSection
3205 (
3206 IN CONST VOID * FileHeader,
3207 IN SIZE_T FileHeaderSize,
3208 IN PVOID File,
3209 OUT PMM_IMAGE_SECTION_OBJECT ImageSectionObject,
3210 OUT PULONG Flags,
3211 IN PEXEFMT_CB_READ_FILE ReadFileCb,
3212 IN PEXEFMT_CB_ALLOCATE_SEGMENTS AllocateSegmentsCb
3213 );
3214
3215 extern NTSTATUS NTAPI ElfFmtCreateSection
3216 (
3217 IN CONST VOID * FileHeader,
3218 IN SIZE_T FileHeaderSize,
3219 IN PVOID File,
3220 OUT PMM_IMAGE_SECTION_OBJECT ImageSectionObject,
3221 OUT PULONG Flags,
3222 IN PEXEFMT_CB_READ_FILE ReadFileCb,
3223 IN PEXEFMT_CB_ALLOCATE_SEGMENTS AllocateSegmentsCb
3224 );
3225
3226 /* TODO: this is a standard DDK/PSDK macro */
3227 #ifndef RTL_NUMBER_OF
3228 #define RTL_NUMBER_OF(ARR_) (sizeof(ARR_) / sizeof((ARR_)[0]))
3229 #endif
3230
3231 static PEXEFMT_LOADER ExeFmtpLoaders[] =
3232 {
3233 PeFmtCreateSection,
3234 #ifdef __ELF
3235 ElfFmtCreateSection
3236 #endif
3237 };
3238
3239 static
3240 PMM_SECTION_SEGMENT
3241 NTAPI
3242 ExeFmtpAllocateSegments(IN ULONG NrSegments)
3243 {
3244 SIZE_T SizeOfSegments;
3245 PMM_SECTION_SEGMENT Segments;
3246
3247 /* TODO: check for integer overflow */
3248 SizeOfSegments = sizeof(MM_SECTION_SEGMENT) * NrSegments;
3249
3250 Segments = ExAllocatePoolWithTag(NonPagedPool,
3251 SizeOfSegments,
3252 TAG_MM_SECTION_SEGMENT);
3253
3254 if(Segments)
3255 RtlZeroMemory(Segments, SizeOfSegments);
3256
3257 return Segments;
3258 }
3259
3260 static
3261 NTSTATUS
3262 NTAPI
3263 ExeFmtpReadFile(IN PVOID File,
3264 IN PLARGE_INTEGER Offset,
3265 IN ULONG Length,
3266 OUT PVOID * Data,
3267 OUT PVOID * AllocBase,
3268 OUT PULONG ReadSize)
3269 {
3270 NTSTATUS Status;
3271 LARGE_INTEGER FileOffset;
3272 ULONG AdjustOffset;
3273 ULONG OffsetAdjustment;
3274 ULONG BufferSize;
3275 ULONG UsedSize;
3276 PVOID Buffer;
3277
3278 ASSERT_IRQL_LESS(DISPATCH_LEVEL);
3279
3280 if(Length == 0)
3281 {
3282 KeBugCheck(MEMORY_MANAGEMENT);
3283 }
3284
3285 FileOffset = *Offset;
3286
3287 /* Negative/special offset: it cannot be used in this context */
3288 if(FileOffset.u.HighPart < 0)
3289 {
3290 KeBugCheck(MEMORY_MANAGEMENT);
3291 }
3292
3293 AdjustOffset = PAGE_ROUND_DOWN(FileOffset.u.LowPart);
3294 OffsetAdjustment = FileOffset.u.LowPart - AdjustOffset;
3295 FileOffset.u.LowPart = AdjustOffset;
3296
3297 BufferSize = Length + OffsetAdjustment;
3298 BufferSize = PAGE_ROUND_UP(BufferSize);
3299
3300 /*
3301 * It's ok to use paged pool, because this is a temporary buffer only used in
3302 * the loading of executables. The assumption is that MmCreateSection is
3303 * always called at low IRQLs and that these buffers don't survive a brief
3304 * initialization phase
3305 */
3306 Buffer = ExAllocatePoolWithTag(PagedPool,
3307 BufferSize,
3308 'rXmM');
3309 if (!Buffer)
3310 {
3311 KeBugCheck(MEMORY_MANAGEMENT);
3312 }
3313
3314 UsedSize = 0;
3315
3316 #if 0
3317 Status = MmspPageRead(File,
3318 Buffer,
3319 BufferSize,
3320 &FileOffset,
3321 &UsedSize);
3322 #else
3323 /*
3324 * FIXME: if we don't use ZwReadFile, caching is not enabled for the file and
3325 * nothing will work. But using ZwReadFile is wrong, and using its side effects
3326 * to initialize internal state is even worse. Our cache manager is in need of
3327 * professional help
3328 */
3329 {
3330 IO_STATUS_BLOCK Iosb;
3331
3332 Status = ZwReadFile(File,
3333 NULL,
3334 NULL,
3335 NULL,
3336 &Iosb,
3337 Buffer,
3338 BufferSize,
3339 &FileOffset,
3340 NULL);
3341
3342 if(NT_SUCCESS(Status))
3343 {
3344 UsedSize = (ULONG)Iosb.Information;
3345 }
3346 }
3347 #endif
3348
3349 if(NT_SUCCESS(Status) && UsedSize < OffsetAdjustment)
3350 {
3351 Status = STATUS_IN_PAGE_ERROR;
3352 ASSERT(!NT_SUCCESS(Status));
3353 }
3354
3355 if(NT_SUCCESS(Status))
3356 {
3357 *Data = (PVOID)((ULONG_PTR)Buffer + OffsetAdjustment);
3358 *AllocBase = Buffer;
3359 *ReadSize = UsedSize - OffsetAdjustment;
3360 }
3361 else
3362 {
3363 ExFreePoolWithTag(Buffer, 'rXmM');
3364 }
3365
3366 return Status;
3367 }
3368
3369 #ifdef NASSERT
3370 # define MmspAssertSegmentsSorted(OBJ_) ((void)0)
3371 # define MmspAssertSegmentsNoOverlap(OBJ_) ((void)0)
3372 # define MmspAssertSegmentsPageAligned(OBJ_) ((void)0)
3373 #else
3374 static
3375 VOID
3376 NTAPI
3377 MmspAssertSegmentsSorted(IN PMM_IMAGE_SECTION_OBJECT ImageSectionObject)
3378 {
3379 ULONG i;
3380
3381 for( i = 1; i < ImageSectionObject->NrSegments; ++ i )
3382 {
3383 ASSERT(ImageSectionObject->Segments[i].VirtualAddress >=
3384 ImageSectionObject->Segments[i - 1].VirtualAddress);
3385 }
3386 }
3387
3388 static
3389 VOID
3390 NTAPI
3391 MmspAssertSegmentsNoOverlap(IN PMM_IMAGE_SECTION_OBJECT ImageSectionObject)
3392 {
3393 ULONG i;
3394
3395 MmspAssertSegmentsSorted(ImageSectionObject);
3396
3397 for( i = 0; i < ImageSectionObject->NrSegments; ++ i )
3398 {
3399 ASSERT(ImageSectionObject->Segments[i].Length > 0);
3400
3401 if(i > 0)
3402 {
3403 ASSERT(ImageSectionObject->Segments[i].VirtualAddress >=
3404 (ImageSectionObject->Segments[i - 1].VirtualAddress +
3405 ImageSectionObject->Segments[i - 1].Length));
3406 }
3407 }
3408 }
3409
3410 static
3411 VOID
3412 NTAPI
3413 MmspAssertSegmentsPageAligned(IN PMM_IMAGE_SECTION_OBJECT ImageSectionObject)
3414 {
3415 ULONG i;
3416
3417 for( i = 0; i < ImageSectionObject->NrSegments; ++ i )
3418 {
3419 ASSERT((ImageSectionObject->Segments[i].VirtualAddress % PAGE_SIZE) == 0);
3420 ASSERT((ImageSectionObject->Segments[i].Length % PAGE_SIZE) == 0);
3421 }
3422 }
3423 #endif
3424
3425 static
3426 int
3427 __cdecl
3428 MmspCompareSegments(const void * x,
3429 const void * y)
3430 {
3431 const MM_SECTION_SEGMENT *Segment1 = (const MM_SECTION_SEGMENT *)x;
3432 const MM_SECTION_SEGMENT *Segment2 = (const MM_SECTION_SEGMENT *)y;
3433
3434 return
3435 (Segment1->VirtualAddress - Segment2->VirtualAddress) >>
3436 ((sizeof(ULONG_PTR) - sizeof(int)) * 8);
3437 }
3438
3439 /*
3440 * Ensures an image section's segments are sorted in memory
3441 */
3442 static
3443 VOID
3444 NTAPI
3445 MmspSortSegments(IN OUT PMM_IMAGE_SECTION_OBJECT ImageSectionObject,
3446 IN ULONG Flags)
3447 {
3448 if (Flags & EXEFMT_LOAD_ASSUME_SEGMENTS_SORTED)
3449 {
3450 MmspAssertSegmentsSorted(ImageSectionObject);
3451 }
3452 else
3453 {
3454 qsort(ImageSectionObject->Segments,
3455 ImageSectionObject->NrSegments,
3456 sizeof(ImageSectionObject->Segments[0]),
3457 MmspCompareSegments);
3458 }
3459 }
3460
3461
3462 /*
3463 * Ensures an image section's segments don't overlap in memory and don't have
3464 * gaps and don't have a null size. We let them map to overlapping file regions,
3465 * though - that's not necessarily an error
3466 */
3467 static
3468 BOOLEAN
3469 NTAPI
3470 MmspCheckSegmentBounds
3471 (
3472 IN OUT PMM_IMAGE_SECTION_OBJECT ImageSectionObject,
3473 IN ULONG Flags
3474 )
3475 {
3476 ULONG i;
3477
3478 if (Flags & EXEFMT_LOAD_ASSUME_SEGMENTS_NO_OVERLAP)
3479 {
3480 MmspAssertSegmentsNoOverlap(ImageSectionObject);
3481 return TRUE;
3482 }
3483
3484 ASSERT(ImageSectionObject->NrSegments >= 1);
3485
3486 for ( i = 0; i < ImageSectionObject->NrSegments; ++ i )
3487 {
3488 if(ImageSectionObject->Segments[i].Length == 0)
3489 {
3490 return FALSE;
3491 }
3492
3493 if(i > 0)
3494 {
3495 /*
3496 * TODO: relax the limitation on gaps. For example, gaps smaller than a
3497 * page could be OK (Windows seems to be OK with them), and larger gaps
3498 * could lead to image sections spanning several discontiguous regions
3499 * (NtMapViewOfSection could then refuse to map them, and they could
3500 * e.g. only be allowed as parameters to NtCreateProcess, like on UNIX)
3501 */
3502 if ((ImageSectionObject->Segments[i - 1].VirtualAddress +
3503 ImageSectionObject->Segments[i - 1].Length) !=
3504 ImageSectionObject->Segments[i].VirtualAddress)
3505 {
3506 return FALSE;
3507 }
3508 }
3509 }
3510
3511 return TRUE;
3512 }
3513
3514 /*
3515 * Merges and pads an image section's segments until they all are page-aligned
3516 * and have a size that is a multiple of the page size
3517 */
3518 static
3519 BOOLEAN
3520 NTAPI
3521 MmspPageAlignSegments
3522 (
3523 IN OUT PMM_IMAGE_SECTION_OBJECT ImageSectionObject,
3524 IN ULONG Flags
3525 )
3526 {
3527 ULONG i;
3528 ULONG LastSegment;
3529 PMM_SECTION_SEGMENT EffectiveSegment;
3530
3531 if (Flags & EXEFMT_LOAD_ASSUME_SEGMENTS_PAGE_ALIGNED)
3532 {
3533 MmspAssertSegmentsPageAligned(ImageSectionObject);
3534 return TRUE;
3535 }
3536
3537 LastSegment = 0;
3538 EffectiveSegment = &ImageSectionObject->Segments[LastSegment];
3539
3540 for ( i = 0; i < ImageSectionObject->NrSegments; ++ i )
3541 {
3542 /*
3543 * The first segment requires special handling
3544 */
3545 if (i == 0)
3546 {
3547 ULONG_PTR VirtualAddress;
3548 ULONG_PTR VirtualOffset;
3549
3550 VirtualAddress = EffectiveSegment->VirtualAddress;
3551
3552 /* Round down the virtual address to the nearest page */
3553 EffectiveSegment->VirtualAddress = PAGE_ROUND_DOWN(VirtualAddress);
3554
3555 /* Round up the virtual size to the nearest page */
3556 EffectiveSegment->Length = (ULONG)(PAGE_ROUND_UP(VirtualAddress + EffectiveSegment->Length) -
3557 EffectiveSegment->VirtualAddress);
3558
3559 /* Adjust the raw address and size */
3560 VirtualOffset = VirtualAddress - EffectiveSegment->VirtualAddress;
3561
3562 if (EffectiveSegment->FileOffset < (LONG_PTR)VirtualOffset)
3563 {
3564 return FALSE;
3565 }
3566
3567 /*
3568 * Garbage in, garbage out: unaligned base addresses make the file
3569 * offset point in curious and odd places, but that's what we were
3570 * asked for
3571 */
3572 EffectiveSegment->FileOffset -= (ULONG)VirtualOffset;
3573 EffectiveSegment->RawLength += (ULONG)VirtualOffset;
3574 }
3575 else
3576 {
3577 PMM_SECTION_SEGMENT Segment = &ImageSectionObject->Segments[i];
3578 ULONG_PTR EndOfEffectiveSegment;
3579
3580 EndOfEffectiveSegment = EffectiveSegment->VirtualAddress + EffectiveSegment->Length;
3581 ASSERT((EndOfEffectiveSegment % PAGE_SIZE) == 0);
3582
3583 /*
3584 * The current segment begins exactly where the current effective
3585 * segment ended, therefore beginning a new effective segment
3586 */
3587 if (EndOfEffectiveSegment == Segment->VirtualAddress)
3588 {
3589 LastSegment ++;
3590 ASSERT(LastSegment <= i);
3591 ASSERT(LastSegment < ImageSectionObject->NrSegments);
3592
3593 EffectiveSegment = &ImageSectionObject->Segments[LastSegment];
3594
3595 if (LastSegment != i)
3596 {
3597 /*
3598 * Copy the current segment. If necessary, the effective segment
3599 * will be expanded later
3600 */
3601 *EffectiveSegment = *Segment;
3602 }
3603
3604 /*
3605 * Page-align the virtual size. We know for sure the virtual address
3606 * already is
3607 */
3608 ASSERT((EffectiveSegment->VirtualAddress % PAGE_SIZE) == 0);
3609 EffectiveSegment->Length = PAGE_ROUND_UP(EffectiveSegment->Length);
3610 }
3611 /*
3612 * The current segment is still part of the current effective segment:
3613 * extend the effective segment to reflect this
3614 */
3615 else if (EndOfEffectiveSegment > Segment->VirtualAddress)
3616 {
3617 static const ULONG FlagsToProtection[16] =
3618 {
3619 PAGE_NOACCESS,
3620 PAGE_READONLY,
3621 PAGE_READWRITE,
3622 PAGE_READWRITE,
3623 PAGE_EXECUTE_READ,
3624 PAGE_EXECUTE_READ,
3625 PAGE_EXECUTE_READWRITE,
3626 PAGE_EXECUTE_READWRITE,
3627 PAGE_WRITECOPY,
3628 PAGE_WRITECOPY,
3629 PAGE_WRITECOPY,
3630 PAGE_WRITECOPY,
3631 PAGE_EXECUTE_WRITECOPY,
3632 PAGE_EXECUTE_WRITECOPY,
3633 PAGE_EXECUTE_WRITECOPY,
3634 PAGE_EXECUTE_WRITECOPY
3635 };
3636
3637 unsigned ProtectionFlags;
3638
3639 /*
3640 * Extend the file size
3641 */
3642
3643 /* Unaligned segments must be contiguous within the file */
3644 if (Segment->FileOffset != (EffectiveSegment->FileOffset +
3645 EffectiveSegment->RawLength))
3646 {
3647 return FALSE;
3648 }
3649
3650 EffectiveSegment->RawLength += Segment->RawLength;
3651
3652 /*
3653 * Extend the virtual size
3654 */
3655 ASSERT(PAGE_ROUND_UP(Segment->VirtualAddress + Segment->Length) >= EndOfEffectiveSegment);
3656
3657 EffectiveSegment->Length = (ULONG)(PAGE_ROUND_UP(Segment->VirtualAddress + Segment->Length) -
3658 EffectiveSegment->VirtualAddress);
3659
3660 /*
3661 * Merge the protection
3662 */
3663 EffectiveSegment->Protection |= Segment->Protection;
3664
3665 /* Clean up redundance */
3666 ProtectionFlags = 0;
3667
3668 if(EffectiveSegment->Protection & PAGE_IS_READABLE)
3669 ProtectionFlags |= 1 << 0;
3670
3671 if(EffectiveSegment->Protection & PAGE_IS_WRITABLE)
3672 ProtectionFlags |= 1 << 1;
3673
3674 if(EffectiveSegment->Protection & PAGE_IS_EXECUTABLE)
3675 ProtectionFlags |= 1 << 2;
3676
3677 if(EffectiveSegment->Protection & PAGE_IS_WRITECOPY)
3678 ProtectionFlags |= 1 << 3;
3679
3680 ASSERT(ProtectionFlags < 16);
3681 EffectiveSegment->Protection = FlagsToProtection[ProtectionFlags];
3682
3683 /* If a segment was required to be shared and cannot, fail */
3684 if(!(Segment->Protection & PAGE_IS_WRITECOPY) &&
3685 EffectiveSegment->Protection & PAGE_IS_WRITECOPY)
3686 {
3687 return FALSE;
3688 }
3689 }
3690 /*
3691 * We assume no holes between segments at this point
3692 */
3693 else
3694 {
3695 KeBugCheck(MEMORY_MANAGEMENT);
3696 }
3697 }
3698 }
3699 ImageSectionObject->NrSegments = LastSegment + 1;
3700
3701 return TRUE;
3702 }
3703
3704 NTSTATUS
3705 ExeFmtpCreateImageSection(HANDLE FileHandle,
3706 PMM_IMAGE_SECTION_OBJECT ImageSectionObject)
3707 {
3708 LARGE_INTEGER Offset;
3709 PVOID FileHeader;
3710 PVOID FileHeaderBuffer;
3711 ULONG FileHeaderSize;
3712 ULONG Flags;
3713 ULONG OldNrSegments;
3714 NTSTATUS Status;
3715 ULONG i;
3716
3717 /*
3718 * Read the beginning of the file (2 pages). Should be enough to contain
3719 * all (or most) of the headers
3720 */
3721 Offset.QuadPart = 0;
3722
3723 /* FIXME: use FileObject instead of FileHandle */
3724 Status = ExeFmtpReadFile (FileHandle,
3725 &Offset,
3726 PAGE_SIZE * 2,
3727 &FileHeader,
3728 &FileHeaderBuffer,
3729 &FileHeaderSize);
3730
3731 if (!NT_SUCCESS(Status))
3732 return Status;
3733
3734 if (FileHeaderSize == 0)
3735 {
3736 ExFreePool(FileHeaderBuffer);
3737 return STATUS_UNSUCCESSFUL;
3738 }
3739
3740 /*
3741 * Look for a loader that can handle this executable
3742 */
3743 for (i = 0; i < RTL_NUMBER_OF(ExeFmtpLoaders); ++ i)
3744 {
3745 RtlZeroMemory(ImageSectionObject, sizeof(*ImageSectionObject));
3746 Flags = 0;
3747
3748 /* FIXME: use FileObject instead of FileHandle */
3749 Status = ExeFmtpLoaders[i](FileHeader,
3750 FileHeaderSize,
3751 FileHandle,
3752 ImageSectionObject,
3753 &Flags,
3754 ExeFmtpReadFile,
3755 ExeFmtpAllocateSegments);
3756
3757 if (!NT_SUCCESS(Status))
3758 {
3759 if (ImageSectionObject->Segments)
3760 {
3761 ExFreePool(ImageSectionObject->Segments);
3762 ImageSectionObject->Segments = NULL;
3763 }
3764 }
3765
3766 if (Status != STATUS_ROS_EXEFMT_UNKNOWN_FORMAT)
3767 break;
3768 }
3769
3770 ExFreePoolWithTag(FileHeaderBuffer, 'rXmM');
3771
3772 /*
3773 * No loader handled the format
3774 */
3775 if (Status == STATUS_ROS_EXEFMT_UNKNOWN_FORMAT)
3776 {
3777 Status = STATUS_INVALID_IMAGE_NOT_MZ;
3778 ASSERT(!NT_SUCCESS(Status));
3779 }
3780
3781 if (!NT_SUCCESS(Status))
3782 return Status;
3783
3784 ASSERT(ImageSectionObject->Segments != NULL);
3785
3786 /*
3787 * Some defaults
3788 */
3789 /* FIXME? are these values platform-dependent? */
3790 if(ImageSectionObject->StackReserve == 0)
3791 ImageSectionObject->StackReserve = 0x40000;
3792
3793 if(ImageSectionObject->StackCommit == 0)
3794 ImageSectionObject->StackCommit = 0x1000;
3795
3796 if(ImageSectionObject->ImageBase == 0)
3797 {
3798 if(ImageSectionObject->ImageCharacteristics & IMAGE_FILE_DLL)
3799 ImageSectionObject->ImageBase = 0x10000000;
3800 else
3801 ImageSectionObject->ImageBase = 0x00400000;
3802 }
3803
3804 /*
3805 * And now the fun part: fixing the segments
3806 */
3807
3808 /* Sort them by virtual address */
3809 MmspSortSegments(ImageSectionObject, Flags);
3810
3811 /* Ensure they don't overlap in memory */
3812 if (!MmspCheckSegmentBounds(ImageSectionObject, Flags))
3813 return STATUS_INVALID_IMAGE_FORMAT;
3814
3815 /* Ensure they are aligned */
3816 OldNrSegments = ImageSectionObject->NrSegments;
3817
3818 if (!MmspPageAlignSegments(ImageSectionObject, Flags))
3819 return STATUS_INVALID_IMAGE_FORMAT;
3820
3821 /* Trim them if the alignment phase merged some of them */
3822 if (ImageSectionObject->NrSegments < OldNrSegments)
3823 {
3824 PMM_SECTION_SEGMENT Segments;
3825 SIZE_T SizeOfSegments;
3826
3827 SizeOfSegments = sizeof(MM_SECTION_SEGMENT) * ImageSectionObject->NrSegments;
3828
3829 Segments = ExAllocatePoolWithTag(PagedPool,
3830 SizeOfSegments,
3831 TAG_MM_SECTION_SEGMENT);
3832
3833 if (Segments == NULL)
3834 return STATUS_INSUFFICIENT_RESOURCES;
3835
3836 RtlCopyMemory(Segments, ImageSectionObject->Segments, SizeOfSegments);
3837 ExFreePool(ImageSectionObject->Segments);
3838 ImageSectionObject->Segments = Segments;
3839 }
3840
3841 /* And finish their initialization */
3842 for ( i = 0; i < ImageSectionObject->NrSegments; ++ i )
3843 {
3844 ExInitializeFastMutex(&ImageSectionObject->Segments[i].Lock);
3845 ImageSectionObject->Segments[i].ReferenceCount = 1;
3846
3847 RtlZeroMemory(&ImageSectionObject->Segments[i].PageDirectory,
3848 sizeof(ImageSectionObject->Segments[i].PageDirectory));
3849 }
3850
3851 ASSERT(NT_SUCCESS(Status));
3852 return Status;
3853 }
3854
3855 NTSTATUS
3856 MmCreateImageSection(PROS_SECTION_OBJECT *SectionObject,
3857 ACCESS_MASK DesiredAccess,
3858 POBJECT_ATTRIBUTES ObjectAttributes,
3859 PLARGE_INTEGER UMaximumSize,
3860 ULONG SectionPageProtection,
3861 ULONG AllocationAttributes,
3862 HANDLE FileHandle)
3863 {
3864 PROS_SECTION_OBJECT Section;
3865 NTSTATUS Status;
3866 PFILE_OBJECT FileObject;
3867 PMM_SECTION_SEGMENT SectionSegments;
3868 PMM_IMAGE_SECTION_OBJECT ImageSectionObject;
3869 ULONG i;
3870 ULONG FileAccess = 0;
3871
3872 /*
3873 * Check file access required
3874 */
3875 if (SectionPageProtection & PAGE_READWRITE ||
3876 SectionPageProtection & PAGE_EXECUTE_READWRITE)
3877 {
3878 FileAccess = FILE_READ_DATA | FILE_WRITE_DATA;
3879 }
3880 else
3881 {
3882 FileAccess = FILE_READ_DATA;
3883 }
3884
3885 /*
3886 * Reference the file handle
3887 */
3888 Status = ObReferenceObjectByHandle(FileHandle,
3889 FileAccess,
3890 IoFileObjectType,
3891 ExGetPreviousMode(),
3892 (PVOID*)(PVOID)&FileObject,
3893 NULL);
3894
3895 if (!NT_SUCCESS(Status))
3896 {
3897 return Status;
3898 }
3899
3900 /*
3901 * Create the section
3902 */
3903 Status = ObCreateObject (ExGetPreviousMode(),
3904 MmSectionObjectType,
3905 ObjectAttributes,
3906 ExGetPreviousMode(),
3907 NULL,
3908 sizeof(ROS_SECTION_OBJECT),
3909 0,
3910 0,
3911 (PVOID*)(PVOID)&Section);
3912 if (!NT_SUCCESS(Status))
3913 {
3914 ObDereferenceObject(FileObject);
3915 return(Status);
3916 }
3917
3918 /*