OSDN Git Service

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