1------------------------------------------------------------------------------
2--                                                                          --
3--                GNU ADA RUN-TIME LIBRARY (GNARL) COMPONENTS               --
4--                                                                          --
5--         S Y S T E M . T A S K I N G . I N I T I A L I Z A T I O N        --
6--                                                                          --
7--                                  B o d y                                 --
8--                                                                          --
9--         Copyright (C) 1992-2003, 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,  59 Temple Place - Suite 330,  Boston, --
20-- MA 02111-1307, 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
34pragma Style_Checks (All_Checks);
35--  Turn off subprogram alpha ordering check, since we group soft link
36--  bodies and dummy soft link bodies together separately in this unit.
37
38pragma Polling (Off);
39--  Turn polling off for this package. We don't need polling during any
40--  of the routines in this package, and more to the point, if we try
41--  to poll it can cause infinite loops.
42
43with Ada.Exceptions;
44--  used for Exception_Occurrence_Access.
45
46with System.Tasking;
47pragma Elaborate_All (System.Tasking);
48--  ensure that the first step initializations have been performed
49
50with System.Task_Primitives;
51--  used for Lock
52
53with System.Task_Primitives.Operations;
54--  used for Set_Priority
55--           Write_Lock
56--           Unlock
57--           Initialize_Lock
58
59with System.Soft_Links;
60--  used for the non-tasking routines (*_NT) that refer to global data.
61--  They are needed here before the tasking run time has been elaborated.
62
63with System.Tasking.Debug;
64--  used for Trace
65
66with System.Stack_Checking;
67
68with System.Parameters;
69--  used for Single_Lock
70
71package body System.Tasking.Initialization is
72
73   package STPO renames System.Task_Primitives.Operations;
74   package SSL  renames System.Soft_Links;
75   package AE   renames Ada.Exceptions;
76
77   use Parameters;
78   use Task_Primitives.Operations;
79
80   Global_Task_Lock : aliased System.Task_Primitives.RTS_Lock;
81   --  This is a global lock; it is used to execute in mutual exclusion
82   --  from all other tasks. It is only used by Task_Lock,
83   --  Task_Unlock, and Final_Task_Unlock.
84
85   function Current_Target_Exception return AE.Exception_Occurrence;
86   pragma Import
87     (Ada, Current_Target_Exception, "__gnat_current_target_exception");
88   --  Import this subprogram from the private part of Ada.Exceptions.
89
90   -----------------------------------------------------------------
91   -- Tasking versions of services needed by non-tasking programs --
92   -----------------------------------------------------------------
93
94   procedure Task_Lock;
95   --  Locks out other tasks. Preceding a section of code by Task_Lock and
96   --  following it by Task_Unlock creates a critical region. This is used
97   --  for ensuring that a region of non-tasking code (such as code used to
98   --  allocate memory) is tasking safe. Note that it is valid for calls to
99   --  Task_Lock/Task_Unlock to be nested, and this must work properly, i.e.
100   --  only the corresponding outer level Task_Unlock will actually unlock.
101
102   procedure Task_Unlock;
103   --  Releases lock previously set by call to Task_Lock. In the nested case,
104   --  all nested locks must be released before other tasks competing for the
105   --  tasking lock are released.
106
107   function  Get_Jmpbuf_Address return  Address;
108   procedure Set_Jmpbuf_Address (Addr : Address);
109   --  Get/Set Jmpbuf_Address for current task
110
111   function  Get_Sec_Stack_Addr return  Address;
112   procedure Set_Sec_Stack_Addr (Addr : Address);
113   --  Get/Set location of current task's secondary stack
114
115   function  Get_Exc_Stack_Addr return Address;
116   --  Get the exception stack for the current task
117
118   procedure Set_Exc_Stack_Addr (Self_ID : Address; Addr : Address);
119   --  Self_ID is the Task_ID of the task that gets the exception stack.
120   --  For Self_ID = Null_Address, the current task gets the exception stack.
121
122   function  Get_Machine_State_Addr return Address;
123   procedure Set_Machine_State_Addr (Addr : Address);
124   --  Get/Set the address for storing the current task's machine state
125
126   function Get_Current_Excep return SSL.EOA;
127   --  Task-safe version of SSL.Get_Current_Excep
128
129   procedure Timed_Delay_T (Time : Duration; Mode : Integer);
130   --  Task-safe version of SSL.Timed_Delay
131
132   function Get_Stack_Info return Stack_Checking.Stack_Access;
133   --  Get access to the current task's Stack_Info
134
135   procedure Update_Exception
136     (X : AE.Exception_Occurrence := Current_Target_Exception);
137   --  Handle exception setting and check for pending actions
138
139   function Task_Name return String;
140   --  Returns current task's name
141
142   ------------------------
143   --  Local Subprograms --
144   ------------------------
145
146   procedure Do_Pending_Action (Self_ID : Task_ID);
147   --  This is introduced to allow more efficient
148   --  in-line expansion of Undefer_Abort.
149
150   ----------------------------
151   -- Tasking Initialization --
152   ----------------------------
153
154   procedure Gnat_Install_Locks (Lock, Unlock : SSL.No_Param_Proc);
155   pragma Import (C, Gnat_Install_Locks, "__gnatlib_install_locks");
156   --  Used by Init_RTS to install procedure Lock and Unlock for the
157   --  thread locking. This has no effect on GCC 2. For GCC 3,
158   --  it has an effect only if gcc is configured with
159   --  --enable_threads=gnat.
160
161   procedure Init_RTS;
162   --  This procedure completes the initialization of the GNARL. The first
163   --  part of the initialization is done in the body of System.Tasking.
164   --  It consists of initializing global locks, and installing tasking
165   --  versions of certain operations used by the compiler. Init_RTS is called
166   --  during elaboration.
167
168   --------------------------
169   -- Change_Base_Priority --
170   --------------------------
171
172   --  Call only with abort deferred and holding Self_ID locked.
173
174   procedure Change_Base_Priority (T : Task_ID) is
175   begin
176      if T.Common.Base_Priority /= T.New_Base_Priority then
177         T.Common.Base_Priority := T.New_Base_Priority;
178         Set_Priority (T, T.Common.Base_Priority);
179      end if;
180   end Change_Base_Priority;
181
182   ------------------------
183   -- Check_Abort_Status --
184   ------------------------
185
186   function Check_Abort_Status return Integer is
187      Self_ID : constant Task_ID := Self;
188   begin
189      if Self_ID /= null and then Self_ID.Deferral_Level = 0
190        and then Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
191      then
192         return 1;
193      else
194         return 0;
195      end if;
196   end Check_Abort_Status;
197
198   -----------------
199   -- Defer_Abort --
200   -----------------
201
202   procedure Defer_Abort (Self_ID : Task_ID) is
203   begin
204      if No_Abort and then not Dynamic_Priority_Support then
205         return;
206      end if;
207
208      pragma Assert (Self_ID.Deferral_Level = 0);
209
210      --  pragma Assert
211      --    (Self_ID.Pending_ATC_Level >= Self_ID.ATC_Nesting_Level);
212
213      --  The above check has been useful in detecting mismatched defer/undefer
214      --  pairs. You may uncomment it when testing on systems that support
215      --  preemptive abort.
216
217      --  If the OS supports preemptive abort (e.g. pthread_kill), it should
218      --  have happened already. A problem is with systems that do not support
219      --  preemptive abort, and so rely on polling. On such systems we may get
220      --  false failures of the assertion, since polling for pending abort does
221      --  no occur until the abort undefer operation.
222
223      --  Even on systems that only poll for abort, the assertion may be useful
224      --  for catching missed abort completion polling points. The operations
225      --  that undefer abort poll for pending aborts. This covers most of the
226      --  places where the core Ada semantics require abort to be caught,
227      --  without any special attention. However, this generally happens on
228      --  exit from runtime system call, which means a pending abort will not
229      --  be noticed on the way into the runtime system. We considered adding a
230      --  check for pending aborts at this point, but chose not to, because of
231      --  the overhead. Instead, we searched for RTS calls where abort
232      --  completion is required and a task could go farther than Ada allows
233      --  before undeferring abort; we then modified the code to ensure the
234      --  abort would be detected.
235
236      Self_ID.Deferral_Level := Self_ID.Deferral_Level + 1;
237   end Defer_Abort;
238
239   --------------------------
240   -- Defer_Abort_Nestable --
241   --------------------------
242
243   procedure Defer_Abort_Nestable (Self_ID : Task_ID) is
244   begin
245      if No_Abort and then not Dynamic_Priority_Support then
246         return;
247      end if;
248
249      --  pragma Assert
250      --    ((Self_ID.Pending_ATC_Level >= Self_ID.ATC_Nesting_Level or else
251      --      Self_ID.Deferral_Level > 0));
252
253      --  See comment in Defer_Abort on the situations in which it may be
254      --  useful to uncomment the above assertion.
255
256      Self_ID.Deferral_Level := Self_ID.Deferral_Level + 1;
257   end Defer_Abort_Nestable;
258
259   --------------------
260   -- Defer_Abortion --
261   --------------------
262
263   procedure Defer_Abortion is
264      Self_ID : Task_ID;
265
266   begin
267      if No_Abort and then not Dynamic_Priority_Support then
268         return;
269      end if;
270
271      Self_ID := STPO.Self;
272      Self_ID.Deferral_Level := Self_ID.Deferral_Level + 1;
273   end Defer_Abortion;
274
275   -----------------------
276   -- Do_Pending_Action --
277   -----------------------
278
279   --  Call only when holding no locks
280
281   procedure Do_Pending_Action (Self_ID : Task_ID) is
282      use type Ada.Exceptions.Exception_Id;
283
284   begin
285      pragma Assert (Self_ID = Self and then Self_ID.Deferral_Level = 0);
286
287      --  Needs loop to recheck for pending action in case a new one occurred
288      --  while we had abort deferred below.
289
290      loop
291         --  Temporarily defer abortion so that we can lock Self_ID.
292
293         Self_ID.Deferral_Level := Self_ID.Deferral_Level + 1;
294
295         if Single_Lock then
296            Lock_RTS;
297         end if;
298
299         Write_Lock (Self_ID);
300         Self_ID.Pending_Action := False;
301         Poll_Base_Priority_Change (Self_ID);
302         Unlock (Self_ID);
303
304         if Single_Lock then
305            Unlock_RTS;
306         end if;
307
308         --  Restore the original Deferral value.
309
310         Self_ID.Deferral_Level := Self_ID.Deferral_Level - 1;
311
312         if not Self_ID.Pending_Action then
313            if Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level then
314               if not Self_ID.Aborting then
315                  Self_ID.Aborting := True;
316                  pragma Debug
317                    (Debug.Trace (Self_ID, "raise Abort_Signal", 'B'));
318                  raise Standard'Abort_Signal;
319
320                  pragma Assert (not Self_ID.ATC_Hack);
321
322               elsif Self_ID.ATC_Hack then
323                  --  The solution really belongs in the Abort_Signal handler
324                  --  for async. entry calls.  The present hack is very
325                  --  fragile. It relies that the very next point after
326                  --  Exit_One_ATC_Level at which the task becomes abortable
327                  --  will be the call to Undefer_Abort in the
328                  --  Abort_Signal handler.
329
330                  Self_ID.ATC_Hack := False;
331
332                  pragma Debug
333                    (Debug.Trace
334                     (Self_ID, "raise Abort_Signal (ATC hack)", 'B'));
335                  raise Standard'Abort_Signal;
336               end if;
337            end if;
338
339            return;
340         end if;
341      end loop;
342   end Do_Pending_Action;
343
344   -----------------------
345   -- Final_Task_Unlock --
346   -----------------------
347
348   --  This version is only for use in Terminate_Task, when the task
349   --  is relinquishing further rights to its own ATCB.
350   --  There is a very interesting potential race condition there, where
351   --  the old task may run concurrently with a new task that is allocated
352   --  the old tasks (now reused) ATCB.  The critical thing here is to
353   --  not make any reference to the ATCB after the lock is released.
354   --  See also comments on Terminate_Task and Unlock.
355
356   procedure Final_Task_Unlock (Self_ID : Task_ID) is
357   begin
358      pragma Assert (Self_ID.Global_Task_Lock_Nesting = 1);
359      Unlock (Global_Task_Lock'Access, Global_Lock => True);
360   end Final_Task_Unlock;
361
362   --------------
363   -- Init_RTS --
364   --------------
365
366   procedure Init_RTS is
367      Self_Id : Task_ID;
368
369   begin
370      --  Terminate run time (regular vs restricted) specific initialization
371      --  of the environment task.
372
373      Self_Id := Environment_Task;
374      Self_Id.Master_of_Task := Environment_Task_Level;
375      Self_Id.Master_Within := Self_Id.Master_of_Task + 1;
376
377      for L in Self_Id.Entry_Calls'Range loop
378         Self_Id.Entry_Calls (L).Self := Self_Id;
379         Self_Id.Entry_Calls (L).Level := L;
380      end loop;
381
382      Self_Id.Awake_Count := 1;
383      Self_Id.Alive_Count := 1;
384
385      Self_Id.Master_Within := Library_Task_Level;
386      --  Normally, a task starts out with internal master nesting level
387      --  one larger than external master nesting level. It is incremented
388      --  to one by Enter_Master, which is called in the task body only if
389      --  the compiler thinks the task may have dependent tasks. There is no
390      --  corresponding call to Enter_Master for the environment task, so we
391      --  would need to increment it to 2 here.  Instead, we set it to 3.
392      --  By doing this we reserve the level 2 for server tasks of the runtime
393      --  system. The environment task does not need to wait for these server
394
395      --  Initialize lock used to implement mutual exclusion between all tasks
396
397      Initialize_Lock (Global_Task_Lock'Access, STPO.Global_Task_Level);
398
399      --  Notify that the tasking run time has been elaborated so that
400      --  the tasking version of the soft links can be used.
401
402      if not No_Abort or else Dynamic_Priority_Support then
403         SSL.Abort_Defer   := Defer_Abortion'Access;
404         SSL.Abort_Undefer := Undefer_Abortion'Access;
405      end if;
406
407      SSL.Update_Exception       := Update_Exception'Access;
408      SSL.Lock_Task              := Task_Lock'Access;
409      SSL.Unlock_Task            := Task_Unlock'Access;
410      SSL.Get_Jmpbuf_Address     := Get_Jmpbuf_Address'Access;
411      SSL.Set_Jmpbuf_Address     := Set_Jmpbuf_Address'Access;
412      SSL.Get_Sec_Stack_Addr     := Get_Sec_Stack_Addr'Access;
413      SSL.Set_Sec_Stack_Addr     := Set_Sec_Stack_Addr'Access;
414      SSL.Get_Exc_Stack_Addr     := Get_Exc_Stack_Addr'Access;
415      SSL.Set_Exc_Stack_Addr     := Set_Exc_Stack_Addr'Access;
416      SSL.Get_Machine_State_Addr := Get_Machine_State_Addr'Access;
417      SSL.Set_Machine_State_Addr := Set_Machine_State_Addr'Access;
418      SSL.Get_Current_Excep      := Get_Current_Excep'Access;
419      SSL.Timed_Delay            := Timed_Delay_T'Access;
420      SSL.Check_Abort_Status     := Check_Abort_Status'Access;
421      SSL.Get_Stack_Info         := Get_Stack_Info'Access;
422      SSL.Task_Name              := Task_Name'Access;
423
424      --  No need to create a new Secondary Stack, since we will use the
425      --  default one created in s-secsta.adb
426
427      SSL.Set_Sec_Stack_Addr     (SSL.Get_Sec_Stack_Addr_NT);
428      SSL.Set_Exc_Stack_Addr     (Null_Address, SSL.Get_Exc_Stack_Addr_NT);
429      SSL.Set_Jmpbuf_Address     (SSL.Get_Jmpbuf_Address_NT);
430      SSL.Set_Machine_State_Addr (SSL.Get_Machine_State_Addr_NT);
431
432      --  Install tasking locks in the GCC runtime.
433
434      Gnat_Install_Locks (Task_Lock'Access, Task_Unlock'Access);
435
436      --  Abortion is deferred in a new ATCB, so we need to undefer abortion
437      --  at this stage to make the environment task abortable.
438
439      Undefer_Abort (Environment_Task);
440   end Init_RTS;
441
442   ---------------------------
443   -- Locked_Abort_To_Level--
444   ---------------------------
445
446   --  Abort a task to the specified ATC nesting level.
447   --  Call this only with T locked.
448
449   --  An earlier version of this code contained a call to Wakeup. That
450   --  should not be necessary here, if Abort_Task is implemented correctly,
451   --  since Abort_Task should include the effect of Wakeup. However, the
452   --  above call was in earlier versions of this file, and at least for
453   --  some targets Abort_Task has not beek doing Wakeup. It should not
454   --  hurt to uncomment the above call, until the error is corrected for
455   --  all targets.
456
457   --  See extended comments in package body System.Tasking.Abortion
458   --  for the overall design of the implementation of task abort.
459
460   --  If the task is sleeping it will be in an abort-deferred region,
461   --  and will not have Abort_Signal raised by Abort_Task.
462   --  Such an "abort deferral" is just to protect the RTS internals,
463   --  and not necessarily required to enforce Ada semantics.
464   --  Abort_Task should wake the task up and let it decide if it wants
465   --  to complete the aborted construct immediately.
466
467   --  Note that the effect of the lowl-level Abort_Task is not persistent.
468   --  If the target task is not blocked, this wakeup will be missed.
469
470   --  We don't bother calling Abort_Task if this task is aborting itself,
471   --  since we are inside the RTS and have abort deferred. Similarly, We
472   --  don't bother to call Abort_Task if T is terminated, since there is
473   --  no need to abort a terminated task, and it could be dangerous to try
474   --  if the task has stopped executing.
475
476   --  Note that an earlier version of this code had some false reasoning
477   --  about being able to reliably wake up a task that had suspended on
478   --  a blocking system call that does not atomically relase the task's
479   --  lock (e.g., UNIX nanosleep, which we once thought could be used to
480   --  implement delays). That still left the possibility of missed
481   --  wakeups.
482
483   --  We cannot safely call Vulnerable_Complete_Activation here,
484   --  since that requires locking Self_ID.Parent. The anti-deadlock
485   --  lock ordering rules would then require us to release the lock
486   --  on Self_ID first, which would create a timing window for other
487   --  tasks to lock Self_ID. This is significant for tasks that may be
488   --  aborted before their execution can enter the task body, and so
489   --  they do not get a chance to call Complete_Task. The actual work
490   --  for this case is done in Terminate_Task.
491
492   procedure Locked_Abort_To_Level
493     (Self_ID : Task_ID;
494      T       : Task_ID;
495      L       : ATC_Level)
496   is
497   begin
498      if not T.Aborting and then T /= Self_ID then
499         case T.Common.State is
500            when Unactivated | Terminated =>
501               pragma Assert (False);
502               null;
503
504            when Runnable =>
505               --  This is needed to cancel an asynchronous protected entry
506               --  call during a requeue with abort.
507
508               T.Entry_Calls
509                 (T.ATC_Nesting_Level).Cancellation_Attempted := True;
510
511            when Interrupt_Server_Blocked_On_Event_Flag =>
512               null;
513
514            when Delay_Sleep                              |
515                 Async_Select_Sleep                       |
516                 Interrupt_Server_Idle_Sleep              |
517                 Interrupt_Server_Blocked_Interrupt_Sleep |
518                 Timer_Server_Sleep                       |
519                 AST_Server_Sleep                         =>
520               Wakeup (T, T.Common.State);
521
522            when Acceptor_Sleep =>
523               T.Open_Accepts := null;
524               Wakeup (T, T.Common.State);
525
526            when Entry_Caller_Sleep  =>
527               T.Entry_Calls
528                 (T.ATC_Nesting_Level).Cancellation_Attempted := True;
529               Wakeup (T, T.Common.State);
530
531            when Activator_Sleep         |
532                 Master_Completion_Sleep |
533                 Master_Phase_2_Sleep    |
534                 Asynchronous_Hold       =>
535               null;
536         end case;
537      end if;
538
539      if T.Pending_ATC_Level > L then
540         T.Pending_ATC_Level := L;
541         T.Pending_Action := True;
542
543         if L = 0 then
544            T.Callable := False;
545         end if;
546
547         --  This prevents aborted task from accepting calls
548
549         if T.Aborting then
550
551            --  The test above is just a heuristic, to reduce wasteful
552            --  calls to Abort_Task.  We are holding T locked, and this
553            --  value will not be set to False except with T also locked,
554            --  inside Exit_One_ATC_Level, so we should not miss wakeups.
555
556            if T.Common.State = Acceptor_Sleep then
557               T.Open_Accepts := null;
558            end if;
559
560         elsif T /= Self_ID and then
561           (T.Common.State = Runnable
562            or else T.Common.State = Interrupt_Server_Blocked_On_Event_Flag)
563            --  The task is blocked on a system call waiting for the
564            --  completion event. In this case Abort_Task may need to take
565            --  special action in order to succeed. Example system: VMS.
566
567         then
568            Abort_Task (T);
569         end if;
570      end if;
571   end Locked_Abort_To_Level;
572
573   -------------------------------
574   -- Poll_Base_Priority_Change --
575   -------------------------------
576
577   --  Poll for pending base priority change and for held tasks.
578   --  This should always be called with (only) Self_ID locked.
579   --  It may temporarily release Self_ID's lock.
580
581   --  The call to Yield is to force enqueuing at the
582   --  tail of the dispatching queue.
583
584   --  We must unlock Self_ID for this to take effect,
585   --  since we are inheriting high active priority from the lock.
586
587   --  See also Poll_Base_Priority_Change_At_Entry_Call,
588   --  in package System.Tasking.Entry_Calls.
589
590   --  In this version, we check if the task is held too because
591   --  doing this only in Do_Pending_Action is not enough.
592
593   procedure Poll_Base_Priority_Change (Self_ID : Task_ID) is
594   begin
595      if Dynamic_Priority_Support and then Self_ID.Pending_Priority_Change then
596
597         --  Check for ceiling violations ???
598
599         Self_ID.Pending_Priority_Change := False;
600
601         if Self_ID.Common.Base_Priority = Self_ID.New_Base_Priority then
602            if Single_Lock then
603               Unlock_RTS;
604               Yield;
605               Lock_RTS;
606            else
607               Unlock (Self_ID);
608               Yield;
609               Write_Lock (Self_ID);
610            end if;
611
612         elsif Self_ID.Common.Base_Priority < Self_ID.New_Base_Priority then
613            Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority;
614            Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
615
616         else
617            --  Lowering priority
618
619            Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority;
620            Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
621
622            if Single_Lock then
623               Unlock_RTS;
624               Yield;
625               Lock_RTS;
626            else
627               Unlock (Self_ID);
628               Yield;
629               Write_Lock (Self_ID);
630            end if;
631         end if;
632      end if;
633   end Poll_Base_Priority_Change;
634
635   --------------------------------
636   -- Remove_From_All_Tasks_List --
637   --------------------------------
638
639   procedure Remove_From_All_Tasks_List (T : Task_ID) is
640      C        : Task_ID;
641      Previous : Task_ID;
642
643   begin
644      pragma Debug
645        (Debug.Trace (Self, "Remove_From_All_Tasks_List", 'C'));
646
647      Previous := Null_Task;
648      C := All_Tasks_List;
649
650      while C /= Null_Task loop
651         if C = T then
652            if Previous = Null_Task then
653               All_Tasks_List :=
654                 All_Tasks_List.Common.All_Tasks_Link;
655            else
656               Previous.Common.All_Tasks_Link := C.Common.All_Tasks_Link;
657            end if;
658
659            return;
660         end if;
661
662         Previous := C;
663         C := C.Common.All_Tasks_Link;
664      end loop;
665
666      pragma Assert (False);
667   end Remove_From_All_Tasks_List;
668
669   ---------------
670   -- Task_Lock --
671   ---------------
672
673   procedure Task_Lock (Self_ID : Task_ID) is
674   begin
675      Self_ID.Global_Task_Lock_Nesting := Self_ID.Global_Task_Lock_Nesting + 1;
676
677      if Self_ID.Global_Task_Lock_Nesting = 1 then
678         Defer_Abort_Nestable (Self_ID);
679         Write_Lock (Global_Task_Lock'Access, Global_Lock => True);
680      end if;
681   end Task_Lock;
682
683   procedure Task_Lock is
684   begin
685      Task_Lock (STPO.Self);
686   end Task_Lock;
687
688   ---------------
689   -- Task_Name --
690   ---------------
691
692   function Task_Name return String is
693      Self_Id : constant Task_ID := STPO.Self;
694
695   begin
696      return Self_Id.Common.Task_Image (1 .. Self_Id.Common.Task_Image_Len);
697   end Task_Name;
698
699   -----------------
700   -- Task_Unlock --
701   -----------------
702
703   procedure Task_Unlock (Self_ID : Task_ID) is
704   begin
705      pragma Assert (Self_ID.Global_Task_Lock_Nesting > 0);
706      Self_ID.Global_Task_Lock_Nesting := Self_ID.Global_Task_Lock_Nesting - 1;
707
708      if Self_ID.Global_Task_Lock_Nesting = 0 then
709         Unlock (Global_Task_Lock'Access, Global_Lock => True);
710         Undefer_Abort_Nestable (Self_ID);
711      end if;
712   end Task_Unlock;
713
714   procedure Task_Unlock is
715   begin
716      Task_Unlock (STPO.Self);
717   end Task_Unlock;
718
719   -------------------
720   -- Undefer_Abort --
721   -------------------
722
723   --  Precondition : Self does not hold any locks!
724
725   --  Undefer_Abort is called on any abortion completion point (aka.
726   --  synchronization point). It performs the following actions if they
727   --  are pending: (1) change the base priority, (2) abort the task.
728
729   --  The priority change has to occur before abortion. Otherwise, it would
730   --  take effect no earlier than the next abortion completion point.
731
732   procedure Undefer_Abort (Self_ID : Task_ID) is
733   begin
734      if No_Abort and then not Dynamic_Priority_Support then
735         return;
736      end if;
737
738      pragma Assert (Self_ID.Deferral_Level = 1);
739
740      Self_ID.Deferral_Level := Self_ID.Deferral_Level - 1;
741
742      if Self_ID.Deferral_Level = 0 then
743         pragma Assert (Check_No_Locks (Self_ID));
744
745         if Self_ID.Pending_Action then
746            Do_Pending_Action (Self_ID);
747         end if;
748      end if;
749   end Undefer_Abort;
750
751   ----------------------------
752   -- Undefer_Abort_Nestable --
753   ----------------------------
754
755   --  An earlier version would re-defer abort if an abort is in progress.
756   --  Then, we modified the effect of the raise statement so that it defers
757   --  abort until control reaches a handler. That was done to prevent
758   --  "skipping over" a handler if another asynchronous abort occurs during
759   --  the propagation of the abort to the handler.
760
761   --  There has been talk of reversing that decision, based on a newer
762   --  implementation of exception propagation. Care must be taken to evaluate
763   --  how such a change would interact with the above code and all the places
764   --  where abort-deferral is used to bridge over critical transitions, such
765   --  as entry to the scope of a region with a finalizer and entry into the
766   --  body of an accept-procedure.
767
768   procedure Undefer_Abort_Nestable (Self_ID : Task_ID) is
769   begin
770      if No_Abort and then not Dynamic_Priority_Support then
771         return;
772      end if;
773
774      pragma Assert (Self_ID.Deferral_Level > 0);
775
776      Self_ID.Deferral_Level := Self_ID.Deferral_Level - 1;
777
778      if Self_ID.Deferral_Level = 0 then
779
780         pragma Assert (Check_No_Locks (Self_ID));
781
782         if Self_ID.Pending_Action then
783            Do_Pending_Action (Self_ID);
784         end if;
785      end if;
786   end Undefer_Abort_Nestable;
787
788   ----------------------
789   -- Undefer_Abortion --
790   ----------------------
791
792   --  Phase out RTS-internal use of Undefer_Abortion
793   --  to reduce overhead due to multiple calls to Self.
794
795   procedure Undefer_Abortion is
796      Self_ID : Task_ID;
797
798   begin
799      if No_Abort and then not Dynamic_Priority_Support then
800         return;
801      end if;
802
803      Self_ID := STPO.Self;
804      pragma Assert (Self_ID.Deferral_Level > 0);
805
806      Self_ID.Deferral_Level := Self_ID.Deferral_Level - 1;
807
808      if Self_ID.Deferral_Level = 0 then
809         pragma Assert (Check_No_Locks (Self_ID));
810
811         if Self_ID.Pending_Action then
812            Do_Pending_Action (Self_ID);
813         end if;
814      end if;
815   end Undefer_Abortion;
816
817   ----------------------
818   -- Update_Exception --
819   ----------------------
820
821   --  Call only when holding no locks.
822
823   procedure Update_Exception
824     (X : AE.Exception_Occurrence := Current_Target_Exception)
825   is
826      Self_Id : constant Task_ID := Self;
827      use Ada.Exceptions;
828
829   begin
830      Save_Occurrence (Self_Id.Common.Compiler_Data.Current_Excep, X);
831
832      if Self_Id.Deferral_Level = 0 then
833         if Self_Id.Pending_Action then
834            Self_Id.Pending_Action := False;
835            Self_Id.Deferral_Level := Self_Id.Deferral_Level + 1;
836
837            if Single_Lock then
838               Lock_RTS;
839            end if;
840
841            Write_Lock (Self_Id);
842            Self_Id.Pending_Action := False;
843            Poll_Base_Priority_Change (Self_Id);
844            Unlock (Self_Id);
845
846            if Single_Lock then
847               Unlock_RTS;
848            end if;
849
850            Self_Id.Deferral_Level := Self_Id.Deferral_Level - 1;
851
852            if Self_Id.Pending_ATC_Level < Self_Id.ATC_Nesting_Level then
853               if not Self_Id.Aborting then
854                  Self_Id.Aborting := True;
855                  raise Standard'Abort_Signal;
856               end if;
857            end if;
858         end if;
859      end if;
860   end Update_Exception;
861
862   --------------------------
863   -- Wakeup_Entry_Caller --
864   --------------------------
865
866   --  This is called at the end of service of an entry call, to abort the
867   --  caller if he is in an abortable part, and to wake up the caller if it
868   --  is on Entry_Caller_Sleep. It assumes that the call is already off-queue.
869
870   --  (This enforces the rule that a task must be off-queue if its state is
871   --  Done or Cancelled.) Call it holding the lock of Entry_Call.Self.
872
873   --  Timed_Call or Simple_Call:
874   --    The caller is waiting on Entry_Caller_Sleep, in
875   --    Wait_For_Completion, or Wait_For_Completion_With_Timeout.
876
877   --  Conditional_Call:
878   --    The caller might be in Wait_For_Completion,
879   --    waiting for a rendezvous (possibly requeued without abort)
880   --    to complete.
881
882   --  Asynchronous_Call:
883   --    The caller may be executing in the abortable part o
884   --    an async. select, or on a time delay,
885   --    if Entry_Call.State >= Was_Abortable.
886
887   procedure Wakeup_Entry_Caller
888     (Self_ID    : Task_ID;
889      Entry_Call : Entry_Call_Link;
890      New_State  : Entry_Call_State)
891   is
892      Caller : constant Task_ID := Entry_Call.Self;
893
894   begin
895      pragma Debug (Debug.Trace
896        (Self_ID, "Wakeup_Entry_Caller", 'E', Caller));
897      pragma Assert (New_State = Done or else New_State = Cancelled);
898
899      pragma Assert
900        (Caller.Common.State /= Terminated
901          and then Caller.Common.State /= Unactivated);
902
903      Entry_Call.State := New_State;
904
905      if Entry_Call.Mode = Asynchronous_Call then
906
907         --  Abort the caller in his abortable part,
908         --  but do so only if call has been queued abortably
909
910         if Entry_Call.State >= Was_Abortable or else New_State = Done then
911            Locked_Abort_To_Level (Self_ID, Caller, Entry_Call.Level - 1);
912         end if;
913
914      elsif Caller.Common.State = Entry_Caller_Sleep then
915         Wakeup (Caller, Entry_Caller_Sleep);
916      end if;
917   end Wakeup_Entry_Caller;
918
919   ----------------------
920   -- Soft-Link Bodies --
921   ----------------------
922
923   function Get_Current_Excep return SSL.EOA is
924   begin
925      return STPO.Self.Common.Compiler_Data.Current_Excep'Access;
926   end Get_Current_Excep;
927
928   function Get_Exc_Stack_Addr return Address is
929   begin
930      return STPO.Self.Common.Compiler_Data.Exc_Stack_Addr;
931   end Get_Exc_Stack_Addr;
932
933   function Get_Jmpbuf_Address return  Address is
934   begin
935      return STPO.Self.Common.Compiler_Data.Jmpbuf_Address;
936   end Get_Jmpbuf_Address;
937
938   function Get_Machine_State_Addr return Address is
939   begin
940      return STPO.Self.Common.Compiler_Data.Machine_State_Addr;
941   end Get_Machine_State_Addr;
942
943   function Get_Sec_Stack_Addr return  Address is
944   begin
945      return STPO.Self.Common.Compiler_Data.Sec_Stack_Addr;
946   end Get_Sec_Stack_Addr;
947
948   function Get_Stack_Info return Stack_Checking.Stack_Access is
949   begin
950      return STPO.Self.Common.Compiler_Data.Pri_Stack_Info'Access;
951   end Get_Stack_Info;
952
953   procedure Set_Exc_Stack_Addr (Self_ID : Address; Addr : Address) is
954      Me : Task_ID := To_Task_Id (Self_ID);
955
956   begin
957      if Me = Null_Task then
958         Me := STPO.Self;
959      end if;
960
961      Me.Common.Compiler_Data.Exc_Stack_Addr := Addr;
962   end Set_Exc_Stack_Addr;
963
964   procedure Set_Jmpbuf_Address (Addr : Address) is
965   begin
966      STPO.Self.Common.Compiler_Data.Jmpbuf_Address := Addr;
967   end Set_Jmpbuf_Address;
968
969   procedure Set_Machine_State_Addr (Addr : Address) is
970   begin
971      STPO.Self.Common.Compiler_Data.Machine_State_Addr := Addr;
972   end Set_Machine_State_Addr;
973
974   procedure Set_Sec_Stack_Addr (Addr : Address) is
975   begin
976      STPO.Self.Common.Compiler_Data.Sec_Stack_Addr := Addr;
977   end Set_Sec_Stack_Addr;
978
979   procedure Timed_Delay_T (Time : Duration; Mode : Integer) is
980   begin
981      STPO.Timed_Delay (STPO.Self, Time, Mode);
982   end Timed_Delay_T;
983
984   -----------------------
985   -- Soft-Link Dummies --
986   -----------------------
987
988   --  These are dummies for subprograms that are only needed by certain
989   --  optional run-time system packages. If they are needed, the soft
990   --  links will be redirected to the real subprogram by elaboration of
991   --  the subprogram body where the real subprogram is declared.
992
993   procedure Finalize_Attributes (T : Task_ID) is
994      pragma Warnings (Off, T);
995
996   begin
997      null;
998   end Finalize_Attributes;
999
1000   procedure Initialize_Attributes (T : Task_ID) is
1001      pragma Warnings (Off, T);
1002
1003   begin
1004      null;
1005   end Initialize_Attributes;
1006
1007begin
1008   Init_RTS;
1009end System.Tasking.Initialization;
1010