forked from reactos/reactos
/
process.c
1617 lines (1428 loc) · 44.4 KB
/
process.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* PROJECT: ReactOS Kernel
* LICENSE: GPL - See COPYING in the top level directory
* FILE: ntoskrnl/ps/process.c
* PURPOSE: Process Manager: Process Management
* PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
* Thomas Weidenmueller (w3seek@reactos.org
*/
/* INCLUDES ******************************************************************/
#include <ntoskrnl.h>
#define NDEBUG
#include <debug.h>
/* GLOBALS *******************************************************************/
extern ULONG PsMinimumWorkingSet, PsMaximumWorkingSet;
POBJECT_TYPE PsProcessType = NULL;
LIST_ENTRY PsActiveProcessHead;
KGUARDED_MUTEX PspActiveProcessMutex;
LARGE_INTEGER ShortPsLockDelay;
ULONG PsRawPrioritySeparation;
ULONG PsPrioritySeparation;
CHAR PspForegroundQuantum[3];
/* Fixed quantum table */
CHAR PspFixedQuantums[6] =
{
/* Short quantums */
3 * 6, /* Level 1 */
3 * 6, /* Level 2 */
3 * 6, /* Level 3 */
/* Long quantums */
6 * 6, /* Level 1 */
6 * 6, /* Level 2 */
6 * 6 /* Level 3 */
};
/* Variable quantum table */
CHAR PspVariableQuantums[6] =
{
/* Short quantums */
1 * 6, /* Level 1 */
2 * 6, /* Level 2 */
3 * 6, /* Level 3 */
/* Long quantums */
2 * 6, /* Level 1 */
4 * 6, /* Level 2 */
6 * 6 /* Level 3 */
};
/* Priority table */
KPRIORITY PspPriorityTable[PROCESS_PRIORITY_CLASS_ABOVE_NORMAL + 1] =
{
8,
4,
8,
13,
24,
6,
10
};
/* PRIVATE FUNCTIONS *********************************************************/
PETHREAD
NTAPI
PsGetNextProcessThread(IN PEPROCESS Process,
IN PETHREAD Thread OPTIONAL)
{
PETHREAD FoundThread = NULL;
PLIST_ENTRY ListHead, Entry;
PAGED_CODE();
PSTRACE(PS_PROCESS_DEBUG,
"Process: %p Thread: %p\n", Process, Thread);
/* Lock the process */
KeEnterCriticalRegion();
ExAcquirePushLockShared(&Process->ProcessLock);
/* Check if we're already starting somewhere */
if (Thread)
{
/* Start where we left off */
Entry = Thread->ThreadListEntry.Flink;
}
else
{
/* Start at the beginning */
Entry = Process->ThreadListHead.Flink;
}
/* Set the list head and start looping */
ListHead = &Process->ThreadListHead;
while (ListHead != Entry)
{
/* Get the Thread */
FoundThread = CONTAINING_RECORD(Entry, ETHREAD, ThreadListEntry);
/* Safe reference the thread */
if (ObReferenceObjectSafe(FoundThread)) break;
/* Nothing found, keep looping */
FoundThread = NULL;
Entry = Entry->Flink;
}
/* Unlock the process */
ExReleasePushLockShared(&Process->ProcessLock);
KeLeaveCriticalRegion();
/* Check if we had a starting thread, and dereference it */
if (Thread) ObDereferenceObject(Thread);
/* Return what we found */
return FoundThread;
}
PEPROCESS
NTAPI
PsGetNextProcess(IN PEPROCESS OldProcess)
{
PLIST_ENTRY Entry;
PEPROCESS FoundProcess = NULL;
PAGED_CODE();
PSTRACE(PS_PROCESS_DEBUG, "Process: %p\n", OldProcess);
/* Acquire the Active Process Lock */
KeAcquireGuardedMutex(&PspActiveProcessMutex);
/* Check if we're already starting somewhere */
if (OldProcess)
{
/* Start where we left off */
Entry = OldProcess->ActiveProcessLinks.Flink;
}
else
{
/* Start at the beginning */
Entry = PsActiveProcessHead.Flink;
}
/* Loop the process list */
while (Entry != &PsActiveProcessHead)
{
/* Get the process */
FoundProcess = CONTAINING_RECORD(Entry, EPROCESS, ActiveProcessLinks);
/* Reference the process */
if (ObReferenceObjectSafe(FoundProcess)) break;
/* Nothing found, keep trying */
FoundProcess = NULL;
Entry = Entry->Flink;
}
/* Release the lock */
KeReleaseGuardedMutex(&PspActiveProcessMutex);
/* Dereference the Process we had referenced earlier */
if (OldProcess) ObDereferenceObject(OldProcess);
return FoundProcess;
}
KPRIORITY
NTAPI
PspComputeQuantumAndPriority(IN PEPROCESS Process,
IN PSPROCESSPRIORITYMODE Mode,
OUT PUCHAR Quantum)
{
ULONG i;
UCHAR LocalQuantum, MemoryPriority;
PAGED_CODE();
PSTRACE(PS_PROCESS_DEBUG, "Process: %p Mode: %lx\n", Process, Mode);
/* Check if this is a foreground process */
if (Mode == PsProcessPriorityForeground)
{
/* Set the memory priority and use priority separation */
MemoryPriority = MEMORY_PRIORITY_FOREGROUND;
i = PsPrioritySeparation;
}
else
{
/* Set the background memory priority and no separation */
MemoryPriority = MEMORY_PRIORITY_BACKGROUND;
i = 0;
}
/* Make sure that the process mode isn't spinning */
if (Mode != PsProcessPrioritySpinning)
{
/* Set the priority */
MmSetMemoryPriorityProcess(Process, MemoryPriority);
}
/* Make sure that the process isn't idle */
if (Process->PriorityClass != PROCESS_PRIORITY_CLASS_IDLE)
{
/* Does the process have a job? */
if ((Process->Job) && (PspUseJobSchedulingClasses))
{
/* Use job quantum */
LocalQuantum = PspJobSchedulingClasses[Process->Job->
SchedulingClass];
}
else
{
/* Use calculated quantum */
LocalQuantum = PspForegroundQuantum[i];
}
}
else
{
/* Process is idle, use default quantum */
LocalQuantum = 6;
}
/* Return quantum to caller */
*Quantum = LocalQuantum;
/* Return priority */
return PspPriorityTable[Process->PriorityClass];
}
VOID
NTAPI
PsChangeQuantumTable(IN BOOLEAN Immediate,
IN ULONG PrioritySeparation)
{
PEPROCESS Process = NULL;
ULONG i;
UCHAR Quantum;
PCHAR QuantumTable;
PAGED_CODE();
PSTRACE(PS_PROCESS_DEBUG,
"%lx PrioritySeparation: %lx\n", Immediate, PrioritySeparation);
/* Write the current priority separation */
PsPrioritySeparation = PspPrioritySeparationFromMask(PrioritySeparation);
/* Normalize it if it was too high */
if (PsPrioritySeparation == 3) PsPrioritySeparation = 2;
/* Get the quantum table to use */
if (PspQuantumTypeFromMask(PrioritySeparation) == PSP_VARIABLE_QUANTUMS)
{
/* Use a variable table */
QuantumTable = PspVariableQuantums;
}
else if (PspQuantumTypeFromMask(PrioritySeparation) == PSP_FIXED_QUANTUMS)
{
/* Use fixed table */
QuantumTable = PspFixedQuantums;
}
else
{
/* Use default for the type of system we're on */
QuantumTable = MmIsThisAnNtAsSystem() ? PspFixedQuantums : PspVariableQuantums;
}
/* Now check if we should use long or short */
if (PspQuantumLengthFromMask(PrioritySeparation) == PSP_LONG_QUANTUMS)
{
/* Use long quantums */
QuantumTable += 3;
}
else if (PspQuantumLengthFromMask(PrioritySeparation) == PSP_SHORT_QUANTUMS)
{
/* Keep existing table */
NOTHING;
}
else
{
/* Use default for the type of system we're on */
QuantumTable += MmIsThisAnNtAsSystem() ? 3 : 0;
}
/* Check if we're using long fixed quantums */
if (QuantumTable == &PspFixedQuantums[3])
{
/* Use Job scheduling classes */
PspUseJobSchedulingClasses = TRUE;
}
else
{
/* Otherwise, we don't */
PspUseJobSchedulingClasses = FALSE;
}
/* Copy the selected table into the Foreground Quantum table */
RtlCopyMemory(PspForegroundQuantum,
QuantumTable,
sizeof(PspForegroundQuantum));
/* Check if we should apply these changes real-time */
if (Immediate)
{
/* We are...loop every process */
Process = PsGetNextProcess(Process);
while (Process)
{
/* Use the priority separation if this is a foreground process */
i = (Process->Vm.Flags.MemoryPriority ==
MEMORY_PRIORITY_BACKGROUND) ?
0: PsPrioritySeparation;
/* Make sure that the process isn't idle */
if (Process->PriorityClass != PROCESS_PRIORITY_CLASS_IDLE)
{
/* Does the process have a job? */
if ((Process->Job) && (PspUseJobSchedulingClasses))
{
/* Use job quantum */
Quantum = PspJobSchedulingClasses[Process->Job->SchedulingClass];
}
else
{
/* Use calculated quantum */
Quantum = PspForegroundQuantum[i];
}
}
else
{
/* Process is idle, use default quantum */
Quantum = 6;
}
/* Now set the quantum */
KeSetQuantumProcess(&Process->Pcb, Quantum);
/* Get the next process */
Process = PsGetNextProcess(Process);
}
}
}
NTSTATUS
NTAPI
PspCreateProcess(OUT PHANDLE ProcessHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
IN HANDLE ParentProcess OPTIONAL,
IN ULONG Flags,
IN HANDLE SectionHandle OPTIONAL,
IN HANDLE DebugPort OPTIONAL,
IN HANDLE ExceptionPort OPTIONAL,
IN BOOLEAN InJob)
{
HANDLE hProcess;
PEPROCESS Process, Parent;
PVOID ExceptionPortObject;
PDEBUG_OBJECT DebugObject;
PSECTION_OBJECT SectionObject;
NTSTATUS Status, AccessStatus;
ULONG_PTR DirectoryTableBase[2] = {0,0};
KAFFINITY Affinity;
HANDLE_TABLE_ENTRY CidEntry;
PETHREAD CurrentThread = PsGetCurrentThread();
KPROCESSOR_MODE PreviousMode = ExGetPreviousMode();
PEPROCESS CurrentProcess = PsGetCurrentProcess();
ULONG MinWs, MaxWs;
ACCESS_STATE LocalAccessState;
PACCESS_STATE AccessState = &LocalAccessState;
AUX_ACCESS_DATA AuxData;
UCHAR Quantum;
BOOLEAN Result, SdAllocated;
PSECURITY_DESCRIPTOR SecurityDescriptor;
SECURITY_SUBJECT_CONTEXT SubjectContext;
BOOLEAN NeedsPeb = FALSE;
INITIAL_PEB InitialPeb;
PAGED_CODE();
PSTRACE(PS_PROCESS_DEBUG,
"ProcessHandle: %p Parent: %p\n", ProcessHandle, ParentProcess);
/* Validate flags */
if (Flags & ~PROCESS_CREATE_FLAGS_LEGAL_MASK) return STATUS_INVALID_PARAMETER;
/* Check for parent */
if (ParentProcess)
{
/* Reference it */
Status = ObReferenceObjectByHandle(ParentProcess,
PROCESS_CREATE_PROCESS,
PsProcessType,
PreviousMode,
(PVOID*)&Parent,
NULL);
if (!NT_SUCCESS(Status)) return Status;
/* If this process should be in a job but the parent isn't */
if ((InJob) && (!Parent->Job))
{
/* This is illegal. Dereference the parent and fail */
ObDereferenceObject(Parent);
return STATUS_INVALID_PARAMETER;
}
/* Inherit Parent process's Affinity. */
Affinity = Parent->Pcb.Affinity;
}
else
{
/* We have no parent */
Parent = NULL;
Affinity = KeActiveProcessors;
}
/* Save working set data */
MinWs = PsMinimumWorkingSet;
MaxWs = PsMaximumWorkingSet;
/* Create the Object */
Status = ObCreateObject(PreviousMode,
PsProcessType,
ObjectAttributes,
PreviousMode,
NULL,
sizeof(EPROCESS),
0,
0,
(PVOID*)&Process);
if (!NT_SUCCESS(Status)) goto Cleanup;
/* Clean up the Object */
RtlZeroMemory(Process, sizeof(EPROCESS));
/* Initialize pushlock and rundown protection */
ExInitializeRundownProtection(&Process->RundownProtect);
Process->ProcessLock.Value = 0;
/* Setup the Thread List Head */
InitializeListHead(&Process->ThreadListHead);
/* Set up the Quota Block from the Parent */
PspInheritQuota(Process, Parent);
/* Set up Dos Device Map from the Parent */
ObInheritDeviceMap(Parent, Process);
/* Check if we have a parent */
if (Parent)
{
/* Inherit PID and Hard Error Processing */
Process->InheritedFromUniqueProcessId = Parent->UniqueProcessId;
Process->DefaultHardErrorProcessing = Parent->
DefaultHardErrorProcessing;
}
else
{
/* Use default hard error processing */
Process->DefaultHardErrorProcessing = TRUE;
}
/* Check for a section handle */
if (SectionHandle)
{
/* Get a pointer to it */
Status = ObReferenceObjectByHandle(SectionHandle,
SECTION_MAP_EXECUTE,
MmSectionObjectType,
PreviousMode,
(PVOID*)&SectionObject,
NULL);
if (!NT_SUCCESS(Status)) goto CleanupWithRef;
}
else
{
/* Assume no section object */
SectionObject = NULL;
/* Is the parent the initial process?
* Check for NULL also, as at initialization PsInitialSystemProcess is NULL */
if (Parent != PsInitialSystemProcess && (Parent != NULL))
{
/* It's not, so acquire the process rundown */
if (ExAcquireRundownProtection(&Parent->RundownProtect))
{
/* If the parent has a section, use it */
SectionObject = Parent->SectionObject;
if (SectionObject) ObReferenceObject(SectionObject);
/* Release process rundown */
ExReleaseRundownProtection(&Parent->RundownProtect);
}
/* If we don't have a section object */
if (!SectionObject)
{
/* Then the process is in termination, so fail */
Status = STATUS_PROCESS_IS_TERMINATING;
goto CleanupWithRef;
}
}
}
/* Save the pointer to the section object */
Process->SectionObject = SectionObject;
/* Check for the debug port */
if (DebugPort)
{
/* Reference it */
Status = ObReferenceObjectByHandle(DebugPort,
DEBUG_OBJECT_ADD_REMOVE_PROCESS,
DbgkDebugObjectType,
PreviousMode,
(PVOID*)&DebugObject,
NULL);
if (!NT_SUCCESS(Status)) goto CleanupWithRef;
/* Save the debug object */
Process->DebugPort = DebugObject;
/* Check if the caller doesn't want the debug stuff inherited */
if (Flags & PROCESS_CREATE_FLAGS_NO_DEBUG_INHERIT)
{
/* Set the process flag */
InterlockedOr((PLONG)&Process->Flags, PSF_NO_DEBUG_INHERIT_BIT);
}
}
else
{
/* Do we have a parent? Copy his debug port */
if (Parent) DbgkCopyProcessDebugPort(Process, Parent);
}
/* Now check for an exception port */
if (ExceptionPort)
{
/* Reference it */
Status = ObReferenceObjectByHandle(ExceptionPort,
PORT_ALL_ACCESS,
LpcPortObjectType,
PreviousMode,
(PVOID*)&ExceptionPortObject,
NULL);
if (!NT_SUCCESS(Status)) goto CleanupWithRef;
/* Save the exception port */
Process->ExceptionPort = ExceptionPortObject;
}
/* Save the pointer to the section object */
Process->SectionObject = SectionObject;
/* Set default exit code */
Process->ExitStatus = STATUS_PENDING;
/* Check if this is the initial process being built */
if (Parent)
{
/* Create the address space for the child */
if (!MmCreateProcessAddressSpace(MinWs,
Process,
DirectoryTableBase))
{
/* Failed */
Status = STATUS_INSUFFICIENT_RESOURCES;
goto CleanupWithRef;
}
}
else
{
/* Otherwise, we are the boot process, we're already semi-initialized */
Process->ObjectTable = CurrentProcess->ObjectTable;
Status = MmInitializeHandBuiltProcess(Process, DirectoryTableBase);
if (!NT_SUCCESS(Status)) goto CleanupWithRef;
}
/* We now have an address space */
InterlockedOr((PLONG)&Process->Flags, PSF_HAS_ADDRESS_SPACE_BIT);
/* Set the maximum WS */
Process->Vm.MaximumWorkingSetSize = MaxWs;
/* Now initialize the Kernel Process */
KeInitializeProcess(&Process->Pcb,
PROCESS_PRIORITY_NORMAL,
Affinity,
DirectoryTableBase,
(BOOLEAN)(Process->DefaultHardErrorProcessing & 4));
/* Duplicate Parent Token */
Status = PspInitializeProcessSecurity(Process, Parent);
if (!NT_SUCCESS(Status)) goto CleanupWithRef;
/* Set default priority class */
Process->PriorityClass = PROCESS_PRIORITY_CLASS_NORMAL;
/* Check if we have a parent */
if (Parent)
{
/* Check our priority class */
if (Parent->PriorityClass == PROCESS_PRIORITY_CLASS_IDLE ||
Parent->PriorityClass == PROCESS_PRIORITY_CLASS_BELOW_NORMAL)
{
/* Normalize it */
Process->PriorityClass = Parent->PriorityClass;
}
/* Initialize object manager for the process */
Status = ObInitProcess(Flags & PROCESS_CREATE_FLAGS_INHERIT_HANDLES ?
Parent : NULL,
Process);
if (!NT_SUCCESS(Status)) goto CleanupWithRef;
}
else
{
/* Do the second part of the boot process memory setup */
Status = MmInitializeHandBuiltProcess2(Process);
if (!NT_SUCCESS(Status)) goto CleanupWithRef;
}
/* Set success for now */
Status = STATUS_SUCCESS;
/* Check if this is a real user-mode process */
if (SectionHandle)
{
/* Initialize the address space */
Status = MmInitializeProcessAddressSpace(Process,
NULL,
SectionObject,
&Flags,
&Process->
SeAuditProcessCreationInfo.
ImageFileName);
if (!NT_SUCCESS(Status)) goto CleanupWithRef;
//
// We need a PEB
//
NeedsPeb = TRUE;
}
else if (Parent)
{
/* Check if this is a child of the system process */
if (Parent != PsInitialSystemProcess)
{
//
// We need a PEB
//
NeedsPeb = TRUE;
/* This is a clone! */
ASSERTMSG("No support for cloning yet\n", FALSE);
}
else
{
/* This is the initial system process */
Flags &= ~PROCESS_CREATE_FLAGS_LARGE_PAGES;
Status = MmInitializeProcessAddressSpace(Process,
NULL,
NULL,
&Flags,
NULL);
if (!NT_SUCCESS(Status)) goto CleanupWithRef;
/* Create a dummy image file name */
Process->SeAuditProcessCreationInfo.ImageFileName =
ExAllocatePoolWithTag(PagedPool,
sizeof(OBJECT_NAME_INFORMATION),
TAG_SEPA);
if (!Process->SeAuditProcessCreationInfo.ImageFileName)
{
/* Fail */
Status = STATUS_INSUFFICIENT_RESOURCES;
goto CleanupWithRef;
}
/* Zero it out */
RtlZeroMemory(Process->SeAuditProcessCreationInfo.ImageFileName,
sizeof(OBJECT_NAME_INFORMATION));
}
}
#if MI_TRACE_PFNS
/* Copy the process name now that we have it */
memcpy(MiGetPfnEntry(Process->Pcb.DirectoryTableBase[0] >> PAGE_SHIFT)->ProcessName, Process->ImageFileName, 16);
if (Process->Pcb.DirectoryTableBase[1]) memcpy(MiGetPfnEntry(Process->Pcb.DirectoryTableBase[1] >> PAGE_SHIFT)->ProcessName, Process->ImageFileName, 16);
if (Process->WorkingSetPage) memcpy(MiGetPfnEntry(Process->WorkingSetPage)->ProcessName, Process->ImageFileName, 16);
#endif
/* Check if we have a section object and map the system DLL */
if (SectionObject) PspMapSystemDll(Process, NULL, FALSE);
/* Create a handle for the Process */
CidEntry.Object = Process;
CidEntry.GrantedAccess = 0;
Process->UniqueProcessId = ExCreateHandle(PspCidTable, &CidEntry);
if (!Process->UniqueProcessId)
{
/* Fail */
Status = STATUS_INSUFFICIENT_RESOURCES;
goto CleanupWithRef;
}
/* Set the handle table PID */
Process->ObjectTable->UniqueProcessId = Process->UniqueProcessId;
/* Check if we need to audit */
if (SeDetailedAuditingWithToken(NULL)) SeAuditProcessCreate(Process);
/* Check if the parent had a job */
if ((Parent) && (Parent->Job))
{
/* FIXME: We need to insert this process */
DPRINT1("Jobs not yet supported\n");
}
/* Create PEB only for User-Mode Processes */
if ((Parent) && (NeedsPeb))
{
//
// Set up the initial PEB
//
RtlZeroMemory(&InitialPeb, sizeof(INITIAL_PEB));
InitialPeb.Mutant = (HANDLE)-1;
InitialPeb.ImageUsesLargePages = 0; // FIXME: Not yet supported
//
// Create it only if we have an image section
//
if (SectionHandle)
{
//
// Create it
//
Status = MmCreatePeb(Process, &InitialPeb, &Process->Peb);
if (!NT_SUCCESS(Status)) goto CleanupWithRef;
}
else
{
//
// We have to clone it
//
ASSERTMSG("No support for cloning yet\n", FALSE);
}
}
/* The process can now be activated */
KeAcquireGuardedMutex(&PspActiveProcessMutex);
InsertTailList(&PsActiveProcessHead, &Process->ActiveProcessLinks);
KeReleaseGuardedMutex(&PspActiveProcessMutex);
/* Create an access state */
Status = SeCreateAccessStateEx(CurrentThread,
((Parent) &&
(Parent == PsInitialSystemProcess)) ?
Parent : CurrentProcess,
&LocalAccessState,
&AuxData,
DesiredAccess,
&PsProcessType->TypeInfo.GenericMapping);
if (!NT_SUCCESS(Status)) goto CleanupWithRef;
/* Insert the Process into the Object Directory */
Status = ObInsertObject(Process,
AccessState,
DesiredAccess,
1,
NULL,
&hProcess);
/* Free the access state */
if (AccessState) SeDeleteAccessState(AccessState);
/* Cleanup on failure */
if (!NT_SUCCESS(Status)) goto Cleanup;
/* Compute Quantum and Priority */
ASSERT(IsListEmpty(&Process->ThreadListHead) == TRUE);
Process->Pcb.BasePriority =
(SCHAR)PspComputeQuantumAndPriority(Process,
PsProcessPriorityBackground,
&Quantum);
Process->Pcb.QuantumReset = Quantum;
/* Check if we have a parent other then the initial system process */
Process->GrantedAccess = PROCESS_TERMINATE;
if ((Parent) && (Parent != PsInitialSystemProcess))
{
/* Get the process's SD */
Status = ObGetObjectSecurity(Process,
&SecurityDescriptor,
&SdAllocated);
if (!NT_SUCCESS(Status))
{
/* We failed, close the handle and clean up */
ObCloseHandle(hProcess, PreviousMode);
goto CleanupWithRef;
}
/* Create the subject context */
SubjectContext.ProcessAuditId = Process;
SubjectContext.PrimaryToken = PsReferencePrimaryToken(Process);
SubjectContext.ClientToken = NULL;
/* Do the access check */
Result = SeAccessCheck(SecurityDescriptor,
&SubjectContext,
FALSE,
MAXIMUM_ALLOWED,
0,
NULL,
&PsProcessType->TypeInfo.GenericMapping,
PreviousMode,
&Process->GrantedAccess,
&AccessStatus);
/* Dereference the token and let go the SD */
ObFastDereferenceObject(&Process->Token,
SubjectContext.PrimaryToken);
ObReleaseObjectSecurity(SecurityDescriptor, SdAllocated);
/* Remove access if it failed */
if (!Result) Process->GrantedAccess = 0;
/* Give the process some basic access */
Process->GrantedAccess |= (PROCESS_VM_OPERATION |
PROCESS_VM_READ |
PROCESS_VM_WRITE |
PROCESS_QUERY_INFORMATION |
PROCESS_TERMINATE |
PROCESS_CREATE_THREAD |
PROCESS_DUP_HANDLE |
PROCESS_CREATE_PROCESS |
PROCESS_SET_INFORMATION |
STANDARD_RIGHTS_ALL |
PROCESS_SET_QUOTA);
}
else
{
/* Set full granted access */
Process->GrantedAccess = PROCESS_ALL_ACCESS;
}
/* Set the Creation Time */
KeQuerySystemTime(&Process->CreateTime);
/* Protect against bad user-mode pointer */
_SEH2_TRY
{
/* Hacky way of returning the PEB to the user-mode creator */
if ((Process->Peb) && (CurrentThread->Tcb.Teb))
{
CurrentThread->Tcb.Teb->NtTib.ArbitraryUserPointer = Process->Peb;
}
/* Save the process handle */
*ProcessHandle = hProcess;
}
_SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
{
/* Get the exception code */
Status = _SEH2_GetExceptionCode();
}
_SEH2_END;
/* Run the Notification Routines */
PspRunCreateProcessNotifyRoutines(Process, TRUE);
/* If 12 processes have been created, enough of user-mode is ready */
if (++ProcessCount == 12) Ki386PerfEnd();
CleanupWithRef:
/*
* Dereference the process. For failures, kills the process and does
* cleanup present in PspDeleteProcess. For success, kills the extra
* reference added by ObInsertObject.
*/
ObDereferenceObject(Process);
Cleanup:
/* Dereference the parent */
if (Parent) ObDereferenceObject(Parent);
/* Return status to caller */
return Status;
}
/* PUBLIC FUNCTIONS **********************************************************/
/*
* @implemented
*/
NTSTATUS
NTAPI
PsCreateSystemProcess(OUT PHANDLE ProcessHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes)
{
/* Call the internal API */
return PspCreateProcess(ProcessHandle,
DesiredAccess,
ObjectAttributes,
NULL,
0,
NULL,
NULL,
NULL,
FALSE);
}
/*
* @implemented
*/
NTSTATUS
NTAPI
PsLookupProcessByProcessId(IN HANDLE ProcessId,
OUT PEPROCESS *Process)
{
PHANDLE_TABLE_ENTRY CidEntry;
PEPROCESS FoundProcess;
NTSTATUS Status = STATUS_INVALID_PARAMETER;
PAGED_CODE();
PSTRACE(PS_PROCESS_DEBUG, "ProcessId: %p\n", ProcessId);
KeEnterCriticalRegion();
/* Get the CID Handle Entry */
CidEntry = ExMapHandleToPointer(PspCidTable, ProcessId);
if (CidEntry)
{
/* Get the Process */
FoundProcess = CidEntry->Object;
/* Make sure it's really a process */
if (FoundProcess->Pcb.Header.Type == ProcessObject)
{
/* Safe Reference and return it */
if (ObReferenceObjectSafe(FoundProcess))
{
*Process = FoundProcess;
Status = STATUS_SUCCESS;
}
}
/* Unlock the Entry */
ExUnlockHandleTableEntry(PspCidTable, CidEntry);
}
/* Return to caller */
KeLeaveCriticalRegion();
return Status;
}
/*
* @implemented
*/
NTSTATUS
NTAPI
PsLookupProcessThreadByCid(IN PCLIENT_ID Cid,
OUT PEPROCESS *Process OPTIONAL,
OUT PETHREAD *Thread)
{
PHANDLE_TABLE_ENTRY CidEntry;
PETHREAD FoundThread;
NTSTATUS Status = STATUS_INVALID_CID;
PAGED_CODE();
PSTRACE(PS_PROCESS_DEBUG, "Cid: %p\n", Cid);
KeEnterCriticalRegion();
/* Get the CID Handle Entry */
CidEntry = ExMapHandleToPointer(PspCidTable, Cid->UniqueThread);
if (CidEntry)
{
/* Get the Process */
FoundThread = CidEntry->Object;
/* Make sure it's really a thread and this process' */
if ((FoundThread->Tcb.Header.Type == ThreadObject) &&
(FoundThread->Cid.UniqueProcess == Cid->UniqueProcess))
{
/* Safe Reference and return it */
if (ObReferenceObjectSafe(FoundThread))
{
*Thread = FoundThread;
Status = STATUS_SUCCESS;
/* Check if we should return the Process too */
if (Process)
{
/* Return it and reference it */
*Process = FoundThread->ThreadsProcess;
ObReferenceObject(*Process);
}
}
}
/* Unlock the Entry */
ExUnlockHandleTableEntry(PspCidTable, CidEntry);