* MAINTAINERS: (Write After Approval): Add myself.
[official-gcc.git] / gcc / ada / g-expect.ads
blob36490288aff38c08fbc525f826f80695ce4c2a41
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT LIBRARY COMPONENTS --
4 -- --
5 -- G N A T . E X P E C T --
6 -- --
7 -- S p e c --
8 -- --
9 -- --
10 -- Copyright (C) 2000-2002 Ada Core Technologies, Inc. --
11 -- --
12 -- GNAT is free software; you can redistribute it and/or modify it under --
13 -- terms of the GNU General Public License as published by the Free Soft- --
14 -- ware Foundation; either version 2, or (at your option) any later ver- --
15 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
16 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
17 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
18 -- for more details. You should have received a copy of the GNU General --
19 -- Public License distributed with GNAT; see file COPYING. If not, write --
20 -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
21 -- MA 02111-1307, USA. --
22 -- --
23 -- As a special exception, if other files instantiate generics from this --
24 -- unit, or you link this unit with other files to produce an executable, --
25 -- this unit does not by itself cause the resulting executable to be --
26 -- covered by the GNU General Public License. This exception does not --
27 -- however invalidate any other reasons why the executable file might be --
28 -- covered by the GNU Public License. --
29 -- --
30 -- GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com). --
31 -- --
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).
38 -- Usage
39 -- =====
41 -- This package provides a set of subprograms similar to what is available
42 -- with the standard Tcl Expect tool.
44 -- It allows you to easily spawn and communicate with an external process.
45 -- You can send commands or inputs to the process, and compare the output
46 -- with some expected regular expression.
48 -- Usage example:
50 -- Non_Blocking_Spawn
51 -- (Fd, "ftp",
52 -- (1 => new String' ("machine@domaine")));
53 -- Timeout := 10000; -- 10 seconds
54 -- Expect (Fd, Result, Regexp_Array'(+"\(user\)", +"\(passwd\)"),
55 -- Timeout);
56 -- case Result is
57 -- when 1 => Send (Fd, "my_name"); -- matched "user"
58 -- when 2 => Send (Fd, "my_passwd"); -- matched "passwd"
59 -- when Expect_Timeout => null; -- timeout
60 -- when others => null;
61 -- end case;
62 -- Close (Fd);
64 -- You can also combine multiple regular expressions together, and get the
65 -- specific string matching a parenthesis pair by doing something like. If you
66 -- expect either "lang=optional ada" or "lang=ada" from the external process,
67 -- you can group the two together, which is more efficient, and simply get the
68 -- name of the language by doing:
70 -- declare
71 -- Matched : Regexp_Array (0 .. 2);
72 -- begin
73 -- Expect (Fd, Result, "lang=(optional)? ([a-z]+)", Matched);
74 -- Put_Line ("Seen: " &
75 -- Expect_Out (Fd) (Matched (2).First .. Matched (2).Last));
76 -- end;
78 -- Alternatively, you might choose to use a lower-level interface to the
79 -- processes, where you can give your own input and output filters every
80 -- time characters are read from or written to the process.
82 -- procedure My_Filter
83 -- (Descriptor : Process_Descriptor'Class;
84 -- Str : String;
85 -- User_Data : System.Address)
86 -- is
87 -- begin
88 -- Put_Line (Str);
89 -- end;
91 -- Non_Blocking_Spawn
92 -- (Fd, "tail",
93 -- (new String' ("-f"), new String' ("a_file")));
94 -- Add_Filter (Fd, My_Filter'Access, Output);
95 -- Expect (Fd, Result, "", 0); -- wait forever
97 -- The above example should probably be run in a separate task, since it is
98 -- blocking on the call to Expect.
100 -- Both examples can be combined, for instance to systematically print the
101 -- output seen by expect, even though you still want to let Expect do the
102 -- filtering. You can use the Trace_Filter subprogram for such a filter.
104 -- If you want to get the output of a simple command, and ignore any previous
105 -- existing output, it is recommended to do something like:
107 -- Expect (Fd, Result, ".*", Timeout => 0);
108 -- -- Empty the buffer, by matching everything (after checking
109 -- -- if there was any input).
111 -- Send (Fd, "command");
112 -- Expect (Fd, Result, ".."); -- match only on the output of command
114 -- Task Safety
115 -- ===========
117 -- This package is not task-safe. However, you can easily make is task safe
118 -- by encapsulating the type Process_Descriptor in a protected record.
119 -- There should not be concurrent calls to Expect.
121 with System;
122 with GNAT.OS_Lib;
123 with GNAT.Regpat;
125 package GNAT.Expect is
127 type Process_Id is new Integer;
128 Invalid_Pid : constant Process_Id := -1;
129 Null_Pid : constant Process_Id := 0;
131 type Filter_Type is (Output, Input, Died);
132 -- The signals that are emitted by the Process_Descriptor upon state
133 -- changed in the child. One can connect to any of this signal through
134 -- the Add_Filter subprograms.
136 -- Output => Every time new characters are read from the process
137 -- associated with Descriptor, the filter is called with
138 -- these new characters in argument.
140 -- Note that output is only generated when the program is
141 -- blocked in a call to Expect.
143 -- Input => Every time new characters are written to the process
144 -- associated with Descriptor, the filter is called with
145 -- these new characters in argument.
146 -- Note that input is only generated by calls to Send.
148 -- Died => The child process has died, or was explicitly killed
150 type Process_Descriptor is tagged private;
151 -- Contains all the components needed to describe a process handled
152 -- in this package, including a process identifier, file descriptors
153 -- associated with the standard input, output and error, and the buffer
154 -- needed to handle the expect calls.
156 type Process_Descriptor_Access is access Process_Descriptor'Class;
158 ------------------------
159 -- Spawning a process --
160 ------------------------
162 procedure Non_Blocking_Spawn
163 (Descriptor : out Process_Descriptor'Class;
164 Command : String;
165 Args : GNAT.OS_Lib.Argument_List;
166 Buffer_Size : Natural := 4096;
167 Err_To_Out : Boolean := False);
168 -- This call spawns a new process and allows sending commands to
169 -- the process and/or automatic parsing of the output.
171 -- The expect buffer associated with that process can contain at most
172 -- Buffer_Size characters. Older characters are simply discarded when
173 -- this buffer is full. Beware that if the buffer is too big, this could
174 -- slow down the Expect calls if not output is matched, since Expect has
175 -- to match all the regexp against all the characters in the buffer.
176 -- If Buffer_Size is 0, there is no limit (ie all the characters are kept
177 -- till Expect matches), but this is slower.
179 -- If Err_To_Out is True, then the standard error of the spawned process is
180 -- connected to the standard output. This is the only way to get the
181 -- Except subprograms also match on output on standard error.
183 -- Invalid_Process is raised if the process could not be spawned.
185 procedure Close (Descriptor : in out Process_Descriptor);
186 -- Terminate the process and close the pipes to it. It implicitly
187 -- does the 'wait' command required to clean up the process table.
188 -- This also frees the buffer associated with the process id.
190 procedure Close
191 (Descriptor : in out Process_Descriptor;
192 Status : out Integer);
193 -- Same as above, but also returns the exit status of the process,
194 -- as set for example by the procedure GNAT.OS_Lib.OS_Exit.
196 procedure Send_Signal
197 (Descriptor : Process_Descriptor;
198 Signal : Integer);
199 -- Send a given signal to the process.
201 procedure Interrupt (Descriptor : in out Process_Descriptor);
202 -- Interrupt the process (the equivalent of Ctrl-C on unix and windows)
203 -- and call close if the process dies.
205 function Get_Input_Fd
206 (Descriptor : Process_Descriptor)
207 return GNAT.OS_Lib.File_Descriptor;
208 -- Return the input file descriptor associated with Descriptor.
210 function Get_Output_Fd
211 (Descriptor : Process_Descriptor)
212 return GNAT.OS_Lib.File_Descriptor;
213 -- Return the output file descriptor associated with Descriptor.
215 function Get_Error_Fd
216 (Descriptor : Process_Descriptor)
217 return GNAT.OS_Lib.File_Descriptor;
218 -- Return the error output file descriptor associated with Descriptor.
220 function Get_Pid
221 (Descriptor : Process_Descriptor)
222 return Process_Id;
223 -- Return the process id associated with a given process descriptor.
225 --------------------
226 -- Adding filters --
227 --------------------
229 -- This is a rather low-level interface to subprocesses, since basically
230 -- the filtering is left entirely to the user. See the Expect subprograms
231 -- below for higher level functions.
233 type Filter_Function is access
234 procedure
235 (Descriptor : Process_Descriptor'Class;
236 Str : String;
237 User_Data : System.Address := System.Null_Address);
238 -- Function called every time new characters are read from or written
239 -- to the process.
241 -- Str is a string of all these characters.
243 -- User_Data, if specified, is a user specific data that will be passed to
244 -- the filter. Note that no checks are done on this parameter that should
245 -- be used with cautiousness.
247 procedure Add_Filter
248 (Descriptor : in out Process_Descriptor;
249 Filter : Filter_Function;
250 Filter_On : Filter_Type := Output;
251 User_Data : System.Address := System.Null_Address;
252 After : Boolean := False);
253 -- Add a new filter for one of the filter type. This filter will be
254 -- run before all the existing filters, unless After is set True,
255 -- in which case it will be run after existing filters. User_Data
256 -- is passed as is to the filter procedure.
258 procedure Remove_Filter
259 (Descriptor : in out Process_Descriptor;
260 Filter : Filter_Function);
261 -- Remove a filter from the list of filters (whatever the type of the
262 -- filter).
264 procedure Trace_Filter
265 (Descriptor : Process_Descriptor'Class;
266 Str : String;
267 User_Data : System.Address := System.Null_Address);
268 -- Function that can be used a filter and that simply outputs Str on
269 -- Standard_Output. This is mainly used for debugging purposes.
270 -- User_Data is ignored.
272 procedure Lock_Filters (Descriptor : in out Process_Descriptor);
273 -- Temporarily disables all output and input filters. They will be
274 -- reactivated only when Unlock_Filters has been called as many times as
275 -- Lock_Filters;
277 procedure Unlock_Filters (Descriptor : in out Process_Descriptor);
278 -- Unlocks the filters. They are reactivated only if Unlock_Filters
279 -- has been called as many times as Lock_Filters.
281 ------------------
282 -- Sending data --
283 ------------------
285 procedure Send
286 (Descriptor : in out Process_Descriptor;
287 Str : String;
288 Add_LF : Boolean := True;
289 Empty_Buffer : Boolean := False);
290 -- Send a string to the file descriptor.
292 -- The string is not formatted in any way, except if Add_LF is True,
293 -- in which case an ASCII.LF is added at the end, so that Str is
294 -- recognized as a command by the external process.
296 -- If Empty_Buffer is True, any input waiting from the process (or in the
297 -- buffer) is first discarded before the command is sent. The output
298 -- filters are of course called as usual.
300 -----------------------------------------------------------
301 -- Working on the output (single process, simple regexp) --
302 -----------------------------------------------------------
304 type Expect_Match is new Integer;
305 Expect_Full_Buffer : constant Expect_Match := -1;
306 -- If the buffer was full and some characters were discarded.
308 Expect_Timeout : constant Expect_Match := -2;
309 -- If not output matching the regexps was found before the timeout.
311 function "+" (S : String) return GNAT.OS_Lib.String_Access;
312 -- Allocate some memory for the string. This is merely a convenience
313 -- convenience function to help create the array of regexps in the
314 -- call to Expect.
316 procedure Expect
317 (Descriptor : in out Process_Descriptor;
318 Result : out Expect_Match;
319 Regexp : String;
320 Timeout : Integer := 10000;
321 Full_Buffer : Boolean := False);
322 -- Wait till a string matching Fd can be read from Fd, and return 1
323 -- if a match was found.
325 -- It consumes all the characters read from Fd until a match found, and
326 -- then sets the return values for the subprograms Expect_Out and
327 -- Expect_Out_Match.
329 -- The empty string "" will never match, and can be used if you only want
330 -- to match after a specific timeout. Beware that if Timeout is -1 at the
331 -- time, the current task will be blocked forever.
333 -- This command times out after Timeout milliseconds (or never if Timeout
334 -- is -1). In that case, Expect_Timeout is returned. The value returned by
335 -- Expect_Out and Expect_Out_Match are meaningless in that case.
337 -- Note that using a timeout of 0ms leads to unpredictable behavior, since
338 -- the result depends on whether the process has already sent some output
339 -- the first time Expect checks, and this depends on the operating system.
341 -- The regular expression must obey the syntax described in GNAT.Regpat.
343 -- If Full_Buffer is True, then Expect will match if the buffer was too
344 -- small and some characters were about to be discarded. In that case,
345 -- Expect_Full_Buffer is returned.
347 procedure Expect
348 (Descriptor : in out Process_Descriptor;
349 Result : out Expect_Match;
350 Regexp : GNAT.Regpat.Pattern_Matcher;
351 Timeout : Integer := 10000;
352 Full_Buffer : Boolean := False);
353 -- Same as the previous one, but with a precompiled regular expression.
354 -- This is more efficient however, especially if you are using this
355 -- expression multiple times, since this package won't need to recompile
356 -- the regexp every time.
358 procedure Expect
359 (Descriptor : in out Process_Descriptor;
360 Result : out Expect_Match;
361 Regexp : String;
362 Matched : out GNAT.Regpat.Match_Array;
363 Timeout : Integer := 10000;
364 Full_Buffer : Boolean := False);
365 -- Same as above, but it is now possible to get the indexes of the
366 -- substrings for the parentheses in the regexp (see the example at the
367 -- top of this package, as well as the documentation in the package
368 -- GNAT.Regpat).
370 -- Matched'First should be 0, and this index will contain the indexes for
371 -- the whole string that was matched. The index 1 will contain the indexes
372 -- for the first parentheses-pair, and so on.
374 ------------
375 -- Expect --
376 ------------
378 procedure Expect
379 (Descriptor : in out Process_Descriptor;
380 Result : out Expect_Match;
381 Regexp : GNAT.Regpat.Pattern_Matcher;
382 Matched : out GNAT.Regpat.Match_Array;
383 Timeout : Integer := 10000;
384 Full_Buffer : Boolean := False);
385 -- Same as above, but with a precompiled regular expression.
387 -------------------------------------------------------------
388 -- Working on the output (single process, multiple regexp) --
389 -------------------------------------------------------------
391 type Regexp_Array is array (Positive range <>) of GNAT.OS_Lib.String_Access;
393 type Pattern_Matcher_Access is access GNAT.Regpat.Pattern_Matcher;
394 type Compiled_Regexp_Array is array (Positive range <>)
395 of Pattern_Matcher_Access;
397 function "+"
398 (P : GNAT.Regpat.Pattern_Matcher)
399 return Pattern_Matcher_Access;
400 -- Allocate some memory for the pattern matcher.
401 -- This is only a convenience function to help create the array of
402 -- compiled regular expressoins.
404 procedure Expect
405 (Descriptor : in out Process_Descriptor;
406 Result : out Expect_Match;
407 Regexps : Regexp_Array;
408 Timeout : Integer := 10000;
409 Full_Buffer : Boolean := False);
410 -- Wait till a string matching one of the regular expressions in Regexps
411 -- is found. This function returns the index of the regexp that matched.
412 -- This command is blocking, but will timeout after Timeout milliseconds.
413 -- In that case, Timeout is returned.
415 procedure Expect
416 (Descriptor : in out Process_Descriptor;
417 Result : out Expect_Match;
418 Regexps : Compiled_Regexp_Array;
419 Timeout : Integer := 10000;
420 Full_Buffer : Boolean := False);
421 -- Same as the previous one, but with precompiled regular expressions.
422 -- This can be much faster if you are using them multiple times.
424 procedure Expect
425 (Descriptor : in out Process_Descriptor;
426 Result : out Expect_Match;
427 Regexps : Regexp_Array;
428 Matched : out GNAT.Regpat.Match_Array;
429 Timeout : Integer := 10000;
430 Full_Buffer : Boolean := False);
431 -- Same as above, except that you can also access the parenthesis
432 -- groups inside the matching regular expression.
433 -- The first index in Matched must be 0, or Constraint_Error will be
434 -- raised. The index 0 contains the indexes for the whole string that was
435 -- matched, the index 1 contains the indexes for the first parentheses
436 -- pair, and so on.
438 procedure Expect
439 (Descriptor : in out Process_Descriptor;
440 Result : out Expect_Match;
441 Regexps : Compiled_Regexp_Array;
442 Matched : out GNAT.Regpat.Match_Array;
443 Timeout : Integer := 10000;
444 Full_Buffer : Boolean := False);
445 -- Same as above, but with precompiled regular expressions.
446 -- The first index in Matched must be 0, or Constraint_Error will be
447 -- raised.
449 -------------------------------------------
450 -- Working on the output (multi-process) --
451 -------------------------------------------
453 type Multiprocess_Regexp is record
454 Descriptor : Process_Descriptor_Access;
455 Regexp : Pattern_Matcher_Access;
456 end record;
457 type Multiprocess_Regexp_Array is array (Positive range <>)
458 of Multiprocess_Regexp;
460 procedure Expect
461 (Result : out Expect_Match;
462 Regexps : Multiprocess_Regexp_Array;
463 Matched : out GNAT.Regpat.Match_Array;
464 Timeout : Integer := 10000;
465 Full_Buffer : Boolean := False);
466 -- Same as above, but for multi processes.
468 procedure Expect
469 (Result : out Expect_Match;
470 Regexps : Multiprocess_Regexp_Array;
471 Timeout : Integer := 10000;
472 Full_Buffer : Boolean := False);
473 -- Same as the previous one, but for multiple processes.
474 -- This procedure finds the first regexp that match the associated process.
476 ------------------------
477 -- Getting the output --
478 ------------------------
480 procedure Flush
481 (Descriptor : in out Process_Descriptor;
482 Timeout : Integer := 0);
483 -- Discard all output waiting from the process.
485 -- This output is simply discarded, and no filter is called. This output
486 -- will also not be visible by the next call to Expect, nor will any
487 -- output currently buffered.
489 -- Timeout is the delay for which we wait for output to be available from
490 -- the process. If 0, we only get what is immediately available.
492 function Expect_Out (Descriptor : Process_Descriptor) return String;
493 -- Return the string matched by the last Expect call.
495 -- The returned string is in fact the concatenation of all the strings
496 -- read from the file descriptor up to, and including, the characters
497 -- that matched the regular expression.
499 -- For instance, with an input "philosophic", and a regular expression
500 -- "hi" in the call to expect, the strings returned the first and second
501 -- time would be respectively "phi" and "losophi".
503 function Expect_Out_Match (Descriptor : Process_Descriptor) return String;
504 -- Return the string matched by the last Expect call.
506 -- The returned string includes only the character that matched the
507 -- specific regular expression. All the characters that came before are
508 -- simply discarded.
510 -- For instance, with an input "philosophic", and a regular expression
511 -- "hi" in the call to expect, the strings returned the first and second
512 -- time would both be "hi".
514 ----------------
515 -- Exceptions --
516 ----------------
518 Invalid_Process : exception;
519 -- Raised by most subprograms above when the parameter Descriptor is not a
520 -- valid process or is a closed process.
522 Process_Died : exception;
523 -- Raised by all the expect subprograms if Descriptor was originally a
524 -- valid process that died while Expect was executing. It is also raised
525 -- when Expect receives an end-of-file.
527 private
528 type Filter_List_Elem;
529 type Filter_List is access Filter_List_Elem;
530 type Filter_List_Elem is record
531 Filter : Filter_Function;
532 User_Data : System.Address;
533 Filter_On : Filter_Type;
534 Next : Filter_List;
535 end record;
537 type Pipe_Type is record
538 Input, Output : GNAT.OS_Lib.File_Descriptor;
539 end record;
540 -- This type represents a pipe, used to communicate between two processes.
542 procedure Set_Up_Communications
543 (Pid : in out Process_Descriptor;
544 Err_To_Out : Boolean;
545 Pipe1 : access Pipe_Type;
546 Pipe2 : access Pipe_Type;
547 Pipe3 : access Pipe_Type);
548 -- Set up all the communication pipes and file descriptors prior to
549 -- spawning the child process.
551 procedure Set_Up_Parent_Communications
552 (Pid : in out Process_Descriptor;
553 Pipe1 : in out Pipe_Type;
554 Pipe2 : in out Pipe_Type;
555 Pipe3 : in out Pipe_Type);
556 -- Finish the set up of the pipes while in the parent process
558 procedure Set_Up_Child_Communications
559 (Pid : in out Process_Descriptor;
560 Pipe1 : in out Pipe_Type;
561 Pipe2 : in out Pipe_Type;
562 Pipe3 : in out Pipe_Type;
563 Cmd : String;
564 Args : System.Address);
565 -- Finish the set up of the pipes while in the child process
566 -- This also spawns the child process (based on Cmd).
567 -- On systems that support fork, this procedure is executed inside the
568 -- newly created process.
570 type Process_Descriptor is tagged record
571 Pid : aliased Process_Id := Invalid_Pid;
572 Input_Fd : GNAT.OS_Lib.File_Descriptor := GNAT.OS_Lib.Invalid_FD;
573 Output_Fd : GNAT.OS_Lib.File_Descriptor := GNAT.OS_Lib.Invalid_FD;
574 Error_Fd : GNAT.OS_Lib.File_Descriptor := GNAT.OS_Lib.Invalid_FD;
575 Filters_Lock : Integer := 0;
577 Filters : Filter_List := null;
579 Buffer : GNAT.OS_Lib.String_Access := null;
580 Buffer_Size : Natural := 0;
581 Buffer_Index : Natural := 0;
583 Last_Match_Start : Natural := 0;
584 Last_Match_End : Natural := 0;
585 end record;
587 -- The following subprogram is provided for use in the body, and also
588 -- possibly in future child units providing extensions to this package.
590 procedure Portable_Execvp
591 (Pid : access Process_Id;
592 Cmd : String;
593 Args : System.Address);
594 pragma Import (C, Portable_Execvp, "__gnat_expect_portable_execvp");
595 -- Executes, in a portable way, the command Cmd (full path must be
596 -- specified), with the given Args. Args must be an array of string
597 -- pointers. Note that the first element in Args must be the executable
598 -- name, and the last element must be a null pointer. The returned value
599 -- in Pid is the process ID, or zero if not supported on the platform.
601 end GNAT.Expect;