2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS kernel
4 * FILE: ntoskrnl/mm/process.c
5 * PURPOSE: Memory functions related to Processes
7 * PROGRAMMERS: Alex Ionescu (alex@relsoft.net)
10 /* INCLUDES *****************************************************************/
14 #include <internal/debug.h>
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 PMADDRESS_SPACE ProcessAddressSpace
= (PMADDRESS_SPACE
)&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 Stack
,
146 /* Lock the Address Space */
147 MmLockAddressSpace(MmGetKernelAddressSpace());
149 /* Delete the Stack */
150 MmFreeMemoryAreaByPtr(MmGetKernelAddressSpace(),
155 /* Unlock the Address Space */
156 MmUnlockAddressSpace(MmGetKernelAddressSpace());
161 MmDeleteTeb(PEPROCESS Process
,
164 PMADDRESS_SPACE ProcessAddressSpace
= (PMADDRESS_SPACE
)&Process
->VadRoot
;
165 PMEMORY_AREA MemoryArea
;
167 /* Lock the Address Space */
168 MmLockAddressSpace(ProcessAddressSpace
);
170 MemoryArea
= MmLocateMemoryAreaByAddress(ProcessAddressSpace
, (PVOID
)Teb
);
174 MmFreeVirtualMemory(Process
, MemoryArea
);
177 /* Unlock the Address Space */
178 MmUnlockAddressSpace(ProcessAddressSpace
);
183 MmCreateKernelStack(BOOLEAN GuiStack
,
186 PMEMORY_AREA StackArea
;
188 PHYSICAL_ADDRESS BoundaryAddressMultiple
;
189 ULONG StackSize
= GuiStack
? KERNEL_LARGE_STACK_SIZE
: KERNEL_STACK_SIZE
;
190 PFN_TYPE Page
[KERNEL_LARGE_STACK_SIZE
/ PAGE_SIZE
];
191 PVOID KernelStack
= NULL
;
194 /* Initialize the Boundary Address */
195 BoundaryAddressMultiple
.QuadPart
= 0;
197 /* Lock the Kernel Address Space */
198 MmLockAddressSpace(MmGetKernelAddressSpace());
200 /* Create a MAREA for the Kernel Stack */
201 Status
= MmCreateMemoryArea(MmGetKernelAddressSpace(),
202 MEMORY_AREA_KERNEL_STACK
,
209 BoundaryAddressMultiple
);
211 /* Unlock the Address Space */
212 MmUnlockAddressSpace(MmGetKernelAddressSpace());
214 /* Check for Success */
215 if (!NT_SUCCESS(Status
))
217 DPRINT1("Failed to create thread stack\n");
222 * Mark the Stack in use.
223 * Note: Currently we mark all 60KB in use for a GUI Thread.
224 * We should only do this inside MmGrowKernelStack. TODO!
226 for (i
= 0; i
< (StackSize
/ PAGE_SIZE
); i
++)
228 Status
= MmRequestPageMemoryConsumer(MC_NPPOOL
, TRUE
, &Page
[i
]);
231 /* Create a Virtual Mapping for it */
232 Status
= MmCreateVirtualMapping(NULL
,
236 StackSize
/ PAGE_SIZE
);
238 /* Check for success */
239 if (!NT_SUCCESS(Status
))
241 DPRINT1("Could not create Virtual Mapping for Kernel Stack\n");
245 /* Return the stack */
254 MmGrowKernelStack(PVOID StackPointer
)
256 PETHREAD Thread
= PsGetCurrentThread();
258 /* Make sure we have reserved space for our grow */
259 ASSERT(((PCHAR
)Thread
->Tcb
.StackBase
- (PCHAR
)Thread
->Tcb
.StackLimit
) <=
260 (KERNEL_LARGE_STACK_SIZE
+ PAGE_SIZE
));
263 * We'll give you three more pages.
264 * NOTE: See note in MmCreateKernelStack. These pages are already being reserved.
265 * It would be more efficient to only grow them (commit them) here.
267 Thread
->Tcb
.StackLimit
-= KERNEL_STACK_SIZE
;
270 return STATUS_SUCCESS
;
275 MmCreatePeb(PEPROCESS Process
)
278 LARGE_INTEGER SectionOffset
;
280 PVOID TableBase
= NULL
;
281 PIMAGE_NT_HEADERS NtHeaders
;
282 PIMAGE_LOAD_CONFIG_DIRECTORY ImageConfigData
;
284 KAFFINITY ProcessAffinityMask
= 0;
285 SectionOffset
.QuadPart
= (ULONGLONG
)0;
286 DPRINT("MmCreatePeb\n");
288 /* Allocate the PEB */
289 Peb
= MiCreatePebOrTeb(Process
,
290 (PVOID
)((ULONG_PTR
)MM_HIGHEST_VAD_ADDRESS
+ 1));
291 ASSERT(Peb
== (PVOID
)0x7FFDF000);
294 DPRINT("Mapping NLS\n");
295 Status
= MmMapViewOfSection(ExpNlsSectionPointer
,
305 if (!NT_SUCCESS(Status
))
307 DPRINT1("MmMapViewOfSection() failed (Status %lx)\n", Status
);
310 DPRINT("TableBase %p ViewSize %lx\n", TableBase
, ViewSize
);
312 /* Attach to Process */
313 KeAttachProcess(&Process
->Pcb
);
315 /* Initialize the PEB */
316 DPRINT("Allocated: %x\n", Peb
);
317 RtlZeroMemory(Peb
, sizeof(PEB
));
320 DPRINT("Setting up PEB\n");
321 Peb
->ImageBaseAddress
= Process
->SectionBaseAddress
;
322 Peb
->InheritedAddressSpace
= 0;
326 Peb
->AnsiCodePageData
= (PCHAR
)TableBase
+ ExpAnsiCodePageDataOffset
;
327 Peb
->OemCodePageData
= (PCHAR
)TableBase
+ ExpOemCodePageDataOffset
;
328 Peb
->UnicodeCaseTableData
= (PCHAR
)TableBase
+ ExpUnicodeCaseTableDataOffset
;
330 /* Default Version Data (could get changed below) */
331 Peb
->OSMajorVersion
= NtMajorVersion
;
332 Peb
->OSMinorVersion
= NtMinorVersion
;
333 Peb
->OSBuildNumber
= (USHORT
)(NtBuildNumber
& 0x3FFF);
334 Peb
->OSPlatformId
= 2; /* VER_PLATFORM_WIN32_NT */
335 Peb
->OSCSDVersion
= (USHORT
)CmNtCSDVersion
;
337 /* Heap and Debug Data */
338 Peb
->NumberOfProcessors
= KeNumberProcessors
;
339 Peb
->BeingDebugged
= (BOOLEAN
)(Process
->DebugPort
!= NULL
? TRUE
: FALSE
);
340 Peb
->NtGlobalFlag
= NtGlobalFlag
;
341 /*Peb->HeapSegmentReserve = MmHeapSegmentReserve;
342 Peb->HeapSegmentCommit = MmHeapSegmentCommit;
343 Peb->HeapDeCommitTotalFreeThreshold = MmHeapDeCommitTotalFreeThreshold;
344 Peb->HeapDeCommitFreeBlockThreshold = MmHeapDeCommitFreeBlockThreshold;*/
345 Peb
->NumberOfHeaps
= 0;
346 Peb
->MaximumNumberOfHeaps
= (PAGE_SIZE
- sizeof(PEB
)) / sizeof(PVOID
);
347 Peb
->ProcessHeaps
= (PVOID
*)Peb
+ 1;
350 if ((NtHeaders
= RtlImageNtHeader(Peb
->ImageBaseAddress
)))
352 /* Write subsystem data */
353 Peb
->ImageSubSystem
= NtHeaders
->OptionalHeader
.Subsystem
;
354 Peb
->ImageSubSystemMajorVersion
= NtHeaders
->OptionalHeader
.MajorSubsystemVersion
;
355 Peb
->ImageSubSystemMinorVersion
= NtHeaders
->OptionalHeader
.MinorSubsystemVersion
;
357 /* Write Version Data */
358 if (NtHeaders
->OptionalHeader
.Win32VersionValue
)
360 Peb
->OSMajorVersion
= NtHeaders
->OptionalHeader
.Win32VersionValue
& 0xFF;
361 Peb
->OSMinorVersion
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 8) & 0xFF;
362 Peb
->OSBuildNumber
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 16) & 0x3FFF;
364 /* Set the Platform ID */
365 Peb
->OSPlatformId
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 30) ^ 2;
368 /* Check if the image is not safe for SMP */
369 if (NtHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_UP_SYSTEM_ONLY
)
371 /* FIXME: Choose one randomly */
372 Peb
->ImageProcessAffinityMask
= 1;
376 /* Use affinity from Image Header */
377 Peb
->ImageProcessAffinityMask
= ProcessAffinityMask
;
382 /* Get the Image Config Data too */
383 ImageConfigData
= RtlImageDirectoryEntryToData(Peb
->ImageBaseAddress
,
385 IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
,
388 ProbeForRead(ImageConfigData
,
389 sizeof(IMAGE_LOAD_CONFIG_DIRECTORY
),
392 /* Process the image config data overrides if specfied. */
393 if (ImageConfigData
!= NULL
)
395 if (ImageConfigData
->CSDVersion
)
397 Peb
->OSCSDVersion
= ImageConfigData
->CSDVersion
;
399 if (ImageConfigData
->ProcessAffinityMask
)
401 ProcessAffinityMask
= ImageConfigData
->ProcessAffinityMask
;
407 Status
= _SEH_GetExceptionCode();
413 Peb
->SessionId
= Process
->Session
;
416 /* Detach from the Process */
419 DPRINT("MmCreatePeb: Peb created at %p\n", Peb
);
425 MmCreateTeb(PEPROCESS Process
,
427 PINITIAL_TEB InitialTeb
)
430 BOOLEAN Attached
= FALSE
;
432 /* Attach to the process */
433 DPRINT("MmCreateTeb\n");
434 if (Process
!= PsGetCurrentProcess())
436 /* Attach to Target */
437 KeAttachProcess(&Process
->Pcb
);
441 /* Allocate the TEB */
442 Teb
= MiCreatePebOrTeb(Process
,
443 (PVOID
)((ULONG_PTR
)MM_HIGHEST_VAD_ADDRESS
+ 1));
445 /* Initialize the PEB */
446 RtlZeroMemory(Teb
, sizeof(TEB
));
449 Teb
->Tib
.ExceptionList
= (PVOID
)0xFFFFFFFF;
450 Teb
->Tib
.Version
= 1;
451 Teb
->Tib
.Self
= (PNT_TIB
)Teb
;
454 Teb
->Cid
= *ClientId
;
455 Teb
->RealClientId
= *ClientId
;
456 Teb
->ProcessEnvironmentBlock
= Process
->Peb
;
457 Teb
->CurrentLocale
= PsDefaultThreadLocaleId
;
459 /* Store stack information from InitialTeb */
460 if(InitialTeb
!= NULL
)
462 Teb
->Tib
.StackBase
= InitialTeb
->StackBase
;
463 Teb
->Tib
.StackLimit
= InitialTeb
->StackLimit
;
464 Teb
->DeallocationStack
= InitialTeb
->AllocatedStackBase
;
467 /* Return TEB Address */
468 DPRINT("Allocated: %x\n", Teb
);
469 if (Attached
) KeDetachProcess();
475 MmCreateProcessAddressSpace(IN PEPROCESS Process
,
476 IN PROS_SECTION_OBJECT Section OPTIONAL
,
477 IN POBJECT_NAME_INFORMATION
*AuditName OPTIONAL
)
480 PMADDRESS_SPACE ProcessAddressSpace
= (PMADDRESS_SPACE
)&Process
->VadRoot
;
482 PMEMORY_AREA MemoryArea
;
483 PHYSICAL_ADDRESS BoundaryAddressMultiple
;
486 BoundaryAddressMultiple
.QuadPart
= 0;
488 /* Initialize the Addresss Space */
489 MmInitializeAddressSpace(Process
, ProcessAddressSpace
);
491 /* Acquire the Lock */
492 MmLockAddressSpace(ProcessAddressSpace
);
494 /* Protect the highest 64KB of the process address space */
495 BaseAddress
= (PVOID
)MmUserProbeAddress
;
496 Status
= MmCreateMemoryArea(ProcessAddressSpace
,
497 MEMORY_AREA_NO_ACCESS
,
504 BoundaryAddressMultiple
);
505 if (!NT_SUCCESS(Status
))
507 DPRINT1("Failed to protect last 64KB\n");
511 /* Protect the 60KB above the shared user page */
512 BaseAddress
= (char*)USER_SHARED_DATA
+ PAGE_SIZE
;
513 Status
= MmCreateMemoryArea(ProcessAddressSpace
,
514 MEMORY_AREA_NO_ACCESS
,
521 BoundaryAddressMultiple
);
522 if (!NT_SUCCESS(Status
))
524 DPRINT1("Failed to protect the memory above the shared user page\n");
528 /* Create the shared data page */
529 BaseAddress
= (PVOID
)USER_SHARED_DATA
;
530 Status
= MmCreateMemoryArea(ProcessAddressSpace
,
531 MEMORY_AREA_SHARED_DATA
,
538 BoundaryAddressMultiple
);
539 if (!NT_SUCCESS(Status
))
541 DPRINT1("Failed to create Shared User Data\n");
545 /* The process now has an address space */
546 Process
->HasAddressSpace
= TRUE
;
548 /* Check if there's a Section Object */
551 UNICODE_STRING FileName
;
556 /* Unlock the Address Space */
557 DPRINT("Unlocking\n");
558 MmUnlockAddressSpace(ProcessAddressSpace
);
560 DPRINT("Mapping process image. Section: %p, Process: %p, ImageBase: %p\n",
561 Section
, Process
, &ImageBase
);
562 Status
= MmMapViewOfSection(Section
,
572 if (!NT_SUCCESS(Status
))
574 DPRINT1("Failed to map process Image\n");
578 /* Save the pointer */
579 Process
->SectionBaseAddress
= ImageBase
;
581 /* Determine the image file name and save it to EPROCESS */
582 DPRINT("Getting Image name\n");
583 FileName
= Section
->FileObject
->FileName
;
584 szSrc
= (PWCHAR
)(FileName
.Buffer
+ FileName
.Length
);
585 while (szSrc
>= FileName
.Buffer
)
587 /* Make sure this isn't a backslash */
588 if (*--szSrc
== OBJ_NAME_PATH_SEPARATOR
)
590 /* If so, stop it here */
596 /* Otherwise, keep going */
601 /* Copy the to the process and truncate it to 15 characters if necessary */
602 szDest
= Process
->ImageFileName
;
603 lnFName
= min(lnFName
, sizeof(Process
->ImageFileName
) - 1);
604 while (lnFName
--) *szDest
++ = (UCHAR
)*szSrc
++;
605 *szDest
= UNICODE_NULL
;
607 /* Check if caller wants an audit name */
610 /* Setup the audit name */
611 SeInitializeProcessAuditName(Section
->FileObject
,
616 /* Return status to caller */
621 /* Unlock the Address Space */
622 DPRINT("Unlocking\n");
623 MmUnlockAddressSpace(ProcessAddressSpace
);
625 /* Return status to caller */
631 MmCleanProcessAddressSpace(IN PEPROCESS Process
)
633 /* FIXME: Add part of MmDeleteProcessAddressSpace here */
638 MmDeleteProcessAddressSpace(PEPROCESS Process
)
641 PMEMORY_AREA MemoryArea
;
643 DPRINT("MmDeleteProcessAddressSpace(Process %x (%s))\n", Process
,
644 Process
->ImageFileName
);
646 MmLockAddressSpace((PMADDRESS_SPACE
)&Process
->VadRoot
);
648 while ((MemoryArea
= ((PMADDRESS_SPACE
)&Process
->VadRoot
)->MemoryAreaRoot
) != NULL
)
650 switch (MemoryArea
->Type
)
652 case MEMORY_AREA_SECTION_VIEW
:
653 Address
= (PVOID
)MemoryArea
->StartingAddress
;
654 MmUnlockAddressSpace((PMADDRESS_SPACE
)&Process
->VadRoot
);
655 MmUnmapViewOfSection(Process
, Address
);
656 MmLockAddressSpace((PMADDRESS_SPACE
)&Process
->VadRoot
);
659 case MEMORY_AREA_VIRTUAL_MEMORY
:
660 case MEMORY_AREA_PEB_OR_TEB
:
661 MmFreeVirtualMemory(Process
, MemoryArea
);
664 case MEMORY_AREA_SHARED_DATA
:
665 case MEMORY_AREA_NO_ACCESS
:
666 MmFreeMemoryArea((PMADDRESS_SPACE
)&Process
->VadRoot
,
672 case MEMORY_AREA_MDL_MAPPING
:
673 KEBUGCHECK(PROCESS_HAS_LOCKED_PAGES
);
681 Mmi386ReleaseMmInfo(Process
);
683 MmUnlockAddressSpace((PMADDRESS_SPACE
)&Process
->VadRoot
);
684 MmDestroyAddressSpace((PMADDRESS_SPACE
)&Process
->VadRoot
);
686 DPRINT("Finished MmReleaseMmInfo()\n");
687 return(STATUS_SUCCESS
);