1 ------------------------------------------------------------------------------
3 -- GNAT LIBRARY COMPONENTS --
5 -- G N A T . E X P E C T --
9 -- Copyright (C) 2000-2010, 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 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. --
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. --
29 -- GNAT was originally developed by the GNAT team at New York University. --
30 -- Extensive contributions were provided by Ada Core Technologies Inc. --
32 ------------------------------------------------------------------------------
34 -- Currently this package is implemented on all native GNAT ports except
35 -- for VMS. It is not yet implemented for any of the cross-ports (e.g. it
36 -- is not available for VxWorks or LynxOS).
42 -- This package provides a set of subprograms similar to what is available
43 -- with the standard Tcl Expect tool.
45 -- It allows you to easily spawn and communicate with an external process.
46 -- You can send commands or inputs to the process, and compare the output
47 -- with some expected regular expression.
53 -- (1 => new String' ("machine@domain")));
54 -- Timeout := 10_000; -- 10 seconds
55 -- Expect (Fd, Result, Regexp_Array'(+"\(user\)", +"\(passwd\)"),
58 -- when 1 => Send (Fd, "my_name"); -- matched "user"
59 -- when 2 => Send (Fd, "my_passwd"); -- matched "passwd"
60 -- when Expect_Timeout => null; -- timeout
61 -- when others => null;
65 -- You can also combine multiple regular expressions together, and get the
66 -- specific string matching a parenthesis pair by doing something like this:
67 -- If you expect either "lang=optional ada" or "lang=ada" from the external
68 -- process, you can group the two together, which is more efficient, and
69 -- simply get the name of the language by doing:
72 -- Matched : Match_Array (0 .. 2);
74 -- Expect (Fd, Result, "lang=(optional)? ([a-z]+)", Matched);
75 -- Put_Line ("Seen: " &
76 -- Expect_Out (Fd) (Matched (2).First .. Matched (2).Last));
79 -- Alternatively, you might choose to use a lower-level interface to the
80 -- processes, where you can give your own input and output filters every
81 -- time characters are read from or written to the process.
83 -- procedure My_Filter
84 -- (Descriptor : Process_Descriptor'Class;
86 -- User_Data : System.Address)
94 -- (new String' ("-f"), new String' ("a_file")));
95 -- Add_Filter (Fd, My_Filter'Access, Output);
96 -- Expect (Fd, Result, "", 0); -- wait forever
98 -- The above example should probably be run in a separate task, since it is
99 -- blocking on the call to Expect.
101 -- Both examples can be combined, for instance to systematically print the
102 -- output seen by expect, even though you still want to let Expect do the
103 -- filtering. You can use the Trace_Filter subprogram for such a filter.
105 -- If you want to get the output of a simple command, and ignore any previous
106 -- existing output, it is recommended to do something like:
108 -- Expect (Fd, Result, ".*", Timeout => 0);
109 -- -- Empty the buffer, by matching everything (after checking
110 -- -- if there was any input).
112 -- Send (Fd, "command");
113 -- Expect (Fd, Result, ".."); -- match only on the output of command
119 -- This package is not task-safe: there should not be concurrent calls to the
120 -- functions defined in this package. In other words, separate tasks must not
121 -- access the facilities of this package without synchronization that
122 -- serializes access.
128 package GNAT
.Expect
is
130 type Process_Id
is new Integer;
131 Invalid_Pid
: constant Process_Id
:= -1;
132 Null_Pid
: constant Process_Id
:= 0;
134 type Filter_Type
is (Output
, Input
, Died
);
135 -- The signals that are emitted by the Process_Descriptor upon state change
136 -- in the child. One can connect to any of these signals through the
137 -- Add_Filter subprograms.
139 -- Output => Every time new characters are read from the process
140 -- associated with Descriptor, the filter is called with
141 -- these new characters in the argument.
143 -- Note that output is generated only when the program is
144 -- blocked in a call to Expect.
146 -- Input => Every time new characters are written to the process
147 -- associated with Descriptor, the filter is called with
148 -- these new characters in the argument.
149 -- Note that input is generated only by calls to Send.
151 -- Died => The child process has died, or was explicitly killed
153 type Process_Descriptor
is tagged private;
154 -- Contains all the components needed to describe a process handled
155 -- in this package, including a process identifier, file descriptors
156 -- associated with the standard input, output and error, and the buffer
157 -- needed to handle the expect calls.
159 type Process_Descriptor_Access
is access Process_Descriptor
'Class;
161 ------------------------
162 -- Spawning a process --
163 ------------------------
165 procedure Non_Blocking_Spawn
166 (Descriptor
: out Process_Descriptor
'Class;
168 Args
: GNAT
.OS_Lib
.Argument_List
;
169 Buffer_Size
: Natural := 4096;
170 Err_To_Out
: Boolean := False);
171 -- This call spawns a new process and allows sending commands to
172 -- the process and/or automatic parsing of the output.
174 -- The expect buffer associated with that process can contain at most
175 -- Buffer_Size characters. Older characters are simply discarded when this
176 -- buffer is full. Beware that if the buffer is too big, this could slow
177 -- down the Expect calls if the output not is matched, since Expect has to
178 -- match all the regexp against all the characters in the buffer. If
179 -- Buffer_Size is 0, there is no limit (i.e. all the characters are kept
180 -- till Expect matches), but this is slower.
182 -- If Err_To_Out is True, then the standard error of the spawned process is
183 -- connected to the standard output. This is the only way to get the Except
184 -- subprograms to also match on output on standard error.
186 -- Invalid_Process is raised if the process could not be spawned.
188 -- For information about spawning processes from tasking programs, see the
189 -- "NOTE: Spawn in tasking programs" in System.OS_Lib (s-os_lib.ads).
191 procedure Close
(Descriptor
: in out Process_Descriptor
);
192 -- Terminate the process and close the pipes to it. It implicitly does the
193 -- 'wait' command required to clean up the process table. This also frees
194 -- the buffer associated with the process id. Raise Invalid_Process if the
195 -- process id is invalid.
198 (Descriptor
: in out Process_Descriptor
;
199 Status
: out Integer);
200 -- Same as above, but also returns the exit status of the process, as set
201 -- for example by the procedure GNAT.OS_Lib.OS_Exit.
203 procedure Send_Signal
204 (Descriptor
: Process_Descriptor
;
206 -- Send a given signal to the process. Raise Invalid_Process if the process
209 procedure Interrupt
(Descriptor
: in out Process_Descriptor
);
210 -- Interrupt the process (the equivalent of Ctrl-C on unix and windows)
211 -- and call close if the process dies.
213 function Get_Input_Fd
214 (Descriptor
: Process_Descriptor
) return GNAT
.OS_Lib
.File_Descriptor
;
215 -- Return the input file descriptor associated with Descriptor
217 function Get_Output_Fd
218 (Descriptor
: Process_Descriptor
) return GNAT
.OS_Lib
.File_Descriptor
;
219 -- Return the output file descriptor associated with Descriptor
221 function Get_Error_Fd
222 (Descriptor
: Process_Descriptor
) return GNAT
.OS_Lib
.File_Descriptor
;
223 -- Return the error output file descriptor associated with Descriptor
226 (Descriptor
: Process_Descriptor
) return Process_Id
;
227 -- Return the process id associated with a given process descriptor
229 function Get_Command_Output
231 Arguments
: GNAT
.OS_Lib
.Argument_List
;
233 Status
: not null access Integer;
234 Err_To_Out
: Boolean := False) return String;
235 -- Execute Command with the specified Arguments and Input, and return the
236 -- generated standard output data as a single string. If Err_To_Out is
237 -- True, generated standard error output is included as well. On return,
238 -- Status is set to the command's exit status.
244 -- This is a rather low-level interface to subprocesses, since basically
245 -- the filtering is left entirely to the user. See the Expect subprograms
246 -- below for higher level functions.
248 type Filter_Function
is access
250 (Descriptor
: Process_Descriptor
'Class;
252 User_Data
: System
.Address
:= System
.Null_Address
);
253 -- Function called every time new characters are read from or written to
256 -- Str is a string of all these characters.
258 -- User_Data, if specified, is user specific data that will be passed to
259 -- the filter. Note that no checks are done on this parameter, so it should
260 -- be used with caution.
263 (Descriptor
: in out Process_Descriptor
;
264 Filter
: Filter_Function
;
265 Filter_On
: Filter_Type
:= Output
;
266 User_Data
: System
.Address
:= System
.Null_Address
;
267 After
: Boolean := False);
268 -- Add a new filter for one of the filter types. This filter will be run
269 -- before all the existing filters, unless After is set True, in which case
270 -- it will be run after existing filters. User_Data is passed as is to the
273 procedure Remove_Filter
274 (Descriptor
: in out Process_Descriptor
;
275 Filter
: Filter_Function
);
276 -- Remove a filter from the list of filters (whatever the type of the
279 procedure Trace_Filter
280 (Descriptor
: Process_Descriptor
'Class;
282 User_Data
: System
.Address
:= System
.Null_Address
);
283 -- Function that can be used as a filter and that simply outputs Str on
284 -- Standard_Output. This is mainly used for debugging purposes.
285 -- User_Data is ignored.
287 procedure Lock_Filters
(Descriptor
: in out Process_Descriptor
);
288 -- Temporarily disables all output and input filters. They will be
289 -- reactivated only when Unlock_Filters has been called as many times as
292 procedure Unlock_Filters
(Descriptor
: in out Process_Descriptor
);
293 -- Unlocks the filters. They are reactivated only if Unlock_Filters
294 -- has been called as many times as Lock_Filters.
301 (Descriptor
: in out Process_Descriptor
;
303 Add_LF
: Boolean := True;
304 Empty_Buffer
: Boolean := False);
305 -- Send a string to the file descriptor.
307 -- The string is not formatted in any way, except if Add_LF is True, in
308 -- which case an ASCII.LF is added at the end, so that Str is recognized
309 -- as a command by the external process.
311 -- If Empty_Buffer is True, any input waiting from the process (or in the
312 -- buffer) is first discarded before the command is sent. The output
313 -- filters are of course called as usual.
315 -----------------------------------------------------------
316 -- Working on the output (single process, simple regexp) --
317 -----------------------------------------------------------
319 type Expect_Match
is new Integer;
320 Expect_Full_Buffer
: constant Expect_Match
:= -1;
321 -- If the buffer was full and some characters were discarded
323 Expect_Timeout
: constant Expect_Match
:= -2;
324 -- If no output matching the regexps was found before the timeout
326 function "+" (S
: String) return GNAT
.OS_Lib
.String_Access
;
327 -- Allocate some memory for the string. This is merely a convenience
328 -- function to help create the array of regexps in the call to Expect.
331 (Descriptor
: in out Process_Descriptor
;
332 Result
: out Expect_Match
;
334 Timeout
: Integer := 10_000
;
335 Full_Buffer
: Boolean := False);
336 -- Wait till a string matching Fd can be read from Fd, and return 1 if a
339 -- It consumes all the characters read from Fd until a match found, and
340 -- then sets the return values for the subprograms Expect_Out and
343 -- The empty string "" will never match, and can be used if you only want
344 -- to match after a specific timeout. Beware that if Timeout is -1 at the
345 -- time, the current task will be blocked forever.
347 -- This command times out after Timeout milliseconds (or never if Timeout
348 -- is -1). In that case, Expect_Timeout is returned. The value returned by
349 -- Expect_Out and Expect_Out_Match are meaningless in that case.
351 -- Note that using a timeout of 0ms leads to unpredictable behavior, since
352 -- the result depends on whether the process has already sent some output
353 -- the first time Expect checks, and this depends on the operating system.
355 -- The regular expression must obey the syntax described in GNAT.Regpat.
357 -- If Full_Buffer is True, then Expect will match if the buffer was too
358 -- small and some characters were about to be discarded. In that case,
359 -- Expect_Full_Buffer is returned.
362 (Descriptor
: in out Process_Descriptor
;
363 Result
: out Expect_Match
;
364 Regexp
: GNAT
.Regpat
.Pattern_Matcher
;
365 Timeout
: Integer := 10_000
;
366 Full_Buffer
: Boolean := False);
367 -- Same as the previous one, but with a precompiled regular expression.
368 -- This is more efficient however, especially if you are using this
369 -- expression multiple times, since this package won't need to recompile
370 -- the regexp every time.
373 (Descriptor
: in out Process_Descriptor
;
374 Result
: out Expect_Match
;
376 Matched
: out GNAT
.Regpat
.Match_Array
;
377 Timeout
: Integer := 10_000
;
378 Full_Buffer
: Boolean := False);
379 -- Same as above, but it is now possible to get the indexes of the
380 -- substrings for the parentheses in the regexp (see the example at the
381 -- top of this package, as well as the documentation in the package
384 -- Matched'First should be 0, and this index will contain the indexes for
385 -- the whole string that was matched. The index 1 will contain the indexes
386 -- for the first parentheses-pair, and so on.
393 (Descriptor
: in out Process_Descriptor
;
394 Result
: out Expect_Match
;
395 Regexp
: GNAT
.Regpat
.Pattern_Matcher
;
396 Matched
: out GNAT
.Regpat
.Match_Array
;
397 Timeout
: Integer := 10_000
;
398 Full_Buffer
: Boolean := False);
399 -- Same as above, but with a precompiled regular expression
401 -------------------------------------------------------------
402 -- Working on the output (single process, multiple regexp) --
403 -------------------------------------------------------------
405 type Regexp_Array
is array (Positive range <>) of GNAT
.OS_Lib
.String_Access
;
407 type Pattern_Matcher_Access
is access all GNAT
.Regpat
.Pattern_Matcher
;
408 type Compiled_Regexp_Array
is
409 array (Positive range <>) of Pattern_Matcher_Access
;
412 (P
: GNAT
.Regpat
.Pattern_Matcher
) return Pattern_Matcher_Access
;
413 -- Allocate some memory for the pattern matcher. This is only a convenience
414 -- function to help create the array of compiled regular expressions.
417 (Descriptor
: in out Process_Descriptor
;
418 Result
: out Expect_Match
;
419 Regexps
: Regexp_Array
;
420 Timeout
: Integer := 10_000
;
421 Full_Buffer
: Boolean := False);
422 -- Wait till a string matching one of the regular expressions in Regexps
423 -- is found. This function returns the index of the regexp that matched.
424 -- This command is blocking, but will timeout after Timeout milliseconds.
425 -- In that case, Timeout is returned.
428 (Descriptor
: in out Process_Descriptor
;
429 Result
: out Expect_Match
;
430 Regexps
: Compiled_Regexp_Array
;
431 Timeout
: Integer := 10_000
;
432 Full_Buffer
: Boolean := False);
433 -- Same as the previous one, but with precompiled regular expressions.
434 -- This can be much faster if you are using them multiple times.
437 (Descriptor
: in out Process_Descriptor
;
438 Result
: out Expect_Match
;
439 Regexps
: Regexp_Array
;
440 Matched
: out GNAT
.Regpat
.Match_Array
;
441 Timeout
: Integer := 10_000
;
442 Full_Buffer
: Boolean := False);
443 -- Same as above, except that you can also access the parenthesis
444 -- groups inside the matching regular expression.
446 -- The first index in Matched must be 0, or Constraint_Error will be
447 -- raised. The index 0 contains the indexes for the whole string that was
448 -- matched, the index 1 contains the indexes for the first parentheses
452 (Descriptor
: in out Process_Descriptor
;
453 Result
: out Expect_Match
;
454 Regexps
: Compiled_Regexp_Array
;
455 Matched
: out GNAT
.Regpat
.Match_Array
;
456 Timeout
: Integer := 10_000
;
457 Full_Buffer
: Boolean := False);
458 -- Same as above, but with precompiled regular expressions. The first index
459 -- in Matched must be 0, or Constraint_Error will be raised.
461 -------------------------------------------
462 -- Working on the output (multi-process) --
463 -------------------------------------------
465 type Multiprocess_Regexp
is record
466 Descriptor
: Process_Descriptor_Access
;
467 Regexp
: Pattern_Matcher_Access
;
470 type Multiprocess_Regexp_Array
is
471 array (Positive range <>) of Multiprocess_Regexp
;
473 procedure Free
(Regexp
: in out Multiprocess_Regexp
);
474 -- Free the memory occupied by Regexp
476 function Has_Process
(Regexp
: Multiprocess_Regexp_Array
) return Boolean;
477 -- Return True if at least one entry in Regexp is non-null, ie there is
478 -- still at least one process to monitor
480 function First_Dead_Process
481 (Regexp
: Multiprocess_Regexp_Array
) return Natural;
482 -- Find the first entry in Regexp that corresponds to a dead process that
483 -- wasn't Free-d yet. This function is called in general when Expect
484 -- (below) raises the exception Process_Died. This returns 0 if no process
488 (Result
: out Expect_Match
;
489 Regexps
: Multiprocess_Regexp_Array
;
490 Matched
: out GNAT
.Regpat
.Match_Array
;
491 Timeout
: Integer := 10_000
;
492 Full_Buffer
: Boolean := False);
493 -- Same as above, but for multi processes. Any of the entries in
494 -- Regexps can have a null Descriptor or Regexp. Such entries will
495 -- simply be ignored. Therefore when a process terminates, you can
496 -- simply reset its entry.
498 -- The expect loop would therefore look like:
500 -- Processes : Multiprocess_Regexp_Array (...) := ...;
503 -- while Has_Process (Processes) loop
505 -- Expect (Result, Processes, Timeout => -1);
506 -- ... process output of process Result (output, full buffer,...)
509 -- when Process_Died =>
511 -- R := First_Dead_Process (Processes);
512 -- Close (Processes (R).Descriptor.all, Status);
513 -- Free (Processes (R));
518 (Result
: out Expect_Match
;
519 Regexps
: Multiprocess_Regexp_Array
;
520 Timeout
: Integer := 10_000
;
521 Full_Buffer
: Boolean := False);
522 -- Same as the previous one, but for multiple processes. This procedure
523 -- finds the first regexp that match the associated process.
525 ------------------------
526 -- Getting the output --
527 ------------------------
530 (Descriptor
: in out Process_Descriptor
;
531 Timeout
: Integer := 0);
532 -- Discard all output waiting from the process.
534 -- This output is simply discarded, and no filter is called. This output
535 -- will also not be visible by the next call to Expect, nor will any output
536 -- currently buffered.
538 -- Timeout is the delay for which we wait for output to be available from
539 -- the process. If 0, we only get what is immediately available.
541 function Expect_Out
(Descriptor
: Process_Descriptor
) return String;
542 -- Return the string matched by the last Expect call.
544 -- The returned string is in fact the concatenation of all the strings read
545 -- from the file descriptor up to, and including, the characters that
546 -- matched the regular expression.
548 -- For instance, with an input "philosophic", and a regular expression "hi"
549 -- in the call to expect, the strings returned the first and second time
550 -- would be respectively "phi" and "losophi".
552 function Expect_Out_Match
(Descriptor
: Process_Descriptor
) return String;
553 -- Return the string matched by the last Expect call.
555 -- The returned string includes only the character that matched the
556 -- specific regular expression. All the characters that came before are
559 -- For instance, with an input "philosophic", and a regular expression
560 -- "hi" in the call to expect, the strings returned the first and second
561 -- time would both be "hi".
567 Invalid_Process
: exception;
568 -- Raised by most subprograms above when the parameter Descriptor is not a
569 -- valid process or is a closed process.
571 Process_Died
: exception;
572 -- Raised by all the expect subprograms if Descriptor was originally a
573 -- valid process that died while Expect was executing. It is also raised
574 -- when Expect receives an end-of-file.
577 type Filter_List_Elem
;
578 type Filter_List
is access Filter_List_Elem
;
579 type Filter_List_Elem
is record
580 Filter
: Filter_Function
;
581 User_Data
: System
.Address
;
582 Filter_On
: Filter_Type
;
586 type Pipe_Type
is record
587 Input
, Output
: GNAT
.OS_Lib
.File_Descriptor
;
589 -- This type represents a pipe, used to communicate between two processes
591 procedure Set_Up_Communications
592 (Pid
: in out Process_Descriptor
;
593 Err_To_Out
: Boolean;
594 Pipe1
: not null access Pipe_Type
;
595 Pipe2
: not null access Pipe_Type
;
596 Pipe3
: not null access Pipe_Type
);
597 -- Set up all the communication pipes and file descriptors prior to
598 -- spawning the child process.
600 procedure Set_Up_Parent_Communications
601 (Pid
: in out Process_Descriptor
;
602 Pipe1
: in out Pipe_Type
;
603 Pipe2
: in out Pipe_Type
;
604 Pipe3
: in out Pipe_Type
);
605 -- Finish the set up of the pipes while in the parent process
607 procedure Set_Up_Child_Communications
608 (Pid
: in out Process_Descriptor
;
609 Pipe1
: in out Pipe_Type
;
610 Pipe2
: in out Pipe_Type
;
611 Pipe3
: in out Pipe_Type
;
613 Args
: System
.Address
);
614 -- Finish the set up of the pipes while in the child process This also
615 -- spawns the child process (based on Cmd). On systems that support fork,
616 -- this procedure is executed inside the newly created process.
618 type Process_Descriptor
is tagged record
619 Pid
: aliased Process_Id
:= Invalid_Pid
;
620 Input_Fd
: GNAT
.OS_Lib
.File_Descriptor
:= GNAT
.OS_Lib
.Invalid_FD
;
621 Output_Fd
: GNAT
.OS_Lib
.File_Descriptor
:= GNAT
.OS_Lib
.Invalid_FD
;
622 Error_Fd
: GNAT
.OS_Lib
.File_Descriptor
:= GNAT
.OS_Lib
.Invalid_FD
;
623 Filters_Lock
: Integer := 0;
625 Filters
: Filter_List
:= null;
627 Buffer
: GNAT
.OS_Lib
.String_Access
:= null;
628 Buffer_Size
: Natural := 0;
629 Buffer_Index
: Natural := 0;
631 Last_Match_Start
: Natural := 0;
632 Last_Match_End
: Natural := 0;
635 -- The following subprogram is provided for use in the body, and also
636 -- possibly in future child units providing extensions to this package.
638 procedure Portable_Execvp
639 (Pid
: not null access Process_Id
;
641 Args
: System
.Address
);
642 pragma Import
(C
, Portable_Execvp
, "__gnat_expect_portable_execvp");
643 -- Executes, in a portable way, the command Cmd (full path must be
644 -- specified), with the given Args, which must be an array of string
645 -- pointers. Note that the first element in Args must be the executable
646 -- name, and the last element must be a null pointer. The returned value
647 -- in Pid is the process ID, or zero if not supported on the platform.