- NDK 0.98, now with versionned headers. Too many changes to list, see the TinyKRNL...
[reactos.git] / reactos / ntoskrnl / mm / process.c
1 /*
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
6 *
7 * PROGRAMMERS: Alex Ionescu (alex@relsoft.net)
8 */
9
10 /* INCLUDES *****************************************************************/
11
12 #include <ntoskrnl.h>
13 #define NDEBUG
14 #include <internal/debug.h>
15
16 extern ULONG NtMajorVersion;
17 extern ULONG NtMinorVersion;
18 extern ULONG NtOSCSDVersion;
19 extern ULONG NtGlobalFlag;
20
21 #define MM_HIGHEST_VAD_ADDRESS \
22 (PVOID)((ULONG_PTR)MM_HIGHEST_USER_ADDRESS - (16 * PAGE_SIZE))
23
24 /* FUNCTIONS *****************************************************************/
25
26 PVOID
27 STDCALL
28 MiCreatePebOrTeb(PROS_EPROCESS Process,
29 PVOID BaseAddress)
30 {
31 NTSTATUS Status;
32 PMADDRESS_SPACE ProcessAddressSpace = &Process->AddressSpace;
33 PMEMORY_AREA MemoryArea;
34 PHYSICAL_ADDRESS BoundaryAddressMultiple;
35 PVOID AllocatedBase = BaseAddress;
36 BoundaryAddressMultiple.QuadPart = 0;
37
38 /* Acquire the Lock */
39 MmLockAddressSpace(ProcessAddressSpace);
40
41 /*
42 * Create a Peb or Teb.
43 * Loop until it works, decreasing by PAGE_SIZE each time. The logic here
44 * is that a PEB allocation should never fail since the address is free,
45 * while TEB allocation can fail, and we should simply try the address
46 * below. Is there a nicer way of doing this automagically? (ie: findning)
47 * a gap region? -- Alex
48 */
49 do {
50 DPRINT("Trying to allocate: %x\n", AllocatedBase);
51 Status = MmCreateMemoryArea(ProcessAddressSpace,
52 MEMORY_AREA_PEB_OR_TEB,
53 &AllocatedBase,
54 PAGE_SIZE,
55 PAGE_READWRITE,
56 &MemoryArea,
57 TRUE,
58 0,
59 BoundaryAddressMultiple);
60 AllocatedBase = RVA(AllocatedBase, -PAGE_SIZE);
61 } while (Status != STATUS_SUCCESS);
62
63 /* Initialize the Region */
64 MmInitializeRegion(&MemoryArea->Data.VirtualMemoryData.RegionListHead,
65 PAGE_SIZE,
66 MEM_COMMIT,
67 PAGE_READWRITE);
68
69 /* Reserve the pages */
70 MmReserveSwapPages(PAGE_SIZE);
71
72 /* Unlock Address Space */
73 DPRINT("Returning\n");
74 MmUnlockAddressSpace(ProcessAddressSpace);
75 return RVA(AllocatedBase, PAGE_SIZE);
76 }
77
78 VOID
79 MiFreeStackPage(PVOID Context,
80 MEMORY_AREA* MemoryArea,
81 PVOID Address,
82 PFN_TYPE Page,
83 SWAPENTRY SwapEntry,
84 BOOLEAN Dirty)
85 {
86 ASSERT(SwapEntry == 0);
87 if (Page) MmReleasePageMemoryConsumer(MC_NPPOOL, Page);
88 }
89
90 VOID
91 STDCALL
92 MmDeleteKernelStack(PVOID Stack,
93 BOOLEAN GuiStack)
94 {
95 /* Lock the Address Space */
96 MmLockAddressSpace(MmGetKernelAddressSpace());
97
98 /* Delete the Stack */
99 MmFreeMemoryAreaByPtr(MmGetKernelAddressSpace(),
100 Stack,
101 MiFreeStackPage,
102 NULL);
103
104 /* Unlock the Address Space */
105 MmUnlockAddressSpace(MmGetKernelAddressSpace());
106 }
107
108 VOID
109 STDCALL
110 MmDeleteTeb(PROS_EPROCESS Process,
111 PTEB Teb)
112 {
113 PMADDRESS_SPACE ProcessAddressSpace = &Process->AddressSpace;
114 PMEMORY_AREA MemoryArea;
115
116 /* Lock the Address Space */
117 MmLockAddressSpace(ProcessAddressSpace);
118
119 MemoryArea = MmLocateMemoryAreaByAddress(ProcessAddressSpace, (PVOID)Teb);
120 if (MemoryArea)
121 {
122 /* Delete the Teb */
123 MmFreeVirtualMemory(Process, MemoryArea);
124 }
125
126 /* Unlock the Address Space */
127 MmUnlockAddressSpace(ProcessAddressSpace);
128 }
129
130 PVOID
131 STDCALL
132 MmCreateKernelStack(BOOLEAN GuiStack)
133 {
134 PMEMORY_AREA StackArea;
135 ULONG i;
136 PHYSICAL_ADDRESS BoundaryAddressMultiple;
137 ULONG StackSize = GuiStack ? KERNEL_LARGE_STACK_SIZE : KERNEL_STACK_SIZE;
138 PFN_TYPE Page[KERNEL_LARGE_STACK_SIZE / PAGE_SIZE];
139 PVOID KernelStack = NULL;
140 NTSTATUS Status;
141
142 /* Initialize the Boundary Address */
143 BoundaryAddressMultiple.QuadPart = 0;
144
145 /* Lock the Kernel Address Space */
146 MmLockAddressSpace(MmGetKernelAddressSpace());
147
148 /* Create a MAREA for the Kernel Stack */
149 Status = MmCreateMemoryArea(MmGetKernelAddressSpace(),
150 MEMORY_AREA_KERNEL_STACK,
151 &KernelStack,
152 StackSize,
153 PAGE_READWRITE,
154 &StackArea,
155 FALSE,
156 0,
157 BoundaryAddressMultiple);
158
159 /* Unlock the Address Space */
160 MmUnlockAddressSpace(MmGetKernelAddressSpace());
161
162 /* Check for Success */
163 if (!NT_SUCCESS(Status))
164 {
165 DPRINT1("Failed to create thread stack\n");
166 KEBUGCHECK(0);
167 }
168
169 /*
170 * Mark the Stack in use.
171 * Note: Currently we mark all 60KB in use for a GUI Thread.
172 * We should only do this inside MmGrowKernelStack. TODO!
173 */
174 for (i = 0; i < (StackSize / PAGE_SIZE); i++)
175 {
176 Status = MmRequestPageMemoryConsumer(MC_NPPOOL, TRUE, &Page[i]);
177 }
178
179 /* Create a Virtual Mapping for it */
180 Status = MmCreateVirtualMapping(NULL,
181 KernelStack,
182 PAGE_READWRITE,
183 Page,
184 StackSize / PAGE_SIZE);
185
186 /* Check for success */
187 if (!NT_SUCCESS(Status))
188 {
189 DPRINT1("Could not create Virtual Mapping for Kernel Stack\n");
190 KEBUGCHECK(0);
191 }
192
193 /* Return the stack */
194 return KernelStack;
195 }
196
197 /*
198 * @implemented
199 */
200 NTSTATUS
201 STDCALL
202 MmGrowKernelStack(PVOID StackPointer)
203 {
204 PETHREAD Thread = PsGetCurrentThread();
205
206 /* Make sure we have reserved space for our grow */
207 ASSERT(((PCHAR)Thread->Tcb.StackBase - (PCHAR)Thread->Tcb.StackLimit) <=
208 (KERNEL_LARGE_STACK_SIZE + PAGE_SIZE));
209
210 /*
211 * We'll give you three more pages.
212 * NOTE: See note in MmCreateKernelStack. These pages are already being reserved.
213 * It would be more efficient to only grow them (commit them) here.
214 */
215 Thread->Tcb.StackLimit -= KERNEL_STACK_SIZE;
216
217 /* Return success */
218 return STATUS_SUCCESS;
219 }
220
221 NTSTATUS
222 STDCALL
223 MmCreatePeb(PROS_EPROCESS Process)
224 {
225 PPEB Peb = NULL;
226 LARGE_INTEGER SectionOffset;
227 SIZE_T ViewSize = 0;
228 PVOID TableBase = NULL;
229 PIMAGE_NT_HEADERS NtHeaders;
230 PIMAGE_LOAD_CONFIG_DIRECTORY ImageConfigData;
231 NTSTATUS Status;
232 KAFFINITY ProcessAffinityMask = 0;
233 SectionOffset.QuadPart = (ULONGLONG)0;
234 DPRINT("MmCreatePeb\n");
235
236 /* Allocate the PEB */
237 Peb = MiCreatePebOrTeb(Process,
238 (PVOID)((ULONG_PTR)MM_HIGHEST_VAD_ADDRESS + 1));
239 ASSERT(Peb == (PVOID)0x7FFDF000);
240
241 /* Map NLS Tables */
242 DPRINT("Mapping NLS\n");
243 Status = MmMapViewOfSection(NlsSectionObject,
244 (PEPROCESS)Process,
245 &TableBase,
246 0,
247 0,
248 &SectionOffset,
249 &ViewSize,
250 ViewShare,
251 MEM_TOP_DOWN,
252 PAGE_READONLY);
253 if (!NT_SUCCESS(Status))
254 {
255 DPRINT1("MmMapViewOfSection() failed (Status %lx)\n", Status);
256 return(Status);
257 }
258 DPRINT("TableBase %p ViewSize %lx\n", TableBase, ViewSize);
259
260 /* Attach to Process */
261 KeAttachProcess(&Process->Pcb);
262
263 /* Initialize the PEB */
264 DPRINT("Allocated: %x\n", Peb);
265 RtlZeroMemory(Peb, sizeof(PEB));
266
267 /* Set up data */
268 DPRINT("Setting up PEB\n");
269 Peb->ImageBaseAddress = Process->SectionBaseAddress;
270 Peb->InheritedAddressSpace = 0;
271 Peb->Mutant = NULL;
272
273 /* NLS */
274 Peb->AnsiCodePageData = (char*)TableBase + NlsAnsiTableOffset;
275 Peb->OemCodePageData = (char*)TableBase + NlsOemTableOffset;
276 Peb->UnicodeCaseTableData = (char*)TableBase + NlsUnicodeTableOffset;
277
278 /* Default Version Data (could get changed below) */
279 Peb->OSMajorVersion = NtMajorVersion;
280 Peb->OSMinorVersion = NtMinorVersion;
281 Peb->OSBuildNumber = 2195;
282 Peb->OSPlatformId = 2; /* VER_PLATFORM_WIN32_NT */
283 Peb->OSCSDVersion = NtOSCSDVersion;
284
285 /* Heap and Debug Data */
286 Peb->NumberOfProcessors = KeNumberProcessors;
287 Peb->BeingDebugged = (BOOLEAN)(Process->DebugPort != NULL ? TRUE : FALSE);
288 Peb->NtGlobalFlag = NtGlobalFlag;
289 /*Peb->HeapSegmentReserve = MmHeapSegmentReserve;
290 Peb->HeapSegmentCommit = MmHeapSegmentCommit;
291 Peb->HeapDeCommitTotalFreeThreshold = MmHeapDeCommitTotalFreeThreshold;
292 Peb->HeapDeCommitFreeBlockThreshold = MmHeapDeCommitFreeBlockThreshold;*/
293 Peb->NumberOfHeaps = 0;
294 Peb->MaximumNumberOfHeaps = (PAGE_SIZE - sizeof(PEB)) / sizeof(PVOID);
295 Peb->ProcessHeaps = (PVOID*)Peb + 1;
296
297 /* Image Data */
298 if ((NtHeaders = RtlImageNtHeader(Peb->ImageBaseAddress)))
299 {
300 /* Get the Image Config Data too */
301 ImageConfigData = RtlImageDirectoryEntryToData(Peb->ImageBaseAddress,
302 TRUE,
303 IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG,
304 &ViewSize);
305
306 /* Write subsystem data */
307 Peb->ImageSubSystem = NtHeaders->OptionalHeader.Subsystem;
308 Peb->ImageSubSystemMajorVersion = NtHeaders->OptionalHeader.MajorSubsystemVersion;
309 Peb->ImageSubSystemMinorVersion = NtHeaders->OptionalHeader.MinorSubsystemVersion;
310
311 /* Write Version Data */
312 if (NtHeaders->OptionalHeader.Win32VersionValue)
313 {
314 Peb->OSMajorVersion = NtHeaders->OptionalHeader.Win32VersionValue & 0xFF;
315 Peb->OSMinorVersion = (NtHeaders->OptionalHeader.Win32VersionValue >> 8) & 0xFF;
316 Peb->OSBuildNumber = (NtHeaders->OptionalHeader.Win32VersionValue >> 16) & 0x3FFF;
317
318 /* Lie about the version if requested */
319 if (ImageConfigData && ImageConfigData->CSDVersion)
320 {
321 Peb->OSCSDVersion = ImageConfigData->CSDVersion;
322 }
323
324 /* Set the Platform ID */
325 Peb->OSPlatformId = (NtHeaders->OptionalHeader.Win32VersionValue >> 30) ^ 2;
326 }
327
328 /* Check for affinity override */
329 if (ImageConfigData && ImageConfigData->ProcessAffinityMask)
330 {
331 ProcessAffinityMask = ImageConfigData->ProcessAffinityMask;
332 }
333
334 /* Check if the image is not safe for SMP */
335 if (NtHeaders->FileHeader.Characteristics & IMAGE_FILE_UP_SYSTEM_ONLY)
336 {
337 /* FIXME: Choose one randomly */
338 Peb->ImageProcessAffinityMask = 1;
339 }
340 else
341 {
342 /* Use affinity from Image Header */
343 Peb->ImageProcessAffinityMask = ProcessAffinityMask;
344 }
345 }
346
347 /* Misc data */
348 Peb->SessionId = Process->Session;
349 Process->Peb = Peb;
350
351 /* Detach from the Process */
352 KeDetachProcess();
353
354 DPRINT("MmCreatePeb: Peb created at %p\n", Peb);
355 return STATUS_SUCCESS;
356 }
357
358 PTEB
359 STDCALL
360 MmCreateTeb(PROS_EPROCESS Process,
361 PCLIENT_ID ClientId,
362 PINITIAL_TEB InitialTeb)
363 {
364 PTEB Teb;
365 BOOLEAN Attached = FALSE;
366
367 /* Attach to the process */
368 DPRINT("MmCreateTeb\n");
369 if (Process != (PROS_EPROCESS)PsGetCurrentProcess())
370 {
371 /* Attach to Target */
372 KeAttachProcess(&Process->Pcb);
373 Attached = TRUE;
374 }
375
376 /* Allocate the TEB */
377 Teb = MiCreatePebOrTeb(Process,
378 (PVOID)((ULONG_PTR)MM_HIGHEST_VAD_ADDRESS + 1));
379
380 /* Initialize the PEB */
381 RtlZeroMemory(Teb, sizeof(TEB));
382
383 /* Set TIB Data */
384 Teb->Tib.ExceptionList = (PVOID)0xFFFFFFFF;
385 Teb->Tib.Version = 1;
386 Teb->Tib.Self = (PNT_TIB)Teb;
387
388 /* Set TEB Data */
389 Teb->Cid = *ClientId;
390 Teb->RealClientId = *ClientId;
391 Teb->ProcessEnvironmentBlock = Process->Peb;
392 Teb->CurrentLocale = PsDefaultThreadLocaleId;
393
394 /* Store stack information from InitialTeb */
395 if(InitialTeb != NULL)
396 {
397 Teb->Tib.StackBase = InitialTeb->StackBase;
398 Teb->Tib.StackLimit = InitialTeb->StackLimit;
399 Teb->DeallocationStack = InitialTeb->AllocatedStackBase;
400 }
401
402 /* Return TEB Address */
403 DPRINT("Allocated: %x\n", Teb);
404 if (Attached) KeDetachProcess();
405 return Teb;
406 }
407
408 NTSTATUS
409 STDCALL
410 MmCreateProcessAddressSpace(IN PROS_EPROCESS Process,
411 IN PROS_SECTION_OBJECT Section OPTIONAL)
412 {
413 NTSTATUS Status;
414 PMADDRESS_SPACE ProcessAddressSpace = &Process->AddressSpace;
415 PVOID BaseAddress;
416 PMEMORY_AREA MemoryArea;
417 PHYSICAL_ADDRESS BoundaryAddressMultiple;
418 SIZE_T ViewSize = 0;
419 PVOID ImageBase = 0;
420 BoundaryAddressMultiple.QuadPart = 0;
421
422 /* Initialize the Addresss Space */
423 MmInitializeAddressSpace(Process, ProcessAddressSpace);
424
425 /* Acquire the Lock */
426 MmLockAddressSpace(ProcessAddressSpace);
427
428 /* Protect the highest 64KB of the process address space */
429 BaseAddress = (PVOID)MmUserProbeAddress;
430 Status = MmCreateMemoryArea(ProcessAddressSpace,
431 MEMORY_AREA_NO_ACCESS,
432 &BaseAddress,
433 0x10000,
434 PAGE_NOACCESS,
435 &MemoryArea,
436 FALSE,
437 0,
438 BoundaryAddressMultiple);
439 if (!NT_SUCCESS(Status))
440 {
441 DPRINT1("Failed to protect last 64KB\n");
442 goto exit;
443 }
444
445 /* Protect the 60KB above the shared user page */
446 BaseAddress = (char*)USER_SHARED_DATA + PAGE_SIZE;
447 Status = MmCreateMemoryArea(ProcessAddressSpace,
448 MEMORY_AREA_NO_ACCESS,
449 &BaseAddress,
450 0x10000 - PAGE_SIZE,
451 PAGE_NOACCESS,
452 &MemoryArea,
453 FALSE,
454 0,
455 BoundaryAddressMultiple);
456 if (!NT_SUCCESS(Status))
457 {
458 DPRINT1("Failed to protect the memory above the shared user page\n");
459 goto exit;
460 }
461
462 /* Create the shared data page */
463 BaseAddress = (PVOID)USER_SHARED_DATA;
464 Status = MmCreateMemoryArea(ProcessAddressSpace,
465 MEMORY_AREA_SHARED_DATA,
466 &BaseAddress,
467 PAGE_SIZE,
468 PAGE_EXECUTE_READ,
469 &MemoryArea,
470 FALSE,
471 0,
472 BoundaryAddressMultiple);
473 if (!NT_SUCCESS(Status))
474 {
475 DPRINT1("Failed to create Shared User Data\n");
476 goto exit;
477 }
478
479 /* Check if there's a Section Object */
480 if (Section)
481 {
482 UNICODE_STRING FileName;
483 PWCHAR szSrc;
484 PCHAR szDest;
485 USHORT lnFName = 0;
486
487 /* Unlock the Address Space */
488 DPRINT("Unlocking\n");
489 MmUnlockAddressSpace(ProcessAddressSpace);
490
491 DPRINT("Mapping process image. Section: %p, Process: %p, ImageBase: %p\n",
492 Section, Process, &ImageBase);
493 Status = MmMapViewOfSection(Section,
494 (PEPROCESS)Process,
495 (PVOID*)&ImageBase,
496 0,
497 0,
498 NULL,
499 &ViewSize,
500 0,
501 MEM_COMMIT,
502 PAGE_READWRITE);
503 if (!NT_SUCCESS(Status))
504 {
505 DPRINT1("Failed to map process Image\n");
506 return Status;
507 }
508
509 /* Save the pointer */
510 Process->SectionBaseAddress = ImageBase;
511
512 /* Determine the image file name and save it to EPROCESS */
513 DPRINT("Getting Image name\n");
514 FileName = Section->FileObject->FileName;
515 szSrc = (PWCHAR)(FileName.Buffer + (FileName.Length / sizeof(WCHAR)) - 1);
516
517 while(szSrc >= FileName.Buffer)
518 {
519 if(*szSrc == L'\\')
520 {
521 szSrc++;
522 break;
523 }
524 else
525 {
526 szSrc--;
527 lnFName++;
528 }
529 }
530
531 /* Copy the to the process and truncate it to 15 characters if necessary */
532 DPRINT("Copying and truncating\n");
533 szDest = Process->ImageFileName;
534 lnFName = min(lnFName, sizeof(Process->ImageFileName) - 1);
535 while(lnFName-- > 0) *(szDest++) = (UCHAR)*(szSrc++);
536
537 /* Return status to caller */
538 return Status;
539 }
540
541 exit:
542 /* Unlock the Address Space */
543 DPRINT("Unlocking\n");
544 MmUnlockAddressSpace(ProcessAddressSpace);
545
546 /* Return status to caller */
547 return Status;
548 }