OSDN Git Service

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