Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5528 lines
160 KiB

  1. /*++
  2. Copyright (c) 1989 Microsoft Corporation
  3. Module Name:
  4. creasect.c
  5. Abstract:
  6. This module contains the routines which implement the
  7. NtCreateSection and NtOpenSection.
  8. Author:
  9. Lou Perazzoli (loup) 22-May-1989
  10. Landy Wang (landyw) 02-Jun-1997
  11. Revision History:
  12. --*/
  13. #include "mi.h"
  14. const ULONG MMCONTROL = 'aCmM';
  15. const ULONG MMTEMPORARY = 'xxmM';
  16. #define MM_SIZE_OF_LARGEST_IMAGE ((ULONG)0x77000000)
  17. #define MM_MAXIMUM_IMAGE_HEADER (2 * PAGE_SIZE)
  18. extern SIZE_T MmAllocationFragment;
  19. //
  20. // The maximum number of image object (object table entries) is
  21. // the number which will fit into the MM_MAXIMUM_IMAGE_HEADER with
  22. // the start of the PE image header in the last word of the first
  23. //
  24. #define MM_MAXIMUM_IMAGE_SECTIONS \
  25. ((MM_MAXIMUM_IMAGE_HEADER - (PAGE_SIZE + sizeof(IMAGE_NT_HEADERS))) / \
  26. sizeof(IMAGE_SECTION_HEADER))
  27. #if DBG
  28. extern PEPROCESS MmWatchProcess;
  29. ULONG MiMakeImageFloppy[2];
  30. #endif
  31. extern POBJECT_TYPE IoFileObjectType;
  32. CCHAR MmImageProtectionArray[16] = {
  33. MM_NOACCESS,
  34. MM_EXECUTE,
  35. MM_READONLY,
  36. MM_EXECUTE_READ,
  37. MM_WRITECOPY,
  38. MM_EXECUTE_WRITECOPY,
  39. MM_WRITECOPY,
  40. MM_EXECUTE_WRITECOPY,
  41. MM_NOACCESS,
  42. MM_EXECUTE,
  43. MM_READONLY,
  44. MM_EXECUTE_READ,
  45. MM_READWRITE,
  46. MM_EXECUTE_READWRITE,
  47. MM_READWRITE,
  48. MM_EXECUTE_READWRITE };
  49. CCHAR
  50. MiGetImageProtection (
  51. IN ULONG SectionCharacteristics
  52. );
  53. NTSTATUS
  54. MiVerifyImageHeader (
  55. IN PIMAGE_NT_HEADERS NtHeader,
  56. IN PIMAGE_DOS_HEADER DosHeader,
  57. IN ULONG NtHeaderSize
  58. );
  59. LOGICAL
  60. MiCheckDosCalls (
  61. IN PIMAGE_OS2_HEADER Os2Header,
  62. IN ULONG HeaderSize
  63. );
  64. PCONTROL_AREA
  65. MiFindImageSectionObject(
  66. IN PFILE_OBJECT File,
  67. IN PLOGICAL GlobalNeeded
  68. );
  69. VOID
  70. MiInsertImageSectionObject(
  71. IN PFILE_OBJECT File,
  72. IN PCONTROL_AREA ControlArea
  73. );
  74. LOGICAL
  75. MiFlushDataSection(
  76. IN PFILE_OBJECT File
  77. );
  78. PVOID
  79. MiCopyHeaderIfResident (
  80. IN PFILE_OBJECT File,
  81. IN PFN_NUMBER ImagePageFrameNumber
  82. );
  83. #ifdef ALLOC_PRAGMA
  84. #pragma alloc_text(PAGE,MiCreateImageFileMap)
  85. #pragma alloc_text(PAGE,NtCreateSection)
  86. #pragma alloc_text(PAGE,NtOpenSection)
  87. #pragma alloc_text(PAGE,MiGetImageProtection)
  88. #pragma alloc_text(PAGE,MiVerifyImageHeader)
  89. #pragma alloc_text(PAGE,MiCheckDosCalls)
  90. #pragma alloc_text(PAGE,MiCreatePagingFileMap)
  91. #pragma alloc_text(PAGE,MiCreateDataFileMap)
  92. #pragma alloc_text(PAGE,MiGetWritablePagesInSection)
  93. #endif
  94. #pragma pack (1)
  95. typedef struct _PHARLAP_CONFIG {
  96. UCHAR uchCopyRight[0x32];
  97. USHORT usType;
  98. USHORT usRsv1;
  99. USHORT usRsv2;
  100. USHORT usSign;
  101. } CONFIGPHARLAP, *PCONFIGPHARLAP;
  102. #pragma pack ()
  103. NTSTATUS
  104. NtCreateSection (
  105. OUT PHANDLE SectionHandle,
  106. IN ACCESS_MASK DesiredAccess,
  107. IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
  108. IN PLARGE_INTEGER MaximumSize OPTIONAL,
  109. IN ULONG SectionPageProtection,
  110. IN ULONG AllocationAttributes,
  111. IN HANDLE FileHandle OPTIONAL
  112. )
  113. /*++
  114. Routine Description:
  115. This function creates a section object and opens a handle to the object
  116. with the specified desired access.
  117. Arguments:
  118. SectionHandle - A pointer to a variable that will
  119. receive the section object handle value.
  120. DesiredAccess - The desired types of access for the section.
  121. DesiredAccess Flags
  122. EXECUTE - Execute access to the section is
  123. desired.
  124. READ - Read access to the section is desired.
  125. WRITE - Write access to the section is desired.
  126. ObjectAttributes - Supplies a pointer to an object attributes structure.
  127. MaximumSize - Supplies the maximum size of the section in bytes.
  128. This value is rounded up to the host page size and
  129. specifies the size of the section (page file
  130. backed section) or the maximum size to which a
  131. file can be extended or mapped (file backed
  132. section).
  133. SectionPageProtection - Supplies the protection to place on each page
  134. in the section. One of PAGE_READ, PAGE_READWRITE, PAGE_EXECUTE,
  135. or PAGE_WRITECOPY and, optionally, PAGE_NOCACHE may be specified.
  136. AllocationAttributes - Supplies a set of flags that describe the
  137. allocation attributes of the section.
  138. AllocationAttributes Flags
  139. SEC_BASED - The section is a based section and will be
  140. allocated at the same virtual address in each process
  141. address space that receives the section. This does not
  142. imply that addresses are reserved for based sections.
  143. Rather if the section cannot be mapped at the based address
  144. an error is returned.
  145. SEC_RESERVE - All pages of the section are set to the
  146. reserved state.
  147. SEC_COMMIT - All pages of the section are set to the commit
  148. state.
  149. SEC_IMAGE - The file specified by the file handle is an
  150. executable image file.
  151. SEC_FILE - The file specified by the file handle is a mapped
  152. file. If a file handle is supplied and neither
  153. SEC_IMAGE or SEC_FILE is supplied, SEC_FILE is
  154. assumed.
  155. SEC_NO_CHANGE - Once the file is mapped, the protection cannot
  156. be changed nor can the view be unmapped. The
  157. view is unmapped when the process is deleted.
  158. Cannot be used with SEC_IMAGE.
  159. FileHandle - Supplies an optional handle of an open file object.
  160. If the value of this handle is null, then the
  161. section will be backed by a paging file. Otherwise
  162. the section is backed by the specified data file.
  163. Return Value:
  164. NTSTATUS.
  165. --*/
  166. {
  167. NTSTATUS Status;
  168. PVOID Section;
  169. HANDLE Handle;
  170. LARGE_INTEGER LargeSize;
  171. LARGE_INTEGER CapturedSize;
  172. ULONG RetryCount;
  173. PCONTROL_AREA ControlArea;
  174. if ((AllocationAttributes & ~(SEC_COMMIT | SEC_RESERVE | SEC_BASED |
  175. SEC_IMAGE | SEC_NOCACHE | SEC_NO_CHANGE)) != 0) {
  176. return STATUS_INVALID_PARAMETER_6;
  177. }
  178. if ((AllocationAttributes & (SEC_COMMIT | SEC_RESERVE | SEC_IMAGE)) == 0) {
  179. return STATUS_INVALID_PARAMETER_6;
  180. }
  181. if ((AllocationAttributes & SEC_IMAGE) &&
  182. (AllocationAttributes & (SEC_COMMIT | SEC_RESERVE |
  183. SEC_NOCACHE | SEC_NO_CHANGE))) {
  184. return STATUS_INVALID_PARAMETER_6;
  185. }
  186. if ((AllocationAttributes & SEC_COMMIT) &&
  187. (AllocationAttributes & SEC_RESERVE)) {
  188. return STATUS_INVALID_PARAMETER_6;
  189. }
  190. //
  191. // Check the SectionProtection Flag.
  192. //
  193. if ((SectionPageProtection & PAGE_NOCACHE) ||
  194. (SectionPageProtection & PAGE_GUARD) ||
  195. (SectionPageProtection & PAGE_NOACCESS)) {
  196. //
  197. // No cache is only specified through SEC_NOCACHE option in the
  198. // allocation attributes.
  199. //
  200. return STATUS_INVALID_PAGE_PROTECTION;
  201. }
  202. if (KeGetPreviousMode() != KernelMode) {
  203. try {
  204. ProbeForWriteHandle(SectionHandle);
  205. if (ARGUMENT_PRESENT (MaximumSize)) {
  206. #if !defined (_WIN64)
  207. //
  208. // Note we only probe for byte alignment because prior to 2195,
  209. // we never probed at all! We don't want to break user apps
  210. // that had bad alignment if they worked before.
  211. //
  212. ProbeForReadSmallStructure(MaximumSize, sizeof(LARGE_INTEGER), sizeof(UCHAR));
  213. #else
  214. ProbeForReadSmallStructure(MaximumSize, sizeof(LARGE_INTEGER), sizeof(LARGE_INTEGER));
  215. #endif
  216. LargeSize = *MaximumSize;
  217. }
  218. else {
  219. ZERO_LARGE (LargeSize);
  220. }
  221. } except (EXCEPTION_EXECUTE_HANDLER) {
  222. return GetExceptionCode();
  223. }
  224. }
  225. else {
  226. if (ARGUMENT_PRESENT (MaximumSize)) {
  227. LargeSize = *MaximumSize;
  228. }
  229. else {
  230. ZERO_LARGE (LargeSize);
  231. }
  232. }
  233. RetryCount = 0;
  234. retry:
  235. CapturedSize = LargeSize;
  236. ASSERT (KeGetCurrentIrql() < DISPATCH_LEVEL);
  237. Status = MmCreateSection ( &Section,
  238. DesiredAccess,
  239. ObjectAttributes,
  240. &CapturedSize,
  241. SectionPageProtection,
  242. AllocationAttributes,
  243. FileHandle,
  244. NULL );
  245. ASSERT (KeGetCurrentIrql() < DISPATCH_LEVEL);
  246. if (!NT_SUCCESS(Status)) {
  247. if ((Status == STATUS_FILE_LOCK_CONFLICT) &&
  248. (RetryCount < 3)) {
  249. //
  250. // The file system may have prevented this from working
  251. // due to log file flushing. Delay and try again.
  252. //
  253. RetryCount += 1;
  254. KeDelayExecutionThread (KernelMode,
  255. FALSE,
  256. (PLARGE_INTEGER)&MmHalfSecond);
  257. goto retry;
  258. }
  259. return Status;
  260. }
  261. ControlArea = ((PSECTION)Section)->Segment->ControlArea;
  262. #if DBG
  263. if (MmDebug & MM_DBG_SECTIONS) {
  264. DbgPrint ("inserting section %p control %p\n", Section, ControlArea);
  265. }
  266. #endif
  267. if ((ControlArea != NULL) && (ControlArea->FilePointer != NULL)) {
  268. CcZeroEndOfLastPage (ControlArea->FilePointer);
  269. }
  270. //
  271. // Note if the insertion fails, Ob will dereference the object for us.
  272. //
  273. Status = ObInsertObject (Section,
  274. NULL,
  275. DesiredAccess,
  276. 0,
  277. (PVOID *)NULL,
  278. &Handle);
  279. if (NT_SUCCESS(Status)) {
  280. try {
  281. *SectionHandle = Handle;
  282. } except (EXCEPTION_EXECUTE_HANDLER) {
  283. //
  284. // If the write attempt fails, then do not report an error.
  285. // When the caller attempts to access the handle value,
  286. // an access violation will occur.
  287. //
  288. }
  289. }
  290. return Status;
  291. }
  292. NTSTATUS
  293. MmCreateSection (
  294. OUT PVOID *SectionObject,
  295. IN ACCESS_MASK DesiredAccess,
  296. IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
  297. IN PLARGE_INTEGER InputMaximumSize,
  298. IN ULONG SectionPageProtection,
  299. IN ULONG AllocationAttributes,
  300. IN HANDLE FileHandle OPTIONAL,
  301. IN PFILE_OBJECT FileObject OPTIONAL
  302. )
  303. /*++
  304. Routine Description:
  305. This function creates a section object and opens a handle to the object
  306. with the specified desired access.
  307. Arguments:
  308. Section - A pointer to a variable that will
  309. receive the section object address.
  310. DesiredAccess - The desired types of access for the section.
  311. DesiredAccess Flags
  312. EXECUTE - Execute access to the section is desired.
  313. READ - Read access to the section is desired.
  314. WRITE - Write access to the section is desired.
  315. ObjectAttributes - Supplies a pointer to an object attributes structure.
  316. InputMaximumSize - Supplies the maximum size of the section in bytes.
  317. This value is rounded up to the host page size and
  318. specifies the size of the section (page file
  319. backed section) or the maximum size to which a
  320. file can be extended or mapped (file backed
  321. section).
  322. SectionPageProtection - Supplies the protection to place on each page
  323. in the section. One of PAGE_READ, PAGE_READWRITE,
  324. PAGE_EXECUTE, or PAGE_WRITECOPY and, optionally,
  325. PAGE_NOCACHE may be specified.
  326. AllocationAttributes - Supplies a set of flags that describe the
  327. allocation attributes of the section.
  328. AllocationAttributes Flags
  329. SEC_BASED - The section is a based section and will be
  330. allocated at the same virtual address in each process
  331. address space that receives the section. This does not
  332. imply that addresses are reserved for based sections.
  333. Rather if the section cannot be mapped at the based address
  334. an error is returned.
  335. SEC_RESERVE - All pages of the section are set to the
  336. reserved state.
  337. SEC_COMMIT - All pages of the section are set to the commit state.
  338. SEC_IMAGE - The file specified by the file handle is an
  339. executable image file.
  340. SEC_FILE - The file specified by the file handle is a mapped
  341. file. If a file handle is supplied and neither
  342. SEC_IMAGE or SEC_FILE is supplied, SEC_FILE is
  343. assumed.
  344. FileHandle - Supplies an optional handle of an open file object.
  345. If the value of this handle is null, then the
  346. section will be backed by a paging file. Otherwise
  347. the section is backed by the specified data file.
  348. FileObject - Supplies an optional pointer to the file object. If this
  349. value is NULL and the FileHandle is NULL, then there is
  350. no file to map (image or mapped file). If this value
  351. is specified, then the File is to be mapped as a MAPPED FILE
  352. and NO file size checking will be performed.
  353. ONLY THE SYSTEM CACHE SHOULD PROVIDE A FILE OBJECT WITH THE
  354. CALL!! as this is optimized to not check the size, only do
  355. data mapping, no protection check, etc.
  356. Note - Only one of FileHandle or File should be specified!
  357. Return Value:
  358. Returns the relevant NTSTATUS code.
  359. --*/
  360. {
  361. SECTION Section;
  362. PSECTION NewSection;
  363. PSEGMENT Segment;
  364. PSEGMENT NewSegment;
  365. KPROCESSOR_MODE PreviousMode;
  366. KIRQL OldIrql;
  367. NTSTATUS Status;
  368. NTSTATUS Status2;
  369. PCONTROL_AREA ControlArea;
  370. PCONTROL_AREA NewControlArea;
  371. PCONTROL_AREA SegmentControlArea;
  372. ACCESS_MASK FileDesiredAccess;
  373. PFILE_OBJECT File;
  374. PEVENT_COUNTER Event;
  375. ULONG IgnoreFileSizing;
  376. ULONG ProtectionMask;
  377. ULONG ProtectMaskForAccess;
  378. ULONG FileAcquired;
  379. PEVENT_COUNTER SegmentEvent;
  380. LOGICAL FileSizeChecked;
  381. LARGE_INTEGER TempSectionSize;
  382. UINT64 EndOfFile;
  383. ULONG IncrementedRefCount;
  384. SIZE_T ControlAreaSize;
  385. PUINT64 MaximumSize;
  386. PMMADDRESS_NODE *SectionBasedRoot;
  387. LOGICAL GlobalNeeded;
  388. PFILE_OBJECT ChangeFileReference;
  389. SIZE_T SizeOfSection;
  390. #if DBG
  391. PVOID PreviousSectionPointer;
  392. PreviousSectionPointer = (PVOID)-1;
  393. #endif
  394. NewControlArea = (PCONTROL_AREA)-1;
  395. UNREFERENCED_PARAMETER (DesiredAccess);
  396. IgnoreFileSizing = FALSE;
  397. FileAcquired = FALSE;
  398. FileSizeChecked = FALSE;
  399. IncrementedRefCount = FALSE;
  400. ChangeFileReference = NULL;
  401. MaximumSize = (PUINT64) InputMaximumSize;
  402. //
  403. // Check allocation attributes flags.
  404. //
  405. File = (PFILE_OBJECT)NULL;
  406. ASSERT ((AllocationAttributes & ~(SEC_COMMIT | SEC_RESERVE | SEC_BASED |
  407. SEC_IMAGE | SEC_NOCACHE | SEC_NO_CHANGE)) == 0);
  408. ASSERT ((AllocationAttributes & (SEC_COMMIT | SEC_RESERVE | SEC_IMAGE)) != 0);
  409. ASSERT (!((AllocationAttributes & SEC_IMAGE) &&
  410. (AllocationAttributes & (SEC_COMMIT | SEC_RESERVE |
  411. SEC_NOCACHE | SEC_NO_CHANGE))));
  412. ASSERT (!((AllocationAttributes & SEC_COMMIT) &&
  413. (AllocationAttributes & SEC_RESERVE)));
  414. ASSERT (!((SectionPageProtection & PAGE_NOCACHE) ||
  415. (SectionPageProtection & PAGE_GUARD) ||
  416. (SectionPageProtection & PAGE_NOACCESS)));
  417. if (AllocationAttributes & SEC_NOCACHE) {
  418. SectionPageProtection |= PAGE_NOCACHE;
  419. }
  420. //
  421. // Check the protection field.
  422. //
  423. ProtectionMask = MiMakeProtectionMask (SectionPageProtection);
  424. if (ProtectionMask == MM_INVALID_PROTECTION) {
  425. return STATUS_INVALID_PAGE_PROTECTION;
  426. }
  427. ProtectMaskForAccess = ProtectionMask & 0x7;
  428. FileDesiredAccess = MmMakeFileAccess[ProtectMaskForAccess];
  429. //
  430. // Get previous processor mode and probe output arguments if necessary.
  431. //
  432. PreviousMode = KeGetPreviousMode();
  433. Section.InitialPageProtection = SectionPageProtection;
  434. Section.Segment = (PSEGMENT)NULL;
  435. //
  436. // Initializing Segment is not needed for correctness, but
  437. // without it the compiler cannot compile this code W4 to check
  438. // for use of uninitialized variables.
  439. //
  440. Segment = (PSEGMENT)-1;
  441. if (ARGUMENT_PRESENT(FileHandle) || ARGUMENT_PRESENT(FileObject)) {
  442. //
  443. // Only one of FileHandle or FileObject should be supplied.
  444. // If a FileObject is supplied, this must be from the
  445. // file system and therefore the file's size should not
  446. // be checked.
  447. //
  448. if (ARGUMENT_PRESENT(FileObject)) {
  449. IgnoreFileSizing = TRUE;
  450. File = FileObject;
  451. //
  452. // Quick check to see if a control area already exists.
  453. //
  454. if (File->SectionObjectPointer->DataSectionObject) {
  455. LOCK_PFN (OldIrql);
  456. ControlArea =
  457. (PCONTROL_AREA)(File->SectionObjectPointer->DataSectionObject);
  458. if ((ControlArea != NULL) &&
  459. (!ControlArea->u.Flags.BeingDeleted) &&
  460. (!ControlArea->u.Flags.BeingCreated)) {
  461. //
  462. // Control area exists and is not being deleted,
  463. // reference it.
  464. //
  465. NewSegment = ControlArea->Segment;
  466. if ((ControlArea->NumberOfSectionReferences == 0) &&
  467. (ControlArea->NumberOfMappedViews == 0) &&
  468. (ControlArea->ModifiedWriteCount == 0)) {
  469. //
  470. // Dereference the current file object (after releasing
  471. // the PFN lock) and reference this one.
  472. //
  473. ASSERT (ControlArea->FilePointer != NULL);
  474. ChangeFileReference = ControlArea->FilePointer;
  475. ControlArea->FilePointer = FileObject;
  476. }
  477. ControlArea->u.Flags.Accessed = 1;
  478. ControlArea->NumberOfSectionReferences += 1;
  479. if (ControlArea->DereferenceList.Flink != NULL) {
  480. //
  481. // Remove this from the list of unused segments.
  482. //
  483. RemoveEntryList (&ControlArea->DereferenceList);
  484. MI_UNUSED_SEGMENTS_REMOVE_CHARGE (ControlArea);
  485. ControlArea->DereferenceList.Flink = NULL;
  486. ControlArea->DereferenceList.Blink = NULL;
  487. }
  488. UNLOCK_PFN (OldIrql);
  489. //
  490. // Inform the object manager to defer this deletion by
  491. // queueing it to another thread to eliminate deadlocks
  492. // with the redirector.
  493. //
  494. if (ChangeFileReference != NULL) {
  495. ObDereferenceObjectDeferDelete (ChangeFileReference);
  496. }
  497. IncrementedRefCount = TRUE;
  498. Section.SizeOfSection.QuadPart = (LONGLONG)*MaximumSize;
  499. goto ReferenceObject;
  500. }
  501. UNLOCK_PFN (OldIrql);
  502. }
  503. ObReferenceObject (FileObject);
  504. }
  505. else {
  506. Status = ObReferenceObjectByHandle ( FileHandle,
  507. FileDesiredAccess,
  508. IoFileObjectType,
  509. PreviousMode,
  510. (PVOID *)&File,
  511. NULL );
  512. if (!NT_SUCCESS(Status)) {
  513. return Status;
  514. }
  515. //
  516. // If this file doesn't have a section object pointer,
  517. // return an error.
  518. //
  519. if (File->SectionObjectPointer == NULL) {
  520. ObDereferenceObject (File);
  521. return STATUS_INVALID_FILE_FOR_SECTION;
  522. }
  523. }
  524. //
  525. // Check to see if the specified file already has a section.
  526. // If not, indicate in the file object's pointer to an FCB that
  527. // a section is being built. This synchronizes segment creation
  528. // for the file.
  529. //
  530. if (AllocationAttributes & SEC_IMAGE) {
  531. //
  532. // This control area is always just a place holder - the real one
  533. // is allocated in MiCreateImageFileMap and will be allocated
  534. // with the correct size and this one freed in a short while.
  535. //
  536. // This place holder must always be allocated as a large control
  537. // area so that it can be chained for the per-session case.
  538. //
  539. ControlAreaSize = sizeof(LARGE_CONTROL_AREA) + sizeof(SUBSECTION);
  540. }
  541. else {
  542. //
  543. // Data files are mapped with larger subsections than images or
  544. // pagefile-backed shared memory. Factor that in here.
  545. //
  546. ControlAreaSize = sizeof(CONTROL_AREA) + sizeof(MSUBSECTION);
  547. }
  548. NewControlArea = ExAllocatePoolWithTag (NonPagedPool,
  549. ControlAreaSize,
  550. MMCONTROL);
  551. if (NewControlArea == NULL) {
  552. ObDereferenceObject (File);
  553. return STATUS_INSUFFICIENT_RESOURCES;
  554. }
  555. RtlZeroMemory (NewControlArea, ControlAreaSize);
  556. NewSegment = NULL;
  557. //
  558. // We only need the file resource if this was a user request, i.e. not
  559. // a call from the cache manager or file system.
  560. //
  561. if (ARGUMENT_PRESENT(FileHandle)) {
  562. Status = FsRtlAcquireToCreateMappedSection (File, SectionPageProtection);
  563. if (!NT_SUCCESS(Status)) {
  564. ExFreePool (NewControlArea);
  565. ObDereferenceObject (File);
  566. return Status;
  567. }
  568. IoSetTopLevelIrp((PIRP)FSRTL_FSP_TOP_LEVEL_IRP);
  569. FileAcquired = TRUE;
  570. }
  571. //
  572. // Initializing GlobalNeeded is not needed for correctness, but
  573. // without it the compiler cannot compile this code W4 to check
  574. // for use of uninitialized variables.
  575. //
  576. GlobalNeeded = FALSE;
  577. //
  578. // Allocate an event to wait on in case the segment is in the
  579. // process of being deleted. This event cannot be allocated
  580. // with the PFN database locked as pool expansion would deadlock.
  581. //
  582. ReallocateandcheckSegment:
  583. SegmentEvent = MiGetEventCounter();
  584. if (SegmentEvent == NULL) {
  585. if (FileAcquired) {
  586. IoSetTopLevelIrp((PIRP)NULL);
  587. FsRtlReleaseFile (File);
  588. }
  589. ExFreePool (NewControlArea);
  590. ObDereferenceObject (File);
  591. return STATUS_INSUFFICIENT_RESOURCES;
  592. }
  593. RecheckSegment:
  594. LOCK_PFN (OldIrql);
  595. if (AllocationAttributes & SEC_IMAGE) {
  596. ControlArea = MiFindImageSectionObject (File, &GlobalNeeded);
  597. }
  598. else {
  599. ControlArea =
  600. (PCONTROL_AREA)(File->SectionObjectPointer->DataSectionObject);
  601. }
  602. if (ControlArea != NULL) {
  603. //
  604. // A segment already exists for this file. Make sure that it
  605. // is not in the process of being deleted, or being created.
  606. //
  607. if ((ControlArea->u.Flags.BeingDeleted) ||
  608. (ControlArea->u.Flags.BeingCreated)) {
  609. //
  610. // The segment object is in the process of being deleted or
  611. // created.
  612. // Check to see if another thread is waiting for the deletion,
  613. // otherwise create an event object to wait upon.
  614. //
  615. if (ControlArea->WaitingForDeletion == NULL) {
  616. //
  617. // Initialize an event and put its address in the control area.
  618. //
  619. ControlArea->WaitingForDeletion = SegmentEvent;
  620. Event = SegmentEvent;
  621. SegmentEvent = NULL;
  622. }
  623. else {
  624. Event = ControlArea->WaitingForDeletion;
  625. //
  626. // No interlock is needed for the RefCount increment as
  627. // no thread can be decrementing it since it is still
  628. // pointed to by the control area.
  629. //
  630. Event->RefCount += 1;
  631. }
  632. //
  633. // Release the PFN lock, the file lock, and wait for the event.
  634. //
  635. UNLOCK_PFN (OldIrql);
  636. if (FileAcquired) {
  637. IoSetTopLevelIrp((PIRP)NULL);
  638. FsRtlReleaseFile (File);
  639. }
  640. KeWaitForSingleObject(&Event->Event,
  641. WrVirtualMemory,
  642. KernelMode,
  643. FALSE,
  644. (PLARGE_INTEGER)NULL);
  645. //
  646. // Before this event can be set, the control area
  647. // WaitingForDeletion field must be cleared (and may be
  648. // reinitialized to something else), but cannot be reset
  649. // to our local event. This allows us to dereference the
  650. // event count lock free.
  651. //
  652. #if 0
  653. //
  654. // Note that the control area cannot be referenced at this
  655. // point because it may have been freed.
  656. //
  657. ASSERT (Event != ControlArea->WaitingForDeletion);
  658. #endif
  659. if (FileAcquired) {
  660. Status = FsRtlAcquireToCreateMappedSection (File, SectionPageProtection);
  661. if (NT_SUCCESS(Status)) {
  662. IoSetTopLevelIrp((PIRP)FSRTL_FSP_TOP_LEVEL_IRP);
  663. }
  664. else {
  665. ExFreePool (NewControlArea);
  666. ObDereferenceObject (File);
  667. return Status;
  668. }
  669. }
  670. MiFreeEventCounter (Event);
  671. if (SegmentEvent == NULL) {
  672. //
  673. // The event was freed from pool, allocate another
  674. // event in case we have to synchronize one more time.
  675. //
  676. goto ReallocateandcheckSegment;
  677. }
  678. goto RecheckSegment;
  679. }
  680. //
  681. // There is already a segment for this file, have
  682. // this section refer to that segment.
  683. // No need to reference the file object any more.
  684. //
  685. NewSegment = ControlArea->Segment;
  686. ControlArea->u.Flags.Accessed = 1;
  687. ControlArea->NumberOfSectionReferences += 1;
  688. if (ControlArea->DereferenceList.Flink != NULL) {
  689. //
  690. // Remove this from the list of unused segments.
  691. //
  692. RemoveEntryList (&ControlArea->DereferenceList);
  693. MI_UNUSED_SEGMENTS_REMOVE_CHARGE (ControlArea);
  694. ControlArea->DereferenceList.Flink = NULL;
  695. ControlArea->DereferenceList.Blink = NULL;
  696. }
  697. IncrementedRefCount = TRUE;
  698. //
  699. // If this reference was not from the cache manager
  700. // up the count of user references.
  701. //
  702. if (IgnoreFileSizing == FALSE) {
  703. ControlArea->NumberOfUserReferences += 1;
  704. }
  705. }
  706. else {
  707. //
  708. // There is no segment associated with this file object.
  709. // Set the file object to refer to the new control area.
  710. //
  711. ControlArea = NewControlArea;
  712. ControlArea->u.Flags.BeingCreated = 1;
  713. if (AllocationAttributes & SEC_IMAGE) {
  714. if (GlobalNeeded == TRUE) {
  715. ControlArea->u.Flags.GlobalOnlyPerSession = 1;
  716. }
  717. MiInsertImageSectionObject (File, ControlArea);
  718. }
  719. else {
  720. #if DBG
  721. PreviousSectionPointer = File->SectionObjectPointer;
  722. #endif
  723. File->SectionObjectPointer->DataSectionObject = (PVOID) ControlArea;
  724. }
  725. }
  726. UNLOCK_PFN (OldIrql);
  727. if (SegmentEvent != NULL) {
  728. MiFreeEventCounter (SegmentEvent);
  729. }
  730. if (NewSegment != (PSEGMENT)NULL) {
  731. //
  732. // A segment already exists for this file object.
  733. // If we're creating an imagemap, flush the data section
  734. // if there is one.
  735. //
  736. if (AllocationAttributes & SEC_IMAGE) {
  737. MiFlushDataSection (File);
  738. }
  739. //
  740. // Deallocate the new control area as it won't be needed.
  741. // Dereference the file object later when we're done with it.
  742. //
  743. ExFreePool (NewControlArea);
  744. //
  745. // The section is in paged pool, this can't be set until
  746. // the PFN mutex has been released.
  747. //
  748. if ((!IgnoreFileSizing) && (ControlArea->u.Flags.Image == 0)) {
  749. //
  750. // The file size in the segment may not match the current
  751. // file size, query the file system and get the file
  752. // size.
  753. //
  754. Status = FsRtlGetFileSize (File, (PLARGE_INTEGER)&EndOfFile );
  755. if (!NT_SUCCESS (Status)) {
  756. if (FileAcquired) {
  757. IoSetTopLevelIrp((PIRP)NULL);
  758. FsRtlReleaseFile (File);
  759. FileAcquired = FALSE;
  760. }
  761. ObDereferenceObject (File);
  762. goto UnrefAndReturn;
  763. }
  764. if (EndOfFile == 0 && *MaximumSize == 0) {
  765. //
  766. // Can't map a zero length without specifying the maximum
  767. // size as non-zero.
  768. //
  769. Status = STATUS_MAPPED_FILE_SIZE_ZERO;
  770. if (FileAcquired) {
  771. IoSetTopLevelIrp((PIRP)NULL);
  772. FsRtlReleaseFile (File);
  773. FileAcquired = FALSE;
  774. }
  775. ObDereferenceObject (File);
  776. goto UnrefAndReturn;
  777. }
  778. }
  779. else {
  780. //
  781. // The size is okay in the segment.
  782. //
  783. EndOfFile = (UINT64) NewSegment->SizeOfSegment;
  784. }
  785. if (FileAcquired) {
  786. IoSetTopLevelIrp((PIRP)NULL);
  787. FsRtlReleaseFile (File);
  788. FileAcquired = FALSE;
  789. }
  790. ObDereferenceObject (File);
  791. if (*MaximumSize == 0) {
  792. Section.SizeOfSection.QuadPart = (LONGLONG)EndOfFile;
  793. FileSizeChecked = TRUE;
  794. }
  795. else if (EndOfFile >= *MaximumSize) {
  796. //
  797. // EndOfFile is greater than the MaximumSize,
  798. // use the specified maximum size.
  799. //
  800. Section.SizeOfSection.QuadPart = (LONGLONG)*MaximumSize;
  801. FileSizeChecked = TRUE;
  802. }
  803. else {
  804. //
  805. // Need to extend the section, make sure the file was
  806. // opened for write access.
  807. //
  808. if (((SectionPageProtection & PAGE_READWRITE) |
  809. (SectionPageProtection & PAGE_EXECUTE_READWRITE)) == 0) {
  810. Status = STATUS_SECTION_TOO_BIG;
  811. goto UnrefAndReturn;
  812. }
  813. Section.SizeOfSection.QuadPart = (LONGLONG)*MaximumSize;
  814. }
  815. }
  816. else {
  817. //
  818. // The file does not have an associated segment, create a segment
  819. // object.
  820. //
  821. PERFINFO_SECTION_CREATE1(File);
  822. if (AllocationAttributes & SEC_IMAGE) {
  823. Status = MiCreateImageFileMap (File, &Segment);
  824. }
  825. else {
  826. Status = MiCreateDataFileMap (File,
  827. &Segment,
  828. MaximumSize,
  829. SectionPageProtection,
  830. AllocationAttributes,
  831. IgnoreFileSizing );
  832. ASSERT (PreviousSectionPointer == File->SectionObjectPointer);
  833. }
  834. if (!NT_SUCCESS(Status)) {
  835. //
  836. // Lock the PFN database and check to see if another thread has
  837. // tried to create a segment to the file object at the same
  838. // time.
  839. //
  840. LOCK_PFN (OldIrql);
  841. Event = ControlArea->WaitingForDeletion;
  842. ControlArea->WaitingForDeletion = NULL;
  843. ASSERT (ControlArea->u.Flags.FilePointerNull == 0);
  844. ControlArea->u.Flags.FilePointerNull = 1;
  845. if (AllocationAttributes & SEC_IMAGE) {
  846. MiRemoveImageSectionObject (File, ControlArea);
  847. }
  848. else {
  849. File->SectionObjectPointer->DataSectionObject = NULL;
  850. }
  851. ControlArea->u.Flags.BeingCreated = 0;
  852. UNLOCK_PFN (OldIrql);
  853. if (FileAcquired) {
  854. IoSetTopLevelIrp((PIRP)NULL);
  855. FsRtlReleaseFile (File);
  856. }
  857. ExFreePool (NewControlArea);
  858. ObDereferenceObject (File);
  859. if (Event != NULL) {
  860. //
  861. // Signal any waiters that the segment structure exists.
  862. //
  863. KeSetEvent (&Event->Event, 0, FALSE);
  864. }
  865. return Status;
  866. }
  867. //
  868. // If the size was specified as zero, set the section size
  869. // from the created segment size. This solves problems with
  870. // race conditions when multiple sections
  871. // are created for the same mapped file with varying sizes.
  872. //
  873. if (*MaximumSize == 0) {
  874. Section.SizeOfSection.QuadPart = (LONGLONG)Segment->SizeOfSegment;
  875. }
  876. else {
  877. Section.SizeOfSection.QuadPart = (LONGLONG)*MaximumSize;
  878. }
  879. }
  880. }
  881. else {
  882. //
  883. // No file handle exists, this is a page file backed section.
  884. //
  885. if (AllocationAttributes & SEC_IMAGE) {
  886. return STATUS_INVALID_FILE_FOR_SECTION;
  887. }
  888. Status = MiCreatePagingFileMap (&NewSegment,
  889. MaximumSize,
  890. ProtectionMask,
  891. AllocationAttributes);
  892. if (!NT_SUCCESS(Status)) {
  893. return Status;
  894. }
  895. //
  896. // Set the section size from the created segment size. This
  897. // solves problems with race conditions when multiple sections
  898. // are created for the same mapped file with varying sizes.
  899. //
  900. Section.SizeOfSection.QuadPart = (LONGLONG)NewSegment->SizeOfSegment;
  901. ControlArea = NewSegment->ControlArea;
  902. //
  903. // Set IncrementedRefCount so any failures from this point before the
  904. // object is created will result in the control area & segment getting
  905. // torn down - otherwise these could leak. This is because pagefile
  906. // backed sections are not (and should not be) added to the
  907. // dereference segment cache.
  908. //
  909. IncrementedRefCount = 1;
  910. }
  911. if (NewSegment == NULL) {
  912. //
  913. // A new segment had to be created. Lock the PFN database and
  914. // check to see if any other threads also tried to create a new segment
  915. // for this file object at the same time.
  916. //
  917. NewSegment = Segment;
  918. SegmentControlArea = Segment->ControlArea;
  919. ASSERT (File != NULL);
  920. LOCK_PFN (OldIrql);
  921. Event = ControlArea->WaitingForDeletion;
  922. ControlArea->WaitingForDeletion = NULL;
  923. if (AllocationAttributes & SEC_IMAGE) {
  924. //
  925. // Change the control area in the file object pointer.
  926. //
  927. MiRemoveImageSectionObject (File, NewControlArea);
  928. MiInsertImageSectionObject (File, SegmentControlArea);
  929. ControlArea = SegmentControlArea;
  930. }
  931. else if (SegmentControlArea->u.Flags.Rom == 1) {
  932. ASSERT (File->SectionObjectPointer->DataSectionObject == NewControlArea);
  933. File->SectionObjectPointer->DataSectionObject = SegmentControlArea;
  934. ControlArea = SegmentControlArea;
  935. }
  936. ControlArea->u.Flags.BeingCreated = 0;
  937. UNLOCK_PFN (OldIrql);
  938. if ((AllocationAttributes & SEC_IMAGE) ||
  939. (SegmentControlArea->u.Flags.Rom == 1)) {
  940. //
  941. // Deallocate the pool used for the original control area.
  942. //
  943. ExFreePool (NewControlArea);
  944. }
  945. if (Event != NULL) {
  946. //
  947. // Signal any waiters that the segment structure exists.
  948. //
  949. KeSetEvent (&Event->Event, 0, FALSE);
  950. }
  951. PERFINFO_SECTION_CREATE(ControlArea);
  952. }
  953. //
  954. // Being created has now been cleared allowing other threads
  955. // to reference the segment. Release the resource on the file.
  956. //
  957. if (FileAcquired) {
  958. IoSetTopLevelIrp((PIRP)NULL);
  959. FsRtlReleaseFile (File);
  960. FileAcquired = FALSE;
  961. }
  962. ReferenceObject:
  963. if (ChangeFileReference) {
  964. ObReferenceObject (FileObject);
  965. }
  966. //
  967. // Now that the segment object is created, make the section object
  968. // refer to the segment object.
  969. //
  970. Section.Segment = NewSegment;
  971. Section.u.LongFlags = ControlArea->u.LongFlags;
  972. //
  973. // Update the count of writable user sections so the transaction semantics
  974. // can be supported. Note that no lock synchronization is needed here as
  975. // the transaction manager must already check for any open writable handles
  976. // to the file - and no writable sections can be created without a writable
  977. // file handle. So all that needs to be provided is a way for the
  978. // transaction manager to know that there are lingering user views or
  979. // created sections still open that have write access.
  980. //
  981. // This must be done before creating the object so a rogue user program
  982. // that suspends this thread cannot subvert a transaction.
  983. //
  984. if ((FileObject == NULL) &&
  985. (SectionPageProtection & (PAGE_READWRITE|PAGE_EXECUTE_READWRITE)) &&
  986. (ControlArea->u.Flags.Image == 0) &&
  987. (ControlArea->FilePointer != NULL)) {
  988. Section.u.Flags.UserWritable = 1;
  989. InterlockedIncrement ((PLONG)&ControlArea->Segment->WritableUserReferences);
  990. }
  991. //
  992. // Create the section object now. The section object is created
  993. // now so that the error handling when the section object cannot
  994. // be created is simplified.
  995. //
  996. Status = ObCreateObject (PreviousMode,
  997. MmSectionObjectType,
  998. ObjectAttributes,
  999. PreviousMode,
  1000. NULL,
  1001. sizeof(SECTION),
  1002. sizeof(SECTION) +
  1003. NewSegment->TotalNumberOfPtes * sizeof(MMPTE),
  1004. sizeof(CONTROL_AREA) +
  1005. NewSegment->ControlArea->NumberOfSubsections *
  1006. sizeof(SUBSECTION),
  1007. (PVOID *)&NewSection);
  1008. if (!NT_SUCCESS(Status)) {
  1009. if ((FileObject == NULL) &&
  1010. (SectionPageProtection & (PAGE_READWRITE|PAGE_EXECUTE_READWRITE)) &&
  1011. (ControlArea->u.Flags.Image == 0) &&
  1012. (ControlArea->FilePointer != NULL)) {
  1013. ASSERT (Section.u.Flags.UserWritable == 1);
  1014. InterlockedDecrement ((PLONG)&ControlArea->Segment->WritableUserReferences);
  1015. }
  1016. goto UnrefAndReturn;
  1017. }
  1018. RtlCopyMemory (NewSection, &Section, sizeof(SECTION));
  1019. NewSection->Address.StartingVpn = 0;
  1020. if (!IgnoreFileSizing) {
  1021. //
  1022. // Indicate that the cache manager is not the owner of this
  1023. // section.
  1024. //
  1025. NewSection->u.Flags.UserReference = 1;
  1026. if (AllocationAttributes & SEC_NO_CHANGE) {
  1027. //
  1028. // Indicate that once the section is mapped, no protection
  1029. // changes or freeing the mapping is allowed.
  1030. //
  1031. NewSection->u.Flags.NoChange = 1;
  1032. }
  1033. if (((SectionPageProtection & PAGE_READWRITE) |
  1034. (SectionPageProtection & PAGE_EXECUTE_READWRITE)) == 0) {
  1035. //
  1036. // This section does not support WRITE access, indicate
  1037. // that changing the protection to WRITE results in COPY_ON_WRITE.
  1038. //
  1039. NewSection->u.Flags.CopyOnWrite = 1;
  1040. }
  1041. if (AllocationAttributes & SEC_BASED) {
  1042. NewSection->u.Flags.Based = 1;
  1043. SectionBasedRoot = &MmSectionBasedRoot;
  1044. //
  1045. // This section is based at a unique address system wide.
  1046. // Ensure it does not wrap the virtual address space as the
  1047. // SECTION structure would have to widen to accomodate this and
  1048. // it's not worth the performance penalty for the very few isolated
  1049. // cases that would want this. Note that sections larger than the
  1050. // address space can easily be created - it's just that beyond a
  1051. // certain point you shouldn't specify SEC_BASED (anything this big
  1052. // couldn't use a SEC_BASED section for anything anyway).
  1053. //
  1054. if ((UINT64)NewSection->SizeOfSection.QuadPart > (UINT64)MmHighSectionBase) {
  1055. ObDereferenceObject (NewSection);
  1056. return STATUS_NO_MEMORY;
  1057. }
  1058. #if defined(_WIN64)
  1059. SizeOfSection = NewSection->SizeOfSection.QuadPart;
  1060. #else
  1061. SizeOfSection = NewSection->SizeOfSection.LowPart;
  1062. #endif
  1063. //
  1064. // Get the allocation base mutex.
  1065. //
  1066. ExAcquireFastMutex (&MmSectionBasedMutex);
  1067. Status2 = MiFindEmptyAddressRangeDownTree (
  1068. SizeOfSection,
  1069. MmHighSectionBase,
  1070. X64K,
  1071. MmSectionBasedRoot,
  1072. (PVOID *)&NewSection->Address.StartingVpn);
  1073. if (!NT_SUCCESS(Status2)) {
  1074. ExReleaseFastMutex (&MmSectionBasedMutex);
  1075. ObDereferenceObject (NewSection);
  1076. return Status2;
  1077. }
  1078. NewSection->Address.EndingVpn = NewSection->Address.StartingVpn +
  1079. SizeOfSection - 1;
  1080. MiInsertBasedSection (NewSection);
  1081. ExReleaseFastMutex (&MmSectionBasedMutex);
  1082. }
  1083. }
  1084. //
  1085. // If the cache manager is creating the section, set the was
  1086. // purged flag as the file size can change.
  1087. //
  1088. ControlArea->u.Flags.WasPurged |= IgnoreFileSizing;
  1089. //
  1090. // Check to see if the section is for a data file and the size
  1091. // of the section is greater than the current size of the
  1092. // segment.
  1093. //
  1094. if (((ControlArea->u.Flags.WasPurged == 1) && (!IgnoreFileSizing)) &&
  1095. (!FileSizeChecked)
  1096. ||
  1097. ((UINT64)NewSection->SizeOfSection.QuadPart >
  1098. NewSection->Segment->SizeOfSegment)) {
  1099. TempSectionSize = NewSection->SizeOfSection;
  1100. NewSection->SizeOfSection.QuadPart = (LONGLONG)NewSection->Segment->SizeOfSegment;
  1101. //
  1102. // Even if the caller didn't specify extension rights, we enable it here
  1103. // temporarily to make the section correct. Use a temporary section
  1104. // instead of temporarily editing the real section to avoid opening
  1105. // a security window that other concurrent threads could exploit.
  1106. //
  1107. if (((NewSection->InitialPageProtection & PAGE_READWRITE) |
  1108. (NewSection->InitialPageProtection & PAGE_EXECUTE_READWRITE)) == 0) {
  1109. SECTION WritableSection;
  1110. *(PSECTION)&WritableSection = *NewSection;
  1111. Status = MmExtendSection (&WritableSection,
  1112. &TempSectionSize,
  1113. IgnoreFileSizing);
  1114. NewSection->SizeOfSection = WritableSection.SizeOfSection;
  1115. }
  1116. else {
  1117. Status = MmExtendSection (NewSection,
  1118. &TempSectionSize,
  1119. IgnoreFileSizing);
  1120. }
  1121. if (!NT_SUCCESS(Status)) {
  1122. ObDereferenceObject (NewSection);
  1123. return Status;
  1124. }
  1125. }
  1126. *SectionObject = (PVOID)NewSection;
  1127. return Status;
  1128. UnrefAndReturn:
  1129. //
  1130. // Unreference the control area, if it was referenced and return
  1131. // the error status.
  1132. //
  1133. if (FileAcquired) {
  1134. IoSetTopLevelIrp((PIRP)NULL);
  1135. FsRtlReleaseFile (File);
  1136. }
  1137. if (IncrementedRefCount) {
  1138. LOCK_PFN (OldIrql);
  1139. ControlArea->NumberOfSectionReferences -= 1;
  1140. if (!IgnoreFileSizing) {
  1141. ASSERT ((LONG)ControlArea->NumberOfUserReferences > 0);
  1142. ControlArea->NumberOfUserReferences -= 1;
  1143. }
  1144. MiCheckControlArea (ControlArea, NULL, OldIrql);
  1145. }
  1146. return Status;
  1147. }
  1148. LOGICAL
  1149. MiMakeControlAreaRom (
  1150. IN PFILE_OBJECT File,
  1151. IN PLARGE_CONTROL_AREA ControlArea,
  1152. IN PFN_NUMBER PageFrameNumber
  1153. )
  1154. /*++
  1155. Routine Description:
  1156. This function marks the control area as ROM-backed. It can fail if the
  1157. parallel control area (image vs data) is currently active as ROM-backed
  1158. as the same PFNs cannot be used for both control areas simultaneously.
  1159. Arguments:
  1160. ControlArea - Supplies the relevant control area.
  1161. PageFrameNumber - Supplies the starting physical page frame number.
  1162. Return Value:
  1163. TRUE if the control area was marked as ROM-backed, FALSE if not.
  1164. --*/
  1165. {
  1166. LOGICAL ControlAreaMarked;
  1167. PCONTROL_AREA OtherControlArea;
  1168. KIRQL OldIrql;
  1169. ControlAreaMarked = FALSE;
  1170. LOCK_PFN (OldIrql);
  1171. if (ControlArea->u.Flags.Image == 1) {
  1172. OtherControlArea = (PCONTROL_AREA) File->SectionObjectPointer->DataSectionObject;
  1173. }
  1174. else {
  1175. OtherControlArea = (PCONTROL_AREA) File->SectionObjectPointer->ImageSectionObject;
  1176. }
  1177. //
  1178. // This could be made smarter (ie: throw away the other control area if it's
  1179. // not in use) but for now, keep it simple.
  1180. //
  1181. if ((OtherControlArea == NULL) || (OtherControlArea->u.Flags.Rom == 0)) {
  1182. ControlArea->u.Flags.Rom = 1;
  1183. ControlArea->StartingFrame = PageFrameNumber;
  1184. ControlAreaMarked = TRUE;
  1185. }
  1186. UNLOCK_PFN (OldIrql);
  1187. return ControlAreaMarked;
  1188. }
  1189. NTSTATUS
  1190. MiCreateImageFileMap (
  1191. IN PFILE_OBJECT File,
  1192. OUT PSEGMENT *Segment
  1193. )
  1194. /*++
  1195. Routine Description:
  1196. This function creates the necessary structures to allow the mapping
  1197. of an image file.
  1198. The image file is opened and verified for correctness, a segment
  1199. object is created and initialized based on data in the image
  1200. header.
  1201. Arguments:
  1202. File - Supplies the file object for the image file.
  1203. Segment - Returns the segment object.
  1204. Return Value:
  1205. NTSTATUS.
  1206. --*/
  1207. {
  1208. NTSTATUS Status;
  1209. ULONG_PTR EndingAddress;
  1210. ULONG NumberOfPtes;
  1211. ULONG SizeOfSegment;
  1212. ULONG SectionVirtualSize;
  1213. ULONG i;
  1214. ULONG j;
  1215. PCONTROL_AREA ControlArea;
  1216. PSUBSECTION Subsection;
  1217. PMMPTE PointerPte;
  1218. MMPTE TempPte;
  1219. MMPTE TempPteDemandZero;
  1220. PVOID Base;
  1221. PIMAGE_DOS_HEADER DosHeader;
  1222. PIMAGE_NT_HEADERS NtHeader;
  1223. PIMAGE_FILE_HEADER FileHeader;
  1224. ULONG SizeOfImage;
  1225. ULONG SizeOfHeaders;
  1226. #if defined (_WIN64)
  1227. PIMAGE_NT_HEADERS32 NtHeader32;
  1228. #endif
  1229. PIMAGE_DATA_DIRECTORY ComPlusDirectoryEntry;
  1230. PIMAGE_SECTION_HEADER SectionTableEntry;
  1231. PSEGMENT NewSegment;
  1232. ULONG SectorOffset;
  1233. ULONG NumberOfSubsections;
  1234. PFN_NUMBER PageFrameNumber;
  1235. PFN_NUMBER XipFrameNumber;
  1236. LOGICAL XipFile;
  1237. LOGICAL GlobalPerSession;
  1238. LARGE_INTEGER StartingOffset;
  1239. PCHAR ExtendedHeader;
  1240. PPFN_NUMBER Page;
  1241. ULONG_PTR PreferredImageBase;
  1242. ULONG_PTR NextVa;
  1243. ULONG_PTR ImageBase;
  1244. PKEVENT InPageEvent;
  1245. PMDL Mdl;
  1246. ULONG ImageFileSize;
  1247. ULONG OffsetToSectionTable;
  1248. ULONG ImageAlignment;
  1249. ULONG RoundingAlignment;
  1250. ULONG FileAlignment;
  1251. LOGICAL ImageCommit;
  1252. LOGICAL SectionCommit;
  1253. IO_STATUS_BLOCK IoStatus;
  1254. LARGE_INTEGER EndOfFile;
  1255. ULONG NtHeaderSize;
  1256. ULONG SubsectionsAllocated;
  1257. PLARGE_CONTROL_AREA LargeControlArea;
  1258. PSUBSECTION NewSubsection;
  1259. ULONG OriginalProtection;
  1260. ULONG LoaderFlags;
  1261. ULONG TempNumberOfSubsections;
  1262. PIMAGE_SECTION_HEADER TempSectionTableEntry;
  1263. ULONG AdditionalSubsections;
  1264. ULONG AdditionalPtes;
  1265. ULONG AdditionalBasePtes;
  1266. ULONG NewSubsectionsAllocated;
  1267. PSEGMENT OldSegment;
  1268. PMMPTE NewPointerPte;
  1269. PMMPTE OldPointerPte;
  1270. ULONG OrigNumberOfPtes;
  1271. PCONTROL_AREA NewControlArea;
  1272. SIZE_T NumberOfCommittedPages;
  1273. PHYSICAL_ADDRESS PhysicalAddress;
  1274. LOGICAL ActiveDataReferences;
  1275. #if defined (_IA64_)
  1276. LOGICAL InvalidAlignmentAllowed;
  1277. InvalidAlignmentAllowed = FALSE;
  1278. #else
  1279. #define InvalidAlignmentAllowed FALSE
  1280. #endif
  1281. PAGED_CODE();
  1282. ExtendedHeader = NULL;
  1283. Status = FsRtlGetFileSize (File, &EndOfFile);
  1284. if (Status == STATUS_FILE_IS_A_DIRECTORY) {
  1285. //
  1286. // Can't map a directory as a section. Return error.
  1287. //
  1288. return STATUS_INVALID_FILE_FOR_SECTION;
  1289. }
  1290. if (!NT_SUCCESS (Status)) {
  1291. return Status;
  1292. }
  1293. if (EndOfFile.HighPart != 0) {
  1294. //
  1295. // File too big. Return error.
  1296. //
  1297. return STATUS_INVALID_FILE_FOR_SECTION;
  1298. }
  1299. //
  1300. // Create a segment which maps an image file.
  1301. // For now map a COFF image file with the subsections
  1302. // containing the based address of the file.
  1303. //
  1304. //
  1305. // Read in the file header.
  1306. //
  1307. InPageEvent = ExAllocatePoolWithTag (NonPagedPool,
  1308. sizeof(KEVENT) + MmSizeOfMdl (
  1309. NULL,
  1310. MM_MAXIMUM_IMAGE_HEADER),
  1311. MMTEMPORARY);
  1312. if (InPageEvent == NULL) {
  1313. return STATUS_INSUFFICIENT_RESOURCES;
  1314. }
  1315. //
  1316. // Initializing IoStatus.Information is not needed for correctness, but
  1317. // without it the compiler cannot compile this code W4 to check
  1318. // for use of uninitialized variables.
  1319. //
  1320. IoStatus.Information = 0;
  1321. Mdl = (PMDL)(InPageEvent + 1);
  1322. //
  1323. // Create an event for the read operation.
  1324. //
  1325. KeInitializeEvent (InPageEvent, NotificationEvent, FALSE);
  1326. //
  1327. // Build an MDL for the operation.
  1328. //
  1329. MmCreateMdl( Mdl, NULL, PAGE_SIZE);
  1330. Mdl->MdlFlags |= MDL_PAGES_LOCKED;
  1331. PageFrameNumber = MiGetPageForHeader();
  1332. Page = (PPFN_NUMBER)(Mdl + 1);
  1333. *Page = PageFrameNumber;
  1334. ZERO_LARGE (StartingOffset);
  1335. CcZeroEndOfLastPage (File);
  1336. //
  1337. // Flush the data section if there is one.
  1338. //
  1339. // At the same time, capture whether there are any references to the
  1340. // data control area. If so, flip the pages from the image control
  1341. // area into pagefile backings to prevent anyone else's data writes
  1342. // from changing the file after it is validated (this can happen if the
  1343. // pages from the image control area need to be re-paged in later).
  1344. //
  1345. ActiveDataReferences = MiFlushDataSection (File);
  1346. Base = MiCopyHeaderIfResident (File, PageFrameNumber);
  1347. if (Base == NULL) {
  1348. Mdl->MdlFlags |= MDL_PAGES_LOCKED;
  1349. Status = IoPageRead (File,
  1350. Mdl,
  1351. &StartingOffset,
  1352. InPageEvent,
  1353. &IoStatus);
  1354. if (Status == STATUS_PENDING) {
  1355. KeWaitForSingleObject( InPageEvent,
  1356. WrPageIn,
  1357. KernelMode,
  1358. FALSE,
  1359. NULL);
  1360. Status = IoStatus.Status;
  1361. }
  1362. if (Mdl->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA) {
  1363. MmUnmapLockedPages (Mdl->MappedSystemVa, Mdl);
  1364. }
  1365. if (!NT_SUCCESS(Status)) {
  1366. if ((Status != STATUS_FILE_LOCK_CONFLICT) && (Status != STATUS_FILE_IS_OFFLINE)) {
  1367. Status = STATUS_INVALID_FILE_FOR_SECTION;
  1368. }
  1369. goto BadSection;
  1370. }
  1371. Base = MiMapImageHeaderInHyperSpace (PageFrameNumber);
  1372. if (IoStatus.Information != PAGE_SIZE) {
  1373. //
  1374. // A full page was not read from the file, zero any remaining
  1375. // bytes.
  1376. //
  1377. RtlZeroMemory ((PVOID)((PCHAR)Base + IoStatus.Information),
  1378. PAGE_SIZE - IoStatus.Information);
  1379. }
  1380. }
  1381. DosHeader = (PIMAGE_DOS_HEADER)Base;
  1382. //
  1383. // Check to determine if this is an NT image (PE format) or
  1384. // a DOS image, Win-16 image, or OS/2 image. If the image is
  1385. // not NT format, return an error indicating which image it
  1386. // appears to be.
  1387. //
  1388. if (DosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
  1389. Status = STATUS_INVALID_IMAGE_NOT_MZ;
  1390. goto NeImage;
  1391. }
  1392. #ifndef i386
  1393. if (((ULONG)DosHeader->e_lfanew & 3) != 0) {
  1394. //
  1395. // The image header is not aligned on a longword boundary.
  1396. // Report this as an invalid protect mode image.
  1397. //
  1398. Status = STATUS_INVALID_IMAGE_PROTECT;
  1399. goto NeImage;
  1400. }
  1401. #endif
  1402. if ((ULONG)DosHeader->e_lfanew > EndOfFile.LowPart) {
  1403. Status = STATUS_INVALID_IMAGE_PROTECT;
  1404. goto NeImage;
  1405. }
  1406. if (((ULONG)DosHeader->e_lfanew +
  1407. sizeof(IMAGE_NT_HEADERS) +
  1408. (16 * sizeof(IMAGE_SECTION_HEADER))) <= (ULONG)DosHeader->e_lfanew) {
  1409. Status = STATUS_INVALID_IMAGE_PROTECT;
  1410. goto NeImage;
  1411. }
  1412. if (((ULONG)DosHeader->e_lfanew +
  1413. sizeof(IMAGE_NT_HEADERS) +
  1414. (16 * sizeof(IMAGE_SECTION_HEADER))) > PAGE_SIZE) {
  1415. //
  1416. // The PE header is not within the page already read or the
  1417. // objects are in another page.
  1418. // Build another MDL and read an additional 8k.
  1419. //
  1420. ExtendedHeader = ExAllocatePoolWithTag (NonPagedPool,
  1421. MM_MAXIMUM_IMAGE_HEADER,
  1422. MMTEMPORARY);
  1423. if (ExtendedHeader == NULL) {
  1424. Status = STATUS_INSUFFICIENT_RESOURCES;
  1425. goto NeImage;
  1426. }
  1427. //
  1428. // Build an MDL for the operation.
  1429. //
  1430. MmCreateMdl( Mdl, ExtendedHeader, MM_MAXIMUM_IMAGE_HEADER);
  1431. MmBuildMdlForNonPagedPool (Mdl);
  1432. StartingOffset.LowPart = PtrToUlong(PAGE_ALIGN ((ULONG)DosHeader->e_lfanew));
  1433. KeClearEvent (InPageEvent);
  1434. Status = IoPageRead (File,
  1435. Mdl,
  1436. &StartingOffset,
  1437. InPageEvent,
  1438. &IoStatus);
  1439. if (Status == STATUS_PENDING) {
  1440. KeWaitForSingleObject (InPageEvent,
  1441. WrPageIn,
  1442. KernelMode,
  1443. FALSE,
  1444. NULL);
  1445. Status = IoStatus.Status;
  1446. }
  1447. if (Mdl->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA) {
  1448. MmUnmapLockedPages (Mdl->MappedSystemVa, Mdl);
  1449. }
  1450. if (!NT_SUCCESS(Status)) {
  1451. if ((Status != STATUS_FILE_LOCK_CONFLICT) && (Status != STATUS_FILE_IS_OFFLINE)) {
  1452. Status = STATUS_INVALID_FILE_FOR_SECTION;
  1453. }
  1454. goto NeImage;
  1455. }
  1456. NtHeader = (PIMAGE_NT_HEADERS)((PCHAR)ExtendedHeader +
  1457. BYTE_OFFSET((ULONG)DosHeader->e_lfanew));
  1458. NtHeaderSize = MM_MAXIMUM_IMAGE_HEADER -
  1459. (ULONG)(BYTE_OFFSET((ULONG)DosHeader->e_lfanew));
  1460. }
  1461. else {
  1462. NtHeader = (PIMAGE_NT_HEADERS)((PCHAR)DosHeader +
  1463. (ULONG)DosHeader->e_lfanew);
  1464. NtHeaderSize = PAGE_SIZE - (ULONG)DosHeader->e_lfanew;
  1465. }
  1466. FileHeader = &NtHeader->FileHeader;
  1467. //
  1468. // Check to see if this is an NT image or a DOS or OS/2 image.
  1469. //
  1470. Status = MiVerifyImageHeader (NtHeader, DosHeader, NtHeaderSize);
  1471. if (Status != STATUS_SUCCESS) {
  1472. goto NeImage;
  1473. }
  1474. #if defined(_WIN64)
  1475. if (NtHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  1476. //
  1477. // The image is 32-bit. All code below this point must check
  1478. // if NtHeader is NULL. If it is, then the image is PE32 and
  1479. // NtHeader32 must be used.
  1480. //
  1481. NtHeader32 = (PIMAGE_NT_HEADERS32)NtHeader;
  1482. NtHeader = NULL;
  1483. }
  1484. else {
  1485. NtHeader32 = NULL;
  1486. }
  1487. if (NtHeader) {
  1488. #endif
  1489. ImageAlignment = NtHeader->OptionalHeader.SectionAlignment;
  1490. FileAlignment = NtHeader->OptionalHeader.FileAlignment - 1;
  1491. SizeOfImage = NtHeader->OptionalHeader.SizeOfImage;
  1492. LoaderFlags = NtHeader->OptionalHeader.LoaderFlags;
  1493. ImageBase = NtHeader->OptionalHeader.ImageBase;
  1494. SizeOfHeaders = NtHeader->OptionalHeader.SizeOfHeaders;
  1495. //
  1496. // Read in the COM+ directory entry.
  1497. //
  1498. ComPlusDirectoryEntry = &NtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR];
  1499. #if defined (_WIN64)
  1500. }
  1501. else {
  1502. ImageAlignment = NtHeader32->OptionalHeader.SectionAlignment;
  1503. FileAlignment = NtHeader32->OptionalHeader.FileAlignment - 1;
  1504. SizeOfImage = NtHeader32->OptionalHeader.SizeOfImage;
  1505. LoaderFlags = NtHeader32->OptionalHeader.LoaderFlags;
  1506. ImageBase = NtHeader32->OptionalHeader.ImageBase;
  1507. SizeOfHeaders = NtHeader32->OptionalHeader.SizeOfHeaders;
  1508. //
  1509. // Read in the COM+ directory entry.
  1510. //
  1511. ComPlusDirectoryEntry = &NtHeader32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR];
  1512. }
  1513. #endif
  1514. //
  1515. // Set the appropriate bit for .NET images inside the image's section loader flags.
  1516. //
  1517. if ((ComPlusDirectoryEntry->VirtualAddress != 0) && (ComPlusDirectoryEntry->Size != 0)) {
  1518. LoaderFlags |= IMAGE_LOADER_FLAGS_COMPLUS;
  1519. }
  1520. RoundingAlignment = ImageAlignment;
  1521. NumberOfSubsections = FileHeader->NumberOfSections;
  1522. if (ImageAlignment < PAGE_SIZE) {
  1523. //
  1524. // The image alignment is less than the page size,
  1525. // map the image with a single subsection.
  1526. //
  1527. ControlArea = ExAllocatePoolWithTag (NonPagedPool,
  1528. (ULONG)(sizeof(CONTROL_AREA) + (sizeof(SUBSECTION))),
  1529. MMCONTROL);
  1530. SubsectionsAllocated = 1;
  1531. }
  1532. else {
  1533. //
  1534. // Allocate a control area and a subsection for each section
  1535. // header plus one for the image header which has no section.
  1536. //
  1537. ControlArea = ExAllocatePoolWithTag(NonPagedPool,
  1538. (ULONG)(sizeof(CONTROL_AREA) +
  1539. (sizeof(SUBSECTION) *
  1540. (NumberOfSubsections + 1))),
  1541. 'iCmM');
  1542. SubsectionsAllocated = NumberOfSubsections + 1;
  1543. }
  1544. if (ControlArea == NULL) {
  1545. //
  1546. // The requested pool could not be allocated.
  1547. //
  1548. Status = STATUS_INSUFFICIENT_RESOURCES;
  1549. goto NeImage;
  1550. }
  1551. //
  1552. // Zero the control area and the FIRST subsection.
  1553. //
  1554. RtlZeroMemory (ControlArea, sizeof(CONTROL_AREA) + sizeof(SUBSECTION));
  1555. ASSERT (ControlArea->u.Flags.GlobalOnlyPerSession == 0);
  1556. Subsection = (PSUBSECTION)(ControlArea + 1);
  1557. NumberOfPtes = BYTES_TO_PAGES (SizeOfImage);
  1558. if (NumberOfPtes == 0) {
  1559. ExFreePool (ControlArea);
  1560. Status = STATUS_INVALID_IMAGE_FORMAT;
  1561. goto NeImage;
  1562. }
  1563. #if defined (_WIN64)
  1564. if (NumberOfPtes >= _4gb) {
  1565. ExFreePool (ControlArea);
  1566. Status = STATUS_INVALID_IMAGE_FORMAT;
  1567. goto NeImage;
  1568. }
  1569. #endif
  1570. #if defined (_IA64_)
  1571. if ((ImageAlignment < PAGE_SIZE) &&
  1572. (KeGetPreviousMode() != KernelMode) &&
  1573. ((FileHeader->Machine < USER_SHARED_DATA->ImageNumberLow) ||
  1574. (FileHeader->Machine > USER_SHARED_DATA->ImageNumberHigh))) {
  1575. InvalidAlignmentAllowed = TRUE;
  1576. }
  1577. OrigNumberOfPtes = NumberOfPtes;
  1578. #endif
  1579. SizeOfSegment = sizeof(SEGMENT) + (sizeof(MMPTE) * (NumberOfPtes - 1)) +
  1580. sizeof(SECTION_IMAGE_INFORMATION);
  1581. NewSegment = ExAllocatePoolWithTag (PagedPool, SizeOfSegment, MMSECT);
  1582. if (NewSegment == NULL) {
  1583. //
  1584. // The requested pool could not be allocated.
  1585. //
  1586. ExFreePool (ControlArea);
  1587. Status = STATUS_INSUFFICIENT_RESOURCES;
  1588. goto NeImage;
  1589. }
  1590. *Segment = NewSegment;
  1591. RtlZeroMemory (NewSegment, sizeof(SEGMENT));
  1592. //
  1593. // Align the prototype PTEs on the proper boundary.
  1594. //
  1595. PointerPte = &NewSegment->ThePtes[0];
  1596. i = (ULONG) (((ULONG_PTR)PointerPte >> PTE_SHIFT) &
  1597. ((MM_PROTO_PTE_ALIGNMENT / PAGE_SIZE) - 1));
  1598. if (i != 0) {
  1599. i = (MM_PROTO_PTE_ALIGNMENT / PAGE_SIZE) - i;
  1600. }
  1601. NewSegment->PrototypePte = &NewSegment->ThePtes[i];
  1602. NewSegment->ControlArea = ControlArea;
  1603. NewSegment->u2.ImageInformation =
  1604. (PSECTION_IMAGE_INFORMATION)((PCHAR)NewSegment + sizeof(SEGMENT) +
  1605. (sizeof(MMPTE) * (NumberOfPtes - 1)));
  1606. NewSegment->TotalNumberOfPtes = NumberOfPtes;
  1607. NewSegment->NonExtendedPtes = NumberOfPtes;
  1608. NewSegment->SizeOfSegment = (ULONG_PTR)NumberOfPtes * PAGE_SIZE;
  1609. RtlZeroMemory (NewSegment->u2.ImageInformation,
  1610. sizeof (SECTION_IMAGE_INFORMATION));
  1611. //
  1612. // This code is built twice on the Win64 build - once for PE32+ and once for
  1613. // PE32 images.
  1614. //
  1615. #define INIT_IMAGE_INFORMATION(OptHdr) { \
  1616. NewSegment->u2.ImageInformation->TransferAddress = \
  1617. (PVOID)((ULONG_PTR)((OptHdr).ImageBase) + \
  1618. (OptHdr).AddressOfEntryPoint); \
  1619. NewSegment->u2.ImageInformation->MaximumStackSize = \
  1620. (OptHdr).SizeOfStackReserve; \
  1621. NewSegment->u2.ImageInformation->CommittedStackSize = \
  1622. (OptHdr).SizeOfStackCommit; \
  1623. NewSegment->u2.ImageInformation->SubSystemType = \
  1624. (OptHdr).Subsystem; \
  1625. NewSegment->u2.ImageInformation->SubSystemMajorVersion = (USHORT)((OptHdr).MajorSubsystemVersion); \
  1626. NewSegment->u2.ImageInformation->SubSystemMinorVersion = (USHORT)((OptHdr).MinorSubsystemVersion); \
  1627. NewSegment->u2.ImageInformation->DllCharacteristics = \
  1628. (OptHdr).DllCharacteristics; \
  1629. NewSegment->u2.ImageInformation->ImageContainsCode = \
  1630. (BOOLEAN)(((OptHdr).SizeOfCode != 0) || \
  1631. ((OptHdr).AddressOfEntryPoint != 0)); \
  1632. }
  1633. #if defined (_WIN64)
  1634. if (NtHeader) {
  1635. #endif
  1636. INIT_IMAGE_INFORMATION(NtHeader->OptionalHeader);
  1637. #if defined (_WIN64)
  1638. }
  1639. else {
  1640. //
  1641. // The image is 32-bit so use the 32-bit header
  1642. //
  1643. INIT_IMAGE_INFORMATION(NtHeader32->OptionalHeader);
  1644. }
  1645. #endif
  1646. #undef INIT_IMAGE_INFORMATION
  1647. NewSegment->u2.ImageInformation->ImageCharacteristics =
  1648. FileHeader->Characteristics;
  1649. NewSegment->u2.ImageInformation->Machine =
  1650. FileHeader->Machine;
  1651. NewSegment->u2.ImageInformation->LoaderFlags =
  1652. LoaderFlags;
  1653. ControlArea->Segment = NewSegment;
  1654. ControlArea->NumberOfSectionReferences = 1;
  1655. ControlArea->NumberOfUserReferences = 1;
  1656. ControlArea->u.Flags.BeingCreated = 1;
  1657. if (ImageAlignment < PAGE_SIZE) {
  1658. //
  1659. // Image alignment is less than a page, the number
  1660. // of subsections is 1.
  1661. //
  1662. ControlArea->NumberOfSubsections = 1;
  1663. }
  1664. else {
  1665. ControlArea->NumberOfSubsections = (USHORT)NumberOfSubsections;
  1666. }
  1667. ControlArea->u.Flags.Image = 1;
  1668. ControlArea->u.Flags.File = 1;
  1669. if ((ActiveDataReferences == TRUE) ||
  1670. (IoIsDeviceEjectable(File->DeviceObject)) ||
  1671. ((FileHeader->Characteristics &
  1672. IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP) &&
  1673. (FILE_REMOVABLE_MEDIA & File->DeviceObject->Characteristics)) ||
  1674. ((FileHeader->Characteristics &
  1675. IMAGE_FILE_NET_RUN_FROM_SWAP) &&
  1676. (FILE_REMOTE_DEVICE & File->DeviceObject->Characteristics))) {
  1677. //
  1678. // This file resides on a floppy disk or a removable media or
  1679. // network with flags set indicating it should be copied
  1680. // to the paging file.
  1681. //
  1682. ControlArea->u.Flags.FloppyMedia = 1;
  1683. }
  1684. #if DBG
  1685. if (MiMakeImageFloppy[0] & 0x1) {
  1686. MiMakeImageFloppy[1] += 1;
  1687. ControlArea->u.Flags.FloppyMedia = 1;
  1688. }
  1689. #endif
  1690. if (FILE_REMOTE_DEVICE & File->DeviceObject->Characteristics) {
  1691. //
  1692. // This file resides on a redirected drive.
  1693. //
  1694. ControlArea->u.Flags.Networked = 1;
  1695. }
  1696. ControlArea->FilePointer = File;
  1697. //
  1698. // Build the subsection and prototype PTEs for the image header.
  1699. //
  1700. Subsection->ControlArea = ControlArea;
  1701. NextVa = ImageBase;
  1702. #if defined (_WIN64)
  1703. //
  1704. // Don't let bogus headers cause system alignment faults.
  1705. //
  1706. if (FileHeader->SizeOfOptionalHeader & (sizeof (ULONG_PTR) - 1)) {
  1707. goto BadPeImageSegment;
  1708. }
  1709. #endif
  1710. if ((NextVa & (X64K - 1)) != 0) {
  1711. //
  1712. // Image header is not aligned on a 64k boundary.
  1713. //
  1714. goto BadPeImageSegment;
  1715. }
  1716. NewSegment->BasedAddress = (PVOID)NextVa;
  1717. if (SizeOfHeaders >= SizeOfImage) {
  1718. goto BadPeImageSegment;
  1719. }
  1720. Subsection->PtesInSubsection = MI_ROUND_TO_SIZE (
  1721. SizeOfHeaders,
  1722. ImageAlignment
  1723. ) >> PAGE_SHIFT;
  1724. PointerPte = NewSegment->PrototypePte;
  1725. Subsection->SubsectionBase = PointerPte;
  1726. TempPte.u.Long = MiGetSubsectionAddressForPte (Subsection);
  1727. TempPte.u.Soft.Prototype = 1;
  1728. NewSegment->SegmentPteTemplate = TempPte;
  1729. SectorOffset = 0;
  1730. if (ImageAlignment < PAGE_SIZE) {
  1731. //
  1732. // Aligned on less than a page size boundary.
  1733. // Build a single subsection to refer to the image.
  1734. //
  1735. PointerPte = NewSegment->PrototypePte;
  1736. Subsection->PtesInSubsection = NumberOfPtes;
  1737. #if !defined (_WIN64)
  1738. //
  1739. // Note this only needs to be checked for 32-bit systems as NT64
  1740. // does a much more extensive reallocation of images that are built
  1741. // with alignment less than PAGE_SIZE.
  1742. //
  1743. if ((UINT64)SizeOfImage < (UINT64)EndOfFile.QuadPart) {
  1744. //
  1745. // Images that have a size of image (according to the header) that's
  1746. // smaller than the actual file only get that many prototype PTEs.
  1747. // Initialize the subsection properly so no one can read off the
  1748. // end as that would corrupt the PFN database element's original
  1749. // PTE entry.
  1750. //
  1751. Subsection->NumberOfFullSectors = (SizeOfImage >> MMSECTOR_SHIFT);
  1752. Subsection->u.SubsectionFlags.SectorEndOffset =
  1753. SizeOfImage & MMSECTOR_MASK;
  1754. }
  1755. else {
  1756. #endif
  1757. Subsection->NumberOfFullSectors =
  1758. (ULONG)(EndOfFile.QuadPart >> MMSECTOR_SHIFT);
  1759. ASSERT ((ULONG)(EndOfFile.HighPart & 0xFFFFF000) == 0);
  1760. Subsection->u.SubsectionFlags.SectorEndOffset =
  1761. EndOfFile.LowPart & MMSECTOR_MASK;
  1762. #if !defined (_WIN64)
  1763. }
  1764. #endif
  1765. Subsection->u.SubsectionFlags.Protection = MM_EXECUTE_WRITECOPY;
  1766. //
  1767. // Set all the PTEs to the execute-read-write protection.
  1768. // The section will control access to these and the segment
  1769. // must provide a method to allow other users to map the file
  1770. // for various protections.
  1771. //
  1772. TempPte.u.Soft.Protection = MM_EXECUTE_WRITECOPY;
  1773. NewSegment->SegmentPteTemplate = TempPte;
  1774. //
  1775. // Invalid image alignments are supported for cross platform
  1776. // emulation. Only IA64 requires extra handling because
  1777. // the native page size is larger than x86.
  1778. //
  1779. if (InvalidAlignmentAllowed == TRUE) {
  1780. TempPteDemandZero.u.Long = 0;
  1781. TempPteDemandZero.u.Soft.Protection = MM_EXECUTE_WRITECOPY;
  1782. SectorOffset = 0;
  1783. for (i = 0; i < NumberOfPtes; i += 1) {
  1784. //
  1785. // Set prototype PTEs.
  1786. //
  1787. if (SectorOffset < EndOfFile.LowPart) {
  1788. //
  1789. // Data resides on the disk, refer to the control section.
  1790. //
  1791. MI_WRITE_INVALID_PTE (PointerPte, TempPte);
  1792. }
  1793. else {
  1794. //
  1795. // Data does not reside on the disk, use Demand zero pages.
  1796. //
  1797. MI_WRITE_INVALID_PTE (PointerPte, TempPteDemandZero);
  1798. }
  1799. SectorOffset += PAGE_SIZE;
  1800. PointerPte += 1;
  1801. }
  1802. }
  1803. else {
  1804. for (i = 0; i < NumberOfPtes; i += 1) {
  1805. //
  1806. // Set all the prototype PTEs to refer to the control section.
  1807. //
  1808. MI_WRITE_INVALID_PTE (PointerPte, TempPte);
  1809. PointerPte += 1;
  1810. }
  1811. }
  1812. NewSegment->u1.ImageCommitment = NumberOfPtes;
  1813. //
  1814. // Indicate alignment is less than a page.
  1815. //
  1816. TempPte.u.Long = 0;
  1817. }
  1818. else {
  1819. //
  1820. // Alignment is PAGE_SIZE or greater.
  1821. //
  1822. if (Subsection->PtesInSubsection > NumberOfPtes) {
  1823. //
  1824. // Inconsistent image, size does not agree with header.
  1825. //
  1826. goto BadPeImageSegment;
  1827. }
  1828. NumberOfPtes -= Subsection->PtesInSubsection;
  1829. Subsection->NumberOfFullSectors =
  1830. SizeOfHeaders >> MMSECTOR_SHIFT;
  1831. Subsection->u.SubsectionFlags.SectorEndOffset =
  1832. SizeOfHeaders & MMSECTOR_MASK;
  1833. Subsection->u.SubsectionFlags.ReadOnly = 1;
  1834. Subsection->u.SubsectionFlags.Protection = MM_READONLY;
  1835. TempPte.u.Soft.Protection = MM_READONLY;
  1836. NewSegment->SegmentPteTemplate = TempPte;
  1837. for (i = 0; i < Subsection->PtesInSubsection; i += 1) {
  1838. //
  1839. // Set all the prototype PTEs to refer to the control section.
  1840. //
  1841. if (SectorOffset < SizeOfHeaders) {
  1842. MI_WRITE_INVALID_PTE (PointerPte, TempPte);
  1843. }
  1844. else {
  1845. MI_WRITE_INVALID_PTE (PointerPte, ZeroPte);
  1846. }
  1847. SectorOffset += PAGE_SIZE;
  1848. PointerPte += 1;
  1849. NextVa += PAGE_SIZE;
  1850. }
  1851. }
  1852. //
  1853. // Build the additional subsections.
  1854. //
  1855. PreferredImageBase = ImageBase;
  1856. //
  1857. // At this point the object table is read in (if it was not
  1858. // already read in) and may displace the image header.
  1859. //
  1860. SectionTableEntry = NULL;
  1861. OffsetToSectionTable = sizeof(ULONG) +
  1862. sizeof(IMAGE_FILE_HEADER) +
  1863. FileHeader->SizeOfOptionalHeader;
  1864. if ((BYTE_OFFSET(NtHeader) + OffsetToSectionTable +
  1865. #if defined (_WIN64)
  1866. BYTE_OFFSET(NtHeader32) +
  1867. #endif
  1868. ((NumberOfSubsections + 1) *
  1869. sizeof (IMAGE_SECTION_HEADER))) <= PAGE_SIZE) {
  1870. //
  1871. // Section tables are within the header which was read.
  1872. //
  1873. #if defined(_WIN64)
  1874. if (NtHeader32) {
  1875. SectionTableEntry = (PIMAGE_SECTION_HEADER)((PCHAR)NtHeader32 +
  1876. OffsetToSectionTable);
  1877. }
  1878. else
  1879. #endif
  1880. {
  1881. SectionTableEntry = (PIMAGE_SECTION_HEADER)((PCHAR)NtHeader +
  1882. OffsetToSectionTable);
  1883. }
  1884. }
  1885. else {
  1886. //
  1887. // Has an extended header been read in and are the object
  1888. // tables resident?
  1889. //
  1890. if (ExtendedHeader != NULL) {
  1891. #if defined(_WIN64)
  1892. if (NtHeader32) {
  1893. SectionTableEntry = (PIMAGE_SECTION_HEADER)((PCHAR)NtHeader32 +
  1894. OffsetToSectionTable);
  1895. }
  1896. else
  1897. #endif
  1898. {
  1899. SectionTableEntry = (PIMAGE_SECTION_HEADER)((PCHAR)NtHeader +
  1900. OffsetToSectionTable);
  1901. }
  1902. //
  1903. // Is the whole range of object tables mapped by the
  1904. // extended header?
  1905. //
  1906. if ((((PCHAR)SectionTableEntry +
  1907. ((NumberOfSubsections + 1) *
  1908. sizeof (IMAGE_SECTION_HEADER))) -
  1909. (PCHAR)ExtendedHeader) >
  1910. MM_MAXIMUM_IMAGE_HEADER) {
  1911. SectionTableEntry = NULL;
  1912. }
  1913. }
  1914. }
  1915. if (SectionTableEntry == NULL) {
  1916. //
  1917. // The section table entries are not in the same
  1918. // pages as the other data already read in. Read in
  1919. // the object table entries.
  1920. //
  1921. if (ExtendedHeader == NULL) {
  1922. ExtendedHeader = ExAllocatePoolWithTag (NonPagedPool,
  1923. MM_MAXIMUM_IMAGE_HEADER,
  1924. MMTEMPORARY);
  1925. if (ExtendedHeader == NULL) {
  1926. ExFreePool (NewSegment);
  1927. ExFreePool (ControlArea);
  1928. Status = STATUS_INSUFFICIENT_RESOURCES;
  1929. goto NeImage;
  1930. }
  1931. //
  1932. // Build an MDL for the operation.
  1933. //
  1934. MmCreateMdl( Mdl, ExtendedHeader, MM_MAXIMUM_IMAGE_HEADER);
  1935. MmBuildMdlForNonPagedPool (Mdl);
  1936. }
  1937. StartingOffset.LowPart = PtrToUlong(PAGE_ALIGN (
  1938. (ULONG)DosHeader->e_lfanew +
  1939. OffsetToSectionTable));
  1940. SectionTableEntry = (PIMAGE_SECTION_HEADER)((PCHAR)ExtendedHeader +
  1941. BYTE_OFFSET((ULONG)DosHeader->e_lfanew +
  1942. OffsetToSectionTable));
  1943. KeClearEvent (InPageEvent);
  1944. Status = IoPageRead (File,
  1945. Mdl,
  1946. &StartingOffset,
  1947. InPageEvent,
  1948. &IoStatus);
  1949. if (Status == STATUS_PENDING) {
  1950. KeWaitForSingleObject( InPageEvent,
  1951. WrPageIn,
  1952. KernelMode,
  1953. FALSE,
  1954. (PLARGE_INTEGER)NULL);
  1955. Status = IoStatus.Status;
  1956. }
  1957. if (Mdl->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA) {
  1958. MmUnmapLockedPages (Mdl->MappedSystemVa, Mdl);
  1959. }
  1960. if (!NT_SUCCESS(Status)) {
  1961. if ((Status != STATUS_FILE_LOCK_CONFLICT) && (Status != STATUS_FILE_IS_OFFLINE)) {
  1962. Status = STATUS_INVALID_FILE_FOR_SECTION;
  1963. }
  1964. ExFreePool (NewSegment);
  1965. ExFreePool (ControlArea);
  1966. goto NeImage;
  1967. }
  1968. //
  1969. // From this point on NtHeader is only valid if it
  1970. // was in the first page of the image, otherwise reading in
  1971. // the object tables wiped it out.
  1972. //
  1973. }
  1974. if ((TempPte.u.Long == 0) && (InvalidAlignmentAllowed == FALSE)) {
  1975. //
  1976. // The image header is no longer valid, TempPte is
  1977. // used to indicate that this image alignment is
  1978. // less than a PAGE_SIZE.
  1979. //
  1980. // Loop through all sections and make sure there is no
  1981. // uninitialized data.
  1982. //
  1983. Status = STATUS_SUCCESS;
  1984. while (NumberOfSubsections > 0) {
  1985. if (SectionTableEntry->Misc.VirtualSize == 0) {
  1986. SectionVirtualSize = SectionTableEntry->SizeOfRawData;
  1987. }
  1988. else {
  1989. SectionVirtualSize = SectionTableEntry->Misc.VirtualSize;
  1990. }
  1991. //
  1992. // If the raw pointer + raw size overflows a long word,
  1993. // return an error.
  1994. //
  1995. if (SectionTableEntry->PointerToRawData +
  1996. SectionTableEntry->SizeOfRawData <
  1997. SectionTableEntry->PointerToRawData) {
  1998. KdPrint(("MMCREASECT: invalid section/file size %Z\n",
  1999. &File->FileName));
  2000. Status = STATUS_INVALID_IMAGE_FORMAT;
  2001. break;
  2002. }
  2003. //
  2004. // If the virtual size and address does not match the rawdata
  2005. // and invalid alignments not allowed return an error.
  2006. //
  2007. if (((SectionTableEntry->PointerToRawData !=
  2008. SectionTableEntry->VirtualAddress))
  2009. ||
  2010. (SectionVirtualSize > SectionTableEntry->SizeOfRawData)) {
  2011. KdPrint(("MMCREASECT: invalid BSS/Trailingzero %Z\n",
  2012. &File->FileName));
  2013. Status = STATUS_INVALID_IMAGE_FORMAT;
  2014. break;
  2015. }
  2016. SectionTableEntry += 1;
  2017. NumberOfSubsections -= 1;
  2018. }
  2019. if (!NT_SUCCESS(Status)) {
  2020. ExFreePool (NewSegment);
  2021. ExFreePool (ControlArea);
  2022. goto NeImage;
  2023. }
  2024. goto PeReturnSuccess;
  2025. }
  2026. else if ((TempPte.u.Long == 0) && (InvalidAlignmentAllowed == TRUE)) {
  2027. TempNumberOfSubsections = NumberOfSubsections;
  2028. TempSectionTableEntry = SectionTableEntry;
  2029. //
  2030. // The image header is no longer valid, TempPte is
  2031. // used to indicate that this image alignment is
  2032. // less than a PAGE_SIZE.
  2033. //
  2034. //
  2035. // Loop through all sections and make sure there is no
  2036. // uninitialized data.
  2037. //
  2038. // Also determine if there are shared data sections and
  2039. // the number of extra ptes they require.
  2040. //
  2041. AdditionalSubsections = 0;
  2042. AdditionalPtes = 0;
  2043. AdditionalBasePtes = 0;
  2044. RoundingAlignment = PAGE_SIZE;
  2045. while (TempNumberOfSubsections > 0) {
  2046. ULONG EndOfSection;
  2047. ULONG ExtraPages;
  2048. if (TempSectionTableEntry->Misc.VirtualSize == 0) {
  2049. SectionVirtualSize = TempSectionTableEntry->SizeOfRawData;
  2050. }
  2051. else {
  2052. SectionVirtualSize = TempSectionTableEntry->Misc.VirtualSize;
  2053. }
  2054. EndOfSection = TempSectionTableEntry->PointerToRawData +
  2055. TempSectionTableEntry->SizeOfRawData;
  2056. //
  2057. // If the raw pointer + raw size overflows a long word, return an error.
  2058. //
  2059. if (EndOfSection < TempSectionTableEntry->PointerToRawData) {
  2060. KdPrint(("MMCREASECT: invalid section/file size %Z\n",
  2061. &File->FileName));
  2062. Status = STATUS_INVALID_IMAGE_FORMAT;
  2063. ExFreePool (NewSegment);
  2064. ExFreePool (ControlArea);
  2065. goto NeImage;
  2066. }
  2067. //
  2068. // If the section goes past SizeOfImage then allocate
  2069. // additional PTEs. On x86 this is handled by the subsection
  2070. // mapping. Note the additional data must be in memory so
  2071. // it can be shuffled around later.
  2072. //
  2073. if ((EndOfSection <= EndOfFile.LowPart) &&
  2074. (EndOfSection > SizeOfImage)) {
  2075. //
  2076. // Allocate enough PTEs to cover the end of this section.
  2077. // Maximize with any other sections that extend beyond SizeOfImage
  2078. //
  2079. ExtraPages = MI_ROUND_TO_SIZE (EndOfSection, RoundingAlignment) >> PAGE_SHIFT;
  2080. if ((ExtraPages > OrigNumberOfPtes) &&
  2081. (ExtraPages - OrigNumberOfPtes > AdditionalBasePtes)) {
  2082. AdditionalBasePtes = ExtraPages - (ULONG) OrigNumberOfPtes;
  2083. }
  2084. }
  2085. // Count number of shared data sections and additional ptes needed
  2086. if ((TempSectionTableEntry->Characteristics & IMAGE_SCN_MEM_SHARED) &&
  2087. (!(TempSectionTableEntry->Characteristics & IMAGE_SCN_MEM_EXECUTE) ||
  2088. (TempSectionTableEntry->Characteristics & IMAGE_SCN_MEM_WRITE))) {
  2089. AdditionalPtes +=
  2090. MI_ROUND_TO_SIZE (SectionVirtualSize, RoundingAlignment) >>
  2091. PAGE_SHIFT;
  2092. AdditionalSubsections += 1;
  2093. }
  2094. TempSectionTableEntry += 1;
  2095. TempNumberOfSubsections -= 1;
  2096. }
  2097. if (AdditionalBasePtes == 0 && (AdditionalSubsections == 0 || AdditionalPtes == 0)) {
  2098. // no shared data sections
  2099. goto PeReturnSuccess;
  2100. }
  2101. //
  2102. // There are additional Base PTEs or shared data sections.
  2103. // For shared sections, allocate new PTEs for these sections
  2104. // at the end of the image. The WX86 loader will change
  2105. // fixups to point to the new pages.
  2106. //
  2107. // First reallocate the control area.
  2108. //
  2109. NewSubsectionsAllocated = SubsectionsAllocated +
  2110. AdditionalSubsections;
  2111. NewControlArea = ExAllocatePoolWithTag(NonPagedPool,
  2112. (ULONG) (sizeof(CONTROL_AREA) +
  2113. (sizeof(SUBSECTION) *
  2114. NewSubsectionsAllocated)),
  2115. 'iCmM');
  2116. if (NewControlArea == NULL) {
  2117. ExFreePool (NewSegment);
  2118. ExFreePool (ControlArea);
  2119. Status = STATUS_INSUFFICIENT_RESOURCES;
  2120. goto NeImage;
  2121. }
  2122. //
  2123. // Copy the old control area to the new one, modify some fields.
  2124. //
  2125. RtlCopyMemory (NewControlArea, ControlArea,
  2126. sizeof(CONTROL_AREA) +
  2127. sizeof(SUBSECTION) * SubsectionsAllocated);
  2128. NewControlArea->NumberOfSubsections = (USHORT) NewSubsectionsAllocated;
  2129. //
  2130. // Now allocate a new segment that has the newly calculated number
  2131. // of PTEs, initialize it from the previously allocated new segment,
  2132. // and overwrite the fields that should be changed.
  2133. //
  2134. OldSegment = NewSegment;
  2135. OrigNumberOfPtes += AdditionalBasePtes;
  2136. PointerPte += AdditionalBasePtes;
  2137. SizeOfSegment = sizeof(SEGMENT) +
  2138. (sizeof(MMPTE) * (OrigNumberOfPtes + AdditionalPtes - 1)) +
  2139. sizeof(SECTION_IMAGE_INFORMATION);
  2140. NewSegment = ExAllocatePoolWithTag (PagedPool,
  2141. SizeOfSegment,
  2142. MMSECT);
  2143. if (NewSegment == NULL) {
  2144. //
  2145. // The requested pool could not be allocated.
  2146. //
  2147. ExFreePool (ControlArea);
  2148. ExFreePool (NewControlArea);
  2149. ExFreePool (OldSegment);
  2150. Status = STATUS_INSUFFICIENT_RESOURCES;
  2151. goto NeImage;
  2152. }
  2153. *Segment = NewSegment;
  2154. RtlCopyMemory (NewSegment, OldSegment, sizeof(SEGMENT));
  2155. //
  2156. // Align the prototype PTEs on the proper boundary.
  2157. //
  2158. NewPointerPte = &NewSegment->ThePtes[0];
  2159. i = (ULONG) (((ULONG_PTR)NewPointerPte >> PTE_SHIFT) &
  2160. ((MM_PROTO_PTE_ALIGNMENT / PAGE_SIZE) - 1));
  2161. if (i != 0) {
  2162. i = (MM_PROTO_PTE_ALIGNMENT / PAGE_SIZE) - i;
  2163. }
  2164. NewSegment->PrototypePte = &NewSegment->ThePtes[i];
  2165. if (i != 0) {
  2166. RtlZeroMemory (&NewSegment->ThePtes[0], sizeof(MMPTE) * i);
  2167. }
  2168. PointerPte = NewSegment->PrototypePte +
  2169. (PointerPte - OldSegment->PrototypePte);
  2170. NewSegment->ControlArea = NewControlArea;
  2171. NewSegment->u2.ImageInformation =
  2172. (PSECTION_IMAGE_INFORMATION)((PCHAR)NewSegment + sizeof(SEGMENT) +
  2173. (sizeof(MMPTE) * (OrigNumberOfPtes + AdditionalPtes - 1)));
  2174. NewSegment->TotalNumberOfPtes = OrigNumberOfPtes + AdditionalPtes;
  2175. NewSegment->NonExtendedPtes = OrigNumberOfPtes + AdditionalPtes;
  2176. NewSegment->SizeOfSegment = (ULONG_PTR)(OrigNumberOfPtes + AdditionalPtes) * PAGE_SIZE;
  2177. RtlCopyMemory (NewSegment->u2.ImageInformation,
  2178. OldSegment->u2.ImageInformation,
  2179. sizeof (SECTION_IMAGE_INFORMATION));
  2180. //
  2181. // Now change the fields in the subsections to account for the new
  2182. // control area and the new segment. Also change the PTEs in the
  2183. // newly allocated segment to point to the new subsections.
  2184. //
  2185. NewControlArea->Segment = NewSegment;
  2186. Subsection = (PSUBSECTION)(ControlArea + 1);
  2187. NewSubsection = (PSUBSECTION)(NewControlArea + 1);
  2188. NewSubsection->PtesInSubsection += AdditionalBasePtes;
  2189. for (i = 0; i < SubsectionsAllocated; i += 1) {
  2190. //
  2191. // Note: SubsectionsAllocated is always 1 (for wx86), so this loop
  2192. // is executed only once.
  2193. //
  2194. NewSubsection->ControlArea = (PCONTROL_AREA) NewControlArea;
  2195. NewSubsection->SubsectionBase = NewSegment->PrototypePte +
  2196. (Subsection->SubsectionBase - OldSegment->PrototypePte);
  2197. NewPointerPte = NewSegment->PrototypePte;
  2198. OldPointerPte = OldSegment->PrototypePte;
  2199. TempPte.u.Long = MiGetSubsectionAddressForPte (NewSubsection);
  2200. TempPte.u.Soft.Prototype = 1;
  2201. for (j = 0; j < OldSegment->TotalNumberOfPtes+AdditionalBasePtes; j += 1) {
  2202. if ((OldPointerPte->u.Soft.Prototype == 1) &&
  2203. (MiGetSubsectionAddress (OldPointerPte) == Subsection)) {
  2204. OriginalProtection = MI_GET_PROTECTION_FROM_SOFT_PTE (OldPointerPte);
  2205. TempPte.u.Soft.Protection = OriginalProtection;
  2206. MI_WRITE_INVALID_PTE (NewPointerPte, TempPte);
  2207. }
  2208. else if (i == 0) {
  2209. //
  2210. // Since the outer for loop is executed only once, there
  2211. // is no need for the i == 0 above, but it is safer to
  2212. // have it. If the code changes later and other sections
  2213. // are added, their PTEs will get initialized here as
  2214. // DemandZero and if they are not DemandZero, they will be
  2215. // overwritten in a later iteration of the outer loop.
  2216. // For now, this else if clause will be executed only
  2217. // for DemandZero PTEs.
  2218. //
  2219. OriginalProtection = MI_GET_PROTECTION_FROM_SOFT_PTE (OldPointerPte);
  2220. TempPteDemandZero.u.Long = 0;
  2221. TempPteDemandZero.u.Soft.Protection = OriginalProtection;
  2222. MI_WRITE_INVALID_PTE (NewPointerPte, TempPteDemandZero);
  2223. }
  2224. NewPointerPte += 1;
  2225. // Stop incrementing the OldPointerPte at the last entry and use it
  2226. // for the additional Base PTEs
  2227. if (j < OldSegment->TotalNumberOfPtes-1) {
  2228. OldPointerPte += 1;
  2229. }
  2230. }
  2231. Subsection += 1;
  2232. NewSubsection += 1;
  2233. }
  2234. RtlZeroMemory (NewSubsection,
  2235. sizeof(SUBSECTION) * AdditionalSubsections);
  2236. ExFreePool (OldSegment);
  2237. ExFreePool (ControlArea);
  2238. ControlArea = (PCONTROL_AREA) NewControlArea;
  2239. //
  2240. // Adjust some variables that are used below.
  2241. // PointerPte has already been set above before OldSegment was freed.
  2242. //
  2243. SubsectionsAllocated = NewSubsectionsAllocated;
  2244. Subsection = NewSubsection - 1; // Points to last used subsection.
  2245. NumberOfPtes = AdditionalPtes; // # PTEs that haven't yet been used in
  2246. // previous subsections.
  2247. //
  2248. // Additional Base PTEs have been added. Only continue if there are
  2249. // additional subsections to process.
  2250. //
  2251. if (AdditionalSubsections == 0 || AdditionalPtes == 0) {
  2252. // no shared data sections
  2253. goto PeReturnSuccess;
  2254. }
  2255. }
  2256. ImageFileSize = EndOfFile.LowPart + 1;
  2257. while (NumberOfSubsections > 0) {
  2258. if ((InvalidAlignmentAllowed == FALSE) ||
  2259. ((SectionTableEntry->Characteristics & IMAGE_SCN_MEM_SHARED) &&
  2260. (!(SectionTableEntry->Characteristics & IMAGE_SCN_MEM_EXECUTE) ||
  2261. (SectionTableEntry->Characteristics & IMAGE_SCN_MEM_WRITE)))) {
  2262. //
  2263. // Handle case where virtual size is 0.
  2264. //
  2265. if (SectionTableEntry->Misc.VirtualSize == 0) {
  2266. SectionVirtualSize = SectionTableEntry->SizeOfRawData;
  2267. }
  2268. else {
  2269. SectionVirtualSize = SectionTableEntry->Misc.VirtualSize;
  2270. }
  2271. //
  2272. // Fix for Borland linker problem. The SizeOfRawData can
  2273. // be a zero, but the PointerToRawData is not zero.
  2274. // Set it to zero.
  2275. //
  2276. if (SectionTableEntry->SizeOfRawData == 0) {
  2277. SectionTableEntry->PointerToRawData = 0;
  2278. }
  2279. //
  2280. // If the section information wraps return an error.
  2281. //
  2282. if (SectionTableEntry->PointerToRawData +
  2283. SectionTableEntry->SizeOfRawData <
  2284. SectionTableEntry->PointerToRawData) {
  2285. goto BadPeImageSegment;
  2286. }
  2287. Subsection->NextSubsection = (Subsection + 1);
  2288. Subsection += 1;
  2289. Subsection->ControlArea = ControlArea;
  2290. Subsection->NextSubsection = NULL;
  2291. Subsection->UnusedPtes = 0;
  2292. if (((NextVa != (PreferredImageBase + SectionTableEntry->VirtualAddress)) && (InvalidAlignmentAllowed == FALSE)) ||
  2293. (SectionVirtualSize == 0)) {
  2294. //
  2295. // The specified virtual address does not align
  2296. // with the next prototype PTE.
  2297. //
  2298. goto BadPeImageSegment;
  2299. }
  2300. Subsection->PtesInSubsection =
  2301. MI_ROUND_TO_SIZE (SectionVirtualSize, RoundingAlignment)
  2302. >> PAGE_SHIFT;
  2303. if (Subsection->PtesInSubsection > NumberOfPtes) {
  2304. //
  2305. // Inconsistent image, size does not agree with object tables.
  2306. //
  2307. goto BadPeImageSegment;
  2308. }
  2309. NumberOfPtes -= Subsection->PtesInSubsection;
  2310. Subsection->u.LongFlags = 0;
  2311. Subsection->StartingSector =
  2312. SectionTableEntry->PointerToRawData >> MMSECTOR_SHIFT;
  2313. //
  2314. // Align ending sector on file align boundary.
  2315. //
  2316. EndingAddress = (SectionTableEntry->PointerToRawData +
  2317. SectionTableEntry->SizeOfRawData +
  2318. FileAlignment) & ~FileAlignment;
  2319. Subsection->NumberOfFullSectors = (ULONG)
  2320. ((EndingAddress >> MMSECTOR_SHIFT) -
  2321. Subsection->StartingSector);
  2322. Subsection->u.SubsectionFlags.SectorEndOffset =
  2323. (ULONG) EndingAddress & MMSECTOR_MASK;
  2324. Subsection->SubsectionBase = PointerPte;
  2325. //
  2326. // Build both a demand zero PTE and a PTE pointing to the
  2327. // subsection.
  2328. //
  2329. TempPte.u.Long = 0;
  2330. TempPteDemandZero.u.Long = 0;
  2331. TempPte.u.Long = MiGetSubsectionAddressForPte (Subsection);
  2332. TempPte.u.Soft.Prototype = 1;
  2333. ImageFileSize = SectionTableEntry->PointerToRawData +
  2334. SectionTableEntry->SizeOfRawData;
  2335. TempPte.u.Soft.Protection =
  2336. MiGetImageProtection (SectionTableEntry->Characteristics);
  2337. TempPteDemandZero.u.Soft.Protection = TempPte.u.Soft.Protection;
  2338. if (SectionTableEntry->PointerToRawData == 0) {
  2339. TempPte = TempPteDemandZero;
  2340. }
  2341. Subsection->u.SubsectionFlags.ReadOnly = 1;
  2342. Subsection->u.SubsectionFlags.Protection = MI_GET_PROTECTION_FROM_SOFT_PTE (&TempPte);
  2343. //
  2344. // Assume the subsection will be unwritable and therefore
  2345. // won't be charged for any commitment.
  2346. //
  2347. SectionCommit = FALSE;
  2348. ImageCommit = FALSE;
  2349. if (TempPte.u.Soft.Protection & MM_PROTECTION_WRITE_MASK) {
  2350. if ((TempPte.u.Soft.Protection & MM_COPY_ON_WRITE_MASK)
  2351. == MM_COPY_ON_WRITE_MASK) {
  2352. //
  2353. // This page is copy on write, charge ImageCommitment
  2354. // for all pages in this subsection.
  2355. //
  2356. ImageCommit = TRUE;
  2357. }
  2358. else {
  2359. //
  2360. // This page is write shared, charge commitment when
  2361. // the mapping completes.
  2362. //
  2363. SectionCommit = TRUE;
  2364. Subsection->u.SubsectionFlags.GlobalMemory = 1;
  2365. ControlArea->u.Flags.GlobalMemory = 1;
  2366. }
  2367. }
  2368. NewSegment->SegmentPteTemplate = TempPte;
  2369. SectorOffset = 0;
  2370. for (i = 0; i < Subsection->PtesInSubsection; i += 1) {
  2371. //
  2372. // Set all the prototype PTEs to refer to the control section.
  2373. //
  2374. if (SectorOffset < SectionVirtualSize) {
  2375. //
  2376. // Make PTE accessible.
  2377. //
  2378. if (SectionCommit) {
  2379. NewSegment->NumberOfCommittedPages += 1;
  2380. }
  2381. if (ImageCommit) {
  2382. NewSegment->u1.ImageCommitment += 1;
  2383. }
  2384. if (SectorOffset < SectionTableEntry->SizeOfRawData) {
  2385. //
  2386. // Data resides on the disk, use the subsection format PTE.
  2387. //
  2388. MI_WRITE_INVALID_PTE (PointerPte, TempPte);
  2389. }
  2390. else {
  2391. //
  2392. // Demand zero pages.
  2393. //
  2394. MI_WRITE_INVALID_PTE (PointerPte, TempPteDemandZero);
  2395. }
  2396. }
  2397. else {
  2398. //
  2399. // No access pages.
  2400. //
  2401. MI_WRITE_INVALID_PTE (PointerPte, ZeroPte);
  2402. }
  2403. SectorOffset += PAGE_SIZE;
  2404. PointerPte += 1;
  2405. NextVa += PAGE_SIZE;
  2406. }
  2407. }
  2408. SectionTableEntry += 1;
  2409. NumberOfSubsections -= 1;
  2410. }
  2411. if (InvalidAlignmentAllowed == FALSE) {
  2412. //
  2413. // Account for the number of subsections that really are mapped.
  2414. //
  2415. ASSERT (ImageAlignment >= PAGE_SIZE);
  2416. ControlArea->NumberOfSubsections += 1;
  2417. //
  2418. // If the file size is not as big as the image claimed to be,
  2419. // return an error.
  2420. //
  2421. if (ImageFileSize > EndOfFile.LowPart) {
  2422. //
  2423. // Invalid image size.
  2424. //
  2425. KdPrint(("MMCREASECT: invalid image size - file size %lx - image size %lx\n %Z\n",
  2426. EndOfFile.LowPart, ImageFileSize, &File->FileName));
  2427. goto BadPeImageSegment;
  2428. }
  2429. //
  2430. // The total number of PTEs was decremented as sections were built,
  2431. // make sure that there are less than 64k's worth at this point.
  2432. //
  2433. if (NumberOfPtes >= (ImageAlignment >> PAGE_SHIFT)) {
  2434. //
  2435. // Inconsistent image, size does not agree with object tables.
  2436. //
  2437. KdPrint(("MMCREASECT: invalid image - PTE left %lx\n image name %Z\n",
  2438. NumberOfPtes, &File->FileName));
  2439. goto BadPeImageSegment;
  2440. }
  2441. //
  2442. // Set any remaining PTEs to no access.
  2443. //
  2444. while (NumberOfPtes != 0) {
  2445. MI_WRITE_INVALID_PTE (PointerPte, ZeroPte);
  2446. PointerPte += 1;
  2447. NumberOfPtes -= 1;
  2448. }
  2449. //
  2450. // Turn the image header page into a transition page within the
  2451. // prototype PTEs.
  2452. //
  2453. if ((ExtendedHeader == NULL) && (SizeOfHeaders < PAGE_SIZE)) {
  2454. //
  2455. // Zero remaining portion of header.
  2456. //
  2457. RtlZeroMemory ((PVOID)((PCHAR)Base +
  2458. SizeOfHeaders),
  2459. PAGE_SIZE - SizeOfHeaders);
  2460. }
  2461. }
  2462. NumberOfCommittedPages = NewSegment->NumberOfCommittedPages;
  2463. if (NumberOfCommittedPages != 0) {
  2464. //
  2465. // Commit the pages for the image section.
  2466. //
  2467. if (MiChargeCommitment (NumberOfCommittedPages, NULL) == FALSE) {
  2468. Status = STATUS_COMMITMENT_LIMIT;
  2469. ExFreePool (NewSegment);
  2470. ExFreePool (ControlArea);
  2471. goto NeImage;
  2472. }
  2473. MM_TRACK_COMMIT (MM_DBG_COMMIT_IMAGE, NumberOfCommittedPages);
  2474. Status = STATUS_SUCCESS;
  2475. InterlockedExchangeAddSizeT (&MmSharedCommit, NumberOfCommittedPages);
  2476. }
  2477. PeReturnSuccess:
  2478. //
  2479. // Only images that are linked with subsections aligned to the native
  2480. // page size can be directly executed from ROM.
  2481. //
  2482. XipFile = FALSE;
  2483. XipFrameNumber = 0;
  2484. if ((FileAlignment == PAGE_SIZE - 1) && (XIPConfigured == TRUE)) {
  2485. Status = XIPLocatePages (File, &PhysicalAddress);
  2486. if (NT_SUCCESS(Status)) {
  2487. XipFrameNumber = (PFN_NUMBER) (PhysicalAddress.QuadPart >> PAGE_SHIFT);
  2488. //
  2489. // The small control area will need to be reallocated as a large
  2490. // one so the starting frame number can be inserted. Set XipFile
  2491. // to denote this.
  2492. //
  2493. XipFile = TRUE;
  2494. }
  2495. }
  2496. //
  2497. // If this image is global per session (or is going to be executed directly
  2498. // from ROM), then allocate a large control area. Note this doesn't need
  2499. // to be done for systemwide global control areas or non-global control
  2500. // areas.
  2501. //
  2502. GlobalPerSession = FALSE;
  2503. if ((ControlArea->u.Flags.GlobalMemory) &&
  2504. ((LoaderFlags & IMAGE_LOADER_FLAGS_SYSTEM_GLOBAL) == 0)) {
  2505. GlobalPerSession = TRUE;
  2506. }
  2507. if ((XipFile == TRUE) || (GlobalPerSession == TRUE)) {
  2508. LargeControlArea = ExAllocatePoolWithTag(NonPagedPool,
  2509. (ULONG)(sizeof(LARGE_CONTROL_AREA) +
  2510. (sizeof(SUBSECTION) *
  2511. SubsectionsAllocated)),
  2512. 'iCmM');
  2513. if (LargeControlArea == NULL) {
  2514. //
  2515. // The requested pool could not be allocated. If the image is
  2516. // execute-in-place only (ie: not global per session), then just
  2517. // execute it normally instead of inplace (to avoid not executing
  2518. // it at all).
  2519. //
  2520. if ((XipFile == TRUE) && (GlobalPerSession == FALSE)) {
  2521. goto SkipLargeControlArea;
  2522. }
  2523. Status = STATUS_INSUFFICIENT_RESOURCES;
  2524. goto ReturnCommitChargeOnError;
  2525. }
  2526. //
  2527. // Copy the normal control area into our larger one, fix the linkages,
  2528. // Fill in the additional fields in the new one and free the old one.
  2529. //
  2530. RtlCopyMemory (LargeControlArea, ControlArea, sizeof(CONTROL_AREA));
  2531. ASSERT (ControlArea->u.Flags.GlobalOnlyPerSession == 0);
  2532. if (XipFile == TRUE) {
  2533. //
  2534. // Mark the large control area accordingly. If we can't, then
  2535. // throw it away and use the small control area and execute from
  2536. // RAM instead.
  2537. //
  2538. if (MiMakeControlAreaRom (File, LargeControlArea, XipFrameNumber) == FALSE) {
  2539. if (GlobalPerSession == FALSE) {
  2540. ExFreePool (LargeControlArea);
  2541. goto SkipLargeControlArea;
  2542. }
  2543. }
  2544. }
  2545. Subsection = (PSUBSECTION)(ControlArea + 1);
  2546. NewSubsection = (PSUBSECTION)(LargeControlArea + 1);
  2547. for (i = 0; i < SubsectionsAllocated; i += 1) {
  2548. RtlCopyMemory (NewSubsection, Subsection, sizeof(SUBSECTION));
  2549. NewSubsection->ControlArea = (PCONTROL_AREA) LargeControlArea;
  2550. NewSubsection->NextSubsection = (NewSubsection + 1);
  2551. PointerPte = NewSegment->PrototypePte;
  2552. TempPte.u.Long = MiGetSubsectionAddressForPte (NewSubsection);
  2553. TempPte.u.Soft.Prototype = 1;
  2554. for (j = 0; j < NewSegment->TotalNumberOfPtes; j += 1) {
  2555. if ((PointerPte->u.Soft.Prototype == 1) &&
  2556. (MiGetSubsectionAddress (PointerPte) == Subsection)) {
  2557. OriginalProtection = MI_GET_PROTECTION_FROM_SOFT_PTE (PointerPte);
  2558. TempPte.u.Soft.Protection = OriginalProtection;
  2559. MI_WRITE_INVALID_PTE (PointerPte, TempPte);
  2560. }
  2561. PointerPte += 1;
  2562. }
  2563. Subsection += 1;
  2564. NewSubsection += 1;
  2565. }
  2566. (NewSubsection - 1)->NextSubsection = NULL;
  2567. NewSegment->ControlArea = (PCONTROL_AREA) LargeControlArea;
  2568. if (GlobalPerSession == TRUE) {
  2569. LargeControlArea->u.Flags.GlobalOnlyPerSession = 1;
  2570. LargeControlArea->SessionId = 0;
  2571. InitializeListHead (&LargeControlArea->UserGlobalList);
  2572. }
  2573. ExFreePool (ControlArea);
  2574. ControlArea = (PCONTROL_AREA) LargeControlArea;
  2575. }
  2576. SkipLargeControlArea:
  2577. MiUnmapImageHeaderInHyperSpace ();
  2578. //
  2579. // Set the PFN database entry for this page to look like a transition
  2580. // page.
  2581. //
  2582. PointerPte = NewSegment->PrototypePte;
  2583. MiUpdateImageHeaderPage (PointerPte, PageFrameNumber, ControlArea);
  2584. if (ExtendedHeader != NULL) {
  2585. ExFreePool (ExtendedHeader);
  2586. }
  2587. ExFreePool (InPageEvent);
  2588. return STATUS_SUCCESS;
  2589. //
  2590. // Error returns from image verification.
  2591. //
  2592. ReturnCommitChargeOnError:
  2593. NumberOfCommittedPages = NewSegment->NumberOfCommittedPages;
  2594. if (NumberOfCommittedPages != 0) {
  2595. MiReturnCommitment (NumberOfCommittedPages);
  2596. MM_TRACK_COMMIT (MM_DBG_COMMIT_RETURN_IMAGE_NO_LARGE_CA, NumberOfCommittedPages);
  2597. InterlockedExchangeAddSizeT (&MmSharedCommit, 0-NumberOfCommittedPages);
  2598. }
  2599. ExFreePool (NewSegment);
  2600. ExFreePool (ControlArea);
  2601. goto NeImage;
  2602. BadPeImageSegment:
  2603. ExFreePool (NewSegment);
  2604. ExFreePool (ControlArea);
  2605. //BadPeImage:
  2606. Status = STATUS_INVALID_IMAGE_FORMAT;
  2607. NeImage:
  2608. MiUnmapImageHeaderInHyperSpace ();
  2609. BadSection:
  2610. MiRemoveImageHeaderPage(PageFrameNumber);
  2611. if (ExtendedHeader != NULL) {
  2612. ExFreePool (ExtendedHeader);
  2613. }
  2614. ExFreePool (InPageEvent);
  2615. return Status;
  2616. }
  2617. LOGICAL
  2618. MiCheckDosCalls (
  2619. IN PIMAGE_OS2_HEADER Os2Header,
  2620. IN ULONG HeaderSize
  2621. )
  2622. /*++
  2623. Routine Description:
  2624. Arguments:
  2625. Return Value:
  2626. Returns the status value.
  2627. --*/
  2628. {
  2629. PUCHAR ImportTable;
  2630. UCHAR EntrySize;
  2631. USHORT ModuleCount;
  2632. USHORT ModuleSize;
  2633. USHORT i;
  2634. PUSHORT ModuleTable;
  2635. PAGED_CODE();
  2636. //
  2637. // If there are no modules to check return immediately.
  2638. //
  2639. ModuleCount = Os2Header->ne_cmod;
  2640. if (ModuleCount == 0) {
  2641. return FALSE;
  2642. }
  2643. //
  2644. // exe headers are notorious for having junk values for offsets
  2645. // in the import table and module table. We guard against this
  2646. // via careful checking plus our exception handler.
  2647. //
  2648. try {
  2649. //
  2650. // Find out where the Module ref table is. Mod table has two byte
  2651. // for each entry in import table. These two bytes tell the offset
  2652. // in the import table for that entry.
  2653. //
  2654. ModuleTable = (PUSHORT)((PCHAR)Os2Header + (ULONG)Os2Header->ne_modtab);
  2655. //
  2656. // Make sure that the module table fits within the passed-in header.
  2657. // Note that each module table entry is 2 bytes long.
  2658. //
  2659. if (((ULONG)Os2Header->ne_modtab + (ModuleCount * 2)) > HeaderSize) {
  2660. return FALSE;
  2661. }
  2662. //
  2663. // Now search individual entries for DOSCALLs.
  2664. //
  2665. for (i = 0; i < ModuleCount; i += 1) {
  2666. ModuleSize = *((UNALIGNED USHORT *)ModuleTable);
  2667. //
  2668. // Import table has count byte followed by the string where count
  2669. // is the string length.
  2670. //
  2671. ImportTable = (PUCHAR)((PCHAR)Os2Header +
  2672. (ULONG)Os2Header->ne_imptab + (ULONG)ModuleSize);
  2673. //
  2674. // Make sure the offset is within the valid range.
  2675. //
  2676. if (((ULONG)Os2Header->ne_imptab + (ULONG)ModuleSize)
  2677. >= HeaderSize) {
  2678. return FALSE;
  2679. }
  2680. EntrySize = *ImportTable++;
  2681. //
  2682. // 0 is a bad size, bail out.
  2683. //
  2684. if (EntrySize == 0) {
  2685. return FALSE;
  2686. }
  2687. //
  2688. // Make sure the offset is within the valid range.
  2689. // The sizeof(UCHAR) is included in the check because ImportTable
  2690. // was incremented above and is used in the RtlEqualMemory
  2691. // comparison below.
  2692. //
  2693. if (((ULONG)Os2Header->ne_imptab + (ULONG)ModuleSize +
  2694. (ULONG)EntrySize + sizeof(UCHAR)) > HeaderSize) {
  2695. return FALSE;
  2696. }
  2697. //
  2698. // If size matches compare DOSCALLS.
  2699. //
  2700. if (EntrySize == 8) {
  2701. if (RtlEqualMemory (ImportTable, "DOSCALLS", 8) ) {
  2702. return TRUE;
  2703. }
  2704. }
  2705. //
  2706. // Move on to the next module table entry. Each entry is 2 bytes.
  2707. //
  2708. ModuleTable = (PUSHORT)((PCHAR)ModuleTable + 2);
  2709. }
  2710. } except (EXCEPTION_EXECUTE_HANDLER) {
  2711. return FALSE;
  2712. }
  2713. return FALSE;
  2714. }
  2715. NTSTATUS
  2716. MiVerifyImageHeader (
  2717. IN PIMAGE_NT_HEADERS NtHeader,
  2718. IN PIMAGE_DOS_HEADER DosHeader,
  2719. IN ULONG NtHeaderSize
  2720. )
  2721. /*++
  2722. Routine Description:
  2723. This function checks for various inconsistencies in the image header.
  2724. Arguments:
  2725. NtHeader - Supplies a pointer to the NT header of the image.
  2726. DosHeader - Supplies a pointer to the DOS header of the image.
  2727. NtHeaderSize - Supplies the size in bytes of the NT header.
  2728. Return Value:
  2729. NTSTATUS.
  2730. --*/
  2731. {
  2732. PCONFIGPHARLAP PharLapConfigured;
  2733. PUCHAR pb;
  2734. LONG pResTableAddress;
  2735. PAGED_CODE();
  2736. if (NtHeader->Signature != IMAGE_NT_SIGNATURE) {
  2737. if ((USHORT)NtHeader->Signature == (USHORT)IMAGE_OS2_SIGNATURE) {
  2738. //
  2739. // Check to see if this is a win-16 image.
  2740. //
  2741. if ((!MiCheckDosCalls ((PIMAGE_OS2_HEADER)NtHeader, NtHeaderSize)) &&
  2742. ((((PIMAGE_OS2_HEADER)NtHeader)->ne_exetyp == 2)
  2743. ||
  2744. ((((PIMAGE_OS2_HEADER)NtHeader)->ne_exetyp == 0) &&
  2745. (((((PIMAGE_OS2_HEADER)NtHeader)->ne_expver & 0xff00) ==
  2746. 0x200) ||
  2747. ((((PIMAGE_OS2_HEADER)NtHeader)->ne_expver & 0xff00) ==
  2748. 0x300))))) {
  2749. //
  2750. // This is a win-16 image.
  2751. //
  2752. return STATUS_INVALID_IMAGE_WIN_16;
  2753. }
  2754. // The following OS/2 headers types go to NTDOS
  2755. //
  2756. // - exetype == 5 means binary is for Dos 4.0.
  2757. // e.g Borland Dos extender type
  2758. //
  2759. // - OS/2 apps which have no import table entries
  2760. // cannot be meant for the OS/2 ss.
  2761. // e.g. QuickC for dos binaries
  2762. //
  2763. // - "old" Borland Dosx BC++ 3.x, Paradox 4.x
  2764. // exe type == 1
  2765. // DosHeader->e_cs * 16 + DosHeader->e_ip + 0x200 - 10
  2766. // contains the string " mode EXE$"
  2767. // but import table is empty, so we don't make special check
  2768. //
  2769. if (((PIMAGE_OS2_HEADER)NtHeader)->ne_exetyp == 5 ||
  2770. ((PIMAGE_OS2_HEADER)NtHeader)->ne_enttab ==
  2771. ((PIMAGE_OS2_HEADER)NtHeader)->ne_imptab )
  2772. {
  2773. return STATUS_INVALID_IMAGE_PROTECT;
  2774. }
  2775. //
  2776. // Borland Dosx types: exe type 1
  2777. //
  2778. // - "new" Borland Dosx BP7.0
  2779. // exe type == 1
  2780. // DosHeader + 0x200 contains the string "16STUB"
  2781. // 0x200 happens to be e_parhdr*16
  2782. //
  2783. if (((PIMAGE_OS2_HEADER)NtHeader)->ne_exetyp == 1 &&
  2784. RtlEqualMemory((PUCHAR)DosHeader + 0x200, "16STUB", 6) )
  2785. {
  2786. return STATUS_INVALID_IMAGE_PROTECT;
  2787. }
  2788. //
  2789. // Check for PharLap extended header which we run as a dos app.
  2790. // The PharLap config block is pointed to by the SizeofHeader
  2791. // field in the DosHdr.
  2792. // The following algorithm for detecting a pharlap exe
  2793. // was recommended by PharLap Software Inc.
  2794. //
  2795. PharLapConfigured =(PCONFIGPHARLAP) ((PCHAR)DosHeader +
  2796. ((ULONG)DosHeader->e_cparhdr << 4));
  2797. if ((PCHAR)PharLapConfigured <
  2798. (PCHAR)DosHeader + PAGE_SIZE - sizeof(CONFIGPHARLAP)) {
  2799. if (RtlEqualMemory(&PharLapConfigured->uchCopyRight[0x18],
  2800. "Phar Lap Software, Inc.", 24) &&
  2801. (PharLapConfigured->usSign == 0x4b50 || // stub loader type 2
  2802. PharLapConfigured->usSign == 0x4f50 || // bindable 286|DosExtender
  2803. PharLapConfigured->usSign == 0x5650 )) // bindable 286|DosExtender (Adv)
  2804. {
  2805. return STATUS_INVALID_IMAGE_PROTECT;
  2806. }
  2807. }
  2808. //
  2809. // Check for Rational extended header which we run as a dos app.
  2810. // We look for the rational copyright at:
  2811. // wCopyRight = *(DosHeader->e_cparhdr*16 + 30h)
  2812. // pCopyRight = wCopyRight + DosHeader->e_cparhdr*16
  2813. // "Copyright (C) Rational Systems, Inc."
  2814. //
  2815. pb = ((PUCHAR)DosHeader + ((ULONG)DosHeader->e_cparhdr << 4));
  2816. if ((ULONG_PTR)pb < (ULONG_PTR)DosHeader + PAGE_SIZE - 0x30 - sizeof(USHORT)) {
  2817. pb += *(PUSHORT)(pb + 0x30);
  2818. if ( (ULONG_PTR)pb < (ULONG_PTR)DosHeader + PAGE_SIZE - 36 &&
  2819. RtlEqualMemory(pb,
  2820. "Copyright (C) Rational Systems, Inc.",
  2821. 36) )
  2822. {
  2823. return STATUS_INVALID_IMAGE_PROTECT;
  2824. }
  2825. }
  2826. //
  2827. // Check for lotus 123 family of applications. Starting
  2828. // with 123 3.0 (till recently shipped 123 3.4), every
  2829. // exe header is bound but is meant for DOS. This can
  2830. // be checked via, a string signature in the extended
  2831. // header. <len byte>"1-2-3 Preloader" is the string
  2832. // at ne_nrestab offset.
  2833. //
  2834. pResTableAddress = ((PIMAGE_OS2_HEADER)NtHeader)->ne_nrestab;
  2835. if (pResTableAddress > DosHeader->e_lfanew &&
  2836. ((ULONG)((pResTableAddress+16) - DosHeader->e_lfanew) <
  2837. NtHeaderSize) &&
  2838. RtlEqualMemory(
  2839. ((PUCHAR)NtHeader + 1 +
  2840. (ULONG)(pResTableAddress - DosHeader->e_lfanew)),
  2841. "1-2-3 Preloader",
  2842. 15) ) {
  2843. return STATUS_INVALID_IMAGE_PROTECT;
  2844. }
  2845. return STATUS_INVALID_IMAGE_NE_FORMAT;
  2846. }
  2847. if ((USHORT)NtHeader->Signature == (USHORT)IMAGE_OS2_SIGNATURE_LE) {
  2848. //
  2849. // This is a LE (OS/2) image. We don't support it, so give it to
  2850. // DOS subsystem. There are cases (Rbase.exe) which have a LE
  2851. // header but actually it is suppose to run under DOS. When we
  2852. // do support LE format, some work needs to be done here to
  2853. // decide whether to give it to VDM or OS/2.
  2854. //
  2855. return STATUS_INVALID_IMAGE_PROTECT;
  2856. }
  2857. return STATUS_INVALID_IMAGE_PROTECT;
  2858. }
  2859. if ((NtHeader->FileHeader.Machine == 0) &&
  2860. (NtHeader->FileHeader.SizeOfOptionalHeader == 0)) {
  2861. //
  2862. // This is a bogus DOS app which has a 32-bit portion
  2863. // masquerading as a PE image.
  2864. //
  2865. return STATUS_INVALID_IMAGE_PROTECT;
  2866. }
  2867. if (!(NtHeader->FileHeader.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE)) {
  2868. return STATUS_INVALID_IMAGE_FORMAT;
  2869. }
  2870. #ifdef i386
  2871. //
  2872. // Make sure the image header is aligned on a Long word boundary.
  2873. //
  2874. if (((ULONG_PTR)NtHeader & 3) != 0) {
  2875. return STATUS_INVALID_IMAGE_FORMAT;
  2876. }
  2877. #endif
  2878. #define VALIDATE_NTHEADER(Hdr) { \
  2879. /* File alignment must be multiple of 512 and power of 2. */ \
  2880. if (((((Hdr)->OptionalHeader).FileAlignment & 511) != 0) && \
  2881. (((Hdr)->OptionalHeader).FileAlignment != \
  2882. ((Hdr)->OptionalHeader).SectionAlignment)) { \
  2883. return STATUS_INVALID_IMAGE_FORMAT; \
  2884. } \
  2885. \
  2886. if (((Hdr)->OptionalHeader).FileAlignment == 0) { \
  2887. return STATUS_INVALID_IMAGE_FORMAT; \
  2888. } \
  2889. \
  2890. if (((((Hdr)->OptionalHeader).FileAlignment - 1) & \
  2891. ((Hdr)->OptionalHeader).FileAlignment) != 0) { \
  2892. return STATUS_INVALID_IMAGE_FORMAT; \
  2893. } \
  2894. \
  2895. if (((Hdr)->OptionalHeader).SectionAlignment < ((Hdr)->OptionalHeader).FileAlignment) { \
  2896. return STATUS_INVALID_IMAGE_FORMAT; \
  2897. } \
  2898. \
  2899. if (((Hdr)->OptionalHeader).SizeOfImage > MM_SIZE_OF_LARGEST_IMAGE) { \
  2900. return STATUS_INVALID_IMAGE_FORMAT; \
  2901. } \
  2902. \
  2903. if ((Hdr)->FileHeader.NumberOfSections > MM_MAXIMUM_IMAGE_SECTIONS) { \
  2904. return STATUS_INVALID_IMAGE_FORMAT; \
  2905. } \
  2906. \
  2907. if (((Hdr)->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) && \
  2908. !((Hdr)->FileHeader.Machine == IMAGE_FILE_MACHINE_I386) ) { \
  2909. return STATUS_INVALID_IMAGE_FORMAT; \
  2910. } \
  2911. \
  2912. if (((Hdr)->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) && \
  2913. !(((Hdr)->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64) || \
  2914. ((Hdr)->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64))) { \
  2915. return STATUS_INVALID_IMAGE_FORMAT; \
  2916. } \
  2917. }
  2918. if (NtHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC) {
  2919. //
  2920. // Image doesn't have the right magic value in its optional header.
  2921. //
  2922. #if defined (_WIN64)
  2923. if (NtHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  2924. //
  2925. // PE32 image. Validate it as such.
  2926. //
  2927. PIMAGE_NT_HEADERS32 NtHeader32 = (PIMAGE_NT_HEADERS32)NtHeader;
  2928. VALIDATE_NTHEADER(NtHeader32);
  2929. return STATUS_SUCCESS;
  2930. }
  2931. #else /* !defined(_WIN64) */
  2932. if (NtHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
  2933. //
  2934. // 64bit image on a 32bit machine.
  2935. //
  2936. return STATUS_INVALID_IMAGE_WIN_64;
  2937. }
  2938. #endif
  2939. return STATUS_INVALID_IMAGE_FORMAT;
  2940. }
  2941. VALIDATE_NTHEADER(NtHeader);
  2942. #undef VALIDATE_NTHEADER
  2943. return STATUS_SUCCESS;
  2944. }
  2945. NTSTATUS
  2946. MiCreateDataFileMap (
  2947. IN PFILE_OBJECT File,
  2948. OUT PSEGMENT *Segment,
  2949. IN PUINT64 MaximumSize,
  2950. IN ULONG SectionPageProtection,
  2951. IN ULONG AllocationAttributes,
  2952. IN ULONG IgnoreFileSizing
  2953. )
  2954. /*++
  2955. Routine Description:
  2956. This function creates the necessary structures to allow the mapping
  2957. of a data file.
  2958. The data file is accessed to verify desired access, a segment
  2959. object is created and initialized.
  2960. Arguments:
  2961. File - Supplies the file object for the image file.
  2962. Segment - Returns the segment object.
  2963. MaximumSize - Supplies the maximum size for the mapping.
  2964. SectionPageProtection - Supplies the initial page protection.
  2965. AllocationAttributes - Supplies the allocation attributes for the mapping.
  2966. IgnoreFileSizing - Supplies TRUE if the cache manager is specifying the
  2967. file size and so it does not need to be validated.
  2968. Return Value:
  2969. NTSTATUS.
  2970. --*/
  2971. {
  2972. NTSTATUS Status;
  2973. ULONG NumberOfPtes;
  2974. ULONG j;
  2975. ULONG Size;
  2976. ULONG PartialSize;
  2977. PCONTROL_AREA ControlArea;
  2978. PLARGE_CONTROL_AREA LargeControlArea;
  2979. PMAPPED_FILE_SEGMENT NewSegment;
  2980. PMSUBSECTION Subsection;
  2981. PMSUBSECTION ExtendedSubsection;
  2982. PMSUBSECTION LargeExtendedSubsection;
  2983. MMPTE TempPte;
  2984. UINT64 EndOfFile;
  2985. UINT64 LastFileChunk;
  2986. UINT64 FileOffset;
  2987. UINT64 NumberOfPtesForEntireFile;
  2988. ULONG ExtendedSubsections;
  2989. PMSUBSECTION Last;
  2990. ULONG NumberOfNewSubsections;
  2991. SIZE_T AllocationFragment;
  2992. PHYSICAL_ADDRESS PhysicalAddress;
  2993. PFN_NUMBER PageFrameNumber;
  2994. PAGED_CODE();
  2995. ExtendedSubsections = 0;
  2996. // *************************************************************
  2997. // Create mapped file section.
  2998. // *************************************************************
  2999. if (!IgnoreFileSizing) {
  3000. Status = FsRtlGetFileSize (File, (PLARGE_INTEGER)&EndOfFile);
  3001. if (Status == STATUS_FILE_IS_A_DIRECTORY) {
  3002. //
  3003. // Can't map a directory as a section. Return error.
  3004. //
  3005. return STATUS_INVALID_FILE_FOR_SECTION;
  3006. }
  3007. if (!NT_SUCCESS (Status)) {
  3008. return Status;
  3009. }
  3010. if (EndOfFile == 0 && *MaximumSize == 0) {
  3011. //
  3012. // Can't map a zero length without specifying the maximum
  3013. // size as non-zero.
  3014. //
  3015. return STATUS_MAPPED_FILE_SIZE_ZERO;
  3016. }
  3017. //
  3018. // Make sure this file is big enough for the section.
  3019. //
  3020. if (*MaximumSize > EndOfFile) {
  3021. //
  3022. // If the maximum size is greater than the end-of-file,
  3023. // and the user did not request page_write or page_execute_readwrite
  3024. // to the section, reject the request.
  3025. //
  3026. if (((SectionPageProtection & PAGE_READWRITE) |
  3027. (SectionPageProtection & PAGE_EXECUTE_READWRITE)) == 0) {
  3028. return STATUS_SECTION_TOO_BIG;
  3029. }
  3030. //
  3031. // Check to make sure that the allocation size large enough
  3032. // to contain all the data, if not set a new allocation size.
  3033. //
  3034. EndOfFile = *MaximumSize;
  3035. Status = FsRtlSetFileSize (File, (PLARGE_INTEGER)&EndOfFile);
  3036. if (!NT_SUCCESS (Status)) {
  3037. return Status;
  3038. }
  3039. }
  3040. }
  3041. else {
  3042. //
  3043. // Ignore the file size, this call is from the cache manager.
  3044. //
  3045. EndOfFile = *MaximumSize;
  3046. }
  3047. //
  3048. // Calculate the number of prototype PTE chunks to build for this section.
  3049. // A subsection is also allocated for each chunk as all the prototype PTEs
  3050. // in any given chunk are initially encoded to point at the same subsection.
  3051. //
  3052. // The maximum total section size is 16PB (2^54). This is because the
  3053. // StartingSector4132 field in each subsection, ie: 2^42-1 bits of file
  3054. // offset where the offset is in 4K (not pagesize) units. Thus, a
  3055. // subsection may describe a *BYTE* file start offset of maximum
  3056. // 2^54 - 4K.
  3057. //
  3058. // Each subsection can span at most 16TB - 64K.
  3059. //
  3060. // This is because the NumberOfFullSectors and various other fields
  3061. // in the subsection are ULONGs.
  3062. //
  3063. // The last item to notice is that the NumberOfSubsections is currently
  3064. // a USHORT in the ControlArea. Note this does not limit us to 64K-1
  3065. // subsections because this field is only relied on for images not data.
  3066. //
  3067. NumberOfPtesForEntireFile = (EndOfFile + PAGE_SIZE - 1) >> PAGE_SHIFT;
  3068. NumberOfPtes = (ULONG)NumberOfPtesForEntireFile;
  3069. if (EndOfFile > MI_MAXIMUM_SECTION_SIZE) {
  3070. return STATUS_SECTION_TOO_BIG;
  3071. }
  3072. if (NumberOfPtesForEntireFile > (UINT64)((MAXULONG_PTR / sizeof(MMPTE)) - sizeof (SEGMENT))) {
  3073. return STATUS_SECTION_TOO_BIG;
  3074. }
  3075. if (NumberOfPtesForEntireFile > EndOfFile) {
  3076. return STATUS_SECTION_TOO_BIG;
  3077. }
  3078. NewSegment = ExAllocatePoolWithTag (PagedPool,
  3079. sizeof(MAPPED_FILE_SEGMENT),
  3080. 'mSmM');
  3081. if (NewSegment == NULL) {
  3082. return STATUS_INSUFFICIENT_RESOURCES;
  3083. }
  3084. //
  3085. // Allocate the subsection memory in smaller sizes so the corresponding
  3086. // prototype PTEs can be trimmed later if paged pool virtual address
  3087. // space becomes scarce. Note the size is snapped locally so it can
  3088. // be changed dynamically without locking.
  3089. //
  3090. AllocationFragment = MmAllocationFragment;
  3091. ASSERT (MiGetByteOffset (AllocationFragment) == 0);
  3092. ASSERT (AllocationFragment >= PAGE_SIZE);
  3093. ASSERT64 (AllocationFragment < _4gb);
  3094. Size = (ULONG) AllocationFragment;
  3095. PartialSize = NumberOfPtes * sizeof(MMPTE);
  3096. NumberOfNewSubsections = 0;
  3097. ExtendedSubsection = NULL;
  3098. //
  3099. // Initializing Last is not needed for correctness, but without it the
  3100. // compiler cannot compile this code W4 to check for use of uninitialized
  3101. // variables.
  3102. //
  3103. Last = NULL;
  3104. ControlArea = (PCONTROL_AREA)File->SectionObjectPointer->DataSectionObject;
  3105. do {
  3106. if (PartialSize < (ULONG) AllocationFragment) {
  3107. PartialSize = (ULONG) ROUND_TO_PAGES (PartialSize);
  3108. Size = PartialSize;
  3109. }
  3110. if (ExtendedSubsection == NULL) {
  3111. ExtendedSubsection = (PMSUBSECTION)(ControlArea + 1);
  3112. //
  3113. // Control area and first subsection were zeroed at allocation time.
  3114. //
  3115. }
  3116. else {
  3117. ExtendedSubsection = ExAllocatePoolWithTag (NonPagedPool,
  3118. sizeof(MSUBSECTION),
  3119. 'cSmM');
  3120. if (ExtendedSubsection == NULL) {
  3121. ExFreePool (NewSegment);
  3122. //
  3123. // Free all the previous allocations and return an error.
  3124. //
  3125. ExtendedSubsection = (PMSUBSECTION)(ControlArea + 1);
  3126. ExtendedSubsection = (PMSUBSECTION) ExtendedSubsection->NextSubsection;
  3127. while (ExtendedSubsection != NULL) {
  3128. Last = (PMSUBSECTION) ExtendedSubsection->NextSubsection;
  3129. ExFreePool (ExtendedSubsection);
  3130. ExtendedSubsection = Last;
  3131. }
  3132. return STATUS_INSUFFICIENT_RESOURCES;
  3133. }
  3134. RtlZeroMemory (ExtendedSubsection, sizeof(MSUBSECTION));
  3135. Last->NextSubsection = (PSUBSECTION) ExtendedSubsection;
  3136. }
  3137. NumberOfNewSubsections += 1;
  3138. ExtendedSubsection->PtesInSubsection = Size / sizeof(MMPTE);
  3139. Last = ExtendedSubsection;
  3140. PartialSize -= Size;
  3141. } while (PartialSize != 0);
  3142. *Segment = (PSEGMENT) NewSegment;
  3143. RtlZeroMemory (NewSegment, sizeof(MAPPED_FILE_SEGMENT));
  3144. NewSegment->LastSubsectionHint = ExtendedSubsection;
  3145. //
  3146. // Control area and first subsection were zeroed at allocation time.
  3147. //
  3148. ControlArea->Segment = (PSEGMENT) NewSegment;
  3149. ControlArea->NumberOfSectionReferences = 1;
  3150. if (IgnoreFileSizing == FALSE) {
  3151. //
  3152. // This reference is not from the cache manager.
  3153. //
  3154. ControlArea->NumberOfUserReferences = 1;
  3155. }
  3156. else {
  3157. //
  3158. // Set the was purged flag to indicate that the
  3159. // file size was not explicitly set.
  3160. //
  3161. ControlArea->u.Flags.WasPurged = 1;
  3162. }
  3163. ControlArea->u.Flags.BeingCreated = 1;
  3164. ControlArea->u.Flags.File = 1;
  3165. if (FILE_REMOTE_DEVICE & File->DeviceObject->Characteristics) {
  3166. //
  3167. // This file resides on a redirected drive.
  3168. //
  3169. ControlArea->u.Flags.Networked = 1;
  3170. }
  3171. if (AllocationAttributes & SEC_NOCACHE) {
  3172. ControlArea->u.Flags.NoCache = 1;
  3173. }
  3174. //
  3175. // Note this count is not correct if we have 65535 or more subsections
  3176. // for this file, but that's ok because the count is only relied on
  3177. // for images, not data anyway.
  3178. //
  3179. ControlArea->NumberOfSubsections = (USHORT)NumberOfNewSubsections;
  3180. ControlArea->FilePointer = File;
  3181. ASSERT (ControlArea->u.Flags.GlobalOnlyPerSession == 0);
  3182. Subsection = (PMSUBSECTION)(ControlArea + 1);
  3183. //
  3184. // Loop through all the subsections and fill in the PTEs.
  3185. //
  3186. TempPte.u.Long = MiGetSubsectionAddressForPte (Subsection);
  3187. TempPte.u.Soft.Prototype = 1;
  3188. //
  3189. // Set all the PTEs to the execute-read-write protection.
  3190. // The section will control access to these and the segment
  3191. // must provide a method to allow other users to map the file
  3192. // for various protections.
  3193. //
  3194. TempPte.u.Soft.Protection = MM_EXECUTE_READWRITE;
  3195. NewSegment->ControlArea = ControlArea;
  3196. NewSegment->SizeOfSegment = EndOfFile;
  3197. NewSegment->TotalNumberOfPtes = NumberOfPtes;
  3198. NewSegment->SegmentPteTemplate = TempPte;
  3199. if (Subsection->NextSubsection != NULL) {
  3200. //
  3201. // Multiple segments and subsections.
  3202. // Align first so it is a multiple of the allocation size.
  3203. //
  3204. NewSegment->NonExtendedPtes =
  3205. (Subsection->PtesInSubsection & ~(((ULONG)AllocationFragment >> PAGE_SHIFT) - 1));
  3206. }
  3207. else {
  3208. NewSegment->NonExtendedPtes = NumberOfPtes;
  3209. }
  3210. Subsection->PtesInSubsection = NewSegment->NonExtendedPtes;
  3211. FileOffset = 0;
  3212. do {
  3213. //
  3214. // Loop through all the subsections to initialize them.
  3215. //
  3216. Subsection->ControlArea = ControlArea;
  3217. Mi4KStartForSubsection(&FileOffset, Subsection);
  3218. Subsection->u.SubsectionFlags.Protection = MM_EXECUTE_READWRITE;
  3219. if (Subsection->NextSubsection == NULL) {
  3220. LastFileChunk = (EndOfFile >> MM4K_SHIFT) - FileOffset;
  3221. //
  3222. // Note this next line restricts the number of bytes mapped by
  3223. // a single subsection to 16TB-4K. Multiple subsections can always
  3224. // be chained together to support an overall file of size 16K TB.
  3225. //
  3226. Subsection->NumberOfFullSectors = (ULONG)LastFileChunk;
  3227. Subsection->u.SubsectionFlags.SectorEndOffset =
  3228. (ULONG) EndOfFile & MM4K_MASK;
  3229. j = Subsection->PtesInSubsection;
  3230. Subsection->PtesInSubsection = (ULONG)(
  3231. NumberOfPtesForEntireFile -
  3232. (FileOffset >> (PAGE_SHIFT - MM4K_SHIFT)));
  3233. MI_CHECK_SUBSECTION (Subsection);
  3234. Subsection->UnusedPtes = j - Subsection->PtesInSubsection;
  3235. }
  3236. else {
  3237. Subsection->NumberOfFullSectors =
  3238. Subsection->PtesInSubsection << (PAGE_SHIFT - MM4K_SHIFT);
  3239. MI_CHECK_SUBSECTION (Subsection);
  3240. }
  3241. FileOffset += Subsection->PtesInSubsection <<
  3242. (PAGE_SHIFT - MM4K_SHIFT);
  3243. Subsection = (PMSUBSECTION) Subsection->NextSubsection;
  3244. } while (Subsection != NULL);
  3245. if (XIPConfigured == TRUE) {
  3246. Status = XIPLocatePages (File, &PhysicalAddress);
  3247. if (NT_SUCCESS(Status)) {
  3248. PageFrameNumber = (PFN_NUMBER) (PhysicalAddress.QuadPart >> PAGE_SHIFT);
  3249. //
  3250. // Allocate a large control area (so the starting frame number
  3251. // can be saved) and repoint all the created subsections to it.
  3252. //
  3253. LargeControlArea = ExAllocatePoolWithTag (NonPagedPool,
  3254. (ULONG)(sizeof(LARGE_CONTROL_AREA) +
  3255. sizeof(MSUBSECTION)),
  3256. MMCONTROL);
  3257. if (LargeControlArea != NULL) {
  3258. *(PCONTROL_AREA) LargeControlArea = *ControlArea;
  3259. if (MiMakeControlAreaRom (File, LargeControlArea, PageFrameNumber) == TRUE) {
  3260. LargeExtendedSubsection = (PMSUBSECTION)(LargeControlArea + 1);
  3261. ExtendedSubsection = (PMSUBSECTION)(ControlArea + 1);
  3262. *LargeExtendedSubsection = *ExtendedSubsection;
  3263. LargeExtendedSubsection->ControlArea = (PCONTROL_AREA) LargeControlArea;
  3264. //
  3265. // Only the first subsection needed to be directly modified
  3266. // as above because it is allocated in a single chunk with
  3267. // the control area. Any additional subsections below
  3268. // just need their control area pointers updated.
  3269. //
  3270. ASSERT (NumberOfNewSubsections >= 1);
  3271. j = NumberOfNewSubsections - 1;
  3272. while (j != 0) {
  3273. ExtendedSubsection = (PMSUBSECTION) ExtendedSubsection->NextSubsection;
  3274. ExtendedSubsection->ControlArea = (PCONTROL_AREA) LargeControlArea;
  3275. j -= 1;
  3276. }
  3277. NewSegment->ControlArea = (PCONTROL_AREA) LargeControlArea;
  3278. }
  3279. else {
  3280. ExFreePool (LargeControlArea);
  3281. }
  3282. }
  3283. }
  3284. }
  3285. return STATUS_SUCCESS;
  3286. }
  3287. NTSTATUS
  3288. MiCreatePagingFileMap (
  3289. OUT PSEGMENT *Segment,
  3290. IN PUINT64 MaximumSize,
  3291. IN ULONG ProtectionMask,
  3292. IN ULONG AllocationAttributes
  3293. )
  3294. /*++
  3295. Routine Description:
  3296. This function creates the necessary structures to allow the mapping
  3297. of a paging file.
  3298. Arguments:
  3299. Segment - Returns the segment object.
  3300. MaximumSize - Supplies the maximum size for the mapping.
  3301. ProtectionMask - Supplies the initial page protection.
  3302. AllocationAttributes - Supplies the allocation attributes for the
  3303. mapping.
  3304. Return Value:
  3305. NTSTATUS.
  3306. --*/
  3307. {
  3308. PFN_NUMBER NumberOfPtes;
  3309. ULONG SizeOfSegment;
  3310. ULONG i;
  3311. PCONTROL_AREA ControlArea;
  3312. PSEGMENT NewSegment;
  3313. PMMPTE PointerPte;
  3314. PSUBSECTION Subsection;
  3315. MMPTE TempPte;
  3316. PAGED_CODE();
  3317. //*******************************************************************
  3318. // Create a section backed by the paging file.
  3319. //*******************************************************************
  3320. if (*MaximumSize == 0) {
  3321. return STATUS_INVALID_PARAMETER_4;
  3322. }
  3323. //
  3324. // Limit page file backed sections to the pagefile maximum size.
  3325. //
  3326. if (*MaximumSize > (MI_MAXIMUM_PAGEFILE_SIZE - (1024 * 1024))) {
  3327. return STATUS_SECTION_TOO_BIG;
  3328. }
  3329. //
  3330. // Create the segment object.
  3331. //
  3332. //
  3333. // Calculate the number of prototype PTEs to build for this segment.
  3334. //
  3335. NumberOfPtes = BYTES_TO_PAGES (*MaximumSize);
  3336. if (AllocationAttributes & SEC_COMMIT) {
  3337. //
  3338. // Commit the pages for the section.
  3339. //
  3340. ASSERT (ProtectionMask != 0);
  3341. if (MiChargeCommitment (NumberOfPtes, NULL) == FALSE) {
  3342. return STATUS_COMMITMENT_LIMIT;
  3343. }
  3344. }
  3345. SizeOfSegment = sizeof(SEGMENT) + sizeof(MMPTE) * ((ULONG)NumberOfPtes - 1);
  3346. NewSegment = ExAllocatePoolWithTag (PagedPool, SizeOfSegment, MMSECT);
  3347. if (NewSegment == NULL) {
  3348. //
  3349. // The requested pool could not be allocated.
  3350. //
  3351. if (AllocationAttributes & SEC_COMMIT) {
  3352. MiReturnCommitment (NumberOfPtes);
  3353. }
  3354. return STATUS_INSUFFICIENT_RESOURCES;
  3355. }
  3356. *Segment = NewSegment;
  3357. ControlArea = ExAllocatePoolWithTag (NonPagedPool,
  3358. (ULONG)sizeof(CONTROL_AREA) +
  3359. (ULONG)sizeof(SUBSECTION),
  3360. MMCONTROL);
  3361. if (ControlArea == NULL) {
  3362. //
  3363. // The requested pool could not be allocated.
  3364. //
  3365. ExFreePool (NewSegment);
  3366. if (AllocationAttributes & SEC_COMMIT) {
  3367. MiReturnCommitment (NumberOfPtes);
  3368. }
  3369. return STATUS_INSUFFICIENT_RESOURCES;
  3370. }
  3371. //
  3372. // Zero control area and first subsection.
  3373. //
  3374. RtlZeroMemory (ControlArea, sizeof(CONTROL_AREA) + sizeof(SUBSECTION));
  3375. ControlArea->Segment = NewSegment;
  3376. ControlArea->NumberOfSectionReferences = 1;
  3377. ControlArea->NumberOfUserReferences = 1;
  3378. ControlArea->NumberOfSubsections = 1;
  3379. if (AllocationAttributes & SEC_BASED) {
  3380. ControlArea->u.Flags.Based = 1;
  3381. }
  3382. if (AllocationAttributes & SEC_RESERVE) {
  3383. ControlArea->u.Flags.Reserve = 1;
  3384. }
  3385. if (AllocationAttributes & SEC_COMMIT) {
  3386. ControlArea->u.Flags.Commit = 1;
  3387. }
  3388. Subsection = (PSUBSECTION)(ControlArea + 1);
  3389. Subsection->ControlArea = ControlArea;
  3390. Subsection->PtesInSubsection = (ULONG)NumberOfPtes;
  3391. Subsection->u.SubsectionFlags.Protection = ProtectionMask;
  3392. //
  3393. // Align the prototype PTEs on the proper boundary.
  3394. //
  3395. PointerPte = &NewSegment->ThePtes[0];
  3396. i = (ULONG) (((ULONG_PTR)PointerPte >> PTE_SHIFT) &
  3397. ((MM_PROTO_PTE_ALIGNMENT / PAGE_SIZE) - 1));
  3398. if (i != 0) {
  3399. i = (MM_PROTO_PTE_ALIGNMENT / PAGE_SIZE) - i;
  3400. }
  3401. //
  3402. // Zero the segment header.
  3403. //
  3404. RtlZeroMemory (NewSegment, sizeof(SEGMENT));
  3405. NewSegment->PrototypePte = &NewSegment->ThePtes[i];
  3406. NewSegment->ControlArea = ControlArea;
  3407. //
  3408. // Record the process that created this segment for the performance
  3409. // analysis tools.
  3410. //
  3411. NewSegment->u1.CreatingProcess = PsGetCurrentProcess ();
  3412. NewSegment->SizeOfSegment = (UINT64)NumberOfPtes * PAGE_SIZE;
  3413. NewSegment->TotalNumberOfPtes = (ULONG)NumberOfPtes;
  3414. NewSegment->NonExtendedPtes = (ULONG)NumberOfPtes;
  3415. PointerPte = NewSegment->PrototypePte;
  3416. Subsection->SubsectionBase = PointerPte;
  3417. TempPte = ZeroPte;
  3418. if (AllocationAttributes & SEC_COMMIT) {
  3419. TempPte.u.Soft.Protection = ProtectionMask;
  3420. //
  3421. // Record commitment charging.
  3422. //
  3423. MM_TRACK_COMMIT (MM_DBG_COMMIT_PAGEFILE_BACKED_SHMEM, NumberOfPtes);
  3424. NewSegment->NumberOfCommittedPages = NumberOfPtes;
  3425. InterlockedExchangeAddSizeT (&MmSharedCommit, NumberOfPtes);
  3426. }
  3427. NewSegment->SegmentPteTemplate.u.Soft.Protection = ProtectionMask;
  3428. //
  3429. // Set all the prototype PTEs to either no access or demand zero
  3430. // depending on the commit flag.
  3431. //
  3432. MiFillMemoryPte (PointerPte, NumberOfPtes * sizeof(MMPTE), TempPte.u.Long);
  3433. return STATUS_SUCCESS;
  3434. }
  3435. NTSTATUS
  3436. NtOpenSection (
  3437. OUT PHANDLE SectionHandle,
  3438. IN ACCESS_MASK DesiredAccess,
  3439. IN POBJECT_ATTRIBUTES ObjectAttributes
  3440. )
  3441. /*++
  3442. Routine Description:
  3443. This function opens a handle to a section object with the specified
  3444. desired access.
  3445. Arguments:
  3446. Sectionhandle - Supplies a pointer to a variable that will
  3447. receive the section object handle value.
  3448. DesiredAccess - Supplies the desired types of access for the
  3449. section.
  3450. DesiredAccess Flags
  3451. EXECUTE - Execute access to the section is desired.
  3452. READ - Read access to the section is desired.
  3453. WRITE - Write access to the section is desired.
  3454. ObjectAttributes - Supplies a pointer to an object attributes structure.
  3455. Return Value:
  3456. NTSTATUS.
  3457. --*/
  3458. {
  3459. HANDLE Handle;
  3460. KPROCESSOR_MODE PreviousMode;
  3461. NTSTATUS Status;
  3462. PAGED_CODE();
  3463. //
  3464. // Get previous processor mode and probe output arguments if necessary.
  3465. //
  3466. PreviousMode = KeGetPreviousMode();
  3467. if (PreviousMode != KernelMode) {
  3468. try {
  3469. ProbeForWriteHandle(SectionHandle);
  3470. } except (EXCEPTION_EXECUTE_HANDLER) {
  3471. return GetExceptionCode();
  3472. }
  3473. }
  3474. //
  3475. // Open handle to the section object with the specified desired
  3476. // access.
  3477. //
  3478. Status = ObOpenObjectByName (ObjectAttributes,
  3479. MmSectionObjectType,
  3480. PreviousMode,
  3481. NULL,
  3482. DesiredAccess,
  3483. NULL,
  3484. &Handle
  3485. );
  3486. try {
  3487. *SectionHandle = Handle;
  3488. } except (EXCEPTION_EXECUTE_HANDLER) {
  3489. return Status;
  3490. }
  3491. return Status;
  3492. }
  3493. CCHAR
  3494. MiGetImageProtection (
  3495. IN ULONG SectionCharacteristics
  3496. )
  3497. /*++
  3498. Routine Description:
  3499. This function takes a section characteristic mask from the
  3500. image and converts it to an PTE protection mask.
  3501. Arguments:
  3502. SectionCharacteristics - Supplies the characteristics mask from the
  3503. image.
  3504. Return Value:
  3505. Returns the protection mask for the PTE.
  3506. --*/
  3507. {
  3508. ULONG Index;
  3509. PAGED_CODE();
  3510. Index = 0;
  3511. if (SectionCharacteristics & IMAGE_SCN_MEM_EXECUTE) {
  3512. Index |= 1;
  3513. }
  3514. if (SectionCharacteristics & IMAGE_SCN_MEM_READ) {
  3515. Index |= 2;
  3516. }
  3517. if (SectionCharacteristics & IMAGE_SCN_MEM_WRITE) {
  3518. Index |= 4;
  3519. }
  3520. if (SectionCharacteristics & IMAGE_SCN_MEM_SHARED) {
  3521. Index |= 8;
  3522. }
  3523. return MmImageProtectionArray[Index];
  3524. }
  3525. PFN_NUMBER
  3526. MiGetPageForHeader (
  3527. VOID
  3528. )
  3529. /*++
  3530. Routine Description:
  3531. This non-pagable function acquires the PFN lock, removes
  3532. a page and updates the PFN database as though the page was
  3533. ready to be deleted if the reference count is decremented.
  3534. Arguments:
  3535. None.
  3536. Return Value:
  3537. Returns the physical page frame number.
  3538. --*/
  3539. {
  3540. KIRQL OldIrql;
  3541. PFN_NUMBER PageFrameNumber;
  3542. PMMPFN Pfn1;
  3543. PEPROCESS Process;
  3544. ULONG PageColor;
  3545. Process = PsGetCurrentProcess();
  3546. PageColor = MI_PAGE_COLOR_VA_PROCESS ((PVOID)X64K,
  3547. &Process->NextPageColor);
  3548. //
  3549. // Lock the PFN database and get a page.
  3550. //
  3551. LOCK_PFN (OldIrql);
  3552. MiEnsureAvailablePageOrWait (NULL, NULL);
  3553. //
  3554. // Remove page for 64k alignment.
  3555. //
  3556. PageFrameNumber = MiRemoveAnyPage (PageColor);
  3557. //
  3558. // Increment the reference count for the page so the
  3559. // paging I/O will work, and so this page cannot be stolen from us.
  3560. //
  3561. Pfn1 = MI_PFN_ELEMENT (PageFrameNumber);
  3562. Pfn1->u3.e2.ReferenceCount += 1;
  3563. //
  3564. // Don't need the PFN lock for the fields below...
  3565. //
  3566. UNLOCK_PFN (OldIrql);
  3567. Pfn1->OriginalPte = ZeroPte;
  3568. Pfn1->PteAddress = (PVOID) (ULONG_PTR)X64K;
  3569. MI_SET_PFN_DELETED (Pfn1);
  3570. return PageFrameNumber;
  3571. }
  3572. VOID
  3573. MiUpdateImageHeaderPage (
  3574. IN PMMPTE PointerPte,
  3575. IN PFN_NUMBER PageFrameNumber,
  3576. IN PCONTROL_AREA ControlArea
  3577. )
  3578. /*++
  3579. Routine Description:
  3580. This non-pagable function acquires the PFN lock, and
  3581. turns the specified prototype PTE into a transition PTE
  3582. referring to the specified physical page. It then
  3583. decrements the reference count causing the page to
  3584. be placed on the standby or modified list.
  3585. Arguments:
  3586. PointerPte - Supplies the PTE to set into the transition state.
  3587. PageFrameNumber - Supplies the physical page.
  3588. ControlArea - Supplies the control area for the prototype PTEs.
  3589. Return Value:
  3590. None.
  3591. --*/
  3592. {
  3593. KIRQL OldIrql;
  3594. LOCK_PFN (OldIrql);
  3595. MiMakeSystemAddressValidPfn (PointerPte);
  3596. MiInitializeTransitionPfn (PageFrameNumber, PointerPte);
  3597. ControlArea->NumberOfPfnReferences += 1;
  3598. //
  3599. // Add the page to the standby list.
  3600. //
  3601. MiDecrementReferenceCount (PageFrameNumber);
  3602. UNLOCK_PFN (OldIrql);
  3603. return;
  3604. }
  3605. VOID
  3606. MiRemoveImageHeaderPage (
  3607. IN PFN_NUMBER PageFrameNumber
  3608. )
  3609. /*++
  3610. Routine Description:
  3611. This non-pagable function acquires the PFN lock, and decrements
  3612. the reference count thereby causing the physical page to
  3613. be deleted.
  3614. Arguments:
  3615. PageFrameNumber - Supplies the PFN to decrement.
  3616. Return Value:
  3617. None.
  3618. --*/
  3619. {
  3620. KIRQL OldIrql;
  3621. LOCK_PFN (OldIrql);
  3622. MiDecrementReferenceCount (PageFrameNumber);
  3623. UNLOCK_PFN (OldIrql);
  3624. return;
  3625. }
  3626. PCONTROL_AREA
  3627. MiFindImageSectionObject(
  3628. IN PFILE_OBJECT File,
  3629. OUT PLOGICAL GlobalNeeded
  3630. )
  3631. /*++
  3632. Routine Description:
  3633. This function searches the control area chains (if any) for an existing
  3634. cache of the specified image file. For non-global control areas, there is
  3635. no chain and the control area is shared for all callers and sessions.
  3636. Likewise for systemwide global control areas.
  3637. However, for global PER-SESSION control areas, we must do the walk.
  3638. Arguments:
  3639. File - Supplies the file object for the image file.
  3640. GlobalNeeded - Supplies a pointer to store whether a global control area is
  3641. required as a placeholder. This can only be set when there
  3642. is already some global control area in the list - ie: our
  3643. caller should only rely on this when this function returns
  3644. NULL so the caller knows what kind of control area to
  3645. insert.
  3646. Return Value:
  3647. Returns the matching control area or NULL if one does not exist.
  3648. Environment:
  3649. Must be holding the PFN lock.
  3650. --*/
  3651. {
  3652. PCONTROL_AREA ControlArea;
  3653. PLARGE_CONTROL_AREA LargeControlArea;
  3654. PLIST_ENTRY Head, Next;
  3655. ULONG SessionId;
  3656. MM_PFN_LOCK_ASSERT();
  3657. *GlobalNeeded = FALSE;
  3658. //
  3659. // Get first (if any) control area pointer.
  3660. //
  3661. ControlArea = (PCONTROL_AREA)(File->SectionObjectPointer->ImageSectionObject);
  3662. //
  3663. // If no control area, or the control area is not session global,
  3664. // then our job is easy. Note, however, that they each require different
  3665. // return values as they represent different states.
  3666. //
  3667. if (ControlArea == NULL) {
  3668. return NULL;
  3669. }
  3670. if (ControlArea->u.Flags.GlobalOnlyPerSession == 0) {
  3671. return ControlArea;
  3672. }
  3673. LargeControlArea = (PLARGE_CONTROL_AREA) ControlArea;
  3674. //
  3675. // Get the current session ID and search for a matching control area.
  3676. //
  3677. SessionId = MmGetSessionId (PsGetCurrentProcess());
  3678. if (LargeControlArea->SessionId == SessionId) {
  3679. return (PCONTROL_AREA) LargeControlArea;
  3680. }
  3681. //
  3682. // Must search the control area list for a matching session ID.
  3683. //
  3684. Head = &LargeControlArea->UserGlobalList;
  3685. for (Next = Head->Flink; Next != Head; Next = Next->Flink) {
  3686. LargeControlArea = CONTAINING_RECORD (Next, LARGE_CONTROL_AREA, UserGlobalList);
  3687. ASSERT (LargeControlArea->u.Flags.GlobalOnlyPerSession == 1);
  3688. if (LargeControlArea->SessionId == SessionId) {
  3689. return (PCONTROL_AREA) LargeControlArea;
  3690. }
  3691. }
  3692. //
  3693. // No match, so tell our caller to create a new global control area.
  3694. //
  3695. *GlobalNeeded = TRUE;
  3696. return NULL;
  3697. }
  3698. VOID
  3699. MiInsertImageSectionObject(
  3700. IN PFILE_OBJECT File,
  3701. IN PCONTROL_AREA InputControlArea
  3702. )
  3703. /*++
  3704. Routine Description:
  3705. This function inserts the control area into the file's section object
  3706. pointers. For non-global control areas, there is no chain and the
  3707. control area is shared for all callers and sessions.
  3708. Likewise for systemwide global control areas.
  3709. However, for global PER-SESSION control areas, we must do a list insertion.
  3710. Arguments:
  3711. File - Supplies the file object for the image file.
  3712. InputControlArea - Supplies the control area to insert.
  3713. Return Value:
  3714. None.
  3715. Environment:
  3716. Must be holding the PFN lock.
  3717. --*/
  3718. {
  3719. PLIST_ENTRY Head;
  3720. PLARGE_CONTROL_AREA ControlArea;
  3721. PLARGE_CONTROL_AREA FirstControlArea;
  3722. #if DBG
  3723. PLIST_ENTRY Next;
  3724. PLARGE_CONTROL_AREA NextControlArea;
  3725. #endif
  3726. MM_PFN_LOCK_ASSERT();
  3727. ControlArea = (PLARGE_CONTROL_AREA) InputControlArea;
  3728. //
  3729. // If this is not a global-per-session control area or just a placeholder
  3730. // control area (with no chain already in place) then just put it in.
  3731. //
  3732. FirstControlArea = (PLARGE_CONTROL_AREA)(File->SectionObjectPointer->ImageSectionObject);
  3733. if (FirstControlArea == NULL) {
  3734. if (ControlArea->u.Flags.GlobalOnlyPerSession == 0) {
  3735. File->SectionObjectPointer->ImageSectionObject = (PVOID)ControlArea;
  3736. return;
  3737. }
  3738. }
  3739. //
  3740. // A per-session control area needs to be inserted...
  3741. //
  3742. ASSERT (ControlArea->u.Flags.GlobalOnlyPerSession == 1);
  3743. ControlArea->SessionId = MmGetSessionId (PsGetCurrentProcess());
  3744. //
  3745. // If the control area list is empty, just initialize links for this entry.
  3746. //
  3747. if (File->SectionObjectPointer->ImageSectionObject == NULL) {
  3748. InitializeListHead (&ControlArea->UserGlobalList);
  3749. }
  3750. else {
  3751. //
  3752. // Insert new entry before the current first entry. The control area
  3753. // must be in the midst of creation/deletion or have a valid session
  3754. // ID to be inserted.
  3755. //
  3756. ASSERT (ControlArea->u.Flags.BeingDeleted ||
  3757. ControlArea->u.Flags.BeingCreated ||
  3758. ControlArea->SessionId != (ULONG)-1);
  3759. FirstControlArea = (PLARGE_CONTROL_AREA)(File->SectionObjectPointer->ImageSectionObject);
  3760. Head = &FirstControlArea->UserGlobalList;
  3761. #if DBG
  3762. //
  3763. // Ensure no duplicate session IDs exist in the list.
  3764. //
  3765. for (Next = Head->Flink; Next != Head; Next = Next->Flink) {
  3766. NextControlArea = CONTAINING_RECORD (Next, LARGE_CONTROL_AREA, UserGlobalList);
  3767. ASSERT (NextControlArea->SessionId != (ULONG)-1 &&
  3768. NextControlArea->SessionId != ControlArea->SessionId);
  3769. }
  3770. #endif
  3771. InsertTailList (Head, &ControlArea->UserGlobalList);
  3772. }
  3773. //
  3774. // Update first control area pointer.
  3775. //
  3776. File->SectionObjectPointer->ImageSectionObject = (PVOID) ControlArea;
  3777. }
  3778. VOID
  3779. MiRemoveImageSectionObject(
  3780. IN PFILE_OBJECT File,
  3781. IN PCONTROL_AREA InputControlArea
  3782. )
  3783. /*++
  3784. Routine Description:
  3785. This function searches the control area chains (if any) for an existing
  3786. cache of the specified image file. For non-global control areas, there is
  3787. no chain and the control area is shared for all callers and sessions.
  3788. Likewise for systemwide global control areas.
  3789. However, for global PER-SESSION control areas, we must do the walk.
  3790. Upon finding the specified control area, we unlink it.
  3791. Arguments:
  3792. File - Supplies the file object for the image file.
  3793. InputControlArea - Supplies the control area to remove.
  3794. Return Value:
  3795. None.
  3796. Environment:
  3797. Must be holding the PFN lock.
  3798. --*/
  3799. {
  3800. #if DBG
  3801. PLIST_ENTRY Head;
  3802. #endif
  3803. PLIST_ENTRY Next;
  3804. PLARGE_CONTROL_AREA ControlArea;
  3805. PLARGE_CONTROL_AREA FirstControlArea;
  3806. PLARGE_CONTROL_AREA NextControlArea;
  3807. MM_PFN_LOCK_ASSERT();
  3808. ControlArea = (PLARGE_CONTROL_AREA) InputControlArea;
  3809. FirstControlArea = (PLARGE_CONTROL_AREA)(File->SectionObjectPointer->ImageSectionObject);
  3810. //
  3811. // Get a pointer to the first control area. If this is not a
  3812. // global-per-session control area, then there is no list, so we're done.
  3813. //
  3814. if (FirstControlArea->u.Flags.GlobalOnlyPerSession == 0) {
  3815. ASSERT (ControlArea->u.Flags.GlobalOnlyPerSession == 0);
  3816. File->SectionObjectPointer->ImageSectionObject = NULL;
  3817. return;
  3818. }
  3819. //
  3820. // A list may exist. Walk it as necessary and delete the requested entry.
  3821. //
  3822. if (FirstControlArea == ControlArea) {
  3823. //
  3824. // The first entry is the one to remove. If it is the only entry
  3825. // in the list, then the new first entry pointer will be NULL.
  3826. // Otherwise, get a pointer to the next entry and unlink the current.
  3827. //
  3828. if (IsListEmpty (&FirstControlArea->UserGlobalList)) {
  3829. NextControlArea = NULL;
  3830. }
  3831. else {
  3832. Next = FirstControlArea->UserGlobalList.Flink;
  3833. RemoveEntryList (&FirstControlArea->UserGlobalList);
  3834. NextControlArea = CONTAINING_RECORD (Next,
  3835. LARGE_CONTROL_AREA,
  3836. UserGlobalList);
  3837. ASSERT (NextControlArea->u.Flags.GlobalOnlyPerSession == 1);
  3838. }
  3839. File->SectionObjectPointer->ImageSectionObject = (PVOID)NextControlArea;
  3840. return;
  3841. }
  3842. //
  3843. // Remove the entry, note that the ImageSectionObject need not be updated
  3844. // as the entry is not at the head.
  3845. //
  3846. #if DBG
  3847. Head = &FirstControlArea->UserGlobalList;
  3848. for (Next = Head->Flink; Next != Head; Next = Next->Flink) {
  3849. NextControlArea = CONTAINING_RECORD (Next,
  3850. LARGE_CONTROL_AREA,
  3851. UserGlobalList);
  3852. ASSERT (NextControlArea->u.Flags.GlobalOnlyPerSession == 1);
  3853. if (NextControlArea == ControlArea) {
  3854. break;
  3855. }
  3856. }
  3857. ASSERT (Next != Head);
  3858. #endif
  3859. RemoveEntryList (&ControlArea->UserGlobalList);
  3860. }
  3861. NTSTATUS
  3862. MiGetWritablePagesInSection (
  3863. IN PSECTION Section,
  3864. OUT PULONG WritablePages
  3865. )
  3866. /*++
  3867. Routine Description:
  3868. This routine calculates the number of writable pages in the image.
  3869. Arguments:
  3870. Section - Supplies the section for the image.
  3871. WritablePages - Supplies a pointer to fill with the
  3872. number of writable pages.
  3873. Return Value:
  3874. STATUS_SUCCESS if all went well, otherwise various NTSTATUS error codes.
  3875. Environment:
  3876. Kernel mode, APC_LEVEL and below, MmSystemLoadLock held.
  3877. --*/
  3878. {
  3879. NTSTATUS Status;
  3880. PVOID ViewBase;
  3881. SIZE_T ViewSize;
  3882. KAPC_STATE ApcState;
  3883. ULONG PagesInSubsection;
  3884. ULONG Protection;
  3885. ULONG NumberOfSubsections;
  3886. ULONG OffsetToSectionTable;
  3887. ULONG SectionVirtualSize;
  3888. PEPROCESS Process;
  3889. LARGE_INTEGER SectionOffset;
  3890. PIMAGE_DOS_HEADER DosHeader;
  3891. PIMAGE_NT_HEADERS NtHeader;
  3892. PIMAGE_SECTION_HEADER SectionTableEntry;
  3893. PAGED_CODE();
  3894. ViewBase = NULL;
  3895. ViewSize = 0;
  3896. SectionOffset.QuadPart = 0;
  3897. *WritablePages = 0;
  3898. KeStackAttachProcess (&PsInitialSystemProcess->Pcb, &ApcState);
  3899. Process = PsGetCurrentProcess();
  3900. Status = MmMapViewOfSection (Section,
  3901. Process,
  3902. &ViewBase,
  3903. 0,
  3904. 0,
  3905. &SectionOffset,
  3906. &ViewSize,
  3907. ViewUnmap,
  3908. 0,
  3909. PAGE_EXECUTE);
  3910. if (!NT_SUCCESS(Status)) {
  3911. KeUnstackDetachProcess (&ApcState);
  3912. return Status;
  3913. }
  3914. //
  3915. // The DLL is mapped as a data file not as an image. Pull apart the
  3916. // executable header. The security checks have already been
  3917. // done as part of creating the section in the first place.
  3918. //
  3919. DosHeader = (PIMAGE_DOS_HEADER) ViewBase;
  3920. ASSERT (DosHeader->e_magic == IMAGE_DOS_SIGNATURE);
  3921. #ifndef i386
  3922. ASSERT (((ULONG)DosHeader->e_lfanew & 3) == 0);
  3923. #endif
  3924. ASSERT ((ULONG)DosHeader->e_lfanew <= ViewSize);
  3925. NtHeader = (PIMAGE_NT_HEADERS)((PCHAR)DosHeader +
  3926. (ULONG)DosHeader->e_lfanew);
  3927. OffsetToSectionTable = sizeof(ULONG) +
  3928. sizeof(IMAGE_FILE_HEADER) +
  3929. NtHeader->FileHeader.SizeOfOptionalHeader;
  3930. SectionTableEntry = (PIMAGE_SECTION_HEADER)((PCHAR)NtHeader +
  3931. OffsetToSectionTable);
  3932. NumberOfSubsections = NtHeader->FileHeader.NumberOfSections;
  3933. while (NumberOfSubsections > 0) {
  3934. Protection = MiGetImageProtection (SectionTableEntry->Characteristics);
  3935. if (Protection & MM_PROTECTION_WRITE_MASK) {
  3936. //
  3937. // Handle the case where the virtual size is 0.
  3938. //
  3939. if (SectionTableEntry->Misc.VirtualSize == 0) {
  3940. SectionVirtualSize = SectionTableEntry->SizeOfRawData;
  3941. }
  3942. else {
  3943. SectionVirtualSize = SectionTableEntry->Misc.VirtualSize;
  3944. }
  3945. PagesInSubsection =
  3946. MI_ROUND_TO_SIZE (SectionVirtualSize, PAGE_SIZE) >> PAGE_SHIFT;
  3947. *WritablePages += PagesInSubsection;
  3948. }
  3949. SectionTableEntry += 1;
  3950. NumberOfSubsections -= 1;
  3951. }
  3952. Status = MiUnmapViewOfSection (Process, ViewBase, FALSE);
  3953. KeUnstackDetachProcess (&ApcState);
  3954. ASSERT (NT_SUCCESS(Status));
  3955. return Status;
  3956. }
  3957. LOGICAL
  3958. MiFlushDataSection(
  3959. IN PFILE_OBJECT File
  3960. )
  3961. /*++
  3962. Routine Description:
  3963. This routine flushes the data section if there is one.
  3964. Arguments:
  3965. File - Supplies the file object.
  3966. Return Value:
  3967. None.
  3968. Environment:
  3969. Kernel mode, APC_LEVEL and below.
  3970. --*/
  3971. {
  3972. KIRQL OldIrql;
  3973. IO_STATUS_BLOCK IoStatus;
  3974. PCONTROL_AREA ControlArea;
  3975. LOGICAL DataInUse;
  3976. DataInUse = FALSE;
  3977. LOCK_PFN (OldIrql);
  3978. ControlArea = (PCONTROL_AREA) File->SectionObjectPointer->DataSectionObject;
  3979. if (ControlArea) {
  3980. if (ControlArea->NumberOfSystemCacheViews) {
  3981. UNLOCK_PFN (OldIrql);
  3982. CcFlushCache (File->SectionObjectPointer,
  3983. NULL,
  3984. 0,
  3985. &IoStatus);
  3986. }
  3987. else {
  3988. UNLOCK_PFN (OldIrql);
  3989. MmFlushSection (File->SectionObjectPointer,
  3990. NULL,
  3991. 0,
  3992. &IoStatus,
  3993. TRUE);
  3994. }
  3995. if ((ControlArea->NumberOfSectionReferences != 0) ||
  3996. (ControlArea->NumberOfMappedViews != 0)) {
  3997. DataInUse = TRUE;
  3998. }
  3999. }
  4000. else {
  4001. UNLOCK_PFN (OldIrql);
  4002. }
  4003. return DataInUse;
  4004. }
  4005. PVOID
  4006. MiCopyHeaderIfResident (
  4007. IN PFILE_OBJECT File,
  4008. IN PFN_NUMBER ImagePageFrameNumber
  4009. )
  4010. /*++
  4011. Routine Description:
  4012. This routine copies the image header from the data section if there is
  4013. one and the page is already resident or in transition.
  4014. Arguments:
  4015. File - Supplies the file object.
  4016. ImagePageFrameNumber - Supplies the image frame to copy the data into.
  4017. Return Value:
  4018. Virtual address of the image page frame number if successful, NULL if not.
  4019. Environment:
  4020. Kernel mode, APC_LEVEL and below.
  4021. --*/
  4022. {
  4023. PMMPFN Pfn1;
  4024. PVOID DataPage;
  4025. PVOID ImagePage;
  4026. KIRQL OldIrql;
  4027. PCONTROL_AREA ControlArea;
  4028. PMMPTE PointerPte;
  4029. MMPTE PteContents;
  4030. PFN_NUMBER PageFrameIndex;
  4031. PEPROCESS Process;
  4032. PSUBSECTION Subsection;
  4033. PSECTION_OBJECT_POINTERS SectionObjectPointer;
  4034. //
  4035. // Take a quick (safely unsynchronized) look to see whether to bother
  4036. // mapping the image header page at all - if there's no data section
  4037. // object, then skip it and just return.
  4038. //
  4039. SectionObjectPointer = File->SectionObjectPointer;
  4040. if (SectionObjectPointer == NULL) {
  4041. return NULL;
  4042. }
  4043. ControlArea = (PCONTROL_AREA) SectionObjectPointer->DataSectionObject;
  4044. if (ControlArea == NULL) {
  4045. return NULL;
  4046. }
  4047. //
  4048. // There's a data section, so map the target page.
  4049. //
  4050. ImagePage = MiMapImageHeaderInHyperSpace (ImagePageFrameNumber);
  4051. LOCK_PFN (OldIrql);
  4052. //
  4053. // Now that we are synchronized via the PFN lock, take a safe look.
  4054. //
  4055. SectionObjectPointer = File->SectionObjectPointer;
  4056. if (SectionObjectPointer == NULL) {
  4057. UNLOCK_PFN (OldIrql);
  4058. MiUnmapImageHeaderInHyperSpace ();
  4059. return NULL;
  4060. }
  4061. ControlArea = (PCONTROL_AREA) SectionObjectPointer->DataSectionObject;
  4062. if (ControlArea == NULL) {
  4063. UNLOCK_PFN (OldIrql);
  4064. MiUnmapImageHeaderInHyperSpace ();
  4065. return NULL;
  4066. }
  4067. if ((ControlArea->u.Flags.BeingCreated) ||
  4068. (ControlArea->u.Flags.BeingDeleted)) {
  4069. UNLOCK_PFN (OldIrql);
  4070. MiUnmapImageHeaderInHyperSpace ();
  4071. return NULL;
  4072. }
  4073. if (ControlArea->u.Flags.Rom == 0) {
  4074. Subsection = (PSUBSECTION) (ControlArea + 1);
  4075. }
  4076. else {
  4077. Subsection = (PSUBSECTION)((PLARGE_CONTROL_AREA)ControlArea + 1);
  4078. }
  4079. //
  4080. // If the prototype PTEs have been tossed (or never created) then we
  4081. // don't have any data to copy.
  4082. //
  4083. PointerPte = Subsection->SubsectionBase;
  4084. if (PointerPte == NULL) {
  4085. UNLOCK_PFN (OldIrql);
  4086. MiUnmapImageHeaderInHyperSpace ();
  4087. return NULL;
  4088. }
  4089. if (MiGetPteAddress (PointerPte)->u.Hard.Valid == 0) {
  4090. //
  4091. // We have no reference to the data section so if we can't do this
  4092. // without relinquishing the PFN lock, then don't bother.
  4093. // ie: the entire control area and everything can be freed
  4094. // while a call to MiMakeSystemAddressValidPfn releases the lock.
  4095. //
  4096. UNLOCK_PFN (OldIrql);
  4097. MiUnmapImageHeaderInHyperSpace ();
  4098. return NULL;
  4099. }
  4100. PteContents = *PointerPte;
  4101. if ((PteContents.u.Hard.Valid == 1) ||
  4102. ((PteContents.u.Soft.Prototype == 0) &&
  4103. (PteContents.u.Soft.Transition == 1))) {
  4104. if (PteContents.u.Hard.Valid == 1) {
  4105. PageFrameIndex = MI_GET_PAGE_FRAME_FROM_PTE (&PteContents);
  4106. }
  4107. else {
  4108. PageFrameIndex = MI_GET_PAGE_FRAME_FROM_TRANSITION_PTE (&PteContents);
  4109. Pfn1 = MI_PFN_ELEMENT (PageFrameIndex);
  4110. if (Pfn1->u3.e1.ReadInProgress != 0) {
  4111. UNLOCK_PFN (OldIrql);
  4112. MiUnmapImageHeaderInHyperSpace ();
  4113. return NULL;
  4114. }
  4115. }
  4116. Process = PsGetCurrentProcess ();
  4117. DataPage = MiMapPageInHyperSpaceAtDpc (Process, PageFrameIndex);
  4118. RtlCopyMemory (ImagePage, DataPage, PAGE_SIZE);
  4119. MiUnmapPageInHyperSpaceFromDpc (Process, DataPage);
  4120. UNLOCK_PFN (OldIrql);
  4121. return ImagePage;
  4122. }
  4123. //
  4124. // The data page is not resident, so return NULL and the caller will take
  4125. // the long way.
  4126. //
  4127. UNLOCK_PFN (OldIrql);
  4128. MiUnmapImageHeaderInHyperSpace ();
  4129. return NULL;
  4130. }