OSDN Git Service

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