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