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