OSDN Git Service

gcc/ada/:
[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
551       Result : Integer;
552       pragma Unreferenced (Result);
553
554       Local_Timedout : Boolean;
555
556    begin
557       Timedout := True;
558       Yielded  := False;
559
560       if Mode = Relative then
561          Rel_Time := Time;
562          Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
563       else
564          Rel_Time := Time - Check_Time;
565          Abs_Time := Time;
566       end if;
567
568       if Rel_Time > 0.0 then
569          loop
570             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
571
572             if Single_Lock then
573                Cond_Timed_Wait
574                  (Self_ID.Common.LL.CV'Access,
575                   Single_RTS_Lock'Access,
576                   Rel_Time, Local_Timedout, Result);
577             else
578                Cond_Timed_Wait
579                  (Self_ID.Common.LL.CV'Access,
580                   Self_ID.Common.LL.L'Access,
581                   Rel_Time, Local_Timedout, Result);
582             end if;
583
584             Check_Time := Monotonic_Clock;
585             exit when Abs_Time <= Check_Time;
586
587             if not Local_Timedout then
588
589                --  Somebody may have called Wakeup for us
590
591                Timedout := False;
592                exit;
593             end if;
594
595             Rel_Time := Abs_Time - Check_Time;
596          end loop;
597       end if;
598    end Timed_Sleep;
599
600    -----------------
601    -- Timed_Delay --
602    -----------------
603
604    procedure Timed_Delay
605      (Self_ID : Task_Id;
606       Time    : Duration;
607       Mode    : ST.Delay_Modes)
608    is
609       Check_Time : Duration := Monotonic_Clock;
610       Rel_Time   : Duration;
611       Abs_Time   : Duration;
612
613       Timedout : Boolean;
614       Result   : Integer;
615       pragma Unreferenced (Timedout, Result);
616
617    begin
618       if Single_Lock then
619          Lock_RTS;
620       end if;
621
622       Write_Lock (Self_ID);
623
624       if Mode = Relative then
625          Rel_Time := Time;
626          Abs_Time := Time + Check_Time;
627       else
628          Rel_Time := Time - Check_Time;
629          Abs_Time := Time;
630       end if;
631
632       if Rel_Time > 0.0 then
633          Self_ID.Common.State := Delay_Sleep;
634
635          loop
636             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
637
638             if Single_Lock then
639                Cond_Timed_Wait
640                  (Self_ID.Common.LL.CV'Access,
641                   Single_RTS_Lock'Access,
642                   Rel_Time, Timedout, Result);
643             else
644                Cond_Timed_Wait
645                  (Self_ID.Common.LL.CV'Access,
646                   Self_ID.Common.LL.L'Access,
647                   Rel_Time, Timedout, Result);
648             end if;
649
650             Check_Time := Monotonic_Clock;
651             exit when Abs_Time <= Check_Time;
652
653             Rel_Time := Abs_Time - Check_Time;
654          end loop;
655
656          Self_ID.Common.State := Runnable;
657       end if;
658
659       Unlock (Self_ID);
660
661       if Single_Lock then
662          Unlock_RTS;
663       end if;
664
665       Yield;
666    end Timed_Delay;
667
668    ------------
669    -- Wakeup --
670    ------------
671
672    procedure Wakeup (T : Task_Id; Reason : System.Tasking.Task_States) is
673       pragma Unreferenced (Reason);
674    begin
675       Cond_Signal (T.Common.LL.CV'Access);
676    end Wakeup;
677
678    -----------
679    -- Yield --
680    -----------
681
682    procedure Yield (Do_Yield : Boolean := True) is
683    begin
684       if Do_Yield then
685          SwitchToThread;
686
687       elsif Annex_D then
688          --  If running with Annex-D semantics we need a delay
689          --  above 0 milliseconds here otherwise processes give
690          --  enough time to the other tasks to have a chance to
691          --  run.
692          --
693          --  This makes cxd8002 ACATS pass on Windows.
694
695          Sleep (1);
696       end if;
697    end Yield;
698
699    ------------------
700    -- Set_Priority --
701    ------------------
702
703    type Prio_Array_Type is array (System.Any_Priority) of Integer;
704    pragma Atomic_Components (Prio_Array_Type);
705
706    Prio_Array : Prio_Array_Type;
707    --  Global array containing the id of the currently running task for
708    --  each priority.
709    --
710    --  Note: we assume that we are on a single processor with run-til-blocked
711    --  scheduling.
712
713    procedure Set_Priority
714      (T                   : Task_Id;
715       Prio                : System.Any_Priority;
716       Loss_Of_Inheritance : Boolean := False)
717    is
718       Res        : BOOL;
719       Array_Item : Integer;
720
721    begin
722       Res := SetThreadPriority
723         (T.Common.LL.Thread, Interfaces.C.int (Underlying_Priorities (Prio)));
724       pragma Assert (Res = True);
725
726       if Dispatching_Policy = 'F' or else Get_Policy (Prio) = 'F' then
727
728          --  Annex D requirement [RM D.2.2 par. 9]:
729          --    If the task drops its priority due to the loss of inherited
730          --    priority, it is added at the head of the ready queue for its
731          --    new active priority.
732
733          if Loss_Of_Inheritance
734            and then Prio < T.Common.Current_Priority
735          then
736             Array_Item := Prio_Array (T.Common.Base_Priority) + 1;
737             Prio_Array (T.Common.Base_Priority) := Array_Item;
738
739             loop
740                --  Let some processes a chance to arrive
741
742                Yield;
743
744                --  Then wait for our turn to proceed
745
746                exit when Array_Item = Prio_Array (T.Common.Base_Priority)
747                  or else Prio_Array (T.Common.Base_Priority) = 1;
748             end loop;
749
750             Prio_Array (T.Common.Base_Priority) :=
751               Prio_Array (T.Common.Base_Priority) - 1;
752          end if;
753       end if;
754
755       T.Common.Current_Priority := Prio;
756    end Set_Priority;
757
758    ------------------
759    -- Get_Priority --
760    ------------------
761
762    function Get_Priority (T : Task_Id) return System.Any_Priority is
763    begin
764       return T.Common.Current_Priority;
765    end Get_Priority;
766
767    ----------------
768    -- Enter_Task --
769    ----------------
770
771    --  There were two paths were we needed to call Enter_Task :
772    --  1) from System.Task_Primitives.Operations.Initialize
773    --  2) from System.Tasking.Stages.Task_Wrapper
774
775    --  The thread initialisation has to be done only for the first case
776
777    --  This is because the GetCurrentThread NT call does not return the real
778    --  thread handler but only a "pseudo" one. It is not possible to release
779    --  the thread handle and free the system ressources from this "pseudo"
780    --  handle. So we really want to keep the real thread handle set in
781    --  System.Task_Primitives.Operations.Create_Task during thread creation.
782
783    procedure Enter_Task (Self_ID : Task_Id) is
784       procedure Init_Float;
785       pragma Import (C, Init_Float, "__gnat_init_float");
786       --  Properly initializes the FPU for x86 systems
787
788    begin
789       Specific.Set (Self_ID);
790       Init_Float;
791
792       if Self_ID.Common.Task_Info /= null
793         and then
794           Self_ID.Common.Task_Info.CPU >= CPU_Number (Number_Of_Processors)
795       then
796          raise Invalid_CPU_Number;
797       end if;
798
799       Self_ID.Common.LL.Thread_Id := GetCurrentThreadId;
800
801       Lock_RTS;
802
803       for J in Known_Tasks'Range loop
804          if Known_Tasks (J) = null then
805             Known_Tasks (J) := Self_ID;
806             Self_ID.Known_Tasks_Index := J;
807             exit;
808          end if;
809       end loop;
810
811       Unlock_RTS;
812    end Enter_Task;
813
814    --------------
815    -- New_ATCB --
816    --------------
817
818    function New_ATCB (Entry_Num : Task_Entry_Index) return Task_Id is
819    begin
820       return new Ada_Task_Control_Block (Entry_Num);
821    end New_ATCB;
822
823    -------------------
824    -- Is_Valid_Task --
825    -------------------
826
827    function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
828
829    -----------------------------
830    -- Register_Foreign_Thread --
831    -----------------------------
832
833    function Register_Foreign_Thread return Task_Id is
834    begin
835       if Is_Valid_Task then
836          return Self;
837       else
838          return Register_Foreign_Thread (GetCurrentThread);
839       end if;
840    end Register_Foreign_Thread;
841
842    --------------------
843    -- Initialize_TCB --
844    --------------------
845
846    procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
847    begin
848       --  Initialize thread ID to 0, this is needed to detect threads that
849       --  are not yet activated.
850
851       Self_ID.Common.LL.Thread := 0;
852
853       Initialize_Cond (Self_ID.Common.LL.CV'Access);
854
855       if not Single_Lock then
856          Initialize_Lock (Self_ID.Common.LL.L'Access, ATCB_Level);
857       end if;
858
859       Succeeded := True;
860    end Initialize_TCB;
861
862    -----------------
863    -- Create_Task --
864    -----------------
865
866    procedure Create_Task
867      (T          : Task_Id;
868       Wrapper    : System.Address;
869       Stack_Size : System.Parameters.Size_Type;
870       Priority   : System.Any_Priority;
871       Succeeded  : out Boolean)
872    is
873       Initial_Stack_Size : constant := 1024;
874       --  We set the initial stack size to 1024. On Windows version prior to XP
875       --  there is no way to fix a task stack size. Only the initial stack size
876       --  can be set, the operating system will raise the task stack size if
877       --  needed.
878
879       function Is_Windows_XP return Integer;
880       pragma Import (C, Is_Windows_XP, "__gnat_is_windows_xp");
881       --  Returns 1 if running on Windows XP
882
883       hTask          : HANDLE;
884       TaskId         : aliased DWORD;
885       pTaskParameter : System.OS_Interface.PVOID;
886       Result         : DWORD;
887       Entry_Point    : PTHREAD_START_ROUTINE;
888
889    begin
890       pTaskParameter := To_Address (T);
891
892       Entry_Point := To_PTHREAD_START_ROUTINE (Wrapper);
893
894       if Is_Windows_XP = 1 then
895          hTask := CreateThread
896            (null,
897             DWORD (Stack_Size),
898             Entry_Point,
899             pTaskParameter,
900             DWORD (Create_Suspended) or
901               DWORD (Stack_Size_Param_Is_A_Reservation),
902             TaskId'Unchecked_Access);
903       else
904          hTask := CreateThread
905            (null,
906             Initial_Stack_Size,
907             Entry_Point,
908             pTaskParameter,
909             DWORD (Create_Suspended),
910             TaskId'Unchecked_Access);
911       end if;
912
913       --  Step 1: Create the thread in blocked mode
914
915       if hTask = 0 then
916          raise Storage_Error;
917       end if;
918
919       --  Step 2: set its TCB
920
921       T.Common.LL.Thread := hTask;
922
923       --  Step 3: set its priority (child has inherited priority from parent)
924
925       Set_Priority (T, Priority);
926
927       if Time_Slice_Val = 0
928         or else Dispatching_Policy = 'F'
929         or else Get_Policy (Priority) = 'F'
930       then
931          --  Here we need Annex D semantics so we disable the NT priority
932          --  boost. A priority boost is temporarily given by the system to a
933          --  thread when it is taken out of a wait state.
934
935          SetThreadPriorityBoost (hTask, DisablePriorityBoost => True);
936       end if;
937
938       --  Step 4: Handle Task_Info
939
940       if T.Common.Task_Info /= null then
941          if T.Common.Task_Info.CPU /= Task_Info.Any_CPU then
942             Result := SetThreadIdealProcessor (hTask, T.Common.Task_Info.CPU);
943             pragma Assert (Result = 1);
944          end if;
945       end if;
946
947       --  Step 5: Now, start it for good:
948
949       Result := ResumeThread (hTask);
950       pragma Assert (Result = 1);
951
952       Succeeded := Result = 1;
953    end Create_Task;
954
955    ------------------
956    -- Finalize_TCB --
957    ------------------
958
959    procedure Finalize_TCB (T : Task_Id) is
960       Self_ID   : Task_Id := T;
961       Result    : DWORD;
962       Succeeded : BOOL;
963       Is_Self   : constant Boolean := T = Self;
964
965       procedure Free is new
966         Ada.Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id);
967
968    begin
969       if not Single_Lock then
970          Finalize_Lock (T.Common.LL.L'Access);
971       end if;
972
973       Finalize_Cond (T.Common.LL.CV'Access);
974
975       if T.Known_Tasks_Index /= -1 then
976          Known_Tasks (T.Known_Tasks_Index) := null;
977       end if;
978
979       if Self_ID.Common.LL.Thread /= 0 then
980
981          --  This task has been activated. Wait for the thread to terminate
982          --  then close it. this is needed to release system ressources.
983
984          Result := WaitForSingleObject (T.Common.LL.Thread, Wait_Infinite);
985          pragma Assert (Result /= WAIT_FAILED);
986          Succeeded := CloseHandle (T.Common.LL.Thread);
987          pragma Assert (Succeeded = True);
988       end if;
989
990       Free (Self_ID);
991
992       if Is_Self then
993          Specific.Set (null);
994       end if;
995    end Finalize_TCB;
996
997    ---------------
998    -- Exit_Task --
999    ---------------
1000
1001    procedure Exit_Task is
1002    begin
1003       Specific.Set (null);
1004    end Exit_Task;
1005
1006    ----------------
1007    -- Abort_Task --
1008    ----------------
1009
1010    procedure Abort_Task (T : Task_Id) is
1011       pragma Unreferenced (T);
1012    begin
1013       null;
1014    end Abort_Task;
1015
1016    ----------------------
1017    -- Environment_Task --
1018    ----------------------
1019
1020    function Environment_Task return Task_Id is
1021    begin
1022       return Environment_Task_Id;
1023    end Environment_Task;
1024
1025    --------------
1026    -- Lock_RTS --
1027    --------------
1028
1029    procedure Lock_RTS is
1030    begin
1031       Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1032    end Lock_RTS;
1033
1034    ----------------
1035    -- Unlock_RTS --
1036    ----------------
1037
1038    procedure Unlock_RTS is
1039    begin
1040       Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1041    end Unlock_RTS;
1042
1043    ----------------
1044    -- Initialize --
1045    ----------------
1046
1047    procedure Initialize (Environment_Task : Task_Id) is
1048       Discard : BOOL;
1049       pragma Unreferenced (Discard);
1050
1051    begin
1052       Environment_Task_Id := Environment_Task;
1053       OS_Primitives.Initialize;
1054       Interrupt_Management.Initialize;
1055
1056       if Time_Slice_Val = 0 or else Dispatching_Policy = 'F' then
1057          --  Here we need Annex D semantics, switch the current process to the
1058          --  Realtime_Priority_Class.
1059
1060          Discard := OS_Interface.SetPriorityClass
1061                       (GetCurrentProcess, Realtime_Priority_Class);
1062
1063          Annex_D := True;
1064       end if;
1065
1066       TlsIndex := TlsAlloc;
1067
1068       --  Initialize the lock used to synchronize chain of all ATCBs
1069
1070       Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
1071
1072       Environment_Task.Common.LL.Thread := GetCurrentThread;
1073       Enter_Task (Environment_Task);
1074    end Initialize;
1075
1076    ---------------------
1077    -- Monotonic_Clock --
1078    ---------------------
1079
1080    function Monotonic_Clock return Duration
1081      renames System.OS_Primitives.Monotonic_Clock;
1082
1083    -------------------
1084    -- RT_Resolution --
1085    -------------------
1086
1087    function RT_Resolution return Duration is
1088    begin
1089       return 0.000_001; --  1 micro-second
1090    end RT_Resolution;
1091
1092    ----------------
1093    -- Initialize --
1094    ----------------
1095
1096    procedure Initialize (S : in out Suspension_Object) is
1097    begin
1098       --  Initialize internal state. It is always initialized to False (ARM
1099       --  D.10 par. 6).
1100
1101       S.State := False;
1102       S.Waiting := False;
1103
1104       --  Initialize internal mutex
1105
1106       InitializeCriticalSection (S.L'Access);
1107
1108       --  Initialize internal condition variable
1109
1110       S.CV := CreateEvent (null, True, False, Null_Ptr);
1111       pragma Assert (S.CV /= 0);
1112    end Initialize;
1113
1114    --------------
1115    -- Finalize --
1116    --------------
1117
1118    procedure Finalize (S : in out Suspension_Object) is
1119       Result : BOOL;
1120    begin
1121       --  Destroy internal mutex
1122
1123       DeleteCriticalSection (S.L'Access);
1124
1125       --  Destroy internal condition variable
1126
1127       Result := CloseHandle (S.CV);
1128       pragma Assert (Result = True);
1129    end Finalize;
1130
1131    -------------------
1132    -- Current_State --
1133    -------------------
1134
1135    function Current_State (S : Suspension_Object) return Boolean is
1136    begin
1137       --  We do not want to use lock on this read operation. State is marked
1138       --  as Atomic so that we ensure that the value retrieved is correct.
1139
1140       return S.State;
1141    end Current_State;
1142
1143    ---------------
1144    -- Set_False --
1145    ---------------
1146
1147    procedure Set_False (S : in out Suspension_Object) is
1148    begin
1149       SSL.Abort_Defer.all;
1150
1151       EnterCriticalSection (S.L'Access);
1152
1153       S.State := False;
1154
1155       LeaveCriticalSection (S.L'Access);
1156
1157       SSL.Abort_Undefer.all;
1158    end Set_False;
1159
1160    --------------
1161    -- Set_True --
1162    --------------
1163
1164    procedure Set_True (S : in out Suspension_Object) is
1165       Result : BOOL;
1166    begin
1167       SSL.Abort_Defer.all;
1168
1169       EnterCriticalSection (S.L'Access);
1170
1171       --  If there is already a task waiting on this suspension object then
1172       --  we resume it, leaving the state of the suspension object to False,
1173       --  as it is specified in ARM D.10 par. 9. Otherwise, it just leaves
1174       --  the state to True.
1175
1176       if S.Waiting then
1177          S.Waiting := False;
1178          S.State := False;
1179
1180          Result := SetEvent (S.CV);
1181          pragma Assert (Result = True);
1182       else
1183          S.State := True;
1184       end if;
1185
1186       LeaveCriticalSection (S.L'Access);
1187
1188       SSL.Abort_Undefer.all;
1189    end Set_True;
1190
1191    ------------------------
1192    -- Suspend_Until_True --
1193    ------------------------
1194
1195    procedure Suspend_Until_True (S : in out Suspension_Object) is
1196       Result      : DWORD;
1197       Result_Bool : BOOL;
1198    begin
1199       SSL.Abort_Defer.all;
1200
1201       EnterCriticalSection (S.L'Access);
1202
1203       if S.Waiting then
1204          --  Program_Error must be raised upon calling Suspend_Until_True
1205          --  if another task is already waiting on that suspension object
1206          --  (ARM D.10 par. 10).
1207
1208          LeaveCriticalSection (S.L'Access);
1209
1210          SSL.Abort_Undefer.all;
1211
1212          raise Program_Error;
1213       else
1214          --  Suspend the task if the state is False. Otherwise, the task
1215          --  continues its execution, and the state of the suspension object
1216          --  is set to False (ARM D.10 par. 9).
1217
1218          if S.State then
1219             S.State := False;
1220
1221             LeaveCriticalSection (S.L'Access);
1222
1223             SSL.Abort_Undefer.all;
1224          else
1225             S.Waiting := True;
1226
1227             --  Must reset CV BEFORE L is unlocked
1228
1229             Result_Bool := ResetEvent (S.CV);
1230             pragma Assert (Result_Bool = True);
1231
1232             LeaveCriticalSection (S.L'Access);
1233
1234             SSL.Abort_Undefer.all;
1235
1236             Result := WaitForSingleObject (S.CV, Wait_Infinite);
1237             pragma Assert (Result = 0);
1238          end if;
1239       end if;
1240    end Suspend_Until_True;
1241
1242    ----------------
1243    -- Check_Exit --
1244    ----------------
1245
1246    --  Dummy versions.  The only currently working versions is for solaris
1247    --  (native).
1248
1249    function Check_Exit (Self_ID : ST.Task_Id) return Boolean is
1250       pragma Unreferenced (Self_ID);
1251    begin
1252       return True;
1253    end Check_Exit;
1254
1255    --------------------
1256    -- Check_No_Locks --
1257    --------------------
1258
1259    function Check_No_Locks (Self_ID : ST.Task_Id) return Boolean is
1260       pragma Unreferenced (Self_ID);
1261    begin
1262       return True;
1263    end Check_No_Locks;
1264
1265    ------------------
1266    -- Suspend_Task --
1267    ------------------
1268
1269    function Suspend_Task
1270      (T           : ST.Task_Id;
1271       Thread_Self : Thread_Id) return Boolean
1272    is
1273    begin
1274       if T.Common.LL.Thread /= Thread_Self then
1275          return SuspendThread (T.Common.LL.Thread) = NO_ERROR;
1276       else
1277          return True;
1278       end if;
1279    end Suspend_Task;
1280
1281    -----------------
1282    -- Resume_Task --
1283    -----------------
1284
1285    function Resume_Task
1286      (T           : ST.Task_Id;
1287       Thread_Self : Thread_Id) return Boolean
1288    is
1289    begin
1290       if T.Common.LL.Thread /= Thread_Self then
1291          return ResumeThread (T.Common.LL.Thread) = NO_ERROR;
1292       else
1293          return True;
1294       end if;
1295    end Resume_Task;
1296
1297    --------------------
1298    -- Stop_All_Tasks --
1299    --------------------
1300
1301    procedure Stop_All_Tasks is
1302    begin
1303       null;
1304    end Stop_All_Tasks;
1305
1306    ---------------
1307    -- Stop_Task --
1308    ---------------
1309
1310    function Stop_Task (T : ST.Task_Id) return Boolean is
1311       pragma Unreferenced (T);
1312    begin
1313       return False;
1314    end Stop_Task;
1315
1316    -------------------
1317    -- Continue_Task --
1318    -------------------
1319
1320    function Continue_Task (T : ST.Task_Id) return Boolean is
1321       pragma Unreferenced (T);
1322    begin
1323       return False;
1324    end Continue_Task;
1325
1326 end System.Task_Primitives.Operations;