1 ------------------------------------------------------------------------------
3 -- GNAT LIBRARY COMPONENTS --
5 -- G N A T . E X P E C T --
9 -- Copyright (C) 2000-2011, AdaCore --
11 -- GNAT 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. --
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. --
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/>. --
27 -- GNAT was originally developed by the GNAT team at New York University. --
28 -- Extensive contributions were provided by Ada Core Technologies Inc. --
30 ------------------------------------------------------------------------------
32 with System; use System;
33 with System.OS_Constants; use System.OS_Constants;
34 with Ada.Calendar; use Ada.Calendar;
37 with GNAT.OS_Lib; use GNAT.OS_Lib;
38 with GNAT.Regpat; use GNAT.Regpat;
40 with Ada.Unchecked_Deallocation;
42 package body GNAT.Expect is
44 type Array_Of_Pd is array (Positive range <>) of Process_Descriptor_Access;
46 Expect_Process_Died : constant Expect_Match := -100;
47 Expect_Internal_Error : constant Expect_Match := -101;
48 -- Additional possible outputs of Expect_Internal. These are not visible in
49 -- the spec because the user will never see them.
51 procedure Expect_Internal
52 (Descriptors : in out Array_Of_Pd;
53 Result : out Expect_Match;
55 Full_Buffer : Boolean);
56 -- Internal function used to read from the process Descriptor.
58 -- Several outputs are possible:
59 -- Result=Expect_Timeout, if no output was available before the timeout
61 -- Result=Expect_Full_Buffer, if Full_Buffer is True and some characters
62 -- had to be discarded from the internal buffer of Descriptor.
63 -- Result=Express_Process_Died if one of the processes was terminated.
64 -- That process's Input_Fd is set to Invalid_FD
65 -- Result=Express_Internal_Error
66 -- Result=<integer>, indicates how many characters were added to the
67 -- internal buffer. These characters are from indexes
68 -- Descriptor.Buffer_Index - Result + 1 .. Descriptor.Buffer_Index
69 -- Process_Died is raised if the process is no longer valid.
71 procedure Reinitialize_Buffer
72 (Descriptor : in out Process_Descriptor'Class);
73 -- Reinitialize the internal buffer.
74 -- The buffer is deleted up to the end of the last match.
76 procedure Free is new Ada.Unchecked_Deallocation
77 (Pattern_Matcher, Pattern_Matcher_Access);
79 procedure Free is new Ada.Unchecked_Deallocation
80 (Filter_List_Elem, Filter_List);
82 procedure Call_Filters
83 (Pid : Process_Descriptor'Class;
85 Filter_On : Filter_Type);
86 -- Call all the filters that have the appropriate type.
87 -- This function does nothing if the filters are locked
89 ------------------------------
90 -- Target dependent section --
91 ------------------------------
93 function Dup (Fd : File_Descriptor) return File_Descriptor;
94 pragma Import (C, Dup);
96 procedure Dup2 (Old_Fd, New_Fd : File_Descriptor);
97 pragma Import (C, Dup2);
99 procedure Kill (Pid : Process_Id; Sig_Num : Integer; Close : Integer);
100 pragma Import (C, Kill, "__gnat_kill");
101 -- if Close is set to 1 all OS resources used by the Pid must be freed
103 function Create_Pipe (Pipe : not null access Pipe_Type) return Integer;
104 pragma Import (C, Create_Pipe, "__gnat_pipe");
107 (Fds : System.Address;
110 Is_Set : System.Address) return Integer;
111 pragma Import (C, Poll, "__gnat_expect_poll");
112 -- Check whether there is any data waiting on the file descriptor
113 -- Out_fd, and wait if there is none, at most Timeout milliseconds
114 -- Returns -1 in case of error, 0 if the timeout expired before
115 -- data became available.
117 -- Out_Is_Set is set to 1 if data was available, 0 otherwise.
119 function Waitpid (Pid : Process_Id) return Integer;
120 pragma Import (C, Waitpid, "__gnat_waitpid");
121 -- Wait for a specific process id, and return its exit code
127 function "+" (S : String) return GNAT.OS_Lib.String_Access is
129 return new String'(S);
137 (P : GNAT.Regpat.Pattern_Matcher) return Pattern_Matcher_Access
140 return new GNAT.Regpat.Pattern_Matcher'(P);
148 (Descriptor : in out Process_Descriptor;
149 Filter : Filter_Function;
150 Filter_On : Filter_Type := Output;
151 User_Data : System.Address := System.Null_Address;
152 After : Boolean := False)
154 Current : Filter_List := Descriptor.Filters;
158 while Current /= null and then Current.Next /= null loop
159 Current := Current.Next;
162 if Current = null then
163 Descriptor.Filters :=
164 new Filter_List_Elem'
165 (Filter => Filter, Filter_On => Filter_On,
166 User_Data => User_Data, Next => null);
169 new Filter_List_Elem'
170 (Filter => Filter, Filter_On => Filter_On,
171 User_Data => User_Data, Next => null);
175 Descriptor.Filters :=
176 new Filter_List_Elem'
177 (Filter => Filter, Filter_On => Filter_On,
178 User_Data => User_Data, Next => Descriptor.Filters);
186 procedure Call_Filters
187 (Pid : Process_Descriptor'Class;
189 Filter_On : Filter_Type)
191 Current_Filter : Filter_List;
194 if Pid.Filters_Lock = 0 then
195 Current_Filter := Pid.Filters;
197 while Current_Filter /= null loop
198 if Current_Filter.Filter_On = Filter_On then
199 Current_Filter.Filter
200 (Pid, Str, Current_Filter.User_Data);
203 Current_Filter := Current_Filter.Next;
213 (Descriptor : in out Process_Descriptor;
214 Status : out Integer)
216 Current_Filter : Filter_List;
217 Next_Filter : Filter_List;
220 if Descriptor.Input_Fd /= Invalid_FD then
221 Close (Descriptor.Input_Fd);
224 if Descriptor.Error_Fd /= Descriptor.Output_Fd then
225 Close (Descriptor.Error_Fd);
228 Close (Descriptor.Output_Fd);
230 -- ??? Should have timeouts for different signals
232 if Descriptor.Pid > 0 then -- see comment in Send_Signal
233 Kill (Descriptor.Pid, Sig_Num => 9, Close => 0);
236 GNAT.OS_Lib.Free (Descriptor.Buffer);
237 Descriptor.Buffer_Size := 0;
239 Current_Filter := Descriptor.Filters;
241 while Current_Filter /= null loop
242 Next_Filter := Current_Filter.Next;
243 Free (Current_Filter);
244 Current_Filter := Next_Filter;
247 Descriptor.Filters := null;
249 -- Check process id (see comment in Send_Signal)
251 if Descriptor.Pid > 0 then
252 Status := Waitpid (Descriptor.Pid);
254 raise Invalid_Process;
258 procedure Close (Descriptor : in out Process_Descriptor) is
260 pragma Unreferenced (Status);
262 Close (Descriptor, Status);
270 (Descriptor : in out Process_Descriptor;
271 Result : out Expect_Match;
273 Timeout : Integer := 10_000;
274 Full_Buffer : Boolean := False)
278 Expect (Descriptor, Result, Never_Match, Timeout, Full_Buffer);
280 Expect (Descriptor, Result, Compile (Regexp), Timeout, Full_Buffer);
285 (Descriptor : in out Process_Descriptor;
286 Result : out Expect_Match;
288 Matched : out GNAT.Regpat.Match_Array;
289 Timeout : Integer := 10_000;
290 Full_Buffer : Boolean := False)
293 pragma Assert (Matched'First = 0);
296 (Descriptor, Result, Never_Match, Matched, Timeout, Full_Buffer);
299 (Descriptor, Result, Compile (Regexp), Matched, Timeout,
305 (Descriptor : in out Process_Descriptor;
306 Result : out Expect_Match;
307 Regexp : GNAT.Regpat.Pattern_Matcher;
308 Timeout : Integer := 10_000;
309 Full_Buffer : Boolean := False)
311 Matched : GNAT.Regpat.Match_Array (0 .. 0);
312 pragma Warnings (Off, Matched);
314 Expect (Descriptor, Result, Regexp, Matched, Timeout, Full_Buffer);
318 (Descriptor : in out Process_Descriptor;
319 Result : out Expect_Match;
320 Regexp : GNAT.Regpat.Pattern_Matcher;
321 Matched : out GNAT.Regpat.Match_Array;
322 Timeout : Integer := 10_000;
323 Full_Buffer : Boolean := False)
326 Descriptors : Array_Of_Pd := (1 => Descriptor'Unrestricted_Access);
327 Try_Until : constant Time := Clock + Duration (Timeout) / 1000.0;
328 Timeout_Tmp : Integer := Timeout;
331 pragma Assert (Matched'First = 0);
332 Reinitialize_Buffer (Descriptor);
335 -- First, test if what is already in the buffer matches (This is
336 -- required if this package is used in multi-task mode, since one of
337 -- the tasks might have added something in the buffer, and we don't
338 -- want other tasks to wait for new input to be available before
339 -- checking the regexps).
342 (Regexp, Descriptor.Buffer (1 .. Descriptor.Buffer_Index), Matched);
344 if Descriptor.Buffer_Index >= 1 and then Matched (0).First /= 0 then
346 Descriptor.Last_Match_Start := Matched (0).First;
347 Descriptor.Last_Match_End := Matched (0).Last;
351 -- Else try to read new input
353 Expect_Internal (Descriptors, N, Timeout_Tmp, Full_Buffer);
356 when Expect_Internal_Error | Expect_Process_Died =>
359 when Expect_Timeout | Expect_Full_Buffer =>
367 -- Calculate the timeout for the next turn
369 -- Note that Timeout is, from the caller's perspective, the maximum
370 -- time until a match, not the maximum time until some output is
371 -- read, and thus cannot be reused as is for Expect_Internal.
373 if Timeout /= -1 then
374 Timeout_Tmp := Integer (Try_Until - Clock) * 1000;
376 if Timeout_Tmp < 0 then
377 Result := Expect_Timeout;
383 -- Even if we had the general timeout above, we have to test that the
384 -- last test we read from the external process didn't match.
387 (Regexp, Descriptor.Buffer (1 .. Descriptor.Buffer_Index), Matched);
389 if Matched (0).First /= 0 then
391 Descriptor.Last_Match_Start := Matched (0).First;
392 Descriptor.Last_Match_End := Matched (0).Last;
398 (Descriptor : in out Process_Descriptor;
399 Result : out Expect_Match;
400 Regexps : Regexp_Array;
401 Timeout : Integer := 10_000;
402 Full_Buffer : Boolean := False)
404 Patterns : Compiled_Regexp_Array (Regexps'Range);
406 Matched : GNAT.Regpat.Match_Array (0 .. 0);
407 pragma Warnings (Off, Matched);
410 for J in Regexps'Range loop
411 Patterns (J) := new Pattern_Matcher'(Compile (Regexps (J).all));
414 Expect (Descriptor, Result, Patterns, Matched, Timeout, Full_Buffer);
416 for J in Regexps'Range loop
422 (Descriptor : in out Process_Descriptor;
423 Result : out Expect_Match;
424 Regexps : Compiled_Regexp_Array;
425 Timeout : Integer := 10_000;
426 Full_Buffer : Boolean := False)
428 Matched : GNAT.Regpat.Match_Array (0 .. 0);
429 pragma Warnings (Off, Matched);
431 Expect (Descriptor, Result, Regexps, Matched, Timeout, Full_Buffer);
435 (Result : out Expect_Match;
436 Regexps : Multiprocess_Regexp_Array;
437 Timeout : Integer := 10_000;
438 Full_Buffer : Boolean := False)
440 Matched : GNAT.Regpat.Match_Array (0 .. 0);
441 pragma Warnings (Off, Matched);
443 Expect (Result, Regexps, Matched, Timeout, Full_Buffer);
447 (Descriptor : in out Process_Descriptor;
448 Result : out Expect_Match;
449 Regexps : Regexp_Array;
450 Matched : out GNAT.Regpat.Match_Array;
451 Timeout : Integer := 10_000;
452 Full_Buffer : Boolean := False)
454 Patterns : Compiled_Regexp_Array (Regexps'Range);
457 pragma Assert (Matched'First = 0);
459 for J in Regexps'Range loop
460 Patterns (J) := new Pattern_Matcher'(Compile (Regexps (J).all));
463 Expect (Descriptor, Result, Patterns, Matched, Timeout, Full_Buffer);
465 for J in Regexps'Range loop
471 (Descriptor : in out Process_Descriptor;
472 Result : out Expect_Match;
473 Regexps : Compiled_Regexp_Array;
474 Matched : out GNAT.Regpat.Match_Array;
475 Timeout : Integer := 10_000;
476 Full_Buffer : Boolean := False)
479 Descriptors : Array_Of_Pd := (1 => Descriptor'Unrestricted_Access);
482 pragma Assert (Matched'First = 0);
484 Reinitialize_Buffer (Descriptor);
487 -- First, test if what is already in the buffer matches (This is
488 -- required if this package is used in multi-task mode, since one of
489 -- the tasks might have added something in the buffer, and we don't
490 -- want other tasks to wait for new input to be available before
491 -- checking the regexps).
493 if Descriptor.Buffer /= null then
494 for J in Regexps'Range loop
497 Descriptor.Buffer (1 .. Descriptor.Buffer_Index),
500 if Matched (0) /= No_Match then
501 Result := Expect_Match (J);
502 Descriptor.Last_Match_Start := Matched (0).First;
503 Descriptor.Last_Match_End := Matched (0).Last;
509 Expect_Internal (Descriptors, N, Timeout, Full_Buffer);
512 when Expect_Internal_Error | Expect_Process_Died =>
515 when Expect_Timeout | Expect_Full_Buffer =>
526 (Result : out Expect_Match;
527 Regexps : Multiprocess_Regexp_Array;
528 Matched : out GNAT.Regpat.Match_Array;
529 Timeout : Integer := 10_000;
530 Full_Buffer : Boolean := False)
533 Descriptors : Array_Of_Pd (Regexps'Range);
536 pragma Assert (Matched'First = 0);
538 for J in Descriptors'Range loop
539 Descriptors (J) := Regexps (J).Descriptor;
541 if Descriptors (J) /= null then
542 Reinitialize_Buffer (Regexps (J).Descriptor.all);
547 -- First, test if what is already in the buffer matches (This is
548 -- required if this package is used in multi-task mode, since one of
549 -- the tasks might have added something in the buffer, and we don't
550 -- want other tasks to wait for new input to be available before
551 -- checking the regexps).
553 for J in Regexps'Range loop
554 if Regexps (J).Regexp /= null
555 and then Regexps (J).Descriptor /= null
557 Match (Regexps (J).Regexp.all,
558 Regexps (J).Descriptor.Buffer
559 (1 .. Regexps (J).Descriptor.Buffer_Index),
562 if Matched (0) /= No_Match then
563 Result := Expect_Match (J);
564 Regexps (J).Descriptor.Last_Match_Start := Matched (0).First;
565 Regexps (J).Descriptor.Last_Match_End := Matched (0).Last;
571 Expect_Internal (Descriptors, N, Timeout, Full_Buffer);
574 when Expect_Internal_Error | Expect_Process_Died =>
577 when Expect_Timeout | Expect_Full_Buffer =>
587 ---------------------
588 -- Expect_Internal --
589 ---------------------
591 procedure Expect_Internal
592 (Descriptors : in out Array_Of_Pd;
593 Result : out Expect_Match;
595 Full_Buffer : Boolean)
597 Num_Descriptors : Integer;
598 Buffer_Size : Integer := 0;
602 type File_Descriptor_Array is
603 array (0 .. Descriptors'Length - 1) of File_Descriptor;
604 Fds : aliased File_Descriptor_Array;
605 Fds_Count : Natural := 0;
607 Fds_To_Descriptor : array (Fds'Range) of Integer;
608 -- Maps file descriptor entries from Fds to entries in Descriptors.
609 -- They do not have the same index when entries in Descriptors are null.
611 type Integer_Array is array (Fds'Range) of Integer;
612 Is_Set : aliased Integer_Array;
615 for J in Descriptors'Range loop
616 if Descriptors (J) /= null then
617 Fds (Fds'First + Fds_Count) := Descriptors (J).Output_Fd;
618 Fds_To_Descriptor (Fds'First + Fds_Count) := J;
619 Fds_Count := Fds_Count + 1;
621 if Descriptors (J).Buffer_Size = 0 then
622 Buffer_Size := Integer'Max (Buffer_Size, 4096);
625 Integer'Max (Buffer_Size, Descriptors (J).Buffer_Size);
631 Buffer : aliased String (1 .. Buffer_Size);
632 -- Buffer used for input. This is allocated only once, not for
633 -- every iteration of the loop
636 -- Index in Descriptors
639 -- Loop until we match or we have a timeout
643 Poll (Fds'Address, Fds_Count, Timeout, Is_Set'Address);
645 case Num_Descriptors is
650 Result := Expect_Internal_Error;
656 Result := Expect_Timeout;
662 for F in Fds'Range loop
663 if Is_Set (F) = 1 then
664 D := Fds_To_Descriptor (F);
666 Buffer_Size := Descriptors (D).Buffer_Size;
668 if Buffer_Size = 0 then
672 N := Read (Descriptors (D).Output_Fd, Buffer'Address,
675 -- Error or End of file
678 -- ??? Note that ddd tries again up to three times
679 -- in that case. See LiterateA.C:174
681 Descriptors (D).Input_Fd := Invalid_FD;
682 Result := Expect_Process_Died;
686 -- If there is no limit to the buffer size
688 if Descriptors (D).Buffer_Size = 0 then
691 Tmp : String_Access := Descriptors (D).Buffer;
695 Descriptors (D).Buffer :=
696 new String (1 .. Tmp'Length + N);
697 Descriptors (D).Buffer (1 .. Tmp'Length) :=
699 Descriptors (D).Buffer
700 (Tmp'Length + 1 .. Tmp'Length + N) :=
703 Descriptors (D).Buffer_Index :=
704 Descriptors (D).Buffer'Last;
707 Descriptors (D).Buffer :=
709 Descriptors (D).Buffer.all :=
711 Descriptors (D).Buffer_Index := N;
716 -- Add what we read to the buffer
718 if Descriptors (D).Buffer_Index + N >
719 Descriptors (D).Buffer_Size
721 -- If the user wants to know when we have
722 -- read more than the buffer can contain.
725 Result := Expect_Full_Buffer;
729 -- Keep as much as possible from the buffer,
730 -- and forget old characters.
732 Descriptors (D).Buffer
733 (1 .. Descriptors (D).Buffer_Size - N) :=
734 Descriptors (D).Buffer
735 (N - Descriptors (D).Buffer_Size +
736 Descriptors (D).Buffer_Index + 1 ..
737 Descriptors (D).Buffer_Index);
738 Descriptors (D).Buffer_Index :=
739 Descriptors (D).Buffer_Size - N;
742 -- Keep what we read in the buffer
744 Descriptors (D).Buffer
745 (Descriptors (D).Buffer_Index + 1 ..
746 Descriptors (D).Buffer_Index + N) :=
748 Descriptors (D).Buffer_Index :=
749 Descriptors (D).Buffer_Index + N;
752 -- Call each of the output filter with what we
756 (Descriptors (D).all, Buffer (1 .. N), Output);
758 Result := Expect_Match (D);
772 function Expect_Out (Descriptor : Process_Descriptor) return String is
774 return Descriptor.Buffer (1 .. Descriptor.Last_Match_End);
777 ----------------------
778 -- Expect_Out_Match --
779 ----------------------
781 function Expect_Out_Match (Descriptor : Process_Descriptor) return String is
783 return Descriptor.Buffer
784 (Descriptor.Last_Match_Start .. Descriptor.Last_Match_End);
785 end Expect_Out_Match;
787 ------------------------
788 -- First_Dead_Process --
789 ------------------------
791 function First_Dead_Process
792 (Regexp : Multiprocess_Regexp_Array) return Natural is
794 for R in Regexp'Range loop
795 if Regexp (R).Descriptor /= null
796 and then Regexp (R).Descriptor.Input_Fd = GNAT.OS_Lib.Invalid_FD
803 end First_Dead_Process;
810 (Descriptor : in out Process_Descriptor;
811 Timeout : Integer := 0)
813 Buffer_Size : constant Integer := 8192;
814 Num_Descriptors : Integer;
816 Is_Set : aliased Integer;
817 Buffer : aliased String (1 .. Buffer_Size);
820 -- Empty the current buffer
822 Descriptor.Last_Match_End := Descriptor.Buffer_Index;
823 Reinitialize_Buffer (Descriptor);
825 -- Read everything from the process to flush its output
829 Poll (Descriptor.Output_Fd'Address, 1, Timeout, Is_Set'Address);
831 case Num_Descriptors is
838 -- Timeout => End of flush
847 N := Read (Descriptor.Output_Fd, Buffer'Address,
864 procedure Free (Regexp : in out Multiprocess_Regexp) is
865 procedure Unchecked_Free is new Ada.Unchecked_Deallocation
866 (Process_Descriptor'Class, Process_Descriptor_Access);
868 Unchecked_Free (Regexp.Descriptor);
869 Free (Regexp.Regexp);
872 ------------------------
873 -- Get_Command_Output --
874 ------------------------
876 function Get_Command_Output
878 Arguments : GNAT.OS_Lib.Argument_List;
880 Status : not null access Integer;
881 Err_To_Out : Boolean := False) return String
885 Process : Process_Descriptor;
887 Output : String_Access := new String (1 .. 1024);
888 -- Buffer used to accumulate standard output from the launched
889 -- command, expanded as necessary during execution.
892 -- Index of the last used character within Output
896 (Process, Command, Arguments, Err_To_Out => Err_To_Out);
898 if Input'Length > 0 then
899 Send (Process, Input);
902 Close (Process.Input_Fd);
903 Process.Input_Fd := Invalid_FD;
906 Result : Expect_Match;
907 pragma Unreferenced (Result);
910 -- This loop runs until the call to Expect raises Process_Died
913 Expect (Process, Result, ".+");
916 NOutput : String_Access;
917 S : constant String := Expect_Out (Process);
918 pragma Assert (S'Length > 0);
921 -- Expand buffer if we need more space. Note here that we add
922 -- S'Length to ensure that S will fit in the new buffer size.
924 if Last + S'Length > Output'Last then
925 NOutput := new String (1 .. 2 * Output'Last + S'Length);
926 NOutput (Output'Range) := Output.all;
929 -- Here if current buffer size is OK
935 NOutput (Last + 1 .. Last + S'Length) := S;
936 Last := Last + S'Length;
943 Close (Process, Status.all);
952 S : constant String := Output (1 .. Last);
957 end Get_Command_Output;
963 function Get_Error_Fd
964 (Descriptor : Process_Descriptor) return GNAT.OS_Lib.File_Descriptor
967 return Descriptor.Error_Fd;
974 function Get_Input_Fd
975 (Descriptor : Process_Descriptor) return GNAT.OS_Lib.File_Descriptor
978 return Descriptor.Input_Fd;
985 function Get_Output_Fd
986 (Descriptor : Process_Descriptor) return GNAT.OS_Lib.File_Descriptor
989 return Descriptor.Output_Fd;
997 (Descriptor : Process_Descriptor) return Process_Id
1000 return Descriptor.Pid;
1007 function Has_Process (Regexp : Multiprocess_Regexp_Array) return Boolean is
1009 return Regexp /= (Regexp'Range => (null, null));
1016 procedure Interrupt (Descriptor : in out Process_Descriptor) is
1017 SIGINT : constant := 2;
1019 Send_Signal (Descriptor, SIGINT);
1026 procedure Lock_Filters (Descriptor : in out Process_Descriptor) is
1028 Descriptor.Filters_Lock := Descriptor.Filters_Lock + 1;
1031 ------------------------
1032 -- Non_Blocking_Spawn --
1033 ------------------------
1035 procedure Non_Blocking_Spawn
1036 (Descriptor : out Process_Descriptor'Class;
1038 Args : GNAT.OS_Lib.Argument_List;
1039 Buffer_Size : Natural := 4096;
1040 Err_To_Out : Boolean := False)
1042 function Fork return Process_Id;
1043 pragma Import (C, Fork, "__gnat_expect_fork");
1044 -- Starts a new process if possible. See the Unix command fork for more
1045 -- information. On systems that do not support this capability (such as
1046 -- Windows...), this command does nothing, and Fork will return
1049 Pipe1, Pipe2, Pipe3 : aliased Pipe_Type;
1051 Arg : String_Access;
1052 Arg_List : String_List (1 .. Args'Length + 2);
1053 C_Arg_List : aliased array (1 .. Args'Length + 2) of System.Address;
1055 Command_With_Path : String_Access;
1058 -- Create the rest of the pipes
1060 Set_Up_Communications
1061 (Descriptor, Err_To_Out, Pipe1'Access, Pipe2'Access, Pipe3'Access);
1063 Command_With_Path := Locate_Exec_On_Path (Command);
1065 if Command_With_Path = null then
1066 raise Invalid_Process;
1069 -- Fork a new process
1071 Descriptor.Pid := Fork;
1073 -- Are we now in the child (or, for Windows, still in the common
1076 if Descriptor.Pid = Null_Pid then
1077 -- Prepare an array of arguments to pass to C
1079 Arg := new String (1 .. Command_With_Path'Length + 1);
1080 Arg (1 .. Command_With_Path'Length) := Command_With_Path.all;
1081 Arg (Arg'Last) := ASCII.NUL;
1082 Arg_List (1) := Arg;
1084 for J in Args'Range loop
1085 Arg := new String (1 .. Args (J)'Length + 1);
1086 Arg (1 .. Args (J)'Length) := Args (J).all;
1087 Arg (Arg'Last) := ASCII.NUL;
1088 Arg_List (J + 2 - Args'First) := Arg.all'Access;
1091 Arg_List (Arg_List'Last) := null;
1093 -- Make sure all arguments are compatible with OS conventions
1095 Normalize_Arguments (Arg_List);
1097 -- Prepare low-level argument list from the normalized arguments
1099 for K in Arg_List'Range loop
1101 (if Arg_List (K) /= null
1102 then Arg_List (K).all'Address
1103 else System.Null_Address);
1106 -- This does not return on Unix systems
1108 Set_Up_Child_Communications
1109 (Descriptor, Pipe1, Pipe2, Pipe3, Command_With_Path.all,
1110 C_Arg_List'Address);
1113 Free (Command_With_Path);
1115 -- Did we have an error when spawning the child ?
1117 if Descriptor.Pid < Null_Pid then
1118 raise Invalid_Process;
1120 -- We are now in the parent process
1122 Set_Up_Parent_Communications (Descriptor, Pipe1, Pipe2, Pipe3);
1125 -- Create the buffer
1127 Descriptor.Buffer_Size := Buffer_Size;
1129 if Buffer_Size /= 0 then
1130 Descriptor.Buffer := new String (1 .. Positive (Buffer_Size));
1133 -- Initialize the filters
1135 Descriptor.Filters := null;
1136 end Non_Blocking_Spawn;
1138 -------------------------
1139 -- Reinitialize_Buffer --
1140 -------------------------
1142 procedure Reinitialize_Buffer
1143 (Descriptor : in out Process_Descriptor'Class)
1146 if Descriptor.Buffer_Size = 0 then
1148 Tmp : String_Access := Descriptor.Buffer;
1151 Descriptor.Buffer :=
1153 (1 .. Descriptor.Buffer_Index - Descriptor.Last_Match_End);
1156 Descriptor.Buffer.all := Tmp
1157 (Descriptor.Last_Match_End + 1 .. Descriptor.Buffer_Index);
1162 Descriptor.Buffer_Index := Descriptor.Buffer'Last;
1166 (1 .. Descriptor.Buffer_Index - Descriptor.Last_Match_End) :=
1168 (Descriptor.Last_Match_End + 1 .. Descriptor.Buffer_Index);
1170 if Descriptor.Buffer_Index > Descriptor.Last_Match_End then
1171 Descriptor.Buffer_Index :=
1172 Descriptor.Buffer_Index - Descriptor.Last_Match_End;
1174 Descriptor.Buffer_Index := 0;
1178 Descriptor.Last_Match_Start := 0;
1179 Descriptor.Last_Match_End := 0;
1180 end Reinitialize_Buffer;
1186 procedure Remove_Filter
1187 (Descriptor : in out Process_Descriptor;
1188 Filter : Filter_Function)
1190 Previous : Filter_List := null;
1191 Current : Filter_List := Descriptor.Filters;
1194 while Current /= null loop
1195 if Current.Filter = Filter then
1196 if Previous = null then
1197 Descriptor.Filters := Current.Next;
1199 Previous.Next := Current.Next;
1203 Previous := Current;
1204 Current := Current.Next;
1213 (Descriptor : in out Process_Descriptor;
1215 Add_LF : Boolean := True;
1216 Empty_Buffer : Boolean := False)
1218 Line_Feed : aliased constant String := (1 .. 1 => ASCII.LF);
1219 Descriptors : Array_Of_Pd := (1 => Descriptor'Unrestricted_Access);
1221 Result : Expect_Match;
1223 pragma Warnings (Off, Result);
1224 pragma Warnings (Off, Discard);
1227 if Empty_Buffer then
1229 -- Force a read on the process if there is anything waiting
1232 (Descriptors, Result, Timeout => 0, Full_Buffer => False);
1234 if Result = Expect_Internal_Error
1235 or else Result = Expect_Process_Died
1240 Descriptor.Last_Match_End := Descriptor.Buffer_Index;
1244 Reinitialize_Buffer (Descriptor);
1247 Call_Filters (Descriptor, Str, Input);
1249 Write (Descriptor.Input_Fd, Str'Address, Str'Last - Str'First + 1);
1252 Call_Filters (Descriptor, Line_Feed, Input);
1254 Write (Descriptor.Input_Fd, Line_Feed'Address, 1);
1262 procedure Send_Signal
1263 (Descriptor : Process_Descriptor;
1267 -- A nonpositive process id passed to kill has special meanings. For
1268 -- example, -1 means kill all processes in sight, including self, in
1269 -- POSIX and Windows (and something slightly different in Linux). See
1270 -- man pages for details. In any case, we don't want to do that. Note
1271 -- that Descriptor.Pid will be -1 if the process was not successfully
1272 -- started; we don't want to kill ourself in that case.
1274 if Descriptor.Pid > 0 then
1275 Kill (Descriptor.Pid, Signal, Close => 1);
1276 -- ??? Need to check process status here
1278 raise Invalid_Process;
1282 ---------------------------------
1283 -- Set_Up_Child_Communications --
1284 ---------------------------------
1286 procedure Set_Up_Child_Communications
1287 (Pid : in out Process_Descriptor;
1288 Pipe1 : in out Pipe_Type;
1289 Pipe2 : in out Pipe_Type;
1290 Pipe3 : in out Pipe_Type;
1292 Args : System.Address)
1294 pragma Warnings (Off, Pid);
1295 pragma Warnings (Off, Pipe1);
1296 pragma Warnings (Off, Pipe2);
1297 pragma Warnings (Off, Pipe3);
1299 Input : File_Descriptor;
1300 Output : File_Descriptor;
1301 Error : File_Descriptor;
1303 No_Fork_On_Target : constant Boolean := Target_OS = Windows;
1306 if No_Fork_On_Target then
1308 -- Since Windows does not have a separate fork/exec, we need to
1309 -- perform the following actions:
1311 -- - save stdin, stdout, stderr
1312 -- - replace them by our pipes
1313 -- - create the child with process handle inheritance
1314 -- - revert to the previous stdin, stdout and stderr.
1316 Input := Dup (GNAT.OS_Lib.Standin);
1317 Output := Dup (GNAT.OS_Lib.Standout);
1318 Error := Dup (GNAT.OS_Lib.Standerr);
1321 -- Since we are still called from the parent process, there is no way
1322 -- currently we can cleanly close the unneeded ends of the pipes, but
1323 -- this doesn't really matter.
1325 -- We could close Pipe1.Output, Pipe2.Input, Pipe3.Input
1327 Dup2 (Pipe1.Input, GNAT.OS_Lib.Standin);
1328 Dup2 (Pipe2.Output, GNAT.OS_Lib.Standout);
1329 Dup2 (Pipe3.Output, GNAT.OS_Lib.Standerr);
1331 Portable_Execvp (Pid.Pid'Access, Cmd & ASCII.NUL, Args);
1333 -- The following commands are not executed on Unix systems, and are only
1334 -- required for Windows systems. We are now in the parent process.
1336 -- Restore the old descriptors
1338 Dup2 (Input, GNAT.OS_Lib.Standin);
1339 Dup2 (Output, GNAT.OS_Lib.Standout);
1340 Dup2 (Error, GNAT.OS_Lib.Standerr);
1344 end Set_Up_Child_Communications;
1346 ---------------------------
1347 -- Set_Up_Communications --
1348 ---------------------------
1350 procedure Set_Up_Communications
1351 (Pid : in out Process_Descriptor;
1352 Err_To_Out : Boolean;
1353 Pipe1 : not null access Pipe_Type;
1354 Pipe2 : not null access Pipe_Type;
1355 Pipe3 : not null access Pipe_Type)
1358 pragma Unreferenced (Status);
1363 if Create_Pipe (Pipe1) /= 0 then
1367 if Create_Pipe (Pipe2) /= 0 then
1371 -- Record the 'parent' end of the two pipes in Pid:
1372 -- Child stdin is connected to the 'write' end of Pipe1;
1373 -- Child stdout is connected to the 'read' end of Pipe2.
1374 -- We do not want these descriptors to remain open in the child
1375 -- process, so we mark them close-on-exec/non-inheritable.
1377 Pid.Input_Fd := Pipe1.Output;
1378 Set_Close_On_Exec (Pipe1.Output, True, Status);
1379 Pid.Output_Fd := Pipe2.Input;
1380 Set_Close_On_Exec (Pipe2.Input, True, Status);
1384 -- Reuse the standard output pipe for standard error
1386 Pipe3.all := Pipe2.all;
1389 -- Create a separate pipe for standard error
1391 if Create_Pipe (Pipe3) /= 0 then
1396 -- As above, record the proper fd for the child's standard error stream
1398 Pid.Error_Fd := Pipe3.Input;
1399 Set_Close_On_Exec (Pipe3.Input, True, Status);
1400 end Set_Up_Communications;
1402 ----------------------------------
1403 -- Set_Up_Parent_Communications --
1404 ----------------------------------
1406 procedure Set_Up_Parent_Communications
1407 (Pid : in out Process_Descriptor;
1408 Pipe1 : in out Pipe_Type;
1409 Pipe2 : in out Pipe_Type;
1410 Pipe3 : in out Pipe_Type)
1412 pragma Warnings (Off, Pid);
1413 pragma Warnings (Off, Pipe1);
1414 pragma Warnings (Off, Pipe2);
1415 pragma Warnings (Off, Pipe3);
1418 Close (Pipe1.Input);
1419 Close (Pipe2.Output);
1421 if Pipe3.Output /= Pipe2.Output then
1422 Close (Pipe3.Output);
1424 end Set_Up_Parent_Communications;
1430 procedure Trace_Filter
1431 (Descriptor : Process_Descriptor'Class;
1433 User_Data : System.Address := System.Null_Address)
1435 pragma Warnings (Off, Descriptor);
1436 pragma Warnings (Off, User_Data);
1441 --------------------
1442 -- Unlock_Filters --
1443 --------------------
1445 procedure Unlock_Filters (Descriptor : in out Process_Descriptor) is
1447 if Descriptor.Filters_Lock > 0 then
1448 Descriptor.Filters_Lock := Descriptor.Filters_Lock - 1;