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 NtOSCSDVersion
;
19 extern ULONG NtGlobalFlag
;
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
= 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
)
185 PMEMORY_AREA StackArea
;
187 PHYSICAL_ADDRESS BoundaryAddressMultiple
;
188 ULONG StackSize
= GuiStack
? KERNEL_LARGE_STACK_SIZE
: KERNEL_STACK_SIZE
;
189 PFN_TYPE Page
[KERNEL_LARGE_STACK_SIZE
/ PAGE_SIZE
];
190 PVOID KernelStack
= NULL
;
193 /* Initialize the Boundary Address */
194 BoundaryAddressMultiple
.QuadPart
= 0;
196 /* Lock the Kernel Address Space */
197 MmLockAddressSpace(MmGetKernelAddressSpace());
199 /* Create a MAREA for the Kernel Stack */
200 Status
= MmCreateMemoryArea(MmGetKernelAddressSpace(),
201 MEMORY_AREA_KERNEL_STACK
,
208 BoundaryAddressMultiple
);
210 /* Unlock the Address Space */
211 MmUnlockAddressSpace(MmGetKernelAddressSpace());
213 /* Check for Success */
214 if (!NT_SUCCESS(Status
))
216 DPRINT1("Failed to create thread stack\n");
221 * Mark the Stack in use.
222 * Note: Currently we mark all 60KB in use for a GUI Thread.
223 * We should only do this inside MmGrowKernelStack. TODO!
225 for (i
= 0; i
< (StackSize
/ PAGE_SIZE
); i
++)
227 Status
= MmRequestPageMemoryConsumer(MC_NPPOOL
, TRUE
, &Page
[i
]);
230 /* Create a Virtual Mapping for it */
231 Status
= MmCreateVirtualMapping(NULL
,
235 StackSize
/ PAGE_SIZE
);
237 /* Check for success */
238 if (!NT_SUCCESS(Status
))
240 DPRINT1("Could not create Virtual Mapping for Kernel Stack\n");
244 /* Return the stack */
253 MmGrowKernelStack(PVOID StackPointer
)
255 PETHREAD Thread
= PsGetCurrentThread();
257 /* Make sure we have reserved space for our grow */
258 ASSERT(((PCHAR
)Thread
->Tcb
.StackBase
- (PCHAR
)Thread
->Tcb
.StackLimit
) <=
259 (KERNEL_LARGE_STACK_SIZE
+ PAGE_SIZE
));
262 * We'll give you three more pages.
263 * NOTE: See note in MmCreateKernelStack. These pages are already being reserved.
264 * It would be more efficient to only grow them (commit them) here.
266 Thread
->Tcb
.StackLimit
-= KERNEL_STACK_SIZE
;
269 return STATUS_SUCCESS
;
274 MmCreatePeb(PEPROCESS Process
)
277 LARGE_INTEGER SectionOffset
;
279 PVOID TableBase
= NULL
;
280 PIMAGE_NT_HEADERS NtHeaders
;
281 PIMAGE_LOAD_CONFIG_DIRECTORY ImageConfigData
;
283 KAFFINITY ProcessAffinityMask
= 0;
284 SectionOffset
.QuadPart
= (ULONGLONG
)0;
285 DPRINT("MmCreatePeb\n");
287 /* Allocate the PEB */
288 Peb
= MiCreatePebOrTeb(Process
,
289 (PVOID
)((ULONG_PTR
)MM_HIGHEST_VAD_ADDRESS
+ 1));
290 ASSERT(Peb
== (PVOID
)0x7FFDF000);
293 DPRINT("Mapping NLS\n");
294 Status
= MmMapViewOfSection(ExpNlsSectionPointer
,
304 if (!NT_SUCCESS(Status
))
306 DPRINT1("MmMapViewOfSection() failed (Status %lx)\n", Status
);
309 DPRINT("TableBase %p ViewSize %lx\n", TableBase
, ViewSize
);
311 /* Attach to Process */
312 KeAttachProcess(&Process
->Pcb
);
314 /* Initialize the PEB */
315 DPRINT("Allocated: %x\n", Peb
);
316 RtlZeroMemory(Peb
, sizeof(PEB
));
319 DPRINT("Setting up PEB\n");
320 Peb
->ImageBaseAddress
= Process
->SectionBaseAddress
;
321 Peb
->InheritedAddressSpace
= 0;
325 Peb
->AnsiCodePageData
= (PCHAR
)TableBase
+ ExpAnsiCodePageDataOffset
;
326 Peb
->OemCodePageData
= (PCHAR
)TableBase
+ ExpOemCodePageDataOffset
;
327 Peb
->UnicodeCaseTableData
= (PCHAR
)TableBase
+ ExpUnicodeCaseTableDataOffset
;
329 /* Default Version Data (could get changed below) */
330 Peb
->OSMajorVersion
= NtMajorVersion
;
331 Peb
->OSMinorVersion
= NtMinorVersion
;
332 Peb
->OSBuildNumber
= 2195;
333 Peb
->OSPlatformId
= 2; /* VER_PLATFORM_WIN32_NT */
334 Peb
->OSCSDVersion
= NtOSCSDVersion
;
336 /* Heap and Debug Data */
337 Peb
->NumberOfProcessors
= KeNumberProcessors
;
338 Peb
->BeingDebugged
= (BOOLEAN
)(Process
->DebugPort
!= NULL
? TRUE
: FALSE
);
339 Peb
->NtGlobalFlag
= NtGlobalFlag
;
340 /*Peb->HeapSegmentReserve = MmHeapSegmentReserve;
341 Peb->HeapSegmentCommit = MmHeapSegmentCommit;
342 Peb->HeapDeCommitTotalFreeThreshold = MmHeapDeCommitTotalFreeThreshold;
343 Peb->HeapDeCommitFreeBlockThreshold = MmHeapDeCommitFreeBlockThreshold;*/
344 Peb
->NumberOfHeaps
= 0;
345 Peb
->MaximumNumberOfHeaps
= (PAGE_SIZE
- sizeof(PEB
)) / sizeof(PVOID
);
346 Peb
->ProcessHeaps
= (PVOID
*)Peb
+ 1;
349 if ((NtHeaders
= RtlImageNtHeader(Peb
->ImageBaseAddress
)))
351 /* Write subsystem data */
352 Peb
->ImageSubSystem
= NtHeaders
->OptionalHeader
.Subsystem
;
353 Peb
->ImageSubSystemMajorVersion
= NtHeaders
->OptionalHeader
.MajorSubsystemVersion
;
354 Peb
->ImageSubSystemMinorVersion
= NtHeaders
->OptionalHeader
.MinorSubsystemVersion
;
356 /* Write Version Data */
357 if (NtHeaders
->OptionalHeader
.Win32VersionValue
)
359 Peb
->OSMajorVersion
= NtHeaders
->OptionalHeader
.Win32VersionValue
& 0xFF;
360 Peb
->OSMinorVersion
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 8) & 0xFF;
361 Peb
->OSBuildNumber
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 16) & 0x3FFF;
363 /* Set the Platform ID */
364 Peb
->OSPlatformId
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 30) ^ 2;
367 /* Check if the image is not safe for SMP */
368 if (NtHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_UP_SYSTEM_ONLY
)
370 /* FIXME: Choose one randomly */
371 Peb
->ImageProcessAffinityMask
= 1;
375 /* Use affinity from Image Header */
376 Peb
->ImageProcessAffinityMask
= ProcessAffinityMask
;
381 /* Get the Image Config Data too */
382 ImageConfigData
= RtlImageDirectoryEntryToData(Peb
->ImageBaseAddress
,
384 IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
,
387 ProbeForRead(ImageConfigData
,
388 sizeof(IMAGE_LOAD_CONFIG_DIRECTORY
),
391 /* Process the image config data overrides if specfied. */
392 if (ImageConfigData
!= NULL
)
394 if (ImageConfigData
->CSDVersion
)
396 Peb
->OSCSDVersion
= ImageConfigData
->CSDVersion
;
398 if (ImageConfigData
->ProcessAffinityMask
)
400 ProcessAffinityMask
= ImageConfigData
->ProcessAffinityMask
;
406 Status
= _SEH_GetExceptionCode();
412 Peb
->SessionId
= Process
->Session
;
415 /* Detach from the Process */
418 DPRINT("MmCreatePeb: Peb created at %p\n", Peb
);
424 MmCreateTeb(PEPROCESS Process
,
426 PINITIAL_TEB InitialTeb
)
429 BOOLEAN Attached
= FALSE
;
431 /* Attach to the process */
432 DPRINT("MmCreateTeb\n");
433 if (Process
!= PsGetCurrentProcess())
435 /* Attach to Target */
436 KeAttachProcess(&Process
->Pcb
);
440 /* Allocate the TEB */
441 Teb
= MiCreatePebOrTeb(Process
,
442 (PVOID
)((ULONG_PTR
)MM_HIGHEST_VAD_ADDRESS
+ 1));
444 /* Initialize the PEB */
445 RtlZeroMemory(Teb
, sizeof(TEB
));
448 Teb
->Tib
.ExceptionList
= (PVOID
)0xFFFFFFFF;
449 Teb
->Tib
.Version
= 1;
450 Teb
->Tib
.Self
= (PNT_TIB
)Teb
;
453 Teb
->Cid
= *ClientId
;
454 Teb
->RealClientId
= *ClientId
;
455 Teb
->ProcessEnvironmentBlock
= Process
->Peb
;
456 Teb
->CurrentLocale
= PsDefaultThreadLocaleId
;
458 /* Store stack information from InitialTeb */
459 if(InitialTeb
!= NULL
)
461 Teb
->Tib
.StackBase
= InitialTeb
->StackBase
;
462 Teb
->Tib
.StackLimit
= InitialTeb
->StackLimit
;
463 Teb
->DeallocationStack
= InitialTeb
->AllocatedStackBase
;
466 /* Return TEB Address */
467 DPRINT("Allocated: %x\n", Teb
);
468 if (Attached
) KeDetachProcess();
474 MmCreateProcessAddressSpace(IN PEPROCESS Process
,
475 IN PROS_SECTION_OBJECT Section OPTIONAL
,
476 IN POBJECT_NAME_INFORMATION
*AuditName OPTIONAL
)
479 PMADDRESS_SPACE ProcessAddressSpace
= (PMADDRESS_SPACE
)&Process
->VadRoot
;
481 PMEMORY_AREA MemoryArea
;
482 PHYSICAL_ADDRESS BoundaryAddressMultiple
;
485 BoundaryAddressMultiple
.QuadPart
= 0;
487 /* Initialize the Addresss Space */
488 MmInitializeAddressSpace(Process
, ProcessAddressSpace
);
490 /* Acquire the Lock */
491 MmLockAddressSpace(ProcessAddressSpace
);
493 /* Protect the highest 64KB of the process address space */
494 BaseAddress
= (PVOID
)MmUserProbeAddress
;
495 Status
= MmCreateMemoryArea(ProcessAddressSpace
,
496 MEMORY_AREA_NO_ACCESS
,
503 BoundaryAddressMultiple
);
504 if (!NT_SUCCESS(Status
))
506 DPRINT1("Failed to protect last 64KB\n");
510 /* Protect the 60KB above the shared user page */
511 BaseAddress
= (char*)USER_SHARED_DATA
+ PAGE_SIZE
;
512 Status
= MmCreateMemoryArea(ProcessAddressSpace
,
513 MEMORY_AREA_NO_ACCESS
,
520 BoundaryAddressMultiple
);
521 if (!NT_SUCCESS(Status
))
523 DPRINT1("Failed to protect the memory above the shared user page\n");
527 /* Create the shared data page */
528 BaseAddress
= (PVOID
)USER_SHARED_DATA
;
529 Status
= MmCreateMemoryArea(ProcessAddressSpace
,
530 MEMORY_AREA_SHARED_DATA
,
537 BoundaryAddressMultiple
);
538 if (!NT_SUCCESS(Status
))
540 DPRINT1("Failed to create Shared User Data\n");
544 /* The process now has an address space */
545 Process
->HasAddressSpace
= TRUE
;
547 /* Check if there's a Section Object */
550 UNICODE_STRING FileName
;
555 /* Unlock the Address Space */
556 DPRINT("Unlocking\n");
557 MmUnlockAddressSpace(ProcessAddressSpace
);
559 DPRINT("Mapping process image. Section: %p, Process: %p, ImageBase: %p\n",
560 Section
, Process
, &ImageBase
);
561 Status
= MmMapViewOfSection(Section
,
571 if (!NT_SUCCESS(Status
))
573 DPRINT1("Failed to map process Image\n");
577 /* Save the pointer */
578 Process
->SectionBaseAddress
= ImageBase
;
580 /* Determine the image file name and save it to EPROCESS */
581 DPRINT("Getting Image name\n");
582 FileName
= Section
->FileObject
->FileName
;
583 szSrc
= (PWCHAR
)(FileName
.Buffer
+ FileName
.Length
);
584 while (szSrc
>= FileName
.Buffer
)
586 /* Make sure this isn't a backslash */
587 if (*--szSrc
== OBJ_NAME_PATH_SEPARATOR
)
589 /* If so, stop it here */
595 /* Otherwise, keep going */
600 /* Copy the to the process and truncate it to 15 characters if necessary */
601 szDest
= Process
->ImageFileName
;
602 lnFName
= min(lnFName
, sizeof(Process
->ImageFileName
) - 1);
603 while (lnFName
--) *szDest
++ = (UCHAR
)*szSrc
++;
604 *szDest
= UNICODE_NULL
;
606 /* Check if caller wants an audit name */
609 /* Setup the audit name */
610 SeInitializeProcessAuditName(Section
->FileObject
,
615 /* Return status to caller */
620 /* Unlock the Address Space */
621 DPRINT("Unlocking\n");
622 MmUnlockAddressSpace(ProcessAddressSpace
);
624 /* Return status to caller */
630 MmCleanProcessAddressSpace(IN PEPROCESS Process
)
632 /* FIXME: Add part of MmDeleteProcessAddressSpace here */
637 MmDeleteProcessAddressSpace(PEPROCESS Process
)
640 PMEMORY_AREA MemoryArea
;
642 DPRINT("MmDeleteProcessAddressSpace(Process %x (%s))\n", Process
,
643 Process
->ImageFileName
);
645 MmLockAddressSpace((PMADDRESS_SPACE
)&Process
->VadRoot
);
647 while ((MemoryArea
= ((PMADDRESS_SPACE
)&Process
->VadRoot
)->MemoryAreaRoot
) != NULL
)
649 switch (MemoryArea
->Type
)
651 case MEMORY_AREA_SECTION_VIEW
:
652 Address
= (PVOID
)MemoryArea
->StartingAddress
;
653 MmUnlockAddressSpace((PMADDRESS_SPACE
)&Process
->VadRoot
);
654 MmUnmapViewOfSection(Process
, Address
);
655 MmLockAddressSpace((PMADDRESS_SPACE
)&Process
->VadRoot
);
658 case MEMORY_AREA_VIRTUAL_MEMORY
:
659 case MEMORY_AREA_PEB_OR_TEB
:
660 MmFreeVirtualMemory(Process
, MemoryArea
);
663 case MEMORY_AREA_SHARED_DATA
:
664 case MEMORY_AREA_NO_ACCESS
:
665 MmFreeMemoryArea((PMADDRESS_SPACE
)&Process
->VadRoot
,
671 case MEMORY_AREA_MDL_MAPPING
:
672 KEBUGCHECK(PROCESS_HAS_LOCKED_PAGES
);
680 Mmi386ReleaseMmInfo(Process
);
682 MmUnlockAddressSpace((PMADDRESS_SPACE
)&Process
->VadRoot
);
683 MmDestroyAddressSpace((PMADDRESS_SPACE
)&Process
->VadRoot
);
685 DPRINT("Finished MmReleaseMmInfo()\n");
686 return(STATUS_SUCCESS
);