spawn_22.0.0_706c53da/source/spawn/spawn-processes-monitor__windows.adb

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
------------------------------------------------------------------------------
--                         Language Server Protocol                         --
--                                                                          --
--                     Copyright (C) 2018-2020, AdaCore                     --
--                                                                          --
-- This is free software;  you can redistribute it  and/or modify it  under --
-- terms of the  GNU General Public License as published  by the Free Soft- --
-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
-- sion.  This software is distributed in the hope  that it will be useful, --
-- but WITHOUT ANY WARRANTY;  without even the implied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public --
-- License for  more details.  You should have  received  a copy of the GNU --
-- General  Public  License  distributed  with  this  software;   see  file --
-- COPYING3.  If not, go to http://www.gnu.org/licenses for a complete copy --
-- of the license.                                                          --
--                                                                          --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception,   --
-- version 3.1, as published by the Free Software Foundation.               --
------------------------------------------------------------------------------

with Ada.Containers.Synchronized_Queue_Interfaces;
with Ada.Containers.Unbounded_Synchronized_Queues;
with Ada.Containers.Vectors;
with Ada.Unchecked_Deallocation;

pragma Warnings (Off);
with System.Win32;
pragma Warnings (On);

with Spawn.Processes.Windows;
with Spawn.Windows_API;

