OSDN Git Service

2007-08-16 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / s-taprop-mingw.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                 GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS                 --
4 --                                                                          --
5 --     S Y S T E M . T A S K _ P R I M I T I V E S . O P E R A T I O N S    --
6 --                                                                          --
7 --                                  B o d y                                 --
8 --                                                                          --
9 --         Copyright (C) 1992-2007, Free Software Foundation, Inc.          --
10 --                                                                          --
11 -- GNARL is free software; you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
14 -- sion. GNARL is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNARL; see file COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, USA.                                              --
21 --                                                                          --
22 -- As a special exception,  if other files  instantiate  generics from this --
23 -- unit, or you link  this unit with other files  to produce an executable, --
24 -- this  unit  does not  by itself cause  the resulting  executable  to  be --
25 -- covered  by the  GNU  General  Public  License.  This exception does not --
26 -- however invalidate  any other reasons why  the executable file  might be --
27 -- covered by the  GNU Public License.                                      --
28 --                                                                          --
29 -- GNARL was developed by the GNARL team at Florida State University.       --
30 -- Extensive contributions were provided by Ada Core Technologies, Inc.     --
31 --                                                                          --
32 ------------------------------------------------------------------------------
33
34 --  This is a NT (native) version of this package
35
36 --  This package contains all the GNULL primitives that interface directly
37 --  with the underlying OS.
38
39 pragma Polling (Off);
40 --  Turn off polling, we do not want ATC polling to take place during
41 --  tasking operations. It causes infinite loops and other problems.
42
43 with System.Tasking.Debug;
44 --  used for Known_Tasks
45
46 with System.OS_Primitives;
47 --  used for Delay_Modes
48
49 with Interfaces.C;
50 --  used for int
51 --           size_t
52
53 with Interfaces.C.Strings;
54 --  used for Null_Ptr
55
56 with System.Task_Info;
57 --  used for Unspecified_Task_Info
58
59 with System.Interrupt_Management;
60 --  used for Initialize
61
62 with System.Soft_Links;
63 --  used for Abort_Defer/Undefer
64
65 --  We use System.Soft_Links instead of System.Tasking.Initialization because
66 --  the later is a higher level package that we shouldn't depend on. For
67 --  example when using the restricted run time, it is replaced by
68 --  System.Tasking.Restricted.Stages.
69
70 with Ada.Unchecked_Deallocation;
71
72 package body System.Task_Primitives.Operations is
73
74    package SSL renames System.Soft_Links;
75
76    use System.Tasking.Debug;
77    use System.Tasking;
78    use Interfaces.C;
79    use Interfaces.C.Strings;
80    use System.OS_Interface;
81    use System.Parameters;
82    use System.OS_Primitives;
83    use System.Task_Info;
84
85    pragma Link_With ("-Xlinker --stack=0x200000,0x1000");
86    --  Change the default stack size (2 MB) for tasking programs on Windows.
87    --  This allows about 1000 tasks running at the same time. Note that
88    --  we set the stack size for non tasking programs on System unit.
89    --  Also note that under Windows XP, we use a Windows XP extension to
90    --  specify the stack size on a per task basis, as done under other OSes.
91
92    ----------------
93    -- Local Data --
94    ----------------
95
96    Environment_Task_Id : Task_Id;
97    --  A variable to hold Task_Id for the environment task
98
99    Single_RTS_Lock : aliased RTS_Lock;
100    --  This is a lock to allow only one thread of control in the RTS at
101    --  a time; it is used to execute in mutual exclusion from all other tasks.
102    --  Used mainly in Single_Lock mode, but also to protect All_Tasks_List
103
104    Time_Slice_Val : Integer;
105    pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
106
107    Dispatching_Policy : Character;
108    pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
109
110    function Get_Policy (Prio : System.Any_Priority) return Character;
111    pragma Import (C, Get_Policy, "__gnat_get_specific_dispatching");
112    --  Get priority specific dispatching policy
113
114    Foreign_Task_Elaborated : aliased Boolean := True;
115    --  Used to identified fake tasks (i.e., non-Ada Threads)
116
117    Annex_D : Boolean := False;
118    --  Set to True if running with Annex-D semantics
119
120    ------------------------------------
121    -- The thread local storage index --
122    ------------------------------------
123
124    TlsIndex : DWORD;
125    pragma Export (Ada, TlsIndex);
126    --  To ensure that this variable won't be local to this package, since
127    --  in some cases, inlining forces this variable to be global anyway.
128
129    --------------------
130    -- Local Packages --
131    --------------------
132
133    package Specific is
134
135       function Is_Valid_Task return Boolean;
136       pragma Inline (Is_Valid_Task);
137       --  Does executing thread have a TCB?
138
139       procedure Set (Self_Id : Task_Id);
140       pragma Inline (Set);
141       --  Set the self id for the current task
142
143    end Specific;
144
145    package body Specific is
146
147       function Is_Valid_Task return Boolean is
148       begin
149          return TlsGetValue (TlsIndex) /= System.Null_Address;
150       end Is_Valid_Task;
151
152       procedure Set (Self_Id : Task_Id) is
153          Succeeded : BOOL;
154       begin
155          Succeeded := TlsSetValue (TlsIndex, To_Address (Self_Id));
156          pragma Assert (Succeeded = True);
157       end Set;
158
159    end Specific;
160
161    ---------------------------------
162    -- Support for foreign threads --
163    ---------------------------------
164
165    function Register_Foreign_Thread (Thread : Thread_Id) return Task_Id;
166    --  Allocate and Initialize a new ATCB for the current Thread
167
168    function Register_Foreign_Thread
169      (Thread : Thread_Id) return Task_Id is separate;
170
171    ----------------------------------
172    -- Condition Variable Functions --
173    ----------------------------------
174
175    procedure Initialize_Cond (Cond : not null access Condition_Variable);
176    --  Initialize given condition variable Cond
177
178    procedure Finalize_Cond (Cond : not null access Condition_Variable);
179    --  Finalize given condition variable Cond
180
181    procedure Cond_Signal (Cond : not null access Condition_Variable);
182    --  Signal condition variable Cond
183
184    procedure Cond_Wait
185      (Cond : not null access Condition_Variable;
186       L    : not null access RTS_Lock);
187    --  Wait on conditional variable Cond, using lock L
188
189    procedure Cond_Timed_Wait
190      (Cond      : not null access Condition_Variable;
191       L         : not null access RTS_Lock;
192       Rel_Time  : Duration;
193       Timed_Out : out Boolean;
194       Status    : out Integer);
195    --  Do timed wait on condition variable Cond using lock L. The duration
196    --  of the timed wait is given by Rel_Time. When the condition is
197    --  signalled, Timed_Out shows whether or not a time out occurred.
198    --  Status is only valid if Timed_Out is False, in which case it
199    --  shows whether Cond_Timed_Wait completed successfully.
200
201    ---------------------
202    -- Initialize_Cond --
203    ---------------------
204
205    procedure Initialize_Cond (Cond : not null access Condition_Variable) is
206       hEvent : HANDLE;
207    begin
208       hEvent := CreateEvent (null, True, False, Null_Ptr);
209       pragma Assert (hEvent /= 0);
210       Cond.all := Condition_Variable (hEvent);
211    end Initialize_Cond;
212
213    -------------------
214    -- Finalize_Cond --
215    -------------------
216
217    --  No such problem here, DosCloseEventSem has been derived.
218    --  What does such refer to in above comment???
219
220    procedure Finalize_Cond (Cond : not null access Condition_Variable) is
221       Result : BOOL;
222    begin
223       Result := CloseHandle (HANDLE (Cond.all));
224       pragma Assert (Result = True);
225    end Finalize_Cond;
226
227    -----------------
228    -- Cond_Signal --
229    -----------------
230
231    procedure Cond_Signal (Cond : not null access Condition_Variable) is
232       Result : BOOL;
233    begin
234       Result := SetEvent (HANDLE (Cond.all));
235       pragma Assert (Result = True);
236    end Cond_Signal;
237
238    ---------------
239    -- Cond_Wait --
240    ---------------
241
242    --  Pre-condition: Cond is posted
243    --                 L is locked.
244
245    --  Post-condition: Cond is posted
246    --                  L is locked.
247
248    procedure Cond_Wait
249      (Cond : not null access Condition_Variable;
250       L    : not null access RTS_Lock)
251    is
252       Result      : DWORD;
253       Result_Bool : BOOL;
254
255    begin
256       --  Must reset Cond BEFORE L is unlocked
257
258       Result_Bool := ResetEvent (HANDLE (Cond.all));
259       pragma Assert (Result_Bool = True);
260       Unlock (L, Global_Lock => True);
261
262       --  No problem if we are interrupted here: if the condition is signaled,
263       --  WaitForSingleObject will simply not block
264
265       Result := WaitForSingleObject (HANDLE (Cond.all), Wait_Infinite);
266       pragma Assert (Result = 0);
267
268       Write_Lock (L, Global_Lock => True);
269    end Cond_Wait;
270
271    ---------------------
272    -- Cond_Timed_Wait --
273    ---------------------
274
275    --  Pre-condition: Cond is posted
276    --                 L is locked.
277
278    --  Post-condition: Cond is posted
279    --                  L is locked.
280
281    procedure Cond_Timed_Wait
282      (Cond      : not null access Condition_Variable;
283       L         : not null access RTS_Lock;
284       Rel_Time  : Duration;
285       Timed_Out : out Boolean;
286       Status    : out Integer)
287    is
288       Time_Out_Max : constant DWORD := 16#FFFF0000#;
289       --  NT 4 can't handle excessive timeout values (e.g. DWORD'Last - 1)
290
291       Time_Out    : DWORD;
292       Result      : BOOL;
293       Wait_Result : DWORD;
294
295    begin
296       --  Must reset Cond BEFORE L is unlocked
297
298       Result := ResetEvent (HANDLE (Cond.all));
299       pragma Assert (Result = True);
300       Unlock (L, Global_Lock => True);
301
302       --  No problem if we are interrupted here: if the condition is signaled,
303       --  WaitForSingleObject will simply not block
304
305       if Rel_Time <= 0.0 then
306          Timed_Out := True;
307          Wait_Result := 0;
308
309       else
310          if Rel_Time >= Duration (Time_Out_Max) / 1000 then
311             Time_Out := Time_Out_Max;
312          else
313             Time_Out := DWORD (Rel_Time * 1000);
314          end if;
315
316          Wait_Result := WaitForSingleObject (HANDLE (Cond.all), Time_Out);
317
318          if Wait_Result = WAIT_TIMEOUT then
319             Timed_Out := True;
320             Wait_Result := 0;
321          else
322             Timed_Out := False;
323          end if;
324       end if;
325
326       Write_Lock (L, Global_Lock => True);
327
328       --  Ensure post-condition
329
330       if Timed_Out then
331          Result := SetEvent (HANDLE (Cond.all));
332          pragma Assert (Result = True);
333       end if;
334
335       Status := Integer (Wait_Result);
336    end Cond_Timed_Wait;
337
338    ------------------
339    -- Stack_Guard  --
340    ------------------
341
342    --  The underlying thread system sets a guard page at the bottom of a thread
343    --  stack, so nothing is needed.
344    --  ??? Check the comment above
345
346    procedure Stack_Guard (T : ST.Task_Id; On : Boolean) is
347       pragma Unreferenced (T, On);
348    begin
349       null;
350    end Stack_Guard;
351
352    --------------------
353    -- Get_Thread_Id  --
354    --------------------
355
356    function Get_Thread_Id (T : ST.Task_Id) return OSI.Thread_Id is
357    begin
358       return T.Common.LL.Thread;
359    end Get_Thread_Id;
360
361    ----------
362    -- Self --
363    ----------
364
365    function Self return Task_Id is
366       Self_Id : constant Task_Id := To_Task_Id (TlsGetValue (TlsIndex));
367    begin
368       if Self_Id = null then
369          return Register_Foreign_Thread (GetCurrentThread);
370       else
371          return Self_Id;
372       end if;
373    end Self;
374
375    ---------------------
376    -- Initialize_Lock --
377    ---------------------
378
379    --  Note: mutexes and cond_variables needed per-task basis are initialized
380    --  in Intialize_TCB and the Storage_Error is handled. Other mutexes (such
381    --  as RTS_Lock, Memory_Lock...) used in the RTS is initialized before any
382    --  status change of RTS. Therefore raising Storage_Error in the following
383    --  routines should be able to be handled safely.
384
385    procedure Initialize_Lock
386      (Prio : System.Any_Priority;
387       L    : not null access Lock)
388    is
389    begin
390       InitializeCriticalSection (L.Mutex'Access);
391       L.Owner_Priority := 0;
392       L.Priority := Prio;
393    end Initialize_Lock;
394
395    procedure Initialize_Lock
396      (L : not null access RTS_Lock; Level : Lock_Level)
397    is
398       pragma Unreferenced (Level);
399    begin
400       InitializeCriticalSection (CRITICAL_SECTION (L.all)'Unrestricted_Access);
401    end Initialize_Lock;
402
403    -------------------
404    -- Finalize_Lock --
405    -------------------
406
407    procedure Finalize_Lock (L : not null access Lock) is
408    begin
409       DeleteCriticalSection (L.Mutex'Access);
410    end Finalize_Lock;
411
412    procedure Finalize_Lock (L : not null access RTS_Lock) is
413    begin
414       DeleteCriticalSection (CRITICAL_SECTION (L.all)'Unrestricted_Access);
415    end Finalize_Lock;
416
417    ----------------
418    -- Write_Lock --
419    ----------------
420
421    procedure Write_Lock
422      (L : not null access Lock; Ceiling_Violation : out Boolean) is
423    begin
424       L.Owner_Priority := Get_Priority (Self);
425
426       if L.Priority < L.Owner_Priority then
427          Ceiling_Violation := True;
428          return;
429       end if;
430
431       EnterCriticalSection (L.Mutex'Access);
432
433       Ceiling_Violation := False;
434    end Write_Lock;
435
436    procedure Write_Lock
437      (L           : not null access RTS_Lock;
438       Global_Lock : Boolean := False)
439    is
440    begin
441       if not Single_Lock or else Global_Lock then
442          EnterCriticalSection (CRITICAL_SECTION (L.all)'Unrestricted_Access);
443       end if;
444    end Write_Lock;
445
446    procedure Write_Lock (T : Task_Id) is
447    begin
448       if not Single_Lock then
449          EnterCriticalSection
450            (CRITICAL_SECTION (T.Common.LL.L)'Unrestricted_Access);
451       end if;
452    end Write_Lock;
453
454    ---------------
455    -- Read_Lock --
456    ---------------
457
458    procedure Read_Lock
459      (L : not null access Lock; Ceiling_Violation : out Boolean) is
460    begin
461       Write_Lock (L, Ceiling_Violation);
462    end Read_Lock;
463
464    ------------
465    -- Unlock --
466    ------------
467
468    procedure Unlock (L : not null access Lock) is
469    begin
470       LeaveCriticalSection (L.Mutex'Access);
471    end Unlock;
472
473    procedure Unlock
474      (L : not null access RTS_Lock; Global_Lock : Boolean := False) is
475    begin
476       if not Single_Lock or else Global_Lock then
477          LeaveCriticalSection (CRITICAL_SECTION (L.all)'Unrestricted_Access);
478       end if;
479    end Unlock;
480
481    procedure Unlock (T : Task_Id) is
482    begin
483       if not Single_Lock then
484          LeaveCriticalSection
485            (CRITICAL_SECTION (T.Common.LL.L)'Unrestricted_Access);
486       end if;
487    end Unlock;
488
489    -----------------
490    -- Set_Ceiling --
491    -----------------
492
493    --  Dynamic priority ceilings are not supported by the underlying system
494
495    procedure Set_Ceiling
496      (L    : not null access Lock;
497       Prio : System.Any_Priority)
498    is
499       pragma Unreferenced (L, Prio);
500    begin
501       null;
502    end Set_Ceiling;
503
504    -----------
505    -- Sleep --
506    -----------
507
508    procedure Sleep
509      (Self_ID : Task_Id;
510       Reason  : System.Tasking.Task_States)
511    is
512       pragma Unreferenced (Reason);
513
514    begin
515       pragma Assert (Self_ID = Self);
516
517       if Single_Lock then
518          Cond_Wait (Self_ID.Common.LL.CV'Access, Single_RTS_Lock'Access);
519       else
520          Cond_Wait (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L'Access);
521       end if;
522
523       if Self_ID.Deferral_Level = 0
524         and then Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
525       then
526          Unlock (Self_ID);
527          raise Standard'Abort_Signal;
528       end if;
529    end Sleep;
530
531    -----------------
532    -- Timed_Sleep --
533    -----------------
534
535    --  This is for use within the run-time system, so abort is assumed to be
536    --  already deferred, and the caller should be holding its own ATCB lock.
537
538    procedure Timed_Sleep
539      (Self_ID  : Task_Id;
540       Time     : Duration;
541       Mode     : ST.Delay_Modes;
542       Reason   : System.Tasking.Task_States;
543       Timedout : out Boolean;
544       Yielded  : out Boolean)
545    is
546       pragma Unreferenced (Reason);
547       Check_Time : Duration := Monotonic_Clock;
548       Rel_Time   : Duration;
549       Abs_Time   : Duration;
550       Result     : Integer;
551
552       Local_Timedout : Boolean;
553
554    begin
555       Timedout := True;
556       Yielded  := False;
557
558       if Mode = Relative then
559          Rel_Time := Time;
560          Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
561       else
562          Rel_Time := Time - Check_Time;
563          Abs_Time := Time;
564       end if;
565
566       if Rel_Time > 0.0 then
567          loop
568             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
569
570             if Single_Lock then
571                Cond_Timed_Wait
572                  (Self_ID.Common.LL.CV'Access,
573                   Single_RTS_Lock'Access,
574                   Rel_Time, Local_Timedout, Result);
575             else
576                Cond_Timed_Wait
577                  (Self_ID.Common.LL.CV'Access,
578                   Self_ID.Common.LL.L'Access,
579                   Rel_Time, Local_Timedout, Result);
580             end if;
581
582             Check_Time := Monotonic_Clock;
583             exit when Abs_Time <= Check_Time;
584
585             if not Local_Timedout then
586
587                --  Somebody may have called Wakeup for us
588
589                Timedout := False;
590                exit;
591             end if;
592
593             Rel_Time := Abs_Time - Check_Time;
594          end loop;
595       end if;
596    end Timed_Sleep;
597
598    -----------------
599    -- Timed_Delay --
600    -----------------
601
602    procedure Timed_Delay
603      (Self_ID : Task_Id;
604       Time    : Duration;
605       Mode    : ST.Delay_Modes)
606    is
607       Check_Time : Duration := Monotonic_Clock;
608       Rel_Time   : Duration;
609       Abs_Time   : Duration;
610       Timedout   : Boolean;
611
612       Result : Integer;
613       pragma Warnings (Off, Integer);
614
615    begin
616       if Single_Lock then
617          Lock_RTS;
618       end if;
619
620       Write_Lock (Self_ID);
621
622       if Mode = Relative then
623          Rel_Time := Time;
624          Abs_Time := Time + Check_Time;
625       else
626          Rel_Time := Time - Check_Time;
627          Abs_Time := Time;
628       end if;
629
630       if Rel_Time > 0.0 then
631          Self_ID.Common.State := Delay_Sleep;
632
633          loop
634             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
635
636             if Single_Lock then
637                Cond_Timed_Wait
638                  (Self_ID.Common.LL.CV'Access,
639                   Single_RTS_Lock'Access,
640                   Rel_Time, Timedout, Result);
641             else
642                Cond_Timed_Wait
643                  (Self_ID.Common.LL.CV'Access,
644                   Self_ID.Common.LL.L'Access,
645                   Rel_Time, Timedout, Result);
646             end if;
647
648             Check_Time := Monotonic_Clock;
649             exit when Abs_Time <= Check_Time;
650
651             Rel_Time := Abs_Time - Check_Time;
652          end loop;
653
654          Self_ID.Common.State := Runnable;
655       end if;
656
657       Unlock (Self_ID);
658
659       if Single_Lock then
660          Unlock_RTS;
661       end if;
662
663       Yield;
664    end Timed_Delay;
665
666    ------------
667    -- Wakeup --
668    ------------
669
670    procedure Wakeup (T : Task_Id; Reason : System.Tasking.Task_States) is
671       pragma Unreferenced (Reason);
672    begin
673       Cond_Signal (T.Common.LL.CV'Access);
674    end Wakeup;
675
676    -----------
677    -- Yield --
678    -----------
679
680    procedure Yield (Do_Yield : Boolean := True) is
681    begin
682       if Do_Yield then
683          SwitchToThread;
684
685       elsif Annex_D then
686          --  If running with Annex-D semantics we need a delay
687          --  above 0 milliseconds here otherwise processes give
688          --  enough time to the other tasks to have a chance to
689          --  run.
690          --
691          --  This makes cxd8002 ACATS pass on Windows.
692
693          Sleep (1);
694       end if;
695    end Yield;
696
697    ------------------
698    -- Set_Priority --
699    ------------------
700
701    type Prio_Array_Type is array (System.Any_Priority) of Integer;
702    pragma Atomic_Components (Prio_Array_Type);
703
704    Prio_Array : Prio_Array_Type;
705    --  Global array containing the id of the currently running task for
706    --  each priority.
707    --
708    --  Note: we assume that we are on a single processor with run-til-blocked
709    --  scheduling.
710
711    procedure Set_Priority
712      (T                   : Task_Id;
713       Prio                : System.Any_Priority;
714       Loss_Of_Inheritance : Boolean := False)
715    is
716       Res        : BOOL;
717       Array_Item : Integer;
718
719    begin
720       Res := SetThreadPriority
721         (T.Common.LL.Thread, Interfaces.C.int (Underlying_Priorities (Prio)));
722       pragma Assert (Res = True);
723
724       if Dispatching_Policy = 'F' or else Get_Policy (Prio) = 'F' then
725
726          --  Annex D requirement [RM D.2.2 par. 9]:
727          --    If the task drops its priority due to the loss of inherited
728          --    priority, it is added at the head of the ready queue for its
729          --    new active priority.
730
731          if Loss_Of_Inheritance
732            and then Prio < T.Common.Current_Priority
733          then
734             Array_Item := Prio_Array (T.Common.Base_Priority) + 1;
735             Prio_Array (T.Common.Base_Priority) := Array_Item;
736
737             loop
738                --  Let some processes a chance to arrive
739
740                Yield;
741
742                --  Then wait for our turn to proceed
743
744                exit when Array_Item = Prio_Array (T.Common.Base_Priority)
745                  or else Prio_Array (T.Common.Base_Priority) = 1;
746             end loop;
747
748             Prio_Array (T.Common.Base_Priority) :=
749               Prio_Array (T.Common.Base_Priority) - 1;
750          end if;
751       end if;
752
753       T.Common.Current_Priority := Prio;
754    end Set_Priority;
755
756    ------------------
757    -- Get_Priority --
758    ------------------
759
760    function Get_Priority (T : Task_Id) return System.Any_Priority is
761    begin
762       return T.Common.Current_Priority;
763    end Get_Priority;
764
765    ----------------
766    -- Enter_Task --
767    ----------------
768
769    --  There were two paths were we needed to call Enter_Task :
770    --  1) from System.Task_Primitives.Operations.Initialize
771    --  2) from System.Tasking.Stages.Task_Wrapper
772
773    --  The thread initialisation has to be done only for the first case
774
775    --  This is because the GetCurrentThread NT call does not return the real
776    --  thread handler but only a "pseudo" one. It is not possible to release
777    --  the thread handle and free the system ressources from this "pseudo"
778    --  handle. So we really want to keep the real thread handle set in
779    --  System.Task_Primitives.Operations.Create_Task during thread creation.
780
781    procedure Enter_Task (Self_ID : Task_Id) is
782       procedure Init_Float;
783       pragma Import (C, Init_Float, "__gnat_init_float");
784       --  Properly initializes the FPU for x86 systems
785
786    begin
787       Specific.Set (Self_ID);
788       Init_Float;
789
790       if Self_ID.Common.Task_Info /= null
791         and then
792           Self_ID.Common.Task_Info.CPU >= CPU_Number (Number_Of_Processors)
793       then
794          raise Invalid_CPU_Number;
795       end if;
796
797       Self_ID.Common.LL.Thread_Id := GetCurrentThreadId;
798
799       Lock_RTS;
800
801       for J in Known_Tasks'Range loop
802          if Known_Tasks (J) = null then
803             Known_Tasks (J) := Self_ID;
804             Self_ID.Known_Tasks_Index := J;
805             exit;
806          end if;
807       end loop;
808
809       Unlock_RTS;
810    end Enter_Task;
811
812    --------------
813    -- New_ATCB --
814    --------------
815
816    function New_ATCB (Entry_Num : Task_Entry_Index) return Task_Id is
817    begin
818       return new Ada_Task_Control_Block (Entry_Num);
819    end New_ATCB;
820
821    -------------------
822    -- Is_Valid_Task --
823    -------------------
824
825    function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
826
827    -----------------------------
828    -- Register_Foreign_Thread --
829    -----------------------------
830
831    function Register_Foreign_Thread return Task_Id is
832    begin
833       if Is_Valid_Task then
834          return Self;
835       else
836          return Register_Foreign_Thread (GetCurrentThread);
837       end if;
838    end Register_Foreign_Thread;
839
840    --------------------
841    -- Initialize_TCB --
842    --------------------
843
844    procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
845    begin
846       --  Initialize thread ID to 0, this is needed to detect threads that
847       --  are not yet activated.
848
849       Self_ID.Common.LL.Thread := 0;
850
851       Initialize_Cond (Self_ID.Common.LL.CV'Access);
852
853       if not Single_Lock then
854          Initialize_Lock (Self_ID.Common.LL.L'Access, ATCB_Level);
855       end if;
856
857       Succeeded := True;
858    end Initialize_TCB;
859
860    -----------------
861    -- Create_Task --
862    -----------------
863
864    procedure Create_Task
865      (T          : Task_Id;
866       Wrapper    : System.Address;
867       Stack_Size : System.Parameters.Size_Type;
868       Priority   : System.Any_Priority;
869       Succeeded  : out Boolean)
870    is
871       Initial_Stack_Size : constant := 1024;
872       --  We set the initial stack size to 1024. On Windows version prior to XP
873       --  there is no way to fix a task stack size. Only the initial stack size
874       --  can be set, the operating system will raise the task stack size if
875       --  needed.
876
877       function Is_Windows_XP return Integer;
878       pragma Import (C, Is_Windows_XP, "__gnat_is_windows_xp");
879       --  Returns 1 if running on Windows XP
880
881       hTask          : HANDLE;
882       TaskId         : aliased DWORD;
883       pTaskParameter : System.OS_Interface.PVOID;
884       Result         : DWORD;
885       Entry_Point    : PTHREAD_START_ROUTINE;
886
887    begin
888       pTaskParameter := To_Address (T);
889
890       Entry_Point := To_PTHREAD_START_ROUTINE (Wrapper);
891
892       if Is_Windows_XP = 1 then
893          hTask := CreateThread
894            (null,
895             DWORD (Stack_Size),
896             Entry_Point,
897             pTaskParameter,
898             DWORD (Create_Suspended) or
899               DWORD (Stack_Size_Param_Is_A_Reservation),
900             TaskId'Unchecked_Access);
901       else
902          hTask := CreateThread
903            (null,
904             Initial_Stack_Size,
905             Entry_Point,
906             pTaskParameter,
907             DWORD (Create_Suspended),
908             TaskId'Unchecked_Access);
909       end if;
910
911       --  Step 1: Create the thread in blocked mode
912
913       if hTask = 0 then
914          raise Storage_Error;
915       end if;
916
917       --  Step 2: set its TCB
918
919       T.Common.LL.Thread := hTask;
920
921       --  Step 3: set its priority (child has inherited priority from parent)
922
923       Set_Priority (T, Priority);
924
925       if Time_Slice_Val = 0
926         or else Dispatching_Policy = 'F'
927         or else Get_Policy (Priority) = 'F'
928       then
929          --  Here we need Annex D semantics so we disable the NT priority
930          --  boost. A priority boost is temporarily given by the system to a
931          --  thread when it is taken out of a wait state.
932
933          SetThreadPriorityBoost (hTask, DisablePriorityBoost => True);
934       end if;
935
936       --  Step 4: Handle Task_Info
937
938       if T.Common.Task_Info /= null then
939          if T.Common.Task_Info.CPU /= Task_Info.Any_CPU then
940             Result := SetThreadIdealProcessor (hTask, T.Common.Task_Info.CPU);
941             pragma Assert (Result = 1);
942          end if;
943       end if;
944
945       --  Step 5: Now, start it for good:
946
947       Result := ResumeThread (hTask);
948       pragma Assert (Result = 1);
949
950       Succeeded := Result = 1;
951    end Create_Task;
952
953    ------------------
954    -- Finalize_TCB --
955    ------------------
956
957    procedure Finalize_TCB (T : Task_Id) is
958       Self_ID   : Task_Id := T;
959       Result    : DWORD;
960       Succeeded : BOOL;
961       Is_Self   : constant Boolean := T = Self;
962
963       procedure Free is new
964         Ada.Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id);
965
966    begin
967       if not Single_Lock then
968          Finalize_Lock (T.Common.LL.L'Access);
969       end if;
970
971       Finalize_Cond (T.Common.LL.CV'Access);
972
973       if T.Known_Tasks_Index /= -1 then
974          Known_Tasks (T.Known_Tasks_Index) := null;
975       end if;
976
977       if Self_ID.Common.LL.Thread /= 0 then
978
979          --  This task has been activated. Wait for the thread to terminate
980          --  then close it. this is needed to release system ressources.
981
982          Result := WaitForSingleObject (T.Common.LL.Thread, Wait_Infinite);
983          pragma Assert (Result /= WAIT_FAILED);
984          Succeeded := CloseHandle (T.Common.LL.Thread);
985          pragma Assert (Succeeded = True);
986       end if;
987
988       Free (Self_ID);
989
990       if Is_Self then
991          Specific.Set (null);
992       end if;
993    end Finalize_TCB;
994
995    ---------------
996    -- Exit_Task --
997    ---------------
998
999    procedure Exit_Task is
1000    begin
1001       Specific.Set (null);
1002    end Exit_Task;
1003
1004    ----------------
1005    -- Abort_Task --
1006    ----------------
1007
1008    procedure Abort_Task (T : Task_Id) is
1009       pragma Unreferenced (T);
1010    begin
1011       null;
1012    end Abort_Task;
1013
1014    ----------------------
1015    -- Environment_Task --
1016    ----------------------
1017
1018    function Environment_Task return Task_Id is
1019    begin
1020       return Environment_Task_Id;
1021    end Environment_Task;
1022
1023    --------------
1024    -- Lock_RTS --
1025    --------------
1026
1027    procedure Lock_RTS is
1028    begin
1029       Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1030    end Lock_RTS;
1031
1032    ----------------
1033    -- Unlock_RTS --
1034    ----------------
1035
1036    procedure Unlock_RTS is
1037    begin
1038       Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1039    end Unlock_RTS;
1040
1041    ----------------
1042    -- Initialize --
1043    ----------------
1044
1045    procedure Initialize (Environment_Task : Task_Id) is
1046       Discard : BOOL;
1047       pragma Unreferenced (Discard);
1048
1049    begin
1050       Environment_Task_Id := Environment_Task;
1051       OS_Primitives.Initialize;
1052       Interrupt_Management.Initialize;
1053
1054       if Time_Slice_Val = 0 or else Dispatching_Policy = 'F' then
1055          --  Here we need Annex D semantics, switch the current process to the
1056          --  Realtime_Priority_Class.
1057
1058          Discard := OS_Interface.SetPriorityClass
1059                       (GetCurrentProcess, Realtime_Priority_Class);
1060
1061          Annex_D := True;
1062       end if;
1063
1064       TlsIndex := TlsAlloc;
1065
1066       --  Initialize the lock used to synchronize chain of all ATCBs
1067
1068       Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
1069
1070       Environment_Task.Common.LL.Thread := GetCurrentThread;
1071       Enter_Task (Environment_Task);
1072    end Initialize;
1073
1074    ---------------------
1075    -- Monotonic_Clock --
1076    ---------------------
1077
1078    function Monotonic_Clock return Duration
1079      renames System.OS_Primitives.Monotonic_Clock;
1080
1081    -------------------
1082    -- RT_Resolution --
1083    -------------------
1084
1085    function RT_Resolution return Duration is
1086    begin
1087       return 0.000_001; --  1 micro-second
1088    end RT_Resolution;
1089
1090    ----------------
1091    -- Initialize --
1092    ----------------
1093
1094    procedure Initialize (S : in out Suspension_Object) is
1095    begin
1096       --  Initialize internal state. It is always initialized to False (ARM
1097       --  D.10 par. 6).
1098
1099       S.State := False;
1100       S.Waiting := False;
1101
1102       --  Initialize internal mutex
1103
1104       InitializeCriticalSection (S.L'Access);
1105
1106       --  Initialize internal condition variable
1107
1108       S.CV := CreateEvent (null, True, False, Null_Ptr);
1109       pragma Assert (S.CV /= 0);
1110    end Initialize;
1111
1112    --------------
1113    -- Finalize --
1114    --------------
1115
1116    procedure Finalize (S : in out Suspension_Object) is
1117       Result : BOOL;
1118    begin
1119       --  Destroy internal mutex
1120
1121       DeleteCriticalSection (S.L'Access);
1122
1123       --  Destroy internal condition variable
1124
1125       Result := CloseHandle (S.CV);
1126       pragma Assert (Result = True);
1127    end Finalize;
1128
1129    -------------------
1130    -- Current_State --
1131    -------------------
1132
1133    function Current_State (S : Suspension_Object) return Boolean is
1134    begin
1135       --  We do not want to use lock on this read operation. State is marked
1136       --  as Atomic so that we ensure that the value retrieved is correct.
1137
1138       return S.State;
1139    end Current_State;
1140
1141    ---------------
1142    -- Set_False --
1143    ---------------
1144
1145    procedure Set_False (S : in out Suspension_Object) is
1146    begin
1147       SSL.Abort_Defer.all;
1148
1149       EnterCriticalSection (S.L'Access);
1150
1151       S.State := False;
1152
1153       LeaveCriticalSection (S.L'Access);
1154
1155       SSL.Abort_Undefer.all;
1156    end Set_False;
1157
1158    --------------
1159    -- Set_True --
1160    --------------
1161
1162    procedure Set_True (S : in out Suspension_Object) is
1163       Result : BOOL;
1164    begin
1165       SSL.Abort_Defer.all;
1166
1167       EnterCriticalSection (S.L'Access);
1168
1169       --  If there is already a task waiting on this suspension object then
1170       --  we resume it, leaving the state of the suspension object to False,
1171       --  as it is specified in ARM D.10 par. 9. Otherwise, it just leaves
1172       --  the state to True.
1173
1174       if S.Waiting then
1175          S.Waiting := False;
1176          S.State := False;
1177
1178          Result := SetEvent (S.CV);
1179          pragma Assert (Result = True);
1180       else
1181          S.State := True;
1182       end if;
1183
1184       LeaveCriticalSection (S.L'Access);
1185
1186       SSL.Abort_Undefer.all;
1187    end Set_True;
1188
1189    ------------------------
1190    -- Suspend_Until_True --
1191    ------------------------
1192
1193    procedure Suspend_Until_True (S : in out Suspension_Object) is
1194       Result      : DWORD;
1195       Result_Bool : BOOL;
1196    begin
1197       SSL.Abort_Defer.all;
1198
1199       EnterCriticalSection (S.L'Access);
1200
1201       if S.Waiting then
1202          --  Program_Error must be raised upon calling Suspend_Until_True
1203          --  if another task is already waiting on that suspension object
1204          --  (ARM D.10 par. 10).
1205
1206          LeaveCriticalSection (S.L'Access);
1207
1208          SSL.Abort_Undefer.all;
1209
1210          raise Program_Error;
1211       else
1212          --  Suspend the task if the state is False. Otherwise, the task
1213          --  continues its execution, and the state of the suspension object
1214          --  is set to False (ARM D.10 par. 9).
1215
1216          if S.State then
1217             S.State := False;
1218
1219             LeaveCriticalSection (S.L'Access);
1220
1221             SSL.Abort_Undefer.all;
1222          else
1223             S.Waiting := True;
1224
1225             --  Must reset CV BEFORE L is unlocked
1226
1227             Result_Bool := ResetEvent (S.CV);
1228             pragma Assert (Result_Bool = True);
1229
1230             LeaveCriticalSection (S.L'Access);
1231
1232             SSL.Abort_Undefer.all;
1233
1234             Result := WaitForSingleObject (S.CV, Wait_Infinite);
1235             pragma Assert (Result = 0);
1236          end if;
1237       end if;
1238    end Suspend_Until_True;
1239
1240    ----------------
1241    -- Check_Exit --
1242    ----------------
1243
1244    --  Dummy versions.  The only currently working versions is for solaris
1245    --  (native).
1246
1247    function Check_Exit (Self_ID : ST.Task_Id) return Boolean is
1248       pragma Unreferenced (Self_ID);
1249    begin
1250       return True;
1251    end Check_Exit;
1252
1253    --------------------
1254    -- Check_No_Locks --
1255    --------------------
1256
1257    function Check_No_Locks (Self_ID : ST.Task_Id) return Boolean is
1258       pragma Unreferenced (Self_ID);
1259    begin
1260       return True;
1261    end Check_No_Locks;
1262
1263    ------------------
1264    -- Suspend_Task --
1265    ------------------
1266
1267    function Suspend_Task
1268      (T           : ST.Task_Id;
1269       Thread_Self : Thread_Id) return Boolean
1270    is
1271    begin
1272       if T.Common.LL.Thread /= Thread_Self then
1273          return SuspendThread (T.Common.LL.Thread) = NO_ERROR;
1274       else
1275          return True;
1276       end if;
1277    end Suspend_Task;
1278
1279    -----------------
1280    -- Resume_Task --
1281    -----------------
1282
1283    function Resume_Task
1284      (T           : ST.Task_Id;
1285       Thread_Self : Thread_Id) return Boolean
1286    is
1287    begin
1288       if T.Common.LL.Thread /= Thread_Self then
1289          return ResumeThread (T.Common.LL.Thread) = NO_ERROR;
1290       else
1291          return True;
1292       end if;
1293    end Resume_Task;
1294
1295    --------------------
1296    -- Stop_All_Tasks --
1297    --------------------
1298
1299    procedure Stop_All_Tasks is
1300    begin
1301       null;
1302    end Stop_All_Tasks;
1303
1304    -------------------
1305    -- Continue_Task --
1306    -------------------
1307
1308    function Continue_Task (T : ST.Task_Id) return Boolean is
1309       pragma Unreferenced (T);
1310    begin
1311       return False;
1312    end Continue_Task;
1313
1314 end System.Task_Primitives.Operations;