1 ------------------------------------------------------------------------------
3 -- GNU ADA RUN-TIME LIBRARY (GNARL) COMPONENTS --
5 -- S Y S T E M . T A S K I N G . S T A G E S --
9 -- Copyright (C) 1992-2003, Free Software Foundation, Inc. --
11 -- GNARL is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 2, or (at your option) any later ver- --
14 -- sion. GNARL is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNARL; see file COPYING. If not, write --
19 -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
20 -- MA 02111-1307, USA. --
22 -- As a special exception, if other files instantiate generics from this --
23 -- unit, or you link this unit with other files to produce an executable, --
24 -- this unit does not by itself cause the resulting executable to be --
25 -- covered by the GNU General Public License. This exception does not --
26 -- however invalidate any other reasons why the executable file might be --
27 -- covered by the GNU Public License. --
29 -- GNARL was developed by the GNARL team at Florida State University. --
30 -- Extensive contributions were provided by Ada Core Technologies, Inc. --
32 ------------------------------------------------------------------------------
35 -- Turn off polling, we do not want ATC polling to take place during
36 -- tasking operations. It causes infinite loops and other problems.
39 -- used for Raise_Exception
41 with System.Tasking.Debug;
42 -- used for enabling tasking facilities with gdb
44 with System.Address_Image;
45 -- used for the function itself.
47 with System.Parameters;
52 with System.Task_Info;
53 -- used for Task_Info_Type
55 with System.Task_Primitives.Operations;
56 -- used for Finalize_Lock
66 with System.Soft_Links;
67 -- These are procedure pointers to non-tasking routines that use
68 -- task specific data. In the absence of tasking, these routines
69 -- refer to global data. In the presense of tasking, they must be
70 -- replaced with pointers to task-specific versions.
71 -- Also used for Create_TSD, Destroy_TSD, Get_Current_Excep
73 with System.Tasking.Initialization;
74 -- Used for Remove_From_All_Tasks_List
77 -- Initialization.Poll_Base_Priority_Change
78 -- Finalize_Attributes_Link
79 -- Initialize_Attributes_Link
81 pragma Elaborate_All (System.Tasking.Initialization);
82 -- This insures that tasking is initialized if any tasks are created.
84 with System.Tasking.Utilities;
85 -- Used for Make_Passive
88 with System.Tasking.Queuing;
89 -- Used for Dequeue_Head
91 with System.Tasking.Rendezvous;
92 -- Used for Call_Simple
94 with System.OS_Primitives;
95 -- Used for Delay_Modes
97 with System.Finalization_Implementation;
98 -- Used for System.Finalization_Implementation.Finalize_Global_List
100 with System.Secondary_Stack;
103 with System.Storage_Elements;
104 -- used for Storage_Array;
106 with System.Standard_Library;
107 -- used for Exception_Trace
109 with System.Traces.Tasking;
110 -- used for Send_Trace_Info
112 package body System.Tasking.Stages is
114 package STPO renames System.Task_Primitives.Operations;
115 package SSL renames System.Soft_Links;
116 package SSE renames System.Storage_Elements;
117 package SST renames System.Secondary_Stack;
123 use Task_Primitives.Operations;
127 use System.Traces.Tasking;
129 -----------------------
130 -- Local Subprograms --
131 -----------------------
133 procedure Trace_Unhandled_Exception_In_Task (Self_Id : Task_ID);
134 -- This procedure outputs the task specific message for exception
137 procedure Task_Wrapper (Self_ID : Task_ID);
138 -- This is the procedure that is called by the GNULL from the
139 -- new context when a task is created. It waits for activation
140 -- and then calls the task body procedure. When the task body
141 -- procedure completes, it terminates the task.
143 procedure Vulnerable_Complete_Task (Self_ID : Task_ID);
144 -- Complete the calling task.
145 -- This procedure must be called with abort deferred.
146 -- It should only be called by Complete_Task and
147 -- Finalizate_Global_Tasks (for the environment task).
149 procedure Vulnerable_Complete_Master (Self_ID : Task_ID);
150 -- Complete the current master of the calling task.
151 -- This procedure must be called with abort deferred.
152 -- It should only be called by Vulnerable_Complete_Task and
155 procedure Vulnerable_Complete_Activation (Self_ID : Task_ID);
156 -- Signal to Self_ID's activator that Self_ID has
157 -- completed activation.
159 -- Call this procedure with abort deferred.
161 procedure Abort_Dependents (Self_ID : Task_ID);
162 -- Abort all the direct dependents of Self at its current master
163 -- nesting level, plus all of their dependents, transitively.
164 -- RTS_Lock should be locked by the caller.
166 procedure Vulnerable_Free_Task (T : Task_ID);
167 -- Recover all runtime system storage associated with the task T.
168 -- This should only be called after T has terminated and will no
169 -- longer be referenced.
171 -- For tasks created by an allocator that fails, due to an exception,
172 -- it is called from Expunge_Unactivated_Tasks.
174 -- It is also called from Unchecked_Deallocation, for objects that
175 -- are or contain tasks.
177 -- Different code is used at master completion, in Terminate_Dependents,
178 -- due to a need for tighter synchronization with the master.
180 ----------------------
181 -- Abort_Dependents --
182 ----------------------
184 procedure Abort_Dependents (Self_ID : Task_ID) is
192 P := C.Common.Parent;
196 -- ??? C is supposed to take care of its own dependents, so
197 -- there should be no need to worry about them. Need to double
200 if C.Master_of_Task = Self_ID.Master_Within then
201 Utilities.Abort_One_Task (Self_ID, C);
202 C.Dependents_Aborted := True;
208 P := P.Common.Parent;
211 C := C.Common.All_Tasks_Link;
214 Self_ID.Dependents_Aborted := True;
215 end Abort_Dependents;
221 procedure Abort_Tasks (Tasks : Task_List) is
223 Utilities.Abort_Tasks (Tasks);
230 -- Note that locks of activator and activated task are both locked
231 -- here. This is necessary because C.Common.State and
232 -- Self.Common.Wait_Count have to be synchronized. This is safe from
233 -- deadlock because the activator is always created before the activated
234 -- task. That satisfies our in-order-of-creation ATCB locking policy.
236 -- At one point, we may also lock the parent, if the parent is
237 -- different from the activator. That is also consistent with the
238 -- lock ordering policy, since the activator cannot be created
239 -- before the parent.
241 -- Since we are holding both the activator's lock, and Task_Wrapper
242 -- locks that before it does anything more than initialize the
243 -- low-level ATCB components, it should be safe to wait to update
244 -- the counts until we see that the thread creation is successful.
246 -- If the thread creation fails, we do need to close the entries
247 -- of the task. The first phase, of dequeuing calls, only requires
248 -- locking the acceptor's ATCB, but the waking up of the callers
249 -- requires locking the caller's ATCB. We cannot safely do this
250 -- while we are holding other locks. Therefore, the queue-clearing
251 -- operation is done in a separate pass over the activation chain.
253 procedure Activate_Tasks (Chain_Access : Activation_Chain_Access) is
254 Self_ID : constant Task_ID := STPO.Self;
257 Next_C, Last_C : Task_ID;
258 Activate_Prio : System.Any_Priority;
260 All_Elaborated : Boolean := True;
264 (Debug.Trace (Self_ID, "Activate_Tasks", 'C'));
266 Initialization.Defer_Abort_Nestable (Self_ID);
268 pragma Assert (Self_ID.Common.Wait_Count = 0);
270 -- Lock RTS_Lock, to prevent activated tasks
271 -- from racing ahead before we finish activating the chain.
275 -- Check that all task bodies have been elaborated.
277 C := Chain_Access.T_ID;
281 if C.Common.Elaborated /= null
282 and then not C.Common.Elaborated.all
284 All_Elaborated := False;
287 -- Reverse the activation chain so that tasks are
288 -- activated in the same order they're declared.
290 Next_C := C.Common.Activation_Link;
291 C.Common.Activation_Link := Last_C;
296 Chain_Access.T_ID := Last_C;
298 if not All_Elaborated then
300 Initialization.Undefer_Abort_Nestable (Self_ID);
302 (Program_Error'Identity, "Some tasks have not been elaborated");
305 -- Activate all the tasks in the chain.
306 -- Creation of the thread of control was deferred until
307 -- activation. So create it now.
309 C := Chain_Access.T_ID;
312 if C.Common.State /= Terminated then
313 pragma Assert (C.Common.State = Unactivated);
315 P := C.Common.Parent;
319 if C.Common.Base_Priority < Get_Priority (Self_ID) then
320 Activate_Prio := Get_Priority (Self_ID);
322 Activate_Prio := C.Common.Base_Priority;
325 System.Task_Primitives.Operations.Create_Task
326 (C, Task_Wrapper'Address,
328 (C.Common.Compiler_Data.Pri_Stack_Info.Size),
329 Activate_Prio, Success);
331 -- There would be a race between the created task and the
332 -- creator to do the following initialization, if we did not
333 -- have a Lock/Unlock_RTS pair in the task wrapper to prevent
334 -- it from racing ahead.
337 C.Common.State := Runnable;
340 P.Awake_Count := P.Awake_Count + 1;
341 P.Alive_Count := P.Alive_Count + 1;
343 if P.Common.State = Master_Completion_Sleep and then
344 C.Master_of_Task = P.Master_Within
346 pragma Assert (Self_ID /= P);
347 P.Common.Wait_Count := P.Common.Wait_Count + 1;
354 -- No need to set Awake_Count, State, etc. here since the loop
355 -- below will do that for any Unactivated tasks.
359 Self_ID.Common.Activation_Failed := True;
363 C := C.Common.Activation_Link;
366 if not Single_Lock then
370 -- Close the entries of any tasks that failed thread creation,
371 -- and count those that have not finished activation.
373 Write_Lock (Self_ID);
374 Self_ID.Common.State := Activator_Sleep;
376 C := Chain_Access.T_ID;
380 if C.Common.State = Unactivated then
381 C.Common.Activator := null;
382 C.Common.State := Terminated;
384 Utilities.Cancel_Queued_Entry_Calls (C);
386 elsif C.Common.Activator /= null then
387 Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1;
391 P := C.Common.Activation_Link;
392 C.Common.Activation_Link := null;
396 -- Wait for the activated tasks to complete activation. It is
397 -- unsafe to abort any of these tasks until the count goes to zero.
400 Initialization.Poll_Base_Priority_Change (Self_ID);
401 exit when Self_ID.Common.Wait_Count = 0;
402 Sleep (Self_ID, Activator_Sleep);
405 Self_ID.Common.State := Runnable;
412 -- Remove the tasks from the chain
414 Chain_Access.T_ID := null;
415 Initialization.Undefer_Abort_Nestable (Self_ID);
417 if Self_ID.Common.Activation_Failed then
418 Self_ID.Common.Activation_Failed := False;
419 Raise_Exception (Tasking_Error'Identity,
420 "Failure during activation");
424 -------------------------
425 -- Complete_Activation --
426 -------------------------
428 procedure Complete_Activation is
429 Self_ID : constant Task_ID := STPO.Self;
431 Initialization.Defer_Abort_Nestable (Self_ID);
437 Vulnerable_Complete_Activation (Self_ID);
443 Initialization.Undefer_Abort_Nestable (Self_ID);
446 -- Why do we need to allow for nested deferral here?
448 if Runtime_Traces then
449 Send_Trace_Info (T_Activate);
451 end Complete_Activation;
453 ---------------------
454 -- Complete_Master --
455 ---------------------
457 procedure Complete_Master is
458 Self_ID : constant Task_ID := STPO.Self;
461 pragma Assert (Self_ID.Deferral_Level > 0);
463 Vulnerable_Complete_Master (Self_ID);
470 -- See comments on Vulnerable_Complete_Task for details
472 procedure Complete_Task is
473 Self_ID : constant Task_ID := STPO.Self;
475 pragma Assert (Self_ID.Deferral_Level > 0);
477 Vulnerable_Complete_Task (Self_ID);
479 -- All of our dependents have terminated. Never undefer abort again!
487 -- Compiler interface only. Do not call from within the RTS.
488 -- This must be called to create a new task.
490 procedure Create_Task
492 Size : System.Parameters.Size_Type;
493 Task_Info : System.Task_Info.Task_Info_Type;
494 Num_Entries : Task_Entry_Index;
495 Master : Master_Level;
496 State : Task_Procedure_Access;
497 Discriminants : System.Address;
498 Elaborated : Access_Boolean;
499 Chain : in out Activation_Chain;
501 Created_Task : out Task_ID)
504 Self_ID : constant Task_ID := STPO.Self;
506 Base_Priority : System.Any_Priority;
511 (Debug.Trace (Self_ID, "Create_Task", 'C'));
513 if Priority = Unspecified_Priority then
514 Base_Priority := Self_ID.Common.Base_Priority;
516 Base_Priority := System.Any_Priority (Priority);
519 -- Find parent P of new Task, via master level number
524 while P.Master_of_Task >= Master loop
525 P := P.Common.Parent;
530 Initialization.Defer_Abort_Nestable (Self_ID);
533 T := New_ATCB (Num_Entries);
537 Initialization.Undefer_Abort_Nestable (Self_ID);
538 Raise_Exception (Storage_Error'Identity, "Cannot allocate task");
541 -- RTS_Lock is used by Abort_Dependents and Abort_Tasks.
542 -- Up to this point, it is possible that we may be part of
543 -- a family of tasks that is being aborted.
546 Write_Lock (Self_ID);
548 -- Now, we must check that we have not been aborted.
549 -- If so, we should give up on creating this task,
550 -- and simply return.
552 if not Self_ID.Callable then
553 pragma Assert (Self_ID.Pending_ATC_Level = 0);
554 pragma Assert (Self_ID.Pending_Action);
555 pragma Assert (Chain.T_ID = null
556 or else Chain.T_ID.Common.State = Unactivated);
560 Initialization.Undefer_Abort_Nestable (Self_ID);
562 -- ??? Should never get here
564 pragma Assert (False);
565 raise Standard'Abort_Signal;
568 Initialize_ATCB (Self_ID, State, Discriminants, P, Elaborated,
569 Base_Priority, Task_Info, Size, T, Success);
574 Initialization.Undefer_Abort_Nestable (Self_ID);
576 (Storage_Error'Identity, "Failed to initialize task");
579 T.Master_of_Task := Master;
580 T.Master_Within := T.Master_of_Task + 1;
582 for L in T.Entry_Calls'Range loop
583 T.Entry_Calls (L).Self := T;
584 T.Entry_Calls (L).Level := L;
587 if Task_Image'Length = 0 then
588 T.Common.Task_Image_Len := 0;
591 T.Common.Task_Image (1) := Task_Image (Task_Image'First);
593 for J in Task_Image'First + 1 .. Task_Image'Last loop
595 -- Remove unwanted blank space generated by 'Image
597 if Task_Image (J) /= ' '
598 or else Task_Image (J - 1) /= '('
601 T.Common.Task_Image (Len) := Task_Image (J);
603 exit when Len = T.Common.Task_Image'Last;
607 T.Common.Task_Image_Len := Len;
613 -- Create TSD as early as possible in the creation of a task, since it
614 -- may be used by the operation of Ada code within the task.
616 SSL.Create_TSD (T.Common.Compiler_Data);
617 T.Common.Activation_Link := Chain.T_ID;
619 Initialization.Initialize_Attributes_Link.all (T);
621 Initialization.Undefer_Abort_Nestable (Self_ID);
623 if Runtime_Traces then
624 Send_Trace_Info (T_Create, T);
632 function Current_Master return Master_Level is
634 return STPO.Self.Master_Within;
641 procedure Enter_Master is
642 Self_ID : constant Task_ID := STPO.Self;
645 Self_ID.Master_Within := Self_ID.Master_Within + 1;
648 -------------------------------
649 -- Expunge_Unactivated_Tasks --
650 -------------------------------
652 -- See procedure Close_Entries for the general case.
654 procedure Expunge_Unactivated_Tasks (Chain : in out Activation_Chain) is
655 Self_ID : constant Task_ID := STPO.Self;
657 Call : Entry_Call_Link;
662 (Debug.Trace (Self_ID, "Expunge_Unactivated_Tasks", 'C'));
664 Initialization.Defer_Abort_Nestable (Self_ID);
667 -- Experimentation has shown that abort is sometimes (but not
668 -- always) already deferred when this is called.
670 -- That may indicate an error. Find out what is going on.
675 pragma Assert (C.Common.State = Unactivated);
677 Temp := C.Common.Activation_Link;
679 if C.Common.State = Unactivated then
683 for J in 1 .. C.Entry_Num loop
684 Queuing.Dequeue_Head (C.Entry_Queues (J), Call);
685 pragma Assert (Call = null);
690 Initialization.Remove_From_All_Tasks_List (C);
693 Vulnerable_Free_Task (C);
699 Initialization.Undefer_Abort_Nestable (Self_ID);
700 end Expunge_Unactivated_Tasks;
702 ---------------------------
703 -- Finalize_Global_Tasks --
704 ---------------------------
707 -- We have a potential problem here if finalization of global
708 -- objects does anything with signals or the timer server, since
709 -- by that time those servers have terminated.
711 -- It is hard to see how that would occur.
713 -- However, a better solution might be to do all this finalization
714 -- using the global finalization chain.
716 procedure Finalize_Global_Tasks is
717 Self_ID : constant Task_ID := STPO.Self;
721 if Self_ID.Deferral_Level = 0 then
723 -- In principle, we should be able to predict whether
724 -- abort is already deferred here (and it should not be deferred
725 -- yet but in practice it seems Finalize_Global_Tasks is being
726 -- called sometimes, from RTS code for exceptions, with abort already
729 Initialization.Defer_Abort_Nestable (Self_ID);
731 -- Never undefer again!!!
734 -- This code is only executed by the environment task
736 pragma Assert (Self_ID = Environment_Task);
738 -- Set Environment_Task'Callable to false to notify library-level tasks
739 -- that it is waiting for them (cf 5619-003).
741 Self_ID.Callable := False;
743 -- Exit level 2 master, for normal tasks in library-level packages.
747 -- Force termination of "independent" library-level server tasks.
751 Abort_Dependents (Self_ID);
753 if not Single_Lock then
757 -- We need to explicitely wait for the task to be terminated here
758 -- because on true concurrent system, we may end this procedure
759 -- before the tasks are really terminated.
761 Write_Lock (Self_ID);
764 exit when Utilities.Independent_Task_Count = 0;
766 -- We used to yield here, but this did not take into account
767 -- low priority tasks that would cause dead lock in some cases.
771 (Self_ID, 0.01, System.OS_Primitives.Relative,
772 Self_ID.Common.State, Ignore, Ignore);
775 -- ??? On multi-processor environments, it seems that the above loop
776 -- isn't sufficient, so we need to add an additional delay.
779 (Self_ID, 0.01, System.OS_Primitives.Relative,
780 Self_ID.Common.State, Ignore, Ignore);
788 -- Complete the environment task
790 Vulnerable_Complete_Task (Self_ID);
792 System.Finalization_Implementation.Finalize_Global_List;
794 SSL.Abort_Defer := SSL.Abort_Defer_NT'Access;
795 SSL.Abort_Undefer := SSL.Abort_Undefer_NT'Access;
796 SSL.Lock_Task := SSL.Task_Lock_NT'Access;
797 SSL.Unlock_Task := SSL.Task_Unlock_NT'Access;
798 SSL.Get_Jmpbuf_Address := SSL.Get_Jmpbuf_Address_NT'Access;
799 SSL.Set_Jmpbuf_Address := SSL.Set_Jmpbuf_Address_NT'Access;
800 SSL.Get_Sec_Stack_Addr := SSL.Get_Sec_Stack_Addr_NT'Access;
801 SSL.Set_Sec_Stack_Addr := SSL.Set_Sec_Stack_Addr_NT'Access;
802 SSL.Get_Exc_Stack_Addr := SSL.Get_Exc_Stack_Addr_NT'Access;
803 SSL.Set_Exc_Stack_Addr := SSL.Set_Exc_Stack_Addr_NT'Access;
804 SSL.Check_Abort_Status := SSL.Check_Abort_Status_NT'Access;
805 SSL.Get_Stack_Info := SSL.Get_Stack_Info_NT'Access;
807 -- Don't bother trying to finalize Initialization.Global_Task_Lock
808 -- and System.Task_Primitives.RTS_Lock.
810 end Finalize_Global_Tasks;
816 procedure Free_Task (T : Task_ID) is
817 Self_Id : constant Task_ID := Self;
820 if T.Common.State = Terminated then
822 -- It is not safe to call Abort_Defer or Write_Lock at this stage
824 Initialization.Task_Lock (Self_Id);
827 Initialization.Remove_From_All_Tasks_List (T);
830 Initialization.Task_Unlock (Self_Id);
832 System.Task_Primitives.Operations.Finalize_TCB (T);
834 -- If the task is not terminated, then we simply ignore the call. This
835 -- happens when a user program attempts an unchecked deallocation on
836 -- a non-terminated task.
847 -- The task wrapper is a procedure that is called first for each task
848 -- task body, and which in turn calls the compiler-generated task body
849 -- procedure. The wrapper's main job is to do initialization for the task.
850 -- It also has some locally declared objects that server as per-task local
851 -- data. Task finalization is done by Complete_Task, which is called from
852 -- an at-end handler that the compiler generates.
854 procedure Task_Wrapper (Self_ID : Task_ID) is
855 use type System.Parameters.Size_Type;
856 use type SSE.Storage_Offset;
857 use System.Standard_Library;
859 Secondary_Stack : aliased SSE.Storage_Array
860 (1 .. Self_ID.Common.Compiler_Data.Pri_Stack_Info.Size *
861 SSE.Storage_Offset (Parameters.Sec_Stack_Ratio) / 100);
862 Secondary_Stack_Address : System.Address := Secondary_Stack'Address;
865 pragma Assert (Self_ID.Deferral_Level = 1);
867 if not Parameters.Sec_Stack_Dynamic then
868 Self_ID.Common.Compiler_Data.Sec_Stack_Addr :=
869 Secondary_Stack'Address;
870 SST.SS_Init (Secondary_Stack_Address, Integer (Secondary_Stack'Last));
873 -- Set the guard page at the bottom of the stack. The call to
874 -- unprotect the page is done in Terminate_Task
876 Stack_Guard (Self_ID, True);
878 -- Initialize low-level TCB components, that cannot be initialized
879 -- by the creator. Enter_Task sets Self_ID.Known_Tasks_Index and
880 -- also Self_ID.LL.Thread
882 Enter_Task (Self_ID);
884 -- We lock RTS_Lock to wait for activator to finish activating
885 -- the rest of the chain, so that everyone in the chain comes out
886 -- in priority order.
888 -- This also protects the value of
889 -- Self_ID.Common.Activator.Common.Wait_Count.
895 -- We are separating the following portion of the code in order to
896 -- place the exception handlers in a different block. In this way,
897 -- we do not call Set_Jmpbuf_Address (which needs Self) before we
898 -- set Self in Enter_Task
900 -- Call the task body procedure
902 -- The task body is called with abort still deferred. That
903 -- eliminates a dangerous window, for which we had to patch-up in
906 -- During the expansion of the task body, we insert an RTS-call
907 -- to Abort_Undefer, at the first point where abort should be
910 Self_ID.Common.Task_Entry_Point (Self_ID.Common.Task_Arg);
911 Initialization.Defer_Abort_Nestable (Self_ID);
914 -- We can't call Terminate_Task in the exception handlers below,
915 -- since there may be (e.g. in the case of GCC exception handling)
916 -- clean ups associated with the exception handler that need to
917 -- access task specific data.
919 -- Defer abortion so that this task can't be aborted while exiting
921 when Standard'Abort_Signal =>
922 Initialization.Defer_Abort_Nestable (Self_ID);
925 -- ??? Using an E : others here causes CD2C11A to fail on
926 -- DEC Unix, see 7925-005.
928 Initialization.Defer_Abort_Nestable (Self_ID);
930 -- Perform the task specific exception tracing duty. We handle
931 -- these outputs here and not in the common notification routine
932 -- because we need access to tasking related data and we don't
933 -- want to drag dependencies against tasking related units in the
934 -- the common notification units. Additionally, no trace is ever
935 -- triggered from the common routine for the Unhandled_Raise case
936 -- in tasks, since an exception never appears unhandled in this
937 -- context because of this handler.
939 if Exception_Trace = Unhandled_Raise then
940 Trace_Unhandled_Exception_In_Task (Self_ID);
944 Terminate_Task (Self_ID);
951 -- Before we allow the thread to exit, we must clean up. This is a
952 -- a delicate job. We must wake up the task's master, who may immediately
953 -- try to deallocate the ATCB out from under the current task WHILE IT IS
956 -- To avoid this, the parent task must be blocked up to the latest
957 -- statement executed. The trouble is that we have another step that we
958 -- also want to postpone to the very end, i.e., calling SSL.Destroy_TSD.
959 -- We have to postpone that until the end because compiler-generated code
960 -- is likely to try to access that data at just about any point.
962 -- We can't call Destroy_TSD while we are holding any other locks, because
963 -- it locks Global_Task_Lock, and our deadlock prevention rules require
964 -- that to be the outermost lock. Our first "solution" was to just lock
965 -- Global_Task_Lock in addition to the other locks, and force the parent
966 -- to also lock this lock between its wakeup and its freeing of the ATCB.
967 -- See Complete_Task for the parent-side of the code that has the matching
968 -- calls to Task_Lock and Task_Unlock. That was not really a solution,
969 -- since the operation Task_Unlock continued to access the ATCB after
970 -- unlocking, after which the parent was observed to race ahead,
971 -- deallocate the ATCB, and then reallocate it to another task. The
972 -- call to Undefer_Abortion in Task_Unlock by the "terminated" task was
973 -- overwriting the data of the new task that reused the ATCB! To solve
974 -- this problem, we introduced the new operation Final_Task_Unlock.
976 procedure Terminate_Task (Self_ID : Task_ID) is
977 Environment_Task : constant Task_ID := STPO.Environment_Task;
978 Master_of_Task : Integer;
981 Debug.Task_Termination_Hook;
983 if Runtime_Traces then
984 Send_Trace_Info (T_Terminate);
987 -- Since GCC cannot allocate stack chunks efficiently without reordering
988 -- some of the allocations, we have to handle this unexpected situation
989 -- here. We should normally never have to call Vulnerable_Complete_Task
990 -- here. See 6602-003 for more details.
992 if Self_ID.Common.Activator /= null then
993 Vulnerable_Complete_Task (Self_ID);
996 Initialization.Task_Lock (Self_ID);
1002 Master_of_Task := Self_ID.Master_of_Task;
1004 -- Check if the current task is an independent task
1005 -- If so, decrement the Independent_Task_Count value.
1007 if Master_of_Task = 2 then
1009 Utilities.Independent_Task_Count :=
1010 Utilities.Independent_Task_Count - 1;
1013 Write_Lock (Environment_Task);
1014 Utilities.Independent_Task_Count :=
1015 Utilities.Independent_Task_Count - 1;
1016 Unlock (Environment_Task);
1020 -- Unprotect the guard page if needed
1022 Stack_Guard (Self_ID, False);
1024 Utilities.Make_Passive (Self_ID, Task_Completed => True);
1030 pragma Assert (Check_Exit (Self_ID));
1032 SSL.Destroy_TSD (Self_ID.Common.Compiler_Data);
1033 Initialization.Final_Task_Unlock (Self_ID);
1036 -- past this point, this thread must assume that the ATCB
1037 -- has been deallocated. It should not be accessed again.
1039 if Master_of_Task > 0 then
1048 function Terminated (T : Task_ID) return Boolean is
1049 Self_ID : constant Task_ID := STPO.Self;
1053 Initialization.Defer_Abort_Nestable (Self_ID);
1060 Result := T.Common.State = Terminated;
1067 Initialization.Undefer_Abort_Nestable (Self_ID);
1071 ----------------------------------------
1072 -- Trace_Unhandled_Exception_In_Task --
1073 ----------------------------------------
1075 procedure Trace_Unhandled_Exception_In_Task (Self_Id : Task_ID) is
1076 procedure To_Stderr (S : String);
1077 pragma Import (Ada, To_Stderr, "__gnat_to_stderr");
1079 use System.Task_Info;
1080 use System.Soft_Links;
1081 use System.Standard_Library;
1083 function To_Address is new
1084 Unchecked_Conversion (Task_ID, System.Address);
1086 function Tailored_Exception_Information
1087 (E : Exception_Occurrence) return String;
1089 (Ada, Tailored_Exception_Information,
1090 "__gnat_tailored_exception_information");
1092 Excep : Exception_Occurrence_Access := SSL.Get_Current_Excep.all;
1095 -- This procedure is called by the task outermost handler in
1096 -- Task_Wrapper below, so only once the task stack has been fully
1097 -- unwound. The common notification routine has been called at the
1098 -- raise point already.
1100 To_Stderr ("task ");
1102 if Self_Id.Common.Task_Image_Len /= 0 then
1104 (Self_Id.Common.Task_Image (1 .. Self_Id.Common.Task_Image_Len));
1108 To_Stderr (System.Address_Image (To_Address (Self_Id)));
1109 To_Stderr (" terminated by unhandled exception");
1110 To_Stderr ((1 => ASCII.LF));
1111 To_Stderr (Tailored_Exception_Information (Excep.all));
1112 end Trace_Unhandled_Exception_In_Task;
1114 ------------------------------------
1115 -- Vulnerable_Complete_Activation --
1116 ------------------------------------
1118 -- As in several other places, the locks of the activator and activated
1119 -- task are both locked here. This follows our deadlock prevention lock
1120 -- ordering policy, since the activated task must be created after the
1123 procedure Vulnerable_Complete_Activation (Self_ID : Task_ID) is
1124 Activator : constant Task_ID := Self_ID.Common.Activator;
1127 pragma Debug (Debug.Trace (Self_ID, "V_Complete_Activation", 'C'));
1129 Write_Lock (Activator);
1130 Write_Lock (Self_ID);
1132 pragma Assert (Self_ID.Common.Activator /= null);
1134 -- Remove dangling reference to Activator, since a task may
1135 -- outlive its activator.
1137 Self_ID.Common.Activator := null;
1139 -- Wake up the activator, if it is waiting for a chain of tasks to
1140 -- activate, and we are the last in the chain to complete activation.
1142 if Activator.Common.State = Activator_Sleep then
1143 Activator.Common.Wait_Count := Activator.Common.Wait_Count - 1;
1145 if Activator.Common.Wait_Count = 0 then
1146 Wakeup (Activator, Activator_Sleep);
1150 -- The activator raises a Tasking_Error if any task it is activating
1151 -- is completed before the activation is done. However, if the reason
1152 -- for the task completion is an abortion, we do not raise an exception.
1155 if not Self_ID.Callable and then Self_ID.Pending_ATC_Level /= 0 then
1156 Activator.Common.Activation_Failed := True;
1162 -- After the activation, active priority should be the same
1163 -- as base priority. We must unlock the Activator first,
1164 -- though, since it should not wait if we have lower priority.
1166 if Get_Priority (Self_ID) /= Self_ID.Common.Base_Priority then
1167 Write_Lock (Self_ID);
1168 Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
1171 end Vulnerable_Complete_Activation;
1173 --------------------------------
1174 -- Vulnerable_Complete_Master --
1175 --------------------------------
1177 procedure Vulnerable_Complete_Master (Self_ID : Task_ID) is
1180 CM : constant Master_Level := Self_ID.Master_Within;
1181 T : aliased Task_ID;
1183 To_Be_Freed : Task_ID;
1184 -- This is a list of ATCBs to be freed, after we have released
1185 -- all RTS locks. This is necessary because of the locking order
1186 -- rules, since the storage manager uses Global_Task_Lock.
1188 pragma Warnings (Off);
1189 function Check_Unactivated_Tasks return Boolean;
1190 pragma Warnings (On);
1191 -- Temporary error-checking code below. This is part of the checks
1192 -- added in the new run time. Call it only inside a pragma Assert.
1194 -----------------------------
1195 -- Check_Unactivated_Tasks --
1196 -----------------------------
1198 function Check_Unactivated_Tasks return Boolean is
1200 if not Single_Lock then
1204 Write_Lock (Self_ID);
1205 C := All_Tasks_List;
1207 while C /= null loop
1208 if C.Common.Activator = Self_ID then
1212 if C.Common.Parent = Self_ID and then C.Master_of_Task = CM then
1215 if C.Common.State = Unactivated then
1222 C := C.Common.All_Tasks_Link;
1227 if not Single_Lock then
1232 end Check_Unactivated_Tasks;
1234 -- Start of processing for Vulnerable_Complete_Master
1238 (Debug.Trace (Self_ID, "V_Complete_Master", 'C'));
1240 pragma Assert (Self_ID.Common.Wait_Count = 0);
1241 pragma Assert (Self_ID.Deferral_Level > 0);
1243 -- Count how many active dependent tasks this master currently
1244 -- has, and record this in Wait_Count.
1246 -- This count should start at zero, since it is initialized to
1247 -- zero for new tasks, and the task should not exit the
1248 -- sleep-loops that use this count until the count reaches zero.
1251 Write_Lock (Self_ID);
1252 C := All_Tasks_List;
1254 while C /= null loop
1255 if C.Common.Activator = Self_ID then
1256 pragma Assert (C.Common.State = Unactivated);
1259 C.Common.Activator := null;
1260 C.Common.State := Terminated;
1261 C.Callable := False;
1262 Utilities.Cancel_Queued_Entry_Calls (C);
1266 if C.Common.Parent = Self_ID and then C.Master_of_Task = CM then
1269 if C.Awake_Count /= 0 then
1270 Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1;
1276 C := C.Common.All_Tasks_Link;
1279 Self_ID.Common.State := Master_Completion_Sleep;
1282 if not Single_Lock then
1286 -- Wait until dependent tasks are all terminated or ready to terminate.
1287 -- While waiting, the task may be awakened if the task's priority needs
1288 -- changing, or this master is aborted. In the latter case, we want
1289 -- to abort the dependents, and resume waiting until Wait_Count goes
1292 Write_Lock (Self_ID);
1295 Initialization.Poll_Base_Priority_Change (Self_ID);
1296 exit when Self_ID.Common.Wait_Count = 0;
1298 -- Here is a difference as compared to Complete_Master
1300 if Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
1301 and then not Self_ID.Dependents_Aborted
1304 Abort_Dependents (Self_ID);
1308 Abort_Dependents (Self_ID);
1310 Write_Lock (Self_ID);
1313 Sleep (Self_ID, Master_Completion_Sleep);
1317 Self_ID.Common.State := Runnable;
1320 -- Dependents are all terminated or on terminate alternatives.
1321 -- Now, force those on terminate alternatives to terminate, by
1324 pragma Assert (Check_Unactivated_Tasks);
1326 if Self_ID.Alive_Count > 1 then
1328 -- Consider finding a way to skip the following extra steps if there
1329 -- are no dependents with terminate alternatives. This could be done
1330 -- by adding another count to the ATCB, similar to Awake_Count, but
1331 -- keeping track of tasks that are on terminate alternatives.
1333 pragma Assert (Self_ID.Common.Wait_Count = 0);
1335 -- Force any remaining dependents to terminate, by aborting them.
1337 if not Single_Lock then
1341 Abort_Dependents (Self_ID);
1343 -- Above, when we "abort" the dependents we are simply using this
1344 -- operation for convenience. We are not required to support the full
1345 -- abort-statement semantics; in particular, we are not required to
1346 -- immediately cancel any queued or in-service entry calls. That is
1347 -- good, because if we tried to cancel a call we would need to lock
1348 -- the caller, in order to wake the caller up. Our anti-deadlock
1349 -- rules prevent us from doing that without releasing the locks on C
1350 -- and Self_ID. Releasing and retaking those locks would be wasteful
1351 -- at best, and should not be considered further without more
1352 -- detailed analysis of potential concurrent accesses to the
1353 -- ATCBs of C and Self_ID.
1355 -- Count how many "alive" dependent tasks this master currently
1356 -- has, and record this in Wait_Count. This count should start at
1357 -- zero, since it is initialized to zero for new tasks, and the
1358 -- task should not exit the sleep-loops that use this count until
1359 -- the count reaches zero.
1361 pragma Assert (Self_ID.Common.Wait_Count = 0);
1363 Write_Lock (Self_ID);
1364 C := All_Tasks_List;
1366 while C /= null loop
1367 if C.Common.Parent = Self_ID and then C.Master_of_Task = CM then
1370 pragma Assert (C.Awake_Count = 0);
1372 if C.Alive_Count > 0 then
1373 pragma Assert (C.Terminate_Alternative);
1374 Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1;
1380 C := C.Common.All_Tasks_Link;
1383 Self_ID.Common.State := Master_Phase_2_Sleep;
1386 if not Single_Lock then
1390 -- Wait for all counted tasks to finish terminating themselves.
1392 Write_Lock (Self_ID);
1395 Initialization.Poll_Base_Priority_Change (Self_ID);
1396 exit when Self_ID.Common.Wait_Count = 0;
1397 Sleep (Self_ID, Master_Phase_2_Sleep);
1400 Self_ID.Common.State := Runnable;
1404 -- We don't wake up for abortion here. We are already terminating
1405 -- just as fast as we can, so there is no point.
1407 -- Remove terminated tasks from the list of Self_ID's dependents, but
1408 -- don't free their ATCBs yet, because of lock order restrictions,
1409 -- which don't allow us to call "free" or "malloc" while holding any
1410 -- other locks. Instead, we put those ATCBs to be freed onto a
1411 -- temporary list, called To_Be_Freed.
1413 if not Single_Lock then
1417 C := All_Tasks_List;
1420 while C /= null loop
1421 if C.Common.Parent = Self_ID and then C.Master_of_Task >= CM then
1423 P.Common.All_Tasks_Link := C.Common.All_Tasks_Link;
1425 All_Tasks_List := C.Common.All_Tasks_Link;
1428 T := C.Common.All_Tasks_Link;
1429 C.Common.All_Tasks_Link := To_Be_Freed;
1435 C := C.Common.All_Tasks_Link;
1441 -- Free all the ATCBs on the list To_Be_Freed.
1443 -- The ATCBs in the list are no longer in All_Tasks_List, and after
1444 -- any interrupt entries are detached from them they should no longer
1447 -- Global_Task_Lock (Task_Lock/Unlock) is locked in the loop below to
1448 -- avoid a race between a terminating task and its parent. The parent
1449 -- might try to deallocate the ACTB out from underneath the exiting
1450 -- task. Note that Free will also lock Global_Task_Lock, but that is
1451 -- OK, since this is the *one* lock for which we have a mechanism to
1452 -- support nested locking. See Task_Wrapper and its finalizer for more
1456 -- The check "T.Common.Parent /= null ..." below is to prevent dangling
1457 -- references to terminated library-level tasks, which could
1458 -- otherwise occur during finalization of library-level objects.
1459 -- A better solution might be to hook task objects into the
1460 -- finalization chain and deallocate the ATCB when the task
1461 -- object is deallocated. However, this change is not likely
1462 -- to gain anything significant, since all this storage should
1463 -- be recovered en-masse when the process exits.
1465 while To_Be_Freed /= null loop
1467 To_Be_Freed := T.Common.All_Tasks_Link;
1469 -- ??? On SGI there is currently no Interrupt_Manager, that's
1470 -- why we need to check if the Interrupt_Manager_ID is null
1472 if T.Interrupt_Entry and Interrupt_Manager_ID /= null then
1474 Detach_Interrupt_Entries_Index : constant Task_Entry_Index := 1;
1475 -- Corresponds to the entry index of System.Interrupts.
1476 -- Interrupt_Manager.Detach_Interrupt_Entries.
1477 -- Be sure to update this value when changing
1478 -- Interrupt_Manager specs.
1480 type Param_Type is access all Task_ID;
1482 Param : aliased Param_Type := T'Access;
1485 System.Tasking.Rendezvous.Call_Simple
1486 (Interrupt_Manager_ID, Detach_Interrupt_Entries_Index,
1491 if (T.Common.Parent /= null
1492 and then T.Common.Parent.Common.Parent /= null)
1493 or else T.Master_of_Task > 3
1495 Initialization.Task_Lock (Self_ID);
1497 -- If Sec_Stack_Addr is not null, it means that Destroy_TSD
1498 -- has not been called yet (case of an unactivated task).
1500 if T.Common.Compiler_Data.Sec_Stack_Addr /= Null_Address then
1501 SSL.Destroy_TSD (T.Common.Compiler_Data);
1504 Vulnerable_Free_Task (T);
1505 Initialization.Task_Unlock (Self_ID);
1509 -- It might seem nice to let the terminated task deallocate its own
1510 -- ATCB. That would not cover the case of unactivated tasks. It also
1511 -- would force us to keep the underlying thread around past termination,
1512 -- since references to the ATCB are possible past termination.
1513 -- Currently, we get rid of the thread as soon as the task terminates,
1514 -- and let the parent recover the ATCB later.
1516 -- Some day, if we want to recover the ATCB earlier, at task
1517 -- termination, we could consider using "fat task IDs", that include the
1518 -- serial number with the ATCB pointer, to catch references to tasks
1519 -- that no longer have ATCBs. It is not clear how much this would gain,
1520 -- since the user-level task object would still be occupying storage.
1522 -- Make next master level up active.
1523 -- We don't need to lock the ATCB, since the value is only updated by
1524 -- each task for itself.
1526 Self_ID.Master_Within := CM - 1;
1527 end Vulnerable_Complete_Master;
1529 ------------------------------
1530 -- Vulnerable_Complete_Task --
1531 ------------------------------
1533 -- Complete the calling task
1535 -- This procedure must be called with abort deferred. (That's why the
1536 -- name has "Vulnerable" in it.) It should only be called by Complete_Task
1537 -- and Finalize_Global_Tasks (for the environment task).
1539 -- The effect is similar to that of Complete_Master. Differences include
1540 -- the closing of entries here, and computation of the number of active
1541 -- dependent tasks in Complete_Master.
1543 -- We don't lock Self_ID before the call to Vulnerable_Complete_Activation,
1544 -- because that does its own locking, and because we do not need the lock
1545 -- to test Self_ID.Common.Activator. That value should only be read and
1546 -- modified by Self.
1548 procedure Vulnerable_Complete_Task (Self_ID : Task_ID) is
1550 pragma Assert (Self_ID.Deferral_Level > 0);
1551 pragma Assert (Self_ID = Self);
1552 pragma Assert (Self_ID.Master_Within = Self_ID.Master_of_Task + 1
1554 Self_ID.Master_Within = Self_ID.Master_of_Task + 2);
1555 pragma Assert (Self_ID.Common.Wait_Count = 0);
1556 pragma Assert (Self_ID.Open_Accepts = null);
1557 pragma Assert (Self_ID.ATC_Nesting_Level = 1);
1559 pragma Debug (Debug.Trace (Self_ID, "V_Complete_Task", 'C'));
1565 Write_Lock (Self_ID);
1566 Self_ID.Callable := False;
1568 -- In theory, Self should have no pending entry calls left on its
1569 -- call-stack. Each async. select statement should clean its own call,
1570 -- and blocking entry calls should defer abort until the calls are
1571 -- cancelled, then clean up.
1573 Utilities.Cancel_Queued_Entry_Calls (Self_ID);
1576 if Self_ID.Common.Activator /= null then
1577 Vulnerable_Complete_Activation (Self_ID);
1584 -- If Self_ID.Master_Within = Self_ID.Master_of_Task + 2
1585 -- we may have dependent tasks for which we need to wait.
1586 -- Otherwise, we can just exit.
1588 if Self_ID.Master_Within = Self_ID.Master_of_Task + 2 then
1589 Vulnerable_Complete_Master (Self_ID);
1591 end Vulnerable_Complete_Task;
1593 --------------------------
1594 -- Vulnerable_Free_Task --
1595 --------------------------
1597 -- Recover all runtime system storage associated with the task T.
1598 -- This should only be called after T has terminated and will no
1599 -- longer be referenced.
1601 -- For tasks created by an allocator that fails, due to an exception,
1602 -- it is called from Expunge_Unactivated_Tasks.
1604 -- For tasks created by elaboration of task object declarations it
1605 -- is called from the finalization code of the Task_Wrapper procedure.
1606 -- It is also called from Unchecked_Deallocation, for objects that
1607 -- are or contain tasks.
1609 procedure Vulnerable_Free_Task (T : Task_ID) is
1611 pragma Debug (Debug.Trace (Self, "Vulnerable_Free_Task", 'C', T));
1618 Initialization.Finalize_Attributes_Link.all (T);
1625 System.Task_Primitives.Operations.Finalize_TCB (T);
1626 end Vulnerable_Free_Task;
1629 -- Establish the Adafinal softlink.
1631 -- This is not done inside the central RTS initialization routine
1632 -- to avoid with-ing this package from System.Tasking.Initialization.
1634 SSL.Adafinal := Finalize_Global_Tasks'Access;
1636 -- Establish soft links for subprograms that manipulate master_id's.
1637 -- This cannot be done when the RTS is initialized, because of various
1638 -- elaboration constraints.
1640 SSL.Current_Master := Stages.Current_Master'Access;
1641 SSL.Enter_Master := Stages.Enter_Master'Access;
1642 SSL.Complete_Master := Stages.Complete_Master'Access;
1643 end System.Tasking.Stages;