forked from reactos/reactos
/
handle.c
1285 lines (1089 loc) · 37 KB
/
handle.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/ex/handle.c
* PURPOSE: Generic Executive Handle Tables
* PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
* Thomas Weidenmueller <w3seek@reactos.com>
*/
/* INCLUDES ******************************************************************/
#include <ntoskrnl.h>
#define NDEBUG
#include <debug.h>
/* GLOBALS *******************************************************************/
LIST_ENTRY HandleTableListHead;
EX_PUSH_LOCK HandleTableListLock;
#define SizeOfHandle(x) (sizeof(HANDLE) * (x))
#define MAKE_HANDLE(x) ((x) << 2)
#define CLEAR_HANDLE(x) MAKE_HANDLE(x.Index)
/* PRIVATE FUNCTIONS *********************************************************/
VOID
NTAPI
INIT_FUNCTION
ExpInitializeHandleTables(VOID)
{
/* Initialize the list of handle tables and the lock */
InitializeListHead(&HandleTableListHead);
ExInitializePushLock(&HandleTableListLock);
}
PHANDLE_TABLE_ENTRY
NTAPI
ExpLookupHandleTableEntry(IN PHANDLE_TABLE HandleTable,
IN EXHANDLE Handle)
{
ULONG TableLevel;
ULONG_PTR TableBase;
PHANDLE_TABLE_ENTRY HandleArray, Entry;
PVOID *PointerArray;
/* Clear the tag bits */
Handle.TagBits = 0;
/* Check if the handle is in the allocated range */
if (Handle.Value >= HandleTable->NextHandleNeedingPool)
{
return NULL;
}
/* Get the table code */
TableBase = HandleTable->TableCode;
/* Extract the table level and actual table base */
TableLevel = (ULONG)(TableBase & 3);
TableBase &= ~3;
PointerArray = (PVOID*)TableBase;
HandleArray = (PHANDLE_TABLE_ENTRY)TableBase;
/* Check what level we're running at */
switch (TableLevel)
{
case 2:
/* Get the mid level pointer array */
PointerArray = PointerArray[Handle.HighIndex];
ASSERT(PointerArray == NULL);
/* Fall through */
case 1:
/* Get the handle array */
HandleArray = PointerArray[Handle.MidIndex];
ASSERT(HandleArray == NULL);
/* Fall through */
case 0:
/* Get the entry using the low index */
Entry = &HandleArray[Handle.LowIndex];
/* All done */
break;
default:
ASSERT(FALSE);
Entry = NULL;
}
/* Return the handle entry */
return Entry;
}
PVOID
NTAPI
ExpAllocateTablePagedPool(IN PEPROCESS Process OPTIONAL,
IN SIZE_T Size)
{
PVOID Buffer;
/* Do the allocation */
Buffer = ExAllocatePoolWithTag(PagedPool, Size, TAG_OBJECT_TABLE);
if (Buffer)
{
/* Clear the memory */
RtlZeroMemory(Buffer, Size);
/* Check if we have a process to charge quota */
if (Process)
{
/* FIXME: Charge quota */
}
}
/* Return the allocated memory */
return Buffer;
}
PVOID
NTAPI
ExpAllocateTablePagedPoolNoZero(IN PEPROCESS Process OPTIONAL,
IN SIZE_T Size)
{
PVOID Buffer;
/* Do the allocation */
Buffer = ExAllocatePoolWithTag(PagedPool, Size, TAG_OBJECT_TABLE);
if (Buffer)
{
/* Check if we have a process to charge quota */
if (Process)
{
/* FIXME: Charge quota */
}
}
/* Return the allocated memory */
return Buffer;
}
VOID
NTAPI
ExpFreeTablePagedPool(IN PEPROCESS Process OPTIONAL,
IN PVOID Buffer,
IN SIZE_T Size)
{
/* Free the buffer */
ExFreePoolWithTag(Buffer, TAG_OBJECT_TABLE);
if (Process)
{
/* FIXME: Release quota */
}
}
VOID
NTAPI
ExpFreeLowLevelTable(IN PEPROCESS Process,
IN PHANDLE_TABLE_ENTRY TableEntry)
{
/* Check if we have an entry */
if (TableEntry[0].Object)
{
/* Free the entry */
ExpFreeTablePagedPool(Process,
TableEntry[0].Object,
LOW_LEVEL_ENTRIES *
sizeof(HANDLE_TABLE_ENTRY_INFO));
}
/* Free the table */
ExpFreeTablePagedPool(Process, TableEntry, PAGE_SIZE);
}
VOID
NTAPI
ExpFreeHandleTable(IN PHANDLE_TABLE HandleTable)
{
PEPROCESS Process = HandleTable->QuotaProcess;
ULONG i, j;
ULONG_PTR TableCode = HandleTable->TableCode;
ULONG_PTR TableBase = TableCode & ~3;
ULONG TableLevel = (ULONG)(TableCode & 3);
PHANDLE_TABLE_ENTRY Level1, *Level2, **Level3;
PAGED_CODE();
/* Check which level we're at */
if (TableLevel == 0)
{
/* Select the first level table base and just free it */
Level1 = (PVOID)TableBase;
ExpFreeLowLevelTable(Process, Level1);
}
else if (TableLevel == 1)
{
/* Select the second level table base */
Level2 = (PVOID)TableBase;
/* Loop each mid level entry */
for (i = 0; i < MID_LEVEL_ENTRIES; i++)
{
/* Leave if we've reached the last entry */
if (!Level2[i]) break;
/* Free the second level table */
ExpFreeLowLevelTable(Process, Level2[i]);
}
/* Free the second level table */
ExpFreeTablePagedPool(Process, Level2, PAGE_SIZE);
}
else
{
/* Select the third level table base */
Level3 = (PVOID)TableBase;
/* Loop each high level entry */
for (i = 0; i < HIGH_LEVEL_ENTRIES; i++)
{
/* Leave if we've reached the last entry */
if (!Level3[i]) break;
/* Loop each mid level entry */
for (j = 0; j < MID_LEVEL_ENTRIES; j++)
{
/* Leave if we've reached the last entry */
if (!Level3[i][j]) break;
/* Free the second level table */
ExpFreeLowLevelTable(Process, Level3[i][j]);
}
/* Free the third level table entry */
ExpFreeTablePagedPool(Process, Level3[i], PAGE_SIZE);
}
/* Free the third level table */
ExpFreeTablePagedPool(Process,
Level3,
SizeOfHandle(HIGH_LEVEL_ENTRIES));
}
/* Free the actual table and check if we need to release quota */
ExFreePoolWithTag(HandleTable, TAG_OBJECT_TABLE);
if (Process)
{
/* FIXME: TODO */
}
}
VOID
NTAPI
ExpFreeHandleTableEntry(IN PHANDLE_TABLE HandleTable,
IN EXHANDLE Handle,
IN PHANDLE_TABLE_ENTRY HandleTableEntry)
{
ULONG OldValue, NewValue, *Free;
ULONG i;
PAGED_CODE();
/* Sanity checks */
ASSERT(HandleTableEntry->Object == NULL);
ASSERT(HandleTableEntry == ExpLookupHandleTableEntry(HandleTable, Handle));
/* Decrement the handle count */
InterlockedDecrement(&HandleTable->HandleCount);
/* Mark the handle as free */
NewValue = (ULONG)CLEAR_HANDLE(Handle);
/* Check if we're FIFO */
if (!HandleTable->StrictFIFO)
{
/* Select a lock index */
i = Handle.Index % 4;
/* Select which entry to use */
Free = (HandleTable->HandleTableLock[i].Locked) ?
&HandleTable->FirstFree : &HandleTable->LastFree;
}
else
{
/* No need to worry about locking, take the last entry */
Free = &HandleTable->LastFree;
}
/* Start value change loop */
for (;;)
{
/* Get the current value and write */
OldValue = *Free;
HandleTableEntry->NextFreeTableEntry = (ULONG)OldValue;
if (InterlockedCompareExchange((PLONG) Free, NewValue, OldValue) == OldValue)
{
/* Break out, we're done. Make sure the handle value makes sense */
ASSERT((OldValue & FREE_HANDLE_MASK) <
HandleTable->NextHandleNeedingPool);
break;
}
}
}
PHANDLE_TABLE
NTAPI
ExpAllocateHandleTable(IN PEPROCESS Process OPTIONAL,
IN BOOLEAN NewTable)
{
PHANDLE_TABLE HandleTable;
PHANDLE_TABLE_ENTRY HandleTableTable, HandleEntry;
ULONG i;
PAGED_CODE();
/* Allocate the table */
HandleTable = ExAllocatePoolWithTag(PagedPool,
sizeof(HANDLE_TABLE),
TAG_OBJECT_TABLE);
if (!HandleTable) return NULL;
/* Check if we have a process */
if (Process)
{
/* FIXME: Charge quota */
}
/* Clear the table */
RtlZeroMemory(HandleTable, sizeof(HANDLE_TABLE));
/* Now allocate the first level structures */
HandleTableTable = ExpAllocateTablePagedPoolNoZero(Process, PAGE_SIZE);
if (!HandleTableTable)
{
/* Failed, free the table */
ExFreePoolWithTag(HandleTable, TAG_OBJECT_TABLE);
return NULL;
}
/* Write the pointer to our first level structures */
HandleTable->TableCode = (ULONG_PTR)HandleTableTable;
/* Initialize the first entry */
HandleEntry = &HandleTableTable[0];
HandleEntry->NextFreeTableEntry = -2;
HandleEntry->Value = 0;
/* Check if this is a new table */
if (NewTable)
{
/* Go past the root entry */
HandleEntry++;
/* Loop every low level entry */
for (i = 1; i < (LOW_LEVEL_ENTRIES - 1); i++)
{
/* Set up the free data */
HandleEntry->Value = 0;
HandleEntry->NextFreeTableEntry = MAKE_HANDLE(i + 1);
/* Move to the next entry */
HandleEntry++;
}
/* Terminate the last entry */
HandleEntry->Value = 0;
HandleEntry->NextFreeTableEntry = 0;
HandleTable->FirstFree = MAKE_HANDLE(1);
}
/* Set the next handle needing pool after our allocated page from above */
HandleTable->NextHandleNeedingPool = MAKE_HANDLE(LOW_LEVEL_ENTRIES);
/* Setup the rest of the handle table data */
HandleTable->QuotaProcess = Process;
HandleTable->UniqueProcessId = PsGetCurrentProcess()->UniqueProcessId;
HandleTable->Flags = 0;
/* Loop all the handle table locks */
for (i = 0; i < 4; i++)
{
/* Initialize the handle table lock */
ExInitializePushLock(&HandleTable->HandleTableLock[i]);
}
/* Initialize the contention event lock and return the lock */
ExInitializePushLock(&HandleTable->HandleContentionEvent);
return HandleTable;
}
PHANDLE_TABLE_ENTRY
NTAPI
ExpAllocateLowLevelTable(IN PHANDLE_TABLE HandleTable,
IN BOOLEAN DoInit)
{
ULONG i, Base;
PHANDLE_TABLE_ENTRY Low, HandleEntry;
/* Allocate the low level table */
Low = ExpAllocateTablePagedPoolNoZero(HandleTable->QuotaProcess,
PAGE_SIZE);
if (!Low) return NULL;
/* Setup the initial entry */
HandleEntry = &Low[0];
HandleEntry->NextFreeTableEntry = -2;
HandleEntry->Value = 0;
/* Check if we're initializing */
if (DoInit)
{
/* Go to the next entry and the base entry */
HandleEntry++;
Base = HandleTable->NextHandleNeedingPool + MAKE_HANDLE(2);
/* Loop each entry */
for (i = Base;
i < Base + MAKE_HANDLE(LOW_LEVEL_ENTRIES - 2);
i += MAKE_HANDLE(1))
{
/* Free this entry and move on to the next one */
HandleEntry->NextFreeTableEntry = i;
HandleEntry->Value = 0;
HandleEntry++;
}
/* Terminate the last entry */
HandleEntry->NextFreeTableEntry = 0;
HandleEntry->Value = 0;
}
/* Return the low level table */
return Low;
}
PHANDLE_TABLE_ENTRY*
NTAPI
ExpAllocateMidLevelTable(IN PHANDLE_TABLE HandleTable,
IN BOOLEAN DoInit,
OUT PHANDLE_TABLE_ENTRY *LowTableEntry)
{
PHANDLE_TABLE_ENTRY *Mid, Low;
/* Allocate the mid level table */
Mid = ExpAllocateTablePagedPool(HandleTable->QuotaProcess, PAGE_SIZE);
if (!Mid) return NULL;
/* Allocate a new low level for it */
Low = ExpAllocateLowLevelTable(HandleTable, DoInit);
if (!Low)
{
/* We failed, free the mid table */
ExpFreeTablePagedPool(HandleTable->QuotaProcess, Mid, PAGE_SIZE);
return NULL;
}
/* Link the tables and return the pointer */
Mid[0] = Low;
*LowTableEntry = Low;
return Mid;
}
BOOLEAN
NTAPI
ExpAllocateHandleTableEntrySlow(IN PHANDLE_TABLE HandleTable,
IN BOOLEAN DoInit)
{
ULONG i, j, Index;
PHANDLE_TABLE_ENTRY Low = NULL, *Mid, **High, *SecondLevel, **ThirdLevel;
ULONG NewFree, FirstFree;
PVOID Value;
ULONG_PTR TableCode = HandleTable->TableCode;
ULONG_PTR TableBase = TableCode & ~3;
ULONG TableLevel = (ULONG)(TableCode & 3);
PAGED_CODE();
/* Check how many levels we already have */
if (TableLevel == 0)
{
/* Allocate a mid level, since we only have a low level */
Mid = ExpAllocateMidLevelTable(HandleTable, DoInit, &Low);
if (!Mid) return FALSE;
/* Link up the tables */
Mid[1] = Mid[0];
Mid[0] = (PVOID)TableBase;
/* Write the new level and attempt to change the table code */
TableBase = ((ULONG_PTR)Mid) | 1;
Value = InterlockedExchangePointer((PVOID*)&HandleTable->TableCode, (PVOID)TableBase);
}
else if (TableLevel == 1)
{
/* Setup the 2nd level table */
SecondLevel = (PVOID)TableBase;
/* Get if the next index can fit in the table */
i = HandleTable->NextHandleNeedingPool /
MAKE_HANDLE(LOW_LEVEL_ENTRIES);
if (i < MID_LEVEL_ENTRIES)
{
/* We need to allocate a new table */
Low = ExpAllocateLowLevelTable(HandleTable, DoInit);
if (!Low) return FALSE;
/* Update the table */
Value = InterlockedExchangePointer((PVOID*)&SecondLevel[i], Low);
ASSERT(Value == NULL);
}
else
{
/* We need a new high level table */
High = ExpAllocateTablePagedPool(HandleTable->QuotaProcess,
SizeOfHandle(HIGH_LEVEL_ENTRIES));
if (!High) return FALSE;
/* Allocate a new mid level table as well */
Mid = ExpAllocateMidLevelTable(HandleTable, DoInit, &Low);
if (!Mid)
{
/* We failed, free the high level table as well */
ExpFreeTablePagedPool(HandleTable->QuotaProcess,
High,
SizeOfHandle(HIGH_LEVEL_ENTRIES));
return FALSE;
}
/* Link up the tables */
High[0] = (PVOID)TableBase;
High[1] = Mid;
/* Write the new table and change the table code */
TableBase = ((ULONG_PTR)High) | 2;
Value = InterlockedExchangePointer((PVOID*)&HandleTable->TableCode,
(PVOID)TableBase);
}
}
else if (TableLevel == 2)
{
/* Setup the 3rd level table */
ThirdLevel = (PVOID)TableBase;
/* Get the index and check if it can fit */
i = HandleTable->NextHandleNeedingPool / MAKE_HANDLE(MAX_MID_INDEX);
if (i >= HIGH_LEVEL_ENTRIES) return FALSE;
/* Check if there's no mid-level table */
if (!ThirdLevel[i])
{
/* Allocate a new mid level table */
Mid = ExpAllocateMidLevelTable(HandleTable, DoInit, &Low);
if (!Mid) return FALSE;
/* Update the table pointer */
Value = InterlockedExchangePointer((PVOID*)&ThirdLevel[i], Mid);
ASSERT(Value == NULL);
}
else
{
/* We have one, check at which index we should insert our entry */
Index = (HandleTable->NextHandleNeedingPool / MAKE_HANDLE(1)) -
i * MAX_MID_INDEX;
j = Index / LOW_LEVEL_ENTRIES;
/* Allocate a new low level */
Low = ExpAllocateLowLevelTable(HandleTable, DoInit);
if (!Low) return FALSE;
/* Update the table pointer */
Value = InterlockedExchangePointer((PVOID*)&ThirdLevel[i][j], Low);
ASSERT(Value == NULL);
}
}
else
{
/* Something is really broken */
ASSERT(FALSE);
}
/* Update the index of the next handle */
Index = InterlockedExchangeAdd((PLONG) &HandleTable->NextHandleNeedingPool,
MAKE_HANDLE(LOW_LEVEL_ENTRIES));
/* Check if need to initialize the table */
if (DoInit)
{
/* Create a new index number */
Index += MAKE_HANDLE(1);
/* Start free index change loop */
for (;;)
{
/* Setup the first free index */
FirstFree = HandleTable->FirstFree;
Low[LOW_LEVEL_ENTRIES - 1].NextFreeTableEntry = FirstFree;
/* Change the index */
NewFree = InterlockedCompareExchange((PLONG) &HandleTable->FirstFree,
Index,
FirstFree);
if (NewFree == FirstFree) break;
}
}
/* All done */
return TRUE;
}
ULONG
NTAPI
ExpMoveFreeHandles(IN PHANDLE_TABLE HandleTable)
{
ULONG LastFree, i;
/* Clear the last free index */
LastFree = InterlockedExchange((PLONG) &HandleTable->LastFree, 0);
/* Check if we had no index */
if (!LastFree) return LastFree;
/* Acquire the locks we need */
for (i = 1; i < 4; i++)
{
/* Acquire this lock exclusively */
ExWaitOnPushLock(&HandleTable->HandleTableLock[i]);
}
/* Check if we're not strict FIFO */
if (!HandleTable->StrictFIFO)
{
/* Update the first free index */
if (!InterlockedCompareExchange((PLONG) &HandleTable->FirstFree, LastFree, 0))
{
/* We're done, exit */
return LastFree;
}
}
/* We are strict FIFO, we need to reverse the entries */
ASSERT(FALSE);
return LastFree;
}
PHANDLE_TABLE_ENTRY
NTAPI
ExpAllocateHandleTableEntry(IN PHANDLE_TABLE HandleTable,
OUT PEXHANDLE NewHandle)
{
ULONG OldValue, NewValue, NewValue1;
PHANDLE_TABLE_ENTRY Entry;
EXHANDLE Handle, OldHandle;
BOOLEAN Result;
ULONG i;
/* Start allocation loop */
for (;;)
{
/* Get the current link */
OldValue = HandleTable->FirstFree;
while (!OldValue)
{
/* No free entries remain, lock the handle table */
KeEnterCriticalRegion();
ExAcquirePushLockExclusive(&HandleTable->HandleTableLock[0]);
/* Check the value again */
OldValue = HandleTable->FirstFree;
if (OldValue)
{
/* Another thread has already created a new level, bail out */
ExReleasePushLockExclusive(&HandleTable->HandleTableLock[0]);
KeLeaveCriticalRegion();
break;
}
/* Now move any free handles */
OldValue = ExpMoveFreeHandles(HandleTable);
if (OldValue)
{
/* Another thread has already moved them, bail out */
ExReleasePushLockExclusive(&HandleTable->HandleTableLock[0]);
KeLeaveCriticalRegion();
break;
}
/* We're the first one through, so do the actual allocation */
Result = ExpAllocateHandleTableEntrySlow(HandleTable, TRUE);
/* Unlock the table and get the value now */
ExReleasePushLockExclusive(&HandleTable->HandleTableLock[0]);
KeLeaveCriticalRegion();
OldValue = HandleTable->FirstFree;
/* Check if allocation failed */
if (!Result)
{
/* Check if nobody else went through here */
if (!OldValue)
{
/* We're still the only thread around, so fail */
NewHandle->GenericHandleOverlay = NULL;
return NULL;
}
}
}
/* We made it, write the current value */
Handle.Value = (OldValue & FREE_HANDLE_MASK);
/* Lookup the entry for this handle */
Entry = ExpLookupHandleTableEntry(HandleTable, Handle);
/* Get an available lock and acquire it */
OldHandle.Value = OldValue;
i = OldHandle.Index % 4;
KeEnterCriticalRegion();
ExAcquirePushLockShared(&HandleTable->HandleTableLock[i]);
/* Check if the value changed after acquiring the lock */
if (OldValue != *(volatile ULONG*)&HandleTable->FirstFree)
{
/* It did, so try again */
ExReleasePushLockShared(&HandleTable->HandleTableLock[i]);
KeLeaveCriticalRegion();
continue;
}
/* Now get the next value and do the compare */
NewValue = *(volatile ULONG*)&Entry->NextFreeTableEntry;
NewValue1 = InterlockedCompareExchange((PLONG) &HandleTable->FirstFree,
NewValue,
OldValue);
/* The change was done, so release the lock */
ExReleasePushLockShared(&HandleTable->HandleTableLock[i]);
KeLeaveCriticalRegion();
/* Check if the compare was successful */
if (NewValue1 == OldValue)
{
/* Make sure that the new handle is in range, and break out */
ASSERT((NewValue & FREE_HANDLE_MASK) <
HandleTable->NextHandleNeedingPool);
break;
}
else
{
/* The compare failed, make sure we expected it */
ASSERT((NewValue1 & FREE_HANDLE_MASK) !=
(OldValue & FREE_HANDLE_MASK));
}
}
/* Increase the number of handles */
InterlockedIncrement(&HandleTable->HandleCount);
/* Return the handle and the entry */
*NewHandle = Handle;
return Entry;
}
PHANDLE_TABLE
NTAPI
ExCreateHandleTable(IN PEPROCESS Process OPTIONAL)
{
PHANDLE_TABLE HandleTable;
PAGED_CODE();
/* Allocate the handle table */
HandleTable = ExpAllocateHandleTable(Process, TRUE);
if (!HandleTable) return NULL;
/* Acquire the handle table lock */
KeEnterCriticalRegion();
ExAcquirePushLockExclusive(&HandleTableListLock);
/* Insert it into the list */
InsertTailList(&HandleTableListHead, &HandleTable->HandleTableList);
/* Release the lock */
ExReleasePushLockExclusive(&HandleTableListLock);
KeLeaveCriticalRegion();
/* Return the handle table */
return HandleTable;
}
HANDLE
NTAPI
ExCreateHandle(IN PHANDLE_TABLE HandleTable,
IN PHANDLE_TABLE_ENTRY HandleTableEntry)
{
EXHANDLE Handle;
PHANDLE_TABLE_ENTRY NewEntry;
PAGED_CODE();
/* Start with a clean handle */
Handle.GenericHandleOverlay = NULL;
/* Allocate a new entry */
NewEntry = ExpAllocateHandleTableEntry(HandleTable, &Handle);
if (NewEntry)
{
/* Enter a critical region */
KeEnterCriticalRegion();
/* Write the entry */
*NewEntry = *HandleTableEntry;
/* Unlock it and leave the critical region */
ExUnlockHandleTableEntry(HandleTable, NewEntry);
KeLeaveCriticalRegion();
}
/* Return the handle value */
return Handle.GenericHandleOverlay;
}
VOID
NTAPI
ExpBlockOnLockedHandleEntry(IN PHANDLE_TABLE HandleTable,
IN PHANDLE_TABLE_ENTRY HandleTableEntry)
{
LONG_PTR OldValue;
EX_PUSH_LOCK_WAIT_BLOCK WaitBlock;
/* Block on the pushlock */
ExBlockPushLock(&HandleTable->HandleContentionEvent, &WaitBlock);
/* Get the current value and check if it's been unlocked */
OldValue = HandleTableEntry->Value;
if (!(OldValue) || (OldValue & EXHANDLE_TABLE_ENTRY_LOCK_BIT))
{
/* Unblock the pushlock and return */
ExfUnblockPushLock(&HandleTable->HandleContentionEvent, &WaitBlock);
}
else
{
/* Wait for it to be unblocked */
ExWaitForUnblockPushLock(&HandleTable->HandleContentionEvent,
&WaitBlock);
}
}
BOOLEAN
NTAPI
ExpLockHandleTableEntry(IN PHANDLE_TABLE HandleTable,
IN PHANDLE_TABLE_ENTRY HandleTableEntry)
{
LONG_PTR NewValue, OldValue;
/* Sanity check */
ASSERT((KeGetCurrentThread()->CombinedApcDisable != 0) ||
(KeGetCurrentIrql() == APC_LEVEL));
/* Start lock loop */
for (;;)
{
/* Get the current value and check if it's locked */
OldValue = *(volatile LONG_PTR *)&HandleTableEntry->Object;
if (OldValue & EXHANDLE_TABLE_ENTRY_LOCK_BIT)
{
/* It's not locked, remove the lock bit to lock it */
NewValue = OldValue & ~EXHANDLE_TABLE_ENTRY_LOCK_BIT;
if (InterlockedCompareExchangePointer(&HandleTableEntry->Object,
(PVOID)NewValue,
(PVOID)OldValue) == (PVOID)OldValue)
{
/* We locked it, get out */
return TRUE;
}
}
else
{
/* We couldn't lock it, bail out if it's been freed */
if (!OldValue) return FALSE;
}
/* It's locked, wait for it to be unlocked */
ExpBlockOnLockedHandleEntry(HandleTable, HandleTableEntry);
}
}
VOID
NTAPI
ExUnlockHandleTableEntry(IN PHANDLE_TABLE HandleTable,
IN PHANDLE_TABLE_ENTRY HandleTableEntry)
{
LONG_PTR OldValue;
PAGED_CODE();
/* Sanity check */
ASSERT((KeGetCurrentThread()->CombinedApcDisable != 0) ||
(KeGetCurrentIrql() == APC_LEVEL));
/* Set the lock bit and make sure it wasn't earlier */
OldValue = InterlockedOr((PLONG) &HandleTableEntry->Value,
EXHANDLE_TABLE_ENTRY_LOCK_BIT);
ASSERT((OldValue & EXHANDLE_TABLE_ENTRY_LOCK_BIT) == 0);
/* Unblock any waiters */
ExfUnblockPushLock(&HandleTable->HandleContentionEvent, NULL);
}
VOID
NTAPI
ExRemoveHandleTable(IN PHANDLE_TABLE HandleTable)
{
PAGED_CODE();
/* Acquire the table lock */
KeEnterCriticalRegion();
ExAcquirePushLockExclusive(&HandleTableListLock);
/* Remove the table and reset the list */
RemoveEntryList(&HandleTable->HandleTableList);
InitializeListHead(&HandleTable->HandleTableList);
/* Release the lock */
ExReleasePushLockExclusive(&HandleTableListLock);
KeLeaveCriticalRegion();
}
VOID
NTAPI
ExDestroyHandleTable(IN PHANDLE_TABLE HandleTable,
IN PVOID DestroyHandleProcedure OPTIONAL)
{
PAGED_CODE();
/* Remove the handle from the list */
ExRemoveHandleTable(HandleTable);
/* Check if we have a destroy callback */
if (DestroyHandleProcedure)
{
/* FIXME: */
ASSERT(FALSE);
}
/* Free the handle table */
ExpFreeHandleTable(HandleTable);
}
BOOLEAN
NTAPI
ExDestroyHandle(IN PHANDLE_TABLE HandleTable,
IN HANDLE Handle,
IN PHANDLE_TABLE_ENTRY HandleTableEntry OPTIONAL)
{
EXHANDLE ExHandle;
PVOID Object;
PAGED_CODE();
/* Setup the actual handle value */
ExHandle.GenericHandleOverlay = Handle;
/* Enter a critical region and check if we have to lookup the handle */
KeEnterCriticalRegion();
if (!HandleTableEntry)
{
/* Lookup the entry */
HandleTableEntry = ExpLookupHandleTableEntry(HandleTable, ExHandle);
/* Make sure that we found an entry, and that it's valid */
if (!(HandleTableEntry) ||
!(HandleTableEntry->Object) ||
(HandleTableEntry->NextFreeTableEntry == -2))
{
/* Invalid handle, fail */
KeLeaveCriticalRegion();
return FALSE;
}
/* Lock the entry */
if (!ExpLockHandleTableEntry(HandleTable, HandleTableEntry))
{
/* Couldn't lock, fail */
KeLeaveCriticalRegion();
return FALSE;
}
}
else
{
/* Make sure the handle is locked */
ASSERT((HandleTableEntry->Value & EXHANDLE_TABLE_ENTRY_LOCK_BIT) == 0);
}
/* Clear the handle */
Object = InterlockedExchangePointer((PVOID*)&HandleTableEntry->Object, NULL);
/* Sanity checks */
ASSERT(Object != NULL);
ASSERT((((ULONG_PTR)Object) & EXHANDLE_TABLE_ENTRY_LOCK_BIT) == 0);
/* Unblock the pushlock */
ExfUnblockPushLock(&HandleTable->HandleContentionEvent, NULL);