OSDN Git Service

2009-04-17 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / s-tassta.adb
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-2009, 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 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.                                     --
17 --                                                                          --
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.               --
21 --                                                                          --
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/>.                                          --
26 --                                                                          --
27 -- GNARL was developed by the GNARL team at Florida State University.       --
28 -- Extensive contributions were provided by Ada Core Technologies, Inc.     --
29 --                                                                          --
30 ------------------------------------------------------------------------------
31
32 pragma Polling (Off);
33 --  Turn off polling, we do not want ATC polling to take place during tasking
34 --  operations. It causes infinite loops and other problems.
35
36 with Ada.Exceptions;
37 with Ada.Unchecked_Deallocation;
38
39 with System.Tasking.Debug;
40 with System.Address_Image;
41 with System.Task_Primitives;
42 with System.Task_Primitives.Operations;
43 with System.Tasking.Utilities;
44 with System.Tasking.Queuing;
45 with System.Tasking.Rendezvous;
46 with System.OS_Primitives;
47 with System.Secondary_Stack;
48 with System.Storage_Elements;
49 with System.Restrictions;
50 with System.Standard_Library;
51 with System.Traces.Tasking;
52 with System.Stack_Usage;
53
54 with System.Soft_Links;
55 --  These are procedure pointers to non-tasking routines that use task
56 --  specific data. In the absence of tasking, these routines refer to global
57 --  data. In the presence of tasking, they must be replaced with pointers to
58 --  task-specific versions. Also used for Create_TSD, Destroy_TSD,
59 --  Get_Current_Excep, Finalize_Global_List, Task_Termination, Handler.
60
61 with System.Tasking.Initialization;
62 pragma Elaborate_All (System.Tasking.Initialization);
63 --  This insures that tasking is initialized if any tasks are created
64
65 package body System.Tasking.Stages is
66
67    package STPO renames System.Task_Primitives.Operations;
68    package SSL  renames System.Soft_Links;
69    package SSE  renames System.Storage_Elements;
70    package SST  renames System.Secondary_Stack;
71
72    use Ada.Exceptions;
73
74    use Parameters;
75    use Task_Primitives;
76    use Task_Primitives.Operations;
77    use Task_Info;
78
79    use System.Traces;
80    use System.Traces.Tasking;
81
82    -----------------------
83    -- Local Subprograms --
84    -----------------------
85
86    procedure Free is new
87      Ada.Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id);
88
89    procedure Free_Entry_Names (T : Task_Id);
90    --  Deallocate all string names associated with task entries
91
92    procedure Trace_Unhandled_Exception_In_Task (Self_Id : Task_Id);
93    --  This procedure outputs the task specific message for exception
94    --  tracing purposes.
95
96    procedure Task_Wrapper (Self_ID : Task_Id);
97    pragma Convention (C, Task_Wrapper);
98    --  This is the procedure that is called by the GNULL from the new context
99    --  when a task is created. It waits for activation and then calls the task
100    --  body procedure. When the task body procedure completes, it terminates
101    --  the task.
102    --
103    --  The Task_Wrapper's address will be provided to the underlying threads
104    --  library as the task entry point. Convention C is what makes most sense
105    --  for that purpose (Export C would make the function globally visible,
106    --  and affect the link name on which GDB depends). This will in addition
107    --  trigger an automatic stack alignment suitable for GCC's assumptions if
108    --  need be.
109
110    --  "Vulnerable_..." in the procedure names below means they must be called
111    --  with abort deferred.
112
113    procedure Vulnerable_Complete_Task (Self_ID : Task_Id);
114    --  Complete the calling task. This procedure must be called with
115    --  abort deferred. It should only be called by Complete_Task and
116    --  Finalize_Global_Tasks (for the environment task).
117
118    procedure Vulnerable_Complete_Master (Self_ID : Task_Id);
119    --  Complete the current master of the calling task. This procedure
120    --  must be called with abort deferred. It should only be called by
121    --  Vulnerable_Complete_Task and Complete_Master.
122
123    procedure Vulnerable_Complete_Activation (Self_ID : Task_Id);
124    --  Signal to Self_ID's activator that Self_ID has completed activation.
125    --  This procedure must be called with abort deferred.
126
127    procedure Abort_Dependents (Self_ID : Task_Id);
128    --  Abort all the direct dependents of Self at its current master nesting
129    --  level, plus all of their dependents, transitively. RTS_Lock should be
130    --  locked by the caller.
131
132    procedure Vulnerable_Free_Task (T : Task_Id);
133    --  Recover all runtime system storage associated with the task T. This
134    --  should only be called after T has terminated and will no longer be
135    --  referenced.
136    --
137    --  For tasks created by an allocator that fails, due to an exception, it is
138    --  called from Expunge_Unactivated_Tasks.
139    --
140    --  Different code is used at master completion, in Terminate_Dependents,
141    --  due to a need for tighter synchronization with the master.
142
143    ----------------------
144    -- Abort_Dependents --
145    ----------------------
146
147    procedure Abort_Dependents (Self_ID : Task_Id) is
148       C : Task_Id;
149       P : Task_Id;
150
151    begin
152       C := All_Tasks_List;
153       while C /= null loop
154          P := C.Common.Parent;
155          while P /= null loop
156             if P = Self_ID then
157
158                --  ??? C is supposed to take care of its own dependents, so
159                --  there should be no need to worry about them. Need to double
160                --  check this.
161
162                if C.Master_of_Task = Self_ID.Master_Within then
163                   Utilities.Abort_One_Task (Self_ID, C);
164                   C.Dependents_Aborted := True;
165                end if;
166
167                exit;
168             end if;
169
170             P := P.Common.Parent;
171          end loop;
172
173          C := C.Common.All_Tasks_Link;
174       end loop;
175
176       Self_ID.Dependents_Aborted := True;
177    end Abort_Dependents;
178
179    -----------------
180    -- Abort_Tasks --
181    -----------------
182
183    procedure Abort_Tasks (Tasks : Task_List) is
184    begin
185       Utilities.Abort_Tasks (Tasks);
186    end Abort_Tasks;
187
188    --------------------
189    -- Activate_Tasks --
190    --------------------
191
192    --  Note that locks of activator and activated task are both locked here.
193    --  This is necessary because C.Common.State and Self.Common.Wait_Count have
194    --  to be synchronized. This is safe from deadlock because the activator is
195    --  always created before the activated task. That satisfies our
196    --  in-order-of-creation ATCB locking policy.
197
198    --  At one point, we may also lock the parent, if the parent is different
199    --  from the activator. That is also consistent with the lock ordering
200    --  policy, since the activator cannot be created before the parent.
201
202    --  Since we are holding both the activator's lock, and Task_Wrapper locks
203    --  that before it does anything more than initialize the low-level ATCB
204    --  components, it should be safe to wait to update the counts until we see
205    --  that the thread creation is successful.
206
207    --  If the thread creation fails, we do need to close the entries of the
208    --  task. The first phase, of dequeuing calls, only requires locking the
209    --  acceptor's ATCB, but the waking up of the callers requires locking the
210    --  caller's ATCB. We cannot safely do this while we are holding other
211    --  locks. Therefore, the queue-clearing operation is done in a separate
212    --  pass over the activation chain.
213
214    procedure Activate_Tasks (Chain_Access : Activation_Chain_Access) is
215       Self_ID        : constant Task_Id := STPO.Self;
216       P              : Task_Id;
217       C              : Task_Id;
218       Next_C, Last_C : Task_Id;
219       Activate_Prio  : System.Any_Priority;
220       Success        : Boolean;
221       All_Elaborated : Boolean := True;
222
223    begin
224       --  If pragma Detect_Blocking is active, then we must check whether this
225       --  potentially blocking operation is called from a protected action.
226
227       if System.Tasking.Detect_Blocking
228         and then Self_ID.Common.Protected_Action_Nesting > 0
229       then
230          raise Program_Error with "potentially blocking operation";
231       end if;
232
233       pragma Debug
234         (Debug.Trace (Self_ID, "Activate_Tasks", 'C'));
235
236       Initialization.Defer_Abort_Nestable (Self_ID);
237
238       pragma Assert (Self_ID.Common.Wait_Count = 0);
239
240       --  Lock RTS_Lock, to prevent activated tasks from racing ahead before
241       --  we finish activating the chain.
242
243       Lock_RTS;
244
245       --  Check that all task bodies have been elaborated
246
247       C := Chain_Access.T_ID;
248       Last_C := null;
249       while C /= null loop
250          if C.Common.Elaborated /= null
251            and then not C.Common.Elaborated.all
252          then
253             All_Elaborated := False;
254          end if;
255
256          --  Reverse the activation chain so that tasks are activated in the
257          --  same order they're declared.
258
259          Next_C := C.Common.Activation_Link;
260          C.Common.Activation_Link := Last_C;
261          Last_C := C;
262          C := Next_C;
263       end loop;
264
265       Chain_Access.T_ID := Last_C;
266
267       if not All_Elaborated then
268          Unlock_RTS;
269          Initialization.Undefer_Abort_Nestable (Self_ID);
270          raise Program_Error with "Some tasks have not been elaborated";
271       end if;
272
273       --  Activate all the tasks in the chain. Creation of the thread of
274       --  control was deferred until activation. So create it now.
275
276       C := Chain_Access.T_ID;
277       while C /= null loop
278          if C.Common.State /= Terminated then
279             pragma Assert (C.Common.State = Unactivated);
280
281             P := C.Common.Parent;
282             Write_Lock (P);
283             Write_Lock (C);
284
285             if C.Common.Base_Priority < Get_Priority (Self_ID) then
286                Activate_Prio := Get_Priority (Self_ID);
287             else
288                Activate_Prio := C.Common.Base_Priority;
289             end if;
290
291             System.Task_Primitives.Operations.Create_Task
292               (C, Task_Wrapper'Address,
293                Parameters.Size_Type
294                  (C.Common.Compiler_Data.Pri_Stack_Info.Size),
295                Activate_Prio, Success);
296
297             --  There would be a race between the created task and the creator
298             --  to do the following initialization, if we did not have a
299             --  Lock/Unlock_RTS pair in the task wrapper to prevent it from
300             --  racing ahead.
301
302             if Success then
303                C.Common.State := Activating;
304                C.Awake_Count := 1;
305                C.Alive_Count := 1;
306                P.Awake_Count := P.Awake_Count + 1;
307                P.Alive_Count := P.Alive_Count + 1;
308
309                if P.Common.State = Master_Completion_Sleep and then
310                  C.Master_of_Task = P.Master_Within
311                then
312                   pragma Assert (Self_ID /= P);
313                   P.Common.Wait_Count := P.Common.Wait_Count + 1;
314                end if;
315
316                for J in System.Tasking.Debug.Known_Tasks'Range loop
317                   if System.Tasking.Debug.Known_Tasks (J) = null then
318                      System.Tasking.Debug.Known_Tasks (J) := C;
319                      C.Known_Tasks_Index := J;
320                      exit;
321                   end if;
322                end loop;
323
324                if Global_Task_Debug_Event_Set then
325                   Debug.Signal_Debug_Event
326                    (Debug.Debug_Event_Activating, C);
327                end if;
328
329                C.Common.State := Runnable;
330
331                Unlock (C);
332                Unlock (P);
333
334             else
335                --  No need to set Awake_Count, State, etc. here since the loop
336                --  below will do that for any Unactivated tasks.
337
338                Unlock (C);
339                Unlock (P);
340                Self_ID.Common.Activation_Failed := True;
341             end if;
342          end if;
343
344          C := C.Common.Activation_Link;
345       end loop;
346
347       if not Single_Lock then
348          Unlock_RTS;
349       end if;
350
351       --  Close the entries of any tasks that failed thread creation, and count
352       --  those that have not finished activation.
353
354       Write_Lock (Self_ID);
355       Self_ID.Common.State := Activator_Sleep;
356
357       C := Chain_Access.T_ID;
358       while C /= null loop
359          Write_Lock (C);
360
361          if C.Common.State = Unactivated then
362             C.Common.Activator := null;
363             C.Common.State := Terminated;
364             C.Callable := False;
365             Utilities.Cancel_Queued_Entry_Calls (C);
366
367          elsif C.Common.Activator /= null then
368             Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1;
369          end if;
370
371          Unlock (C);
372          P := C.Common.Activation_Link;
373          C.Common.Activation_Link := null;
374          C := P;
375       end loop;
376
377       --  Wait for the activated tasks to complete activation. It is
378       --  unsafe to abort any of these tasks until the count goes to zero.
379
380       loop
381          exit when Self_ID.Common.Wait_Count = 0;
382          Sleep (Self_ID, Activator_Sleep);
383       end loop;
384
385       Self_ID.Common.State := Runnable;
386       Unlock (Self_ID);
387
388       if Single_Lock then
389          Unlock_RTS;
390       end if;
391
392       --  Remove the tasks from the chain
393
394       Chain_Access.T_ID := null;
395       Initialization.Undefer_Abort_Nestable (Self_ID);
396
397       if Self_ID.Common.Activation_Failed then
398          Self_ID.Common.Activation_Failed := False;
399          raise Tasking_Error with "Failure during activation";
400       end if;
401    end Activate_Tasks;
402
403    -------------------------
404    -- Complete_Activation --
405    -------------------------
406
407    procedure Complete_Activation is
408       Self_ID : constant Task_Id := STPO.Self;
409
410    begin
411       Initialization.Defer_Abort_Nestable (Self_ID);
412
413       if Single_Lock then
414          Lock_RTS;
415       end if;
416
417       Vulnerable_Complete_Activation (Self_ID);
418
419       if Single_Lock then
420          Unlock_RTS;
421       end if;
422
423       Initialization.Undefer_Abort_Nestable (Self_ID);
424
425       --  ??? Why do we need to allow for nested deferral here?
426
427       if Runtime_Traces then
428          Send_Trace_Info (T_Activate);
429       end if;
430    end Complete_Activation;
431
432    ---------------------
433    -- Complete_Master --
434    ---------------------
435
436    procedure Complete_Master is
437       Self_ID : constant Task_Id := STPO.Self;
438    begin
439       pragma Assert
440         (Self_ID.Deferral_Level > 0
441           or else not System.Restrictions.Abort_Allowed);
442       Vulnerable_Complete_Master (Self_ID);
443    end Complete_Master;
444
445    -------------------
446    -- Complete_Task --
447    -------------------
448
449    --  See comments on Vulnerable_Complete_Task for details
450
451    procedure Complete_Task is
452       Self_ID  : constant Task_Id := STPO.Self;
453
454    begin
455       pragma Assert
456         (Self_ID.Deferral_Level > 0
457           or else not System.Restrictions.Abort_Allowed);
458
459       Vulnerable_Complete_Task (Self_ID);
460
461       --  All of our dependents have terminated. Never undefer abort again!
462
463    end Complete_Task;
464
465    -----------------
466    -- Create_Task --
467    -----------------
468
469    --  Compiler interface only. Do not call from within the RTS. This must be
470    --  called to create a new task.
471
472    procedure Create_Task
473      (Priority          : Integer;
474       Size              : System.Parameters.Size_Type;
475       Task_Info         : System.Task_Info.Task_Info_Type;
476       Relative_Deadline : Ada.Real_Time.Time_Span;
477       Num_Entries       : Task_Entry_Index;
478       Master            : Master_Level;
479       State             : Task_Procedure_Access;
480       Discriminants     : System.Address;
481       Elaborated        : Access_Boolean;
482       Chain             : in out Activation_Chain;
483       Task_Image        : String;
484       Created_Task      : out Task_Id;
485       Build_Entry_Names : Boolean)
486    is
487       T, P          : Task_Id;
488       Self_ID       : constant Task_Id := STPO.Self;
489       Success       : Boolean;
490       Base_Priority : System.Any_Priority;
491       Len           : Natural;
492
493       pragma Unreferenced (Relative_Deadline);
494       --  EDF scheduling is not supported by any of the target platforms so
495       --  this parameter is not passed any further.
496
497    begin
498       --  If Master is greater than the current master, it means that Master
499       --  has already awaited its dependent tasks. This raises Program_Error,
500       --  by 4.8(10.3/2). See AI-280. Ignore this check for foreign threads.
501
502       if Self_ID.Master_of_Task /= Foreign_Task_Level
503         and then Master > Self_ID.Master_Within
504       then
505          raise Program_Error with
506            "create task after awaiting termination";
507       end if;
508
509       --  If pragma Detect_Blocking is active must be checked whether this
510       --  potentially blocking operation is called from a protected action.
511
512       if System.Tasking.Detect_Blocking
513         and then Self_ID.Common.Protected_Action_Nesting > 0
514       then
515          raise Program_Error with "potentially blocking operation";
516       end if;
517
518       pragma Debug
519         (Debug.Trace (Self_ID, "Create_Task", 'C'));
520
521       if Priority = Unspecified_Priority then
522          Base_Priority := Self_ID.Common.Base_Priority;
523       else
524          Base_Priority := System.Any_Priority (Priority);
525       end if;
526
527       --  Find parent P of new Task, via master level number
528
529       P := Self_ID;
530
531       if P /= null then
532          while P.Master_of_Task >= Master loop
533             P := P.Common.Parent;
534             exit when P = null;
535          end loop;
536       end if;
537
538       Initialization.Defer_Abort_Nestable (Self_ID);
539
540       begin
541          T := New_ATCB (Num_Entries);
542       exception
543          when others =>
544             Initialization.Undefer_Abort_Nestable (Self_ID);
545             raise Storage_Error with "Cannot allocate task";
546       end;
547
548       --  RTS_Lock is used by Abort_Dependents and Abort_Tasks. Up to this
549       --  point, it is possible that we may be part of a family of tasks that
550       --  is being aborted.
551
552       Lock_RTS;
553       Write_Lock (Self_ID);
554
555       --  Now, we must check that we have not been aborted. If so, we should
556       --  give up on creating this task, and simply return.
557
558       if not Self_ID.Callable then
559          pragma Assert (Self_ID.Pending_ATC_Level = 0);
560          pragma Assert (Self_ID.Pending_Action);
561          pragma Assert
562            (Chain.T_ID = null or else Chain.T_ID.Common.State = Unactivated);
563
564          Unlock (Self_ID);
565          Unlock_RTS;
566          Initialization.Undefer_Abort_Nestable (Self_ID);
567
568          --  ??? Should never get here
569
570          pragma Assert (False);
571          raise Standard'Abort_Signal;
572       end if;
573
574       Initialize_ATCB (Self_ID, State, Discriminants, P, Elaborated,
575         Base_Priority, Task_Info, Size, T, Success);
576
577       if not Success then
578          Free (T);
579          Unlock (Self_ID);
580          Unlock_RTS;
581          Initialization.Undefer_Abort_Nestable (Self_ID);
582          raise Storage_Error with "Failed to initialize task";
583       end if;
584
585       if Master = Foreign_Task_Level + 2 then
586
587          --  This should not happen, except when a foreign task creates non
588          --  library-level Ada tasks. In this case, we pretend the master is
589          --  a regular library level task, otherwise the run-time will get
590          --  confused when waiting for these tasks to terminate.
591
592          T.Master_of_Task := Library_Task_Level;
593       else
594          T.Master_of_Task := Master;
595       end if;
596
597       T.Master_Within := T.Master_of_Task + 1;
598
599       for L in T.Entry_Calls'Range loop
600          T.Entry_Calls (L).Self := T;
601          T.Entry_Calls (L).Level := L;
602       end loop;
603
604       if Task_Image'Length = 0 then
605          T.Common.Task_Image_Len := 0;
606       else
607          Len := 1;
608          T.Common.Task_Image (1) := Task_Image (Task_Image'First);
609
610          --  Remove unwanted blank space generated by 'Image
611
612          for J in Task_Image'First + 1 .. Task_Image'Last loop
613             if Task_Image (J) /= ' '
614               or else Task_Image (J - 1) /= '('
615             then
616                Len := Len + 1;
617                T.Common.Task_Image (Len) := Task_Image (J);
618                exit when Len = T.Common.Task_Image'Last;
619             end if;
620          end loop;
621
622          T.Common.Task_Image_Len := Len;
623       end if;
624
625       if Build_Entry_Names then
626          T.Entry_Names :=
627            new Entry_Names_Array (1 .. Entry_Index (Num_Entries));
628       end if;
629
630       Unlock (Self_ID);
631       Unlock_RTS;
632
633       --  Create TSD as early as possible in the creation of a task, since it
634       --  may be used by the operation of Ada code within the task.
635
636       SSL.Create_TSD (T.Common.Compiler_Data);
637       T.Common.Activation_Link := Chain.T_ID;
638       Chain.T_ID := T;
639       Initialization.Initialize_Attributes_Link.all (T);
640       Created_Task := T;
641       Initialization.Undefer_Abort_Nestable (Self_ID);
642
643       if Runtime_Traces then
644          Send_Trace_Info (T_Create, T);
645       end if;
646    end Create_Task;
647
648    --------------------
649    -- Current_Master --
650    --------------------
651
652    function Current_Master return Master_Level is
653    begin
654       return STPO.Self.Master_Within;
655    end Current_Master;
656
657    ------------------
658    -- Enter_Master --
659    ------------------
660
661    procedure Enter_Master is
662       Self_ID : constant Task_Id := STPO.Self;
663    begin
664       Self_ID.Master_Within := Self_ID.Master_Within + 1;
665    end Enter_Master;
666
667    -------------------------------
668    -- Expunge_Unactivated_Tasks --
669    -------------------------------
670
671    --  See procedure Close_Entries for the general case
672
673    procedure Expunge_Unactivated_Tasks (Chain : in out Activation_Chain) is
674       Self_ID : constant Task_Id := STPO.Self;
675       C       : Task_Id;
676       Call    : Entry_Call_Link;
677       Temp    : Task_Id;
678
679    begin
680       pragma Debug
681         (Debug.Trace (Self_ID, "Expunge_Unactivated_Tasks", 'C'));
682
683       Initialization.Defer_Abort_Nestable (Self_ID);
684
685       --  ???
686       --  Experimentation has shown that abort is sometimes (but not always)
687       --  already deferred when this is called.
688
689       --  That may indicate an error. Find out what is going on
690
691       C := Chain.T_ID;
692       while C /= null loop
693          pragma Assert (C.Common.State = Unactivated);
694
695          Temp := C.Common.Activation_Link;
696
697          if C.Common.State = Unactivated then
698             Lock_RTS;
699             Write_Lock (C);
700
701             for J in 1 .. C.Entry_Num loop
702                Queuing.Dequeue_Head (C.Entry_Queues (J), Call);
703                pragma Assert (Call = null);
704             end loop;
705
706             Unlock (C);
707
708             Initialization.Remove_From_All_Tasks_List (C);
709             Unlock_RTS;
710
711             Vulnerable_Free_Task (C);
712             C := Temp;
713          end if;
714       end loop;
715
716       Chain.T_ID := null;
717       Initialization.Undefer_Abort_Nestable (Self_ID);
718    end Expunge_Unactivated_Tasks;
719
720    ---------------------------
721    -- Finalize_Global_Tasks --
722    ---------------------------
723
724    --  ???
725    --  We have a potential problem here if finalization of global objects does
726    --  anything with signals or the timer server, since by that time those
727    --  servers have terminated.
728
729    --  It is hard to see how that would occur
730
731    --  However, a better solution might be to do all this finalization
732    --  using the global finalization chain.
733
734    procedure Finalize_Global_Tasks is
735       Self_ID : constant Task_Id := STPO.Self;
736
737       Ignore  : Boolean;
738       pragma Unreferenced (Ignore);
739
740    begin
741       if Self_ID.Deferral_Level = 0 then
742          --  ???
743          --  In principle, we should be able to predict whether abort is
744          --  already deferred here (and it should not be deferred yet but in
745          --  practice it seems Finalize_Global_Tasks is being called sometimes,
746          --  from RTS code for exceptions, with abort already deferred.
747
748          Initialization.Defer_Abort_Nestable (Self_ID);
749
750          --  Never undefer again!!!
751       end if;
752
753       --  This code is only executed by the environment task
754
755       pragma Assert (Self_ID = Environment_Task);
756
757       --  Set Environment_Task'Callable to false to notify library-level tasks
758       --  that it is waiting for them.
759
760       Self_ID.Callable := False;
761
762       --  Exit level 2 master, for normal tasks in library-level packages
763
764       Complete_Master;
765
766       --  Force termination of "independent" library-level server tasks
767
768       Lock_RTS;
769
770       Abort_Dependents (Self_ID);
771
772       if not Single_Lock then
773          Unlock_RTS;
774       end if;
775
776       --  We need to explicitly wait for the task to be terminated here
777       --  because on true concurrent system, we may end this procedure before
778       --  the tasks are really terminated.
779
780       Write_Lock (Self_ID);
781
782       loop
783          exit when Utilities.Independent_Task_Count = 0;
784
785          --  We used to yield here, but this did not take into account low
786          --  priority tasks that would cause dead lock in some cases (true
787          --  FIFO scheduling).
788
789          Timed_Sleep
790            (Self_ID, 0.01, System.OS_Primitives.Relative,
791             Self_ID.Common.State, Ignore, Ignore);
792       end loop;
793
794       --  ??? On multi-processor environments, it seems that the above loop
795       --  isn't sufficient, so we need to add an additional delay.
796
797       Timed_Sleep
798         (Self_ID, 0.01, System.OS_Primitives.Relative,
799          Self_ID.Common.State, Ignore, Ignore);
800
801       Unlock (Self_ID);
802
803       if Single_Lock then
804          Unlock_RTS;
805       end if;
806
807       --  Complete the environment task
808
809       Vulnerable_Complete_Task (Self_ID);
810
811       --  Handle normal task termination by the environment task, but only
812       --  for the normal task termination. In the case of Abnormal and
813       --  Unhandled_Exception they must have been handled before, and the
814       --  task termination soft link must have been changed so the task
815       --  termination routine is not executed twice.
816
817       SSL.Task_Termination_Handler.all (Ada.Exceptions.Null_Occurrence);
818
819       --  Finalize the global list for controlled objects if needed
820
821       SSL.Finalize_Global_List.all;
822
823       --  Reset the soft links to non-tasking
824
825       SSL.Abort_Defer        := SSL.Abort_Defer_NT'Access;
826       SSL.Abort_Undefer      := SSL.Abort_Undefer_NT'Access;
827       SSL.Lock_Task          := SSL.Task_Lock_NT'Access;
828       SSL.Unlock_Task        := SSL.Task_Unlock_NT'Access;
829       SSL.Get_Jmpbuf_Address := SSL.Get_Jmpbuf_Address_NT'Access;
830       SSL.Set_Jmpbuf_Address := SSL.Set_Jmpbuf_Address_NT'Access;
831       SSL.Get_Sec_Stack_Addr := SSL.Get_Sec_Stack_Addr_NT'Access;
832       SSL.Set_Sec_Stack_Addr := SSL.Set_Sec_Stack_Addr_NT'Access;
833       SSL.Check_Abort_Status := SSL.Check_Abort_Status_NT'Access;
834       SSL.Get_Stack_Info     := SSL.Get_Stack_Info_NT'Access;
835
836       --  Don't bother trying to finalize Initialization.Global_Task_Lock
837       --  and System.Task_Primitives.RTS_Lock.
838
839    end Finalize_Global_Tasks;
840
841    ----------------------
842    -- Free_Entry_Names --
843    ----------------------
844
845    procedure Free_Entry_Names (T : Task_Id) is
846       Names : Entry_Names_Array_Access := T.Entry_Names;
847
848       procedure Free_Entry_Names_Array_Access is new
849         Ada.Unchecked_Deallocation
850           (Entry_Names_Array, Entry_Names_Array_Access);
851
852    begin
853       if Names = null then
854          return;
855       end if;
856
857       Free_Entry_Names_Array (Names.all);
858       Free_Entry_Names_Array_Access (Names);
859    end Free_Entry_Names;
860
861    ---------------
862    -- Free_Task --
863    ---------------
864
865    procedure Free_Task (T : Task_Id) is
866       Self_Id : constant Task_Id := Self;
867
868    begin
869       if T.Common.State = Terminated then
870
871          --  It is not safe to call Abort_Defer or Write_Lock at this stage
872
873          Initialization.Task_Lock (Self_Id);
874
875          Lock_RTS;
876          Initialization.Finalize_Attributes_Link.all (T);
877          Initialization.Remove_From_All_Tasks_List (T);
878          Unlock_RTS;
879
880          Initialization.Task_Unlock (Self_Id);
881
882          Free_Entry_Names (T);
883          System.Task_Primitives.Operations.Finalize_TCB (T);
884
885       --  If the task is not terminated, then we simply ignore the call. This
886       --  happens when a user program attempts an unchecked deallocation on
887       --  a non-terminated task.
888
889       else
890          null;
891       end if;
892    end Free_Task;
893
894    ---------------------------
895    -- Move_Activation_Chain --
896    ---------------------------
897
898    procedure Move_Activation_Chain
899      (From, To   : Activation_Chain_Access;
900       New_Master : Master_ID)
901    is
902       Self_ID : constant Task_Id := STPO.Self;
903       C       : Task_Id;
904
905    begin
906       pragma Debug
907         (Debug.Trace (Self_ID, "Move_Activation_Chain", 'C'));
908
909       --  Nothing to do if From is empty, and we can check that without
910       --  deferring aborts.
911
912       C := From.all.T_ID;
913
914       if C = null then
915          return;
916       end if;
917
918       Initialization.Defer_Abort (Self_ID);
919
920       --  Loop through the From chain, changing their Master_of_Task
921       --  fields, and to find the end of the chain.
922
923       loop
924          C.Master_of_Task := New_Master;
925          exit when C.Common.Activation_Link = null;
926          C := C.Common.Activation_Link;
927       end loop;
928
929       --  Hook From in at the start of To
930
931       C.Common.Activation_Link := To.all.T_ID;
932       To.all.T_ID := From.all.T_ID;
933
934       --  Set From to empty
935
936       From.all.T_ID := null;
937
938       Initialization.Undefer_Abort (Self_ID);
939    end Move_Activation_Chain;
940
941    --  Compiler interface only. Do not call from within the RTS
942
943    --------------------
944    -- Set_Entry_Name --
945    --------------------
946
947    procedure Set_Entry_Name
948      (T   : Task_Id;
949       Pos : Task_Entry_Index;
950       Val : String_Access)
951    is
952    begin
953       pragma Assert (T.Entry_Names /= null);
954
955       T.Entry_Names (Entry_Index (Pos)) := Val;
956    end Set_Entry_Name;
957
958    ------------------
959    -- Task_Wrapper --
960    ------------------
961
962    --  The task wrapper is a procedure that is called first for each task body
963    --  and which in turn calls the compiler-generated task body procedure.
964    --  The wrapper's main job is to do initialization for the task. It also
965    --  has some locally declared objects that serve as per-task local data.
966    --  Task finalization is done by Complete_Task, which is called from an
967    --  at-end handler that the compiler generates.
968
969    procedure Task_Wrapper (Self_ID : Task_Id) is
970       use type SSE.Storage_Offset;
971       use System.Standard_Library;
972       use System.Stack_Usage;
973
974       Bottom_Of_Stack : aliased Integer;
975
976       Task_Alternate_Stack :
977         aliased SSE.Storage_Array (1 .. Alternate_Stack_Size);
978       --  The alternate signal stack for this task, if any
979
980       Use_Alternate_Stack : constant Boolean := Alternate_Stack_Size /= 0;
981       --  Whether to use above alternate signal stack for stack overflows
982
983       Secondary_Stack_Size :
984         constant SSE.Storage_Offset :=
985           Self_ID.Common.Compiler_Data.Pri_Stack_Info.Size *
986           SSE.Storage_Offset (Parameters.Sec_Stack_Ratio) / 100;
987
988       Secondary_Stack : aliased SSE.Storage_Array (1 .. Secondary_Stack_Size);
989
990       pragma Warnings (Off);
991       --  Why are warnings being turned off here???
992
993       Secondary_Stack_Address : System.Address := Secondary_Stack'Address;
994       --  Address of secondary stack. In the fixed secondary stack case, this
995       --  value is not modified, causing a warning, hence the bracketing with
996       --  Warnings (Off/On). But why is so much *more* bracketed???
997
998       Small_Overflow_Guard : constant := 12 * 1024;
999       --  Note: this used to be 4K, but was changed to 12K, since smaller
1000       --  values resulted in segmentation faults from dynamic stack analysis.
1001
1002       Big_Overflow_Guard   : constant := 16 * 1024;
1003       Small_Stack_Limit    : constant := 64 * 1024;
1004       --  ??? These three values are experimental, and seems to work on most
1005       --  platforms. They still need to be analyzed further. They also need
1006       --  documentation, what are they???
1007
1008       Size : Natural :=
1009                Natural (Self_ID.Common.Compiler_Data.Pri_Stack_Info.Size);
1010
1011       Overflow_Guard : Natural;
1012       --  Size of the overflow guard, used by dynamic stack usage analysis
1013
1014       pragma Warnings (On);
1015
1016       SEH_Table : aliased SSE.Storage_Array (1 .. 8);
1017       --  Structured Exception Registration table (2 words)
1018
1019       procedure Install_SEH_Handler (Addr : System.Address);
1020       pragma Import (C, Install_SEH_Handler, "__gnat_install_SEH_handler");
1021       --  Install the SEH (Structured Exception Handling) handler
1022
1023       Cause : Cause_Of_Termination := Normal;
1024       --  Indicates the reason why this task terminates. Normal corresponds to
1025       --  a task terminating due to completing the last statement of its body,
1026       --  or as a result of waiting on a terminate alternative. If the task
1027       --  terminates because it is being aborted then Cause will be set to
1028       --  Abnormal. If the task terminates because of an exception raised by
1029       --  the execution of its task body, then Cause is set to
1030       --  Unhandled_Exception.
1031
1032       EO : Exception_Occurrence;
1033       --  If the task terminates because of an exception raised by the
1034       --  execution of its task body, then EO will contain the associated
1035       --  exception occurrence. Otherwise, it will contain Null_Occurrence.
1036
1037       TH : Termination_Handler := null;
1038       --  Pointer to the protected procedure to be executed upon task
1039       --  termination.
1040
1041       procedure Search_Fall_Back_Handler (ID : Task_Id);
1042       --  Procedure that searches recursively a fall-back handler through the
1043       --  master relationship. If the handler is found, its pointer is stored
1044       --  in TH.
1045
1046       ------------------------------
1047       -- Search_Fall_Back_Handler --
1048       ------------------------------
1049
1050       procedure Search_Fall_Back_Handler (ID : Task_Id) is
1051       begin
1052          --  If there is a fall back handler, store its pointer for later
1053          --  execution.
1054
1055          if ID.Common.Fall_Back_Handler /= null then
1056             TH := ID.Common.Fall_Back_Handler;
1057
1058          --  Otherwise look for a fall back handler in the parent
1059
1060          elsif ID.Common.Parent /= null then
1061             Search_Fall_Back_Handler (ID.Common.Parent);
1062
1063          --  Otherwise, do nothing
1064
1065          else
1066             return;
1067          end if;
1068       end Search_Fall_Back_Handler;
1069
1070    begin
1071       pragma Assert (Self_ID.Deferral_Level = 1);
1072
1073       --  Assume a size of the stack taken at this stage
1074
1075       if Size < Small_Stack_Limit then
1076          Overflow_Guard := Small_Overflow_Guard;
1077       else
1078          Overflow_Guard := Big_Overflow_Guard;
1079       end if;
1080
1081       if not Parameters.Sec_Stack_Dynamic then
1082          Self_ID.Common.Compiler_Data.Sec_Stack_Addr :=
1083            Secondary_Stack'Address;
1084          SST.SS_Init (Secondary_Stack_Address, Integer (Secondary_Stack'Last));
1085          Size := Size - Natural (Secondary_Stack_Size);
1086       end if;
1087
1088       if Use_Alternate_Stack then
1089          Self_ID.Common.Task_Alternate_Stack := Task_Alternate_Stack'Address;
1090       end if;
1091
1092       Size := Size - Overflow_Guard;
1093
1094       if System.Stack_Usage.Is_Enabled then
1095          STPO.Lock_RTS;
1096          Initialize_Analyzer
1097            (Self_ID.Common.Analyzer,
1098             Self_ID.Common.Task_Image
1099               (1 .. Self_ID.Common.Task_Image_Len),
1100             Natural
1101               (Self_ID.Common.Compiler_Data.Pri_Stack_Info.Size),
1102             Size,
1103             SSE.To_Integer (Bottom_Of_Stack'Address));
1104          STPO.Unlock_RTS;
1105          Fill_Stack (Self_ID.Common.Analyzer);
1106       end if;
1107
1108       --  Set the guard page at the bottom of the stack. The call to unprotect
1109       --  the page is done in Terminate_Task
1110
1111       Stack_Guard (Self_ID, True);
1112
1113       --  Initialize low-level TCB components, that cannot be initialized by
1114       --  the creator. Enter_Task sets Self_ID.LL.Thread
1115
1116       Enter_Task (Self_ID);
1117
1118       --  We setup the SEH (Structured Exception Handling) handler if supported
1119       --  on the target.
1120
1121       Install_SEH_Handler (SEH_Table'Address);
1122
1123       --  Initialize exception occurrence
1124
1125       Save_Occurrence (EO, Ada.Exceptions.Null_Occurrence);
1126
1127       --  We lock RTS_Lock to wait for activator to finish activating the rest
1128       --  of the chain, so that everyone in the chain comes out in priority
1129       --  order.
1130
1131       --  This also protects the value of
1132       --    Self_ID.Common.Activator.Common.Wait_Count.
1133
1134       Lock_RTS;
1135       Unlock_RTS;
1136
1137       if not System.Restrictions.Abort_Allowed then
1138
1139          --  If Abort is not allowed, reset the deferral level since it will
1140          --  not get changed by the generated code. Keeping a default value
1141          --  of one would prevent some operations (e.g. select or delay) to
1142          --  proceed successfully.
1143
1144          Self_ID.Deferral_Level := 0;
1145       end if;
1146
1147       if Global_Task_Debug_Event_Set then
1148          Debug.Signal_Debug_Event
1149           (Debug.Debug_Event_Run, Self_ID);
1150       end if;
1151
1152       begin
1153          --  We are separating the following portion of the code in order to
1154          --  place the exception handlers in a different block. In this way,
1155          --  we do not call Set_Jmpbuf_Address (which needs Self) before we
1156          --  set Self in Enter_Task
1157
1158          --  Call the task body procedure
1159
1160          --  The task body is called with abort still deferred. That
1161          --  eliminates a dangerous window, for which we had to patch-up in
1162          --  Terminate_Task.
1163
1164          --  During the expansion of the task body, we insert an RTS-call
1165          --  to Abort_Undefer, at the first point where abort should be
1166          --  allowed.
1167
1168          Self_ID.Common.Task_Entry_Point (Self_ID.Common.Task_Arg);
1169          Initialization.Defer_Abort_Nestable (Self_ID);
1170
1171       exception
1172          --  We can't call Terminate_Task in the exception handlers below,
1173          --  since there may be (e.g. in the case of GCC exception handling)
1174          --  clean ups associated with the exception handler that need to
1175          --  access task specific data.
1176
1177          --  Defer abort so that this task can't be aborted while exiting
1178
1179          when Standard'Abort_Signal =>
1180             Initialization.Defer_Abort_Nestable (Self_ID);
1181
1182             --  Update the cause that motivated the task termination so that
1183             --  the appropriate information is passed to the task termination
1184             --  procedure. Task termination as a result of waiting on a
1185             --  terminate alternative is a normal termination, although it is
1186             --  implemented using the abort mechanisms.
1187
1188             if Self_ID.Terminate_Alternative then
1189                Cause := Normal;
1190
1191                if Global_Task_Debug_Event_Set then
1192                   Debug.Signal_Debug_Event
1193                    (Debug.Debug_Event_Terminated, Self_ID);
1194                end if;
1195             else
1196                Cause := Abnormal;
1197
1198                if Global_Task_Debug_Event_Set then
1199                   Debug.Signal_Debug_Event
1200                    (Debug.Debug_Event_Abort_Terminated, Self_ID);
1201                end if;
1202             end if;
1203          when others =>
1204             --  ??? Using an E : others here causes CD2C11A to fail on Tru64
1205
1206             Initialization.Defer_Abort_Nestable (Self_ID);
1207
1208             --  Perform the task specific exception tracing duty.  We handle
1209             --  these outputs here and not in the common notification routine
1210             --  because we need access to tasking related data and we don't
1211             --  want to drag dependencies against tasking related units in the
1212             --  the common notification units. Additionally, no trace is ever
1213             --  triggered from the common routine for the Unhandled_Raise case
1214             --  in tasks, since an exception never appears unhandled in this
1215             --  context because of this handler.
1216
1217             if Exception_Trace = Unhandled_Raise then
1218                Trace_Unhandled_Exception_In_Task (Self_ID);
1219             end if;
1220
1221             --  Update the cause that motivated the task termination so that
1222             --  the appropriate information is passed to the task termination
1223             --  procedure, as well as the associated Exception_Occurrence.
1224
1225             Cause := Unhandled_Exception;
1226
1227             Save_Occurrence (EO, SSL.Get_Current_Excep.all.all);
1228
1229             if Global_Task_Debug_Event_Set then
1230                Debug.Signal_Debug_Event
1231                  (Debug.Debug_Event_Exception_Terminated, Self_ID);
1232             end if;
1233       end;
1234
1235       --  Look for a task termination handler. This code is for all tasks but
1236       --  the environment task. The task termination code for the environment
1237       --  task is executed by SSL.Task_Termination_Handler.
1238
1239       if Single_Lock then
1240          Lock_RTS;
1241       end if;
1242
1243       Write_Lock (Self_ID);
1244
1245       if Self_ID.Common.Specific_Handler /= null then
1246          TH := Self_ID.Common.Specific_Handler;
1247       else
1248          --  Look for a fall-back handler following the master relationship
1249          --  for the task.
1250
1251          Search_Fall_Back_Handler (Self_ID);
1252       end if;
1253
1254       Unlock (Self_ID);
1255
1256       if Single_Lock then
1257          Unlock_RTS;
1258       end if;
1259
1260       --  Execute the task termination handler if we found it
1261
1262       if TH /= null then
1263          TH.all (Cause, Self_ID, EO);
1264       end if;
1265
1266       if System.Stack_Usage.Is_Enabled then
1267          Compute_Result (Self_ID.Common.Analyzer);
1268          Report_Result (Self_ID.Common.Analyzer);
1269       end if;
1270
1271       Terminate_Task (Self_ID);
1272    end Task_Wrapper;
1273
1274    --------------------
1275    -- Terminate_Task --
1276    --------------------
1277
1278    --  Before we allow the thread to exit, we must clean up. This is a
1279    --  delicate job. We must wake up the task's master, who may immediately try
1280    --  to deallocate the ATCB out from under the current task WHILE IT IS STILL
1281    --  EXECUTING.
1282
1283    --  To avoid this, the parent task must be blocked up to the latest
1284    --  statement executed. The trouble is that we have another step that we
1285    --  also want to postpone to the very end, i.e., calling SSL.Destroy_TSD.
1286    --  We have to postpone that until the end because compiler-generated code
1287    --  is likely to try to access that data at just about any point.
1288
1289    --  We can't call Destroy_TSD while we are holding any other locks, because
1290    --  it locks Global_Task_Lock, and our deadlock prevention rules require
1291    --  that to be the outermost lock. Our first "solution" was to just lock
1292    --  Global_Task_Lock in addition to the other locks, and force the parent to
1293    --  also lock this lock between its wakeup and its freeing of the ATCB. See
1294    --  Complete_Task for the parent-side of the code that has the matching
1295    --  calls to Task_Lock and Task_Unlock. That was not really a solution,
1296    --  since the operation Task_Unlock continued to access the ATCB after
1297    --  unlocking, after which the parent was observed to race ahead, deallocate
1298    --  the ATCB, and then reallocate it to another task. The call to
1299    --  Undefer_Abort in Task_Unlock by the "terminated" task was overwriting
1300    --  the data of the new task that reused the ATCB! To solve this problem, we
1301    --  introduced the new operation Final_Task_Unlock.
1302
1303    procedure Terminate_Task (Self_ID : Task_Id) is
1304       Environment_Task : constant Task_Id := STPO.Environment_Task;
1305       Master_of_Task   : Integer;
1306
1307    begin
1308       Debug.Task_Termination_Hook;
1309
1310       if Runtime_Traces then
1311          Send_Trace_Info (T_Terminate);
1312       end if;
1313
1314       --  Since GCC cannot allocate stack chunks efficiently without reordering
1315       --  some of the allocations, we have to handle this unexpected situation
1316       --  here. We should normally never have to call Vulnerable_Complete_Task
1317       --  here.
1318
1319       if Self_ID.Common.Activator /= null then
1320          Vulnerable_Complete_Task (Self_ID);
1321       end if;
1322
1323       Initialization.Task_Lock (Self_ID);
1324
1325       if Single_Lock then
1326          Lock_RTS;
1327       end if;
1328
1329       Master_of_Task := Self_ID.Master_of_Task;
1330
1331       --  Check if the current task is an independent task If so, decrement
1332       --  the Independent_Task_Count value.
1333
1334       if Master_of_Task = Independent_Task_Level then
1335          if Single_Lock then
1336             Utilities.Independent_Task_Count :=
1337               Utilities.Independent_Task_Count - 1;
1338          else
1339             Write_Lock (Environment_Task);
1340             Utilities.Independent_Task_Count :=
1341               Utilities.Independent_Task_Count - 1;
1342             Unlock (Environment_Task);
1343          end if;
1344       end if;
1345
1346       --  Unprotect the guard page if needed
1347
1348       Stack_Guard (Self_ID, False);
1349
1350       Utilities.Make_Passive (Self_ID, Task_Completed => True);
1351
1352       if Single_Lock then
1353          Unlock_RTS;
1354       end if;
1355
1356       pragma Assert (Check_Exit (Self_ID));
1357
1358       SSL.Destroy_TSD (Self_ID.Common.Compiler_Data);
1359       Initialization.Final_Task_Unlock (Self_ID);
1360
1361       --  WARNING: past this point, this thread must assume that the ATCB has
1362       --  been deallocated. It should not be accessed again.
1363
1364       if Master_of_Task > 0 then
1365          STPO.Exit_Task;
1366       end if;
1367    end Terminate_Task;
1368
1369    ----------------
1370    -- Terminated --
1371    ----------------
1372
1373    function Terminated (T : Task_Id) return Boolean is
1374       Self_ID : constant Task_Id := STPO.Self;
1375       Result  : Boolean;
1376
1377    begin
1378       Initialization.Defer_Abort_Nestable (Self_ID);
1379
1380       if Single_Lock then
1381          Lock_RTS;
1382       end if;
1383
1384       Write_Lock (T);
1385       Result := T.Common.State = Terminated;
1386       Unlock (T);
1387
1388       if Single_Lock then
1389          Unlock_RTS;
1390       end if;
1391
1392       Initialization.Undefer_Abort_Nestable (Self_ID);
1393       return Result;
1394    end Terminated;
1395
1396    ----------------------------------------
1397    -- Trace_Unhandled_Exception_In_Task --
1398    ----------------------------------------
1399
1400    procedure Trace_Unhandled_Exception_In_Task (Self_Id : Task_Id) is
1401       procedure To_Stderr (S : String);
1402       pragma Import (Ada, To_Stderr, "__gnat_to_stderr");
1403
1404       use System.Soft_Links;
1405       use System.Standard_Library;
1406
1407       function To_Address is new
1408         Ada.Unchecked_Conversion
1409          (Task_Id, System.Task_Primitives.Task_Address);
1410
1411       function Tailored_Exception_Information
1412         (E : Exception_Occurrence) return String;
1413       pragma Import
1414         (Ada, Tailored_Exception_Information,
1415          "__gnat_tailored_exception_information");
1416
1417       Excep : constant Exception_Occurrence_Access :=
1418                 SSL.Get_Current_Excep.all;
1419
1420    begin
1421       --  This procedure is called by the task outermost handler in
1422       --  Task_Wrapper below, so only once the task stack has been fully
1423       --  unwound. The common notification routine has been called at the
1424       --  raise point already.
1425
1426       --  Lock to prevent unsynchronized output
1427
1428       Initialization.Task_Lock (Self_Id);
1429       To_Stderr ("task ");
1430
1431       if Self_Id.Common.Task_Image_Len /= 0 then
1432          To_Stderr
1433            (Self_Id.Common.Task_Image (1 .. Self_Id.Common.Task_Image_Len));
1434          To_Stderr ("_");
1435       end if;
1436
1437       To_Stderr (System.Address_Image (To_Address (Self_Id)));
1438       To_Stderr (" terminated by unhandled exception");
1439       To_Stderr ((1 => ASCII.LF));
1440       To_Stderr (Tailored_Exception_Information (Excep.all));
1441       Initialization.Task_Unlock (Self_Id);
1442    end Trace_Unhandled_Exception_In_Task;
1443
1444    ------------------------------------
1445    -- Vulnerable_Complete_Activation --
1446    ------------------------------------
1447
1448    --  As in several other places, the locks of the activator and activated
1449    --  task are both locked here. This follows our deadlock prevention lock
1450    --  ordering policy, since the activated task must be created after the
1451    --  activator.
1452
1453    procedure Vulnerable_Complete_Activation (Self_ID : Task_Id) is
1454       Activator : constant Task_Id := Self_ID.Common.Activator;
1455
1456    begin
1457       pragma Debug (Debug.Trace (Self_ID, "V_Complete_Activation", 'C'));
1458
1459       Write_Lock (Activator);
1460       Write_Lock (Self_ID);
1461
1462       pragma Assert (Self_ID.Common.Activator /= null);
1463
1464       --  Remove dangling reference to Activator, since a task may
1465       --  outlive its activator.
1466
1467       Self_ID.Common.Activator := null;
1468
1469       --  Wake up the activator, if it is waiting for a chain of tasks to
1470       --  activate, and we are the last in the chain to complete activation.
1471
1472       if Activator.Common.State = Activator_Sleep then
1473          Activator.Common.Wait_Count := Activator.Common.Wait_Count - 1;
1474
1475          if Activator.Common.Wait_Count = 0 then
1476             Wakeup (Activator, Activator_Sleep);
1477          end if;
1478       end if;
1479
1480       --  The activator raises a Tasking_Error if any task it is activating
1481       --  is completed before the activation is done. However, if the reason
1482       --  for the task completion is an abort, we do not raise an exception.
1483       --  See RM 9.2(5).
1484
1485       if not Self_ID.Callable and then Self_ID.Pending_ATC_Level /= 0 then
1486          Activator.Common.Activation_Failed := True;
1487       end if;
1488
1489       Unlock (Self_ID);
1490       Unlock (Activator);
1491
1492       --  After the activation, active priority should be the same as base
1493       --  priority. We must unlock the Activator first, though, since it
1494       --  should not wait if we have lower priority.
1495
1496       if Get_Priority (Self_ID) /= Self_ID.Common.Base_Priority then
1497          Write_Lock (Self_ID);
1498          Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
1499          Unlock (Self_ID);
1500       end if;
1501    end Vulnerable_Complete_Activation;
1502
1503    --------------------------------
1504    -- Vulnerable_Complete_Master --
1505    --------------------------------
1506
1507    procedure Vulnerable_Complete_Master (Self_ID : Task_Id) is
1508       C  : Task_Id;
1509       P  : Task_Id;
1510       CM : constant Master_Level := Self_ID.Master_Within;
1511       T  : aliased Task_Id;
1512
1513       To_Be_Freed : Task_Id;
1514       --  This is a list of ATCBs to be freed, after we have released all RTS
1515       --  locks. This is necessary because of the locking order rules, since
1516       --  the storage manager uses Global_Task_Lock.
1517
1518       pragma Warnings (Off);
1519       function Check_Unactivated_Tasks return Boolean;
1520       pragma Warnings (On);
1521       --  Temporary error-checking code below. This is part of the checks
1522       --  added in the new run time. Call it only inside a pragma Assert.
1523
1524       -----------------------------
1525       -- Check_Unactivated_Tasks --
1526       -----------------------------
1527
1528       function Check_Unactivated_Tasks return Boolean is
1529       begin
1530          if not Single_Lock then
1531             Lock_RTS;
1532          end if;
1533
1534          Write_Lock (Self_ID);
1535
1536          C := All_Tasks_List;
1537          while C /= null loop
1538             if C.Common.Activator = Self_ID and then C.Master_of_Task = CM then
1539                return False;
1540             end if;
1541
1542             if C.Common.Parent = Self_ID and then C.Master_of_Task = CM then
1543                Write_Lock (C);
1544
1545                if C.Common.State = Unactivated then
1546                   return False;
1547                end if;
1548
1549                Unlock (C);
1550             end if;
1551
1552             C := C.Common.All_Tasks_Link;
1553          end loop;
1554
1555          Unlock (Self_ID);
1556
1557          if not Single_Lock then
1558             Unlock_RTS;
1559          end if;
1560
1561          return True;
1562       end Check_Unactivated_Tasks;
1563
1564    --  Start of processing for Vulnerable_Complete_Master
1565
1566    begin
1567       pragma Debug
1568         (Debug.Trace (Self_ID, "V_Complete_Master", 'C'));
1569
1570       pragma Assert (Self_ID.Common.Wait_Count = 0);
1571       pragma Assert
1572         (Self_ID.Deferral_Level > 0
1573           or else not System.Restrictions.Abort_Allowed);
1574
1575       --  Count how many active dependent tasks this master currently has, and
1576       --  record this in Wait_Count.
1577
1578       --  This count should start at zero, since it is initialized to zero for
1579       --  new tasks, and the task should not exit the sleep-loops that use this
1580       --  count until the count reaches zero.
1581
1582       --  While we're counting, if we run across any unactivated tasks that
1583       --  belong to this master, we summarily terminate them as required by
1584       --  RM-9.2(6).
1585
1586       Lock_RTS;
1587       Write_Lock (Self_ID);
1588
1589       C := All_Tasks_List;
1590       while C /= null loop
1591
1592          --  Terminate unactivated (never-to-be activated) tasks
1593
1594          if C.Common.Activator = Self_ID and then C.Master_of_Task = CM then
1595
1596             pragma Assert (C.Common.State = Unactivated);
1597             --  Usually, C.Common.Activator = Self_ID implies C.Master_of_Task
1598             --  = CM. The only case where C is pending activation by this
1599             --  task, but the master of C is not CM is in Ada 2005, when C is
1600             --  part of a return object of a build-in-place function.
1601
1602             Write_Lock (C);
1603             C.Common.Activator := null;
1604             C.Common.State := Terminated;
1605             C.Callable := False;
1606             Utilities.Cancel_Queued_Entry_Calls (C);
1607             Unlock (C);
1608          end if;
1609
1610          --  Count it if dependent on this master
1611
1612          if C.Common.Parent = Self_ID and then C.Master_of_Task = CM then
1613             Write_Lock (C);
1614
1615             if C.Awake_Count /= 0 then
1616                Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1;
1617             end if;
1618
1619             Unlock (C);
1620          end if;
1621
1622          C := C.Common.All_Tasks_Link;
1623       end loop;
1624
1625       Self_ID.Common.State := Master_Completion_Sleep;
1626       Unlock (Self_ID);
1627
1628       if not Single_Lock then
1629          Unlock_RTS;
1630       end if;
1631
1632       --  Wait until dependent tasks are all terminated or ready to terminate.
1633       --  While waiting, the task may be awakened if the task's priority needs
1634       --  changing, or this master is aborted. In the latter case, we abort the
1635       --  dependents, and resume waiting until Wait_Count goes to zero.
1636
1637       Write_Lock (Self_ID);
1638
1639       loop
1640          exit when Self_ID.Common.Wait_Count = 0;
1641
1642          --  Here is a difference as compared to Complete_Master
1643
1644          if Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
1645            and then not Self_ID.Dependents_Aborted
1646          then
1647             if Single_Lock then
1648                Abort_Dependents (Self_ID);
1649             else
1650                Unlock (Self_ID);
1651                Lock_RTS;
1652                Abort_Dependents (Self_ID);
1653                Unlock_RTS;
1654                Write_Lock (Self_ID);
1655             end if;
1656          else
1657             Sleep (Self_ID, Master_Completion_Sleep);
1658          end if;
1659       end loop;
1660
1661       Self_ID.Common.State := Runnable;
1662       Unlock (Self_ID);
1663
1664       --  Dependents are all terminated or on terminate alternatives. Now,
1665       --  force those on terminate alternatives to terminate, by aborting them.
1666
1667       pragma Assert (Check_Unactivated_Tasks);
1668
1669       if Self_ID.Alive_Count > 1 then
1670          --  ???
1671          --  Consider finding a way to skip the following extra steps if there
1672          --  are no dependents with terminate alternatives. This could be done
1673          --  by adding another count to the ATCB, similar to Awake_Count, but
1674          --  keeping track of tasks that are on terminate alternatives.
1675
1676          pragma Assert (Self_ID.Common.Wait_Count = 0);
1677
1678          --  Force any remaining dependents to terminate by aborting them
1679
1680          if not Single_Lock then
1681             Lock_RTS;
1682          end if;
1683
1684          Abort_Dependents (Self_ID);
1685
1686          --  Above, when we "abort" the dependents we are simply using this
1687          --  operation for convenience. We are not required to support the full
1688          --  abort-statement semantics; in particular, we are not required to
1689          --  immediately cancel any queued or in-service entry calls. That is
1690          --  good, because if we tried to cancel a call we would need to lock
1691          --  the caller, in order to wake the caller up. Our anti-deadlock
1692          --  rules prevent us from doing that without releasing the locks on C
1693          --  and Self_ID. Releasing and retaking those locks would be wasteful
1694          --  at best, and should not be considered further without more
1695          --  detailed analysis of potential concurrent accesses to the ATCBs
1696          --  of C and Self_ID.
1697
1698          --  Count how many "alive" dependent tasks this master currently has,
1699          --  and record this in Wait_Count. This count should start at zero,
1700          --  since it is initialized to zero for new tasks, and the task should
1701          --  not exit the sleep-loops that use this count until the count
1702          --  reaches zero.
1703
1704          pragma Assert (Self_ID.Common.Wait_Count = 0);
1705
1706          Write_Lock (Self_ID);
1707
1708          C := All_Tasks_List;
1709          while C /= null loop
1710             if C.Common.Parent = Self_ID and then C.Master_of_Task = CM then
1711                Write_Lock (C);
1712
1713                pragma Assert (C.Awake_Count = 0);
1714
1715                if C.Alive_Count > 0 then
1716                   pragma Assert (C.Terminate_Alternative);
1717                   Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1;
1718                end if;
1719
1720                Unlock (C);
1721             end if;
1722
1723             C := C.Common.All_Tasks_Link;
1724          end loop;
1725
1726          Self_ID.Common.State := Master_Phase_2_Sleep;
1727          Unlock (Self_ID);
1728
1729          if not Single_Lock then
1730             Unlock_RTS;
1731          end if;
1732
1733          --  Wait for all counted tasks to finish terminating themselves
1734
1735          Write_Lock (Self_ID);
1736
1737          loop
1738             exit when Self_ID.Common.Wait_Count = 0;
1739             Sleep (Self_ID, Master_Phase_2_Sleep);
1740          end loop;
1741
1742          Self_ID.Common.State := Runnable;
1743          Unlock (Self_ID);
1744       end if;
1745
1746       --  We don't wake up for abort here. We are already terminating just as
1747       --  fast as we can, so there is no point.
1748
1749       --  Remove terminated tasks from the list of Self_ID's dependents, but
1750       --  don't free their ATCBs yet, because of lock order restrictions, which
1751       --  don't allow us to call "free" or "malloc" while holding any other
1752       --  locks. Instead, we put those ATCBs to be freed onto a temporary list,
1753       --  called To_Be_Freed.
1754
1755       if not Single_Lock then
1756          Lock_RTS;
1757       end if;
1758
1759       C := All_Tasks_List;
1760       P := null;
1761       while C /= null loop
1762          if C.Common.Parent = Self_ID and then C.Master_of_Task >= CM then
1763             if P /= null then
1764                P.Common.All_Tasks_Link := C.Common.All_Tasks_Link;
1765             else
1766                All_Tasks_List := C.Common.All_Tasks_Link;
1767             end if;
1768
1769             T := C.Common.All_Tasks_Link;
1770             C.Common.All_Tasks_Link := To_Be_Freed;
1771             To_Be_Freed := C;
1772             C := T;
1773
1774          else
1775             P := C;
1776             C := C.Common.All_Tasks_Link;
1777          end if;
1778       end loop;
1779
1780       Unlock_RTS;
1781
1782       --  Free all the ATCBs on the list To_Be_Freed
1783
1784       --  The ATCBs in the list are no longer in All_Tasks_List, and after
1785       --  any interrupt entries are detached from them they should no longer
1786       --  be referenced.
1787
1788       --  Global_Task_Lock (Task_Lock/Unlock) is locked in the loop below to
1789       --  avoid a race between a terminating task and its parent. The parent
1790       --  might try to deallocate the ACTB out from underneath the exiting
1791       --  task. Note that Free will also lock Global_Task_Lock, but that is
1792       --  OK, since this is the *one* lock for which we have a mechanism to
1793       --  support nested locking. See Task_Wrapper and its finalizer for more
1794       --  explanation.
1795
1796       --  ???
1797       --  The check "T.Common.Parent /= null ..." below is to prevent dangling
1798       --  references to terminated library-level tasks, which could otherwise
1799       --  occur during finalization of library-level objects. A better solution
1800       --  might be to hook task objects into the finalization chain and
1801       --  deallocate the ATCB when the task object is deallocated. However,
1802       --  this change is not likely to gain anything significant, since all
1803       --  this storage should be recovered en-masse when the process exits.
1804
1805       while To_Be_Freed /= null loop
1806          T := To_Be_Freed;
1807          To_Be_Freed := T.Common.All_Tasks_Link;
1808
1809          --  ??? On SGI there is currently no Interrupt_Manager, that's
1810          --  why we need to check if the Interrupt_Manager_ID is null
1811
1812          if T.Interrupt_Entry and Interrupt_Manager_ID /= null then
1813             declare
1814                Detach_Interrupt_Entries_Index : constant Task_Entry_Index := 1;
1815                --  Corresponds to the entry index of System.Interrupts.
1816                --  Interrupt_Manager.Detach_Interrupt_Entries.
1817                --  Be sure to update this value when changing
1818                --  Interrupt_Manager specs.
1819
1820                type Param_Type is access all Task_Id;
1821
1822                Param : aliased Param_Type := T'Access;
1823
1824             begin
1825                System.Tasking.Rendezvous.Call_Simple
1826                  (Interrupt_Manager_ID, Detach_Interrupt_Entries_Index,
1827                   Param'Address);
1828             end;
1829          end if;
1830
1831          if (T.Common.Parent /= null
1832               and then T.Common.Parent.Common.Parent /= null)
1833            or else T.Master_of_Task > Library_Task_Level
1834          then
1835             Initialization.Task_Lock (Self_ID);
1836
1837             --  If Sec_Stack_Addr is not null, it means that Destroy_TSD
1838             --  has not been called yet (case of an unactivated task).
1839
1840             if T.Common.Compiler_Data.Sec_Stack_Addr /= Null_Address then
1841                SSL.Destroy_TSD (T.Common.Compiler_Data);
1842             end if;
1843
1844             Vulnerable_Free_Task (T);
1845             Initialization.Task_Unlock (Self_ID);
1846          end if;
1847       end loop;
1848
1849       --  It might seem nice to let the terminated task deallocate its own
1850       --  ATCB. That would not cover the case of unactivated tasks. It also
1851       --  would force us to keep the underlying thread around past termination,
1852       --  since references to the ATCB are possible past termination.
1853
1854       --  Currently, we get rid of the thread as soon as the task terminates,
1855       --  and let the parent recover the ATCB later.
1856
1857       --  Some day, if we want to recover the ATCB earlier, at task
1858       --  termination, we could consider using "fat task IDs", that include the
1859       --  serial number with the ATCB pointer, to catch references to tasks
1860       --  that no longer have ATCBs. It is not clear how much this would gain,
1861       --  since the user-level task object would still be occupying storage.
1862
1863       --  Make next master level up active. We don't need to lock the ATCB,
1864       --  since the value is only updated by each task for itself.
1865
1866       Self_ID.Master_Within := CM - 1;
1867    end Vulnerable_Complete_Master;
1868
1869    ------------------------------
1870    -- Vulnerable_Complete_Task --
1871    ------------------------------
1872
1873    --  Complete the calling task
1874
1875    --  This procedure must be called with abort deferred. It should only be
1876    --  called by Complete_Task and Finalize_Global_Tasks (for the environment
1877    --  task).
1878
1879    --  The effect is similar to that of Complete_Master. Differences include
1880    --  the closing of entries here, and computation of the number of active
1881    --  dependent tasks in Complete_Master.
1882
1883    --  We don't lock Self_ID before the call to Vulnerable_Complete_Activation,
1884    --  because that does its own locking, and because we do not need the lock
1885    --  to test Self_ID.Common.Activator. That value should only be read and
1886    --  modified by Self.
1887
1888    procedure Vulnerable_Complete_Task (Self_ID : Task_Id) is
1889    begin
1890       pragma Assert
1891         (Self_ID.Deferral_Level > 0
1892           or else not System.Restrictions.Abort_Allowed);
1893       pragma Assert (Self_ID = Self);
1894       pragma Assert (Self_ID.Master_Within = Self_ID.Master_of_Task + 1
1895                        or else
1896                      Self_ID.Master_Within = Self_ID.Master_of_Task + 2);
1897       pragma Assert (Self_ID.Common.Wait_Count = 0);
1898       pragma Assert (Self_ID.Open_Accepts = null);
1899       pragma Assert (Self_ID.ATC_Nesting_Level = 1);
1900
1901       pragma Debug (Debug.Trace (Self_ID, "V_Complete_Task", 'C'));
1902
1903       if Single_Lock then
1904          Lock_RTS;
1905       end if;
1906
1907       Write_Lock (Self_ID);
1908       Self_ID.Callable := False;
1909
1910       --  In theory, Self should have no pending entry calls left on its
1911       --  call-stack. Each async. select statement should clean its own call,
1912       --  and blocking entry calls should defer abort until the calls are
1913       --  cancelled, then clean up.
1914
1915       Utilities.Cancel_Queued_Entry_Calls (Self_ID);
1916       Unlock (Self_ID);
1917
1918       if Self_ID.Common.Activator /= null then
1919          Vulnerable_Complete_Activation (Self_ID);
1920       end if;
1921
1922       if Single_Lock then
1923          Unlock_RTS;
1924       end if;
1925
1926       --  If Self_ID.Master_Within = Self_ID.Master_of_Task + 2 we may have
1927       --  dependent tasks for which we need to wait. Otherwise we just exit.
1928
1929       if Self_ID.Master_Within = Self_ID.Master_of_Task + 2 then
1930          Vulnerable_Complete_Master (Self_ID);
1931       end if;
1932    end Vulnerable_Complete_Task;
1933
1934    --------------------------
1935    -- Vulnerable_Free_Task --
1936    --------------------------
1937
1938    --  Recover all runtime system storage associated with the task T. This
1939    --  should only be called after T has terminated and will no longer be
1940    --  referenced.
1941
1942    --  For tasks created by an allocator that fails, due to an exception, it
1943    --  is called from Expunge_Unactivated_Tasks.
1944
1945    --  For tasks created by elaboration of task object declarations it is
1946    --  called from the finalization code of the Task_Wrapper procedure. It is
1947    --  also called from Ada.Unchecked_Deallocation, for objects that are or
1948    --  contain tasks.
1949
1950    procedure Vulnerable_Free_Task (T : Task_Id) is
1951    begin
1952       pragma Debug (Debug.Trace (Self, "Vulnerable_Free_Task", 'C', T));
1953
1954       if Single_Lock then
1955          Lock_RTS;
1956       end if;
1957
1958       Write_Lock (T);
1959       Initialization.Finalize_Attributes_Link.all (T);
1960       Unlock (T);
1961
1962       if Single_Lock then
1963          Unlock_RTS;
1964       end if;
1965
1966       Free_Entry_Names (T);
1967       System.Task_Primitives.Operations.Finalize_TCB (T);
1968    end Vulnerable_Free_Task;
1969
1970 --  Package elaboration code
1971
1972 begin
1973    --  Establish the Adafinal oftlink
1974
1975    --  This is not done inside the central RTS initialization routine
1976    --  to avoid with-ing this package from System.Tasking.Initialization.
1977
1978    SSL.Adafinal := Finalize_Global_Tasks'Access;
1979
1980    --  Establish soft links for subprograms that manipulate master_id's.
1981    --  This cannot be done when the RTS is initialized, because of various
1982    --  elaboration constraints.
1983
1984    SSL.Current_Master  := Stages.Current_Master'Access;
1985    SSL.Enter_Master    := Stages.Enter_Master'Access;
1986    SSL.Complete_Master := Stages.Complete_Master'Access;
1987 end System.Tasking.Stages;