2 * PROJECT: ReactOS Kernel
3 * LICENSE: BSD - See COPYING.ARM in the top level directory
4 * FILE: ntoskrnl/mm/ARM3/procsup.c
5 * PURPOSE: ARM Memory Manager Process Related Management
6 * PROGRAMMERS: ReactOS Portable Systems Group
9 /* INCLUDES *******************************************************************/
15 #line 15 "ARMĀ³::PROCSUP"
16 #define MODULE_INVOLVED_IN_ARM3
17 #include "../ARM3/miarm.h"
19 /* GLOBALS ********************************************************************/
21 ULONG MmProcessColorSeed
= 0x12345678;
23 /* PRIVATE FUNCTIONS **********************************************************/
27 MiRosTakeOverPebTebRanges(IN PEPROCESS Process
)
30 PMEMORY_AREA MemoryArea
;
31 PHYSICAL_ADDRESS BoundaryAddressMultiple
;
32 PVOID AllocatedBase
= (PVOID
)USER_SHARED_DATA
;
33 BoundaryAddressMultiple
.QuadPart
= 0;
35 Status
= MmCreateMemoryArea(&Process
->Vm
,
36 MEMORY_AREA_OWNED_BY_ARM3
,
38 ((ULONG_PTR
)MM_HIGHEST_USER_ADDRESS
- 1) -
39 (ULONG_PTR
)USER_SHARED_DATA
,
44 BoundaryAddressMultiple
);
45 ASSERT(NT_SUCCESS(Status
));
50 MiCreatePebOrTeb(IN PEPROCESS Process
,
54 PETHREAD Thread
= PsGetCurrentThread();
58 ULONG_PTR StartAddress
, EndAddress
;
59 LARGE_INTEGER CurrentTime
;
60 TABLE_SEARCH_RESULT Result
= TableFoundNode
;
61 PMMADDRESS_NODE Parent
;
64 Vad
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(MMVAD_LONG
), 'ldaV');
65 if (!Vad
) return STATUS_NO_MEMORY
;
67 /* Setup the primary flags with the size, and make it commited, private, RW */
69 Vad
->u
.VadFlags
.CommitCharge
= BYTES_TO_PAGES(Size
);
70 Vad
->u
.VadFlags
.MemCommit
= TRUE
;
71 Vad
->u
.VadFlags
.PrivateMemory
= TRUE
;
72 Vad
->u
.VadFlags
.Protection
= MM_READWRITE
;
73 Vad
->u
.VadFlags
.NoChange
= TRUE
;
75 /* Setup the secondary flags to make it a secured, writable, long VAD */
76 Vad
->u2
.LongFlags2
= 0;
77 Vad
->u2
.VadFlags2
.OneSecured
= TRUE
;
78 Vad
->u2
.VadFlags2
.LongVad
= TRUE
;
79 Vad
->u2
.VadFlags2
.ReadOnly
= FALSE
;
81 /* Lock the process address space */
82 KeAcquireGuardedMutex(&Process
->AddressCreationLock
);
84 /* Check if this is a PEB creation */
85 if (Size
== sizeof(PEB
))
87 /* Start at the highest valid address */
88 StartAddress
= (ULONG_PTR
)MM_HIGHEST_VAD_ADDRESS
+ 1;
90 /* Select the random coefficient */
91 KeQueryTickCount(&CurrentTime
);
92 CurrentTime
.LowPart
&= ((64 * _1KB
) >> PAGE_SHIFT
) - 1;
93 if (CurrentTime
.LowPart
<= 1) CurrentTime
.LowPart
= 2;
94 RandomCoeff
= CurrentTime
.LowPart
<< PAGE_SHIFT
;
96 /* Select the highest valid address minus the random coefficient */
97 StartAddress
-= RandomCoeff
;
98 EndAddress
= StartAddress
+ ROUND_TO_PAGES(Size
) - 1;
100 /* Try to find something below the random upper margin */
101 Result
= MiFindEmptyAddressRangeDownTree(ROUND_TO_PAGES(Size
),
109 /* Check for success. TableFoundNode means nothing free. */
110 if (Result
== TableFoundNode
)
112 /* For TEBs, or if a PEB location couldn't be found, scan the VAD root */
113 Result
= MiFindEmptyAddressRangeDownTree(ROUND_TO_PAGES(Size
),
114 (ULONG_PTR
)MM_HIGHEST_VAD_ADDRESS
+ 1,
119 /* Bail out, if still nothing free was found */
120 if (Result
== TableFoundNode
) return STATUS_NO_MEMORY
;
123 /* Validate that it came from the VAD ranges */
124 ASSERT(*Base
>= (ULONG_PTR
)MI_LOWEST_VAD_ADDRESS
);
126 /* Build the rest of the VAD now */
127 Vad
->StartingVpn
= (*Base
) >> PAGE_SHIFT
;
128 Vad
->EndingVpn
= ((*Base
) + Size
- 1) >> PAGE_SHIFT
;
129 Vad
->u3
.Secured
.StartVpn
= *Base
;
130 Vad
->u3
.Secured
.EndVpn
= (Vad
->EndingVpn
<< PAGE_SHIFT
) | (PAGE_SIZE
- 1);
131 Vad
->u1
.Parent
= NULL
;
133 /* FIXME: Should setup VAD bitmap */
134 Status
= STATUS_SUCCESS
;
136 /* Pretend as if we own the working set */
137 MiLockProcessWorkingSet(Process
, Thread
);
140 ASSERT(Vad
->EndingVpn
>= Vad
->StartingVpn
);
141 Process
->VadRoot
.NodeHint
= Vad
;
142 Vad
->ControlArea
= NULL
; // For Memory-Area hack
143 Vad
->FirstPrototypePte
= NULL
;
144 DPRINT("VAD: %p\n", Vad
);
145 DPRINT("Allocated PEB/TEB at: 0x%p for %16s\n", *Base
, Process
->ImageFileName
);
146 MiInsertNode(&Process
->VadRoot
, (PVOID
)Vad
, Parent
, Result
);
148 /* Release the working set */
149 MiUnlockProcessWorkingSet(Process
, Thread
);
151 /* Release the address space lock */
152 KeReleaseGuardedMutex(&Process
->AddressCreationLock
);
154 /* Return the status */
160 MmDeleteTeb(IN PEPROCESS Process
,
164 PETHREAD Thread
= PsGetCurrentThread();
166 PMM_AVL_TABLE VadTree
= &Process
->VadRoot
;
167 DPRINT("Deleting TEB: %p in %16s\n", Teb
, Process
->ImageFileName
);
169 /* TEB is one page */
170 TebEnd
= (ULONG_PTR
)Teb
+ ROUND_TO_PAGES(sizeof(TEB
)) - 1;
172 /* Attach to the process */
173 KeAttachProcess(&Process
->Pcb
);
175 /* Lock the process address space */
176 KeAcquireGuardedMutex(&Process
->AddressCreationLock
);
178 /* Find the VAD, make sure it's a TEB VAD */
179 Vad
= MiLocateAddress(Teb
);
180 DPRINT("Removing node for VAD: %lx %lx\n", Vad
->StartingVpn
, Vad
->EndingVpn
);
182 if (Vad
->StartingVpn
!= ((ULONG_PTR
)Teb
>> PAGE_SHIFT
))
184 /* Bug in the AVL code? */
185 DPRINT1("Corrupted VAD!\n");
189 /* Sanity checks for a valid TEB VAD */
190 ASSERT((Vad
->StartingVpn
== ((ULONG_PTR
)Teb
>> PAGE_SHIFT
) &&
191 (Vad
->EndingVpn
== (TebEnd
>> PAGE_SHIFT
))));
192 ASSERT(Vad
->u
.VadFlags
.NoChange
== TRUE
);
193 ASSERT(Vad
->u2
.VadFlags2
.MultipleSecured
== FALSE
);
195 /* Lock the working set */
196 MiLockProcessWorkingSet(Process
, Thread
);
198 /* Remove this VAD from the tree */
199 ASSERT(VadTree
->NumberGenericTableElements
>= 1);
200 MiRemoveNode((PMMADDRESS_NODE
)Vad
, VadTree
);
202 /* Release the working set */
203 MiUnlockProcessWorkingSet(Process
, Thread
);
209 /* Release the address space lock */
210 KeReleaseGuardedMutex(&Process
->AddressCreationLock
);
218 MmDeleteKernelStack(IN PVOID StackBase
,
222 PFN_NUMBER StackPages
, PageFrameNumber
;//, PageTableFrameNumber;
223 PMMPFN Pfn1
;//, Pfn2;
228 // This should be the guard page, so decrement by one
230 PointerPte
= MiAddressToPte(StackBase
);
234 // Calculate pages used
236 StackPages
= BYTES_TO_PAGES(GuiStack
?
237 KERNEL_LARGE_STACK_SIZE
: KERNEL_STACK_SIZE
);
239 /* Acquire the PFN lock */
240 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
245 for (i
= 0; i
< StackPages
; i
++)
248 // Check if this is a valid PTE
250 if (PointerPte
->u
.Hard
.Valid
== 1)
252 /* Get the PTE's page */
253 PageFrameNumber
= PFN_FROM_PTE(PointerPte
);
254 Pfn1
= MiGetPfnEntry(PageFrameNumber
);
255 #if 0 // ARM3 might not own the page table, so don't take this risk. Leak it instead!
256 /* Now get the page of the page table mapping it */
257 PageTableFrameNumber
= Pfn1
->u4
.PteFrame
;
258 Pfn2
= MiGetPfnEntry(PageTableFrameNumber
);
260 /* Remove a shared reference, since the page is going away */
261 MiDecrementShareCount(Pfn2
, PageTableFrameNumber
);
263 /* Set the special pending delete marker */
264 MI_SET_PFN_DELETED(Pfn1
);
266 /* And now delete the actual stack page */
267 MiDecrementShareCount(Pfn1
, PageFrameNumber
);
277 // We should be at the guard page now
279 ASSERT(PointerPte
->u
.Hard
.Valid
== 0);
281 /* Release the PFN lock */
282 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
287 MiReleaseSystemPtes(PointerPte
, StackPages
+ 1, SystemPteSpace
);
292 MmCreateKernelStack(IN BOOLEAN GuiStack
,
295 PFN_NUMBER StackPtes
, StackPages
;
296 PMMPTE PointerPte
, StackPte
;
298 MMPTE TempPte
, InvalidPte
;
300 PFN_NUMBER PageFrameIndex
;
304 // Calculate pages needed
309 // We'll allocate 64KB stack, but only commit 12K
311 StackPtes
= BYTES_TO_PAGES(KERNEL_LARGE_STACK_SIZE
);
312 StackPages
= BYTES_TO_PAGES(KERNEL_LARGE_STACK_COMMIT
);
318 // We'll allocate 12K and that's it
320 StackPtes
= BYTES_TO_PAGES(KERNEL_STACK_SIZE
);
321 StackPages
= StackPtes
;
325 // Reserve stack pages, plus a guard page
327 StackPte
= MiReserveSystemPtes(StackPtes
+ 1, SystemPteSpace
);
328 if (!StackPte
) return NULL
;
331 // Get the stack address
333 BaseAddress
= MiPteToAddress(StackPte
+ StackPtes
+ 1);
336 // Select the right PTE address where we actually start committing pages
338 PointerPte
= StackPte
;
339 if (GuiStack
) PointerPte
+= BYTES_TO_PAGES(KERNEL_LARGE_STACK_SIZE
-
340 KERNEL_LARGE_STACK_COMMIT
);
343 /* Setup the temporary invalid PTE */
344 MI_MAKE_SOFTWARE_PTE(&InvalidPte
, MM_NOACCESS
);
346 /* Setup the template stack PTE */
347 MI_MAKE_HARDWARE_PTE_KERNEL(&TempPte
, PointerPte
+ 1, MM_READWRITE
, 0);
350 // Acquire the PFN DB lock
352 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
355 // Loop each stack page
357 for (i
= 0; i
< StackPages
; i
++)
364 /* Get a page and write the current invalid PTE */
365 PageFrameIndex
= MiRemoveAnyPage(MI_GET_NEXT_COLOR());
366 MI_WRITE_INVALID_PTE(PointerPte
, InvalidPte
);
368 /* Initialize the PFN entry for this page */
369 MiInitializePfn(PageFrameIndex
, PointerPte
, 1);
371 /* Write the valid PTE */
372 TempPte
.u
.Hard
.PageFrameNumber
= PageFrameIndex
;
373 MI_WRITE_VALID_PTE(PointerPte
, TempPte
);
377 // Release the PFN lock
379 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
382 // Return the stack address
389 MmGrowKernelStackEx(IN PVOID StackPointer
,
392 PKTHREAD Thread
= KeGetCurrentThread();
393 PMMPTE LimitPte
, NewLimitPte
, LastPte
;
395 MMPTE TempPte
, InvalidPte
;
396 PFN_NUMBER PageFrameIndex
;
399 // Make sure the stack did not overflow
401 ASSERT(((ULONG_PTR
)Thread
->StackBase
- (ULONG_PTR
)Thread
->StackLimit
) <=
402 (KERNEL_LARGE_STACK_SIZE
+ PAGE_SIZE
));
405 // Get the current stack limit
407 LimitPte
= MiAddressToPte(Thread
->StackLimit
);
408 ASSERT(LimitPte
->u
.Hard
.Valid
== 1);
411 // Get the new one and make sure this isn't a retarded request
413 NewLimitPte
= MiAddressToPte((PVOID
)((ULONG_PTR
)StackPointer
- GrowSize
));
414 if (NewLimitPte
== LimitPte
) return STATUS_SUCCESS
;
417 // Now make sure you're not going past the reserved space
419 LastPte
= MiAddressToPte((PVOID
)((ULONG_PTR
)Thread
->StackBase
-
420 KERNEL_LARGE_STACK_SIZE
));
421 if (NewLimitPte
< LastPte
)
426 DPRINT1("Thread wants too much stack\n");
427 return STATUS_STACK_OVERFLOW
;
431 // Calculate the number of new pages
435 /* Setup the temporary invalid PTE */
436 MI_MAKE_SOFTWARE_PTE(&InvalidPte
, MM_NOACCESS
);
439 // Acquire the PFN DB lock
441 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
444 // Loop each stack page
446 while (LimitPte
>= NewLimitPte
)
448 /* Get a page and write the current invalid PTE */
449 PageFrameIndex
= MiRemoveAnyPage(MI_GET_NEXT_COLOR());
450 MI_WRITE_INVALID_PTE(LimitPte
, InvalidPte
);
452 /* Initialize the PFN entry for this page */
453 MiInitializePfn(PageFrameIndex
, LimitPte
, 1);
455 /* Setup the template stack PTE */
456 MI_MAKE_HARDWARE_PTE_KERNEL(&TempPte
, LimitPte
, MM_READWRITE
, PageFrameIndex
);
458 /* Write the valid PTE */
459 MI_WRITE_VALID_PTE(LimitPte
--, TempPte
);
463 // Release the PFN lock
465 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
470 Thread
->StackLimit
= (ULONG_PTR
)MiPteToAddress(NewLimitPte
);
471 return STATUS_SUCCESS
;
476 MmGrowKernelStack(IN PVOID StackPointer
)
479 // Call the extended version
481 return MmGrowKernelStackEx(StackPointer
, KERNEL_LARGE_STACK_COMMIT
);
486 MmSetMemoryPriorityProcess(IN PEPROCESS Process
,
487 IN UCHAR MemoryPriority
)
492 // Check if we have less then 16MB of Physical Memory
494 if ((MmSystemSize
== MmSmallSystem
) &&
495 (MmNumberOfPhysicalPages
< ((15 * 1024 * 1024) / PAGE_SIZE
)))
498 // Always use background priority
500 MemoryPriority
= MEMORY_PRIORITY_BACKGROUND
;
504 // Save the old priority and update it
506 OldPriority
= (UCHAR
)Process
->Vm
.Flags
.MemoryPriority
;
507 Process
->Vm
.Flags
.MemoryPriority
= MemoryPriority
;
510 // Return the old priority
517 MmGetSessionLocaleId(VOID
)
523 // Get the current process
525 Process
= PsGetCurrentProcess();
528 // Check if it's the Session Leader
530 if (Process
->Vm
.Flags
.SessionLeader
)
533 // Make sure it has a valid Session
535 if (Process
->Session
)
541 return ((PMM_SESSION_SPACE
)Process
->Session
)->LocaleId
;
547 // Not a session leader, return the default
549 return PsDefaultThreadLocaleId
;
554 MmCreatePeb(IN PEPROCESS Process
,
555 IN PINITIAL_PEB InitialPeb
,
559 LARGE_INTEGER SectionOffset
;
561 PVOID TableBase
= NULL
;
562 PIMAGE_NT_HEADERS NtHeaders
;
563 PIMAGE_LOAD_CONFIG_DIRECTORY ImageConfigData
;
565 USHORT Characteristics
;
566 KAFFINITY ProcessAffinityMask
= 0;
567 SectionOffset
.QuadPart
= (ULONGLONG
)0;
573 KeAttachProcess(&Process
->Pcb
);
578 Status
= MiCreatePebOrTeb(Process
, sizeof(PEB
), (PULONG_PTR
)&Peb
);
579 ASSERT(NT_SUCCESS(Status
));
584 Status
= MmMapViewOfSection(ExpNlsSectionPointer
,
594 if (!NT_SUCCESS(Status
)) return Status
;
597 // Use SEH in case we can't load the PEB
602 // Initialize the PEB
604 RtlZeroMemory(Peb
, sizeof(PEB
));
609 Peb
->ImageBaseAddress
= Process
->SectionBaseAddress
;
610 Peb
->InheritedAddressSpace
= InitialPeb
->InheritedAddressSpace
;
611 Peb
->Mutant
= InitialPeb
->Mutant
;
612 Peb
->ImageUsesLargePages
= InitialPeb
->ImageUsesLargePages
;
617 Peb
->AnsiCodePageData
= (PCHAR
)TableBase
+ ExpAnsiCodePageDataOffset
;
618 Peb
->OemCodePageData
= (PCHAR
)TableBase
+ ExpOemCodePageDataOffset
;
619 Peb
->UnicodeCaseTableData
= (PCHAR
)TableBase
+ ExpUnicodeCaseTableDataOffset
;
622 // Default Version Data (could get changed below)
624 Peb
->OSMajorVersion
= NtMajorVersion
;
625 Peb
->OSMinorVersion
= NtMinorVersion
;
626 Peb
->OSBuildNumber
= (USHORT
)(NtBuildNumber
& 0x3FFF);
627 Peb
->OSPlatformId
= 2; /* VER_PLATFORM_WIN32_NT */
628 Peb
->OSCSDVersion
= (USHORT
)CmNtCSDVersion
;
631 // Heap and Debug Data
633 Peb
->NumberOfProcessors
= KeNumberProcessors
;
634 Peb
->BeingDebugged
= (BOOLEAN
)(Process
->DebugPort
!= NULL
? TRUE
: FALSE
);
635 Peb
->NtGlobalFlag
= NtGlobalFlag
;
636 /*Peb->HeapSegmentReserve = MmHeapSegmentReserve;
637 Peb->HeapSegmentCommit = MmHeapSegmentCommit;
638 Peb->HeapDeCommitTotalFreeThreshold = MmHeapDeCommitTotalFreeThreshold;
639 Peb->HeapDeCommitFreeBlockThreshold = MmHeapDeCommitFreeBlockThreshold;
640 Peb->CriticalSectionTimeout = MmCriticalSectionTimeout;
641 Peb->MinimumStackCommit = MmMinimumStackCommitInBytes;
643 Peb
->MaximumNumberOfHeaps
= (PAGE_SIZE
- sizeof(PEB
)) / sizeof(PVOID
);
644 Peb
->ProcessHeaps
= (PVOID
*)(Peb
+ 1);
649 if (Process
->Session
) Peb
->SessionId
= 0; // MmGetSessionId(Process);
651 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
657 _SEH2_YIELD(return _SEH2_GetExceptionCode());
662 // Use SEH in case we can't load the image
669 NtHeaders
= RtlImageNtHeader(Peb
->ImageBaseAddress
);
670 Characteristics
= NtHeaders
->FileHeader
.Characteristics
;
672 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
678 _SEH2_YIELD(return STATUS_INVALID_IMAGE_PROTECT
);
688 // Use SEH in case we can't load the headers
693 // Get the Image Config Data too
695 ImageConfigData
= RtlImageDirectoryEntryToData(Peb
->ImageBaseAddress
,
697 IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
,
704 ProbeForRead(ImageConfigData
,
705 sizeof(IMAGE_LOAD_CONFIG_DIRECTORY
),
710 // Write subsystem data
712 Peb
->ImageSubsystem
= NtHeaders
->OptionalHeader
.Subsystem
;
713 Peb
->ImageSubsystemMajorVersion
= NtHeaders
->OptionalHeader
.MajorSubsystemVersion
;
714 Peb
->ImageSubsystemMinorVersion
= NtHeaders
->OptionalHeader
.MinorSubsystemVersion
;
717 // Check for version data
719 if (NtHeaders
->OptionalHeader
.Win32VersionValue
)
722 // Extract values and write them
724 Peb
->OSMajorVersion
= NtHeaders
->OptionalHeader
.Win32VersionValue
& 0xFF;
725 Peb
->OSMinorVersion
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 8) & 0xFF;
726 Peb
->OSBuildNumber
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 16) & 0x3FFF;
727 Peb
->OSPlatformId
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 30) ^ 2;
731 // Process the image config data overrides if specfied
733 if (ImageConfigData
!= NULL
)
736 // Process CSD version override
738 if (ImageConfigData
->CSDVersion
)
743 Peb
->OSCSDVersion
= ImageConfigData
->CSDVersion
;
747 // Process affinity mask ovverride
749 if (ImageConfigData
->ProcessAffinityMask
)
754 ProcessAffinityMask
= ImageConfigData
->ProcessAffinityMask
;
759 // Check if this is a UP image
760 if (Characteristics
& IMAGE_FILE_UP_SYSTEM_ONLY
)
763 // Force it to use CPU 0
765 Peb
->ImageProcessAffinityMask
= 0;
770 // Whatever was configured
772 Peb
->ImageProcessAffinityMask
= ProcessAffinityMask
;
775 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
781 _SEH2_YIELD(return STATUS_INVALID_IMAGE_PROTECT
);
787 // Detach from the Process
791 return STATUS_SUCCESS
;
796 MmCreateTeb(IN PEPROCESS Process
,
797 IN PCLIENT_ID ClientId
,
798 IN PINITIAL_TEB InitialTeb
,
802 NTSTATUS Status
= STATUS_SUCCESS
;
808 KeAttachProcess(&Process
->Pcb
);
813 Status
= MiCreatePebOrTeb(Process
, sizeof(TEB
), (PULONG_PTR
)&Teb
);
814 ASSERT(NT_SUCCESS(Status
));
817 // Use SEH in case we can't load the TEB
822 // Initialize the PEB
824 RtlZeroMemory(Teb
, sizeof(TEB
));
829 Teb
->NtTib
.ExceptionList
= EXCEPTION_CHAIN_END
;
830 Teb
->NtTib
.Self
= (PNT_TIB
)Teb
;
833 // Identify this as an OS/2 V3.0 ("Cruiser") TIB
835 Teb
->NtTib
.Version
= 30 << 8;
840 Teb
->ClientId
= *ClientId
;
841 Teb
->RealClientId
= *ClientId
;
842 Teb
->ProcessEnvironmentBlock
= Process
->Peb
;
843 Teb
->CurrentLocale
= PsDefaultThreadLocaleId
;
846 // Check if we have a grandparent TEB
848 if ((InitialTeb
->PreviousStackBase
== NULL
) &&
849 (InitialTeb
->PreviousStackLimit
== NULL
))
852 // Use initial TEB values
854 Teb
->NtTib
.StackBase
= InitialTeb
->StackBase
;
855 Teb
->NtTib
.StackLimit
= InitialTeb
->StackLimit
;
856 Teb
->DeallocationStack
= InitialTeb
->AllocatedStackBase
;
861 // Use grandparent TEB values
863 Teb
->NtTib
.StackBase
= InitialTeb
->PreviousStackBase
;
864 Teb
->NtTib
.StackLimit
= InitialTeb
->PreviousStackLimit
;
868 // Initialize the static unicode string
870 Teb
->StaticUnicodeString
.MaximumLength
= sizeof(Teb
->StaticUnicodeBuffer
);
871 Teb
->StaticUnicodeString
.Buffer
= Teb
->StaticUnicodeBuffer
;
873 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
878 Status
= _SEH2_GetExceptionCode();
892 MmInitializeProcessAddressSpace(IN PEPROCESS Process
,
893 IN PEPROCESS ProcessClone OPTIONAL
,
894 IN PVOID Section OPTIONAL
,
896 IN POBJECT_NAME_INFORMATION
*AuditName OPTIONAL
)
898 NTSTATUS Status
= STATUS_SUCCESS
;
901 PROS_SECTION_OBJECT SectionObject
= Section
;
905 PFN_NUMBER PageFrameNumber
;
906 UNICODE_STRING FileName
;
911 /* We should have a PDE */
912 ASSERT(Process
->Pcb
.DirectoryTableBase
[0] != 0);
913 ASSERT(Process
->PdeUpdateNeeded
== FALSE
);
915 /* Attach to the process */
916 KeAttachProcess(&Process
->Pcb
);
918 /* The address space should now been in phase 1 or 0 */
919 ASSERT(Process
->AddressSpaceInitialized
<= 1);
920 Process
->AddressSpaceInitialized
= 2;
922 /* Initialize the Addresss Space lock */
923 KeInitializeGuardedMutex(&Process
->AddressCreationLock
);
924 Process
->Vm
.WorkingSetExpansionLinks
.Flink
= NULL
;
926 /* Initialize AVL tree */
927 ASSERT(Process
->VadRoot
.NumberGenericTableElements
== 0);
928 Process
->VadRoot
.BalancedRoot
.u1
.Parent
= &Process
->VadRoot
.BalancedRoot
;
930 /* Lock PFN database */
931 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
933 /* Setup the PFN for the PDE base of this process */
934 PointerPte
= MiAddressToPte(PDE_BASE
);
935 PageFrameNumber
= PFN_FROM_PTE(PointerPte
);
936 MiInitializePfn(PageFrameNumber
, PointerPte
, TRUE
);
938 /* Do the same for hyperspace */
939 PointerPde
= MiAddressToPde(HYPER_SPACE
);
940 PageFrameNumber
= PFN_FROM_PTE(PointerPde
);
941 MiInitializePfn(PageFrameNumber
, PointerPde
, TRUE
);
943 /* Release PFN lock */
944 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
946 /* Lock the VAD, ARM3-owned ranges away */
947 MiRosTakeOverPebTebRanges(Process
);
949 /* Check if there's a Section Object */
952 /* Determine the image file name and save it to EPROCESS */
953 FileName
= SectionObject
->FileObject
->FileName
;
954 Source
= (PWCHAR
)((PCHAR
)FileName
.Buffer
+ FileName
.Length
);
957 /* Loop the file name*/
958 while (Source
> FileName
.Buffer
)
960 /* Make sure this isn't a backslash */
961 if (*--Source
== OBJ_NAME_PATH_SEPARATOR
)
963 /* If so, stop it here */
969 /* Otherwise, keep going */
975 /* Copy the to the process and truncate it to 15 characters if necessary */
976 Destination
= Process
->ImageFileName
;
977 Length
= min(Length
, sizeof(Process
->ImageFileName
) - 1);
978 while (Length
--) *Destination
++ = (UCHAR
)*Source
++;
979 *Destination
= ANSI_NULL
;
981 /* Check if caller wants an audit name */
984 /* Setup the audit name */
985 Status
= SeInitializeProcessAuditName(SectionObject
->FileObject
,
988 if (!NT_SUCCESS(Status
))
996 /* Map the section */
997 Status
= MmMapViewOfSection(Section
,
1008 /* Save the pointer */
1009 Process
->SectionBaseAddress
= ImageBase
;
1012 /* Be nice and detach */
1015 /* Return status to caller */
1021 MmInitializeHandBuiltProcess(IN PEPROCESS Process
,
1022 IN PULONG_PTR DirectoryTableBase
)
1024 /* Share the directory base with the idle process */
1025 DirectoryTableBase
[0] = PsGetCurrentProcess()->Pcb
.DirectoryTableBase
[0];
1026 DirectoryTableBase
[1] = PsGetCurrentProcess()->Pcb
.DirectoryTableBase
[1];
1028 /* Initialize the Addresss Space */
1029 KeInitializeGuardedMutex(&Process
->AddressCreationLock
);
1030 KeInitializeSpinLock(&Process
->HyperSpaceLock
);
1031 Process
->Vm
.WorkingSetExpansionLinks
.Flink
= NULL
;
1032 ASSERT(Process
->VadRoot
.NumberGenericTableElements
== 0);
1033 Process
->VadRoot
.BalancedRoot
.u1
.Parent
= &Process
->VadRoot
.BalancedRoot
;
1036 Process
->HasAddressSpace
= TRUE
;//??
1037 return STATUS_SUCCESS
;
1042 MmInitializeHandBuiltProcess2(IN PEPROCESS Process
)
1044 /* Lock the VAD, ARM3-owned ranges away */
1045 MiRosTakeOverPebTebRanges(Process
);
1046 return STATUS_SUCCESS
;
1050 /* FIXME: Evaluate ways to make this portable yet arch-specific */
1053 MmCreateProcessAddressSpace(IN ULONG MinWs
,
1054 IN PEPROCESS Process
,
1055 OUT PULONG_PTR DirectoryTableBase
)
1058 PFN_NUMBER PdeIndex
, HyperIndex
;
1060 MMPTE TempPte
, PdePte
;
1065 /* Choose a process color */
1066 Process
->NextPageColor
= RtlRandom(&MmProcessColorSeed
);
1068 /* Setup the hyperspace lock */
1069 KeInitializeSpinLock(&Process
->HyperSpaceLock
);
1071 /* Lock PFN database */
1072 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
1074 /* Get a zero page for the PDE, if possible */
1075 Color
= MI_GET_NEXT_PROCESS_COLOR(Process
);
1076 PdeIndex
= MiRemoveZeroPageSafe(Color
);
1079 /* No zero pages, grab a free one */
1080 PdeIndex
= MiRemoveAnyPage(Color
);
1082 /* Zero it outside the PFN lock */
1083 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
1084 MiZeroPhysicalPage(PdeIndex
);
1085 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
1088 /* Get a zero page for hyperspace, if possible */
1089 Color
= MI_GET_NEXT_PROCESS_COLOR(Process
);
1090 HyperIndex
= MiRemoveZeroPageSafe(Color
);
1093 /* No zero pages, grab a free one */
1094 HyperIndex
= MiRemoveAnyPage(Color
);
1096 /* Zero it outside the PFN lock */
1097 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
1098 MiZeroPhysicalPage(HyperIndex
);
1102 /* Release the PFN lock */
1103 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
1106 /* Switch to phase 1 initialization */
1107 ASSERT(Process
->AddressSpaceInitialized
== 0);
1108 Process
->AddressSpaceInitialized
= 1;
1110 /* Set the base directory pointers */
1111 DirectoryTableBase
[0] = PdeIndex
<< PAGE_SHIFT
;
1112 DirectoryTableBase
[1] = HyperIndex
<< PAGE_SHIFT
;
1114 /* Make sure we don't already have a page directory setup */
1115 ASSERT(Process
->Pcb
.DirectoryTableBase
[0] == 0);
1117 /* Insert us into the Mm process list */
1118 InsertTailList(&MmProcessList
, &Process
->MmProcessLinks
);
1120 /* Get a PTE to map the page directory */
1121 PointerPte
= MiReserveSystemPtes(1, SystemPteSpace
);
1122 ASSERT(PointerPte
!= NULL
);
1125 MI_MAKE_HARDWARE_PTE_KERNEL(&PdePte
,
1130 /* Set it dirty and map it */
1131 PdePte
.u
.Hard
.Dirty
= TRUE
;
1132 MI_WRITE_VALID_PTE(PointerPte
, PdePte
);
1134 /* Now get the page directory (which we'll double map, so call it a page table */
1135 SystemTable
= MiPteToAddress(PointerPte
);
1137 /* Copy all the kernel mappings */
1138 PdeOffset
= MiGetPdeOffset(MmSystemRangeStart
);
1139 RtlCopyMemory(&SystemTable
[PdeOffset
],
1140 MiAddressToPde(MmSystemRangeStart
),
1141 PAGE_SIZE
- PdeOffset
* sizeof(MMPTE
));
1143 /* Now write the PTE/PDE entry for hyperspace itself */
1144 TempPte
= ValidKernelPte
;
1145 TempPte
.u
.Hard
.PageFrameNumber
= HyperIndex
;
1146 PdeOffset
= MiGetPdeOffset(HYPER_SPACE
);
1147 SystemTable
[PdeOffset
] = TempPte
;
1151 ASSERT(MiGetPdeOffset(MmHyperSpaceEnd
) >= PdeOffset
);
1153 /* Now do the x86 trick of making the PDE a page table itself */
1154 PdeOffset
= MiGetPdeOffset(PTE_BASE
);
1155 TempPte
.u
.Hard
.PageFrameNumber
= PdeIndex
;
1156 SystemTable
[PdeOffset
] = TempPte
;
1158 /* Let go of the system PTE */
1159 MiReleaseSystemPtes(PointerPte
, 1, SystemPteSpace
);
1166 MmCleanProcessAddressSpace(IN PEPROCESS Process
)
1169 PMM_AVL_TABLE VadTree
;
1170 PETHREAD Thread
= PsGetCurrentThread();
1172 /* Lock the process address space from changes */
1173 MmLockAddressSpace(&Process
->Vm
);
1175 /* Enumerate the VADs */
1176 VadTree
= &Process
->VadRoot
;
1177 while (VadTree
->NumberGenericTableElements
)
1179 /* Grab the current VAD */
1180 Vad
= (PMMVAD
)VadTree
->BalancedRoot
.RightChild
;
1182 /* Lock the working set */
1183 MiLockProcessWorkingSet(Process
, Thread
);
1185 /* Remove this VAD from the tree */
1186 ASSERT(VadTree
->NumberGenericTableElements
>= 1);
1187 MiRemoveNode((PMMADDRESS_NODE
)Vad
, VadTree
);
1189 /* Only PEB/TEB VADs supported for now */
1190 ASSERT(Vad
->u
.VadFlags
.PrivateMemory
== 1);
1191 ASSERT(Vad
->u
.VadFlags
.VadType
== VadNone
);
1193 /* Delete the addresses */
1194 MiDeleteVirtualAddresses(Vad
->StartingVpn
<< PAGE_SHIFT
,
1195 (Vad
->EndingVpn
<< PAGE_SHIFT
) | (PAGE_SIZE
- 1),
1198 /* Release the working set */
1199 MiUnlockProcessWorkingSet(Process
, Thread
);
1201 /* Skip ARM3 fake VADs, they'll be freed by MmDeleteProcessAddresSpace */
1202 if (Vad
->u
.VadFlags
.Spare
== 1)
1204 /* Set a flag so MmDeleteMemoryArea knows to free, but not to remove */
1205 Vad
->u
.VadFlags
.Spare
= 2;
1209 /* Free the VAD memory */
1213 /* Release the address space */
1214 MmUnlockAddressSpace(&Process
->Vm
);
1217 /* SYSTEM CALLS ***************************************************************/
1221 NtAllocateUserPhysicalPages(IN HANDLE ProcessHandle
,
1222 IN OUT PULONG_PTR NumberOfPages
,
1223 IN OUT PULONG_PTR UserPfnArray
)
1226 return STATUS_NOT_IMPLEMENTED
;
1231 NtMapUserPhysicalPages(IN PVOID VirtualAddresses
,
1232 IN ULONG_PTR NumberOfPages
,
1233 IN OUT PULONG_PTR UserPfnArray
)
1236 return STATUS_NOT_IMPLEMENTED
;
1241 NtMapUserPhysicalPagesScatter(IN PVOID
*VirtualAddresses
,
1242 IN ULONG_PTR NumberOfPages
,
1243 IN OUT PULONG_PTR UserPfnArray
)
1246 return STATUS_NOT_IMPLEMENTED
;
1251 NtFreeUserPhysicalPages(IN HANDLE ProcessHandle
,
1252 IN OUT PULONG_PTR NumberOfPages
,
1253 IN OUT PULONG_PTR UserPfnArray
)
1256 return STATUS_NOT_IMPLEMENTED
;