2005-12-29 Paul Brook <paul@codesourcery.com>
[official-gcc.git] / gcc / ada / g-expect.ads
blobb47a3a487d7c6d0e339af760167b8b9cd6beb112
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 -- Copyright (C) 2000-2005, 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 ------------------------------------------------------------------------------
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 -- -----------
39 -- -- Usage --
40 -- -----------
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.
49 -- Usage example:
51 -- Non_Blocking_Spawn
52 -- (Fd, "ftp",
53 -- (1 => new String' ("machine@domain")));
54 -- Timeout := 10000; -- 10 seconds
55 -- Expect (Fd, Result, Regexp_Array'(+"\(user\)", +"\(passwd\)"),
56 -- Timeout);
57 -- case Result is
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;
62 -- end case;
63 -- Close (Fd);
65 -- You can also combine multiple regular expressions together, and get the
66 -- specific string matching a parenthesis pair by doing something like. If you
67 -- expect either "lang=optional ada" or "lang=ada" from the external process,
68 -- you can group the two together, which is more efficient, and simply get the
69 -- name of the language by doing:
71 -- declare
72 -- Matched : Match_Array (0 .. 2);
73 -- begin
74 -- Expect (Fd, Result, "lang=(optional)? ([a-z]+)", Matched);
75 -- Put_Line ("Seen: " &
76 -- Expect_Out (Fd) (Matched (2).First .. Matched (2).Last));
77 -- end;
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;
85 -- Str : String;
86 -- User_Data : System.Address)
87 -- is
88 -- begin
89 -- Put_Line (Str);
90 -- end;
92 -- Non_Blocking_Spawn
93 -- (Fd, "tail",
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
115 -- -----------------
116 -- -- Task Safety --
117 -- -----------------
119 -- This package is not task-safe: there should be not concurrent calls to
120 -- the functions defined in this package. In other words, separate tasks
121 -- may not access the facilities of this package without synchronization
122 -- that serializes access.
124 with System;
125 with GNAT.OS_Lib;
126 with GNAT.Regpat;
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
136 -- changed in the child. One can connect to any of this signal through
137 -- the 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 argument.
143 -- Note that output is only generated 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 argument.
149 -- Note that input is only generated 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;
167 Command : String;
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
176 -- this buffer is full. Beware that if the buffer is too big, this could
177 -- slow down the Expect calls if not output is matched, since Expect has
178 -- to match all the regexp against all the characters in the buffer.
179 -- If Buffer_Size is 0, there is no limit (ie 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
184 -- Except subprograms also match on output on standard error.
186 -- Invalid_Process is raised if the process could not be spawned.
188 procedure Close (Descriptor : in out Process_Descriptor);
189 -- Terminate the process and close the pipes to it. It implicitly
190 -- does the 'wait' command required to clean up the process table.
191 -- This also frees the buffer associated with the process id.
193 procedure Close
194 (Descriptor : in out Process_Descriptor;
195 Status : out Integer);
196 -- Same as above, but also returns the exit status of the process,
197 -- as set for example by the procedure GNAT.OS_Lib.OS_Exit.
199 procedure Send_Signal
200 (Descriptor : Process_Descriptor;
201 Signal : Integer);
202 -- Send a given signal to the process
204 procedure Interrupt (Descriptor : in out Process_Descriptor);
205 -- Interrupt the process (the equivalent of Ctrl-C on unix and windows)
206 -- and call close if the process dies.
208 function Get_Input_Fd
209 (Descriptor : Process_Descriptor)
210 return GNAT.OS_Lib.File_Descriptor;
211 -- Return the input file descriptor associated with Descriptor
213 function Get_Output_Fd
214 (Descriptor : Process_Descriptor)
215 return GNAT.OS_Lib.File_Descriptor;
216 -- Return the output file descriptor associated with Descriptor
218 function Get_Error_Fd
219 (Descriptor : Process_Descriptor)
220 return GNAT.OS_Lib.File_Descriptor;
221 -- Return the error output file descriptor associated with Descriptor
223 function Get_Pid
224 (Descriptor : Process_Descriptor)
225 return Process_Id;
226 -- Return the process id assocated with a given process descriptor
228 function Get_Command_Output
229 (Command : String;
230 Arguments : GNAT.OS_Lib.Argument_List;
231 Input : String;
232 Status : access Integer;
233 Err_To_Out : Boolean := False) return String;
234 -- Execute Command with the specified Arguments and Input, and return the
235 -- generated standard output data as a single string. If Err_To_Out is
236 -- True, generated standard error output is included as well. On return,
237 -- Status is set to the command's exit status.
239 --------------------
240 -- Adding filters --
241 --------------------
243 -- This is a rather low-level interface to subprocesses, since basically
244 -- the filtering is left entirely to the user. See the Expect subprograms
245 -- below for higher level functions.
247 type Filter_Function is access
248 procedure
249 (Descriptor : Process_Descriptor'Class;
250 Str : String;
251 User_Data : System.Address := System.Null_Address);
252 -- Function called every time new characters are read from or written
253 -- to the process.
255 -- Str is a string of all these characters.
257 -- User_Data, if specified, is a user specific data that will be passed to
258 -- the filter. Note that no checks are done on this parameter that should
259 -- be used with cautiousness.
261 procedure Add_Filter
262 (Descriptor : in out Process_Descriptor;
263 Filter : Filter_Function;
264 Filter_On : Filter_Type := Output;
265 User_Data : System.Address := System.Null_Address;
266 After : Boolean := False);
267 -- Add a new filter for one of the filter type. This filter will be
268 -- run before all the existing filters, unless After is set True,
269 -- in which case it will be run after existing filters. User_Data
270 -- is passed as is to the filter procedure.
272 procedure Remove_Filter
273 (Descriptor : in out Process_Descriptor;
274 Filter : Filter_Function);
275 -- Remove a filter from the list of filters (whatever the type of the
276 -- filter).
278 procedure Trace_Filter
279 (Descriptor : Process_Descriptor'Class;
280 Str : String;
281 User_Data : System.Address := System.Null_Address);
282 -- Function that can be used a filter and that simply outputs Str on
283 -- Standard_Output. This is mainly used for debugging purposes.
284 -- User_Data is ignored.
286 procedure Lock_Filters (Descriptor : in out Process_Descriptor);
287 -- Temporarily disables all output and input filters. They will be
288 -- reactivated only when Unlock_Filters has been called as many times as
289 -- Lock_Filters;
291 procedure Unlock_Filters (Descriptor : in out Process_Descriptor);
292 -- Unlocks the filters. They are reactivated only if Unlock_Filters
293 -- has been called as many times as Lock_Filters.
295 ------------------
296 -- Sending data --
297 ------------------
299 procedure Send
300 (Descriptor : in out Process_Descriptor;
301 Str : String;
302 Add_LF : Boolean := True;
303 Empty_Buffer : Boolean := False);
304 -- Send a string to the file descriptor.
306 -- The string is not formatted in any way, except if Add_LF is True,
307 -- in which case an ASCII.LF is added at the end, so that Str is
308 -- recognized as a command by the external process.
310 -- If Empty_Buffer is True, any input waiting from the process (or in the
311 -- buffer) is first discarded before the command is sent. The output
312 -- filters are of course called as usual.
314 -----------------------------------------------------------
315 -- Working on the output (single process, simple regexp) --
316 -----------------------------------------------------------
318 type Expect_Match is new Integer;
319 Expect_Full_Buffer : constant Expect_Match := -1;
320 -- If the buffer was full and some characters were discarded
322 Expect_Timeout : constant Expect_Match := -2;
323 -- If not output matching the regexps was found before the timeout
325 function "+" (S : String) return GNAT.OS_Lib.String_Access;
326 -- Allocate some memory for the string. This is merely a convenience
327 -- function to help create the array of regexps in the call to Expect.
329 procedure Expect
330 (Descriptor : in out Process_Descriptor;
331 Result : out Expect_Match;
332 Regexp : String;
333 Timeout : Integer := 10000;
334 Full_Buffer : Boolean := False);
335 -- Wait till a string matching Fd can be read from Fd, and return 1
336 -- if a match was found.
338 -- It consumes all the characters read from Fd until a match found, and
339 -- then sets the return values for the subprograms Expect_Out and
340 -- Expect_Out_Match.
342 -- The empty string "" will never match, and can be used if you only want
343 -- to match after a specific timeout. Beware that if Timeout is -1 at the
344 -- time, the current task will be blocked forever.
346 -- This command times out after Timeout milliseconds (or never if Timeout
347 -- is -1). In that case, Expect_Timeout is returned. The value returned by
348 -- Expect_Out and Expect_Out_Match are meaningless in that case.
350 -- Note that using a timeout of 0ms leads to unpredictable behavior, since
351 -- the result depends on whether the process has already sent some output
352 -- the first time Expect checks, and this depends on the operating system.
354 -- The regular expression must obey the syntax described in GNAT.Regpat.
356 -- If Full_Buffer is True, then Expect will match if the buffer was too
357 -- small and some characters were about to be discarded. In that case,
358 -- Expect_Full_Buffer is returned.
360 procedure Expect
361 (Descriptor : in out Process_Descriptor;
362 Result : out Expect_Match;
363 Regexp : GNAT.Regpat.Pattern_Matcher;
364 Timeout : Integer := 10000;
365 Full_Buffer : Boolean := False);
366 -- Same as the previous one, but with a precompiled regular expression.
367 -- This is more efficient however, especially if you are using this
368 -- expression multiple times, since this package won't need to recompile
369 -- the regexp every time.
371 procedure Expect
372 (Descriptor : in out Process_Descriptor;
373 Result : out Expect_Match;
374 Regexp : String;
375 Matched : out GNAT.Regpat.Match_Array;
376 Timeout : Integer := 10000;
377 Full_Buffer : Boolean := False);
378 -- Same as above, but it is now possible to get the indexes of the
379 -- substrings for the parentheses in the regexp (see the example at the
380 -- top of this package, as well as the documentation in the package
381 -- GNAT.Regpat).
383 -- Matched'First should be 0, and this index will contain the indexes for
384 -- the whole string that was matched. The index 1 will contain the indexes
385 -- for the first parentheses-pair, and so on.
387 ------------
388 -- Expect --
389 ------------
391 procedure Expect
392 (Descriptor : in out Process_Descriptor;
393 Result : out Expect_Match;
394 Regexp : GNAT.Regpat.Pattern_Matcher;
395 Matched : out GNAT.Regpat.Match_Array;
396 Timeout : Integer := 10000;
397 Full_Buffer : Boolean := False);
398 -- Same as above, but with a precompiled regular expression
400 -------------------------------------------------------------
401 -- Working on the output (single process, multiple regexp) --
402 -------------------------------------------------------------
404 type Regexp_Array is array (Positive range <>) of GNAT.OS_Lib.String_Access;
406 type Pattern_Matcher_Access is access GNAT.Regpat.Pattern_Matcher;
407 type Compiled_Regexp_Array is array (Positive range <>)
408 of Pattern_Matcher_Access;
410 function "+"
411 (P : GNAT.Regpat.Pattern_Matcher)
412 return Pattern_Matcher_Access;
413 -- Allocate some memory for the pattern matcher.
414 -- This is only a convenience function to help create the array of
415 -- compiled regular expressoins.
417 procedure Expect
418 (Descriptor : in out Process_Descriptor;
419 Result : out Expect_Match;
420 Regexps : Regexp_Array;
421 Timeout : Integer := 10000;
422 Full_Buffer : Boolean := False);
423 -- Wait till a string matching one of the regular expressions in Regexps
424 -- is found. This function returns the index of the regexp that matched.
425 -- This command is blocking, but will timeout after Timeout milliseconds.
426 -- In that case, Timeout is returned.
428 procedure Expect
429 (Descriptor : in out Process_Descriptor;
430 Result : out Expect_Match;
431 Regexps : Compiled_Regexp_Array;
432 Timeout : Integer := 10000;
433 Full_Buffer : Boolean := False);
434 -- Same as the previous one, but with precompiled regular expressions.
435 -- This can be much faster if you are using them multiple times.
437 procedure Expect
438 (Descriptor : in out Process_Descriptor;
439 Result : out Expect_Match;
440 Regexps : Regexp_Array;
441 Matched : out GNAT.Regpat.Match_Array;
442 Timeout : Integer := 10000;
443 Full_Buffer : Boolean := False);
444 -- Same as above, except that you can also access the parenthesis
445 -- 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
449 -- pair, and so on.
451 procedure Expect
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 := 10000;
457 Full_Buffer : Boolean := False);
458 -- Same as above, but with precompiled regular expressions.
459 -- The first index in Matched must be 0, or Constraint_Error will be
460 -- raised.
462 -------------------------------------------
463 -- Working on the output (multi-process) --
464 -------------------------------------------
466 type Multiprocess_Regexp is record
467 Descriptor : Process_Descriptor_Access;
468 Regexp : Pattern_Matcher_Access;
469 end record;
470 type Multiprocess_Regexp_Array is array (Positive range <>)
471 of Multiprocess_Regexp;
473 procedure Expect
474 (Result : out Expect_Match;
475 Regexps : Multiprocess_Regexp_Array;
476 Matched : out GNAT.Regpat.Match_Array;
477 Timeout : Integer := 10000;
478 Full_Buffer : Boolean := False);
479 -- Same as above, but for multi processes
481 procedure Expect
482 (Result : out Expect_Match;
483 Regexps : Multiprocess_Regexp_Array;
484 Timeout : Integer := 10000;
485 Full_Buffer : Boolean := False);
486 -- Same as the previous one, but for multiple processes.
487 -- This procedure finds the first regexp that match the associated process.
489 ------------------------
490 -- Getting the output --
491 ------------------------
493 procedure Flush
494 (Descriptor : in out Process_Descriptor;
495 Timeout : Integer := 0);
496 -- Discard all output waiting from the process.
498 -- This output is simply discarded, and no filter is called. This output
499 -- will also not be visible by the next call to Expect, nor will any
500 -- output currently buffered.
502 -- Timeout is the delay for which we wait for output to be available from
503 -- the process. If 0, we only get what is immediately available.
505 function Expect_Out (Descriptor : Process_Descriptor) return String;
506 -- Return the string matched by the last Expect call.
508 -- The returned string is in fact the concatenation of all the strings
509 -- read from the file descriptor up to, and including, the characters
510 -- that matched the regular expression.
512 -- For instance, with an input "philosophic", and a regular expression
513 -- "hi" in the call to expect, the strings returned the first and second
514 -- time would be respectively "phi" and "losophi".
516 function Expect_Out_Match (Descriptor : Process_Descriptor) return String;
517 -- Return the string matched by the last Expect call.
519 -- The returned string includes only the character that matched the
520 -- specific regular expression. All the characters that came before are
521 -- simply discarded.
523 -- For instance, with an input "philosophic", and a regular expression
524 -- "hi" in the call to expect, the strings returned the first and second
525 -- time would both be "hi".
527 ----------------
528 -- Exceptions --
529 ----------------
531 Invalid_Process : exception;
532 -- Raised by most subprograms above when the parameter Descriptor is not a
533 -- valid process or is a closed process.
535 Process_Died : exception;
536 -- Raised by all the expect subprograms if Descriptor was originally a
537 -- valid process that died while Expect was executing. It is also raised
538 -- when Expect receives an end-of-file.
540 private
541 type Filter_List_Elem;
542 type Filter_List is access Filter_List_Elem;
543 type Filter_List_Elem is record
544 Filter : Filter_Function;
545 User_Data : System.Address;
546 Filter_On : Filter_Type;
547 Next : Filter_List;
548 end record;
550 type Pipe_Type is record
551 Input, Output : GNAT.OS_Lib.File_Descriptor;
552 end record;
553 -- This type represents a pipe, used to communicate between two processes
555 procedure Set_Up_Communications
556 (Pid : in out Process_Descriptor;
557 Err_To_Out : Boolean;
558 Pipe1 : access Pipe_Type;
559 Pipe2 : access Pipe_Type;
560 Pipe3 : access Pipe_Type);
561 -- Set up all the communication pipes and file descriptors prior to
562 -- spawning the child process.
564 procedure Set_Up_Parent_Communications
565 (Pid : in out Process_Descriptor;
566 Pipe1 : in out Pipe_Type;
567 Pipe2 : in out Pipe_Type;
568 Pipe3 : in out Pipe_Type);
569 -- Finish the set up of the pipes while in the parent process
571 procedure Set_Up_Child_Communications
572 (Pid : in out Process_Descriptor;
573 Pipe1 : in out Pipe_Type;
574 Pipe2 : in out Pipe_Type;
575 Pipe3 : in out Pipe_Type;
576 Cmd : String;
577 Args : System.Address);
578 -- Finish the set up of the pipes while in the child process
579 -- This also spawns the child process (based on Cmd).
580 -- On systems that support fork, this procedure is executed inside the
581 -- newly created process.
583 type Process_Descriptor is tagged record
584 Pid : aliased Process_Id := Invalid_Pid;
585 Input_Fd : GNAT.OS_Lib.File_Descriptor := GNAT.OS_Lib.Invalid_FD;
586 Output_Fd : GNAT.OS_Lib.File_Descriptor := GNAT.OS_Lib.Invalid_FD;
587 Error_Fd : GNAT.OS_Lib.File_Descriptor := GNAT.OS_Lib.Invalid_FD;
588 Filters_Lock : Integer := 0;
590 Filters : Filter_List := null;
592 Buffer : GNAT.OS_Lib.String_Access := null;
593 Buffer_Size : Natural := 0;
594 Buffer_Index : Natural := 0;
596 Last_Match_Start : Natural := 0;
597 Last_Match_End : Natural := 0;
598 end record;
600 -- The following subprogram is provided for use in the body, and also
601 -- possibly in future child units providing extensions to this package.
603 procedure Portable_Execvp
604 (Pid : access Process_Id;
605 Cmd : String;
606 Args : System.Address);
607 pragma Import (C, Portable_Execvp, "__gnat_expect_portable_execvp");
608 -- Executes, in a portable way, the command Cmd (full path must be
609 -- specified), with the given Args. Args must be an array of string
610 -- pointers. Note that the first element in Args must be the executable
611 -- name, and the last element must be a null pointer. The returned value
612 -- in Pid is the process ID, or zero if not supported on the platform.
614 end GNAT.Expect;