package body Spawn.Processes.Monitor is

   subtype Context is Internal.Context;
   subtype Stream_Element_Buffer is Internal.Stream_Element_Buffer;

   type Process_Access is access all Processes.Process'Class;

   procedure Start_Process (Self : access Processes.Process'Class);

   package Command_Queue_Interfaces is
     new Ada.Containers.Synchronized_Queue_Interfaces (Command);

   package Command_Queues is new Ada.Containers.Unbounded_Synchronized_Queues
     (Queue_Interfaces => Command_Queue_Interfaces);

   package Read_Write_Ex is
     new Windows_API.Generic_Read_Write_Ex (Context);

   procedure Standard_Input_Callback
     (dwErrorCode               : Windows_API.DWORD;
      dwNumberOfBytesTransfered : Windows_API.DWORD;
      lpOverlapped              : access Context)
        with Convention => Stdcall;

   procedure Standard_Output_Callback
     (dwErrorCode               : Windows_API.DWORD;
      dwNumberOfBytesTransfered : Windows_API.DWORD;
      lpOverlapped              : access Context)
        with Convention => Stdcall;

   procedure Standard_Error_Callback
     (dwErrorCode               : Windows_API.DWORD;
      dwNumberOfBytesTransfered : Windows_API.DWORD;
      lpOverlapped              : access Context)
        with Convention => Stdcall;

   procedure Do_Watch_Pipe
     (Process : not null Process_Access;
      Kind    : Standard_Pipe);

   Callback : constant array (Stdout .. Stderr) of Read_Write_Ex.Callback :=
     (Standard_Output_Callback'Access,
      Standard_Error_Callback'Access);

   Queue : Command_Queues.Queue;

   package Poll is
      procedure Wake_Up;

      procedure Add_Process (Process : Process_Access);
      procedure Wait_Process_Death (Timeout : Integer);
   end Poll;

   package body Poll is
      package Info_Vectors is new Ada.Containers.Vectors
        (Positive, Process_Access);
      type pollfd_array_access is access all Windows_API.HANDLE_Array;
      procedure Free is new Ada.Unchecked_Deallocation
        (Windows_API.HANDLE_Array, pollfd_array_access);

      List  : Info_Vectors.Vector;
      fds   : pollfd_array_access;
      Last  : Natural := 0;
      wake  : Windows_API.HANDLE := 0;

      -----------------
      -- Add_Process --
      -----------------

      procedure Add_Process (Process : Process_Access) is
      begin
         if fds = null then
            --  Make event for wake up poll and initialize fds
            wake := Windows_API.CreateEventW
              (lpSecurityAttributes => null,
               bManualReset         => System.Win32.FALSE,
               bInitialState        => System.Win32.FALSE,
               lpName               => null);
            fds := new Windows_API.HANDLE_Array (1 .. 5);
            fds (1) := wake;
            List.Append (null); --  Dummy value
            Last := 1;
         elsif fds'Length < Last + 1 then
            --  Grow fds by factor of 1.5
            declare
               Old : pollfd_array_access := fds;
            begin
               fds := new Windows_API.HANDLE_Array (1 .. fds'Last * 3 / 2);
               fds (Old'Range) := Old.all;
               Free (Old);
            end;
         end if;

         Last := Last + 1;
         Process.Index := Last;

         fds (Last) := Process.pid.hProcess;

         if List.Last_Index < Last then
            List.Append (Process);
         else
            List (Last) := (Process);
         end if;
      end Add_Process;

      ------------------------
      -- Wait_Process_Death --
      ------------------------

      procedure Wait_Process_Death (Timeout : Integer) is
         use type Windows_API.DWORD;

         Result    : Windows_API.DWORD;
         Index     : Integer;
         Process   : Process_Access;

      begin
         loop
            Result := Windows_API.WaitForMultipleObjectsEx
              (nCount         => Windows_API.DWORD (Last),
               lpHandles      => fds.all,
               bWaitAll       => System.Win32.FALSE,
               dwMilliseconds => Windows_API.DWORD (Timeout),
               bAlertable     => System.Win32.TRUE);

            if Result /= Windows_API.WAIT_IO_COMPLETION then
               exit;
            end if;
         end loop;

         Index := Integer (Result) + 1;

         if Result = Windows_API.WAIT_TIMEOUT then
            return;
         elsif Index = 1 then
            --  Wake up event triggered
            return;
         elsif Index <= Last then
            --  Some process died
            Process := List (Index);
            Windows.On_Process_Died (Process.all);
         else
            raise Program_Error with "WaitForMultipleObjectsEx FAILED";
         end if;
      end Wait_Process_Death;

      -------------
      -- Wake_Up --
      -------------

      procedure Wake_Up is
         use type Windows_API.BOOL;
         use type Windows_API.HANDLE;
         Result : Windows_API.BOOL;
      begin
         if wake /= 0 then  --  If wake has been created
            Result := Windows_API.SetEvent (wake);
            pragma Assert (Result /= System.Win32.FALSE);
         end if;
      end Wake_Up;
   end Poll;

   -------------------
   -- Do_Watch_Pipe --
   -------------------

   procedure Do_Watch_Pipe
     (Process : not null Process_Access;
      Kind    : Standard_Pipe)
   is
      use type Ada.Streams.Stream_Element_Count;
      use type Windows_API.BOOL;
      Ok : Windows_API.BOOL;
      Last : Ada.Streams.Stream_Element_Count;
   begin
      case Kind is
         when Stdout | Stderr =>
            Ok := Read_Write_Ex.ReadFileEx
              (hFile                => Process.pipe (Kind).Handle,
               lpBuffer             => Process.pipe (Kind).Buffer,
               nNumberOfBytesToRead => Process.pipe (Kind).Buffer'Length,
               lpOverlapped         => Process.pipe (Kind)'Access,
               lpCompletionRoutine  => Callback (Kind));

            if Ok = System.Win32.FALSE then
               Process.Listener.Error_Occurred
                 (Integer (System.Win32.GetLastError));
            end if;
         when Stdin =>
            Last := Process.pipe (Kind).Last;

            if Last not in Stream_Element_Buffer'Range then
               Last := Last - Stream_Element_Buffer'Last;
            end if;

            Ok := Read_Write_Ex.WriteFileEx
              (hFile                 => Process.pipe (Kind).Handle,
               lpBuffer              => Process.pipe (Kind).Buffer,
               nNumberOfBytesToWrite => Windows_API.DWORD (Last),
               lpOverlapped          => Process.pipe (Kind)'Access,
               lpCompletionRoutine   => Standard_Input_Callback'Access);

            if Ok = System.Win32.FALSE then
               Process.Listener.Error_Occurred
                 (Integer (System.Win32.GetLastError));
            end if;
      end case;
   end Do_Watch_Pipe;

   -------------
   -- Enqueue --
   -------------

   procedure Enqueue (Value : Command) is
   begin
      Queue.Enqueue (Value);
      Poll.Wake_Up;
   end Enqueue;

   ----------------
   -- Loop_Cycle --
   ----------------

   procedure Loop_Cycle (Timeout : Integer) is
      use type Ada.Containers.Count_Type;
      Command : Monitor.Command;
   begin
      while Queue.Current_Use > 0 loop
         Queue.Dequeue (Command);

         case Command.Kind is
            when Start =>
               Start_Process (Command.Process);
            when Close_Pipe =>
               Windows.Do_Close_Pipe (Command.Process.all, Command.Pipe);
            when Watch_Pipe =>
               Do_Watch_Pipe (Command.Process, Command.Pipe);
         end case;
      end loop;

      Poll.Wait_Process_Death (Timeout);
   end Loop_Cycle;

   -----------------------------
   -- Standard_Error_Callback --
   -----------------------------

   procedure Standard_Error_Callback
     (dwErrorCode               : Windows_API.DWORD;
      dwNumberOfBytesTransfered : Windows_API.DWORD;
      lpOverlapped              : access Context) is
   begin
      Windows.IO_Callback
        (dwErrorCode, dwNumberOfBytesTransfered, lpOverlapped, Stderr);
   end Standard_Error_Callback;

   ------------------------------
   -- Standard_Output_Callback --
   ------------------------------

   procedure Standard_Output_Callback
     (dwErrorCode               : Windows_API.DWORD;
      dwNumberOfBytesTransfered : Windows_API.DWORD;
      lpOverlapped              : access Context) is
   begin
      Windows.IO_Callback
        (dwErrorCode, dwNumberOfBytesTransfered, lpOverlapped, Stdout);
   end Standard_Output_Callback;

   -----------------------------
   -- Standard_Input_Callback --
   -----------------------------

   procedure Standard_Input_Callback
     (dwErrorCode               : Windows_API.DWORD;
      dwNumberOfBytesTransfered : Windows_API.DWORD;
      lpOverlapped              : access Context) is
   begin
      Windows.IO_Callback
        (dwErrorCode, dwNumberOfBytesTransfered, lpOverlapped, Stdin);
   end Standard_Input_Callback;

   -------------------
   -- Start_Process --
   -------------------

   procedure Start_Process (Self : access Processes.Process'Class) is
      procedure On_Start;

      procedure On_Start is
      begin
         Poll.Add_Process (Process_Access (Self));
      end On_Start;
   begin
      Windows.Do_Start_Process (Self.all, On_Start'Access);
   end Start_Process;

end Spawn.Processes.Monitor;