2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS kernel
4 * FILE: ntoskrnl/mm/procsup.c
5 * PURPOSE: Memory functions related to Processes
7 * PROGRAMMERS: Alex Ionescu (alex@relsoft.net)
10 /* INCLUDES *****************************************************************/
16 extern ULONG NtMajorVersion
;
17 extern ULONG NtMinorVersion
;
18 extern ULONG CmNtCSDVersion
;
19 extern ULONG NtBuildNumber
;
20 extern MM_SYSTEMSIZE MmSystemSize
;
22 #define MM_HIGHEST_VAD_ADDRESS \
23 (PVOID)((ULONG_PTR)MM_HIGHEST_USER_ADDRESS - (16 * PAGE_SIZE))
25 /* FUNCTIONS *****************************************************************/
29 MmSetMemoryPriorityProcess(IN PEPROCESS Process
,
30 IN UCHAR MemoryPriority
)
34 /* Check if we have less then 16MB of Physical Memory */
35 if ((MmSystemSize
== MmSmallSystem
) &&
36 (MmStats
.NrTotalPages
< ((15 * 1024 * 1024) / PAGE_SIZE
)))
38 /* Always use background priority */
42 /* Save the old priority and update it */
43 OldPriority
= (UCHAR
)Process
->Vm
.Flags
.MemoryPriority
;
44 Process
->Vm
.Flags
.MemoryPriority
= MemoryPriority
;
46 /* Return the old priority */
52 MmGetSessionLocaleId(VOID
)
57 /* Get the current process */
58 Process
= PsGetCurrentProcess();
60 /* Check if it's the Session Leader */
61 if (Process
->Vm
.Flags
.SessionLeader
)
63 /* Make sure it has a valid Session */
66 /* Get the Locale ID */
68 return ((PMM_SESSION_SPACE
)Process
->Session
)->LocaleId
;
73 /* Not a session leader, return the default */
74 return PsDefaultThreadLocaleId
;
79 MiCreatePebOrTeb(PEPROCESS Process
,
83 PMM_AVL_TABLE ProcessAddressSpace
= &Process
->VadRoot
;
84 PMEMORY_AREA MemoryArea
;
85 PHYSICAL_ADDRESS BoundaryAddressMultiple
;
86 PVOID AllocatedBase
= BaseAddress
;
87 BoundaryAddressMultiple
.QuadPart
= 0;
89 /* Acquire the Lock */
90 MmLockAddressSpace(ProcessAddressSpace
);
93 * Create a Peb or Teb.
94 * Loop until it works, decreasing by PAGE_SIZE each time. The logic here
95 * is that a PEB allocation should never fail since the address is free,
96 * while TEB allocation can fail, and we should simply try the address
97 * below. Is there a nicer way of doing this automagically? (ie: findning)
98 * a gap region? -- Alex
101 DPRINT("Trying to allocate: %x\n", AllocatedBase
);
102 Status
= MmCreateMemoryArea(ProcessAddressSpace
,
103 MEMORY_AREA_PEB_OR_TEB
,
110 BoundaryAddressMultiple
);
111 AllocatedBase
= RVA(AllocatedBase
, -PAGE_SIZE
);
112 } while (Status
!= STATUS_SUCCESS
);
114 /* Initialize the Region */
115 MmInitializeRegion(&MemoryArea
->Data
.VirtualMemoryData
.RegionListHead
,
120 /* Reserve the pages */
121 MmReserveSwapPages(PAGE_SIZE
);
123 /* Unlock Address Space */
124 DPRINT("Returning\n");
125 MmUnlockAddressSpace(ProcessAddressSpace
);
126 return RVA(AllocatedBase
, PAGE_SIZE
);
130 MiFreeStackPage(PVOID Context
,
131 MEMORY_AREA
* MemoryArea
,
137 ASSERT(SwapEntry
== 0);
138 if (Page
) MmReleasePageMemoryConsumer(MC_NPPOOL
, Page
);
143 MmDeleteKernelStack(PVOID StackBase
,
146 ULONG StackSize
= GuiStack
? KERNEL_LARGE_STACK_SIZE
: KERNEL_STACK_SIZE
;
148 /* Lock the Address Space */
149 MmLockAddressSpace(MmGetKernelAddressSpace());
151 /* Delete the Stack */
152 MmFreeMemoryAreaByPtr(MmGetKernelAddressSpace(),
153 (PVOID
)((ULONG_PTR
)StackBase
- StackSize
),
157 /* Unlock the Address Space */
158 MmUnlockAddressSpace(MmGetKernelAddressSpace());
163 MmDeleteTeb(PEPROCESS Process
,
166 PMM_AVL_TABLE ProcessAddressSpace
= &Process
->VadRoot
;
167 PMEMORY_AREA MemoryArea
;
169 /* Lock the Address Space */
170 MmLockAddressSpace(ProcessAddressSpace
);
172 MemoryArea
= MmLocateMemoryAreaByAddress(ProcessAddressSpace
, (PVOID
)Teb
);
176 MmFreeVirtualMemory(Process
, MemoryArea
);
179 /* Unlock the Address Space */
180 MmUnlockAddressSpace(ProcessAddressSpace
);
185 MmCreateKernelStack(BOOLEAN GuiStack
,
188 PMEMORY_AREA StackArea
;
190 PHYSICAL_ADDRESS BoundaryAddressMultiple
;
191 ULONG StackSize
= GuiStack
? KERNEL_LARGE_STACK_SIZE
: KERNEL_STACK_SIZE
;
192 PFN_TYPE Page
[KERNEL_LARGE_STACK_SIZE
/ PAGE_SIZE
];
193 PVOID KernelStack
= NULL
;
196 /* Initialize the Boundary Address */
197 BoundaryAddressMultiple
.QuadPart
= 0;
199 /* Lock the Kernel Address Space */
200 MmLockAddressSpace(MmGetKernelAddressSpace());
202 /* Create a MAREA for the Kernel Stack */
203 Status
= MmCreateMemoryArea(MmGetKernelAddressSpace(),
204 MEMORY_AREA_KERNEL_STACK
,
211 BoundaryAddressMultiple
);
213 /* Unlock the Address Space */
214 MmUnlockAddressSpace(MmGetKernelAddressSpace());
216 /* Check for Success */
217 if (!NT_SUCCESS(Status
))
219 DPRINT1("Failed to create thread stack\n");
220 KeBugCheck(MEMORY_MANAGEMENT
);
224 * Mark the Stack in use.
225 * Note: Currently we mark all 60KB in use for a GUI Thread.
226 * We should only do this inside MmGrowKernelStack. TODO!
228 for (i
= 0; i
< (StackSize
/ PAGE_SIZE
); i
++)
230 Status
= MmRequestPageMemoryConsumer(MC_NPPOOL
, TRUE
, &Page
[i
]);
233 /* Create a Virtual Mapping for it */
234 Status
= MmCreateVirtualMapping(NULL
,
238 StackSize
/ PAGE_SIZE
);
240 /* Check for success */
241 if (!NT_SUCCESS(Status
))
243 DPRINT1("Could not create Virtual Mapping for Kernel Stack\n");
244 KeBugCheck(MEMORY_MANAGEMENT
);
247 /* Return the stack base */
248 return (PVOID
)((ULONG_PTR
)KernelStack
+
249 (GuiStack
? KERNEL_LARGE_STACK_SIZE
: KERNEL_STACK_SIZE
));
257 MmGrowKernelStack(PVOID StackPointer
)
259 PETHREAD Thread
= PsGetCurrentThread();
261 /* Make sure we have reserved space for our grow */
262 ASSERT(((PCHAR
)Thread
->Tcb
.StackBase
- (PCHAR
)Thread
->Tcb
.StackLimit
) <=
263 (KERNEL_LARGE_STACK_SIZE
+ PAGE_SIZE
));
266 * We'll give you three more pages.
267 * NOTE: See note in MmCreateKernelStack. These pages are already being reserved.
268 * It would be more efficient to only grow them (commit them) here.
270 Thread
->Tcb
.StackLimit
-= KERNEL_STACK_SIZE
;
273 return STATUS_SUCCESS
;
278 MmCreatePeb(PEPROCESS Process
)
281 LARGE_INTEGER SectionOffset
;
283 PVOID TableBase
= NULL
;
284 PIMAGE_NT_HEADERS NtHeaders
;
285 PIMAGE_LOAD_CONFIG_DIRECTORY ImageConfigData
;
287 KAFFINITY ProcessAffinityMask
= 0;
288 SectionOffset
.QuadPart
= (ULONGLONG
)0;
289 DPRINT("MmCreatePeb\n");
291 /* Allocate the PEB */
292 Peb
= MiCreatePebOrTeb(Process
,
293 (PVOID
)((ULONG_PTR
)MM_HIGHEST_VAD_ADDRESS
+ 1));
294 ASSERT(Peb
== (PVOID
)0x7FFDF000);
297 DPRINT("Mapping NLS\n");
298 Status
= MmMapViewOfSection(ExpNlsSectionPointer
,
308 if (!NT_SUCCESS(Status
))
310 DPRINT1("MmMapViewOfSection() failed (Status %lx)\n", Status
);
313 DPRINT("TableBase %p ViewSize %lx\n", TableBase
, ViewSize
);
315 /* Attach to Process */
316 KeAttachProcess(&Process
->Pcb
);
318 /* Initialize the PEB */
319 DPRINT("Allocated: %x\n", Peb
);
320 RtlZeroMemory(Peb
, sizeof(PEB
));
323 DPRINT("Setting up PEB\n");
324 Peb
->ImageBaseAddress
= Process
->SectionBaseAddress
;
325 Peb
->InheritedAddressSpace
= 0;
329 Peb
->AnsiCodePageData
= (PCHAR
)TableBase
+ ExpAnsiCodePageDataOffset
;
330 Peb
->OemCodePageData
= (PCHAR
)TableBase
+ ExpOemCodePageDataOffset
;
331 Peb
->UnicodeCaseTableData
= (PCHAR
)TableBase
+ ExpUnicodeCaseTableDataOffset
;
333 /* Default Version Data (could get changed below) */
334 Peb
->OSMajorVersion
= NtMajorVersion
;
335 Peb
->OSMinorVersion
= NtMinorVersion
;
336 Peb
->OSBuildNumber
= (USHORT
)(NtBuildNumber
& 0x3FFF);
337 Peb
->OSPlatformId
= 2; /* VER_PLATFORM_WIN32_NT */
338 Peb
->OSCSDVersion
= (USHORT
)CmNtCSDVersion
;
340 /* Heap and Debug Data */
341 Peb
->NumberOfProcessors
= KeNumberProcessors
;
342 Peb
->BeingDebugged
= (BOOLEAN
)(Process
->DebugPort
!= NULL
? TRUE
: FALSE
);
343 Peb
->NtGlobalFlag
= NtGlobalFlag
;
344 /*Peb->HeapSegmentReserve = MmHeapSegmentReserve;
345 Peb->HeapSegmentCommit = MmHeapSegmentCommit;
346 Peb->HeapDeCommitTotalFreeThreshold = MmHeapDeCommitTotalFreeThreshold;
347 Peb->HeapDeCommitFreeBlockThreshold = MmHeapDeCommitFreeBlockThreshold;*/
348 Peb
->NumberOfHeaps
= 0;
349 Peb
->MaximumNumberOfHeaps
= (PAGE_SIZE
- sizeof(PEB
)) / sizeof(PVOID
);
350 Peb
->ProcessHeaps
= (PVOID
*)Peb
+ 1;
353 if ((NtHeaders
= RtlImageNtHeader(Peb
->ImageBaseAddress
)))
355 /* Write subsystem data */
356 Peb
->ImageSubSystem
= NtHeaders
->OptionalHeader
.Subsystem
;
357 Peb
->ImageSubSystemMajorVersion
= NtHeaders
->OptionalHeader
.MajorSubsystemVersion
;
358 Peb
->ImageSubSystemMinorVersion
= NtHeaders
->OptionalHeader
.MinorSubsystemVersion
;
360 /* Write Version Data */
361 if (NtHeaders
->OptionalHeader
.Win32VersionValue
)
363 Peb
->OSMajorVersion
= NtHeaders
->OptionalHeader
.Win32VersionValue
& 0xFF;
364 Peb
->OSMinorVersion
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 8) & 0xFF;
365 Peb
->OSBuildNumber
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 16) & 0x3FFF;
367 /* Set the Platform ID */
368 Peb
->OSPlatformId
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 30) ^ 2;
371 /* Check if the image is not safe for SMP */
372 if (NtHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_UP_SYSTEM_ONLY
)
374 /* FIXME: Choose one randomly */
375 Peb
->ImageProcessAffinityMask
= 1;
379 /* Use affinity from Image Header */
380 Peb
->ImageProcessAffinityMask
= ProcessAffinityMask
;
385 /* Get the Image Config Data too */
386 ImageConfigData
= RtlImageDirectoryEntryToData(Peb
->ImageBaseAddress
,
388 IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
,
391 ProbeForRead(ImageConfigData
,
392 sizeof(IMAGE_LOAD_CONFIG_DIRECTORY
),
395 /* Process the image config data overrides if specfied. */
396 if (ImageConfigData
!= NULL
)
398 if (ImageConfigData
->CSDVersion
)
400 Peb
->OSCSDVersion
= ImageConfigData
->CSDVersion
;
402 if (ImageConfigData
->ProcessAffinityMask
)
404 ProcessAffinityMask
= ImageConfigData
->ProcessAffinityMask
;
408 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
410 Status
= _SEH2_GetExceptionCode();
416 Peb
->SessionId
= Process
->Session
;
419 /* Detach from the Process */
422 DPRINT("MmCreatePeb: Peb created at %p\n", Peb
);
428 MmCreateTeb(PEPROCESS Process
,
430 PINITIAL_TEB InitialTeb
)
433 BOOLEAN Attached
= FALSE
;
435 /* Attach to the process */
436 DPRINT("MmCreateTeb\n");
437 if (Process
!= PsGetCurrentProcess())
439 /* Attach to Target */
440 KeAttachProcess(&Process
->Pcb
);
444 /* Allocate the TEB */
445 Teb
= MiCreatePebOrTeb(Process
,
446 (PVOID
)((ULONG_PTR
)MM_HIGHEST_VAD_ADDRESS
+ 1));
448 /* Initialize the PEB */
449 RtlZeroMemory(Teb
, sizeof(TEB
));
452 Teb
->Tib
.ExceptionList
= (PVOID
)0xFFFFFFFF;
453 Teb
->Tib
.Version
= 1;
454 Teb
->Tib
.Self
= (PNT_TIB
)Teb
;
457 Teb
->ClientId
= *ClientId
;
458 Teb
->RealClientId
= *ClientId
;
459 Teb
->ProcessEnvironmentBlock
= Process
->Peb
;
460 Teb
->CurrentLocale
= PsDefaultThreadLocaleId
;
462 /* Store stack information from InitialTeb */
463 if(InitialTeb
!= NULL
)
465 Teb
->Tib
.StackBase
= InitialTeb
->StackBase
;
466 Teb
->Tib
.StackLimit
= InitialTeb
->StackLimit
;
467 Teb
->DeallocationStack
= InitialTeb
->AllocatedStackBase
;
470 /* Initialize the static unicode string */
471 Teb
->StaticUnicodeString
.Length
= 0;
472 Teb
->StaticUnicodeString
.MaximumLength
= sizeof(Teb
->StaticUnicodeBuffer
);
473 Teb
->StaticUnicodeString
.Buffer
= Teb
->StaticUnicodeBuffer
;
475 /* Return TEB Address */
476 DPRINT("Allocated: %x\n", Teb
);
477 if (Attached
) KeDetachProcess();
483 MmInitializeHandBuiltProcess2(IN PEPROCESS Process
)
486 PMEMORY_AREA MemoryArea
;
487 PHYSICAL_ADDRESS BoundaryAddressMultiple
;
489 PMM_AVL_TABLE ProcessAddressSpace
= &Process
->VadRoot
;
490 BoundaryAddressMultiple
.QuadPart
= 0;
492 /* Create the shared data page */
493 BaseAddress
= (PVOID
)USER_SHARED_DATA
;
494 Status
= MmCreateMemoryArea(ProcessAddressSpace
,
495 MEMORY_AREA_SHARED_DATA
,
502 BoundaryAddressMultiple
);
508 MmInitializeProcessAddressSpace(IN PEPROCESS Process
,
509 IN PEPROCESS ProcessClone OPTIONAL
,
510 IN PVOID Section OPTIONAL
,
512 IN POBJECT_NAME_INFORMATION
*AuditName OPTIONAL
)
515 PMM_AVL_TABLE ProcessAddressSpace
= &Process
->VadRoot
;
517 PMEMORY_AREA MemoryArea
;
518 PHYSICAL_ADDRESS BoundaryAddressMultiple
;
521 PROS_SECTION_OBJECT SectionObject
= Section
;
522 BoundaryAddressMultiple
.QuadPart
= 0;
524 /* Initialize the Addresss Space lock */
525 KeInitializeGuardedMutex(&Process
->AddressCreationLock
);
526 Process
->VadRoot
.BalancedRoot
.u1
.Parent
= NULL
;
528 /* Acquire the Lock */
529 MmLockAddressSpace(ProcessAddressSpace
);
531 /* Protect the highest 64KB of the process address space */
532 BaseAddress
= (PVOID
)MmUserProbeAddress
;
533 Status
= MmCreateMemoryArea(ProcessAddressSpace
,
534 MEMORY_AREA_NO_ACCESS
,
541 BoundaryAddressMultiple
);
542 if (!NT_SUCCESS(Status
))
544 DPRINT1("Failed to protect last 64KB\n");
548 /* Protect the 60KB above the shared user page */
549 BaseAddress
= (char*)USER_SHARED_DATA
+ PAGE_SIZE
;
550 Status
= MmCreateMemoryArea(ProcessAddressSpace
,
551 MEMORY_AREA_NO_ACCESS
,
558 BoundaryAddressMultiple
);
559 if (!NT_SUCCESS(Status
))
561 DPRINT1("Failed to protect the memory above the shared user page\n");
565 /* Create the shared data page */
566 BaseAddress
= (PVOID
)USER_SHARED_DATA
;
567 Status
= MmCreateMemoryArea(ProcessAddressSpace
,
568 MEMORY_AREA_SHARED_DATA
,
575 BoundaryAddressMultiple
);
576 if (!NT_SUCCESS(Status
))
578 DPRINT1("Failed to create Shared User Data\n");
582 /* The process now has an address space */
583 Process
->HasAddressSpace
= TRUE
;
585 /* Check if there's a Section Object */
588 UNICODE_STRING FileName
;
593 /* Unlock the Address Space */
594 DPRINT("Unlocking\n");
595 MmUnlockAddressSpace(ProcessAddressSpace
);
597 DPRINT("Mapping process image. Section: %p, Process: %p, ImageBase: %p\n",
598 SectionObject
, Process
, &ImageBase
);
599 Status
= MmMapViewOfSection(Section
,
609 if (!NT_SUCCESS(Status
))
611 DPRINT1("Failed to map process Image\n");
615 /* Save the pointer */
616 Process
->SectionBaseAddress
= ImageBase
;
618 /* Determine the image file name and save it to EPROCESS */
619 DPRINT("Getting Image name\n");
620 FileName
= SectionObject
->FileObject
->FileName
;
621 szSrc
= (PWCHAR
)((PCHAR
)FileName
.Buffer
+ FileName
.Length
);
624 /* Loop the file name*/
625 while (szSrc
> FileName
.Buffer
)
627 /* Make sure this isn't a backslash */
628 if (*--szSrc
== OBJ_NAME_PATH_SEPARATOR
)
630 /* If so, stop it here */
636 /* Otherwise, keep going */
642 /* Copy the to the process and truncate it to 15 characters if necessary */
643 szDest
= Process
->ImageFileName
;
644 lnFName
= min(lnFName
, sizeof(Process
->ImageFileName
) - 1);
645 while (lnFName
--) *szDest
++ = (UCHAR
)*szSrc
++;
648 /* Check if caller wants an audit name */
651 /* Setup the audit name */
652 SeInitializeProcessAuditName(SectionObject
->FileObject
,
657 /* Return status to caller */
662 /* Unlock the Address Space */
663 DPRINT("Unlocking\n");
664 MmUnlockAddressSpace(ProcessAddressSpace
);
666 /* Return status to caller */
672 MmCleanProcessAddressSpace(IN PEPROCESS Process
)
674 /* FIXME: Add part of MmDeleteProcessAddressSpace here */
679 MmDeleteProcessAddressSpace(PEPROCESS Process
)
682 PMEMORY_AREA MemoryArea
;
684 DPRINT("MmDeleteProcessAddressSpace(Process %x (%s))\n", Process
,
685 Process
->ImageFileName
);
687 MmLockAddressSpace(&Process
->VadRoot
);
689 while ((MemoryArea
= (PMEMORY_AREA
)Process
->VadRoot
.BalancedRoot
.u1
.Parent
) != NULL
)
691 switch (MemoryArea
->Type
)
693 case MEMORY_AREA_SECTION_VIEW
:
694 Address
= (PVOID
)MemoryArea
->StartingAddress
;
695 MmUnlockAddressSpace(&Process
->VadRoot
);
696 MmUnmapViewOfSection(Process
, Address
);
697 MmLockAddressSpace(&Process
->VadRoot
);
700 case MEMORY_AREA_VIRTUAL_MEMORY
:
701 case MEMORY_AREA_PEB_OR_TEB
:
702 MmFreeVirtualMemory(Process
, MemoryArea
);
705 case MEMORY_AREA_SHARED_DATA
:
706 case MEMORY_AREA_NO_ACCESS
:
707 MmFreeMemoryArea(&Process
->VadRoot
,
713 case MEMORY_AREA_MDL_MAPPING
:
714 KeBugCheck(PROCESS_HAS_LOCKED_PAGES
);
718 KeBugCheck(MEMORY_MANAGEMENT
);
722 Mmi386ReleaseMmInfo(Process
);
724 MmUnlockAddressSpace(&Process
->VadRoot
);
726 DPRINT("Finished MmReleaseMmInfo()\n");
727 return(STATUS_SUCCESS
);