2005-12-29 Paul Brook <paul@codesourcery.com>
[official-gcc.git] / gcc / ada / s-tassta.adb
blob4ceea414a6d09391c609665e24864800ac791478
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
4 -- --
5 -- S Y S T E M . T A S K I N G . S T A G E S --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2005, Free Software Foundation, Inc. --
10 -- --
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, 51 Franklin Street, Fifth Floor, --
20 -- Boston, MA 02110-1301, USA. --
21 -- --
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. --
28 -- --
29 -- GNARL was developed by the GNARL team at Florida State University. --
30 -- Extensive contributions were provided by Ada Core Technologies, Inc. --
31 -- --
32 ------------------------------------------------------------------------------
34 pragma Polling (Off);
35 -- Turn off polling, we do not want ATC polling to take place during
36 -- tasking operations. It causes infinite loops and other problems.
38 with Ada.Exceptions;
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;
48 -- Used for Size_Type
49 -- Single_Lock
50 -- Runtime_Traces
52 with System.Task_Info;
53 -- Used for Task_Info_Type
55 with System.Task_Primitives.Operations;
56 -- Used for Finalize_Lock
57 -- Enter_Task
58 -- Write_Lock
59 -- Unlock
60 -- Sleep
61 -- Wakeup
62 -- Get_Priority
63 -- Lock/Unlock_RTS
64 -- New_ATCB
66 with System.Soft_Links;
67 -- These are procedure pointers to non-tasking routines that use task
68 -- specific data. In the absence of tasking, these routines refer to global
69 -- data. In the presense of tasking, they must be replaced with pointers to
70 -- task-specific versions. Also used for Create_TSD, Destroy_TSD,
71 -- Get_Current_Excep, Finalize_Global_List, Task_Termination, Handler.
73 with System.Tasking.Initialization;
74 -- Used for Remove_From_All_Tasks_List
75 -- Defer_Abort
76 -- Undefer_Abort
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
86 -- Abort_One_Task
87 -- Abort_Tasks
89 with System.Tasking.Queuing;
90 -- Used for Dequeue_Head
92 with System.Tasking.Rendezvous;
93 -- Used for Call_Simple
95 with System.OS_Primitives;
96 -- Used for Delay_Modes
98 with System.Secondary_Stack;
99 -- Used for SS_Init
101 with System.Storage_Elements;
102 -- Used for Storage_Array
104 with System.Restrictions;
105 -- Used for Abort_Allowed
107 with System.Standard_Library;
108 -- Used for Exception_Trace
110 with System.Traces.Tasking;
111 -- Used for Send_Trace_Info
113 with Unchecked_Deallocation;
114 -- To recover from failure of ATCB initialization
116 with System.Stack_Usage;
118 package body System.Tasking.Stages is
120 package STPO renames System.Task_Primitives.Operations;
121 package SSL renames System.Soft_Links;
122 package SSE renames System.Storage_Elements;
123 package SST renames System.Secondary_Stack;
125 use Ada.Exceptions;
127 use Parameters;
128 use Task_Primitives;
129 use Task_Primitives.Operations;
130 use Task_Info;
132 use System.Traces;
133 use System.Traces.Tasking;
135 -----------------------
136 -- Local Subprograms --
137 -----------------------
139 procedure Free is new
140 Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id);
142 procedure Trace_Unhandled_Exception_In_Task (Self_Id : Task_Id);
143 -- This procedure outputs the task specific message for exception
144 -- tracing purposes.
146 procedure Task_Wrapper (Self_ID : Task_Id);
147 pragma Convention (C, Task_Wrapper);
148 -- This is the procedure that is called by the GNULL from the new context
149 -- when a task is created. It waits for activation and then calls the task
150 -- body procedure. When the task body procedure completes, it terminates
151 -- the task.
153 -- The Task_Wrapper's address will be provided to the underlying threads
154 -- library as the task entry point. Convention C is what makes most sense
155 -- for that purpose (Export C would make the function globally visible,
156 -- and affect the link name on which GDB depends). This will in addition
157 -- trigger an automatic stack alignment suitable for GCC's assumptions if
158 -- need be.
160 procedure Vulnerable_Complete_Task (Self_ID : Task_Id);
161 -- Complete the calling task. This procedure must be called with
162 -- abort deferred. It should only be called by Complete_Task and
163 -- Finalizate_Global_Tasks (for the environment task).
165 procedure Vulnerable_Complete_Master (Self_ID : Task_Id);
166 -- Complete the current master of the calling task. This procedure
167 -- must be called with abort deferred. It should only be called by
168 -- Vulnerable_Complete_Task and Complete_Master.
170 procedure Vulnerable_Complete_Activation (Self_ID : Task_Id);
171 -- Signal to Self_ID's activator that Self_ID has completed activation.
172 -- This procedure must be called with abort deferred.
174 procedure Abort_Dependents (Self_ID : Task_Id);
175 -- Abort all the direct dependents of Self at its current master
176 -- nesting level, plus all of their dependents, transitively.
177 -- RTS_Lock should be locked by the caller.
179 procedure Vulnerable_Free_Task (T : Task_Id);
180 -- Recover all runtime system storage associated with the task T.
181 -- This should only be called after T has terminated and will no
182 -- longer be referenced.
184 -- For tasks created by an allocator that fails, due to an exception,
185 -- it is called from Expunge_Unactivated_Tasks.
187 -- It is also called from Unchecked_Deallocation, for objects that
188 -- are or contain tasks.
190 -- Different code is used at master completion, in Terminate_Dependents,
191 -- due to a need for tighter synchronization with the master.
193 ----------------------
194 -- Abort_Dependents --
195 ----------------------
197 procedure Abort_Dependents (Self_ID : Task_Id) is
198 C : Task_Id;
199 P : Task_Id;
201 begin
202 C := All_Tasks_List;
203 while C /= null loop
204 P := C.Common.Parent;
205 while P /= null loop
206 if P = Self_ID then
208 -- ??? C is supposed to take care of its own dependents, so
209 -- there should be no need to worry about them. Need to double
210 -- check this.
212 if C.Master_of_Task = Self_ID.Master_Within then
213 Utilities.Abort_One_Task (Self_ID, C);
214 C.Dependents_Aborted := True;
215 end if;
217 exit;
218 end if;
220 P := P.Common.Parent;
221 end loop;
223 C := C.Common.All_Tasks_Link;
224 end loop;
226 Self_ID.Dependents_Aborted := True;
227 end Abort_Dependents;
229 -----------------
230 -- Abort_Tasks --
231 -----------------
233 procedure Abort_Tasks (Tasks : Task_List) is
234 begin
235 Utilities.Abort_Tasks (Tasks);
236 end Abort_Tasks;
238 --------------------
239 -- Activate_Tasks --
240 --------------------
242 -- Note that locks of activator and activated task are both locked
243 -- here. This is necessary because C.Common.State and
244 -- Self.Common.Wait_Count have to be synchronized. This is safe from
245 -- deadlock because the activator is always created before the activated
246 -- task. That satisfies our in-order-of-creation ATCB locking policy.
248 -- At one point, we may also lock the parent, if the parent is
249 -- different from the activator. That is also consistent with the
250 -- lock ordering policy, since the activator cannot be created
251 -- before the parent.
253 -- Since we are holding both the activator's lock, and Task_Wrapper
254 -- locks that before it does anything more than initialize the
255 -- low-level ATCB components, it should be safe to wait to update
256 -- the counts until we see that the thread creation is successful.
258 -- If the thread creation fails, we do need to close the entries
259 -- of the task. The first phase, of dequeuing calls, only requires
260 -- locking the acceptor's ATCB, but the waking up of the callers
261 -- requires locking the caller's ATCB. We cannot safely do this
262 -- while we are holding other locks. Therefore, the queue-clearing
263 -- operation is done in a separate pass over the activation chain.
265 procedure Activate_Tasks (Chain_Access : Activation_Chain_Access) is
266 Self_ID : constant Task_Id := STPO.Self;
267 P : Task_Id;
268 C : Task_Id;
269 Next_C, Last_C : Task_Id;
270 Activate_Prio : System.Any_Priority;
271 Success : Boolean;
272 All_Elaborated : Boolean := True;
274 begin
275 -- If pragma Detect_Blocking is active, then we must check whether this
276 -- potentially blocking operation is called from a protected action.
278 if System.Tasking.Detect_Blocking
279 and then Self_ID.Common.Protected_Action_Nesting > 0
280 then
281 Ada.Exceptions.Raise_Exception
282 (Program_Error'Identity, "potentially blocking operation");
283 end if;
285 pragma Debug
286 (Debug.Trace (Self_ID, "Activate_Tasks", 'C'));
288 Initialization.Defer_Abort_Nestable (Self_ID);
290 pragma Assert (Self_ID.Common.Wait_Count = 0);
292 -- Lock RTS_Lock, to prevent activated tasks from racing ahead before
293 -- we finish activating the chain.
295 Lock_RTS;
297 -- Check that all task bodies have been elaborated
299 C := Chain_Access.T_ID;
300 Last_C := null;
301 while C /= null loop
302 if C.Common.Elaborated /= null
303 and then not C.Common.Elaborated.all
304 then
305 All_Elaborated := False;
306 end if;
308 -- Reverse the activation chain so that tasks are
309 -- activated in the same order they're declared.
311 Next_C := C.Common.Activation_Link;
312 C.Common.Activation_Link := Last_C;
313 Last_C := C;
314 C := Next_C;
315 end loop;
317 Chain_Access.T_ID := Last_C;
319 if not All_Elaborated then
320 Unlock_RTS;
321 Initialization.Undefer_Abort_Nestable (Self_ID);
322 Raise_Exception
323 (Program_Error'Identity, "Some tasks have not been elaborated");
324 end if;
326 -- Activate all the tasks in the chain. Creation of the thread of
327 -- control was deferred until activation. So create it now.
329 C := Chain_Access.T_ID;
330 while C /= null loop
331 if C.Common.State /= Terminated then
332 pragma Assert (C.Common.State = Unactivated);
334 P := C.Common.Parent;
335 Write_Lock (P);
336 Write_Lock (C);
338 if C.Common.Base_Priority < Get_Priority (Self_ID) then
339 Activate_Prio := Get_Priority (Self_ID);
340 else
341 Activate_Prio := C.Common.Base_Priority;
342 end if;
344 System.Task_Primitives.Operations.Create_Task
345 (C, Task_Wrapper'Address,
346 Parameters.Size_Type
347 (C.Common.Compiler_Data.Pri_Stack_Info.Size),
348 Activate_Prio, Success);
350 -- There would be a race between the created task and the
351 -- creator to do the following initialization, if we did not
352 -- have a Lock/Unlock_RTS pair in the task wrapper to prevent
353 -- it from racing ahead.
355 if Success then
356 C.Common.State := Runnable;
357 C.Awake_Count := 1;
358 C.Alive_Count := 1;
359 P.Awake_Count := P.Awake_Count + 1;
360 P.Alive_Count := P.Alive_Count + 1;
362 if P.Common.State = Master_Completion_Sleep and then
363 C.Master_of_Task = P.Master_Within
364 then
365 pragma Assert (Self_ID /= P);
366 P.Common.Wait_Count := P.Common.Wait_Count + 1;
367 end if;
369 Unlock (C);
370 Unlock (P);
372 else
373 -- No need to set Awake_Count, State, etc. here since the loop
374 -- below will do that for any Unactivated tasks.
376 Unlock (C);
377 Unlock (P);
378 Self_ID.Common.Activation_Failed := True;
379 end if;
380 end if;
382 C := C.Common.Activation_Link;
383 end loop;
385 if not Single_Lock then
386 Unlock_RTS;
387 end if;
389 -- Close the entries of any tasks that failed thread creation,
390 -- and count those that have not finished activation.
392 Write_Lock (Self_ID);
393 Self_ID.Common.State := Activator_Sleep;
395 C := Chain_Access.T_ID;
396 while C /= null loop
397 Write_Lock (C);
399 if C.Common.State = Unactivated then
400 C.Common.Activator := null;
401 C.Common.State := Terminated;
402 C.Callable := False;
403 Utilities.Cancel_Queued_Entry_Calls (C);
405 elsif C.Common.Activator /= null then
406 Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1;
407 end if;
409 Unlock (C);
410 P := C.Common.Activation_Link;
411 C.Common.Activation_Link := null;
412 C := P;
413 end loop;
415 -- Wait for the activated tasks to complete activation. It is
416 -- unsafe to abort any of these tasks until the count goes to zero.
418 loop
419 Initialization.Poll_Base_Priority_Change (Self_ID);
420 exit when Self_ID.Common.Wait_Count = 0;
421 Sleep (Self_ID, Activator_Sleep);
422 end loop;
424 Self_ID.Common.State := Runnable;
425 Unlock (Self_ID);
427 if Single_Lock then
428 Unlock_RTS;
429 end if;
431 -- Remove the tasks from the chain
433 Chain_Access.T_ID := null;
434 Initialization.Undefer_Abort_Nestable (Self_ID);
436 if Self_ID.Common.Activation_Failed then
437 Self_ID.Common.Activation_Failed := False;
438 Raise_Exception (Tasking_Error'Identity,
439 "Failure during activation");
440 end if;
441 end Activate_Tasks;
443 -------------------------
444 -- Complete_Activation --
445 -------------------------
447 procedure Complete_Activation is
448 Self_ID : constant Task_Id := STPO.Self;
450 begin
451 Initialization.Defer_Abort_Nestable (Self_ID);
453 if Single_Lock then
454 Lock_RTS;
455 end if;
457 Vulnerable_Complete_Activation (Self_ID);
459 if Single_Lock then
460 Unlock_RTS;
461 end if;
463 Initialization.Undefer_Abort_Nestable (Self_ID);
465 -- ???
466 -- Why do we need to allow for nested deferral here?
468 if Runtime_Traces then
469 Send_Trace_Info (T_Activate);
470 end if;
471 end Complete_Activation;
473 ---------------------
474 -- Complete_Master --
475 ---------------------
477 procedure Complete_Master is
478 Self_ID : constant Task_Id := STPO.Self;
479 begin
480 pragma Assert (Self_ID.Deferral_Level > 0);
481 Vulnerable_Complete_Master (Self_ID);
482 end Complete_Master;
484 -------------------
485 -- Complete_Task --
486 -------------------
488 -- See comments on Vulnerable_Complete_Task for details
490 procedure Complete_Task is
491 Self_ID : constant Task_Id := STPO.Self;
493 begin
494 pragma Assert (Self_ID.Deferral_Level > 0);
496 Vulnerable_Complete_Task (Self_ID);
498 -- All of our dependents have terminated. Never undefer abort again!
500 end Complete_Task;
502 -----------------
503 -- Create_Task --
504 -----------------
506 -- Compiler interface only. Do not call from within the RTS.
507 -- This must be called to create a new task.
509 procedure Create_Task
510 (Priority : Integer;
511 Size : System.Parameters.Size_Type;
512 Task_Info : System.Task_Info.Task_Info_Type;
513 Num_Entries : Task_Entry_Index;
514 Master : Master_Level;
515 State : Task_Procedure_Access;
516 Discriminants : System.Address;
517 Elaborated : Access_Boolean;
518 Chain : in out Activation_Chain;
519 Task_Image : String;
520 Created_Task : out Task_Id)
522 T, P : Task_Id;
523 Self_ID : constant Task_Id := STPO.Self;
524 Success : Boolean;
525 Base_Priority : System.Any_Priority;
526 Len : Natural;
528 begin
529 -- If pragma Detect_Blocking is active must be checked whether
530 -- this potentially blocking operation is called from a
531 -- protected action.
533 if System.Tasking.Detect_Blocking
534 and then Self_ID.Common.Protected_Action_Nesting > 0
535 then
536 Ada.Exceptions.Raise_Exception
537 (Program_Error'Identity, "potentially blocking operation");
538 end if;
540 pragma Debug
541 (Debug.Trace (Self_ID, "Create_Task", 'C'));
543 if Priority = Unspecified_Priority then
544 Base_Priority := Self_ID.Common.Base_Priority;
545 else
546 Base_Priority := System.Any_Priority (Priority);
547 end if;
549 -- Find parent P of new Task, via master level number
551 P := Self_ID;
553 if P /= null then
554 while P.Master_of_Task >= Master loop
555 P := P.Common.Parent;
556 exit when P = null;
557 end loop;
558 end if;
560 Initialization.Defer_Abort_Nestable (Self_ID);
562 begin
563 T := New_ATCB (Num_Entries);
564 exception
565 when others =>
566 Initialization.Undefer_Abort_Nestable (Self_ID);
567 Raise_Exception (Storage_Error'Identity, "Cannot allocate task");
568 end;
570 -- RTS_Lock is used by Abort_Dependents and Abort_Tasks.
571 -- Up to this point, it is possible that we may be part of
572 -- a family of tasks that is being aborted.
574 Lock_RTS;
575 Write_Lock (Self_ID);
577 -- Now, we must check that we have not been aborted.
578 -- If so, we should give up on creating this task,
579 -- and simply return.
581 if not Self_ID.Callable then
582 pragma Assert (Self_ID.Pending_ATC_Level = 0);
583 pragma Assert (Self_ID.Pending_Action);
584 pragma Assert
585 (Chain.T_ID = null or else Chain.T_ID.Common.State = Unactivated);
587 Unlock (Self_ID);
588 Unlock_RTS;
589 Initialization.Undefer_Abort_Nestable (Self_ID);
591 -- ??? Should never get here
593 pragma Assert (False);
594 raise Standard'Abort_Signal;
595 end if;
597 Initialize_ATCB (Self_ID, State, Discriminants, P, Elaborated,
598 Base_Priority, Task_Info, Size, T, Success);
600 if not Success then
601 Free (T);
602 Unlock (Self_ID);
603 Unlock_RTS;
604 Initialization.Undefer_Abort_Nestable (Self_ID);
605 Raise_Exception
606 (Storage_Error'Identity, "Failed to initialize task");
607 end if;
609 T.Master_of_Task := Master;
610 T.Master_Within := T.Master_of_Task + 1;
612 for L in T.Entry_Calls'Range loop
613 T.Entry_Calls (L).Self := T;
614 T.Entry_Calls (L).Level := L;
615 end loop;
617 if Task_Image'Length = 0 then
618 T.Common.Task_Image_Len := 0;
619 else
620 Len := 1;
621 T.Common.Task_Image (1) := Task_Image (Task_Image'First);
623 -- Remove unwanted blank space generated by 'Image
625 for J in Task_Image'First + 1 .. Task_Image'Last loop
626 if Task_Image (J) /= ' '
627 or else Task_Image (J - 1) /= '('
628 then
629 Len := Len + 1;
630 T.Common.Task_Image (Len) := Task_Image (J);
631 exit when Len = T.Common.Task_Image'Last;
632 end if;
633 end loop;
635 T.Common.Task_Image_Len := Len;
636 end if;
638 Unlock (Self_ID);
639 Unlock_RTS;
641 -- Create TSD as early as possible in the creation of a task, since it
642 -- may be used by the operation of Ada code within the task.
644 SSL.Create_TSD (T.Common.Compiler_Data);
645 T.Common.Activation_Link := Chain.T_ID;
646 Chain.T_ID := T;
647 Initialization.Initialize_Attributes_Link.all (T);
648 Created_Task := T;
649 Initialization.Undefer_Abort_Nestable (Self_ID);
651 if Runtime_Traces then
652 Send_Trace_Info (T_Create, T);
653 end if;
654 end Create_Task;
656 --------------------
657 -- Current_Master --
658 --------------------
660 function Current_Master return Master_Level is
661 begin
662 return STPO.Self.Master_Within;
663 end Current_Master;
665 ------------------
666 -- Enter_Master --
667 ------------------
669 procedure Enter_Master is
670 Self_ID : constant Task_Id := STPO.Self;
671 begin
672 Self_ID.Master_Within := Self_ID.Master_Within + 1;
673 end Enter_Master;
675 -------------------------------
676 -- Expunge_Unactivated_Tasks --
677 -------------------------------
679 -- See procedure Close_Entries for the general case
681 procedure Expunge_Unactivated_Tasks (Chain : in out Activation_Chain) is
682 Self_ID : constant Task_Id := STPO.Self;
683 C : Task_Id;
684 Call : Entry_Call_Link;
685 Temp : Task_Id;
687 begin
688 pragma Debug
689 (Debug.Trace (Self_ID, "Expunge_Unactivated_Tasks", 'C'));
691 Initialization.Defer_Abort_Nestable (Self_ID);
693 -- ???
694 -- Experimentation has shown that abort is sometimes (but not
695 -- always) already deferred when this is called.
697 -- That may indicate an error. Find out what is going on
699 C := Chain.T_ID;
700 while C /= null loop
701 pragma Assert (C.Common.State = Unactivated);
703 Temp := C.Common.Activation_Link;
705 if C.Common.State = Unactivated then
706 Lock_RTS;
707 Write_Lock (C);
709 for J in 1 .. C.Entry_Num loop
710 Queuing.Dequeue_Head (C.Entry_Queues (J), Call);
711 pragma Assert (Call = null);
712 end loop;
714 Unlock (C);
716 Initialization.Remove_From_All_Tasks_List (C);
717 Unlock_RTS;
719 Vulnerable_Free_Task (C);
720 C := Temp;
721 end if;
722 end loop;
724 Chain.T_ID := null;
725 Initialization.Undefer_Abort_Nestable (Self_ID);
726 end Expunge_Unactivated_Tasks;
728 ---------------------------
729 -- Finalize_Global_Tasks --
730 ---------------------------
732 -- ???
733 -- We have a potential problem here if finalization of global
734 -- objects does anything with signals or the timer server, since
735 -- by that time those servers have terminated.
737 -- It is hard to see how that would occur
739 -- However, a better solution might be to do all this finalization
740 -- using the global finalization chain.
742 procedure Finalize_Global_Tasks is
743 Self_ID : constant Task_Id := STPO.Self;
744 Ignore : Boolean;
746 begin
747 if Self_ID.Deferral_Level = 0 then
748 -- ???
749 -- In principle, we should be able to predict whether
750 -- abort is already deferred here (and it should not be deferred
751 -- yet but in practice it seems Finalize_Global_Tasks is being
752 -- called sometimes, from RTS code for exceptions, with abort already
753 -- deferred.
755 Initialization.Defer_Abort_Nestable (Self_ID);
757 -- Never undefer again!!!
758 end if;
760 -- This code is only executed by the environment task
762 pragma Assert (Self_ID = Environment_Task);
764 -- Set Environment_Task'Callable to false to notify library-level tasks
765 -- that it is waiting for them (cf 5619-003).
767 Self_ID.Callable := False;
769 -- Exit level 2 master, for normal tasks in library-level packages
771 Complete_Master;
773 -- Force termination of "independent" library-level server tasks
775 Lock_RTS;
777 Abort_Dependents (Self_ID);
779 if not Single_Lock then
780 Unlock_RTS;
781 end if;
783 -- We need to explicitely wait for the task to be terminated here
784 -- because on true concurrent system, we may end this procedure
785 -- before the tasks are really terminated.
787 Write_Lock (Self_ID);
789 loop
790 exit when Utilities.Independent_Task_Count = 0;
792 -- We used to yield here, but this did not take into account
793 -- low priority tasks that would cause dead lock in some cases.
794 -- See 8126-020.
796 Timed_Sleep
797 (Self_ID, 0.01, System.OS_Primitives.Relative,
798 Self_ID.Common.State, Ignore, Ignore);
799 end loop;
801 -- ??? On multi-processor environments, it seems that the above loop
802 -- isn't sufficient, so we need to add an additional delay.
804 Timed_Sleep
805 (Self_ID, 0.01, System.OS_Primitives.Relative,
806 Self_ID.Common.State, Ignore, Ignore);
808 Unlock (Self_ID);
810 if Single_Lock then
811 Unlock_RTS;
812 end if;
814 -- Complete the environment task
816 Vulnerable_Complete_Task (Self_ID);
818 -- Handle normal task termination by the environment task, but only
819 -- for the normal task termination. In the case of Abnormal and
820 -- Unhandled_Exception they must have been handled before, and the
821 -- task termination soft link must have been changed so the task
822 -- termination routine is not executed twice.
824 SSL.Task_Termination_Handler.all (Ada.Exceptions.Null_Occurrence);
826 -- Finalize the global list for controlled objects if needed
828 SSL.Finalize_Global_List.all;
830 -- Reset the soft links to non-tasking
832 SSL.Abort_Defer := SSL.Abort_Defer_NT'Access;
833 SSL.Abort_Undefer := SSL.Abort_Undefer_NT'Access;
834 SSL.Lock_Task := SSL.Task_Lock_NT'Access;
835 SSL.Unlock_Task := SSL.Task_Unlock_NT'Access;
836 SSL.Get_Jmpbuf_Address := SSL.Get_Jmpbuf_Address_NT'Access;
837 SSL.Set_Jmpbuf_Address := SSL.Set_Jmpbuf_Address_NT'Access;
838 SSL.Get_Sec_Stack_Addr := SSL.Get_Sec_Stack_Addr_NT'Access;
839 SSL.Set_Sec_Stack_Addr := SSL.Set_Sec_Stack_Addr_NT'Access;
840 SSL.Check_Abort_Status := SSL.Check_Abort_Status_NT'Access;
841 SSL.Get_Stack_Info := SSL.Get_Stack_Info_NT'Access;
843 -- Don't bother trying to finalize Initialization.Global_Task_Lock
844 -- and System.Task_Primitives.RTS_Lock.
846 end Finalize_Global_Tasks;
848 ---------------
849 -- Free_Task --
850 ---------------
852 procedure Free_Task (T : Task_Id) is
853 Self_Id : constant Task_Id := Self;
855 begin
856 if T.Common.State = Terminated then
858 -- It is not safe to call Abort_Defer or Write_Lock at this stage
860 Initialization.Task_Lock (Self_Id);
862 Lock_RTS;
863 Initialization.Remove_From_All_Tasks_List (T);
864 Unlock_RTS;
866 Initialization.Task_Unlock (Self_Id);
868 System.Task_Primitives.Operations.Finalize_TCB (T);
870 -- If the task is not terminated, then we simply ignore the call. This
871 -- happens when a user program attempts an unchecked deallocation on
872 -- a non-terminated task.
874 else
875 null;
876 end if;
877 end Free_Task;
879 ------------------
880 -- Task_Wrapper --
881 ------------------
883 -- The task wrapper is a procedure that is called first for each task
884 -- task body, and which in turn calls the compiler-generated task body
885 -- procedure. The wrapper's main job is to do initialization for the task.
886 -- It also has some locally declared objects that server as per-task local
887 -- data. Task finalization is done by Complete_Task, which is called from
888 -- an at-end handler that the compiler generates.
890 procedure Task_Wrapper (Self_ID : Task_Id) is
891 use type System.Parameters.Size_Type;
892 use type SSE.Storage_Offset;
893 use System.Standard_Library;
894 use System.Stack_Usage;
896 Bottom_Of_Stack : aliased Integer;
898 Secondary_Stack_Size :
899 constant SSE.Storage_Offset :=
900 Self_ID.Common.Compiler_Data.Pri_Stack_Info.Size *
901 SSE.Storage_Offset (Parameters.Sec_Stack_Ratio) / 100;
903 Secondary_Stack :
904 aliased SSE.Storage_Array
905 (1 .. Secondary_Stack_Size);
907 pragma Warnings (Off);
908 Secondary_Stack_Address : System.Address := Secondary_Stack'Address;
910 Overflow_Guard : constant := 16#1_000#;
912 Size :
913 Natural := Natural (Self_ID.Common.Compiler_Data.Pri_Stack_Info.Size);
915 pragma Warnings (On);
916 -- Address of secondary stack. In the fixed secondary stack case, this
917 -- value is not modified, causing a warning, hence the bracketing with
918 -- Warnings (Off/On).
920 SEH_Table : aliased SSE.Storage_Array (1 .. 8);
921 -- Structured Exception Registration table (2 words)
923 procedure Install_SEH_Handler (Addr : System.Address);
924 pragma Import (C, Install_SEH_Handler, "__gnat_install_SEH_handler");
925 -- Install the SEH (Structured Exception Handling) handler
927 Cause : Cause_Of_Termination := Normal;
928 -- Indicates the reason why this task terminates. Normal corresponds to
929 -- a task terminating due to completing the last statement of its body,
930 -- or as a result of waiting on a terminate alternative. If the task
931 -- terminates because it is being aborted then Cause will be set to
932 -- Abnormal. If the task terminates because of an exception raised by
933 -- the execution of its task body, then Cause is set to
934 -- Unhandled_Exception.
936 EO : Exception_Occurrence;
937 -- If the task terminates because of an exception raised by the
938 -- execution of its task body, then EO will contain the associated
939 -- exception occurrence. Otherwise, it will contain Null_Occurrence.
941 procedure Search_Fall_Back_Handler (ID : Task_Id);
942 -- Procedure that searches recursively a fall-back handler through the
943 -- master relationship.
945 procedure Search_Fall_Back_Handler (ID : Task_Id) is
946 begin
947 -- If there is a fall back handler, execute it
949 if ID.Common.Fall_Back_Handler /= null then
950 ID.Common.Fall_Back_Handler.all (Cause, Self_ID, EO);
952 -- Otherwise look for a fall back handler in the parent
954 elsif ID.Common.Parent /= null then
955 Search_Fall_Back_Handler (ID.Common.Parent);
957 -- Otherwise, do nothing
959 else
960 return;
961 end if;
962 end Search_Fall_Back_Handler;
964 begin
965 pragma Assert (Self_ID.Deferral_Level = 1);
967 if not Parameters.Sec_Stack_Dynamic then
968 Self_ID.Common.Compiler_Data.Sec_Stack_Addr :=
969 Secondary_Stack'Address;
970 SST.SS_Init (Secondary_Stack_Address, Integer (Secondary_Stack'Last));
971 Size := Size - Natural (Secondary_Stack_Size);
972 end if;
974 Size := Size - Overflow_Guard;
976 if System.Stack_Usage.Is_Enabled then
977 STPO.Lock_RTS;
978 Initialize_Analyzer (Self_ID.Common.Analyzer,
979 Self_ID.Common.Task_Image
980 (1 .. Self_ID.Common.Task_Image_Len),
981 Size,
982 SSE.To_Integer (Bottom_Of_Stack'Address));
983 STPO.Unlock_RTS;
984 Fill_Stack (Self_ID.Common.Analyzer);
985 end if;
987 -- Set the guard page at the bottom of the stack. The call to unprotect
988 -- the page is done in Terminate_Task
990 Stack_Guard (Self_ID, True);
992 -- Initialize low-level TCB components, that cannot be initialized
993 -- by the creator. Enter_Task sets Self_ID.Known_Tasks_Index and
994 -- also Self_ID.LL.Thread
996 Enter_Task (Self_ID);
998 -- We setup the SEH (Structured Exception Handling) handler if supported
999 -- on the target.
1001 Install_SEH_Handler (SEH_Table'Address);
1003 -- Initialize exception occurrence
1005 Save_Occurrence (EO, Ada.Exceptions.Null_Occurrence);
1007 -- We lock RTS_Lock to wait for activator to finish activating the rest
1008 -- of the chain, so that everyone in the chain comes out in priority
1009 -- order.
1011 -- This also protects the value of
1012 -- Self_ID.Common.Activator.Common.Wait_Count.
1014 Lock_RTS;
1015 Unlock_RTS;
1017 if not System.Restrictions.Abort_Allowed then
1019 -- If Abort is not allowed, reset the deferral level since it will
1020 -- not get changed by the generated code. Keeping a default value
1021 -- of one would prevent some operations (e.g. select or delay) to
1022 -- proceed successfully.
1024 Self_ID.Deferral_Level := 0;
1025 end if;
1027 begin
1028 -- We are separating the following portion of the code in order to
1029 -- place the exception handlers in a different block. In this way,
1030 -- we do not call Set_Jmpbuf_Address (which needs Self) before we
1031 -- set Self in Enter_Task
1033 -- Call the task body procedure
1035 -- The task body is called with abort still deferred. That
1036 -- eliminates a dangerous window, for which we had to patch-up in
1037 -- Terminate_Task.
1039 -- During the expansion of the task body, we insert an RTS-call
1040 -- to Abort_Undefer, at the first point where abort should be
1041 -- allowed.
1043 Self_ID.Common.Task_Entry_Point (Self_ID.Common.Task_Arg);
1044 Initialization.Defer_Abort_Nestable (Self_ID);
1046 exception
1047 -- We can't call Terminate_Task in the exception handlers below,
1048 -- since there may be (e.g. in the case of GCC exception handling)
1049 -- clean ups associated with the exception handler that need to
1050 -- access task specific data.
1052 -- Defer abort so that this task can't be aborted while exiting
1054 when Standard'Abort_Signal =>
1055 Initialization.Defer_Abort_Nestable (Self_ID);
1057 -- Update the cause that motivated the task termination so that
1058 -- the appropriate information is passed to the task termination
1059 -- procedure. Task termination as a result of waiting on a
1060 -- terminate alternative is a normal termination, although it is
1061 -- implemented using the abort mechanisms.
1063 if Self_ID.Terminate_Alternative then
1064 Cause := Normal;
1065 else
1066 Cause := Abnormal;
1067 end if;
1068 when others =>
1069 -- ??? Using an E : others here causes CD2C11A to fail on
1070 -- DEC Unix, see 7925-005.
1072 Initialization.Defer_Abort_Nestable (Self_ID);
1074 -- Perform the task specific exception tracing duty. We handle
1075 -- these outputs here and not in the common notification routine
1076 -- because we need access to tasking related data and we don't
1077 -- want to drag dependencies against tasking related units in the
1078 -- the common notification units. Additionally, no trace is ever
1079 -- triggered from the common routine for the Unhandled_Raise case
1080 -- in tasks, since an exception never appears unhandled in this
1081 -- context because of this handler.
1083 if Exception_Trace = Unhandled_Raise then
1084 Trace_Unhandled_Exception_In_Task (Self_ID);
1085 end if;
1087 -- Update the cause that motivated the task termination so that
1088 -- the appropriate information is passed to the task termination
1089 -- procedure, as well as the associated Exception_Occurrence.
1091 Cause := Unhandled_Exception;
1092 Save_Occurrence (EO, SSL.Get_Current_Excep.all.all);
1093 end;
1095 -- Look for a task termination handler. This code is for all tasks but
1096 -- the environment task. The task termination code for the environment
1097 -- task is executed by SSL.Task_Termination_Handler.
1099 if Self_ID.Common.Specific_Handler /= null then
1100 Self_ID.Common.Specific_Handler.all (Cause, Self_ID, EO);
1101 else
1102 -- Look for a fall-back handler following the master relationship
1103 -- for the task.
1105 Search_Fall_Back_Handler (Self_ID);
1106 end if;
1108 if System.Stack_Usage.Is_Enabled then
1109 Compute_Result (Self_ID.Common.Analyzer);
1110 Report_Result (Self_ID.Common.Analyzer);
1111 end if;
1113 Terminate_Task (Self_ID);
1114 end Task_Wrapper;
1116 --------------------
1117 -- Terminate_Task --
1118 --------------------
1120 -- Before we allow the thread to exit, we must clean up. This is a
1121 -- a delicate job. We must wake up the task's master, who may immediately
1122 -- try to deallocate the ATCB out from under the current task WHILE IT IS
1123 -- STILL EXECUTING.
1125 -- To avoid this, the parent task must be blocked up to the latest
1126 -- statement executed. The trouble is that we have another step that we
1127 -- also want to postpone to the very end, i.e., calling SSL.Destroy_TSD.
1128 -- We have to postpone that until the end because compiler-generated code
1129 -- is likely to try to access that data at just about any point.
1131 -- We can't call Destroy_TSD while we are holding any other locks, because
1132 -- it locks Global_Task_Lock, and our deadlock prevention rules require
1133 -- that to be the outermost lock. Our first "solution" was to just lock
1134 -- Global_Task_Lock in addition to the other locks, and force the parent to
1135 -- also lock this lock between its wakeup and its freeing of the ATCB. See
1136 -- Complete_Task for the parent-side of the code that has the matching
1137 -- calls to Task_Lock and Task_Unlock. That was not really a solution,
1138 -- since the operation Task_Unlock continued to access the ATCB after
1139 -- unlocking, after which the parent was observed to race ahead, deallocate
1140 -- the ATCB, and then reallocate it to another task. The call to
1141 -- Undefer_Abortion in Task_Unlock by the "terminated" task was overwriting
1142 -- the data of the new task that reused the ATCB! To solve this problem, we
1143 -- introduced the new operation Final_Task_Unlock.
1145 procedure Terminate_Task (Self_ID : Task_Id) is
1146 Environment_Task : constant Task_Id := STPO.Environment_Task;
1147 Master_of_Task : Integer;
1149 begin
1150 Debug.Task_Termination_Hook;
1152 if Runtime_Traces then
1153 Send_Trace_Info (T_Terminate);
1154 end if;
1156 -- Since GCC cannot allocate stack chunks efficiently without reordering
1157 -- some of the allocations, we have to handle this unexpected situation
1158 -- here. We should normally never have to call Vulnerable_Complete_Task
1159 -- here. See 6602-003 for more details.
1161 if Self_ID.Common.Activator /= null then
1162 Vulnerable_Complete_Task (Self_ID);
1163 end if;
1165 Initialization.Task_Lock (Self_ID);
1167 if Single_Lock then
1168 Lock_RTS;
1169 end if;
1171 Master_of_Task := Self_ID.Master_of_Task;
1173 -- Check if the current task is an independent task If so, decrement
1174 -- the Independent_Task_Count value.
1176 if Master_of_Task = 2 then
1177 if Single_Lock then
1178 Utilities.Independent_Task_Count :=
1179 Utilities.Independent_Task_Count - 1;
1180 else
1181 Write_Lock (Environment_Task);
1182 Utilities.Independent_Task_Count :=
1183 Utilities.Independent_Task_Count - 1;
1184 Unlock (Environment_Task);
1185 end if;
1186 end if;
1188 -- Unprotect the guard page if needed
1190 Stack_Guard (Self_ID, False);
1192 Utilities.Make_Passive (Self_ID, Task_Completed => True);
1194 if Single_Lock then
1195 Unlock_RTS;
1196 end if;
1198 pragma Assert (Check_Exit (Self_ID));
1200 SSL.Destroy_TSD (Self_ID.Common.Compiler_Data);
1201 Initialization.Final_Task_Unlock (Self_ID);
1203 -- WARNING: past this point, this thread must assume that the ATCB
1204 -- has been deallocated. It should not be accessed again.
1206 if Master_of_Task > 0 then
1207 STPO.Exit_Task;
1208 end if;
1209 end Terminate_Task;
1211 ----------------
1212 -- Terminated --
1213 ----------------
1215 function Terminated (T : Task_Id) return Boolean is
1216 Self_ID : constant Task_Id := STPO.Self;
1217 Result : Boolean;
1219 begin
1220 Initialization.Defer_Abort_Nestable (Self_ID);
1222 if Single_Lock then
1223 Lock_RTS;
1224 end if;
1226 Write_Lock (T);
1227 Result := T.Common.State = Terminated;
1228 Unlock (T);
1230 if Single_Lock then
1231 Unlock_RTS;
1232 end if;
1234 Initialization.Undefer_Abort_Nestable (Self_ID);
1235 return Result;
1236 end Terminated;
1238 ----------------------------------------
1239 -- Trace_Unhandled_Exception_In_Task --
1240 ----------------------------------------
1242 procedure Trace_Unhandled_Exception_In_Task (Self_Id : Task_Id) is
1243 procedure To_Stderr (S : String);
1244 pragma Import (Ada, To_Stderr, "__gnat_to_stderr");
1246 use System.Soft_Links;
1247 use System.Standard_Library;
1249 function To_Address is new
1250 Unchecked_Conversion (Task_Id, System.Address);
1252 function Tailored_Exception_Information
1253 (E : Exception_Occurrence) return String;
1254 pragma Import
1255 (Ada, Tailored_Exception_Information,
1256 "__gnat_tailored_exception_information");
1258 Excep : constant Exception_Occurrence_Access :=
1259 SSL.Get_Current_Excep.all;
1261 begin
1262 -- This procedure is called by the task outermost handler in
1263 -- Task_Wrapper below, so only once the task stack has been fully
1264 -- unwound. The common notification routine has been called at the
1265 -- raise point already.
1267 To_Stderr ("task ");
1269 if Self_Id.Common.Task_Image_Len /= 0 then
1270 To_Stderr
1271 (Self_Id.Common.Task_Image (1 .. Self_Id.Common.Task_Image_Len));
1272 To_Stderr ("_");
1273 end if;
1275 To_Stderr (System.Address_Image (To_Address (Self_Id)));
1276 To_Stderr (" terminated by unhandled exception");
1277 To_Stderr ((1 => ASCII.LF));
1278 To_Stderr (Tailored_Exception_Information (Excep.all));
1279 end Trace_Unhandled_Exception_In_Task;
1281 ------------------------------------
1282 -- Vulnerable_Complete_Activation --
1283 ------------------------------------
1285 -- As in several other places, the locks of the activator and activated
1286 -- task are both locked here. This follows our deadlock prevention lock
1287 -- ordering policy, since the activated task must be created after the
1288 -- activator.
1290 procedure Vulnerable_Complete_Activation (Self_ID : Task_Id) is
1291 Activator : constant Task_Id := Self_ID.Common.Activator;
1293 begin
1294 pragma Debug (Debug.Trace (Self_ID, "V_Complete_Activation", 'C'));
1296 Write_Lock (Activator);
1297 Write_Lock (Self_ID);
1299 pragma Assert (Self_ID.Common.Activator /= null);
1301 -- Remove dangling reference to Activator, since a task may
1302 -- outlive its activator.
1304 Self_ID.Common.Activator := null;
1306 -- Wake up the activator, if it is waiting for a chain of tasks to
1307 -- activate, and we are the last in the chain to complete activation.
1309 if Activator.Common.State = Activator_Sleep then
1310 Activator.Common.Wait_Count := Activator.Common.Wait_Count - 1;
1312 if Activator.Common.Wait_Count = 0 then
1313 Wakeup (Activator, Activator_Sleep);
1314 end if;
1315 end if;
1317 -- The activator raises a Tasking_Error if any task it is activating
1318 -- is completed before the activation is done. However, if the reason
1319 -- for the task completion is an abort, we do not raise an exception.
1320 -- See RM 9.2(5).
1322 if not Self_ID.Callable and then Self_ID.Pending_ATC_Level /= 0 then
1323 Activator.Common.Activation_Failed := True;
1324 end if;
1326 Unlock (Self_ID);
1327 Unlock (Activator);
1329 -- After the activation, active priority should be the same
1330 -- as base priority. We must unlock the Activator first,
1331 -- though, since it should not wait if we have lower priority.
1333 if Get_Priority (Self_ID) /= Self_ID.Common.Base_Priority then
1334 Write_Lock (Self_ID);
1335 Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
1336 Unlock (Self_ID);
1337 end if;
1338 end Vulnerable_Complete_Activation;
1340 --------------------------------
1341 -- Vulnerable_Complete_Master --
1342 --------------------------------
1344 procedure Vulnerable_Complete_Master (Self_ID : Task_Id) is
1345 C : Task_Id;
1346 P : Task_Id;
1347 CM : constant Master_Level := Self_ID.Master_Within;
1348 T : aliased Task_Id;
1350 To_Be_Freed : Task_Id;
1351 -- This is a list of ATCBs to be freed, after we have released
1352 -- all RTS locks. This is necessary because of the locking order
1353 -- rules, since the storage manager uses Global_Task_Lock.
1355 pragma Warnings (Off);
1356 function Check_Unactivated_Tasks return Boolean;
1357 pragma Warnings (On);
1358 -- Temporary error-checking code below. This is part of the checks
1359 -- added in the new run time. Call it only inside a pragma Assert.
1361 -----------------------------
1362 -- Check_Unactivated_Tasks --
1363 -----------------------------
1365 function Check_Unactivated_Tasks return Boolean is
1366 begin
1367 if not Single_Lock then
1368 Lock_RTS;
1369 end if;
1371 Write_Lock (Self_ID);
1373 C := All_Tasks_List;
1374 while C /= null loop
1375 if C.Common.Activator = Self_ID then
1376 return False;
1377 end if;
1379 if C.Common.Parent = Self_ID and then C.Master_of_Task = CM then
1380 Write_Lock (C);
1382 if C.Common.State = Unactivated then
1383 return False;
1384 end if;
1386 Unlock (C);
1387 end if;
1389 C := C.Common.All_Tasks_Link;
1390 end loop;
1392 Unlock (Self_ID);
1394 if not Single_Lock then
1395 Unlock_RTS;
1396 end if;
1398 return True;
1399 end Check_Unactivated_Tasks;
1401 -- Start of processing for Vulnerable_Complete_Master
1403 begin
1404 pragma Debug
1405 (Debug.Trace (Self_ID, "V_Complete_Master", 'C'));
1407 pragma Assert (Self_ID.Common.Wait_Count = 0);
1408 pragma Assert (Self_ID.Deferral_Level > 0);
1410 -- Count how many active dependent tasks this master currently
1411 -- has, and record this in Wait_Count.
1413 -- This count should start at zero, since it is initialized to
1414 -- zero for new tasks, and the task should not exit the
1415 -- sleep-loops that use this count until the count reaches zero.
1417 Lock_RTS;
1418 Write_Lock (Self_ID);
1420 C := All_Tasks_List;
1421 while C /= null loop
1422 if C.Common.Activator = Self_ID then
1423 pragma Assert (C.Common.State = Unactivated);
1425 Write_Lock (C);
1426 C.Common.Activator := null;
1427 C.Common.State := Terminated;
1428 C.Callable := False;
1429 Utilities.Cancel_Queued_Entry_Calls (C);
1430 Unlock (C);
1431 end if;
1433 if C.Common.Parent = Self_ID and then C.Master_of_Task = CM then
1434 Write_Lock (C);
1436 if C.Awake_Count /= 0 then
1437 Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1;
1438 end if;
1440 Unlock (C);
1441 end if;
1443 C := C.Common.All_Tasks_Link;
1444 end loop;
1446 Self_ID.Common.State := Master_Completion_Sleep;
1447 Unlock (Self_ID);
1449 if not Single_Lock then
1450 Unlock_RTS;
1451 end if;
1453 -- Wait until dependent tasks are all terminated or ready to terminate.
1454 -- While waiting, the task may be awakened if the task's priority needs
1455 -- changing, or this master is aborted. In the latter case, we want
1456 -- to abort the dependents, and resume waiting until Wait_Count goes
1457 -- to zero.
1459 Write_Lock (Self_ID);
1461 loop
1462 Initialization.Poll_Base_Priority_Change (Self_ID);
1463 exit when Self_ID.Common.Wait_Count = 0;
1465 -- Here is a difference as compared to Complete_Master
1467 if Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
1468 and then not Self_ID.Dependents_Aborted
1469 then
1470 if Single_Lock then
1471 Abort_Dependents (Self_ID);
1472 else
1473 Unlock (Self_ID);
1474 Lock_RTS;
1475 Abort_Dependents (Self_ID);
1476 Unlock_RTS;
1477 Write_Lock (Self_ID);
1478 end if;
1479 else
1480 Sleep (Self_ID, Master_Completion_Sleep);
1481 end if;
1482 end loop;
1484 Self_ID.Common.State := Runnable;
1485 Unlock (Self_ID);
1487 -- Dependents are all terminated or on terminate alternatives.
1488 -- Now, force those on terminate alternatives to terminate, by
1489 -- aborting them.
1491 pragma Assert (Check_Unactivated_Tasks);
1493 if Self_ID.Alive_Count > 1 then
1494 -- ???
1495 -- Consider finding a way to skip the following extra steps if there
1496 -- are no dependents with terminate alternatives. This could be done
1497 -- by adding another count to the ATCB, similar to Awake_Count, but
1498 -- keeping track of tasks that are on terminate alternatives.
1500 pragma Assert (Self_ID.Common.Wait_Count = 0);
1502 -- Force any remaining dependents to terminate by aborting them
1504 if not Single_Lock then
1505 Lock_RTS;
1506 end if;
1508 Abort_Dependents (Self_ID);
1510 -- Above, when we "abort" the dependents we are simply using this
1511 -- operation for convenience. We are not required to support the full
1512 -- abort-statement semantics; in particular, we are not required to
1513 -- immediately cancel any queued or in-service entry calls. That is
1514 -- good, because if we tried to cancel a call we would need to lock
1515 -- the caller, in order to wake the caller up. Our anti-deadlock
1516 -- rules prevent us from doing that without releasing the locks on C
1517 -- and Self_ID. Releasing and retaking those locks would be wasteful
1518 -- at best, and should not be considered further without more
1519 -- detailed analysis of potential concurrent accesses to the
1520 -- ATCBs of C and Self_ID.
1522 -- Count how many "alive" dependent tasks this master currently
1523 -- has, and record this in Wait_Count. This count should start at
1524 -- zero, since it is initialized to zero for new tasks, and the
1525 -- task should not exit the sleep-loops that use this count until
1526 -- the count reaches zero.
1528 pragma Assert (Self_ID.Common.Wait_Count = 0);
1530 Write_Lock (Self_ID);
1532 C := All_Tasks_List;
1533 while C /= null loop
1534 if C.Common.Parent = Self_ID and then C.Master_of_Task = CM then
1535 Write_Lock (C);
1537 pragma Assert (C.Awake_Count = 0);
1539 if C.Alive_Count > 0 then
1540 pragma Assert (C.Terminate_Alternative);
1541 Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1;
1542 end if;
1544 Unlock (C);
1545 end if;
1547 C := C.Common.All_Tasks_Link;
1548 end loop;
1550 Self_ID.Common.State := Master_Phase_2_Sleep;
1551 Unlock (Self_ID);
1553 if not Single_Lock then
1554 Unlock_RTS;
1555 end if;
1557 -- Wait for all counted tasks to finish terminating themselves
1559 Write_Lock (Self_ID);
1561 loop
1562 Initialization.Poll_Base_Priority_Change (Self_ID);
1563 exit when Self_ID.Common.Wait_Count = 0;
1564 Sleep (Self_ID, Master_Phase_2_Sleep);
1565 end loop;
1567 Self_ID.Common.State := Runnable;
1568 Unlock (Self_ID);
1569 end if;
1571 -- We don't wake up for abort here. We are already terminating just as
1572 -- fast as we can, so there is no point.
1574 -- Remove terminated tasks from the list of Self_ID's dependents, but
1575 -- don't free their ATCBs yet, because of lock order restrictions,
1576 -- which don't allow us to call "free" or "malloc" while holding any
1577 -- other locks. Instead, we put those ATCBs to be freed onto a
1578 -- temporary list, called To_Be_Freed.
1580 if not Single_Lock then
1581 Lock_RTS;
1582 end if;
1584 C := All_Tasks_List;
1585 P := null;
1586 while C /= null loop
1587 if C.Common.Parent = Self_ID and then C.Master_of_Task >= CM then
1588 if P /= null then
1589 P.Common.All_Tasks_Link := C.Common.All_Tasks_Link;
1590 else
1591 All_Tasks_List := C.Common.All_Tasks_Link;
1592 end if;
1594 T := C.Common.All_Tasks_Link;
1595 C.Common.All_Tasks_Link := To_Be_Freed;
1596 To_Be_Freed := C;
1597 C := T;
1599 else
1600 P := C;
1601 C := C.Common.All_Tasks_Link;
1602 end if;
1603 end loop;
1605 Unlock_RTS;
1607 -- Free all the ATCBs on the list To_Be_Freed
1609 -- The ATCBs in the list are no longer in All_Tasks_List, and after
1610 -- any interrupt entries are detached from them they should no longer
1611 -- be referenced.
1613 -- Global_Task_Lock (Task_Lock/Unlock) is locked in the loop below to
1614 -- avoid a race between a terminating task and its parent. The parent
1615 -- might try to deallocate the ACTB out from underneath the exiting
1616 -- task. Note that Free will also lock Global_Task_Lock, but that is
1617 -- OK, since this is the *one* lock for which we have a mechanism to
1618 -- support nested locking. See Task_Wrapper and its finalizer for more
1619 -- explanation.
1621 -- ???
1622 -- The check "T.Common.Parent /= null ..." below is to prevent dangling
1623 -- references to terminated library-level tasks, which could
1624 -- otherwise occur during finalization of library-level objects.
1625 -- A better solution might be to hook task objects into the
1626 -- finalization chain and deallocate the ATCB when the task
1627 -- object is deallocated. However, this change is not likely
1628 -- to gain anything significant, since all this storage should
1629 -- be recovered en-masse when the process exits.
1631 while To_Be_Freed /= null loop
1632 T := To_Be_Freed;
1633 To_Be_Freed := T.Common.All_Tasks_Link;
1635 -- ??? On SGI there is currently no Interrupt_Manager, that's
1636 -- why we need to check if the Interrupt_Manager_ID is null
1638 if T.Interrupt_Entry and Interrupt_Manager_ID /= null then
1639 declare
1640 Detach_Interrupt_Entries_Index : constant Task_Entry_Index := 1;
1641 -- Corresponds to the entry index of System.Interrupts.
1642 -- Interrupt_Manager.Detach_Interrupt_Entries.
1643 -- Be sure to update this value when changing
1644 -- Interrupt_Manager specs.
1646 type Param_Type is access all Task_Id;
1648 Param : aliased Param_Type := T'Access;
1650 begin
1651 System.Tasking.Rendezvous.Call_Simple
1652 (Interrupt_Manager_ID, Detach_Interrupt_Entries_Index,
1653 Param'Address);
1654 end;
1655 end if;
1657 if (T.Common.Parent /= null
1658 and then T.Common.Parent.Common.Parent /= null)
1659 or else T.Master_of_Task > 3
1660 then
1661 Initialization.Task_Lock (Self_ID);
1663 -- If Sec_Stack_Addr is not null, it means that Destroy_TSD
1664 -- has not been called yet (case of an unactivated task).
1666 if T.Common.Compiler_Data.Sec_Stack_Addr /= Null_Address then
1667 SSL.Destroy_TSD (T.Common.Compiler_Data);
1668 end if;
1670 Vulnerable_Free_Task (T);
1671 Initialization.Task_Unlock (Self_ID);
1672 end if;
1673 end loop;
1675 -- It might seem nice to let the terminated task deallocate its own
1676 -- ATCB. That would not cover the case of unactivated tasks. It also
1677 -- would force us to keep the underlying thread around past termination,
1678 -- since references to the ATCB are possible past termination.
1679 -- Currently, we get rid of the thread as soon as the task terminates,
1680 -- and let the parent recover the ATCB later.
1682 -- Some day, if we want to recover the ATCB earlier, at task
1683 -- termination, we could consider using "fat task IDs", that include the
1684 -- serial number with the ATCB pointer, to catch references to tasks
1685 -- that no longer have ATCBs. It is not clear how much this would gain,
1686 -- since the user-level task object would still be occupying storage.
1688 -- Make next master level up active.
1689 -- We don't need to lock the ATCB, since the value is only updated by
1690 -- each task for itself.
1692 Self_ID.Master_Within := CM - 1;
1693 end Vulnerable_Complete_Master;
1695 ------------------------------
1696 -- Vulnerable_Complete_Task --
1697 ------------------------------
1699 -- Complete the calling task
1701 -- This procedure must be called with abort deferred. (That's why the
1702 -- name has "Vulnerable" in it.) It should only be called by Complete_Task
1703 -- and Finalize_Global_Tasks (for the environment task).
1705 -- The effect is similar to that of Complete_Master. Differences include
1706 -- the closing of entries here, and computation of the number of active
1707 -- dependent tasks in Complete_Master.
1709 -- We don't lock Self_ID before the call to Vulnerable_Complete_Activation,
1710 -- because that does its own locking, and because we do not need the lock
1711 -- to test Self_ID.Common.Activator. That value should only be read and
1712 -- modified by Self.
1714 procedure Vulnerable_Complete_Task (Self_ID : Task_Id) is
1715 begin
1716 pragma Assert (Self_ID.Deferral_Level > 0);
1717 pragma Assert (Self_ID = Self);
1718 pragma Assert (Self_ID.Master_Within = Self_ID.Master_of_Task + 1
1719 or else
1720 Self_ID.Master_Within = Self_ID.Master_of_Task + 2);
1721 pragma Assert (Self_ID.Common.Wait_Count = 0);
1722 pragma Assert (Self_ID.Open_Accepts = null);
1723 pragma Assert (Self_ID.ATC_Nesting_Level = 1);
1725 pragma Debug (Debug.Trace (Self_ID, "V_Complete_Task", 'C'));
1727 if Single_Lock then
1728 Lock_RTS;
1729 end if;
1731 Write_Lock (Self_ID);
1732 Self_ID.Callable := False;
1734 -- In theory, Self should have no pending entry calls left on its
1735 -- call-stack. Each async. select statement should clean its own call,
1736 -- and blocking entry calls should defer abort until the calls are
1737 -- cancelled, then clean up.
1739 Utilities.Cancel_Queued_Entry_Calls (Self_ID);
1740 Unlock (Self_ID);
1742 if Self_ID.Common.Activator /= null then
1743 Vulnerable_Complete_Activation (Self_ID);
1744 end if;
1746 if Single_Lock then
1747 Unlock_RTS;
1748 end if;
1750 -- If Self_ID.Master_Within = Self_ID.Master_of_Task + 2
1751 -- we may have dependent tasks for which we need to wait.
1752 -- Otherwise, we can just exit.
1754 if Self_ID.Master_Within = Self_ID.Master_of_Task + 2 then
1755 Vulnerable_Complete_Master (Self_ID);
1756 end if;
1757 end Vulnerable_Complete_Task;
1759 --------------------------
1760 -- Vulnerable_Free_Task --
1761 --------------------------
1763 -- Recover all runtime system storage associated with the task T.
1764 -- This should only be called after T has terminated and will no
1765 -- longer be referenced.
1767 -- For tasks created by an allocator that fails, due to an exception,
1768 -- it is called from Expunge_Unactivated_Tasks.
1770 -- For tasks created by elaboration of task object declarations it
1771 -- is called from the finalization code of the Task_Wrapper procedure.
1772 -- It is also called from Unchecked_Deallocation, for objects that
1773 -- are or contain tasks.
1775 procedure Vulnerable_Free_Task (T : Task_Id) is
1776 begin
1777 pragma Debug (Debug.Trace (Self, "Vulnerable_Free_Task", 'C', T));
1779 if Single_Lock then
1780 Lock_RTS;
1781 end if;
1783 Write_Lock (T);
1784 Initialization.Finalize_Attributes_Link.all (T);
1785 Unlock (T);
1787 if Single_Lock then
1788 Unlock_RTS;
1789 end if;
1791 System.Task_Primitives.Operations.Finalize_TCB (T);
1792 end Vulnerable_Free_Task;
1794 -- Package elaboration code
1796 begin
1797 -- Establish the Adafinal softlink
1799 -- This is not done inside the central RTS initialization routine
1800 -- to avoid with-ing this package from System.Tasking.Initialization.
1802 SSL.Adafinal := Finalize_Global_Tasks'Access;
1804 -- Establish soft links for subprograms that manipulate master_id's.
1805 -- This cannot be done when the RTS is initialized, because of various
1806 -- elaboration constraints.
1808 SSL.Current_Master := Stages.Current_Master'Access;
1809 SSL.Enter_Master := Stages.Enter_Master'Access;
1810 SSL.Complete_Master := Stages.Complete_Master'Access;
1811 end System.Tasking.Stages;