OSDN Git Service

2007-10-15 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / g-expect.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT LIBRARY COMPONENTS                          --
4 --                                                                          --
5 --                          G N A T . E X P E C T                           --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --                     Copyright (C) 2000-2007, AdaCore                     --
10 --                                                                          --
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 2,  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.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, USA.                                              --
21 --                                                                          --
22 -- As a special exception,  if other files  instantiate  generics from this --
23 -- unit, or you link  this unit with other files  to produce an executable, --
24 -- this  unit  does not  by itself cause  the resulting  executable  to  be --
25 -- covered  by the  GNU  General  Public  License.  This exception does not --
26 -- however invalidate  any other reasons why  the executable file  might be --
27 -- covered by the  GNU Public License.                                      --
28 --                                                                          --
29 -- GNAT was originally developed  by the GNAT team at  New York University. --
30 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
31 --                                                                          --
32 ------------------------------------------------------------------------------
33
34 with System;       use System;
35 with Ada.Calendar; use Ada.Calendar;
36
37 with GNAT.IO;
38 with GNAT.OS_Lib;  use GNAT.OS_Lib;
39 with GNAT.Regpat;  use GNAT.Regpat;
40
41 with Ada.Unchecked_Deallocation;
42
43 package body GNAT.Expect is
44
45    type Array_Of_Pd is array (Positive range <>) of Process_Descriptor_Access;
46
47    procedure Expect_Internal
48      (Descriptors : in out Array_Of_Pd;
49       Result      : out Expect_Match;
50       Timeout     : Integer;
51       Full_Buffer : Boolean);
52    --  Internal function used to read from the process Descriptor.
53    --
54    --  Three outputs are possible:
55    --     Result=Expect_Timeout, if no output was available before the timeout
56    --        expired.
57    --     Result=Expect_Full_Buffer, if Full_Buffer is True and some characters
58    --        had to be discarded from the internal buffer of Descriptor.
59    --     Result=<integer>, indicates how many characters were added to the
60    --        internal buffer. These characters are from indexes
61    --        Descriptor.Buffer_Index - Result + 1 .. Descriptor.Buffer_Index
62    --  Process_Died is raised if the process is no longer valid.
63
64    procedure Reinitialize_Buffer
65      (Descriptor : in out Process_Descriptor'Class);
66    --  Reinitialize the internal buffer.
67    --  The buffer is deleted up to the end of the last match.
68
69    procedure Free is new Ada.Unchecked_Deallocation
70      (Pattern_Matcher, Pattern_Matcher_Access);
71
72    procedure Free is new Ada.Unchecked_Deallocation
73      (Filter_List_Elem, Filter_List);
74
75    procedure Call_Filters
76      (Pid       : Process_Descriptor'Class;
77       Str       : String;
78       Filter_On : Filter_Type);
79    --  Call all the filters that have the appropriate type.
80    --  This function does nothing if the filters are locked
81
82    ------------------------------
83    -- Target dependent section --
84    ------------------------------
85
86    function Dup (Fd : File_Descriptor) return File_Descriptor;
87    pragma Import (C, Dup);
88
89    procedure Dup2 (Old_Fd, New_Fd : File_Descriptor);
90    pragma Import (C, Dup2);
91
92    procedure Kill (Pid : Process_Id; Sig_Num : Integer; Close : Integer);
93    pragma Import (C, Kill, "__gnat_kill");
94    --  if Close is set to 1 all OS resources used by the Pid must be freed
95
96    function Create_Pipe (Pipe : not null access Pipe_Type) return Integer;
97    pragma Import (C, Create_Pipe, "__gnat_pipe");
98
99    function Poll
100      (Fds     : System.Address;
101       Num_Fds : Integer;
102       Timeout : Integer;
103       Is_Set  : System.Address) return Integer;
104    pragma Import (C, Poll, "__gnat_expect_poll");
105    --  Check whether there is any data waiting on the file descriptor
106    --  Out_fd, and wait if there is none, at most Timeout milliseconds
107    --  Returns -1 in case of error, 0 if the timeout expired before
108    --  data became available.
109    --
110    --  Out_Is_Set is set to 1 if data was available, 0 otherwise.
111
112    function Waitpid (Pid : Process_Id) return Integer;
113    pragma Import (C, Waitpid, "__gnat_waitpid");
114    --  Wait for a specific process id, and return its exit code
115
116    ---------
117    -- "+" --
118    ---------
119
120    function "+" (S : String) return GNAT.OS_Lib.String_Access is
121    begin
122       return new String'(S);
123    end "+";
124
125    ---------
126    -- "+" --
127    ---------
128
129    function "+"
130      (P : GNAT.Regpat.Pattern_Matcher) return Pattern_Matcher_Access
131    is
132    begin
133       return new GNAT.Regpat.Pattern_Matcher'(P);
134    end "+";
135
136    ----------------
137    -- Add_Filter --
138    ----------------
139
140    procedure Add_Filter
141      (Descriptor : in out Process_Descriptor;
142       Filter     : Filter_Function;
143       Filter_On  : Filter_Type := Output;
144       User_Data  : System.Address := System.Null_Address;
145       After      : Boolean := False)
146    is
147       Current : Filter_List := Descriptor.Filters;
148
149    begin
150       if After then
151          while Current /= null and then Current.Next /= null loop
152             Current := Current.Next;
153          end loop;
154
155          if Current = null then
156             Descriptor.Filters :=
157               new Filter_List_Elem'
158                (Filter => Filter, Filter_On => Filter_On,
159                 User_Data => User_Data, Next => null);
160          else
161             Current.Next :=
162               new Filter_List_Elem'
163               (Filter => Filter, Filter_On => Filter_On,
164                User_Data => User_Data, Next => null);
165          end if;
166
167       else
168          Descriptor.Filters :=
169            new Filter_List_Elem'
170              (Filter => Filter, Filter_On => Filter_On,
171               User_Data => User_Data, Next => Descriptor.Filters);
172       end if;
173    end Add_Filter;
174
175    ------------------
176    -- Call_Filters --
177    ------------------
178
179    procedure Call_Filters
180      (Pid       : Process_Descriptor'Class;
181       Str       : String;
182       Filter_On : Filter_Type)
183    is
184       Current_Filter  : Filter_List;
185
186    begin
187       if Pid.Filters_Lock = 0 then
188          Current_Filter := Pid.Filters;
189
190          while Current_Filter /= null loop
191             if Current_Filter.Filter_On = Filter_On then
192                Current_Filter.Filter
193                  (Pid, Str, Current_Filter.User_Data);
194             end if;
195
196             Current_Filter := Current_Filter.Next;
197          end loop;
198       end if;
199    end Call_Filters;
200
201    -----------
202    -- Close --
203    -----------
204
205    procedure Close
206      (Descriptor : in out Process_Descriptor;
207       Status     : out Integer)
208    is
209       Current_Filter : Filter_List;
210       Next_Filter    : Filter_List;
211
212    begin
213       Close (Descriptor.Input_Fd);
214
215       if Descriptor.Error_Fd /= Descriptor.Output_Fd then
216          Close (Descriptor.Error_Fd);
217       end if;
218
219       Close (Descriptor.Output_Fd);
220
221       --  ??? Should have timeouts for different signals
222
223       if Descriptor.Pid > 0 then  --  see comment in Send_Signal
224          Kill (Descriptor.Pid, Sig_Num => 9, Close => 0);
225       end if;
226
227       GNAT.OS_Lib.Free (Descriptor.Buffer);
228       Descriptor.Buffer_Size := 0;
229
230       Current_Filter := Descriptor.Filters;
231
232       while Current_Filter /= null loop
233          Next_Filter := Current_Filter.Next;
234          Free (Current_Filter);
235          Current_Filter := Next_Filter;
236       end loop;
237
238       Descriptor.Filters := null;
239
240       --  Check process id (see comment in Send_Signal)
241
242       if Descriptor.Pid > 0 then
243          Status := Waitpid (Descriptor.Pid);
244       else
245          raise Invalid_Process;
246       end if;
247    end Close;
248
249    procedure Close (Descriptor : in out Process_Descriptor) is
250       Status : Integer;
251       pragma Unreferenced (Status);
252    begin
253       Close (Descriptor, Status);
254    end Close;
255
256    ------------
257    -- Expect --
258    ------------
259
260    procedure Expect
261      (Descriptor  : in out Process_Descriptor;
262       Result      : out Expect_Match;
263       Regexp      : String;
264       Timeout     : Integer := 10000;
265       Full_Buffer : Boolean := False)
266    is
267    begin
268       if Regexp = "" then
269          Expect (Descriptor, Result, Never_Match, Timeout, Full_Buffer);
270       else
271          Expect (Descriptor, Result, Compile (Regexp), Timeout, Full_Buffer);
272       end if;
273    end Expect;
274
275    procedure Expect
276      (Descriptor  : in out Process_Descriptor;
277       Result      : out Expect_Match;
278       Regexp      : String;
279       Matched     : out GNAT.Regpat.Match_Array;
280       Timeout     : Integer := 10000;
281       Full_Buffer : Boolean := False)
282    is
283    begin
284       pragma Assert (Matched'First = 0);
285       if Regexp = "" then
286          Expect
287            (Descriptor, Result, Never_Match, Matched, Timeout, Full_Buffer);
288       else
289          Expect
290            (Descriptor, Result, Compile (Regexp), Matched, Timeout,
291             Full_Buffer);
292       end if;
293    end Expect;
294
295    procedure Expect
296      (Descriptor  : in out Process_Descriptor;
297       Result      : out Expect_Match;
298       Regexp      : GNAT.Regpat.Pattern_Matcher;
299       Timeout     : Integer := 10000;
300       Full_Buffer : Boolean := False)
301    is
302       Matched : GNAT.Regpat.Match_Array (0 .. 0);
303       pragma Warnings (Off, Matched);
304    begin
305       Expect (Descriptor, Result, Regexp, Matched, Timeout, Full_Buffer);
306    end Expect;
307
308    procedure Expect
309      (Descriptor  : in out Process_Descriptor;
310       Result      : out Expect_Match;
311       Regexp      : GNAT.Regpat.Pattern_Matcher;
312       Matched     : out GNAT.Regpat.Match_Array;
313       Timeout     : Integer := 10000;
314       Full_Buffer : Boolean := False)
315    is
316       N           : Expect_Match;
317       Descriptors : Array_Of_Pd := (1 => Descriptor'Unrestricted_Access);
318       Try_Until   : constant Time := Clock + Duration (Timeout) / 1000.0;
319       Timeout_Tmp : Integer := Timeout;
320
321    begin
322       pragma Assert (Matched'First = 0);
323       Reinitialize_Buffer (Descriptor);
324
325       loop
326          --  First, test if what is already in the buffer matches (This is
327          --  required if this package is used in multi-task mode, since one of
328          --  the tasks might have added something in the buffer, and we don't
329          --  want other tasks to wait for new input to be available before
330          --  checking the regexps).
331
332          Match
333            (Regexp, Descriptor.Buffer (1 .. Descriptor.Buffer_Index), Matched);
334
335          if Descriptor.Buffer_Index >= 1 and then Matched (0).First /= 0 then
336             Result := 1;
337             Descriptor.Last_Match_Start := Matched (0).First;
338             Descriptor.Last_Match_End := Matched (0).Last;
339             return;
340          end if;
341
342          --  Else try to read new input
343
344          Expect_Internal (Descriptors, N, Timeout_Tmp, Full_Buffer);
345
346          if N = Expect_Timeout or else N = Expect_Full_Buffer then
347             Result := N;
348             return;
349          end if;
350
351          --  Calculate the timeout for the next turn
352
353          --  Note that Timeout is, from the caller's perspective, the maximum
354          --  time until a match, not the maximum time until some output is
355          --  read, and thus cannot be reused as is for Expect_Internal.
356
357          if Timeout /= -1 then
358             Timeout_Tmp := Integer (Try_Until - Clock) * 1000;
359
360             if Timeout_Tmp < 0 then
361                Result := Expect_Timeout;
362                exit;
363             end if;
364          end if;
365       end loop;
366
367       --  Even if we had the general timeout above, we have to test that the
368       --  last test we read from the external process didn't match.
369
370       Match
371         (Regexp, Descriptor.Buffer (1 .. Descriptor.Buffer_Index), Matched);
372
373       if Matched (0).First /= 0 then
374          Result := 1;
375          Descriptor.Last_Match_Start := Matched (0).First;
376          Descriptor.Last_Match_End := Matched (0).Last;
377          return;
378       end if;
379    end Expect;
380
381    procedure Expect
382      (Descriptor  : in out Process_Descriptor;
383       Result      : out Expect_Match;
384       Regexps     : Regexp_Array;
385       Timeout     : Integer := 10000;
386       Full_Buffer : Boolean := False)
387    is
388       Patterns : Compiled_Regexp_Array (Regexps'Range);
389
390       Matched : GNAT.Regpat.Match_Array (0 .. 0);
391       pragma Warnings (Off, Matched);
392
393    begin
394       for J in Regexps'Range loop
395          Patterns (J) := new Pattern_Matcher'(Compile (Regexps (J).all));
396       end loop;
397
398       Expect (Descriptor, Result, Patterns, Matched, Timeout, Full_Buffer);
399
400       for J in Regexps'Range loop
401          Free (Patterns (J));
402       end loop;
403    end Expect;
404
405    procedure Expect
406      (Descriptor  : in out Process_Descriptor;
407       Result      : out Expect_Match;
408       Regexps     : Compiled_Regexp_Array;
409       Timeout     : Integer := 10000;
410       Full_Buffer : Boolean := False)
411    is
412       Matched : GNAT.Regpat.Match_Array (0 .. 0);
413       pragma Warnings (Off, Matched);
414    begin
415       Expect (Descriptor, Result, Regexps, Matched, Timeout, Full_Buffer);
416    end Expect;
417
418    procedure Expect
419      (Result      : out Expect_Match;
420       Regexps     : Multiprocess_Regexp_Array;
421       Timeout     : Integer := 10000;
422       Full_Buffer : Boolean := False)
423    is
424       Matched : GNAT.Regpat.Match_Array (0 .. 0);
425       pragma Warnings (Off, Matched);
426    begin
427       Expect (Result, Regexps, Matched, Timeout, Full_Buffer);
428    end Expect;
429
430    procedure Expect
431      (Descriptor  : in out Process_Descriptor;
432       Result      : out Expect_Match;
433       Regexps     : Regexp_Array;
434       Matched     : out GNAT.Regpat.Match_Array;
435       Timeout     : Integer := 10000;
436       Full_Buffer : Boolean := False)
437    is
438       Patterns : Compiled_Regexp_Array (Regexps'Range);
439
440    begin
441       pragma Assert (Matched'First = 0);
442
443       for J in Regexps'Range loop
444          Patterns (J) := new Pattern_Matcher'(Compile (Regexps (J).all));
445       end loop;
446
447       Expect (Descriptor, Result, Patterns, Matched, Timeout, Full_Buffer);
448
449       for J in Regexps'Range loop
450          Free (Patterns (J));
451       end loop;
452    end Expect;
453
454    procedure Expect
455      (Descriptor  : in out Process_Descriptor;
456       Result      : out Expect_Match;
457       Regexps     : Compiled_Regexp_Array;
458       Matched     : out GNAT.Regpat.Match_Array;
459       Timeout     : Integer := 10000;
460       Full_Buffer : Boolean := False)
461    is
462       N           : Expect_Match;
463       Descriptors : Array_Of_Pd := (1 => Descriptor'Unrestricted_Access);
464
465    begin
466       pragma Assert (Matched'First = 0);
467
468       Reinitialize_Buffer (Descriptor);
469
470       loop
471          --  First, test if what is already in the buffer matches (This is
472          --  required if this package is used in multi-task mode, since one of
473          --  the tasks might have added something in the buffer, and we don't
474          --  want other tasks to wait for new input to be available before
475          --  checking the regexps).
476
477          if Descriptor.Buffer /= null then
478             for J in Regexps'Range loop
479                Match
480                  (Regexps (J).all,
481                   Descriptor.Buffer (1 .. Descriptor.Buffer_Index),
482                   Matched);
483
484                if Matched (0) /= No_Match then
485                   Result := Expect_Match (J);
486                   Descriptor.Last_Match_Start := Matched (0).First;
487                   Descriptor.Last_Match_End := Matched (0).Last;
488                   return;
489                end if;
490             end loop;
491          end if;
492
493          Expect_Internal (Descriptors, N, Timeout, Full_Buffer);
494
495          if N = Expect_Timeout or else N = Expect_Full_Buffer then
496             Result := N;
497             return;
498          end if;
499       end loop;
500    end Expect;
501
502    procedure Expect
503      (Result      : out Expect_Match;
504       Regexps     : Multiprocess_Regexp_Array;
505       Matched     : out GNAT.Regpat.Match_Array;
506       Timeout     : Integer := 10000;
507       Full_Buffer : Boolean := False)
508    is
509       N           : Expect_Match;
510       Descriptors : Array_Of_Pd (Regexps'Range);
511
512    begin
513       pragma Assert (Matched'First = 0);
514
515       for J in Descriptors'Range loop
516          Descriptors (J) := Regexps (J).Descriptor;
517          Reinitialize_Buffer (Regexps (J).Descriptor.all);
518       end loop;
519
520       loop
521          --  First, test if what is already in the buffer matches (This is
522          --  required if this package is used in multi-task mode, since one of
523          --  the tasks might have added something in the buffer, and we don't
524          --  want other tasks to wait for new input to be available before
525          --  checking the regexps).
526
527          for J in Regexps'Range loop
528             Match (Regexps (J).Regexp.all,
529                    Regexps (J).Descriptor.Buffer
530                      (1 .. Regexps (J).Descriptor.Buffer_Index),
531                    Matched);
532
533             if Matched (0) /= No_Match then
534                Result := Expect_Match (J);
535                Regexps (J).Descriptor.Last_Match_Start := Matched (0).First;
536                Regexps (J).Descriptor.Last_Match_End := Matched (0).Last;
537                return;
538             end if;
539          end loop;
540
541          Expect_Internal (Descriptors, N, Timeout, Full_Buffer);
542
543          if N = Expect_Timeout or else N = Expect_Full_Buffer then
544             Result := N;
545             return;
546          end if;
547       end loop;
548    end Expect;
549
550    ---------------------
551    -- Expect_Internal --
552    ---------------------
553
554    procedure Expect_Internal
555      (Descriptors : in out Array_Of_Pd;
556       Result      : out Expect_Match;
557       Timeout     : Integer;
558       Full_Buffer : Boolean)
559    is
560       Num_Descriptors : Integer;
561       Buffer_Size     : Integer := 0;
562
563       N : Integer;
564
565       type File_Descriptor_Array is
566         array (Descriptors'Range) of File_Descriptor;
567       Fds : aliased File_Descriptor_Array;
568
569       type Integer_Array is array (Descriptors'Range) of Integer;
570       Is_Set : aliased Integer_Array;
571
572    begin
573       for J in Descriptors'Range loop
574          Fds (J) := Descriptors (J).Output_Fd;
575
576          if Descriptors (J).Buffer_Size = 0 then
577             Buffer_Size := Integer'Max (Buffer_Size, 4096);
578          else
579             Buffer_Size :=
580               Integer'Max (Buffer_Size, Descriptors (J).Buffer_Size);
581          end if;
582       end loop;
583
584       declare
585          Buffer : aliased String (1 .. Buffer_Size);
586          --  Buffer used for input. This is allocated only once, not for
587          --  every iteration of the loop
588
589       begin
590          --  Loop until we match or we have a timeout
591
592          loop
593             Num_Descriptors :=
594               Poll (Fds'Address, Fds'Length, Timeout, Is_Set'Address);
595
596             case Num_Descriptors is
597
598                --  Error?
599
600                when -1 =>
601                   raise Process_Died;
602
603                --  Timeout?
604
605                when 0  =>
606                   Result := Expect_Timeout;
607                   return;
608
609                --  Some input
610
611                when others =>
612                   for J in Descriptors'Range loop
613                      if Is_Set (J) = 1 then
614                         Buffer_Size := Descriptors (J).Buffer_Size;
615
616                         if Buffer_Size = 0 then
617                            Buffer_Size := 4096;
618                         end if;
619
620                         N := Read (Descriptors (J).Output_Fd, Buffer'Address,
621                                    Buffer_Size);
622
623                         --  Error or End of file
624
625                         if N <= 0 then
626                            --  ??? Note that ddd tries again up to three times
627                            --  in that case. See LiterateA.C:174
628                            raise Process_Died;
629
630                         else
631                            --  If there is no limit to the buffer size
632
633                            if Descriptors (J).Buffer_Size = 0 then
634
635                               declare
636                                  Tmp : String_Access := Descriptors (J).Buffer;
637
638                               begin
639                                  if Tmp /= null then
640                                     Descriptors (J).Buffer :=
641                                       new String (1 .. Tmp'Length + N);
642                                     Descriptors (J).Buffer (1 .. Tmp'Length) :=
643                                       Tmp.all;
644                                     Descriptors (J).Buffer
645                                       (Tmp'Length + 1 .. Tmp'Length + N) :=
646                                       Buffer (1 .. N);
647                                     Free (Tmp);
648                                     Descriptors (J).Buffer_Index :=
649                                       Descriptors (J).Buffer'Last;
650
651                                  else
652                                     Descriptors (J).Buffer :=
653                                       new String (1 .. N);
654                                     Descriptors (J).Buffer.all :=
655                                       Buffer (1 .. N);
656                                     Descriptors (J).Buffer_Index := N;
657                                  end if;
658                               end;
659
660                            else
661                               --  Add what we read to the buffer
662
663                               if Descriptors (J).Buffer_Index + N - 1 >
664                                 Descriptors (J).Buffer_Size
665                               then
666                                  --  If the user wants to know when we have
667                                  --  read more than the buffer can contain.
668
669                                  if Full_Buffer then
670                                     Result := Expect_Full_Buffer;
671                                     return;
672                                  end if;
673
674                                  --  Keep as much as possible from the buffer,
675                                  --  and forget old characters.
676
677                                  Descriptors (J).Buffer
678                                    (1 .. Descriptors (J).Buffer_Size - N) :=
679                                   Descriptors (J).Buffer
680                                    (N - Descriptors (J).Buffer_Size +
681                                     Descriptors (J).Buffer_Index + 1 ..
682                                     Descriptors (J).Buffer_Index);
683                                  Descriptors (J).Buffer_Index :=
684                                    Descriptors (J).Buffer_Size - N;
685                               end if;
686
687                               --  Keep what we read in the buffer
688
689                               Descriptors (J).Buffer
690                                 (Descriptors (J).Buffer_Index + 1 ..
691                                  Descriptors (J).Buffer_Index + N) :=
692                                 Buffer (1 .. N);
693                               Descriptors (J).Buffer_Index :=
694                                 Descriptors (J).Buffer_Index + N;
695                            end if;
696
697                            --  Call each of the output filter with what we
698                            --  read.
699
700                            Call_Filters
701                              (Descriptors (J).all, Buffer (1 .. N), Output);
702
703                            Result := Expect_Match (N);
704                            return;
705                         end if;
706                      end if;
707                   end loop;
708             end case;
709          end loop;
710       end;
711    end Expect_Internal;
712
713    ----------------
714    -- Expect_Out --
715    ----------------
716
717    function Expect_Out (Descriptor : Process_Descriptor) return String is
718    begin
719       return Descriptor.Buffer (1 .. Descriptor.Last_Match_End);
720    end Expect_Out;
721
722    ----------------------
723    -- Expect_Out_Match --
724    ----------------------
725
726    function Expect_Out_Match (Descriptor : Process_Descriptor) return String is
727    begin
728       return Descriptor.Buffer
729         (Descriptor.Last_Match_Start .. Descriptor.Last_Match_End);
730    end Expect_Out_Match;
731
732    -----------
733    -- Flush --
734    -----------
735
736    procedure Flush
737      (Descriptor : in out Process_Descriptor;
738       Timeout    : Integer := 0)
739    is
740       Buffer_Size     : constant Integer := 8192;
741       Num_Descriptors : Integer;
742       N               : Integer;
743       Is_Set          : aliased Integer;
744       Buffer          : aliased String (1 .. Buffer_Size);
745
746    begin
747       --  Empty the current buffer
748
749       Descriptor.Last_Match_End := Descriptor.Buffer_Index;
750       Reinitialize_Buffer (Descriptor);
751
752       --  Read everything from the process to flush its output
753
754       loop
755          Num_Descriptors :=
756            Poll (Descriptor.Output_Fd'Address, 1, Timeout, Is_Set'Address);
757
758          case Num_Descriptors is
759
760             --  Error ?
761
762             when -1 =>
763                raise Process_Died;
764
765             --  Timeout => End of flush
766
767             when 0  =>
768                return;
769
770             --  Some input
771
772             when others =>
773                if Is_Set = 1 then
774                   N := Read (Descriptor.Output_Fd, Buffer'Address,
775                              Buffer_Size);
776
777                   if N = -1 then
778                      raise Process_Died;
779                   elsif N = 0 then
780                      return;
781                   end if;
782                end if;
783          end case;
784       end loop;
785    end Flush;
786
787    ------------------------
788    -- Get_Command_Output --
789    ------------------------
790
791    function Get_Command_Output
792      (Command    : String;
793       Arguments  : GNAT.OS_Lib.Argument_List;
794       Input      : String;
795       Status     : not null access Integer;
796       Err_To_Out : Boolean := False) return String
797    is
798       use GNAT.Expect;
799
800       Process : Process_Descriptor;
801
802       Output : String_Access := new String (1 .. 1024);
803       --  Buffer used to accumulate standard output from the launched
804       --  command, expanded as necessary during execution.
805
806       Last : Integer := 0;
807       --  Index of the last used character within Output
808
809    begin
810       Non_Blocking_Spawn
811         (Process, Command, Arguments, Err_To_Out => Err_To_Out);
812
813       if Input'Length > 0 then
814          Send (Process, Input);
815       end if;
816
817       GNAT.OS_Lib.Close (Get_Input_Fd (Process));
818
819       declare
820          Result : Expect_Match;
821          pragma Unreferenced (Result);
822
823       begin
824          --  This loop runs until the call to Expect raises Process_Died
825
826          loop
827             Expect (Process, Result, ".+");
828
829             declare
830                NOutput : String_Access;
831                S       : constant String := Expect_Out (Process);
832                pragma Assert (S'Length > 0);
833
834             begin
835                --  Expand buffer if we need more space. Note here that we add
836                --  S'Length to ensure that S will fit in the new buffer size.
837
838                if Last + S'Length > Output'Last then
839                   NOutput := new String (1 .. 2 * Output'Last + S'Length);
840                   NOutput (Output'Range) := Output.all;
841                   Free (Output);
842
843                   --  Here if current buffer size is OK
844
845                else
846                   NOutput := Output;
847                end if;
848
849                NOutput (Last + 1 .. Last + S'Length) := S;
850                Last := Last + S'Length;
851                Output := NOutput;
852             end;
853          end loop;
854
855       exception
856          when Process_Died =>
857             Close (Process, Status.all);
858       end;
859
860       if Last = 0 then
861          return "";
862       end if;
863
864       declare
865          S : constant String := Output (1 .. Last);
866       begin
867          Free (Output);
868          return S;
869       end;
870    end Get_Command_Output;
871
872    ------------------
873    -- Get_Error_Fd --
874    ------------------
875
876    function Get_Error_Fd
877      (Descriptor : Process_Descriptor) return GNAT.OS_Lib.File_Descriptor
878    is
879    begin
880       return Descriptor.Error_Fd;
881    end Get_Error_Fd;
882
883    ------------------
884    -- Get_Input_Fd --
885    ------------------
886
887    function Get_Input_Fd
888      (Descriptor : Process_Descriptor) return GNAT.OS_Lib.File_Descriptor
889    is
890    begin
891       return Descriptor.Input_Fd;
892    end Get_Input_Fd;
893
894    -------------------
895    -- Get_Output_Fd --
896    -------------------
897
898    function Get_Output_Fd
899      (Descriptor : Process_Descriptor) return GNAT.OS_Lib.File_Descriptor
900    is
901    begin
902       return Descriptor.Output_Fd;
903    end Get_Output_Fd;
904
905    -------------
906    -- Get_Pid --
907    -------------
908
909    function Get_Pid
910      (Descriptor : Process_Descriptor) return Process_Id
911    is
912    begin
913       return Descriptor.Pid;
914    end Get_Pid;
915
916    ---------------
917    -- Interrupt --
918    ---------------
919
920    procedure Interrupt (Descriptor : in out Process_Descriptor) is
921       SIGINT : constant := 2;
922    begin
923       Send_Signal (Descriptor, SIGINT);
924    end Interrupt;
925
926    ------------------
927    -- Lock_Filters --
928    ------------------
929
930    procedure Lock_Filters (Descriptor : in out Process_Descriptor) is
931    begin
932       Descriptor.Filters_Lock := Descriptor.Filters_Lock + 1;
933    end Lock_Filters;
934
935    ------------------------
936    -- Non_Blocking_Spawn --
937    ------------------------
938
939    procedure Non_Blocking_Spawn
940      (Descriptor  : out Process_Descriptor'Class;
941       Command     : String;
942       Args        : GNAT.OS_Lib.Argument_List;
943       Buffer_Size : Natural := 4096;
944       Err_To_Out  : Boolean := False)
945    is
946       function Fork return Process_Id;
947       pragma Import (C, Fork, "__gnat_expect_fork");
948       --  Starts a new process if possible. See the Unix command fork for more
949       --  information. On systems that do not support this capability (such as
950       --  Windows...), this command does nothing, and Fork will return
951       --  Null_Pid.
952
953       Pipe1, Pipe2, Pipe3 : aliased Pipe_Type;
954
955       Arg        : String_Access;
956       Arg_List   : String_List (1 .. Args'Length + 2);
957       C_Arg_List : aliased array (1 .. Args'Length + 2) of System.Address;
958
959       Command_With_Path : String_Access;
960
961    begin
962       --  Create the rest of the pipes
963
964       Set_Up_Communications
965         (Descriptor, Err_To_Out, Pipe1'Access, Pipe2'Access, Pipe3'Access);
966
967       Command_With_Path := Locate_Exec_On_Path (Command);
968
969       if Command_With_Path = null then
970          raise Invalid_Process;
971       end if;
972
973       --  Fork a new process
974
975       Descriptor.Pid := Fork;
976
977       --  Are we now in the child (or, for Windows, still in the common
978       --  process).
979
980       if Descriptor.Pid = Null_Pid then
981          --  Prepare an array of arguments to pass to C
982
983          Arg := new String (1 .. Command_With_Path'Length + 1);
984          Arg (1 .. Command_With_Path'Length) := Command_With_Path.all;
985          Arg (Arg'Last)        := ASCII.NUL;
986          Arg_List (1)          := Arg;
987
988          for J in Args'Range loop
989             Arg                     := new String (1 .. Args (J)'Length + 1);
990             Arg (1 .. Args (J)'Length)    := Args (J).all;
991             Arg (Arg'Last)                := ASCII.NUL;
992             Arg_List (J + 2 - Args'First) := Arg.all'Access;
993          end loop;
994
995          Arg_List (Arg_List'Last) := null;
996
997          --  Make sure all arguments are compatible with OS conventions
998
999          Normalize_Arguments (Arg_List);
1000
1001          --  Prepare low-level argument list from the normalized arguments
1002
1003          for K in Arg_List'Range loop
1004             if Arg_List (K) /= null then
1005                C_Arg_List (K) := Arg_List (K).all'Address;
1006             else
1007                C_Arg_List (K) := System.Null_Address;
1008             end if;
1009          end loop;
1010
1011          --  This does not return on Unix systems
1012
1013          Set_Up_Child_Communications
1014            (Descriptor, Pipe1, Pipe2, Pipe3, Command_With_Path.all,
1015             C_Arg_List'Address);
1016       end if;
1017
1018       Free (Command_With_Path);
1019
1020       --  Did we have an error when spawning the child ?
1021
1022       if Descriptor.Pid < Null_Pid then
1023          raise Invalid_Process;
1024       else
1025          --  We are now in the parent process
1026
1027          Set_Up_Parent_Communications (Descriptor, Pipe1, Pipe2, Pipe3);
1028       end if;
1029
1030       --  Create the buffer
1031
1032       Descriptor.Buffer_Size := Buffer_Size;
1033
1034       if Buffer_Size /= 0 then
1035          Descriptor.Buffer := new String (1 .. Positive (Buffer_Size));
1036       end if;
1037
1038       --  Initialize the filters
1039
1040       Descriptor.Filters := null;
1041    end Non_Blocking_Spawn;
1042
1043    -------------------------
1044    -- Reinitialize_Buffer --
1045    -------------------------
1046
1047    procedure Reinitialize_Buffer
1048      (Descriptor : in out Process_Descriptor'Class)
1049    is
1050    begin
1051       if Descriptor.Buffer_Size = 0 then
1052          declare
1053             Tmp : String_Access := Descriptor.Buffer;
1054
1055          begin
1056             Descriptor.Buffer :=
1057               new String
1058                 (1 .. Descriptor.Buffer_Index - Descriptor.Last_Match_End);
1059
1060             if Tmp /= null then
1061                Descriptor.Buffer.all := Tmp
1062                  (Descriptor.Last_Match_End + 1 .. Descriptor.Buffer_Index);
1063                Free (Tmp);
1064             end if;
1065          end;
1066
1067          Descriptor.Buffer_Index := Descriptor.Buffer'Last;
1068
1069       else
1070          Descriptor.Buffer
1071            (1 .. Descriptor.Buffer_Index - Descriptor.Last_Match_End) :=
1072              Descriptor.Buffer
1073                (Descriptor.Last_Match_End + 1 .. Descriptor.Buffer_Index);
1074
1075          if Descriptor.Buffer_Index > Descriptor.Last_Match_End then
1076             Descriptor.Buffer_Index :=
1077               Descriptor.Buffer_Index - Descriptor.Last_Match_End;
1078          else
1079             Descriptor.Buffer_Index := 0;
1080          end if;
1081       end if;
1082
1083       Descriptor.Last_Match_Start := 0;
1084       Descriptor.Last_Match_End := 0;
1085    end Reinitialize_Buffer;
1086
1087    -------------------
1088    -- Remove_Filter --
1089    -------------------
1090
1091    procedure Remove_Filter
1092      (Descriptor : in out Process_Descriptor;
1093       Filter     : Filter_Function)
1094    is
1095       Previous : Filter_List := null;
1096       Current  : Filter_List := Descriptor.Filters;
1097
1098    begin
1099       while Current /= null loop
1100          if Current.Filter = Filter then
1101             if Previous = null then
1102                Descriptor.Filters := Current.Next;
1103             else
1104                Previous.Next := Current.Next;
1105             end if;
1106          end if;
1107
1108          Previous := Current;
1109          Current := Current.Next;
1110       end loop;
1111    end Remove_Filter;
1112
1113    ----------
1114    -- Send --
1115    ----------
1116
1117    procedure Send
1118      (Descriptor   : in out Process_Descriptor;
1119       Str          : String;
1120       Add_LF       : Boolean := True;
1121       Empty_Buffer : Boolean := False)
1122    is
1123       Line_Feed   : aliased constant String := (1 .. 1 => ASCII.LF);
1124       Descriptors : Array_Of_Pd := (1 => Descriptor'Unrestricted_Access);
1125
1126       Result  : Expect_Match;
1127       Discard : Natural;
1128       pragma Warnings (Off, Result);
1129       pragma Warnings (Off, Discard);
1130
1131    begin
1132       if Empty_Buffer then
1133
1134          --  Force a read on the process if there is anything waiting
1135
1136          Expect_Internal
1137            (Descriptors, Result, Timeout => 0, Full_Buffer => False);
1138          Descriptor.Last_Match_End := Descriptor.Buffer_Index;
1139
1140          --  Empty the buffer
1141
1142          Reinitialize_Buffer (Descriptor);
1143       end if;
1144
1145       Call_Filters (Descriptor, Str, Input);
1146       Discard :=
1147         Write (Descriptor.Input_Fd, Str'Address, Str'Last - Str'First + 1);
1148
1149       if Add_LF then
1150          Call_Filters (Descriptor, Line_Feed, Input);
1151          Discard :=
1152            Write (Descriptor.Input_Fd, Line_Feed'Address, 1);
1153       end if;
1154    end Send;
1155
1156    -----------------
1157    -- Send_Signal --
1158    -----------------
1159
1160    procedure Send_Signal
1161      (Descriptor : Process_Descriptor;
1162       Signal     : Integer)
1163    is
1164    begin
1165       --  A nonpositive process id passed to kill has special meanings. For
1166       --  example, -1 means kill all processes in sight, including self, in
1167       --  POSIX and Windows (and something slightly different in Linux). See
1168       --  man pages for details. In any case, we don't want to do that. Note
1169       --  that Descriptor.Pid will be -1 if the process was not successfully
1170       --  started; we don't want to kill ourself in that case.
1171
1172       if Descriptor.Pid > 0 then
1173          Kill (Descriptor.Pid, Signal, Close => 1);
1174          --  ??? Need to check process status here
1175       else
1176          raise Invalid_Process;
1177       end if;
1178    end Send_Signal;
1179
1180    ---------------------------------
1181    -- Set_Up_Child_Communications --
1182    ---------------------------------
1183
1184    procedure Set_Up_Child_Communications
1185      (Pid   : in out Process_Descriptor;
1186       Pipe1 : in out Pipe_Type;
1187       Pipe2 : in out Pipe_Type;
1188       Pipe3 : in out Pipe_Type;
1189       Cmd   : String;
1190       Args  : System.Address)
1191    is
1192       pragma Warnings (Off, Pid);
1193
1194       Input  : File_Descriptor;
1195       Output : File_Descriptor;
1196       Error  : File_Descriptor;
1197
1198    begin
1199       --  Since Windows does not have a separate fork/exec, we need to
1200       --  perform the following actions:
1201       --    - save stdin, stdout, stderr
1202       --    - replace them by our pipes
1203       --    - create the child with process handle inheritance
1204       --    - revert to the previous stdin, stdout and stderr.
1205
1206       Input  := Dup (GNAT.OS_Lib.Standin);
1207       Output := Dup (GNAT.OS_Lib.Standout);
1208       Error  := Dup (GNAT.OS_Lib.Standerr);
1209
1210       --  Since we are still called from the parent process, there is no way
1211       --  currently we can cleanly close the unneeded ends of the pipes, but
1212       --  this doesn't really matter.
1213       --  We could close Pipe1.Output, Pipe2.Input, Pipe3.Input.
1214
1215       Dup2 (Pipe1.Input,  GNAT.OS_Lib.Standin);
1216       Dup2 (Pipe2.Output, GNAT.OS_Lib.Standout);
1217       Dup2 (Pipe3.Output, GNAT.OS_Lib.Standerr);
1218
1219       Portable_Execvp (Pid.Pid'Access, Cmd & ASCII.Nul, Args);
1220
1221       --  The following commands are not executed on Unix systems, and are
1222       --  only required for Windows systems. We are now in the parent process.
1223
1224       --  Restore the old descriptors
1225
1226       Dup2 (Input,  GNAT.OS_Lib.Standin);
1227       Dup2 (Output, GNAT.OS_Lib.Standout);
1228       Dup2 (Error,  GNAT.OS_Lib.Standerr);
1229       Close (Input);
1230       Close (Output);
1231       Close (Error);
1232    end Set_Up_Child_Communications;
1233
1234    ---------------------------
1235    -- Set_Up_Communications --
1236    ---------------------------
1237
1238    procedure Set_Up_Communications
1239      (Pid        : in out Process_Descriptor;
1240       Err_To_Out : Boolean;
1241       Pipe1      : not null access Pipe_Type;
1242       Pipe2      : not null access Pipe_Type;
1243       Pipe3      : not null access Pipe_Type)
1244    is
1245       Status : Boolean;
1246       pragma Unreferenced (Status);
1247
1248    begin
1249       --  Create the pipes
1250
1251       if Create_Pipe (Pipe1) /= 0 then
1252          return;
1253       end if;
1254
1255       if Create_Pipe (Pipe2) /= 0 then
1256          return;
1257       end if;
1258
1259       --  Record the 'parent' end of the two pipes in Pid:
1260       --    Child stdin  is connected to the 'write' end of Pipe1;
1261       --    Child stdout is connected to the 'read'  end of Pipe2.
1262       --  We do not want these descriptors to remain open in the child
1263       --  process, so we mark them close-on-exec/non-inheritable.
1264
1265       Pid.Input_Fd  := Pipe1.Output;
1266       Set_Close_On_Exec (Pipe1.Output, True, Status);
1267       Pid.Output_Fd := Pipe2.Input;
1268       Set_Close_On_Exec (Pipe2.Input, True, Status);
1269
1270       if Err_To_Out then
1271
1272          --  Reuse the standard output pipe for standard error
1273
1274          Pipe3.all := Pipe2.all;
1275       else
1276
1277          --  Create a separate pipe for standard error
1278
1279          if Create_Pipe (Pipe3) /= 0 then
1280             return;
1281          end if;
1282       end if;
1283
1284       --  As above, record the proper fd for the child's standard error stream
1285
1286       Pid.Error_Fd := Pipe3.Input;
1287       Set_Close_On_Exec (Pipe3.Input, True, Status);
1288    end Set_Up_Communications;
1289
1290    ----------------------------------
1291    -- Set_Up_Parent_Communications --
1292    ----------------------------------
1293
1294    procedure Set_Up_Parent_Communications
1295      (Pid   : in out Process_Descriptor;
1296       Pipe1 : in out Pipe_Type;
1297       Pipe2 : in out Pipe_Type;
1298       Pipe3 : in out Pipe_Type)
1299    is
1300       pragma Warnings (Off, Pid);
1301    begin
1302       Close (Pipe1.Input);
1303       Close (Pipe2.Output);
1304       Close (Pipe3.Output);
1305    end Set_Up_Parent_Communications;
1306
1307    ------------------
1308    -- Trace_Filter --
1309    ------------------
1310
1311    procedure Trace_Filter
1312      (Descriptor : Process_Descriptor'Class;
1313       Str        : String;
1314       User_Data  : System.Address := System.Null_Address)
1315    is
1316       pragma Warnings (Off, Descriptor);
1317       pragma Warnings (Off, User_Data);
1318    begin
1319       GNAT.IO.Put (Str);
1320    end Trace_Filter;
1321
1322    --------------------
1323    -- Unlock_Filters --
1324    --------------------
1325
1326    procedure Unlock_Filters (Descriptor : in out Process_Descriptor) is
1327    begin
1328       if Descriptor.Filters_Lock > 0 then
1329          Descriptor.Filters_Lock := Descriptor.Filters_Lock - 1;
1330       end if;
1331    end Unlock_Filters;
1332
1333 end GNAT.Expect;