[KMTESTS:IO]
[reactos.git] / reactos / subsystems / win32 / csrsrv / thredsup.c
1 /*
2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS Client/Server Runtime SubSystem
4 * FILE: subsystems/win32/csrsrv/thredsup.c
5 * PURPOSE: CSR Server DLL Thread Management
6 * PROGRAMMERS: ReactOS Portable Systems Group
7 * Alex Ionescu (alex@relsoft.net)
8 */
9
10 /* INCLUDES *******************************************************************/
11
12 #include <srv.h>
13
14 #define NDEBUG
15 #include <debug.h>
16
17 #define CsrHashThread(t) (HandleToUlong(t) % NUMBER_THREAD_HASH_BUCKETS)
18
19 /* GLOBALS ********************************************************************/
20
21 LIST_ENTRY CsrThreadHashTable[NUMBER_THREAD_HASH_BUCKETS];
22
23
24 /* PRIVATE FUNCTIONS **********************************************************/
25
26 /*++
27 * @name ProtectHandle
28 * @implemented NT5.2
29 *
30 * The ProtectHandle routine protects an object handle against closure.
31 *
32 * @return TRUE or FALSE.
33 *
34 * @remarks None.
35 *
36 *--*/
37 BOOLEAN
38 NTAPI
39 ProtectHandle(IN HANDLE ObjectHandle)
40 {
41 NTSTATUS Status;
42 OBJECT_HANDLE_ATTRIBUTE_INFORMATION HandleInfo;
43
44 /* Query current state */
45 Status = NtQueryObject(ObjectHandle,
46 ObjectHandleFlagInformation,
47 &HandleInfo,
48 sizeof(HandleInfo),
49 NULL);
50 if (NT_SUCCESS(Status))
51 {
52 /* Enable protect from close */
53 HandleInfo.ProtectFromClose = TRUE;
54 Status = NtSetInformationObject(ObjectHandle,
55 ObjectHandleFlagInformation,
56 &HandleInfo,
57 sizeof(HandleInfo));
58 if (NT_SUCCESS(Status)) return TRUE;
59 }
60
61 /* We failed to or set the state */
62 return FALSE;
63 }
64
65 /*++
66 * @name UnProtectHandle
67 * @implemented NT5.2
68 *
69 * The UnProtectHandle routine unprotects an object handle against closure.
70 *
71 * @return TRUE or FALSE.
72 *
73 * @remarks None.
74 *
75 *--*/
76 BOOLEAN
77 NTAPI
78 UnProtectHandle(IN HANDLE ObjectHandle)
79 {
80 NTSTATUS Status;
81 OBJECT_HANDLE_ATTRIBUTE_INFORMATION HandleInfo;
82
83 /* Query current state */
84 Status = NtQueryObject(ObjectHandle,
85 ObjectHandleFlagInformation,
86 &HandleInfo,
87 sizeof(HandleInfo),
88 NULL);
89 if (NT_SUCCESS(Status))
90 {
91 /* Disable protect from close */
92 HandleInfo.ProtectFromClose = FALSE;
93 Status = NtSetInformationObject(ObjectHandle,
94 ObjectHandleFlagInformation,
95 &HandleInfo,
96 sizeof(HandleInfo));
97 if (NT_SUCCESS(Status)) return TRUE;
98 }
99
100 /* We failed to or set the state */
101 return FALSE;
102 }
103
104 /*++
105 * @name CsrAllocateThread
106 *
107 * The CsrAllocateThread routine allocates a new CSR Thread object.
108 *
109 * @param CsrProcess
110 * Pointer to the CSR Process which will contain this CSR Thread.
111 *
112 * @return Pointer to the newly allocated CSR Thread.
113 *
114 * @remarks None.
115 *
116 *--*/
117 PCSR_THREAD
118 NTAPI
119 CsrAllocateThread(IN PCSR_PROCESS CsrProcess)
120 {
121 PCSR_THREAD CsrThread;
122
123 /* Allocate the structure */
124 CsrThread = RtlAllocateHeap(CsrHeap, HEAP_ZERO_MEMORY, sizeof(CSR_THREAD));
125 if (!CsrThread) return NULL;
126
127 /* Reference the Thread and Process */
128 CsrLockedReferenceThread(CsrThread);
129 CsrLockedReferenceProcess(CsrProcess);
130
131 /* Set the Parent Process */
132 CsrThread->Process = CsrProcess;
133
134 /* Return Thread */
135 return CsrThread;
136 }
137
138 /*++
139 * @name CsrLockedReferenceThread
140 *
141 * The CsrLockedReferenceThread references a CSR Thread while the
142 * Process Lock is already being held.
143 *
144 * @param CsrThread
145 * Pointer to the CSR Thread to be referenced.
146 *
147 * @return None.
148 *
149 * @remarks This routine will return with the Process Lock held.
150 *
151 *--*/
152 VOID
153 NTAPI
154 CsrLockedReferenceThread(IN PCSR_THREAD CsrThread)
155 {
156 /* Increment the reference count */
157 ++CsrThread->ReferenceCount;
158 }
159
160 /*++
161 * @name CsrLocateThreadByClientId
162 *
163 * The CsrLocateThreadByClientId routine locates the CSR Thread and,
164 * optionally, its parent CSR Process, corresponding to a Client ID.
165 *
166 * @param Process
167 * Optional pointer to a CSR Process pointer which will contain
168 * the CSR Thread's parent.
169 *
170 * @param ClientId
171 * Pointer to a Client ID structure containing the Unique Thread ID
172 * to look up.
173 *
174 * @return Pointer to the CSR Thread corresponding to this CID, or NULL if
175 * none was found.
176 *
177 * @remarks None.
178 *
179 *--*/
180 PCSR_THREAD
181 NTAPI
182 CsrLocateThreadByClientId(OUT PCSR_PROCESS *Process OPTIONAL,
183 IN PCLIENT_ID ClientId)
184 {
185 ULONG i;
186 PLIST_ENTRY ListHead, NextEntry;
187 PCSR_THREAD FoundThread;
188 // ASSERT(ProcessStructureListLocked());
189
190 if (Process) *Process = NULL;
191
192 /* Hash the Thread */
193 i = CsrHashThread(ClientId->UniqueThread);
194
195 /* Set the list pointers */
196 ListHead = &CsrThreadHashTable[i];
197 NextEntry = ListHead->Flink;
198
199 /* Star the loop */
200 while (NextEntry != ListHead)
201 {
202 /* Get the thread */
203 FoundThread = CONTAINING_RECORD(NextEntry, CSR_THREAD, HashLinks);
204
205 /* Move to the next entry */
206 NextEntry = NextEntry->Flink;
207
208 /* Compare the CID */
209 // if (*(PULONGLONG)&FoundThread->ClientId == *(PULONGLONG)ClientId)
210 if ( FoundThread->ClientId.UniqueProcess == ClientId->UniqueProcess &&
211 FoundThread->ClientId.UniqueThread == ClientId->UniqueThread )
212 {
213 /* Match found, return the process */
214 if (Process) *Process = FoundThread->Process;
215
216 /* Return thread too */
217 return FoundThread;
218 }
219 }
220
221 /* Nothing found */
222 return NULL;
223 }
224
225 /*++
226 * @name CsrLocateThreadInProcess
227 *
228 * The CsrLocateThreadInProcess routine locates the CSR Thread
229 * corresponding to a Client ID inside a specific CSR Process.
230 *
231 * @param Process
232 * Optional pointer to the CSR Process which contains the CSR Thread
233 * that will be looked up.
234 *
235 * @param ClientId
236 * Pointer to a Client ID structure containing the Unique Thread ID
237 * to look up.
238 *
239 * @return Pointer to the CSR Thread corresponding to this CID, or NULL if
240 * none was found.
241 *
242 * @remarks If the CsrProcess argument is NULL, the lookup will be done inside
243 * CsrRootProcess.
244 *
245 *--*/
246 PCSR_THREAD
247 NTAPI
248 CsrLocateThreadInProcess(IN PCSR_PROCESS CsrProcess OPTIONAL,
249 IN PCLIENT_ID Cid)
250 {
251 PLIST_ENTRY ListHead, NextEntry;
252 PCSR_THREAD FoundThread = NULL;
253
254 /* Use the Root Process if none was specified */
255 if (!CsrProcess) CsrProcess = CsrRootProcess;
256
257 /* Save the List pointers */
258 ListHead = &CsrProcess->ThreadList;
259 NextEntry = ListHead->Flink;
260
261 /* Start the Loop */
262 while (NextEntry != ListHead)
263 {
264 /* Get Thread Entry */
265 FoundThread = CONTAINING_RECORD(NextEntry, CSR_THREAD, Link);
266
267 /* Check for TID Match */
268 if (FoundThread->ClientId.UniqueThread == Cid->UniqueThread) break;
269
270 /* Move to the next entry */
271 NextEntry = NextEntry->Flink;
272 }
273
274 /* Return what we found */
275 return FoundThread;
276 }
277
278 /*++
279 * @name CsrInsertThread
280 *
281 * The CsrInsertThread routine inserts a CSR Thread into its parent's
282 * Thread List and into the Thread Hash Table.
283 *
284 * @param Process
285 * Pointer to the CSR Process containing this CSR Thread.
286 *
287 * @param Thread
288 * Pointer to the CSR Thread to be inserted.
289 *
290 * @return None.
291 *
292 * @remarks None.
293 *
294 *--*/
295 NTSTATUS
296 NTAPI
297 CsrInsertThread(IN PCSR_PROCESS Process,
298 IN PCSR_THREAD Thread)
299 {
300 ULONG i;
301 NTSTATUS Status;
302 ULONG ThreadInfo;
303 // ASSERT(ProcessStructureListLocked());
304
305 /* Make sure the thread isn't already dead by the time we got this */
306 Status = NtQueryInformationThread(Thread->ThreadHandle,
307 ThreadIsTerminated,
308 &ThreadInfo,
309 sizeof(ThreadInfo),
310 NULL);
311 if (!NT_SUCCESS(Status)) return Status;
312 if (ThreadInfo) return STATUS_THREAD_IS_TERMINATING;
313
314 /* Insert it into the Regular List */
315 InsertTailList(&Process->ThreadList, &Thread->Link);
316
317 /* Increase Thread Count */
318 Process->ThreadCount++;
319
320 /* Hash the Thread */
321 i = CsrHashThread(Thread->ClientId.UniqueThread);
322
323 /* Insert it there too */
324 InsertHeadList(&CsrThreadHashTable[i], &Thread->HashLinks);
325 return STATUS_SUCCESS;
326 }
327
328 /*++
329 * @name CsrDeallocateThread
330 *
331 * The CsrDeallocateThread frees the memory associated with a CSR Thread.
332 *
333 * @param CsrThread
334 * Pointer to the CSR Thread to be freed.
335 *
336 * @return None.
337 *
338 * @remarks Do not call this routine. It is reserved for the internal
339 * thread management routines when a CSR Thread has been cleanly
340 * dereferenced and killed.
341 *
342 *--*/
343 VOID
344 NTAPI
345 CsrDeallocateThread(IN PCSR_THREAD CsrThread)
346 {
347 /* Free the process object from the heap */
348 // ASSERT(CsrThread->WaitBlock == NULL);
349 RtlFreeHeap(CsrHeap, 0, CsrThread);
350 }
351
352 /*++
353 * @name CsrRemoveThread
354 *
355 * The CsrRemoveThread function undoes a CsrInsertThread operation and
356 * removes the CSR Thread from the the Hash Table and Thread List.
357 *
358 * @param CsrThread
359 * Pointer to the CSR Thread to remove.
360 *
361 * @return None.
362 *
363 * @remarks If this CSR Thread is the last one inside a CSR Process, the
364 * parent will be dereferenced and the CsrProcessLastThreadTerminated
365 * flag will be set.
366 *
367 * After executing this routine, the CSR Thread will have the
368 * CsrThreadInTermination flag set.
369 *
370 *--*/
371 VOID
372 NTAPI
373 CsrRemoveThread(IN PCSR_THREAD CsrThread)
374 {
375 ASSERT(ProcessStructureListLocked());
376
377 /* Remove it from the List */
378 RemoveEntryList(&CsrThread->Link);
379
380 /* Decreate the thread count of the process */
381 CsrThread->Process->ThreadCount--;
382
383 /* Remove it from the Hash List as well */
384 if (CsrThread->HashLinks.Flink) RemoveEntryList(&CsrThread->HashLinks);
385
386 /* Check if this is the last Thread */
387 if (CsrThread->Process->ThreadCount == 0)
388 {
389 /* Check if it's not already been marked for deletion */
390 if ((CsrThread->Process->Flags & CsrProcessLastThreadTerminated) == 0)
391 {
392 /* Let everyone know this process is about to lose the thread */
393 CsrThread->Process->Flags |= CsrProcessLastThreadTerminated;
394
395 /* Reference the Process */
396 CsrLockedDereferenceProcess(CsrThread->Process);
397 }
398 }
399
400 /* Mark the thread for deletion */
401 CsrThread->Flags |= CsrThreadInTermination;
402 }
403
404 /*++
405 * @name CsrThreadRefcountZero
406 *
407 * The CsrThreadRefcountZero routine is executed when a CSR Thread has lost
408 * all its active references. It removes and de-allocates the CSR Thread.
409 *
410 * @param CsrThread
411 * Pointer to the CSR Thread that is to be deleted.
412 *
413 * @return None.
414 *
415 * @remarks Do not call this routine. It is reserved for the internal
416 * thread management routines when a CSR Thread has lost all
417 * its references.
418 *
419 * This routine is called with the Process Lock held.
420 *
421 *--*/
422 VOID
423 NTAPI
424 CsrThreadRefcountZero(IN PCSR_THREAD CsrThread)
425 {
426 PCSR_PROCESS CsrProcess = CsrThread->Process;
427 NTSTATUS Status;
428 ASSERT(ProcessStructureListLocked());
429
430 /* Remove this thread */
431 CsrRemoveThread(CsrThread);
432
433 /* Release the Process Lock */
434 CsrReleaseProcessLock();
435
436 /* Close the NT Thread Handle */
437 if (CsrThread->ThreadHandle)
438 {
439 UnProtectHandle(CsrThread->ThreadHandle);
440 Status = NtClose(CsrThread->ThreadHandle);
441
442 if (!NT_SUCCESS(Status))
443 DPRINT1("CSR: NtClose failed, we are going to ASSERT, Status = 0x%08lx; [%02x,%02x] Process: 0x%p; ThreadHandle: 0x%p\n",
444 Status, CsrThread->ClientId.UniqueProcess, CsrThread->ClientId.UniqueThread, CsrProcess, CsrThread->ThreadHandle);
445
446 ASSERT(NT_SUCCESS(Status));
447 }
448
449 /* De-allocate the CSR Thread Object */
450 CsrDeallocateThread(CsrThread);
451
452 /* Remove a reference from the process */
453 CsrDereferenceProcess(CsrProcess);
454 }
455
456 /*++
457 * @name CsrLockedDereferenceThread
458 *
459 * The CsrLockedDereferenceThread dereferences a CSR Thread while the
460 * Process Lock is already being held.
461 *
462 * @param CsrThread
463 * Pointer to the CSR Thread to be dereferenced.
464 *
465 * @return None.
466 *
467 * @remarks This routine will return with the Process Lock held.
468 *
469 *--*/
470 VOID
471 NTAPI
472 CsrLockedDereferenceThread(IN PCSR_THREAD CsrThread)
473 {
474 LONG LockCount;
475
476 /* Decrease reference count */
477 LockCount = --CsrThread->ReferenceCount;
478 ASSERT(LockCount >= 0);
479 if (LockCount == 0)
480 {
481 /* Call the generic cleanup code */
482 CsrAcquireProcessLock();
483 CsrThreadRefcountZero(CsrThread);
484 }
485 }
486
487
488 /* PUBLIC FUNCTIONS ***********************************************************/
489
490 /*++
491 * @name CsrAddStaticServerThread
492 * @implemented NT4
493 *
494 * The CsrAddStaticServerThread routine adds a new CSR Thread to the
495 * CSR Server Process (CsrRootProcess).
496 *
497 * @param hThread
498 * Handle to an existing NT Thread to which to associate this
499 * CSR Thread.
500 *
501 * @param ClientId
502 * Pointer to the Client ID structure of the NT Thread to associate
503 * with this CSR Thread.
504 *
505 * @param ThreadFlags
506 * Initial CSR Thread Flags to associate to this CSR Thread. Usually
507 * CsrThreadIsServerThread.
508 *
509 * @return Pointer to the newly allocated CSR Thread.
510 *
511 * @remarks None.
512 *
513 *--*/
514 PCSR_THREAD
515 NTAPI
516 CsrAddStaticServerThread(IN HANDLE hThread,
517 IN PCLIENT_ID ClientId,
518 IN ULONG ThreadFlags)
519 {
520 PCSR_THREAD CsrThread;
521
522 /* Get the Lock */
523 CsrAcquireProcessLock();
524
525 /* Allocate the Server Thread */
526 CsrThread = CsrAllocateThread(CsrRootProcess);
527 if (CsrThread)
528 {
529 /* Setup the Object */
530 CsrThread->ThreadHandle = hThread;
531 ProtectHandle(hThread);
532 CsrThread->ClientId = *ClientId;
533 CsrThread->Flags = ThreadFlags;
534
535 /* Insert it into the Thread List */
536 InsertTailList(&CsrRootProcess->ThreadList, &CsrThread->Link);
537
538 /* Increment the thread count */
539 CsrRootProcess->ThreadCount++;
540 }
541 else
542 {
543 DPRINT1("CsrAddStaticServerThread: alloc failed for thread 0x%x\n", hThread);
544 }
545
546 /* Release the Process Lock and return */
547 CsrReleaseProcessLock();
548 return CsrThread;
549 }
550
551 /*++
552 * @name CsrCreateRemoteThread
553 * @implemented NT4
554 *
555 * The CsrCreateRemoteThread routine creates a CSR Thread object for
556 * an NT Thread which is not part of the current NT Process.
557 *
558 * @param hThread
559 * Handle to an existing NT Thread to which to associate this
560 * CSR Thread.
561 *
562 * @param ClientId
563 * Pointer to the Client ID structure of the NT Thread to associate
564 * with this CSR Thread.
565 *
566 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
567 *
568 * @remarks None.
569 *
570 *--*/
571 NTSTATUS
572 NTAPI
573 CsrCreateRemoteThread(IN HANDLE hThread,
574 IN PCLIENT_ID ClientId)
575 {
576 NTSTATUS Status;
577 HANDLE ThreadHandle;
578 PCSR_THREAD CsrThread;
579 PCSR_PROCESS CsrProcess;
580 KERNEL_USER_TIMES KernelTimes;
581
582 /* Get the Thread Create Time */
583 Status = NtQueryInformationThread(hThread,
584 ThreadTimes,
585 &KernelTimes,
586 sizeof(KernelTimes),
587 NULL);
588 if (!NT_SUCCESS(Status))
589 {
590 DPRINT1("Failed to query thread times: %lx\n", Status);
591 return Status;
592 }
593
594 /* Lock the Owner Process */
595 Status = CsrLockProcessByClientId(ClientId->UniqueProcess, &CsrProcess);
596 if (!NT_SUCCESS(Status))
597 {
598 DPRINT1("No known process for %lx\n", ClientId->UniqueProcess);
599 return Status;
600 }
601
602 /* Make sure the thread didn't terminate */
603 if (KernelTimes.ExitTime.QuadPart)
604 {
605 /* Unlock the process and return */
606 CsrUnlockProcess(CsrProcess);
607 DPRINT1("Dead thread: %I64x\n", KernelTimes.ExitTime.QuadPart);
608 return STATUS_THREAD_IS_TERMINATING;
609 }
610
611 /* Allocate a CSR Thread Structure */
612 CsrThread = CsrAllocateThread(CsrProcess);
613 if (!CsrThread)
614 {
615 DPRINT1("CSRSRV: %s: out of memory!\n", __FUNCTION__);
616 CsrUnlockProcess(CsrProcess);
617 return STATUS_NO_MEMORY;
618 }
619
620 /* Duplicate the Thread Handle */
621 Status = NtDuplicateObject(NtCurrentProcess(),
622 hThread,
623 NtCurrentProcess(),
624 &ThreadHandle,
625 0,
626 0,
627 DUPLICATE_SAME_ACCESS);
628 /* Allow failure */
629 if (!NT_SUCCESS(Status))
630 {
631 DPRINT1("Thread duplication failed: %lx\n", Status);
632 ThreadHandle = hThread;
633 }
634
635 /* Save the data we have */
636 CsrThread->CreateTime = KernelTimes.CreateTime;
637 CsrThread->ClientId = *ClientId;
638 CsrThread->ThreadHandle = ThreadHandle;
639 ProtectHandle(ThreadHandle);
640 CsrThread->Flags = 0;
641
642 /* Insert the Thread into the Process */
643 Status = CsrInsertThread(CsrProcess, CsrThread);
644 if (!NT_SUCCESS(Status))
645 {
646 /* Bail out */
647 if (CsrThread->ThreadHandle != hThread) NtClose(CsrThread->ThreadHandle);
648 CsrUnlockProcess(CsrProcess);
649 CsrDeallocateThread(CsrThread);
650 return Status;
651 }
652
653 /* Release the lock and return */
654 CsrUnlockProcess(CsrProcess);
655 return STATUS_SUCCESS;
656 }
657
658 /*++
659 * @name CsrCreateThread
660 * @implemented NT4
661 *
662 * The CsrCreateThread routine creates a CSR Thread object for an NT Thread.
663 *
664 * @param CsrProcess
665 * Pointer to the CSR Process which will contain the CSR Thread.
666 *
667 * @param hThread
668 * Handle to an existing NT Thread to which to associate this
669 * CSR Thread.
670 *
671 * @param ClientId
672 * Pointer to the Client ID structure of the NT Thread to associate
673 * with this CSR Thread.
674 *
675 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
676 *
677 * @remarks None.
678 *
679 *--*/
680 NTSTATUS
681 NTAPI
682 CsrCreateThread(IN PCSR_PROCESS CsrProcess,
683 IN HANDLE hThread,
684 IN PCLIENT_ID ClientId,
685 IN BOOLEAN HaveClient)
686 {
687 NTSTATUS Status;
688 PCSR_THREAD CsrThread, CurrentThread;
689 PCSR_PROCESS CurrentProcess;
690 CLIENT_ID CurrentCid;
691 KERNEL_USER_TIMES KernelTimes;
692
693 if (HaveClient)
694 {
695 /* Get the current thread and CID */
696 CurrentThread = CsrGetClientThread();
697 CurrentCid = CurrentThread->ClientId;
698
699 /* Acquire the Process Lock */
700 CsrAcquireProcessLock();
701
702 /* Get the current Process and make sure the Thread is valid with this CID */
703 CurrentThread = CsrLocateThreadByClientId(&CurrentProcess, &CurrentCid);
704
705 /* Something is wrong if we get an empty thread back */
706 if (!CurrentThread)
707 {
708 DPRINT1("CSRSRV: %s: invalid thread!\n", __FUNCTION__);
709 CsrReleaseProcessLock();
710 return STATUS_THREAD_IS_TERMINATING;
711 }
712 }
713 else
714 {
715 /* Acquire the Process Lock */
716 CsrAcquireProcessLock();
717 }
718
719 /* Get the Thread Create Time */
720 Status = NtQueryInformationThread(hThread,
721 ThreadTimes,
722 &KernelTimes,
723 sizeof(KernelTimes),
724 NULL);
725 if (!NT_SUCCESS(Status))
726 {
727 CsrReleaseProcessLock();
728 return Status;
729 }
730
731 /* Allocate a CSR Thread Structure */
732 CsrThread = CsrAllocateThread(CsrProcess);
733 if (!CsrThread)
734 {
735 DPRINT1("CSRSRV: %s: out of memory!\n", __FUNCTION__);
736 CsrReleaseProcessLock();
737 return STATUS_NO_MEMORY;
738 }
739
740 /* Save the data we have */
741 CsrThread->CreateTime = KernelTimes.CreateTime;
742 CsrThread->ClientId = *ClientId;
743 CsrThread->ThreadHandle = hThread;
744 ProtectHandle(hThread);
745 CsrThread->Flags = 0;
746
747 /* Insert the Thread into the Process */
748 Status = CsrInsertThread(CsrProcess, CsrThread);
749 if (!NT_SUCCESS(Status))
750 {
751 /* Bail out */
752 CsrUnlockProcess(CsrProcess);
753 CsrDeallocateThread(CsrThread);
754 return Status;
755 }
756
757 /* Release the lock and return */
758 CsrReleaseProcessLock();
759
760 return STATUS_SUCCESS;
761 }
762
763 /*++
764 * @name CsrDereferenceThread
765 * @implemented NT4
766 *
767 * The CsrDereferenceThread routine removes a reference from a CSR Thread.
768 *
769 * @param CsrThread
770 * Pointer to the CSR Thread to dereference.
771 *
772 * @return None.
773 *
774 * @remarks If the reference count has reached zero (ie: the CSR Thread has
775 * no more active references), it will be deleted.
776 *
777 *--*/
778 VOID
779 NTAPI
780 CsrDereferenceThread(IN PCSR_THREAD CsrThread)
781 {
782 /* Acquire process lock */
783 CsrAcquireProcessLock();
784
785 /* Decrease reference count */
786 ASSERT(CsrThread->ReferenceCount > 0);
787 if ((--CsrThread->ReferenceCount) == 0)
788 {
789 /* Call the generic cleanup code */
790 CsrThreadRefcountZero(CsrThread);
791 }
792 else
793 {
794 /* Just release the lock */
795 CsrReleaseProcessLock();
796 }
797 }
798
799 /*++
800 * @name CsrDestroyThread
801 * @implemented NT4
802 *
803 * The CsrDestroyThread routine destroys the CSR Thread corresponding to
804 * a given Thread ID.
805 *
806 * @param Cid
807 * Pointer to the Client ID Structure corresponding to the CSR
808 * Thread which is about to be destroyed.
809 *
810 * @return STATUS_SUCCESS in case of success, STATUS_THREAD_IS_TERMINATING
811 * if the CSR Thread is already terminating.
812 *
813 * @remarks None.
814 *
815 *--*/
816 NTSTATUS
817 NTAPI
818 CsrDestroyThread(IN PCLIENT_ID Cid)
819 {
820 CLIENT_ID ClientId = *Cid;
821 PCSR_THREAD CsrThread;
822 PCSR_PROCESS CsrProcess;
823
824 /* Acquire lock */
825 CsrAcquireProcessLock();
826
827 /* Find the thread */
828 CsrThread = CsrLocateThreadByClientId(&CsrProcess,
829 &ClientId);
830
831 /* Make sure we got one back, and that it's not already gone */
832 if (!CsrThread || (CsrThread->Flags & CsrThreadTerminated))
833 {
834 /* Release the lock and return failure */
835 CsrReleaseProcessLock();
836 return STATUS_THREAD_IS_TERMINATING;
837 }
838
839 /* Set the terminated flag */
840 CsrThread->Flags |= CsrThreadTerminated;
841
842 /* Acquire the Wait Lock */
843 CsrAcquireWaitLock();
844
845 /* Do we have an active wait block? */
846 if (CsrThread->WaitBlock)
847 {
848 /* Notify waiters of termination */
849 CsrNotifyWaitBlock(CsrThread->WaitBlock,
850 NULL,
851 NULL,
852 NULL,
853 CsrProcessTerminating,
854 TRUE);
855 }
856
857 /* Release the Wait Lock */
858 CsrReleaseWaitLock();
859
860 /* Dereference the thread */
861 CsrLockedDereferenceThread(CsrThread);
862
863 /* Release the Process Lock and return success */
864 CsrReleaseProcessLock();
865 return STATUS_SUCCESS;
866 }
867
868 /*++
869 * @name CsrExecServerThread
870 * @implemented NT4
871 *
872 * The CsrExecServerThread routine creates an NT Thread and then
873 * initializes a CSR Thread for it.
874 *
875 * @param ThreadHandler
876 * Pointer to the thread's startup routine.
877 *
878 * @param Flags
879 * Initial CSR Thread Flags to set to the CSR Thread.
880 *
881 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
882 *
883 * @remarks This routine is similar to CsrAddStaticServerThread, but it
884 * also creates an NT Thread instead of expecting one to already
885 * exist.
886 *
887 *--*/
888 NTSTATUS
889 NTAPI
890 CsrExecServerThread(IN PVOID ThreadHandler,
891 IN ULONG Flags)
892 {
893 PCSR_THREAD CsrThread;
894 HANDLE hThread;
895 CLIENT_ID ClientId;
896 NTSTATUS Status;
897
898 /* Acquire process lock */
899 CsrAcquireProcessLock();
900
901 /* Allocate a CSR Thread in the Root Process */
902 ASSERT(CsrRootProcess != NULL);
903 CsrThread = CsrAllocateThread(CsrRootProcess);
904 if (!CsrThread)
905 {
906 /* Fail */
907 CsrReleaseProcessLock();
908 return STATUS_NO_MEMORY;
909 }
910
911 /* Create the Thread */
912 Status = RtlCreateUserThread(NtCurrentProcess(),
913 NULL,
914 FALSE,
915 0,
916 0,
917 0,
918 ThreadHandler,
919 NULL,
920 &hThread,
921 &ClientId);
922 if (!NT_SUCCESS(Status))
923 {
924 /* Fail */
925 CsrDeallocateThread(CsrThread);
926 CsrReleaseProcessLock();
927 return Status;
928 }
929
930 /* Setup the Thread Object */
931 CsrThread->ThreadHandle = hThread;
932 ProtectHandle(hThread);
933 CsrThread->ClientId = ClientId;
934 CsrThread->Flags = Flags;
935
936 /* Insert it into the Thread List */
937 InsertHeadList(&CsrRootProcess->ThreadList, &CsrThread->Link);
938
939 /* Increase the thread count */
940 CsrRootProcess->ThreadCount++;
941
942 /* Return */
943 CsrReleaseProcessLock();
944 return Status;
945 }
946
947 /*++
948 * @name CsrLockThreadByClientId
949 * @implemented NT4
950 *
951 * The CsrLockThreadByClientId routine locks the CSR Thread corresponding
952 * to the given Thread ID and optionally returns it.
953 *
954 * @param Tid
955 * Thread ID corresponding to the CSR Thread which will be locked.
956 *
957 * @param CsrThread
958 * Optional pointer to a CSR Thread pointer which will hold the
959 * CSR Thread corresponding to the given Thread ID.
960 *
961 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
962 *
963 * @remarks Locking a CSR Thread is defined as acquiring an extra
964 * reference to it and returning with the Process Lock held.
965 *
966 *--*/
967 NTSTATUS
968 NTAPI
969 CsrLockThreadByClientId(IN HANDLE Tid,
970 OUT PCSR_THREAD *CsrThread)
971 {
972 PLIST_ENTRY NextEntry;
973 PCSR_THREAD CurrentThread = NULL;
974 NTSTATUS Status = STATUS_UNSUCCESSFUL;
975 ULONG i;
976
977 /* Acquire the lock */
978 CsrAcquireProcessLock();
979
980 /* Assume failure */
981 ASSERT(CsrThread != NULL);
982 *CsrThread = NULL;
983
984 /* Convert to Hash */
985 i = CsrHashThread(Tid);
986
987 /* Setup the List Pointers */
988 NextEntry = CsrThreadHashTable[i].Flink;
989
990 /* Start Loop */
991 while (NextEntry != &CsrThreadHashTable[i])
992 {
993 /* Get the Thread */
994 CurrentThread = CONTAINING_RECORD(NextEntry, CSR_THREAD, HashLinks);
995
996 /* Check for TID Match */
997 if ((CurrentThread->ClientId.UniqueThread == Tid) &&
998 (CurrentThread->Flags & CsrThreadTerminated) == 0)
999 {
1000 /* Get out of here */
1001 break;
1002 }
1003
1004 /* Move to the next entry */
1005 NextEntry = NextEntry->Flink;
1006 }
1007
1008 /* Nothing found if we got back to the list */
1009 if (NextEntry == &CsrThreadHashTable[i]) CurrentThread = NULL;
1010
1011 /* Did the loop find something? */
1012 if (CurrentThread)
1013 {
1014 /* Reference the found thread */
1015 Status = STATUS_SUCCESS;
1016 CsrLockedReferenceThread(CurrentThread);
1017 *CsrThread = CurrentThread;
1018 }
1019 else
1020 {
1021 /* Nothing found, release the lock */
1022 Status = STATUS_UNSUCCESSFUL;
1023 CsrReleaseProcessLock();
1024 }
1025
1026 /* Return the status */
1027 return Status;
1028 }
1029
1030 /*++
1031 * @name CsrReferenceThread
1032 * @implemented NT4
1033 *
1034 * The CsrReferenceThread routine increases the active reference count of
1035 * a CSR Thread.
1036 *
1037 * @param CsrThread
1038 * Pointer to the CSR Thread whose reference count will be increased.
1039 *
1040 * @return None.
1041 *
1042 * @remarks Do not use this routine if the Process Lock is already held.
1043 *
1044 *--*/
1045 VOID
1046 NTAPI
1047 CsrReferenceThread(IN PCSR_THREAD CsrThread)
1048 {
1049 /* Acquire process lock */
1050 CsrAcquireProcessLock();
1051
1052 /* Sanity checks */
1053 ASSERT((CsrThread->Flags & CsrThreadTerminated) == 0);
1054 ASSERT(CsrThread->ReferenceCount != 0);
1055
1056 /* Increment reference count */
1057 CsrThread->ReferenceCount++;
1058
1059 /* Release the lock */
1060 CsrReleaseProcessLock();
1061 }
1062
1063 /*++
1064 * @name CsrUnlockThread
1065 * @implemented NT4
1066 *
1067 * The CsrUnlockThread undoes a previous CsrLockThreadByClientId operation.
1068 *
1069 * @param CsrThread
1070 * Pointer to a previously locked CSR Thread.
1071 *
1072 * @return STATUS_SUCCESS.
1073 *
1074 * @remarks This routine must be called with the Process Lock held.
1075 *
1076 *--*/
1077 NTSTATUS
1078 NTAPI
1079 CsrUnlockThread(IN PCSR_THREAD CsrThread)
1080 {
1081 /* Dereference the Thread */
1082 ASSERT(ProcessStructureListLocked());
1083 CsrLockedDereferenceThread(CsrThread);
1084
1085 /* Release the lock and return */
1086 CsrReleaseProcessLock();
1087 return STATUS_SUCCESS;
1088 }
1089
1090 /* EOF */