1 ------------------------------------------------------------------------------
3 -- GNAT 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-2013, 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 3, or (at your option) any later ver- --
14 -- sion. GNAT 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. --
18 -- As a special exception under Section 7 of GPL version 3, you are granted --
19 -- additional permissions described in the GCC Runtime Library Exception, --
20 -- version 3.1, as published by the Free Software Foundation. --
22 -- You should have received a copy of the GNU General Public License and --
23 -- a copy of the GCC Runtime Library Exception along with this program; --
24 -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
25 -- <http://www.gnu.org/licenses/>. --
27 -- GNARL was developed by the GNARL team at Florida State University. --
28 -- Extensive contributions were provided by Ada Core Technologies, Inc. --
30 ------------------------------------------------------------------------------
33 -- Turn off polling, we do not want ATC polling to take place during tasking
34 -- operations. It causes infinite loops and other problems.
36 pragma Partition_Elaboration_Policy
(Concurrent
);
37 -- This package only implements the concurrent elaboration policy. This pragma
38 -- will enforce it (and detect conflicts with user specified policy).
41 with Ada
.Unchecked_Deallocation
;
43 with System
.Interrupt_Management
;
44 with System
.Tasking
.Debug
;
45 with System
.Address_Image
;
46 with System
.Task_Primitives
;
47 with System
.Task_Primitives
.Operations
;
48 with System
.Tasking
.Utilities
;
49 with System
.Tasking
.Queuing
;
50 with System
.Tasking
.Rendezvous
;
51 with System
.OS_Primitives
;
52 with System
.Secondary_Stack
;
53 with System
.Storage_Elements
;
54 with System
.Restrictions
;
55 with System
.Standard_Library
;
56 with System
.Traces
.Tasking
;
57 with System
.Stack_Usage
;
59 with System
.Soft_Links
;
60 -- These are procedure pointers to non-tasking routines that use task
61 -- specific data. In the absence of tasking, these routines refer to global
62 -- data. In the presence of tasking, they must be replaced with pointers to
63 -- task-specific versions. Also used for Create_TSD, Destroy_TSD, Get_Current
64 -- _Excep, Finalize_Library_Objects, Task_Termination, Handler.
66 with System
.Tasking
.Initialization
;
67 pragma Elaborate_All
(System
.Tasking
.Initialization
);
68 -- This insures that tasking is initialized if any tasks are created
70 package body System
.Tasking
.Stages
is
72 package STPO
renames System
.Task_Primitives
.Operations
;
73 package SSL
renames System
.Soft_Links
;
74 package SSE
renames System
.Storage_Elements
;
75 package SST
renames System
.Secondary_Stack
;
81 use Task_Primitives
.Operations
;
85 use System
.Traces
.Tasking
;
87 -----------------------
88 -- Local Subprograms --
89 -----------------------
92 Ada
.Unchecked_Deallocation
(Ada_Task_Control_Block
, Task_Id
);
94 procedure Trace_Unhandled_Exception_In_Task
(Self_Id
: Task_Id
);
95 -- This procedure outputs the task specific message for exception
98 procedure Task_Wrapper
(Self_ID
: Task_Id
);
99 pragma Convention
(C
, Task_Wrapper
);
100 -- This is the procedure that is called by the GNULL from the new context
101 -- when a task is created. It waits for activation and then calls the task
102 -- body procedure. When the task body procedure completes, it terminates
105 -- The Task_Wrapper's address will be provided to the underlying threads
106 -- library as the task entry point. Convention C is what makes most sense
107 -- for that purpose (Export C would make the function globally visible,
108 -- and affect the link name on which GDB depends). This will in addition
109 -- trigger an automatic stack alignment suitable for GCC's assumptions if
112 -- "Vulnerable_..." in the procedure names below means they must be called
113 -- with abort deferred.
115 procedure Vulnerable_Complete_Task
(Self_ID
: Task_Id
);
116 -- Complete the calling task. This procedure must be called with
117 -- abort deferred. It should only be called by Complete_Task and
118 -- Finalize_Global_Tasks (for the environment task).
120 procedure Vulnerable_Complete_Master
(Self_ID
: Task_Id
);
121 -- Complete the current master of the calling task. This procedure
122 -- must be called with abort deferred. It should only be called by
123 -- Vulnerable_Complete_Task and Complete_Master.
125 procedure Vulnerable_Complete_Activation
(Self_ID
: Task_Id
);
126 -- Signal to Self_ID's activator that Self_ID has completed activation.
127 -- This procedure must be called with abort deferred.
129 procedure Abort_Dependents
(Self_ID
: Task_Id
);
130 -- Abort all the direct dependents of Self at its current master nesting
131 -- level, plus all of their dependents, transitively. RTS_Lock should be
132 -- locked by the caller.
134 procedure Vulnerable_Free_Task
(T
: Task_Id
);
135 -- Recover all runtime system storage associated with the task T. This
136 -- should only be called after T has terminated and will no longer be
139 -- For tasks created by an allocator that fails, due to an exception, it is
140 -- called from Expunge_Unactivated_Tasks.
142 -- Different code is used at master completion, in Terminate_Dependents,
143 -- due to a need for tighter synchronization with the master.
145 ----------------------
146 -- Abort_Dependents --
147 ----------------------
149 procedure Abort_Dependents
(Self_ID
: Task_Id
) is
156 P
:= C
.Common
.Parent
;
160 -- ??? C is supposed to take care of its own dependents, so
161 -- there should be no need to worry about them. Need to double
164 if C
.Master_of_Task
= Self_ID
.Master_Within
then
165 Utilities
.Abort_One_Task
(Self_ID
, C
);
166 C
.Dependents_Aborted
:= True;
172 P
:= P
.Common
.Parent
;
175 C
:= C
.Common
.All_Tasks_Link
;
178 Self_ID
.Dependents_Aborted
:= True;
179 end Abort_Dependents
;
185 procedure Abort_Tasks
(Tasks
: Task_List
) is
187 Utilities
.Abort_Tasks
(Tasks
);
194 -- Note that locks of activator and activated task are both locked here.
195 -- This is necessary because C.Common.State and Self.Common.Wait_Count have
196 -- to be synchronized. This is safe from deadlock because the activator is
197 -- always created before the activated task. That satisfies our
198 -- in-order-of-creation ATCB locking policy.
200 -- At one point, we may also lock the parent, if the parent is different
201 -- from the activator. That is also consistent with the lock ordering
202 -- policy, since the activator cannot be created before the parent.
204 -- Since we are holding both the activator's lock, and Task_Wrapper locks
205 -- that before it does anything more than initialize the low-level ATCB
206 -- components, it should be safe to wait to update the counts until we see
207 -- that the thread creation is successful.
209 -- If the thread creation fails, we do need to close the entries of the
210 -- task. The first phase, of dequeuing calls, only requires locking the
211 -- acceptor's ATCB, but the waking up of the callers requires locking the
212 -- caller's ATCB. We cannot safely do this while we are holding other
213 -- locks. Therefore, the queue-clearing operation is done in a separate
214 -- pass over the activation chain.
216 procedure Activate_Tasks
(Chain_Access
: Activation_Chain_Access
) is
217 Self_ID
: constant Task_Id
:= STPO
.Self
;
220 Next_C
, Last_C
: Task_Id
;
221 Activate_Prio
: System
.Any_Priority
;
223 All_Elaborated
: Boolean := True;
226 -- If pragma Detect_Blocking is active, then we must check whether this
227 -- potentially blocking operation is called from a protected action.
229 if System
.Tasking
.Detect_Blocking
230 and then Self_ID
.Common
.Protected_Action_Nesting
> 0
232 raise Program_Error
with "potentially blocking operation";
236 (Debug
.Trace
(Self_ID
, "Activate_Tasks", 'C'));
238 Initialization
.Defer_Abort_Nestable
(Self_ID
);
240 pragma Assert
(Self_ID
.Common
.Wait_Count
= 0);
242 -- Lock RTS_Lock, to prevent activated tasks from racing ahead before
243 -- we finish activating the chain.
247 -- Check that all task bodies have been elaborated
249 C
:= Chain_Access
.T_ID
;
252 if C
.Common
.Elaborated
/= null
253 and then not C
.Common
.Elaborated
.all
255 All_Elaborated
:= False;
258 -- Reverse the activation chain so that tasks are activated in the
259 -- same order they're declared.
261 Next_C
:= C
.Common
.Activation_Link
;
262 C
.Common
.Activation_Link
:= Last_C
;
267 Chain_Access
.T_ID
:= Last_C
;
269 if not All_Elaborated
then
271 Initialization
.Undefer_Abort_Nestable
(Self_ID
);
272 raise Program_Error
with "Some tasks have not been elaborated";
275 -- Activate all the tasks in the chain. Creation of the thread of
276 -- control was deferred until activation. So create it now.
278 C
:= Chain_Access
.T_ID
;
280 if C
.Common
.State
/= Terminated
then
281 pragma Assert
(C
.Common
.State
= Unactivated
);
283 P
:= C
.Common
.Parent
;
288 (if C
.Common
.Base_Priority
< Get_Priority
(Self_ID
)
289 then Get_Priority
(Self_ID
)
290 else C
.Common
.Base_Priority
);
292 System
.Task_Primitives
.Operations
.Create_Task
293 (C
, Task_Wrapper
'Address,
295 (C
.Common
.Compiler_Data
.Pri_Stack_Info
.Size
),
296 Activate_Prio
, Success
);
298 -- There would be a race between the created task and the creator
299 -- to do the following initialization, if we did not have a
300 -- Lock/Unlock_RTS pair in the task wrapper to prevent it from
304 C
.Common
.State
:= Activating
;
307 P
.Awake_Count
:= P
.Awake_Count
+ 1;
308 P
.Alive_Count
:= P
.Alive_Count
+ 1;
310 if P
.Common
.State
= Master_Completion_Sleep
and then
311 C
.Master_of_Task
= P
.Master_Within
313 pragma Assert
(Self_ID
/= P
);
314 P
.Common
.Wait_Count
:= P
.Common
.Wait_Count
+ 1;
317 for J
in System
.Tasking
.Debug
.Known_Tasks
'Range loop
318 if System
.Tasking
.Debug
.Known_Tasks
(J
) = null then
319 System
.Tasking
.Debug
.Known_Tasks
(J
) := C
;
320 C
.Known_Tasks_Index
:= J
;
325 if Global_Task_Debug_Event_Set
then
326 Debug
.Signal_Debug_Event
327 (Debug
.Debug_Event_Activating
, C
);
330 C
.Common
.State
:= Runnable
;
336 -- No need to set Awake_Count, State, etc. here since the loop
337 -- below will do that for any Unactivated tasks.
341 Self_ID
.Common
.Activation_Failed
:= True;
345 C
:= C
.Common
.Activation_Link
;
348 if not Single_Lock
then
352 -- Close the entries of any tasks that failed thread creation, and count
353 -- those that have not finished activation.
355 Write_Lock
(Self_ID
);
356 Self_ID
.Common
.State
:= Activator_Sleep
;
358 C
:= Chain_Access
.T_ID
;
362 if C
.Common
.State
= Unactivated
then
363 C
.Common
.Activator
:= null;
364 C
.Common
.State
:= Terminated
;
366 Utilities
.Cancel_Queued_Entry_Calls
(C
);
368 elsif C
.Common
.Activator
/= null then
369 Self_ID
.Common
.Wait_Count
:= Self_ID
.Common
.Wait_Count
+ 1;
373 P
:= C
.Common
.Activation_Link
;
374 C
.Common
.Activation_Link
:= null;
378 -- Wait for the activated tasks to complete activation. It is
379 -- unsafe to abort any of these tasks until the count goes to zero.
382 exit when Self_ID
.Common
.Wait_Count
= 0;
383 Sleep
(Self_ID
, Activator_Sleep
);
386 Self_ID
.Common
.State
:= Runnable
;
393 -- Remove the tasks from the chain
395 Chain_Access
.T_ID
:= null;
396 Initialization
.Undefer_Abort_Nestable
(Self_ID
);
398 if Self_ID
.Common
.Activation_Failed
then
399 Self_ID
.Common
.Activation_Failed
:= False;
400 raise Tasking_Error
with "Failure during activation";
404 -------------------------
405 -- Complete_Activation --
406 -------------------------
408 procedure Complete_Activation
is
409 Self_ID
: constant Task_Id
:= STPO
.Self
;
412 Initialization
.Defer_Abort_Nestable
(Self_ID
);
418 Vulnerable_Complete_Activation
(Self_ID
);
424 Initialization
.Undefer_Abort_Nestable
(Self_ID
);
426 -- ??? Why do we need to allow for nested deferral here?
428 if Runtime_Traces
then
429 Send_Trace_Info
(T_Activate
);
431 end Complete_Activation
;
433 ---------------------
434 -- Complete_Master --
435 ---------------------
437 procedure Complete_Master
is
438 Self_ID
: constant Task_Id
:= STPO
.Self
;
441 (Self_ID
.Deferral_Level
> 0
442 or else not System
.Restrictions
.Abort_Allowed
);
443 Vulnerable_Complete_Master
(Self_ID
);
450 -- See comments on Vulnerable_Complete_Task for details
452 procedure Complete_Task
is
453 Self_ID
: constant Task_Id
:= STPO
.Self
;
457 (Self_ID
.Deferral_Level
> 0
458 or else not System
.Restrictions
.Abort_Allowed
);
460 Vulnerable_Complete_Task
(Self_ID
);
462 -- All of our dependents have terminated. Never undefer abort again!
470 -- Compiler interface only. Do not call from within the RTS. This must be
471 -- called to create a new task.
473 procedure Create_Task
475 Size
: System
.Parameters
.Size_Type
;
476 Task_Info
: System
.Task_Info
.Task_Info_Type
;
478 Relative_Deadline
: Ada
.Real_Time
.Time_Span
;
479 Domain
: Dispatching_Domain_Access
;
480 Num_Entries
: Task_Entry_Index
;
481 Master
: Master_Level
;
482 State
: Task_Procedure_Access
;
483 Discriminants
: System
.Address
;
484 Elaborated
: Access_Boolean
;
485 Chain
: in out Activation_Chain
;
487 Created_Task
: out Task_Id
)
490 Self_ID
: constant Task_Id
:= STPO
.Self
;
492 Base_Priority
: System
.Any_Priority
;
494 Base_CPU
: System
.Multiprocessors
.CPU_Range
;
496 use type System
.Multiprocessors
.CPU_Range
;
498 pragma Unreferenced
(Relative_Deadline
);
499 -- EDF scheduling is not supported by any of the target platforms so
500 -- this parameter is not passed any further.
503 -- If Master is greater than the current master, it means that Master
504 -- has already awaited its dependent tasks. This raises Program_Error,
505 -- by 4.8(10.3/2). See AI-280. Ignore this check for foreign threads.
507 if Self_ID
.Master_of_Task
/= Foreign_Task_Level
508 and then Master
> Self_ID
.Master_Within
510 raise Program_Error
with
511 "create task after awaiting termination";
514 -- If pragma Detect_Blocking is active must be checked whether this
515 -- potentially blocking operation is called from a protected action.
517 if System
.Tasking
.Detect_Blocking
518 and then Self_ID
.Common
.Protected_Action_Nesting
> 0
520 raise Program_Error
with "potentially blocking operation";
523 pragma Debug
(Debug
.Trace
(Self_ID
, "Create_Task", 'C'));
526 (if Priority
= Unspecified_Priority
527 then Self_ID
.Common
.Base_Priority
528 else System
.Any_Priority
(Priority
));
530 -- Legal values of CPU are the special Unspecified_CPU value which is
531 -- inserted by the compiler for tasks without CPU aspect, and those in
532 -- the range of CPU_Range but no greater than Number_Of_CPUs. Otherwise
533 -- the task is defined to have failed, and it becomes a completed task
536 if CPU
/= Unspecified_CPU
537 and then (CPU
< Integer (System
.Multiprocessors
.CPU_Range
'First)
539 CPU
> Integer (System
.Multiprocessors
.CPU_Range
'Last)
541 CPU
> Integer (System
.Multiprocessors
.Number_Of_CPUs
))
543 raise Tasking_Error
with "CPU not in range";
545 -- Normal CPU affinity
548 -- When the application code says nothing about the task affinity
549 -- (task without CPU aspect) then the compiler inserts the
550 -- Unspecified_CPU value which indicates to the run-time library that
551 -- the task will activate and execute on the same processor as its
552 -- activating task if the activating task is assigned a processor
556 (if CPU
= Unspecified_CPU
557 then Self_ID
.Common
.Base_CPU
558 else System
.Multiprocessors
.CPU_Range
(CPU
));
561 -- Find parent P of new Task, via master level number
566 while P
.Master_of_Task
>= Master
loop
567 P
:= P
.Common
.Parent
;
572 Initialization
.Defer_Abort_Nestable
(Self_ID
);
575 T
:= New_ATCB
(Num_Entries
);
578 Initialization
.Undefer_Abort_Nestable
(Self_ID
);
579 raise Storage_Error
with "Cannot allocate task";
582 -- RTS_Lock is used by Abort_Dependents and Abort_Tasks. Up to this
583 -- point, it is possible that we may be part of a family of tasks that
587 Write_Lock
(Self_ID
);
589 -- Now, we must check that we have not been aborted. If so, we should
590 -- give up on creating this task, and simply return.
592 if not Self_ID
.Callable
then
593 pragma Assert
(Self_ID
.Pending_ATC_Level
= 0);
594 pragma Assert
(Self_ID
.Pending_Action
);
596 (Chain
.T_ID
= null or else Chain
.T_ID
.Common
.State
= Unactivated
);
600 Initialization
.Undefer_Abort_Nestable
(Self_ID
);
602 -- ??? Should never get here
604 pragma Assert
(False);
605 raise Standard
'Abort_Signal;
608 Initialize_ATCB
(Self_ID
, State
, Discriminants
, P
, Elaborated
,
609 Base_Priority
, Base_CPU
, Domain
, Task_Info
, Size
, T
, Success
);
615 Initialization
.Undefer_Abort_Nestable
(Self_ID
);
616 raise Storage_Error
with "Failed to initialize task";
619 if Master
= Foreign_Task_Level
+ 2 then
621 -- This should not happen, except when a foreign task creates non
622 -- library-level Ada tasks. In this case, we pretend the master is
623 -- a regular library level task, otherwise the run-time will get
624 -- confused when waiting for these tasks to terminate.
626 T
.Master_of_Task
:= Library_Task_Level
;
629 T
.Master_of_Task
:= Master
;
632 T
.Master_Within
:= T
.Master_of_Task
+ 1;
634 for L
in T
.Entry_Calls
'Range loop
635 T
.Entry_Calls
(L
).Self
:= T
;
636 T
.Entry_Calls
(L
).Level
:= L
;
639 if Task_Image
'Length = 0 then
640 T
.Common
.Task_Image_Len
:= 0;
643 T
.Common
.Task_Image
(1) := Task_Image
(Task_Image
'First);
645 -- Remove unwanted blank space generated by 'Image
647 for J
in Task_Image
'First + 1 .. Task_Image
'Last loop
648 if Task_Image
(J
) /= ' '
649 or else Task_Image
(J
- 1) /= '('
652 T
.Common
.Task_Image
(Len
) := Task_Image
(J
);
653 exit when Len
= T
.Common
.Task_Image
'Last;
657 T
.Common
.Task_Image_Len
:= Len
;
660 -- The task inherits the dispatching domain of the parent only if no
661 -- specific domain has been defined in the spec of the task (using the
662 -- dispatching domain pragma or aspect).
664 if T
.Common
.Domain
/= null then
666 elsif T
.Common
.Activator
/= null then
667 T
.Common
.Domain
:= T
.Common
.Activator
.Common
.Domain
;
669 T
.Common
.Domain
:= System
.Tasking
.System_Domain
;
675 -- The CPU associated to the task (if any) must belong to the
676 -- dispatching domain.
678 if Base_CPU
/= System
.Multiprocessors
.Not_A_Specific_CPU
680 (Base_CPU
not in T
.Common
.Domain
'Range
681 or else not T
.Common
.Domain
(Base_CPU
))
683 Initialization
.Undefer_Abort_Nestable
(Self_ID
);
684 raise Tasking_Error
with "CPU not in dispatching domain";
687 -- To handle the interaction between pragma CPU and dispatching domains
688 -- we need to signal that this task is being allocated to a processor.
689 -- This is needed only for tasks belonging to the system domain (the
690 -- creation of new dispatching domains can only take processors from the
691 -- system domain) and only before the environment task calls the main
692 -- procedure (dispatching domains cannot be created after this).
694 if Base_CPU
/= System
.Multiprocessors
.Not_A_Specific_CPU
695 and then T
.Common
.Domain
= System
.Tasking
.System_Domain
696 and then not System
.Tasking
.Dispatching_Domains_Frozen
698 -- Increase the number of tasks attached to the CPU to which this
699 -- task is being moved.
701 Dispatching_Domain_Tasks
(Base_CPU
) :=
702 Dispatching_Domain_Tasks
(Base_CPU
) + 1;
705 -- Create TSD as early as possible in the creation of a task, since it
706 -- may be used by the operation of Ada code within the task.
708 SSL
.Create_TSD
(T
.Common
.Compiler_Data
);
709 T
.Common
.Activation_Link
:= Chain
.T_ID
;
711 Initialization
.Initialize_Attributes_Link
.all (T
);
713 Initialization
.Undefer_Abort_Nestable
(Self_ID
);
715 if Runtime_Traces
then
716 Send_Trace_Info
(T_Create
, T
);
724 function Current_Master
return Master_Level
is
726 return STPO
.Self
.Master_Within
;
733 procedure Enter_Master
is
734 Self_ID
: constant Task_Id
:= STPO
.Self
;
736 Self_ID
.Master_Within
:= Self_ID
.Master_Within
+ 1;
739 -------------------------------
740 -- Expunge_Unactivated_Tasks --
741 -------------------------------
743 -- See procedure Close_Entries for the general case
745 procedure Expunge_Unactivated_Tasks
(Chain
: in out Activation_Chain
) is
746 Self_ID
: constant Task_Id
:= STPO
.Self
;
748 Call
: Entry_Call_Link
;
753 (Debug
.Trace
(Self_ID
, "Expunge_Unactivated_Tasks", 'C'));
755 Initialization
.Defer_Abort_Nestable
(Self_ID
);
758 -- Experimentation has shown that abort is sometimes (but not always)
759 -- already deferred when this is called.
761 -- That may indicate an error. Find out what is going on
765 pragma Assert
(C
.Common
.State
= Unactivated
);
767 Temp
:= C
.Common
.Activation_Link
;
769 if C
.Common
.State
= Unactivated
then
773 for J
in 1 .. C
.Entry_Num
loop
774 Queuing
.Dequeue_Head
(C
.Entry_Queues
(J
), Call
);
775 pragma Assert
(Call
= null);
780 Initialization
.Remove_From_All_Tasks_List
(C
);
783 Vulnerable_Free_Task
(C
);
789 Initialization
.Undefer_Abort_Nestable
(Self_ID
);
790 end Expunge_Unactivated_Tasks
;
792 ---------------------------
793 -- Finalize_Global_Tasks --
794 ---------------------------
797 -- We have a potential problem here if finalization of global objects does
798 -- anything with signals or the timer server, since by that time those
799 -- servers have terminated.
801 -- It is hard to see how that would occur
803 -- However, a better solution might be to do all this finalization
804 -- using the global finalization chain.
806 procedure Finalize_Global_Tasks
is
807 Self_ID
: constant Task_Id
:= STPO
.Self
;
811 pragma Unreferenced
(Ignore_1
, Ignore_2
);
814 (Int
: System
.Interrupt_Management
.Interrupt_ID
) return Character;
815 pragma Import
(C
, State
, "__gnat_get_interrupt_state");
816 -- Get interrupt state for interrupt number Int. Defined in init.c
818 Default
: constant Character := 's';
819 -- 's' Interrupt_State pragma set state to System (use "default"
823 if Self_ID
.Deferral_Level
= 0 then
825 -- In principle, we should be able to predict whether abort is
826 -- already deferred here (and it should not be deferred yet but in
827 -- practice it seems Finalize_Global_Tasks is being called sometimes,
828 -- from RTS code for exceptions, with abort already deferred.
830 Initialization
.Defer_Abort_Nestable
(Self_ID
);
832 -- Never undefer again!!!
835 -- This code is only executed by the environment task
837 pragma Assert
(Self_ID
= Environment_Task
);
839 -- Set Environment_Task'Callable to false to notify library-level tasks
840 -- that it is waiting for them.
842 Self_ID
.Callable
:= False;
844 -- Exit level 2 master, for normal tasks in library-level packages
848 -- Force termination of "independent" library-level server tasks
852 Abort_Dependents
(Self_ID
);
854 if not Single_Lock
then
858 -- We need to explicitly wait for the task to be terminated here
859 -- because on true concurrent system, we may end this procedure before
860 -- the tasks are really terminated.
862 Write_Lock
(Self_ID
);
864 -- If the Abort_Task signal is set to system, it means that we may not
865 -- have been able to abort all independent tasks (in particular
866 -- Server_Task may be blocked, waiting for a signal), in which case,
867 -- do not wait for Independent_Task_Count to go down to 0.
870 (System
.Interrupt_Management
.Abort_Task_Interrupt
) /= Default
873 exit when Utilities
.Independent_Task_Count
= 0;
875 -- We used to yield here, but this did not take into account low
876 -- priority tasks that would cause dead lock in some cases (true
880 (Self_ID
, 0.01, System
.OS_Primitives
.Relative
,
881 Self_ID
.Common
.State
, Ignore_1
, Ignore_2
);
885 -- ??? On multi-processor environments, it seems that the above loop
886 -- isn't sufficient, so we need to add an additional delay.
889 (Self_ID
, 0.01, System
.OS_Primitives
.Relative
,
890 Self_ID
.Common
.State
, Ignore_1
, Ignore_2
);
898 -- Complete the environment task
900 Vulnerable_Complete_Task
(Self_ID
);
902 -- Handle normal task termination by the environment task, but only
903 -- for the normal task termination. In the case of Abnormal and
904 -- Unhandled_Exception they must have been handled before, and the
905 -- task termination soft link must have been changed so the task
906 -- termination routine is not executed twice.
908 SSL
.Task_Termination_Handler
.all (Ada
.Exceptions
.Null_Occurrence
);
910 -- Finalize all library-level controlled objects
912 if not SSL
."=" (SSL
.Finalize_Library_Objects
, null) then
913 SSL
.Finalize_Library_Objects
.all;
916 -- Reset the soft links to non-tasking
918 SSL
.Abort_Defer
:= SSL
.Abort_Defer_NT
'Access;
919 SSL
.Abort_Undefer
:= SSL
.Abort_Undefer_NT
'Access;
920 SSL
.Lock_Task
:= SSL
.Task_Lock_NT
'Access;
921 SSL
.Unlock_Task
:= SSL
.Task_Unlock_NT
'Access;
922 SSL
.Get_Jmpbuf_Address
:= SSL
.Get_Jmpbuf_Address_NT
'Access;
923 SSL
.Set_Jmpbuf_Address
:= SSL
.Set_Jmpbuf_Address_NT
'Access;
924 SSL
.Get_Sec_Stack_Addr
:= SSL
.Get_Sec_Stack_Addr_NT
'Access;
925 SSL
.Set_Sec_Stack_Addr
:= SSL
.Set_Sec_Stack_Addr_NT
'Access;
926 SSL
.Check_Abort_Status
:= SSL
.Check_Abort_Status_NT
'Access;
927 SSL
.Get_Stack_Info
:= SSL
.Get_Stack_Info_NT
'Access;
929 -- Don't bother trying to finalize Initialization.Global_Task_Lock
930 -- and System.Task_Primitives.RTS_Lock.
932 end Finalize_Global_Tasks
;
938 procedure Free_Task
(T
: Task_Id
) is
939 Self_Id
: constant Task_Id
:= Self
;
942 if T
.Common
.State
= Terminated
then
944 -- It is not safe to call Abort_Defer or Write_Lock at this stage
946 Initialization
.Task_Lock
(Self_Id
);
949 Initialization
.Finalize_Attributes_Link
.all (T
);
950 Initialization
.Remove_From_All_Tasks_List
(T
);
953 Initialization
.Task_Unlock
(Self_Id
);
955 System
.Task_Primitives
.Operations
.Finalize_TCB
(T
);
958 -- If the task is not terminated, then mark the task as to be freed
961 T
.Free_On_Termination
:= True;
965 ---------------------------
966 -- Move_Activation_Chain --
967 ---------------------------
969 procedure Move_Activation_Chain
970 (From
, To
: Activation_Chain_Access
;
971 New_Master
: Master_ID
)
973 Self_ID
: constant Task_Id
:= STPO
.Self
;
978 (Debug
.Trace
(Self_ID
, "Move_Activation_Chain", 'C'));
980 -- Nothing to do if From is empty, and we can check that without
989 Initialization
.Defer_Abort
(Self_ID
);
991 -- Loop through the From chain, changing their Master_of_Task fields,
992 -- and to find the end of the chain.
995 C
.Master_of_Task
:= New_Master
;
996 exit when C
.Common
.Activation_Link
= null;
997 C
:= C
.Common
.Activation_Link
;
1000 -- Hook From in at the start of To
1002 C
.Common
.Activation_Link
:= To
.all.T_ID
;
1003 To
.all.T_ID
:= From
.all.T_ID
;
1005 -- Set From to empty
1007 From
.all.T_ID
:= null;
1009 Initialization
.Undefer_Abort
(Self_ID
);
1010 end Move_Activation_Chain
;
1016 -- The task wrapper is a procedure that is called first for each task body
1017 -- and which in turn calls the compiler-generated task body procedure.
1018 -- The wrapper's main job is to do initialization for the task. It also
1019 -- has some locally declared objects that serve as per-task local data.
1020 -- Task finalization is done by Complete_Task, which is called from an
1021 -- at-end handler that the compiler generates.
1023 procedure Task_Wrapper
(Self_ID
: Task_Id
) is
1024 use type SSE
.Storage_Offset
;
1025 use System
.Standard_Library
;
1026 use System
.Stack_Usage
;
1028 Bottom_Of_Stack
: aliased Integer;
1030 Task_Alternate_Stack
:
1031 aliased SSE
.Storage_Array
(1 .. Alternate_Stack_Size
);
1032 -- The alternate signal stack for this task, if any
1034 Use_Alternate_Stack
: constant Boolean := Alternate_Stack_Size
/= 0;
1035 -- Whether to use above alternate signal stack for stack overflows
1037 Secondary_Stack_Size
:
1038 constant SSE
.Storage_Offset
:=
1039 Self_ID
.Common
.Compiler_Data
.Pri_Stack_Info
.Size
*
1040 SSE
.Storage_Offset
(Parameters
.Sec_Stack_Percentage
) / 100;
1042 Secondary_Stack
: aliased SSE
.Storage_Array
(1 .. Secondary_Stack_Size
);
1043 -- Actual area allocated for secondary stack
1045 Secondary_Stack_Address
: System
.Address
:= Secondary_Stack
'Address;
1046 -- Address of secondary stack. In the fixed secondary stack case, this
1047 -- value is not modified, causing a warning, hence the bracketing with
1048 -- Warnings (Off/On). But why is so much *more* bracketed???
1050 SEH_Table
: aliased SSE
.Storage_Array
(1 .. 8);
1051 -- Structured Exception Registration table (2 words)
1053 procedure Install_SEH_Handler
(Addr
: System
.Address
);
1054 pragma Import
(C
, Install_SEH_Handler
, "__gnat_install_SEH_handler");
1055 -- Install the SEH (Structured Exception Handling) handler
1057 Cause
: Cause_Of_Termination
:= Normal
;
1058 -- Indicates the reason why this task terminates. Normal corresponds to
1059 -- a task terminating due to completing the last statement of its body,
1060 -- or as a result of waiting on a terminate alternative. If the task
1061 -- terminates because it is being aborted then Cause will be set
1062 -- to Abnormal. If the task terminates because of an exception
1063 -- raised by the execution of its task body, then Cause is set
1064 -- to Unhandled_Exception.
1066 EO
: Exception_Occurrence
;
1067 -- If the task terminates because of an exception raised by the
1068 -- execution of its task body, then EO will contain the associated
1069 -- exception occurrence. Otherwise, it will contain Null_Occurrence.
1071 TH
: Termination_Handler
:= null;
1072 -- Pointer to the protected procedure to be executed upon task
1075 procedure Search_Fall_Back_Handler
(ID
: Task_Id
);
1076 -- Procedure that searches recursively a fall-back handler through the
1077 -- master relationship. If the handler is found, its pointer is stored
1078 -- in TH. It stops when the handler is found or when the ID is null.
1080 ------------------------------
1081 -- Search_Fall_Back_Handler --
1082 ------------------------------
1084 procedure Search_Fall_Back_Handler
(ID
: Task_Id
) is
1086 -- A null Task_Id indicates that we have reached the root of the
1087 -- task hierarchy and no handler has been found.
1092 -- If there is a fall back handler, store its pointer for later
1095 elsif ID
.Common
.Fall_Back_Handler
/= null then
1096 TH
:= ID
.Common
.Fall_Back_Handler
;
1098 -- Otherwise look for a fall back handler in the parent
1101 Search_Fall_Back_Handler
(ID
.Common
.Parent
);
1103 end Search_Fall_Back_Handler
;
1105 -- Start of processing for Task_Wrapper
1108 pragma Assert
(Self_ID
.Deferral_Level
= 1);
1110 -- Assume a size of the stack taken at this stage
1112 if not Parameters
.Sec_Stack_Dynamic
then
1113 Self_ID
.Common
.Compiler_Data
.Sec_Stack_Addr
:=
1114 Secondary_Stack
'Address;
1115 SST
.SS_Init
(Secondary_Stack_Address
, Integer (Secondary_Stack
'Last));
1118 if Use_Alternate_Stack
then
1119 Self_ID
.Common
.Task_Alternate_Stack
:= Task_Alternate_Stack
'Address;
1122 -- Set the guard page at the bottom of the stack. The call to unprotect
1123 -- the page is done in Terminate_Task
1125 Stack_Guard
(Self_ID
, True);
1127 -- Initialize low-level TCB components, that cannot be initialized by
1128 -- the creator. Enter_Task sets Self_ID.LL.Thread.
1130 Enter_Task
(Self_ID
);
1132 -- Initialize dynamic stack usage
1134 if System
.Stack_Usage
.Is_Enabled
then
1136 Guard_Page_Size
: constant := 16 * 1024;
1137 -- Part of the stack used as a guard page. This is an OS dependent
1138 -- value, so we need to use the maximum. This value is only used
1139 -- when the stack address is known, that is currently Windows.
1141 Small_Overflow_Guard
: constant := 12 * 1024;
1142 -- Note: this used to be 4K, but was changed to 12K, since
1143 -- smaller values resulted in segmentation faults from dynamic
1146 Big_Overflow_Guard
: constant := 64 * 1024 + 8 * 1024;
1147 Small_Stack_Limit
: constant := 64 * 1024;
1148 -- ??? These three values are experimental, and seem to work on
1149 -- most platforms. They still need to be analyzed further. They
1150 -- also need documentation, what are they and why does the logic
1151 -- differ depending on whether the stack is large or small???
1153 Pattern_Size
: Natural :=
1154 Natural (Self_ID
.Common
.
1155 Compiler_Data
.Pri_Stack_Info
.Size
);
1156 -- Size of the pattern
1158 Stack_Base
: Address
;
1159 -- Address of the base of the stack
1162 Stack_Base
:= Self_ID
.Common
.Compiler_Data
.Pri_Stack_Info
.Base
;
1164 if Stack_Base
= Null_Address
then
1166 -- On many platforms, we don't know the real stack base
1167 -- address. Estimate it using an address in the frame.
1169 Stack_Base
:= Bottom_Of_Stack
'Address;
1171 -- Also reduce the size of the stack to take into account the
1172 -- secondary stack array declared in this frame. This is for
1173 -- sure very conservative.
1175 if not Parameters
.Sec_Stack_Dynamic
then
1177 Pattern_Size
- Natural (Secondary_Stack_Size
);
1180 -- Adjustments for inner frames
1182 Pattern_Size
:= Pattern_Size
-
1183 (if Pattern_Size
< Small_Stack_Limit
1184 then Small_Overflow_Guard
1185 else Big_Overflow_Guard
);
1187 -- Reduce by the size of the final guard page
1189 Pattern_Size
:= Pattern_Size
- Guard_Page_Size
;
1194 (Self_ID
.Common
.Analyzer
,
1195 Self_ID
.Common
.Task_Image
(1 .. Self_ID
.Common
.Task_Image_Len
),
1196 Natural (Self_ID
.Common
.Compiler_Data
.Pri_Stack_Info
.Size
),
1197 SSE
.To_Integer
(Stack_Base
),
1200 Fill_Stack
(Self_ID
.Common
.Analyzer
);
1204 -- We setup the SEH (Structured Exception Handling) handler if supported
1207 Install_SEH_Handler
(SEH_Table
'Address);
1209 -- Initialize exception occurrence
1211 Save_Occurrence
(EO
, Ada
.Exceptions
.Null_Occurrence
);
1213 -- We lock RTS_Lock to wait for activator to finish activating the rest
1214 -- of the chain, so that everyone in the chain comes out in priority
1217 -- This also protects the value of
1218 -- Self_ID.Common.Activator.Common.Wait_Count.
1223 if not System
.Restrictions
.Abort_Allowed
then
1225 -- If Abort is not allowed, reset the deferral level since it will
1226 -- not get changed by the generated code. Keeping a default value
1227 -- of one would prevent some operations (e.g. select or delay) to
1228 -- proceed successfully.
1230 Self_ID
.Deferral_Level
:= 0;
1233 if Global_Task_Debug_Event_Set
then
1234 Debug
.Signal_Debug_Event
(Debug
.Debug_Event_Run
, Self_ID
);
1238 -- We are separating the following portion of the code in order to
1239 -- place the exception handlers in a different block. In this way,
1240 -- we do not call Set_Jmpbuf_Address (which needs Self) before we
1241 -- set Self in Enter_Task
1243 -- Call the task body procedure
1245 -- The task body is called with abort still deferred. That
1246 -- eliminates a dangerous window, for which we had to patch-up in
1249 -- During the expansion of the task body, we insert an RTS-call
1250 -- to Abort_Undefer, at the first point where abort should be
1253 Self_ID
.Common
.Task_Entry_Point
(Self_ID
.Common
.Task_Arg
);
1254 Initialization
.Defer_Abort_Nestable
(Self_ID
);
1257 -- We can't call Terminate_Task in the exception handlers below,
1258 -- since there may be (e.g. in the case of GCC exception handling)
1259 -- clean ups associated with the exception handler that need to
1260 -- access task specific data.
1262 -- Defer abort so that this task can't be aborted while exiting
1264 when Standard
'Abort_Signal =>
1265 Initialization
.Defer_Abort_Nestable
(Self_ID
);
1267 -- Update the cause that motivated the task termination so that
1268 -- the appropriate information is passed to the task termination
1269 -- procedure. Task termination as a result of waiting on a
1270 -- terminate alternative is a normal termination, although it is
1271 -- implemented using the abort mechanisms.
1273 if Self_ID
.Terminate_Alternative
then
1276 if Global_Task_Debug_Event_Set
then
1277 Debug
.Signal_Debug_Event
1278 (Debug
.Debug_Event_Terminated
, Self_ID
);
1283 if Global_Task_Debug_Event_Set
then
1284 Debug
.Signal_Debug_Event
1285 (Debug
.Debug_Event_Abort_Terminated
, Self_ID
);
1290 -- ??? Using an E : others here causes CD2C11A to fail on Tru64
1292 Initialization
.Defer_Abort_Nestable
(Self_ID
);
1294 -- Perform the task specific exception tracing duty. We handle
1295 -- these outputs here and not in the common notification routine
1296 -- because we need access to tasking related data and we don't
1297 -- want to drag dependencies against tasking related units in the
1298 -- the common notification units. Additionally, no trace is ever
1299 -- triggered from the common routine for the Unhandled_Raise case
1300 -- in tasks, since an exception never appears unhandled in this
1301 -- context because of this handler.
1303 if Exception_Trace
= Unhandled_Raise
then
1304 Trace_Unhandled_Exception_In_Task
(Self_ID
);
1307 -- Update the cause that motivated the task termination so that
1308 -- the appropriate information is passed to the task termination
1309 -- procedure, as well as the associated Exception_Occurrence.
1311 Cause
:= Unhandled_Exception
;
1313 Save_Occurrence
(EO
, SSL
.Get_Current_Excep
.all.all);
1315 if Global_Task_Debug_Event_Set
then
1316 Debug
.Signal_Debug_Event
1317 (Debug
.Debug_Event_Exception_Terminated
, Self_ID
);
1321 -- Look for a task termination handler. This code is for all tasks but
1322 -- the environment task. The task termination code for the environment
1323 -- task is executed by SSL.Task_Termination_Handler.
1329 Write_Lock
(Self_ID
);
1331 if Self_ID
.Common
.Specific_Handler
/= null then
1332 TH
:= Self_ID
.Common
.Specific_Handler
;
1334 -- Look for a fall-back handler following the master relationship
1335 -- for the task. As specified in ARM C.7.3 par. 9/2, "the fall-back
1336 -- handler applies only to the dependent tasks of the task". Hence,
1337 -- if the terminating tasks (Self_ID) had a fall-back handler, it
1338 -- would not apply to itself, so we start the search with the parent.
1340 Search_Fall_Back_Handler
(Self_ID
.Common
.Parent
);
1349 -- Execute the task termination handler if we found it
1353 TH
.all (Cause
, Self_ID
, EO
);
1357 -- RM-C.7.3 requires all exceptions raised here to be ignored
1364 if System
.Stack_Usage
.Is_Enabled
then
1365 Compute_Result
(Self_ID
.Common
.Analyzer
);
1366 Report_Result
(Self_ID
.Common
.Analyzer
);
1369 Terminate_Task
(Self_ID
);
1372 --------------------
1373 -- Terminate_Task --
1374 --------------------
1376 -- Before we allow the thread to exit, we must clean up. This is a delicate
1377 -- job. We must wake up the task's master, who may immediately try to
1378 -- deallocate the ATCB from the current task WHILE IT IS STILL EXECUTING.
1380 -- To avoid this, the parent task must be blocked up to the latest
1381 -- statement executed. The trouble is that we have another step that we
1382 -- also want to postpone to the very end, i.e., calling SSL.Destroy_TSD.
1383 -- We have to postpone that until the end because compiler-generated code
1384 -- is likely to try to access that data at just about any point.
1386 -- We can't call Destroy_TSD while we are holding any other locks, because
1387 -- it locks Global_Task_Lock, and our deadlock prevention rules require
1388 -- that to be the outermost lock. Our first "solution" was to just lock
1389 -- Global_Task_Lock in addition to the other locks, and force the parent to
1390 -- also lock this lock between its wakeup and its freeing of the ATCB. See
1391 -- Complete_Task for the parent-side of the code that has the matching
1392 -- calls to Task_Lock and Task_Unlock. That was not really a solution,
1393 -- since the operation Task_Unlock continued to access the ATCB after
1394 -- unlocking, after which the parent was observed to race ahead, deallocate
1395 -- the ATCB, and then reallocate it to another task. The call to
1396 -- Undefer_Abort in Task_Unlock by the "terminated" task was overwriting
1397 -- the data of the new task that reused the ATCB! To solve this problem, we
1398 -- introduced the new operation Final_Task_Unlock.
1400 procedure Terminate_Task
(Self_ID
: Task_Id
) is
1401 Environment_Task
: constant Task_Id
:= STPO
.Environment_Task
;
1402 Master_of_Task
: Integer;
1403 Deallocate
: Boolean;
1406 Debug
.Task_Termination_Hook
;
1408 if Runtime_Traces
then
1409 Send_Trace_Info
(T_Terminate
);
1412 -- Since GCC cannot allocate stack chunks efficiently without reordering
1413 -- some of the allocations, we have to handle this unexpected situation
1414 -- here. Normally we never have to call Vulnerable_Complete_Task here.
1416 if Self_ID
.Common
.Activator
/= null then
1417 Vulnerable_Complete_Task
(Self_ID
);
1420 Initialization
.Task_Lock
(Self_ID
);
1426 Master_of_Task
:= Self_ID
.Master_of_Task
;
1428 -- Check if the current task is an independent task If so, decrement
1429 -- the Independent_Task_Count value.
1431 if Master_of_Task
= Independent_Task_Level
then
1433 Utilities
.Independent_Task_Count
:=
1434 Utilities
.Independent_Task_Count
- 1;
1437 Write_Lock
(Environment_Task
);
1438 Utilities
.Independent_Task_Count
:=
1439 Utilities
.Independent_Task_Count
- 1;
1440 Unlock
(Environment_Task
);
1444 -- Unprotect the guard page if needed
1446 Stack_Guard
(Self_ID
, False);
1448 Utilities
.Make_Passive
(Self_ID
, Task_Completed
=> True);
1449 Deallocate
:= Self_ID
.Free_On_Termination
;
1455 pragma Assert
(Check_Exit
(Self_ID
));
1457 SSL
.Destroy_TSD
(Self_ID
.Common
.Compiler_Data
);
1458 Initialization
.Final_Task_Unlock
(Self_ID
);
1460 -- WARNING: past this point, this thread must assume that the ATCB has
1461 -- been deallocated, and can't access it anymore (which is why we have
1462 -- saved the Free_On_Termination flag in a temporary variable).
1465 Free_Task
(Self_ID
);
1468 if Master_of_Task
> 0 then
1477 function Terminated
(T
: Task_Id
) return Boolean is
1478 Self_ID
: constant Task_Id
:= STPO
.Self
;
1482 Initialization
.Defer_Abort_Nestable
(Self_ID
);
1489 Result
:= T
.Common
.State
= Terminated
;
1496 Initialization
.Undefer_Abort_Nestable
(Self_ID
);
1500 ----------------------------------------
1501 -- Trace_Unhandled_Exception_In_Task --
1502 ----------------------------------------
1504 procedure Trace_Unhandled_Exception_In_Task
(Self_Id
: Task_Id
) is
1505 procedure To_Stderr
(S
: String);
1506 pragma Import
(Ada
, To_Stderr
, "__gnat_to_stderr");
1508 use System
.Soft_Links
;
1509 use System
.Standard_Library
;
1511 function To_Address
is new
1512 Ada
.Unchecked_Conversion
1513 (Task_Id
, System
.Task_Primitives
.Task_Address
);
1515 function Tailored_Exception_Information
1516 (E
: Exception_Occurrence
) return String;
1518 (Ada
, Tailored_Exception_Information
,
1519 "__gnat_tailored_exception_information");
1521 Excep
: constant Exception_Occurrence_Access
:=
1522 SSL
.Get_Current_Excep
.all;
1525 -- This procedure is called by the task outermost handler in
1526 -- Task_Wrapper below, so only once the task stack has been fully
1527 -- unwound. The common notification routine has been called at the
1528 -- raise point already.
1530 -- Lock to prevent unsynchronized output
1532 Initialization
.Task_Lock
(Self_Id
);
1533 To_Stderr
("task ");
1535 if Self_Id
.Common
.Task_Image_Len
/= 0 then
1537 (Self_Id
.Common
.Task_Image
(1 .. Self_Id
.Common
.Task_Image_Len
));
1541 To_Stderr
(System
.Address_Image
(To_Address
(Self_Id
)));
1542 To_Stderr
(" terminated by unhandled exception");
1543 To_Stderr
((1 => ASCII
.LF
));
1544 To_Stderr
(Tailored_Exception_Information
(Excep
.all));
1545 Initialization
.Task_Unlock
(Self_Id
);
1546 end Trace_Unhandled_Exception_In_Task
;
1548 ------------------------------------
1549 -- Vulnerable_Complete_Activation --
1550 ------------------------------------
1552 -- As in several other places, the locks of the activator and activated
1553 -- task are both locked here. This follows our deadlock prevention lock
1554 -- ordering policy, since the activated task must be created after the
1557 procedure Vulnerable_Complete_Activation
(Self_ID
: Task_Id
) is
1558 Activator
: constant Task_Id
:= Self_ID
.Common
.Activator
;
1561 pragma Debug
(Debug
.Trace
(Self_ID
, "V_Complete_Activation", 'C'));
1563 Write_Lock
(Activator
);
1564 Write_Lock
(Self_ID
);
1566 pragma Assert
(Self_ID
.Common
.Activator
/= null);
1568 -- Remove dangling reference to Activator, since a task may outlive its
1571 Self_ID
.Common
.Activator
:= null;
1573 -- Wake up the activator, if it is waiting for a chain of tasks to
1574 -- activate, and we are the last in the chain to complete activation.
1576 if Activator
.Common
.State
= Activator_Sleep
then
1577 Activator
.Common
.Wait_Count
:= Activator
.Common
.Wait_Count
- 1;
1579 if Activator
.Common
.Wait_Count
= 0 then
1580 Wakeup
(Activator
, Activator_Sleep
);
1584 -- The activator raises a Tasking_Error if any task it is activating
1585 -- is completed before the activation is done. However, if the reason
1586 -- for the task completion is an abort, we do not raise an exception.
1589 if not Self_ID
.Callable
and then Self_ID
.Pending_ATC_Level
/= 0 then
1590 Activator
.Common
.Activation_Failed
:= True;
1596 -- After the activation, active priority should be the same as base
1597 -- priority. We must unlock the Activator first, though, since it
1598 -- should not wait if we have lower priority.
1600 if Get_Priority
(Self_ID
) /= Self_ID
.Common
.Base_Priority
then
1601 Write_Lock
(Self_ID
);
1602 Set_Priority
(Self_ID
, Self_ID
.Common
.Base_Priority
);
1605 end Vulnerable_Complete_Activation
;
1607 --------------------------------
1608 -- Vulnerable_Complete_Master --
1609 --------------------------------
1611 procedure Vulnerable_Complete_Master
(Self_ID
: Task_Id
) is
1614 CM
: constant Master_Level
:= Self_ID
.Master_Within
;
1615 T
: aliased Task_Id
;
1617 To_Be_Freed
: Task_Id
;
1618 -- This is a list of ATCBs to be freed, after we have released all RTS
1619 -- locks. This is necessary because of the locking order rules, since
1620 -- the storage manager uses Global_Task_Lock.
1622 pragma Warnings
(Off
);
1623 function Check_Unactivated_Tasks
return Boolean;
1624 pragma Warnings
(On
);
1625 -- Temporary error-checking code below. This is part of the checks
1626 -- added in the new run time. Call it only inside a pragma Assert.
1628 -----------------------------
1629 -- Check_Unactivated_Tasks --
1630 -----------------------------
1632 function Check_Unactivated_Tasks
return Boolean is
1634 if not Single_Lock
then
1638 Write_Lock
(Self_ID
);
1640 C
:= All_Tasks_List
;
1641 while C
/= null loop
1642 if C
.Common
.Activator
= Self_ID
and then C
.Master_of_Task
= CM
then
1646 if C
.Common
.Parent
= Self_ID
and then C
.Master_of_Task
= CM
then
1649 if C
.Common
.State
= Unactivated
then
1656 C
:= C
.Common
.All_Tasks_Link
;
1661 if not Single_Lock
then
1666 end Check_Unactivated_Tasks
;
1668 -- Start of processing for Vulnerable_Complete_Master
1672 (Debug
.Trace
(Self_ID
, "V_Complete_Master", 'C'));
1674 pragma Assert
(Self_ID
.Common
.Wait_Count
= 0);
1676 (Self_ID
.Deferral_Level
> 0
1677 or else not System
.Restrictions
.Abort_Allowed
);
1679 -- Count how many active dependent tasks this master currently has, and
1680 -- record this in Wait_Count.
1682 -- This count should start at zero, since it is initialized to zero for
1683 -- new tasks, and the task should not exit the sleep-loops that use this
1684 -- count until the count reaches zero.
1686 -- While we're counting, if we run across any unactivated tasks that
1687 -- belong to this master, we summarily terminate them as required by
1691 Write_Lock
(Self_ID
);
1693 C
:= All_Tasks_List
;
1694 while C
/= null loop
1696 -- Terminate unactivated (never-to-be activated) tasks
1698 if C
.Common
.Activator
= Self_ID
and then C
.Master_of_Task
= CM
then
1700 -- Usually, C.Common.Activator = Self_ID implies C.Master_of_Task
1701 -- = CM. The only case where C is pending activation by this
1702 -- task, but the master of C is not CM is in Ada 2005, when C is
1703 -- part of a return object of a build-in-place function.
1705 pragma Assert
(C
.Common
.State
= Unactivated
);
1708 C
.Common
.Activator
:= null;
1709 C
.Common
.State
:= Terminated
;
1710 C
.Callable
:= False;
1711 Utilities
.Cancel_Queued_Entry_Calls
(C
);
1715 -- Count it if dependent on this master
1717 if C
.Common
.Parent
= Self_ID
and then C
.Master_of_Task
= CM
then
1720 if C
.Awake_Count
/= 0 then
1721 Self_ID
.Common
.Wait_Count
:= Self_ID
.Common
.Wait_Count
+ 1;
1727 C
:= C
.Common
.All_Tasks_Link
;
1730 Self_ID
.Common
.State
:= Master_Completion_Sleep
;
1733 if not Single_Lock
then
1737 -- Wait until dependent tasks are all terminated or ready to terminate.
1738 -- While waiting, the task may be awakened if the task's priority needs
1739 -- changing, or this master is aborted. In the latter case, we abort the
1740 -- dependents, and resume waiting until Wait_Count goes to zero.
1742 Write_Lock
(Self_ID
);
1745 exit when Self_ID
.Common
.Wait_Count
= 0;
1747 -- Here is a difference as compared to Complete_Master
1749 if Self_ID
.Pending_ATC_Level
< Self_ID
.ATC_Nesting_Level
1750 and then not Self_ID
.Dependents_Aborted
1753 Abort_Dependents
(Self_ID
);
1757 Abort_Dependents
(Self_ID
);
1759 Write_Lock
(Self_ID
);
1762 Sleep
(Self_ID
, Master_Completion_Sleep
);
1766 Self_ID
.Common
.State
:= Runnable
;
1769 -- Dependents are all terminated or on terminate alternatives. Now,
1770 -- force those on terminate alternatives to terminate, by aborting them.
1772 pragma Assert
(Check_Unactivated_Tasks
);
1774 if Self_ID
.Alive_Count
> 1 then
1776 -- Consider finding a way to skip the following extra steps if there
1777 -- are no dependents with terminate alternatives. This could be done
1778 -- by adding another count to the ATCB, similar to Awake_Count, but
1779 -- keeping track of tasks that are on terminate alternatives.
1781 pragma Assert
(Self_ID
.Common
.Wait_Count
= 0);
1783 -- Force any remaining dependents to terminate by aborting them
1785 if not Single_Lock
then
1789 Abort_Dependents
(Self_ID
);
1791 -- Above, when we "abort" the dependents we are simply using this
1792 -- operation for convenience. We are not required to support the full
1793 -- abort-statement semantics; in particular, we are not required to
1794 -- immediately cancel any queued or in-service entry calls. That is
1795 -- good, because if we tried to cancel a call we would need to lock
1796 -- the caller, in order to wake the caller up. Our anti-deadlock
1797 -- rules prevent us from doing that without releasing the locks on C
1798 -- and Self_ID. Releasing and retaking those locks would be wasteful
1799 -- at best, and should not be considered further without more
1800 -- detailed analysis of potential concurrent accesses to the ATCBs
1801 -- of C and Self_ID.
1803 -- Count how many "alive" dependent tasks this master currently has,
1804 -- and record this in Wait_Count. This count should start at zero,
1805 -- since it is initialized to zero for new tasks, and the task should
1806 -- not exit the sleep-loops that use this count until the count
1809 pragma Assert
(Self_ID
.Common
.Wait_Count
= 0);
1811 Write_Lock
(Self_ID
);
1813 C
:= All_Tasks_List
;
1814 while C
/= null loop
1815 if C
.Common
.Parent
= Self_ID
and then C
.Master_of_Task
= CM
then
1818 pragma Assert
(C
.Awake_Count
= 0);
1820 if C
.Alive_Count
> 0 then
1821 pragma Assert
(C
.Terminate_Alternative
);
1822 Self_ID
.Common
.Wait_Count
:= Self_ID
.Common
.Wait_Count
+ 1;
1828 C
:= C
.Common
.All_Tasks_Link
;
1831 Self_ID
.Common
.State
:= Master_Phase_2_Sleep
;
1834 if not Single_Lock
then
1838 -- Wait for all counted tasks to finish terminating themselves
1840 Write_Lock
(Self_ID
);
1843 exit when Self_ID
.Common
.Wait_Count
= 0;
1844 Sleep
(Self_ID
, Master_Phase_2_Sleep
);
1847 Self_ID
.Common
.State
:= Runnable
;
1851 -- We don't wake up for abort here. We are already terminating just as
1852 -- fast as we can, so there is no point.
1854 -- Remove terminated tasks from the list of Self_ID's dependents, but
1855 -- don't free their ATCBs yet, because of lock order restrictions, which
1856 -- don't allow us to call "free" or "malloc" while holding any other
1857 -- locks. Instead, we put those ATCBs to be freed onto a temporary list,
1858 -- called To_Be_Freed.
1860 if not Single_Lock
then
1864 C
:= All_Tasks_List
;
1866 while C
/= null loop
1868 -- If Free_On_Termination is set, do nothing here, and let the
1869 -- task free itself if not already done, otherwise we risk a race
1870 -- condition where Vulnerable_Free_Task is called in the loop below,
1871 -- while the task calls Free_Task itself, in Terminate_Task.
1873 if C
.Common
.Parent
= Self_ID
1874 and then C
.Master_of_Task
>= CM
1875 and then not C
.Free_On_Termination
1878 P
.Common
.All_Tasks_Link
:= C
.Common
.All_Tasks_Link
;
1880 All_Tasks_List
:= C
.Common
.All_Tasks_Link
;
1883 T
:= C
.Common
.All_Tasks_Link
;
1884 C
.Common
.All_Tasks_Link
:= To_Be_Freed
;
1890 C
:= C
.Common
.All_Tasks_Link
;
1896 -- Free all the ATCBs on the list To_Be_Freed
1898 -- The ATCBs in the list are no longer in All_Tasks_List, and after
1899 -- any interrupt entries are detached from them they should no longer
1902 -- Global_Task_Lock (Task_Lock/Unlock) is locked in the loop below to
1903 -- avoid a race between a terminating task and its parent. The parent
1904 -- might try to deallocate the ACTB out from underneath the exiting
1905 -- task. Note that Free will also lock Global_Task_Lock, but that is
1906 -- OK, since this is the *one* lock for which we have a mechanism to
1907 -- support nested locking. See Task_Wrapper and its finalizer for more
1911 -- The check "T.Common.Parent /= null ..." below is to prevent dangling
1912 -- references to terminated library-level tasks, which could otherwise
1913 -- occur during finalization of library-level objects. A better solution
1914 -- might be to hook task objects into the finalization chain and
1915 -- deallocate the ATCB when the task object is deallocated. However,
1916 -- this change is not likely to gain anything significant, since all
1917 -- this storage should be recovered en-masse when the process exits.
1919 while To_Be_Freed
/= null loop
1921 To_Be_Freed
:= T
.Common
.All_Tasks_Link
;
1923 -- ??? On SGI there is currently no Interrupt_Manager, that's why we
1924 -- need to check if the Interrupt_Manager_ID is null.
1926 if T
.Interrupt_Entry
and then Interrupt_Manager_ID
/= null then
1928 Detach_Interrupt_Entries_Index
: constant Task_Entry_Index
:= 1;
1929 -- Corresponds to the entry index of System.Interrupts.
1930 -- Interrupt_Manager.Detach_Interrupt_Entries. Be sure
1931 -- to update this value when changing Interrupt_Manager specs.
1933 type Param_Type
is access all Task_Id
;
1935 Param
: aliased Param_Type
:= T
'Access;
1938 System
.Tasking
.Rendezvous
.Call_Simple
1939 (Interrupt_Manager_ID
, Detach_Interrupt_Entries_Index
,
1944 if (T
.Common
.Parent
/= null
1945 and then T
.Common
.Parent
.Common
.Parent
/= null)
1946 or else T
.Master_of_Task
> Library_Task_Level
1948 Initialization
.Task_Lock
(Self_ID
);
1950 -- If Sec_Stack_Addr is not null, it means that Destroy_TSD
1951 -- has not been called yet (case of an unactivated task).
1953 if T
.Common
.Compiler_Data
.Sec_Stack_Addr
/= Null_Address
then
1954 SSL
.Destroy_TSD
(T
.Common
.Compiler_Data
);
1957 Vulnerable_Free_Task
(T
);
1958 Initialization
.Task_Unlock
(Self_ID
);
1962 -- It might seem nice to let the terminated task deallocate its own
1963 -- ATCB. That would not cover the case of unactivated tasks. It also
1964 -- would force us to keep the underlying thread around past termination,
1965 -- since references to the ATCB are possible past termination.
1967 -- Currently, we get rid of the thread as soon as the task terminates,
1968 -- and let the parent recover the ATCB later.
1970 -- Some day, if we want to recover the ATCB earlier, at task
1971 -- termination, we could consider using "fat task IDs", that include the
1972 -- serial number with the ATCB pointer, to catch references to tasks
1973 -- that no longer have ATCBs. It is not clear how much this would gain,
1974 -- since the user-level task object would still be occupying storage.
1976 -- Make next master level up active. We don't need to lock the ATCB,
1977 -- since the value is only updated by each task for itself.
1979 Self_ID
.Master_Within
:= CM
- 1;
1980 end Vulnerable_Complete_Master
;
1982 ------------------------------
1983 -- Vulnerable_Complete_Task --
1984 ------------------------------
1986 -- Complete the calling task
1988 -- This procedure must be called with abort deferred. It should only be
1989 -- called by Complete_Task and Finalize_Global_Tasks (for the environment
1992 -- The effect is similar to that of Complete_Master. Differences include
1993 -- the closing of entries here, and computation of the number of active
1994 -- dependent tasks in Complete_Master.
1996 -- We don't lock Self_ID before the call to Vulnerable_Complete_Activation,
1997 -- because that does its own locking, and because we do not need the lock
1998 -- to test Self_ID.Common.Activator. That value should only be read and
1999 -- modified by Self.
2001 procedure Vulnerable_Complete_Task
(Self_ID
: Task_Id
) is
2004 (Self_ID
.Deferral_Level
> 0
2005 or else not System
.Restrictions
.Abort_Allowed
);
2006 pragma Assert
(Self_ID
= Self
);
2007 pragma Assert
(Self_ID
.Master_Within
= Self_ID
.Master_of_Task
+ 1
2009 Self_ID
.Master_Within
= Self_ID
.Master_of_Task
+ 2);
2010 pragma Assert
(Self_ID
.Common
.Wait_Count
= 0);
2011 pragma Assert
(Self_ID
.Open_Accepts
= null);
2012 pragma Assert
(Self_ID
.ATC_Nesting_Level
= 1);
2014 pragma Debug
(Debug
.Trace
(Self_ID
, "V_Complete_Task", 'C'));
2020 Write_Lock
(Self_ID
);
2021 Self_ID
.Callable
:= False;
2023 -- In theory, Self should have no pending entry calls left on its
2024 -- call-stack. Each async. select statement should clean its own call,
2025 -- and blocking entry calls should defer abort until the calls are
2026 -- cancelled, then clean up.
2028 Utilities
.Cancel_Queued_Entry_Calls
(Self_ID
);
2031 if Self_ID
.Common
.Activator
/= null then
2032 Vulnerable_Complete_Activation
(Self_ID
);
2039 -- If Self_ID.Master_Within = Self_ID.Master_of_Task + 2 we may have
2040 -- dependent tasks for which we need to wait. Otherwise we just exit.
2042 if Self_ID
.Master_Within
= Self_ID
.Master_of_Task
+ 2 then
2043 Vulnerable_Complete_Master
(Self_ID
);
2045 end Vulnerable_Complete_Task
;
2047 --------------------------
2048 -- Vulnerable_Free_Task --
2049 --------------------------
2051 -- Recover all runtime system storage associated with the task T. This
2052 -- should only be called after T has terminated and will no longer be
2055 -- For tasks created by an allocator that fails, due to an exception, it
2056 -- is called from Expunge_Unactivated_Tasks.
2058 -- For tasks created by elaboration of task object declarations it is
2059 -- called from the finalization code of the Task_Wrapper procedure.
2061 procedure Vulnerable_Free_Task
(T
: Task_Id
) is
2063 pragma Debug
(Debug
.Trace
(Self
, "Vulnerable_Free_Task", 'C', T
));
2070 Initialization
.Finalize_Attributes_Link
.all (T
);
2077 System
.Task_Primitives
.Operations
.Finalize_TCB
(T
);
2078 end Vulnerable_Free_Task
;
2080 -- Package elaboration code
2083 -- Establish the Adafinal softlink
2085 -- This is not done inside the central RTS initialization routine
2086 -- to avoid with'ing this package from System.Tasking.Initialization.
2088 SSL
.Adafinal
:= Finalize_Global_Tasks
'Access;
2090 -- Establish soft links for subprograms that manipulate master_id's.
2091 -- This cannot be done when the RTS is initialized, because of various
2092 -- elaboration constraints.
2094 SSL
.Current_Master
:= Stages
.Current_Master
'Access;
2095 SSL
.Enter_Master
:= Stages
.Enter_Master
'Access;
2096 SSL
.Complete_Master
:= Stages
.Complete_Master
'Access;
2097 end System
.Tasking
.Stages
;