gdb/testsuite/
[platform/upstream/binutils.git] / gdb / testsuite / lib / gdb.exp
1 # Copyright 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
2 # 2003, 2004, 2005, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
3
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 # This file was written by Fred Fish. (fnf@cygnus.com)
18
19 # Generic gdb subroutines that should work for any target.  If these
20 # need to be modified for any target, it can be done with a variable
21 # or by passing arguments.
22
23 if {$tool == ""} {
24     # Tests would fail, logs on get_compiler_info() would be missing.
25     send_error "`site.exp' not found, run `make site.exp'!\n"
26     exit 2
27 }
28
29 load_lib libgloss.exp
30
31 global GDB
32
33 if [info exists TOOL_EXECUTABLE] {
34     set GDB $TOOL_EXECUTABLE;
35 }
36 if ![info exists GDB] {
37     if ![is_remote host] {
38         set GDB [findfile $base_dir/../../gdb/gdb "$base_dir/../../gdb/gdb" [transform gdb]]
39     } else {
40         set GDB [transform gdb];
41     }
42 }
43 verbose "using GDB = $GDB" 2
44
45 # GDBFLAGS is available for the user to set on the command line.
46 # E.g. make check RUNTESTFLAGS=GDBFLAGS=mumble
47 # Testcases may use it to add additional flags, but they must:
48 # - append new flags, not overwrite
49 # - restore the original value when done
50 global GDBFLAGS
51 if ![info exists GDBFLAGS] {
52     set GDBFLAGS ""
53 }
54 verbose "using GDBFLAGS = $GDBFLAGS" 2
55
56 # INTERNAL_GDBFLAGS contains flags that the testsuite requires.
57 set INTERNAL_GDBFLAGS "-nw -nx"
58
59 # The variable gdb_prompt is a regexp which matches the gdb prompt.
60 # Set it if it is not already set.
61 global gdb_prompt
62 if ![info exists gdb_prompt] then {
63     set gdb_prompt "\[(\]gdb\[)\]"
64 }
65
66 # The variable fullname_syntax_POSIX is a regexp which matches a POSIX 
67 # absolute path ie. /foo/ 
68 set fullname_syntax_POSIX {/[^\n]*/}
69 # The variable fullname_syntax_UNC is a regexp which matches a Windows 
70 # UNC path ie. \\D\foo\ 
71 set fullname_syntax_UNC {\\\\[^\\]+\\[^\n]+\\}
72 # The variable fullname_syntax_DOS_CASE is a regexp which matches a 
73 # particular DOS case that GDB most likely will output
74 # ie. \foo\, but don't match \\.*\ 
75 set fullname_syntax_DOS_CASE {\\[^\\][^\n]*\\}
76 # The variable fullname_syntax_DOS is a regexp which matches a DOS path
77 # ie. a:\foo\ && a:foo\ 
78 set fullname_syntax_DOS {[a-zA-Z]:[^\n]*\\}
79 # The variable fullname_syntax is a regexp which matches what GDB considers
80 # an absolute path. It is currently debatable if the Windows style paths 
81 # d:foo and \abc should be considered valid as an absolute path.
82 # Also, the purpse of this regexp is not to recognize a well formed 
83 # absolute path, but to say with certainty that a path is absolute.
84 set fullname_syntax "($fullname_syntax_POSIX|$fullname_syntax_UNC|$fullname_syntax_DOS_CASE|$fullname_syntax_DOS)"
85
86 # Needed for some tests under Cygwin.
87 global EXEEXT
88 global env
89
90 if ![info exists env(EXEEXT)] {
91     set EXEEXT ""
92 } else {
93     set EXEEXT $env(EXEEXT)
94 }
95
96 set octal "\[0-7\]+"
97
98 ### Only procedures should come after this point.
99
100 #
101 # gdb_version -- extract and print the version number of GDB
102 #
103 proc default_gdb_version {} {
104     global GDB
105     global INTERNAL_GDBFLAGS GDBFLAGS
106     global gdb_prompt
107     set output [remote_exec host "$GDB $INTERNAL_GDBFLAGS --version"]
108     set tmp [lindex $output 1];
109     set version ""
110     regexp " \[0-9\]\[^ \t\n\r\]+" "$tmp" version
111     if ![is_remote host] {
112         clone_output "[which $GDB] version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
113     } else {
114         clone_output "$GDB on remote host version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
115     }
116 }
117
118 proc gdb_version { } {
119     return [default_gdb_version];
120 }
121
122 #
123 # gdb_unload -- unload a file if one is loaded
124 #
125
126 proc gdb_unload {} {
127     global verbose
128     global GDB
129     global gdb_prompt
130     send_gdb "file\n"
131     gdb_expect 60 {
132         -re "No executable file now\[^\r\n\]*\[\r\n\]" { exp_continue }
133         -re "No symbol file now\[^\r\n\]*\[\r\n\]" { exp_continue }
134         -re "A program is being debugged already..*Kill it.*y or n. $"\
135             { send_gdb "y\n"
136                 verbose "\t\tKilling previous program being debugged"
137             exp_continue
138         }
139         -re "Discard symbol table from .*y or n.*$" {
140             send_gdb "y\n"
141             exp_continue
142         }
143         -re "$gdb_prompt $" {}
144         timeout {
145             perror "couldn't unload file in $GDB (timed out)."
146             return -1
147         }
148     }
149 }
150
151 # Many of the tests depend on setting breakpoints at various places and
152 # running until that breakpoint is reached.  At times, we want to start
153 # with a clean-slate with respect to breakpoints, so this utility proc 
154 # lets us do this without duplicating this code everywhere.
155 #
156
157 proc delete_breakpoints {} {
158     global gdb_prompt
159
160     # we need a larger timeout value here or this thing just confuses
161     # itself.  May need a better implementation if possible. - guo
162     #
163     send_gdb "delete breakpoints\n"
164     gdb_expect 100 {
165          -re "Delete all breakpoints.*y or n.*$" {
166             send_gdb "y\n";
167             exp_continue
168         }
169          -re "$gdb_prompt $" { # This happens if there were no breakpoints
170             }
171          timeout { perror "Delete all breakpoints in delete_breakpoints (timeout)" ; return }
172     }
173     send_gdb "info breakpoints\n"
174     gdb_expect 100 {
175          -re "No breakpoints or watchpoints..*$gdb_prompt $" {}
176          -re "$gdb_prompt $" { perror "breakpoints not deleted" ; return }
177          -re "Delete all breakpoints.*or n.*$" {
178             send_gdb "y\n";
179             exp_continue
180         }
181          timeout { perror "info breakpoints (timeout)" ; return }
182     }
183 }
184
185
186 #
187 # Generic run command.
188 #
189 # The second pattern below matches up to the first newline *only*.
190 # Using ``.*$'' could swallow up output that we attempt to match
191 # elsewhere.
192 #
193 proc gdb_run_cmd {args} {
194     global gdb_prompt
195
196     if [target_info exists gdb_init_command] {
197         send_gdb "[target_info gdb_init_command]\n";
198         gdb_expect 30 {
199             -re "$gdb_prompt $" { }
200             default {
201                 perror "gdb_init_command for target failed";
202                 return;
203             }
204         }
205     }
206
207     if [target_info exists use_gdb_stub] {
208         if [target_info exists gdb,do_reload_on_run] {
209             if { [gdb_reload] != 0 } {
210                 return;
211             }
212             send_gdb "continue\n";
213             gdb_expect 60 {
214                 -re "Continu\[^\r\n\]*\[\r\n\]" {}
215                 default {}
216             }
217             return;
218         }
219
220         if [target_info exists gdb,start_symbol] {
221             set start [target_info gdb,start_symbol];
222         } else {
223             set start "start";
224         }
225         send_gdb  "jump *$start\n"
226         set start_attempt 1;
227         while { $start_attempt } {
228             # Cap (re)start attempts at three to ensure that this loop
229             # always eventually fails.  Don't worry about trying to be
230             # clever and not send a command when it has failed.
231             if [expr $start_attempt > 3] {
232                 perror "Jump to start() failed (retry count exceeded)";
233                 return;
234             }
235             set start_attempt [expr $start_attempt + 1];
236             gdb_expect 30 {
237                 -re "Continuing at \[^\r\n\]*\[\r\n\]" {
238                     set start_attempt 0;
239                 }
240                 -re "No symbol \"_start\" in current.*$gdb_prompt $" {
241                     perror "Can't find start symbol to run in gdb_run";
242                     return;
243                 }
244                 -re "No symbol \"start\" in current.*$gdb_prompt $" {
245                     send_gdb "jump *_start\n";
246                 }
247                 -re "No symbol.*context.*$gdb_prompt $" {
248                     set start_attempt 0;
249                 }
250                 -re "Line.* Jump anyway.*y or n. $" {
251                     send_gdb "y\n"
252                 }
253                 -re "The program is not being run.*$gdb_prompt $" {
254                     if { [gdb_reload] != 0 } {
255                         return;
256                     }
257                     send_gdb "jump *$start\n";
258                 }
259                 timeout {
260                     perror "Jump to start() failed (timeout)"; 
261                     return
262                 }
263             }
264         }
265         if [target_info exists gdb_stub] {
266             gdb_expect 60 {
267                 -re "$gdb_prompt $" {
268                     send_gdb "continue\n"
269                 }
270             }
271         }
272         return
273     }
274
275     if [target_info exists gdb,do_reload_on_run] {
276         if { [gdb_reload] != 0 } {
277             return;
278         }
279     }
280     send_gdb "run $args\n"
281 # This doesn't work quite right yet.
282 # Use -notransfer here so that test cases (like chng-sym.exp)
283 # may test for additional start-up messages.
284    gdb_expect 60 {
285         -re "The program .* has been started already.*y or n. $" {
286             send_gdb "y\n"
287             exp_continue
288         }
289         -notransfer -re "Starting program: \[^\r\n\]*" {}
290     }
291 }
292
293 # Generic start command.  Return 0 if we could start the program, -1
294 # if we could not.
295
296 proc gdb_start_cmd {args} {
297     global gdb_prompt
298
299     if [target_info exists gdb_init_command] {
300         send_gdb "[target_info gdb_init_command]\n";
301         gdb_expect 30 {
302             -re "$gdb_prompt $" { }
303             default {
304                 perror "gdb_init_command for target failed";
305                 return;
306             }
307         }
308     }
309
310     if [target_info exists use_gdb_stub] {
311         return -1
312     }
313
314     send_gdb "start $args\n"
315     # Use -notransfer here so that test cases (like chng-sym.exp)
316     # may test for additional start-up messages.
317     gdb_expect 60 {
318         -re "The program .* has been started already.*y or n. $" {
319             send_gdb "y\n"
320             exp_continue
321         }
322         -notransfer -re "Starting program: \[^\r\n\]*" {
323             return 0
324         }
325     }
326     return -1
327 }
328
329 # Set a breakpoint at FUNCTION.  If there is an additional argument it is
330 # a list of options; the supported options are allow-pending, temporary,
331 # and no-message.
332
333 proc gdb_breakpoint { function args } {
334     global gdb_prompt
335     global decimal
336
337     set pending_response n
338     if {[lsearch -exact [lindex $args 0] allow-pending] != -1} {
339         set pending_response y
340     }
341
342     set break_command "break"
343     set break_message "Breakpoint"
344     if {[lsearch -exact [lindex $args 0] temporary] != -1} {
345         set break_command "tbreak"
346         set break_message "Temporary breakpoint"
347     }
348
349     set no_message 0
350     if {[lsearch -exact [lindex $args 0] no-message] != -1} {
351         set no_message 1
352     }
353
354     send_gdb "$break_command $function\n"
355     # The first two regexps are what we get with -g, the third is without -g.
356     gdb_expect 30 {
357         -re "$break_message \[0-9\]* at .*: file .*, line $decimal.\r\n$gdb_prompt $" {}
358         -re "$break_message \[0-9\]*: file .*, line $decimal.\r\n$gdb_prompt $" {}
359         -re "$break_message \[0-9\]* at .*$gdb_prompt $" {}
360         -re "$break_message \[0-9\]* \\(.*\\) pending.*$gdb_prompt $" {
361                 if {$pending_response == "n"} {
362                         if { $no_message == 0 } {
363                                 fail "setting breakpoint at $function"
364                         }
365                         return 0
366                 }
367         }
368         -re "Make breakpoint pending.*y or \\\[n\\\]. $" { 
369                 send_gdb "$pending_response\n"
370                 exp_continue
371         }
372         -re "$gdb_prompt $" {
373                 if { $no_message == 0 } {
374                         fail "setting breakpoint at $function"
375                 }
376                 return 0
377         }
378         timeout {
379                 if { $no_message == 0 } {
380                         fail "setting breakpoint at $function (timeout)"
381                 }
382                 return 0
383         }
384     }
385     return 1;
386 }    
387
388 # Set breakpoint at function and run gdb until it breaks there.
389 # Since this is the only breakpoint that will be set, if it stops
390 # at a breakpoint, we will assume it is the one we want.  We can't
391 # just compare to "function" because it might be a fully qualified,
392 # single quoted C++ function specifier.  If there's an additional argument,
393 # pass it to gdb_breakpoint.
394
395 proc runto { function args } {
396     global gdb_prompt
397     global decimal
398
399     delete_breakpoints
400
401     if ![gdb_breakpoint $function [lindex $args 0]] {
402         return 0;
403     }
404
405     gdb_run_cmd
406     
407     # the "at foo.c:36" output we get with -g.
408     # the "in func" output we get without -g.
409     gdb_expect 30 {
410         -re "Break.* at .*:$decimal.*$gdb_prompt $" {
411             return 1
412         }
413         -re "Breakpoint \[0-9\]*, \[0-9xa-f\]* in .*$gdb_prompt $" { 
414             return 1
415         }
416         -re "$gdb_prompt $" { 
417             fail "running to $function in runto"
418             return 0
419         }
420         eof { 
421             fail "running to $function in runto (end of file)"
422             return 0
423         }
424         timeout { 
425             fail "running to $function in runto (timeout)"
426             return 0
427         }
428     }
429     return 1
430 }
431
432 #
433 # runto_main -- ask gdb to run until we hit a breakpoint at main.
434 #               The case where the target uses stubs has to be handled
435 #               specially--if it uses stubs, assuming we hit
436 #               breakpoint() and just step out of the function.
437 #
438 proc runto_main { } {
439     global gdb_prompt
440     global decimal
441
442     if ![target_info exists gdb_stub] {
443         return [runto main]
444     }                   
445
446     delete_breakpoints
447
448     gdb_step_for_stub;
449
450     return 1
451 }
452
453
454 ### Continue, and expect to hit a breakpoint.
455 ### Report a pass or fail, depending on whether it seems to have
456 ### worked.  Use NAME as part of the test name; each call to
457 ### continue_to_breakpoint should use a NAME which is unique within
458 ### that test file.
459 proc gdb_continue_to_breakpoint {name {location_pattern .*}} {
460     global gdb_prompt
461     set full_name "continue to breakpoint: $name"
462
463     send_gdb "continue\n"
464     gdb_expect {
465         -re "Breakpoint .* (at|in) $location_pattern\r\n$gdb_prompt $" {
466             pass $full_name
467         }
468         -re ".*$gdb_prompt $" {
469             fail $full_name
470         }
471         timeout { 
472             fail "$full_name (timeout)"
473         }
474     }
475 }
476
477
478 # gdb_internal_error_resync:
479 #
480 # Answer the questions GDB asks after it reports an internal error
481 # until we get back to a GDB prompt.  Decline to quit the debugging
482 # session, and decline to create a core file.  Return non-zero if the
483 # resync succeeds.
484 #
485 # This procedure just answers whatever questions come up until it sees
486 # a GDB prompt; it doesn't require you to have matched the input up to
487 # any specific point.  However, it only answers questions it sees in
488 # the output itself, so if you've matched a question, you had better
489 # answer it yourself before calling this.
490 #
491 # You can use this function thus:
492 #
493 # gdb_expect {
494 #     ...
495 #     -re ".*A problem internal to GDB has been detected" {
496 #         gdb_internal_error_resync
497 #     }
498 #     ...
499 # }
500 #
501 proc gdb_internal_error_resync {} {
502     global gdb_prompt
503
504     set count 0
505     while {$count < 10} {
506         gdb_expect {
507             -re "Quit this debugging session\\? \\(y or n\\) $" {
508                 send_gdb "n\n"
509                 incr count
510             }
511             -re "Create a core file of GDB\\? \\(y or n\\) $" {
512                 send_gdb "n\n"
513                 incr count
514             }
515             -re "$gdb_prompt $" {
516                 # We're resynchronized.
517                 return 1
518             }
519             timeout {
520                 perror "Could not resync from internal error (timeout)"
521                 return 0
522             }
523         }
524     }
525     perror "Could not resync from internal error (resync count exceeded)"
526     return 0
527 }
528
529
530 # gdb_test_multiple COMMAND MESSAGE EXPECT_ARGUMENTS
531 # Send a command to gdb; test the result.
532 #
533 # COMMAND is the command to execute, send to GDB with send_gdb.  If
534 #   this is the null string no command is sent.
535 # MESSAGE is a message to be printed with the built-in failure patterns
536 #   if one of them matches.  If MESSAGE is empty COMMAND will be used.
537 # EXPECT_ARGUMENTS will be fed to expect in addition to the standard
538 #   patterns.  Pattern elements will be evaluated in the caller's
539 #   context; action elements will be executed in the caller's context.
540 #   Unlike patterns for gdb_test, these patterns should generally include
541 #   the final newline and prompt.
542 #
543 # Returns:
544 #    1 if the test failed, according to a built-in failure pattern
545 #    0 if only user-supplied patterns matched
546 #   -1 if there was an internal error.
547 #  
548 # You can use this function thus:
549 #
550 # gdb_test_multiple "print foo" "test foo" {
551 #    -re "expected output 1" {
552 #        pass "print foo"
553 #    }
554 #    -re "expected output 2" {
555 #        fail "print foo"
556 #    }
557 # }
558 #
559 # The standard patterns, such as "Program exited..." and "A problem
560 # ...", all being implicitly appended to that list.
561 #
562 proc gdb_test_multiple { command message user_code } {
563     global verbose
564     global gdb_prompt
565     global GDB
566     upvar timeout timeout
567     upvar expect_out expect_out
568
569     if { $message == "" } {
570         set message $command
571     }
572
573     # TCL/EXPECT WART ALERT
574     # Expect does something very strange when it receives a single braced
575     # argument.  It splits it along word separators and performs substitutions.
576     # This means that { "[ab]" } is evaluated as "[ab]", but { "\[ab\]" } is
577     # evaluated as "\[ab\]".  But that's not how TCL normally works; inside a
578     # double-quoted list item, "\[ab\]" is just a long way of representing
579     # "[ab]", because the backslashes will be removed by lindex.
580
581     # Unfortunately, there appears to be no easy way to duplicate the splitting
582     # that expect will do from within TCL.  And many places make use of the
583     # "\[0-9\]" construct, so we need to support that; and some places make use
584     # of the "[func]" construct, so we need to support that too.  In order to
585     # get this right we have to substitute quoted list elements differently
586     # from braced list elements.
587
588     # We do this roughly the same way that Expect does it.  We have to use two
589     # lists, because if we leave unquoted newlines in the argument to uplevel
590     # they'll be treated as command separators, and if we escape newlines
591     # we mangle newlines inside of command blocks.  This assumes that the
592     # input doesn't contain a pattern which contains actual embedded newlines
593     # at this point!
594
595     regsub -all {\n} ${user_code} { } subst_code
596     set subst_code [uplevel list $subst_code]
597
598     set processed_code ""
599     set patterns ""
600     set expecting_action 0
601     foreach item $user_code subst_item $subst_code {
602         if { $item == "-n" || $item == "-notransfer" || $item == "-nocase" } {
603             lappend processed_code $item
604             continue
605         }
606         if {$item == "-indices" || $item == "-re" || $item == "-ex"} {
607             lappend processed_code $item
608             continue
609         }
610         if { $expecting_action } {
611             lappend processed_code "uplevel [list $item]"
612             set expecting_action 0
613             # Cosmetic, no effect on the list.
614             append processed_code "\n"
615             continue
616         }
617         set expecting_action 1
618         lappend processed_code $subst_item
619         if {$patterns != ""} {
620             append patterns "; "
621         }
622         append patterns "\"$subst_item\""
623     }
624
625     # Also purely cosmetic.
626     regsub -all {\r} $patterns {\\r} patterns
627     regsub -all {\n} $patterns {\\n} patterns
628
629     if $verbose>2 then {
630         send_user "Sending \"$command\" to gdb\n"
631         send_user "Looking to match \"$patterns\"\n"
632         send_user "Message is \"$message\"\n"
633     }
634
635     set result -1
636     set string "${command}\n";
637     if { $command != "" } {
638         while { "$string" != "" } {
639             set foo [string first "\n" "$string"];
640             set len [string length "$string"];
641             if { $foo < [expr $len - 1] } {
642                 set str [string range "$string" 0 $foo];
643                 if { [send_gdb "$str"] != "" } {
644                     global suppress_flag;
645
646                     if { ! $suppress_flag } {
647                         perror "Couldn't send $command to GDB.";
648                     }
649                     fail "$message";
650                     return $result;
651                 }
652                 # since we're checking if each line of the multi-line
653                 # command are 'accepted' by GDB here,
654                 # we need to set -notransfer expect option so that
655                 # command output is not lost for pattern matching
656                 # - guo
657                 gdb_expect 2 {
658                     -notransfer -re "\[\r\n\]" { verbose "partial: match" 3 }
659                     timeout { verbose "partial: timeout" 3 }
660                 }
661                 set string [string range "$string" [expr $foo + 1] end];
662             } else {
663                 break;
664             }
665         }
666         if { "$string" != "" } {
667             if { [send_gdb "$string"] != "" } {
668                 global suppress_flag;
669
670                 if { ! $suppress_flag } {
671                     perror "Couldn't send $command to GDB.";
672                 }
673                 fail "$message";
674                 return $result;
675             }
676         }
677     }
678
679     if [target_info exists gdb,timeout] {
680         set tmt [target_info gdb,timeout];
681     } else {
682         if [info exists timeout] {
683             set tmt $timeout;
684         } else {
685             global timeout;
686             if [info exists timeout] {
687                 set tmt $timeout;
688             } else {
689                 set tmt 60;
690             }
691         }
692     }
693
694     set code {
695          -re ".*A problem internal to GDB has been detected" {
696              fail "$message (GDB internal error)"
697              gdb_internal_error_resync
698          }
699          -re "\\*\\*\\* DOSEXIT code.*" {
700              if { $message != "" } {
701                  fail "$message";
702              }
703              gdb_suppress_entire_file "GDB died";
704              set result -1;
705          }
706     }
707     append code $processed_code
708     append code {
709          -re "Ending remote debugging.*$gdb_prompt $" {
710             if ![isnative] then {
711                 warning "Can`t communicate to remote target."
712             }
713             gdb_exit
714             gdb_start
715             set result -1
716         }
717          -re "Undefined\[a-z\]* command:.*$gdb_prompt $" {
718             perror "Undefined command \"$command\"."
719             fail "$message"
720             set result 1
721         }
722          -re "Ambiguous command.*$gdb_prompt $" {
723             perror "\"$command\" is not a unique command name."
724             fail "$message"
725             set result 1
726         }
727          -re "Program exited with code \[0-9\]+.*$gdb_prompt $" {
728             if ![string match "" $message] then {
729                 set errmsg "$message (the program exited)"
730             } else {
731                 set errmsg "$command (the program exited)"
732             }
733             fail "$errmsg"
734             set result -1
735         }
736          -re "EXIT code \[0-9\r\n\]+Program exited normally.*$gdb_prompt $" {
737             if ![string match "" $message] then {
738                 set errmsg "$message (the program exited)"
739             } else {
740                 set errmsg "$command (the program exited)"
741             }
742             fail "$errmsg"
743             set result -1
744         }
745          -re "The program is not being run.*$gdb_prompt $" {
746             if ![string match "" $message] then {
747                 set errmsg "$message (the program is no longer running)"
748             } else {
749                 set errmsg "$command (the program is no longer running)"
750             }
751             fail "$errmsg"
752             set result -1
753         }
754          -re "\r\n$gdb_prompt $" {
755             if ![string match "" $message] then {
756                 fail "$message"
757             }
758             set result 1
759         }
760          "<return>" {
761             send_gdb "\n"
762             perror "Window too small."
763             fail "$message"
764             set result -1
765         }
766         -re "\\((y or n|y or \\\[n\\\]|\\\[y\\\] or n)\\) " {
767             send_gdb "n\n"
768             gdb_expect -re "$gdb_prompt $"
769             fail "$message (got interactive prompt)"
770             set result -1
771         }
772         -re "\\\[0\\\] cancel\r\n\\\[1\\\] all.*\r\n> $" {
773             send_gdb "0\n"
774             gdb_expect -re "$gdb_prompt $"
775             fail "$message (got breakpoint menu)"
776             set result -1
777         }
778          eof {
779              perror "Process no longer exists"
780              if { $message != "" } {
781                  fail "$message"
782              }
783              return -1
784         }
785          full_buffer {
786             perror "internal buffer is full."
787             fail "$message"
788             set result -1
789         }
790         timeout {
791             if ![string match "" $message] then {
792                 fail "$message (timeout)"
793             }
794             set result 1
795         }
796     }
797
798     set result 0
799     set code [catch {gdb_expect $tmt $code} string]
800     if {$code == 1} {
801         global errorInfo errorCode;
802         return -code error -errorinfo $errorInfo -errorcode $errorCode $string
803     } elseif {$code == 2} {
804         return -code return $string
805     } elseif {$code == 3} {
806         return
807     } elseif {$code > 4} {
808         return -code $code $string
809     }
810     return $result
811 }
812
813 # gdb_test COMMAND PATTERN MESSAGE QUESTION RESPONSE
814 # Send a command to gdb; test the result.
815 #
816 # COMMAND is the command to execute, send to GDB with send_gdb.  If
817 #   this is the null string no command is sent.
818 # PATTERN is the pattern to match for a PASS, and must NOT include
819 #   the \r\n sequence immediately before the gdb prompt.
820 # MESSAGE is an optional message to be printed.  If this is
821 #   omitted, then the pass/fail messages use the command string as the
822 #   message.  (If this is the empty string, then sometimes we don't
823 #   call pass or fail at all; I don't understand this at all.)
824 # QUESTION is a question GDB may ask in response to COMMAND, like
825 #   "are you sure?"
826 # RESPONSE is the response to send if QUESTION appears.
827 #
828 # Returns:
829 #    1 if the test failed,
830 #    0 if the test passes,
831 #   -1 if there was an internal error.
832 #  
833 proc gdb_test { args } {
834     global verbose
835     global gdb_prompt
836     global GDB
837     upvar timeout timeout
838
839     if [llength $args]>2 then {
840         set message [lindex $args 2]
841     } else {
842         set message [lindex $args 0]
843     }
844     set command [lindex $args 0]
845     set pattern [lindex $args 1]
846
847     if [llength $args]==5 {
848         set question_string [lindex $args 3];
849         set response_string [lindex $args 4];
850     } else {
851         set question_string "^FOOBAR$"
852     }
853
854     return [gdb_test_multiple $command $message {
855         -re "\[\r\n\]*($pattern)\[\r\n\]+$gdb_prompt $" {
856             if ![string match "" $message] then {
857                 pass "$message"
858             }
859         }
860         -re "(${question_string})$" {
861             send_gdb "$response_string\n";
862             exp_continue;
863         }
864      }]
865 }
866 \f
867 # Test that a command gives an error.  For pass or fail, return
868 # a 1 to indicate that more tests can proceed.  However a timeout
869 # is a serious error, generates a special fail message, and causes
870 # a 0 to be returned to indicate that more tests are likely to fail
871 # as well.
872
873 proc test_print_reject { args } {
874     global gdb_prompt
875     global verbose
876
877     if [llength $args]==2 then {
878         set expectthis [lindex $args 1]
879     } else {
880         set expectthis "should never match this bogus string"
881     }
882     set sendthis [lindex $args 0]
883     if $verbose>2 then {
884         send_user "Sending \"$sendthis\" to gdb\n"
885         send_user "Looking to match \"$expectthis\"\n"
886     }
887     send_gdb "$sendthis\n"
888     #FIXME: Should add timeout as parameter.
889     gdb_expect {
890         -re "A .* in expression.*\\.*$gdb_prompt $" {
891             pass "reject $sendthis"
892             return 1
893         }
894         -re "Invalid syntax in expression.*$gdb_prompt $" {
895             pass "reject $sendthis"
896             return 1
897         }
898         -re "Junk after end of expression.*$gdb_prompt $" {
899             pass "reject $sendthis"
900             return 1
901         }
902         -re "Invalid number.*$gdb_prompt $" {
903             pass "reject $sendthis"
904             return 1
905         }
906         -re "Invalid character constant.*$gdb_prompt $" {
907             pass "reject $sendthis"
908             return 1
909         }
910         -re "No symbol table is loaded.*$gdb_prompt $" {
911             pass "reject $sendthis"
912             return 1
913         }
914         -re "No symbol .* in current context.*$gdb_prompt $" {
915             pass "reject $sendthis"
916             return 1
917         }
918         -re "Unmatched single quote.*$gdb_prompt $" {
919             pass "reject $sendthis"
920             return 1
921         }
922         -re "A character constant must contain at least one character.*$gdb_prompt $" {
923             pass "reject $sendthis"
924             return 1
925         }
926         -re "$expectthis.*$gdb_prompt $" {
927             pass "reject $sendthis"
928             return 1
929         }
930         -re ".*$gdb_prompt $" {
931             fail "reject $sendthis"
932             return 1
933         }
934         default {
935             fail "reject $sendthis (eof or timeout)"
936             return 0
937         }
938     }
939 }
940 \f
941 # Given an input string, adds backslashes as needed to create a
942 # regexp that will match the string.
943
944 proc string_to_regexp {str} {
945     set result $str
946     regsub -all {[]*+.|()^$\[\\]} $str {\\&} result
947     return $result
948 }
949
950 # Same as gdb_test, but the second parameter is not a regexp,
951 # but a string that must match exactly.
952
953 proc gdb_test_exact { args } {
954     upvar timeout timeout
955
956     set command [lindex $args 0]
957
958     # This applies a special meaning to a null string pattern.  Without
959     # this, "$pattern\r\n$gdb_prompt $" will match anything, including error
960     # messages from commands that should have no output except a new
961     # prompt.  With this, only results of a null string will match a null
962     # string pattern.
963
964     set pattern [lindex $args 1]
965     if [string match $pattern ""] {
966         set pattern [string_to_regexp [lindex $args 0]]
967     } else {
968         set pattern [string_to_regexp [lindex $args 1]]
969     }
970
971     # It is most natural to write the pattern argument with only
972     # embedded \n's, especially if you are trying to avoid Tcl quoting
973     # problems.  But gdb_expect really wants to see \r\n in patterns.  So
974     # transform the pattern here.  First transform \r\n back to \n, in
975     # case some users of gdb_test_exact already do the right thing.
976     regsub -all "\r\n" $pattern "\n" pattern
977     regsub -all "\n" $pattern "\r\n" pattern
978     if [llength $args]==3 then {
979         set message [lindex $args 2]
980     } else {
981         set message $command
982     }
983
984     return [gdb_test $command $pattern $message]
985 }
986 \f
987 proc gdb_reinitialize_dir { subdir } {
988     global gdb_prompt
989
990     if [is_remote host] {
991         return "";
992     }
993     send_gdb "dir\n"
994     gdb_expect 60 {
995         -re "Reinitialize source path to empty.*y or n. " {
996             send_gdb "y\n"
997             gdb_expect 60 {
998                 -re "Source directories searched.*$gdb_prompt $" {
999                     send_gdb "dir $subdir\n"
1000                     gdb_expect 60 {
1001                         -re "Source directories searched.*$gdb_prompt $" {
1002                             verbose "Dir set to $subdir"
1003                         }
1004                         -re "$gdb_prompt $" {
1005                             perror "Dir \"$subdir\" failed."
1006                         }
1007                     }
1008                 }
1009                 -re "$gdb_prompt $" {
1010                     perror "Dir \"$subdir\" failed."
1011                 }
1012             }
1013         }
1014         -re "$gdb_prompt $" {
1015             perror "Dir \"$subdir\" failed."
1016         }
1017     }
1018 }
1019
1020 #
1021 # gdb_exit -- exit the GDB, killing the target program if necessary
1022 #
1023 proc default_gdb_exit {} {
1024     global GDB
1025     global INTERNAL_GDBFLAGS GDBFLAGS
1026     global verbose
1027     global gdb_spawn_id;
1028
1029     gdb_stop_suppressing_tests;
1030
1031     if ![info exists gdb_spawn_id] {
1032         return;
1033     }
1034
1035     verbose "Quitting $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
1036
1037     if { [is_remote host] && [board_info host exists fileid] } {
1038         send_gdb "quit\n";
1039         gdb_expect 10 {
1040             -re "y or n" {
1041                 send_gdb "y\n";
1042                 exp_continue;
1043             }
1044             -re "DOSEXIT code" { }
1045             default { }
1046         }
1047     }
1048
1049     if ![is_remote host] {
1050         remote_close host;
1051     }
1052     unset gdb_spawn_id
1053 }
1054
1055 # Load a file into the debugger.
1056 # The return value is 0 for success, -1 for failure.
1057 #
1058 # This procedure also set the global variable GDB_FILE_CMD_DEBUG_INFO
1059 # to one of these values:
1060 #
1061 #   debug    file was loaded successfully and has debug information
1062 #   nodebug  file was loaded successfully and has no debug information
1063 #   fail     file was not loaded
1064 #
1065 # I tried returning this information as part of the return value,
1066 # but ran into a mess because of the many re-implementations of
1067 # gdb_load in config/*.exp.
1068 #
1069 # TODO: gdb.base/sepdebug.exp and gdb.stabs/weird.exp might be able to use
1070 # this if they can get more information set.
1071
1072 proc gdb_file_cmd { arg } {
1073     global gdb_prompt
1074     global verbose
1075     global GDB
1076     global last_loaded_file
1077
1078     set last_loaded_file $arg
1079
1080     # Set whether debug info was found.
1081     # Default to "fail".
1082     global gdb_file_cmd_debug_info
1083     set gdb_file_cmd_debug_info "fail"
1084
1085     if [is_remote host] {
1086         set arg [remote_download host $arg]
1087         if { $arg == "" } {
1088             perror "download failed"
1089             return -1
1090         }
1091     }
1092
1093     # The file command used to kill the remote target.  For the benefit
1094     # of the testsuite, preserve this behavior.
1095     send_gdb "kill\n"
1096     gdb_expect 120 {
1097         -re "Kill the program being debugged. .y or n. $" {
1098             send_gdb "y\n"
1099             verbose "\t\tKilling previous program being debugged"
1100             exp_continue
1101         }
1102         -re "$gdb_prompt $" {
1103             # OK.
1104         }
1105     }
1106
1107     send_gdb "file $arg\n"
1108     gdb_expect 120 {
1109         -re "Reading symbols from.*no debugging symbols found.*done.*$gdb_prompt $" {
1110             verbose "\t\tLoaded $arg into the $GDB with no debugging symbols"
1111             set gdb_file_cmd_debug_info "nodebug"
1112             return 0
1113         }
1114         -re "Reading symbols from.*done.*$gdb_prompt $" {
1115             verbose "\t\tLoaded $arg into the $GDB"
1116             set gdb_file_cmd_debug_info "debug"
1117             return 0
1118         }
1119         -re "Load new symbol table from \".*\".*y or n. $" {
1120             send_gdb "y\n"
1121             gdb_expect 120 {
1122                 -re "Reading symbols from.*done.*$gdb_prompt $" {
1123                     verbose "\t\tLoaded $arg with new symbol table into $GDB"
1124                     set gdb_file_cmd_debug_info "debug"
1125                     return 0
1126                 }
1127                 timeout {
1128                     perror "(timeout) Couldn't load $arg, other program already loaded."
1129                     return -1
1130                 }
1131             }
1132         }
1133         -re "No such file or directory.*$gdb_prompt $" {
1134             perror "($arg) No such file or directory"
1135             return -1
1136         }
1137         -re "$gdb_prompt $" {
1138             perror "couldn't load $arg into $GDB."
1139             return -1
1140             }
1141         timeout {
1142             perror "couldn't load $arg into $GDB (timed out)."
1143             return -1
1144         }
1145         eof {
1146             # This is an attempt to detect a core dump, but seems not to
1147             # work.  Perhaps we need to match .* followed by eof, in which
1148             # gdb_expect does not seem to have a way to do that.
1149             perror "couldn't load $arg into $GDB (end of file)."
1150             return -1
1151         }
1152     }
1153 }
1154
1155 #
1156 # start gdb -- start gdb running, default procedure
1157 #
1158 # When running over NFS, particularly if running many simultaneous
1159 # tests on different hosts all using the same server, things can
1160 # get really slow.  Give gdb at least 3 minutes to start up.
1161 #
1162 proc default_gdb_start { } {
1163     global verbose
1164     global GDB
1165     global INTERNAL_GDBFLAGS GDBFLAGS
1166     global gdb_prompt
1167     global timeout
1168     global gdb_spawn_id;
1169     global env
1170
1171     gdb_stop_suppressing_tests;
1172
1173     set env(LC_CTYPE) C
1174
1175     # Don't let a .inputrc file or an existing setting of INPUTRC mess up
1176     # the test results.  Even if /dev/null doesn't exist on the particular
1177     # platform, the readline library will use the default setting just by
1178     # failing to open the file.  OTOH, opening /dev/null successfully will
1179     # also result in the default settings being used since nothing will be
1180     # read from this file.
1181     set env(INPUTRC) "/dev/null"
1182
1183     # The gdb.base/readline.exp arrow key test relies on the standard VT100
1184     # bindings, so make sure that an appropriate terminal is selected.
1185     # The same bug doesn't show up if we use ^P / ^N instead.
1186     set env(TERM) "vt100"
1187
1188     verbose "Spawning $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
1189
1190     if [info exists gdb_spawn_id] {
1191         return 0;
1192     }
1193
1194     if ![is_remote host] {
1195         if { [which $GDB] == 0 } then {
1196             perror "$GDB does not exist."
1197             exit 1
1198         }
1199     }
1200     set res [remote_spawn host "$GDB $INTERNAL_GDBFLAGS $GDBFLAGS [host_info gdb_opts]"];
1201     if { $res < 0 || $res == "" } {
1202         perror "Spawning $GDB failed."
1203         return 1;
1204     }
1205     gdb_expect 360 {
1206         -re "\[\r\n\]$gdb_prompt $" {
1207             verbose "GDB initialized."
1208         }
1209         -re "$gdb_prompt $"     {
1210             perror "GDB never initialized."
1211             return -1
1212         }
1213         timeout {
1214             perror "(timeout) GDB never initialized after 10 seconds."
1215             remote_close host;
1216             return -1
1217         }
1218     }
1219     set gdb_spawn_id -1;
1220     # force the height to "unlimited", so no pagers get used
1221
1222     send_gdb "set height 0\n"
1223     gdb_expect 10 {
1224         -re "$gdb_prompt $" { 
1225             verbose "Setting height to 0." 2
1226         }
1227         timeout {
1228             warning "Couldn't set the height to 0"
1229         }
1230     }
1231     # force the width to "unlimited", so no wraparound occurs
1232     send_gdb "set width 0\n"
1233     gdb_expect 10 {
1234         -re "$gdb_prompt $" {
1235             verbose "Setting width to 0." 2
1236         }
1237         timeout {
1238             warning "Couldn't set the width to 0."
1239         }
1240     }
1241     return 0;
1242 }
1243
1244 # Examine the output of compilation to determine whether compilation
1245 # failed or not.  If it failed determine whether it is due to missing
1246 # compiler or due to compiler error.  Report pass, fail or unsupported
1247 # as appropriate
1248
1249 proc gdb_compile_test {src output} {
1250     if { $output == "" } {
1251         pass "compilation [file tail $src]"
1252     } elseif { [regexp {^[a-zA-Z_0-9]+: Can't find [^ ]+\.$} $output] } {
1253         unsupported "compilation [file tail $src]"
1254     } elseif { [regexp {.*: command not found[\r|\n]*$} $output] } {
1255         unsupported "compilation [file tail $src]"
1256     } else {
1257         verbose -log "compilation failed: $output" 2
1258         fail "compilation [file tail $src]"
1259     }
1260 }
1261
1262 # Return a 1 for configurations for which we don't even want to try to
1263 # test C++.
1264
1265 proc skip_cplus_tests {} {
1266     if { [istarget "h8300-*-*"] } {
1267         return 1
1268     }
1269
1270     # The C++ IO streams are too large for HC11/HC12 and are thus not
1271     # available.  The gdb C++ tests use them and don't compile.
1272     if { [istarget "m6811-*-*"] } {
1273         return 1
1274     }
1275     if { [istarget "m6812-*-*"] } {
1276         return 1
1277     }
1278     return 0
1279 }
1280
1281 # Return a 1 if I don't even want to try to test FORTRAN.
1282
1283 proc skip_fortran_tests {} {
1284     return 0
1285 }
1286
1287 # Return a 1 if I don't even want to try to test ada.
1288
1289 proc skip_ada_tests {} {
1290     return 0
1291 }
1292
1293 # Return a 1 if I don't even want to try to test java.
1294
1295 proc skip_java_tests {} {
1296     return 0
1297 }
1298
1299 # Return a 1 if we should skip shared library tests.
1300
1301 proc skip_shlib_tests {} {
1302     # Run the shared library tests on native systems.
1303     if {[isnative]} {
1304         return 0
1305     }
1306
1307     # An abbreviated list of remote targets where we should be able to
1308     # run shared library tests.
1309     if {([istarget *-*-linux*]
1310          || [istarget *-*-*bsd*]
1311          || [istarget *-*-solaris2*]
1312          || [istarget arm*-*-symbianelf*]
1313          || [istarget *-*-mingw*]
1314          || [istarget *-*-cygwin*]
1315          || [istarget *-*-pe*])} {
1316         return 0
1317     }
1318
1319     return 1
1320 }
1321
1322 # Run a test on the target to see if it supports vmx hardware.  Return 0 if so, 
1323 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
1324
1325 proc skip_altivec_tests {} {
1326     global skip_vmx_tests_saved
1327     global srcdir subdir gdb_prompt
1328
1329     # Use the cached value, if it exists.
1330     set me "skip_altivec_tests"
1331     if [info exists skip_vmx_tests_saved] {
1332         verbose "$me:  returning saved $skip_vmx_tests_saved" 2
1333         return $skip_vmx_tests_saved
1334     }
1335
1336     # Some simulators are known to not support VMX instructions.
1337     if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
1338         verbose "$me:  target known to not support VMX, returning 1" 2
1339         return [set skip_vmx_tests_saved 1]
1340     }
1341
1342     # Make sure we have a compiler that understands altivec.
1343     set compile_flags {debug nowarnings}
1344     if [get_compiler_info not-used] {
1345        warning "Could not get compiler info"
1346        return 1
1347     }
1348     if [test_compiler_info gcc*] {
1349         set compile_flags "$compile_flags additional_flags=-maltivec"
1350     } elseif [test_compiler_info xlc*] {
1351         set compile_flags "$compile_flags additional_flags=-qaltivec"
1352     } else {
1353         verbose "Could not compile with altivec support, returning 1" 2
1354         return 1
1355     }
1356
1357     # Set up, compile, and execute a test program containing VMX instructions.
1358     # Include the current process ID in the file names to prevent conflicts
1359     # with invocations for multiple testsuites.
1360     set src vmx[pid].c
1361     set exe vmx[pid].x
1362
1363     set f [open $src "w"]
1364     puts $f "int main() {"
1365     puts $f "#ifdef __MACH__"
1366     puts $f "  asm volatile (\"vor v0,v0,v0\");"
1367     puts $f "#else"
1368     puts $f "  asm volatile (\"vor 0,0,0\");"
1369     puts $f "#endif"
1370     puts $f "  return 0; }"
1371     close $f
1372
1373     verbose "$me:  compiling testfile $src" 2
1374     set lines [gdb_compile $src $exe executable $compile_flags]
1375     file delete $src
1376
1377     if ![string match "" $lines] then {
1378         verbose "$me:  testfile compilation failed, returning 1" 2
1379         return [set skip_vmx_tests_saved 1]
1380     }
1381
1382     # No error message, compilation succeeded so now run it via gdb.
1383
1384     gdb_exit
1385     gdb_start
1386     gdb_reinitialize_dir $srcdir/$subdir
1387     gdb_load "$exe"
1388     gdb_run_cmd
1389     gdb_expect {
1390         -re ".*Illegal instruction.*${gdb_prompt} $" {
1391             verbose -log "\n$me altivec hardware not detected" 
1392             set skip_vmx_tests_saved 1
1393         }
1394         -re ".*Program exited normally.*${gdb_prompt} $" {
1395             verbose -log "\n$me: altivec hardware detected" 
1396             set skip_vmx_tests_saved 0
1397         }
1398         default {
1399           warning "\n$me: default case taken"
1400             set skip_vmx_tests_saved 1
1401         }
1402     }
1403     gdb_exit
1404     remote_file build delete $exe
1405
1406     verbose "$me:  returning $skip_vmx_tests_saved" 2
1407     return $skip_vmx_tests_saved
1408 }
1409
1410 # Run a test on the target to see if it supports vmx hardware.  Return 0 if so,
1411 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
1412
1413 proc skip_vsx_tests {} {
1414     global skip_vsx_tests_saved
1415     global srcdir subdir gdb_prompt
1416
1417     # Use the cached value, if it exists.
1418     set me "skip_vsx_tests"
1419     if [info exists skip_vsx_tests_saved] {
1420         verbose "$me:  returning saved $skip_vsx_tests_saved" 2
1421         return $skip_vsx_tests_saved
1422     }
1423
1424     # Some simulators are known to not support Altivec instructions, so
1425     # they won't support VSX instructions as well.
1426     if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
1427         verbose "$me:  target known to not support VSX, returning 1" 2
1428         return [set skip_vsx_tests_saved 1]
1429     }
1430
1431     # Make sure we have a compiler that understands altivec.
1432     set compile_flags {debug nowarnings quiet}
1433     if [get_compiler_info not-used] {
1434        warning "Could not get compiler info"
1435        return 1
1436     }
1437     if [test_compiler_info gcc*] {
1438         set compile_flags "$compile_flags additional_flags=-mvsx"
1439     } elseif [test_compiler_info xlc*] {
1440         set compile_flags "$compile_flags additional_flags=-qvsx"
1441     } else {
1442         verbose "Could not compile with vsx support, returning 1" 2
1443         return 1
1444     }
1445
1446     set src vsx[pid].c
1447     set exe vsx[pid].x
1448
1449     set f [open $src "w"]
1450     puts $f "int main() {"
1451     puts $f "#ifdef __MACH__"
1452     puts $f "  asm volatile (\"lxvd2x v0,v0,v0\");"
1453     puts $f "#else"
1454     puts $f "  asm volatile (\"lxvd2x 0,0,0\");"
1455     puts $f "#endif"
1456     puts $f "  return 0; }"
1457     close $f
1458
1459     verbose "$me:  compiling testfile $src" 2
1460     set lines [gdb_compile $src $exe executable $compile_flags]
1461     file delete $src
1462
1463     if ![string match "" $lines] then {
1464         verbose "$me:  testfile compilation failed, returning 1" 2
1465         return [set skip_vsx_tests_saved 1]
1466     }
1467
1468     # No error message, compilation succeeded so now run it via gdb.
1469
1470     gdb_exit
1471     gdb_start
1472     gdb_reinitialize_dir $srcdir/$subdir
1473     gdb_load "$exe"
1474     gdb_run_cmd
1475     gdb_expect {
1476         -re ".*Illegal instruction.*${gdb_prompt} $" {
1477             verbose -log "\n$me VSX hardware not detected"
1478             set skip_vsx_tests_saved 1
1479         }
1480         -re ".*Program exited normally.*${gdb_prompt} $" {
1481             verbose -log "\n$me: VSX hardware detected"
1482             set skip_vsx_tests_saved 0
1483         }
1484         default {
1485           warning "\n$me: default case taken"
1486             set skip_vsx_tests_saved 1
1487         }
1488     }
1489     gdb_exit
1490     remote_file build delete $exe
1491
1492     verbose "$me:  returning $skip_vsx_tests_saved" 2
1493     return $skip_vsx_tests_saved
1494 }
1495
1496 # Skip all the tests in the file if you are not on an hppa running
1497 # hpux target.
1498
1499 proc skip_hp_tests {} {
1500     eval set skip_hp [ expr ![isnative] || ![istarget "hppa*-*-hpux*"] ]
1501     verbose "Skip hp tests is $skip_hp"
1502     return $skip_hp
1503 }
1504
1505 # Return whether we should skip tests for showing inlined functions in
1506 # backtraces.  Requires get_compiler_info and get_debug_format.
1507
1508 proc skip_inline_frame_tests {} {
1509     # GDB only recognizes inlining information in DWARF 2 (DWARF 3).
1510     if { ! [test_debug_format "DWARF 2"] } {
1511         return 1
1512     }
1513
1514     # GCC before 4.1 does not emit DW_AT_call_file / DW_AT_call_line.
1515     if { ([test_compiler_info "gcc-2-*"]
1516           || [test_compiler_info "gcc-3-*"]
1517           || [test_compiler_info "gcc-4-0-*"]) } {
1518         return 1
1519     }
1520
1521     return 0
1522 }
1523
1524 # Return whether we should skip tests for showing variables from
1525 # inlined functions.  Requires get_compiler_info and get_debug_format.
1526
1527 proc skip_inline_var_tests {} {
1528     # GDB only recognizes inlining information in DWARF 2 (DWARF 3).
1529     if { ! [test_debug_format "DWARF 2"] } {
1530         return 1
1531     }
1532
1533     return 0
1534 }
1535
1536 set compiler_info               "unknown"
1537 set gcc_compiled                0
1538 set hp_cc_compiler              0
1539 set hp_aCC_compiler             0
1540
1541 # Figure out what compiler I am using.
1542 #
1543 # BINFILE is a "compiler information" output file.  This implementation
1544 # does not use BINFILE.
1545 #
1546 # ARGS can be empty or "C++".  If empty, "C" is assumed.
1547 #
1548 # There are several ways to do this, with various problems.
1549 #
1550 # [ gdb_compile -E $ifile -o $binfile.ci ]
1551 # source $binfile.ci
1552 #
1553 #   Single Unix Spec v3 says that "-E -o ..." together are not
1554 #   specified.  And in fact, the native compiler on hp-ux 11 (among
1555 #   others) does not work with "-E -o ...".  Most targets used to do
1556 #   this, and it mostly worked, because it works with gcc.
1557 #
1558 # [ catch "exec $compiler -E $ifile > $binfile.ci" exec_output ]
1559 # source $binfile.ci
1560
1561 #   This avoids the problem with -E and -o together.  This almost works
1562 #   if the build machine is the same as the host machine, which is
1563 #   usually true of the targets which are not gcc.  But this code does
1564 #   not figure which compiler to call, and it always ends up using the C
1565 #   compiler.  Not good for setting hp_aCC_compiler.  Targets
1566 #   hppa*-*-hpux* and mips*-*-irix* used to do this.
1567 #
1568 # [ gdb_compile -E $ifile > $binfile.ci ]
1569 # source $binfile.ci
1570 #
1571 #   dejagnu target_compile says that it supports output redirection,
1572 #   but the code is completely different from the normal path and I
1573 #   don't want to sweep the mines from that path.  So I didn't even try
1574 #   this.
1575 #
1576 # set cppout [ gdb_compile $ifile "" preprocess $args quiet ]
1577 # eval $cppout
1578 #
1579 #   I actually do this for all targets now.  gdb_compile runs the right
1580 #   compiler, and TCL captures the output, and I eval the output.
1581 #
1582 #   Unfortunately, expect logs the output of the command as it goes by,
1583 #   and dejagnu helpfully prints a second copy of it right afterwards.
1584 #   So I turn off expect logging for a moment.
1585 #   
1586 # [ gdb_compile $ifile $ciexe_file executable $args ]
1587 # [ remote_exec $ciexe_file ]
1588 # [ source $ci_file.out ]
1589 #
1590 #   I could give up on -E and just do this.
1591 #   I didn't get desperate enough to try this.
1592 #
1593 # -- chastain 2004-01-06
1594
1595 proc get_compiler_info {binfile args} {
1596     # For compiler.c and compiler.cc
1597     global srcdir
1598
1599     # I am going to play with the log to keep noise out.
1600     global outdir
1601     global tool
1602
1603     # These come from compiler.c or compiler.cc
1604     global compiler_info
1605
1606     # Legacy global data symbols.
1607     global gcc_compiled
1608     global hp_cc_compiler
1609     global hp_aCC_compiler
1610
1611     # Choose which file to preprocess.
1612     set ifile "${srcdir}/lib/compiler.c"
1613     if { [llength $args] > 0 && [lindex $args 0] == "c++" } {
1614         set ifile "${srcdir}/lib/compiler.cc"
1615     }
1616
1617     # Run $ifile through the right preprocessor.
1618     # Toggle gdb.log to keep the compiler output out of the log.
1619     log_file
1620     if [is_remote host] {
1621         # We have to use -E and -o together, despite the comments
1622         # above, because of how DejaGnu handles remote host testing.
1623         set ppout "$outdir/compiler.i"
1624         gdb_compile "${ifile}" "$ppout" preprocess [list "$args" quiet]
1625         set file [open $ppout r]
1626         set cppout [read $file]
1627         close $file
1628     } else {
1629         set cppout [ gdb_compile "${ifile}" "" preprocess [list "$args" quiet] ]
1630     }
1631     log_file -a "$outdir/$tool.log" 
1632
1633     # Eval the output.
1634     set unknown 0
1635     foreach cppline [ split "$cppout" "\n" ] {
1636         if { [ regexp "^#" "$cppline" ] } {
1637             # line marker
1638         } elseif { [ regexp "^\[\n\r\t \]*$" "$cppline" ] } {
1639             # blank line
1640         } elseif { [ regexp "^\[\n\r\t \]*set\[\n\r\t \]" "$cppline" ] } {
1641             # eval this line
1642             verbose "get_compiler_info: $cppline" 2
1643             eval "$cppline"
1644         } else {
1645             # unknown line
1646             verbose -log "get_compiler_info: $cppline"
1647             set unknown 1
1648         }
1649     }
1650
1651     # Reset to unknown compiler if any diagnostics happened.
1652     if { $unknown } {
1653         set compiler_info "unknown"
1654     }
1655
1656     # Set the legacy symbols.
1657     set gcc_compiled     0
1658     set hp_cc_compiler   0
1659     set hp_aCC_compiler  0
1660     if { [regexp "^gcc-1-" "$compiler_info" ] } { set gcc_compiled 1 }
1661     if { [regexp "^gcc-2-" "$compiler_info" ] } { set gcc_compiled 2 }
1662     if { [regexp "^gcc-3-" "$compiler_info" ] } { set gcc_compiled 3 }
1663     if { [regexp "^gcc-4-" "$compiler_info" ] } { set gcc_compiled 4 }
1664     if { [regexp "^gcc-5-" "$compiler_info" ] } { set gcc_compiled 5 }
1665     if { [regexp "^hpcc-"  "$compiler_info" ] } { set hp_cc_compiler 1 }
1666     if { [regexp "^hpacc-" "$compiler_info" ] } { set hp_aCC_compiler 1 }
1667
1668     # Log what happened.
1669     verbose -log "get_compiler_info: $compiler_info"
1670
1671     # Most compilers will evaluate comparisons and other boolean
1672     # operations to 0 or 1.
1673     uplevel \#0 { set true 1 }
1674     uplevel \#0 { set false 0 }
1675
1676     # Use of aCC results in boolean results being displayed as
1677     # "true" or "false"
1678     if { $hp_aCC_compiler } {
1679       uplevel \#0 { set true true }
1680       uplevel \#0 { set false false }
1681     }
1682
1683     return 0;
1684 }
1685
1686 proc test_compiler_info { {compiler ""} } {
1687     global compiler_info
1688
1689      # if no arg, return the compiler_info string
1690
1691      if [string match "" $compiler] {
1692          if [info exists compiler_info] {
1693              return $compiler_info
1694          } else {
1695              perror "No compiler info found."
1696          }
1697      }
1698
1699     return [string match $compiler $compiler_info]
1700 }
1701
1702 proc current_target_name { } {
1703     global target_info
1704     if [info exists target_info(target,name)] {
1705         set answer $target_info(target,name)
1706     } else {
1707         set answer ""
1708     }
1709     return $answer
1710 }
1711
1712 set gdb_wrapper_initialized 0
1713 set gdb_wrapper_target ""
1714
1715 proc gdb_wrapper_init { args } {
1716     global gdb_wrapper_initialized;
1717     global gdb_wrapper_file;
1718     global gdb_wrapper_flags;
1719     global gdb_wrapper_target
1720
1721     if { $gdb_wrapper_initialized == 1 } { return; }
1722
1723     if {[target_info exists needs_status_wrapper] && \
1724             [target_info needs_status_wrapper] != "0"} {
1725         set result [build_wrapper "testglue.o"];
1726         if { $result != "" } {
1727             set gdb_wrapper_file [lindex $result 0];
1728             set gdb_wrapper_flags [lindex $result 1];
1729         } else {
1730             warning "Status wrapper failed to build."
1731         }
1732     }
1733     set gdb_wrapper_initialized 1
1734     set gdb_wrapper_target [current_target_name]
1735 }
1736
1737 # Some targets need to always link a special object in.  Save its path here.
1738 global gdb_saved_set_unbuffered_mode_obj
1739 set gdb_saved_set_unbuffered_mode_obj ""
1740
1741 proc gdb_compile {source dest type options} {
1742     global GDB_TESTCASE_OPTIONS;
1743     global gdb_wrapper_file;
1744     global gdb_wrapper_flags;
1745     global gdb_wrapper_initialized;
1746     global srcdir
1747     global objdir
1748     global gdb_saved_set_unbuffered_mode_obj
1749
1750     set outdir [file dirname $dest]
1751
1752     # Add platform-specific options if a shared library was specified using
1753     # "shlib=librarypath" in OPTIONS.
1754     set new_options ""
1755     set shlib_found 0
1756     set shlib_load 0
1757     foreach opt $options {
1758         if [regexp {^shlib=(.*)} $opt dummy_var shlib_name] {
1759             if [test_compiler_info "xlc-*"] {
1760                 # IBM xlc compiler doesn't accept shared library named other
1761                 # than .so: use "-Wl," to bypass this
1762                 lappend source "-Wl,$shlib_name"
1763             } elseif { ([istarget "*-*-mingw*"]
1764                         || [istarget *-*-cygwin*]
1765                         || [istarget *-*-pe*])} {
1766                 lappend source "${shlib_name}.a"
1767             } else {
1768                lappend source $shlib_name
1769             }
1770             if { $shlib_found == 0 } {
1771                 set shlib_found 1
1772                 if { ([istarget "*-*-mingw*"]
1773                       || [istarget *-*-cygwin*]) } {
1774                     lappend new_options "additional_flags=-Wl,--enable-auto-import"
1775                 }
1776             }
1777         } elseif { $opt == "shlib_load" } {
1778             set shlib_load 1
1779         } else {
1780             lappend new_options $opt
1781         }
1782     }
1783
1784     # We typically link to shared libraries using an absolute path, and
1785     # that's how they are found at runtime.  If we are going to
1786     # dynamically load one by basename, we must specify rpath.  If we
1787     # are using a remote host, DejaGNU will link to the shared library
1788     # using a relative path, so again we must specify an rpath.
1789     if { $shlib_load || ($shlib_found && [is_remote host]) } {
1790         if { ([istarget "*-*-mingw*"]
1791               || [istarget *-*-cygwin*]
1792               || [istarget *-*-pe*]
1793               || [istarget arm*-*-symbianelf*]
1794               || [istarget hppa*-*-hpux*])} {
1795             # Do not need anything.
1796         } elseif { [istarget *-*-openbsd*] } {
1797             lappend new_options "additional_flags=-Wl,-rpath,${outdir}"
1798         } else {
1799             if { $shlib_load } {
1800                 lappend new_options "libs=-ldl"
1801             }
1802             lappend new_options "additional_flags=-Wl,-rpath,\\\$ORIGIN"
1803         }
1804     }
1805     set options $new_options
1806
1807     if [target_info exists gdb_stub] {
1808         set options2 { "additional_flags=-Dusestubs" }
1809         lappend options "libs=[target_info gdb_stub]";
1810         set options [concat $options2 $options]
1811     }
1812     if [target_info exists is_vxworks] {
1813         set options2 { "additional_flags=-Dvxworks" }
1814         lappend options "libs=[target_info gdb_stub]";
1815         set options [concat $options2 $options]
1816     }
1817     if [info exists GDB_TESTCASE_OPTIONS] {
1818         lappend options "additional_flags=$GDB_TESTCASE_OPTIONS";
1819     }
1820     verbose "options are $options"
1821     verbose "source is $source $dest $type $options"
1822
1823     if { $gdb_wrapper_initialized == 0 } { gdb_wrapper_init }
1824
1825     if {[target_info exists needs_status_wrapper] && \
1826             [target_info needs_status_wrapper] != "0" && \
1827             [info exists gdb_wrapper_file]} {
1828         lappend options "libs=${gdb_wrapper_file}"
1829         lappend options "ldflags=${gdb_wrapper_flags}"
1830     }
1831
1832     # Replace the "nowarnings" option with the appropriate additional_flags
1833     # to disable compiler warnings.
1834     set nowarnings [lsearch -exact $options nowarnings]
1835     if {$nowarnings != -1} {
1836         if [target_info exists gdb,nowarnings_flag] {
1837             set flag "additional_flags=[target_info gdb,nowarnings_flag]"
1838         } else {
1839             set flag "additional_flags=-w"
1840         }
1841         set options [lreplace $options $nowarnings $nowarnings $flag]
1842     }
1843
1844     if { $type == "executable" } {
1845         if { ([istarget "*-*-mingw*"]
1846               || [istarget "*-*-*djgpp"]
1847               || [istarget "*-*-cygwin*"])} {
1848             # Force output to unbuffered mode, by linking in an object file
1849             # with a global contructor that calls setvbuf.
1850             #
1851             # Compile the special object seperatelly for two reasons:
1852             #  1) Insulate it from $options.
1853             #  2) Avoid compiling it for every gdb_compile invocation,
1854             #  which is time consuming, especially if we're remote
1855             #  host testing.
1856             #
1857             if { $gdb_saved_set_unbuffered_mode_obj == "" } {
1858                 verbose "compiling gdb_saved_set_unbuffered_obj"
1859                 set unbuf_src ${srcdir}/lib/set_unbuffered_mode.c
1860                 set unbuf_obj ${objdir}/set_unbuffered_mode.o
1861
1862                 set result [gdb_compile "${unbuf_src}" "${unbuf_obj}" object {nowarnings}]
1863                 if { $result != "" } {
1864                     return $result
1865                 }
1866
1867                 set gdb_saved_set_unbuffered_mode_obj ${objdir}/set_unbuffered_mode_saved.o
1868                 # Link a copy of the output object, because the
1869                 # original may be automatically deleted.
1870                 remote_exec host "cp -f $unbuf_obj $gdb_saved_set_unbuffered_mode_obj"
1871             } else {
1872                 verbose "gdb_saved_set_unbuffered_obj already compiled"
1873             }
1874
1875             # Rely on the internal knowledge that the global ctors are ran in
1876             # reverse link order.  In that case, we can use ldflags to
1877             # avoid copying the object file to the host multiple
1878             # times.
1879             # This object can only be added if standard libraries are
1880             # used. Thus, we need to disable it if -nostdlib option is used
1881             if {[lsearch -regexp $options "-nostdlib"] < 0 } {
1882                 lappend options "ldflags=$gdb_saved_set_unbuffered_mode_obj"
1883             }
1884         }
1885     }
1886
1887     set result [target_compile $source $dest $type $options];
1888
1889     # Prune uninteresting compiler (and linker) output.
1890     regsub "Creating library file: \[^\r\n\]*\[\r\n\]+" $result "" result
1891
1892     regsub "\[\r\n\]*$" "$result" "" result;
1893     regsub "^\[\r\n\]*" "$result" "" result;
1894     
1895     if {[lsearch $options quiet] < 0} {
1896         # We shall update this on a per language basis, to avoid
1897         # changing the entire testsuite in one go.
1898         if {[lsearch $options f77] >= 0} {
1899             gdb_compile_test $source $result
1900         } elseif { $result != "" } {
1901             clone_output "gdb compile failed, $result"
1902         }
1903     }
1904     return $result;
1905 }
1906
1907
1908 # This is just like gdb_compile, above, except that it tries compiling
1909 # against several different thread libraries, to see which one this
1910 # system has.
1911 proc gdb_compile_pthreads {source dest type options} {
1912     set built_binfile 0
1913     set why_msg "unrecognized error"
1914     foreach lib {-lpthreads -lpthread -lthread} {
1915         # This kind of wipes out whatever libs the caller may have
1916         # set.  Or maybe theirs will override ours.  How infelicitous.
1917         set options_with_lib [concat $options [list libs=$lib quiet]]
1918         set ccout [gdb_compile $source $dest $type $options_with_lib]
1919         switch -regexp -- $ccout {
1920             ".*no posix threads support.*" {
1921                 set why_msg "missing threads include file"
1922                 break
1923             }
1924             ".*cannot open -lpthread.*" {
1925                 set why_msg "missing runtime threads library"
1926             }
1927             ".*Can't find library for -lpthread.*" {
1928                 set why_msg "missing runtime threads library"
1929             }
1930             {^$} {
1931                 pass "successfully compiled posix threads test case"
1932                 set built_binfile 1
1933                 break
1934             }
1935         }
1936     }
1937     if {!$built_binfile} {
1938         unsupported "Couldn't compile $source: ${why_msg}"
1939         return -1
1940     }
1941 }
1942
1943 # Build a shared library from SOURCES.  You must use get_compiler_info
1944 # first.
1945
1946 proc gdb_compile_shlib {sources dest options} {
1947     set obj_options $options
1948
1949     switch -glob [test_compiler_info] {
1950         "xlc-*" {
1951             lappend obj_options "additional_flags=-qpic"
1952         }
1953         "gcc-*" {
1954             if { !([istarget "powerpc*-*-aix*"]
1955                    || [istarget "rs6000*-*-aix*"]
1956                    || [istarget "*-*-cygwin*"]
1957                    || [istarget "*-*-mingw*"]
1958                    || [istarget "*-*-pe*"]) } {
1959                 lappend obj_options "additional_flags=-fpic"
1960             }
1961         }
1962         default {
1963             switch -glob [istarget] {
1964                 "hppa*-hp-hpux*" {
1965                     lappend obj_options "additional_flags=+z"
1966                 }
1967                 "mips-sgi-irix*" {
1968                     # Disable SGI compiler's implicit -Dsgi
1969                     lappend obj_options "additional_flags=-Usgi"
1970                 } 
1971                 default {
1972                     # don't know what the compiler is...
1973                 }
1974             }
1975         }
1976     }
1977
1978     set outdir [file dirname $dest]
1979     set objects ""
1980     foreach source $sources {
1981        set sourcebase [file tail $source]
1982        if {[gdb_compile $source "${outdir}/${sourcebase}.o" object $obj_options] != ""} {
1983            return -1
1984        }
1985        lappend objects ${outdir}/${sourcebase}.o
1986     }
1987
1988     if [istarget "hppa*-*-hpux*"] {
1989        remote_exec build "ld -b ${objects} -o ${dest}"
1990     } else {
1991        set link_options $options
1992        if [test_compiler_info "xlc-*"] {
1993           lappend link_options "additional_flags=-qmkshrobj"
1994        } else {
1995           lappend link_options "additional_flags=-shared"
1996
1997            if { ([istarget "*-*-mingw*"]
1998                  || [istarget *-*-cygwin*]
1999                  || [istarget *-*-pe*])} {
2000                lappend link_options "additional_flags=-Wl,--out-implib,${dest}.a"
2001            }
2002        }
2003        if {[gdb_compile "${objects}" "${dest}" executable $link_options] != ""} {
2004            return -1
2005        }
2006     }
2007 }
2008
2009 # This is just like gdb_compile_pthreads, above, except that we always add the
2010 # objc library for compiling Objective-C programs
2011 proc gdb_compile_objc {source dest type options} {
2012     set built_binfile 0
2013     set why_msg "unrecognized error"
2014     foreach lib {-lobjc -lpthreads -lpthread -lthread solaris} {
2015         # This kind of wipes out whatever libs the caller may have
2016         # set.  Or maybe theirs will override ours.  How infelicitous.
2017         if { $lib == "solaris" } {
2018             set lib "-lpthread -lposix4"
2019         }
2020         if { $lib != "-lobjc" } {
2021           set lib "-lobjc $lib"
2022         }
2023         set options_with_lib [concat $options [list libs=$lib quiet]]
2024         set ccout [gdb_compile $source $dest $type $options_with_lib]
2025         switch -regexp -- $ccout {
2026             ".*no posix threads support.*" {
2027                 set why_msg "missing threads include file"
2028                 break
2029             }
2030             ".*cannot open -lpthread.*" {
2031                 set why_msg "missing runtime threads library"
2032             }
2033             ".*Can't find library for -lpthread.*" {
2034                 set why_msg "missing runtime threads library"
2035             }
2036             {^$} {
2037                 pass "successfully compiled objc with posix threads test case"
2038                 set built_binfile 1
2039                 break
2040             }
2041         }
2042     }
2043     if {!$built_binfile} {
2044         unsupported "Couldn't compile $source: ${why_msg}"
2045         return -1
2046     }
2047 }
2048
2049 proc send_gdb { string } {
2050     global suppress_flag;
2051     if { $suppress_flag } {
2052         return "suppressed";
2053     }
2054     return [remote_send host "$string"];
2055 }
2056
2057 #
2058 #
2059
2060 proc gdb_expect { args } {
2061     if { [llength $args] == 2  && [lindex $args 0] != "-re" } {
2062         set atimeout [lindex $args 0];
2063         set expcode [list [lindex $args 1]];
2064     } else {
2065         set expcode $args;
2066     }
2067
2068     upvar timeout timeout;
2069
2070     if [target_info exists gdb,timeout] {
2071         if [info exists timeout] {
2072             if { $timeout < [target_info gdb,timeout] } {
2073                 set gtimeout [target_info gdb,timeout];
2074             } else {
2075                 set gtimeout $timeout;
2076             }
2077         } else {
2078             set gtimeout [target_info gdb,timeout];
2079         }
2080     }
2081
2082     if ![info exists gtimeout] {
2083         global timeout;
2084         if [info exists timeout] {
2085             set gtimeout $timeout;
2086         }
2087     }
2088
2089     if [info exists atimeout] {
2090         if { ![info exists gtimeout] || $gtimeout < $atimeout } {
2091             set gtimeout $atimeout;
2092         }
2093     } else {
2094         if ![info exists gtimeout] {
2095             # Eeeeew.
2096             set gtimeout 60;
2097         }
2098     }
2099
2100     global suppress_flag;
2101     global remote_suppress_flag;
2102     if [info exists remote_suppress_flag] {
2103         set old_val $remote_suppress_flag;
2104     }
2105     if [info exists suppress_flag] {
2106         if { $suppress_flag } {
2107             set remote_suppress_flag 1;
2108         }
2109     }
2110     set code [catch \
2111         {uplevel remote_expect host $gtimeout $expcode} string];
2112     if [info exists old_val] {
2113         set remote_suppress_flag $old_val;
2114     } else {
2115         if [info exists remote_suppress_flag] {
2116             unset remote_suppress_flag;
2117         }
2118     }
2119
2120     if {$code == 1} {
2121         global errorInfo errorCode;
2122
2123         return -code error -errorinfo $errorInfo -errorcode $errorCode $string
2124     } elseif {$code == 2} {
2125         return -code return $string
2126     } elseif {$code == 3} {
2127         return
2128     } elseif {$code > 4} {
2129         return -code $code $string
2130     }
2131 }
2132
2133 # gdb_expect_list MESSAGE SENTINEL LIST -- expect a sequence of outputs
2134 #
2135 # Check for long sequence of output by parts.
2136 # MESSAGE: is the test message to be printed with the test success/fail.
2137 # SENTINEL: Is the terminal pattern indicating that output has finished.
2138 # LIST: is the sequence of outputs to match.
2139 # If the sentinel is recognized early, it is considered an error.
2140 #
2141 # Returns:
2142 #    1 if the test failed,
2143 #    0 if the test passes,
2144 #   -1 if there was an internal error.
2145 #
2146 proc gdb_expect_list {test sentinel list} {
2147     global gdb_prompt
2148     global suppress_flag
2149     set index 0
2150     set ok 1
2151     if { $suppress_flag } {
2152         set ok 0
2153         unresolved "${test}"
2154     }
2155     while { ${index} < [llength ${list}] } {
2156         set pattern [lindex ${list} ${index}]
2157         set index [expr ${index} + 1]
2158         if { ${index} == [llength ${list}] } {
2159             if { ${ok} } {
2160                 gdb_expect {
2161                     -re "${pattern}${sentinel}" {
2162                         # pass "${test}, pattern ${index} + sentinel"
2163                     }
2164                     -re "${sentinel}" {
2165                         fail "${test} (pattern ${index} + sentinel)"
2166                         set ok 0
2167                     }
2168                     -re ".*A problem internal to GDB has been detected" {
2169                         fail "${test} (GDB internal error)"
2170                         set ok 0
2171                         gdb_internal_error_resync
2172                     }
2173                     timeout {
2174                         fail "${test} (pattern ${index} + sentinel) (timeout)"
2175                         set ok 0
2176                     }
2177                 }
2178             } else {
2179                 # unresolved "${test}, pattern ${index} + sentinel"
2180             }
2181         } else {
2182             if { ${ok} } {
2183                 gdb_expect {
2184                     -re "${pattern}" {
2185                         # pass "${test}, pattern ${index}"
2186                     }
2187                     -re "${sentinel}" {
2188                         fail "${test} (pattern ${index})"
2189                         set ok 0
2190                     }
2191                     -re ".*A problem internal to GDB has been detected" {
2192                         fail "${test} (GDB internal error)"
2193                         set ok 0
2194                         gdb_internal_error_resync
2195                     }
2196                     timeout {
2197                         fail "${test} (pattern ${index}) (timeout)"
2198                         set ok 0
2199                     }
2200                 }
2201             } else {
2202                 # unresolved "${test}, pattern ${index}"
2203             }
2204         }
2205     }
2206     if { ${ok} } {
2207         pass "${test}"
2208         return 0
2209     } else {
2210         return 1
2211     }
2212 }
2213
2214 #
2215 #
2216 proc gdb_suppress_entire_file { reason } {
2217     global suppress_flag;
2218
2219     warning "$reason\n";
2220     set suppress_flag -1;
2221 }
2222
2223 #
2224 # Set suppress_flag, which will cause all subsequent calls to send_gdb and
2225 # gdb_expect to fail immediately (until the next call to 
2226 # gdb_stop_suppressing_tests).
2227 #
2228 proc gdb_suppress_tests { args } {
2229     global suppress_flag;
2230
2231     return;  # fnf - disable pending review of results where
2232              # testsuite ran better without this
2233     incr suppress_flag;
2234
2235     if { $suppress_flag == 1 } {
2236         if { [llength $args] > 0 } {
2237             warning "[lindex $args 0]\n";
2238         } else {
2239             warning "Because of previous failure, all subsequent tests in this group will automatically fail.\n";
2240         }
2241     }
2242 }
2243
2244 #
2245 # Clear suppress_flag.
2246 #
2247 proc gdb_stop_suppressing_tests { } {
2248     global suppress_flag;
2249
2250     if [info exists suppress_flag] {
2251         if { $suppress_flag > 0 } {
2252             set suppress_flag 0;
2253             clone_output "Tests restarted.\n";
2254         }
2255     } else {
2256         set suppress_flag 0;
2257     }
2258 }
2259
2260 proc gdb_clear_suppressed { } {
2261     global suppress_flag;
2262
2263     set suppress_flag 0;
2264 }
2265
2266 proc gdb_start { } {
2267     default_gdb_start
2268 }
2269
2270 proc gdb_exit { } {
2271     catch default_gdb_exit
2272 }
2273
2274 #
2275 # gdb_load_cmd -- load a file into the debugger.
2276 #                 ARGS - additional args to load command.
2277 #                 return a -1 if anything goes wrong.
2278 #
2279 proc gdb_load_cmd { args } {
2280     global gdb_prompt
2281
2282     if [target_info exists gdb_load_timeout] {
2283         set loadtimeout [target_info gdb_load_timeout]
2284     } else {
2285         set loadtimeout 1600
2286     }
2287     send_gdb "load $args\n"
2288     verbose "Timeout is now $loadtimeout seconds" 2
2289     gdb_expect $loadtimeout {
2290         -re "Loading section\[^\r\]*\r\n" {
2291             exp_continue
2292         }
2293         -re "Start address\[\r\]*\r\n" {
2294             exp_continue
2295         }
2296         -re "Transfer rate\[\r\]*\r\n" {
2297             exp_continue
2298         }
2299         -re "Memory access error\[^\r\]*\r\n" {
2300             perror "Failed to load program"
2301             return -1
2302         }
2303         -re "$gdb_prompt $" {
2304             return 0
2305         }
2306         -re "(.*)\r\n$gdb_prompt " {
2307             perror "Unexpected reponse from 'load' -- $expect_out(1,string)"
2308             return -1
2309         }
2310         timeout {
2311             perror "Timed out trying to load $args."
2312             return -1
2313         }
2314     }
2315     return -1
2316 }
2317
2318 # gdb_download
2319 #
2320 # Copy a file to the remote target and return its target filename.
2321 # Schedule the file to be deleted at the end of this test.
2322
2323 proc gdb_download { filename } {
2324     global cleanfiles
2325
2326     set destname [remote_download target $filename]
2327     lappend cleanfiles $destname
2328     return $destname
2329 }
2330
2331 # gdb_load_shlibs LIB...
2332 #
2333 # Copy the listed libraries to the target.
2334
2335 proc gdb_load_shlibs { args } {
2336     if {![is_remote target]} {
2337         return
2338     }
2339
2340     foreach file $args {
2341         gdb_download $file
2342     }
2343
2344     # Even if the target supplies full paths for shared libraries,
2345     # they may not be paths for this system.
2346     gdb_test "set solib-search-path [file dirname [lindex $args 0]]" "" ""
2347 }
2348
2349 #
2350 # gdb_load -- load a file into the debugger.
2351 # Many files in config/*.exp override this procedure.
2352 #
2353 proc gdb_load { arg } {
2354     return [gdb_file_cmd $arg]
2355 }
2356
2357 # gdb_reload -- load a file into the target.  Called before "running",
2358 # either the first time or after already starting the program once,
2359 # for remote targets.  Most files that override gdb_load should now
2360 # override this instead.
2361
2362 proc gdb_reload { } {
2363     # For the benefit of existing configurations, default to gdb_load.
2364     # Specifying no file defaults to the executable currently being
2365     # debugged.
2366     return [gdb_load ""]
2367 }
2368
2369 proc gdb_continue { function } {
2370     global decimal
2371
2372     return [gdb_test "continue" ".*Breakpoint $decimal, $function .*" "continue to $function"];
2373 }
2374
2375 proc default_gdb_init { args } {
2376     global gdb_wrapper_initialized
2377     global gdb_wrapper_target
2378     global cleanfiles
2379     
2380     set cleanfiles {}
2381
2382     gdb_clear_suppressed;
2383
2384     # Make sure that the wrapper is rebuilt
2385     # with the appropriate multilib option.
2386     if { $gdb_wrapper_target != [current_target_name] } {
2387         set gdb_wrapper_initialized 0
2388     }
2389     
2390     # Unlike most tests, we have a small number of tests that generate
2391     # a very large amount of output.  We therefore increase the expect
2392     # buffer size to be able to contain the entire test output.
2393     match_max -d 30000
2394     # Also set this value for the currently running GDB. 
2395     match_max [match_max -d]
2396
2397     # We want to add the name of the TCL testcase to the PASS/FAIL messages.
2398     if { [llength $args] > 0 } {
2399         global pf_prefix
2400
2401         set file [lindex $args 0];
2402
2403         set pf_prefix "[file tail [file dirname $file]]/[file tail $file]:";
2404     }
2405     global gdb_prompt;
2406     if [target_info exists gdb_prompt] {
2407         set gdb_prompt [target_info gdb_prompt];
2408     } else {
2409         set gdb_prompt "\\(gdb\\)"
2410     }
2411 }
2412
2413 proc gdb_init { args } {
2414     return [eval default_gdb_init $args];
2415 }
2416
2417 proc gdb_finish { } {
2418     global cleanfiles
2419
2420     # Exit first, so that the files are no longer in use.
2421     gdb_exit
2422
2423     if { [llength $cleanfiles] > 0 } {
2424         eval remote_file target delete $cleanfiles
2425         set cleanfiles {}
2426     }
2427 }
2428
2429 global debug_format
2430 set debug_format "unknown"
2431
2432 # Run the gdb command "info source" and extract the debugging format
2433 # information from the output and save it in debug_format.
2434
2435 proc get_debug_format { } {
2436     global gdb_prompt
2437     global verbose
2438     global expect_out
2439     global debug_format
2440
2441     set debug_format "unknown"
2442     send_gdb "info source\n"
2443     gdb_expect 10 {
2444         -re "Compiled with (.*) debugging format.\r\n.*$gdb_prompt $" {
2445             set debug_format $expect_out(1,string)
2446             verbose "debug format is $debug_format"
2447             return 1;
2448         }
2449         -re "No current source file.\r\n$gdb_prompt $" {
2450             perror "get_debug_format used when no current source file"
2451             return 0;
2452         }
2453         -re "$gdb_prompt $" {
2454             warning "couldn't check debug format (no valid response)."
2455             return 1;
2456         }
2457         timeout {
2458             warning "couldn't check debug format (timed out)."
2459             return 1;
2460         }
2461     }
2462 }
2463
2464 # Return true if FORMAT matches the debug format the current test was
2465 # compiled with.  FORMAT is a shell-style globbing pattern; it can use
2466 # `*', `[...]', and so on.
2467 #
2468 # This function depends on variables set by `get_debug_format', above.
2469
2470 proc test_debug_format {format} {
2471     global debug_format
2472
2473     return [expr [string match $format $debug_format] != 0]
2474 }
2475
2476 # Like setup_xfail, but takes the name of a debug format (DWARF 1,
2477 # COFF, stabs, etc).  If that format matches the format that the
2478 # current test was compiled with, then the next test is expected to
2479 # fail for any target.  Returns 1 if the next test or set of tests is
2480 # expected to fail, 0 otherwise (or if it is unknown).  Must have
2481 # previously called get_debug_format.
2482 proc setup_xfail_format { format } {
2483     set ret [test_debug_format $format];
2484
2485     if {$ret} then {
2486         setup_xfail "*-*-*"
2487     }
2488     return $ret;
2489 }
2490
2491 proc gdb_step_for_stub { } {
2492     global gdb_prompt;
2493
2494     if ![target_info exists gdb,use_breakpoint_for_stub] {
2495         if [target_info exists gdb_stub_step_command] {
2496             set command [target_info gdb_stub_step_command];
2497         } else {
2498             set command "step";
2499         }
2500         send_gdb "${command}\n";
2501         set tries 0;
2502         gdb_expect 60 {
2503             -re "(main.* at |.*in .*start).*$gdb_prompt" {
2504                 return;
2505             }
2506             -re ".*$gdb_prompt" {
2507                 incr tries;
2508                 if { $tries == 5 } {
2509                     fail "stepping out of breakpoint function";
2510                     return;
2511                 }
2512                 send_gdb "${command}\n";
2513                 exp_continue;
2514             }
2515             default {
2516                 fail "stepping out of breakpoint function";
2517                 return;
2518             }
2519         }
2520     }
2521     send_gdb "where\n";
2522     gdb_expect {
2523         -re "main\[^\r\n\]*at \(\[^:]+\):\(\[0-9\]+\)" {
2524             set file $expect_out(1,string);
2525             set linenum [expr $expect_out(2,string) + 1];
2526             set breakplace "${file}:${linenum}";
2527         }
2528         default {}
2529     }
2530     send_gdb "break ${breakplace}\n";
2531     gdb_expect 60 {
2532         -re "Breakpoint (\[0-9\]+) at.*$gdb_prompt" {
2533             set breakpoint $expect_out(1,string);
2534         }
2535         -re "Breakpoint (\[0-9\]+): file.*$gdb_prompt" {
2536             set breakpoint $expect_out(1,string);
2537         }
2538         default {}
2539     }
2540     send_gdb "continue\n";
2541     gdb_expect 60 {
2542         -re "Breakpoint ${breakpoint},.*$gdb_prompt" {
2543             gdb_test "delete $breakpoint" ".*" "";
2544             return;
2545         }
2546         default {}
2547     }
2548 }
2549
2550 # gdb_get_line_number TEXT [FILE]
2551 #
2552 # Search the source file FILE, and return the line number of the
2553 # first line containing TEXT.  If no match is found, return -1.
2554
2555 # TEXT is a string literal, not a regular expression.
2556 #
2557 # The default value of FILE is "$srcdir/$subdir/$srcfile".  If FILE is
2558 # specified, and does not start with "/", then it is assumed to be in
2559 # "$srcdir/$subdir".  This is awkward, and can be fixed in the future,
2560 # by changing the callers and the interface at the same time.
2561 # In particular: gdb.base/break.exp, gdb.base/condbreak.exp,
2562 # gdb.base/ena-dis-br.exp.
2563 #
2564 # Use this function to keep your test scripts independent of the
2565 # exact line numbering of the source file.  Don't write:
2566
2567 #   send_gdb "break 20"
2568
2569 # This means that if anyone ever edits your test's source file, 
2570 # your test could break.  Instead, put a comment like this on the
2571 # source file line you want to break at:
2572
2573 #   /* breakpoint spot: frotz.exp: test name */
2574
2575 # and then write, in your test script (which we assume is named
2576 # frotz.exp):
2577
2578 #   send_gdb "break [gdb_get_line_number "frotz.exp: test name"]\n"
2579 #
2580 # (Yes, Tcl knows how to handle the nested quotes and brackets.
2581 # Try this:
2582 #       $ tclsh
2583 #       % puts "foo [lindex "bar baz" 1]"
2584 #       foo baz
2585 #       % 
2586 # Tcl is quite clever, for a little stringy language.)
2587 #
2588 # ===
2589 #
2590 # The previous implementation of this procedure used the gdb search command.
2591 # This version is different:
2592 #
2593 #   . It works with MI, and it also works when gdb is not running.
2594 #
2595 #   . It operates on the build machine, not the host machine.
2596 #
2597 #   . For now, this implementation fakes a current directory of
2598 #     $srcdir/$subdir to be compatible with the old implementation.
2599 #     This will go away eventually and some callers will need to
2600 #     be changed.
2601 #
2602 #   . The TEXT argument is literal text and matches literally,
2603 #     not a regular expression as it was before.
2604 #
2605 #   . State changes in gdb, such as changing the current file
2606 #     and setting $_, no longer happen.
2607 #
2608 # After a bit of time we can forget about the differences from the
2609 # old implementation.
2610 #
2611 # --chastain 2004-08-05
2612
2613 proc gdb_get_line_number { text { file "" } } {
2614     global srcdir
2615     global subdir
2616     global srcfile
2617
2618     if { "$file" == "" } then {
2619         set file "$srcfile"
2620     }
2621     if { ! [regexp "^/" "$file"] } then {
2622         set file "$srcdir/$subdir/$file"
2623     }
2624
2625     if { [ catch { set fd [open "$file"] } message ] } then {
2626         perror "$message"
2627         return -1
2628     }
2629
2630     set found -1
2631     for { set line 1 } { 1 } { incr line } {
2632         if { [ catch { set nchar [gets "$fd" body] } message ] } then {
2633             perror "$message"
2634             return -1
2635         }
2636         if { $nchar < 0 } then {
2637             break
2638         }
2639         if { [string first "$text" "$body"] >= 0 } then {
2640             set found $line
2641             break
2642         }
2643     }
2644
2645     if { [ catch { close "$fd" } message ] } then {
2646         perror "$message"
2647         return -1
2648     }
2649
2650     return $found
2651 }
2652
2653 # gdb_continue_to_end:
2654 #       The case where the target uses stubs has to be handled specially. If a
2655 #       stub is used, we set a breakpoint at exit because we cannot rely on
2656 #       exit() behavior of a remote target.
2657
2658 # mssg is the error message that gets printed.
2659
2660 proc gdb_continue_to_end {mssg} {
2661   if [target_info exists use_gdb_stub] {
2662     if {![gdb_breakpoint "exit"]} {
2663       return 0
2664     }
2665     gdb_test "continue" "Continuing..*Breakpoint .*exit.*" \
2666       "continue until exit at $mssg"
2667   } else {
2668     # Continue until we exit.  Should not stop again.
2669     # Don't bother to check the output of the program, that may be
2670     # extremely tough for some remote systems.
2671     gdb_test "continue"\
2672       "Continuing.\[\r\n0-9\]+(... EXIT code 0\[\r\n\]+|Program exited normally\\.).*"\
2673       "continue until exit at $mssg"
2674   }
2675 }
2676
2677 proc rerun_to_main {} {
2678   global gdb_prompt
2679
2680   if [target_info exists use_gdb_stub] {
2681     gdb_run_cmd
2682     gdb_expect {
2683       -re ".*Breakpoint .*main .*$gdb_prompt $"\
2684               {pass "rerun to main" ; return 0}
2685       -re "$gdb_prompt $"\
2686               {fail "rerun to main" ; return 0}
2687       timeout {fail "(timeout) rerun to main" ; return 0}
2688     }
2689   } else {
2690     send_gdb "run\n"
2691     gdb_expect {
2692       -re "The program .* has been started already.*y or n. $" {
2693           send_gdb "y\n"
2694           exp_continue
2695       }
2696       -re "Starting program.*$gdb_prompt $"\
2697               {pass "rerun to main" ; return 0}
2698       -re "$gdb_prompt $"\
2699               {fail "rerun to main" ; return 0}
2700       timeout {fail "(timeout) rerun to main" ; return 0}
2701     }
2702   }
2703 }
2704
2705 # Print a message and return true if a test should be skipped
2706 # due to lack of floating point suport.
2707
2708 proc gdb_skip_float_test { msg } {
2709     if [target_info exists gdb,skip_float_tests] {
2710         verbose "Skipping test '$msg': no float tests.";
2711         return 1;
2712     }
2713     return 0;
2714 }
2715
2716 # Print a message and return true if a test should be skipped
2717 # due to lack of stdio support.
2718
2719 proc gdb_skip_stdio_test { msg } {
2720     if [target_info exists gdb,noinferiorio] {
2721         verbose "Skipping test '$msg': no inferior i/o.";
2722         return 1;
2723     }
2724     return 0;
2725 }
2726
2727 proc gdb_skip_bogus_test { msg } {
2728     return 0;
2729 }
2730
2731 # Return true if a test should be skipped due to lack of XML support
2732 # in the host GDB.
2733 # NOTE: This must be called while gdb is *not* running.
2734
2735 proc gdb_skip_xml_test { } {
2736     global gdb_prompt
2737     global srcdir
2738     global xml_missing_cached
2739
2740     if {[info exists xml_missing_cached]} {
2741         return $xml_missing_cached
2742     }
2743
2744     gdb_start
2745     set xml_missing_cached 0
2746     gdb_test_multiple "set tdesc filename ${srcdir}/gdb.xml/trivial.xml" "" {
2747         -re ".*XML support was disabled at compile time.*$gdb_prompt $" {
2748             set xml_missing_cached 1
2749         }
2750         -re ".*$gdb_prompt $" { }
2751     }
2752     gdb_exit
2753     return $xml_missing_cached
2754 }
2755
2756 # Note: the procedure gdb_gnu_strip_debug will produce an executable called
2757 # ${binfile}.dbglnk, which is just like the executable ($binfile) but without
2758 # the debuginfo. Instead $binfile has a .gnu_debuglink section which contains
2759 # the name of a debuginfo only file. This file will be stored in the 
2760 # gdb.base/.debug subdirectory.
2761
2762 # Functions for separate debug info testing
2763
2764 # starting with an executable:
2765 # foo --> original executable
2766
2767 # at the end of the process we have:
2768 # foo.stripped --> foo w/o debug info
2769 # .debug/foo.debug --> foo's debug info
2770 # foo --> like foo, but with a new .gnu_debuglink section pointing to foo.debug.
2771
2772 # Return the name of the file in which we should stor EXEC's separated
2773 # debug info. EXEC contains the full path.
2774 proc separate_debug_filename { exec } {
2775
2776     # In a .debug subdirectory off the same directory where the testcase
2777     # executable is going to be. Something like:
2778     # <your-path>/gdb/testsuite/gdb.base/.debug/blah.debug.
2779     # This is the default location where gdb expects to findi
2780     # the debug info file.
2781
2782     set exec_dir [file dirname $exec]
2783     set exec_file [file tail $exec]
2784     set debug_dir [file join $exec_dir ".debug"]
2785     set debug_file [file join $debug_dir "${exec_file}.debug"]
2786
2787     return $debug_file
2788 }
2789
2790 # Return the build-id hex string (usually 160 bits as 40 hex characters)
2791 # converted to the form: .build-id/ab/cdef1234...89.debug
2792 # Return "" if no build-id found.
2793 proc build_id_debug_filename_get { exec } {
2794     set tmp "${exec}-tmp"
2795     set objcopy_program [transform objcopy]
2796
2797     set result [catch "exec $objcopy_program -j .note.gnu.build-id -O binary $exec $tmp" output]
2798     verbose "result is $result"
2799     verbose "output is $output"
2800     if {$result == 1} {
2801         return ""
2802     }
2803     set fi [open $tmp]
2804     fconfigure $fi -translation binary
2805     # Skip the NOTE header.
2806     read $fi 16
2807     set data [read $fi]
2808     close $fi
2809     file delete $tmp
2810     if ![string compare $data ""] then {
2811         return ""
2812     }
2813     # Convert it to hex.
2814     binary scan $data H* data
2815     set data [regsub {^..} $data {\0/}]
2816     return ".build-id/${data}.debug";
2817 }
2818
2819 # Create stripped files for DEST, replacing it.  If ARGS is passed, it is a
2820 # list of optional flags.  The only currently supported flag is no-main,
2821 # which removes the symbol entry for main from the separate debug file.
2822
2823 proc gdb_gnu_strip_debug { dest args } {
2824
2825     set debug_file [separate_debug_filename $dest]
2826     set strip_to_file_program [transform strip]
2827     set objcopy_program [transform objcopy]
2828
2829     # Make sure the directory that will hold the separated debug
2830     # info actually exists.
2831     set debug_dir [file dirname $debug_file]
2832     if {! [file isdirectory $debug_dir]} {
2833         file mkdir $debug_dir
2834     }
2835
2836     set debug_link [file tail $debug_file]
2837     set stripped_file "${dest}.stripped"
2838
2839     # Get rid of the debug info, and store result in stripped_file
2840     # something like gdb/testsuite/gdb.base/blah.stripped.
2841     set result [catch "exec $strip_to_file_program --strip-debug ${dest} -o ${stripped_file}" output]
2842     verbose "result is $result"
2843     verbose "output is $output"
2844     if {$result == 1} {
2845       return 1
2846     }
2847
2848     # Workaround PR binutils/10802:
2849     # Preserve the 'x' bit also for PIEs (Position Independent Executables).
2850     set perm [file attributes ${dest} -permissions]
2851     file attributes ${stripped_file} -permissions $perm
2852
2853     # Get rid of everything but the debug info, and store result in debug_file
2854     # This will be in the .debug subdirectory, see above.
2855     set result [catch "exec $strip_to_file_program --only-keep-debug ${dest} -o ${debug_file}" output]
2856     verbose "result is $result"
2857     verbose "output is $output"
2858     if {$result == 1} {
2859       return 1
2860     }
2861
2862     # If no-main is passed, strip the symbol for main from the separate
2863     # file.  This is to simulate the behavior of elfutils's eu-strip, which
2864     # leaves the symtab in the original file only.  There's no way to get
2865     # objcopy or strip to remove the symbol table without also removing the
2866     # debugging sections, so this is as close as we can get.
2867     if { [llength $args] == 1 && [lindex $args 0] == "no-main" } {
2868         set result [catch "exec $objcopy_program -N main ${debug_file} ${debug_file}-tmp" output]
2869         verbose "result is $result"
2870         verbose "output is $output"
2871         if {$result == 1} {
2872             return 1
2873         }
2874         file delete "${debug_file}"
2875         file rename "${debug_file}-tmp" "${debug_file}"
2876     }
2877
2878     # Link the two previous output files together, adding the .gnu_debuglink
2879     # section to the stripped_file, containing a pointer to the debug_file,
2880     # save the new file in dest.
2881     # This will be the regular executable filename, in the usual location.
2882     set result [catch "exec $objcopy_program --add-gnu-debuglink=${debug_file} ${stripped_file} ${dest}" output]
2883     verbose "result is $result"
2884     verbose "output is $output"
2885     if {$result == 1} {
2886       return 1
2887     }
2888
2889     # Workaround PR binutils/10802:
2890     # Preserve the 'x' bit also for PIEs (Position Independent Executables).
2891     set perm [file attributes ${stripped_file} -permissions]
2892     file attributes ${dest} -permissions $perm
2893
2894     return 0
2895 }
2896
2897 # Test the output of GDB_COMMAND matches the pattern obtained
2898 # by concatenating all elements of EXPECTED_LINES.  This makes
2899 # it possible to split otherwise very long string into pieces.
2900 # If third argument is not empty, it's used as the name of the
2901 # test to be printed on pass/fail.
2902 proc help_test_raw { gdb_command expected_lines args } {
2903     set message $gdb_command
2904     if [llength $args]>0 then {
2905         set message [lindex $args 0]
2906     } 
2907     set expected_output [join $expected_lines ""]
2908     gdb_test "${gdb_command}" "${expected_output}" $message
2909 }
2910
2911 # Test the output of "help COMMNAD_CLASS". EXPECTED_INITIAL_LINES
2912 # are regular expressions that should match the beginning of output,
2913 # before the list of commands in that class.  The presence of 
2914 # command list and standard epilogue will be tested automatically.
2915 proc test_class_help { command_class expected_initial_lines args } {
2916     set l_stock_body {
2917         "List of commands\:.*\[\r\n\]+"
2918         "Type \"help\" followed by command name for full documentation\.\[\r\n\]+"
2919         "Type \"apropos word\" to search for commands related to \"word\"\.[\r\n\]+"
2920         "Command name abbreviations are allowed if unambiguous\." 
2921     }
2922     set l_entire_body [concat $expected_initial_lines $l_stock_body]
2923
2924     eval [list help_test_raw "help ${command_class}" $l_entire_body] $args
2925 }
2926
2927 # COMMAND_LIST should have either one element -- command to test, or
2928 # two elements -- abbreviated command to test, and full command the first
2929 # element is abbreviation of.
2930 # The command must be a prefix command.  EXPECTED_INITIAL_LINES
2931 # are regular expressions that should match the beginning of output,
2932 # before the list of subcommands.  The presence of 
2933 # subcommand list and standard epilogue will be tested automatically.
2934 proc test_prefix_command_help { command_list expected_initial_lines args } {
2935     set command [lindex $command_list 0]   
2936     if {[llength $command_list]>1} {        
2937         set full_command [lindex $command_list 1]
2938     } else {
2939         set full_command $command
2940     }
2941     # Use 'list' and not just {} because we want variables to
2942     # be expanded in this list.
2943     set l_stock_body [list\
2944          "List of $full_command subcommands\:.*\[\r\n\]+"\
2945          "Type \"help $full_command\" followed by $full_command subcommand name for full documentation\.\[\r\n\]+"\
2946          "Type \"apropos word\" to search for commands related to \"word\"\.\[\r\n\]+"\
2947          "Command name abbreviations are allowed if unambiguous\."]
2948     set l_entire_body [concat $expected_initial_lines $l_stock_body]
2949     if {[llength $args]>0} {
2950         help_test_raw "help ${command}" $l_entire_body [lindex $args 0]
2951     } else {
2952         help_test_raw "help ${command}" $l_entire_body
2953     }
2954 }
2955
2956 # Build executable named EXECUTABLE, from SOURCES.  If SOURCES are not
2957 # provided, uses $EXECUTABLE.c.  The TESTNAME paramer is the name of test
2958 # to pass to untested, if something is wrong.  OPTIONS are passed
2959 # to gdb_compile directly.
2960 proc build_executable { testname executable {sources ""} {options {debug}} } {
2961
2962     global objdir
2963     global subdir
2964     global srcdir
2965     if {[llength $sources]==0} {
2966         set sources ${executable}.c
2967     }
2968
2969     set binfile ${objdir}/${subdir}/${executable}
2970
2971     set objects {}
2972     for {set i 0} "\$i<[llength $sources]" {incr i} {
2973         set s [lindex $sources $i]
2974         if  { [gdb_compile "${srcdir}/${subdir}/${s}" "${binfile}${i}.o" object $options] != "" } {
2975             untested $testname
2976             return -1
2977         }
2978         lappend objects "${binfile}${i}.o"
2979     }
2980     
2981     if  { [gdb_compile $objects "${binfile}" executable $options] != "" } {
2982         untested $testname
2983         return -1
2984     }
2985
2986     if [get_compiler_info ${binfile}] {
2987         return -1
2988     }
2989     return 0
2990 }
2991
2992 # Starts fresh GDB binary and loads EXECUTABLE into GDB. EXECUTABLE is
2993 # the name of binary in ${objdir}/${subdir}.
2994 proc clean_restart { executable } {
2995     global srcdir
2996     global objdir
2997     global subdir
2998     set binfile ${objdir}/${subdir}/${executable}
2999
3000     gdb_exit
3001     gdb_start
3002     gdb_reinitialize_dir $srcdir/$subdir
3003     gdb_load ${binfile}
3004
3005     if [target_info exists gdb_stub] {
3006         gdb_step_for_stub;
3007     }    
3008 }
3009
3010 # Prepares for testing, by calling build_executable, and then clean_restart.
3011 # Please refer to build_executable for parameter description.
3012 proc prepare_for_testing { testname executable {sources ""} {options {debug}}} {
3013
3014     if {[build_executable $testname $executable $sources $options] == -1} {
3015         return -1
3016     }
3017     clean_restart $executable
3018
3019     return 0
3020 }
3021
3022 proc get_valueof { fmt exp default } {
3023     global gdb_prompt
3024
3025     set test "get valueof \"${exp}\""
3026     set val ${default}
3027     gdb_test_multiple "print${fmt} ${exp}" "$test" {
3028         -re "\\$\[0-9\]* = (.*)\[\r\n\]*$gdb_prompt $" {
3029             set val $expect_out(1,string)
3030             pass "$test ($val)"
3031         }
3032         timeout {
3033             fail "$test (timeout)"
3034         }
3035     }
3036     return ${val}
3037 }
3038
3039 proc get_integer_valueof { exp default } {
3040     global gdb_prompt
3041
3042     set test "get integer valueof \"${exp}\""
3043     set val ${default}
3044     gdb_test_multiple "print /d ${exp}" "$test" {
3045         -re "\\$\[0-9\]* = (\[-\]*\[0-9\]*).*$gdb_prompt $" {
3046             set val $expect_out(1,string)
3047             pass "$test ($val)"
3048         }
3049         timeout {
3050             fail "$test (timeout)"
3051         }
3052     }
3053     return ${val}
3054 }
3055
3056 proc get_hexadecimal_valueof { exp default } {
3057     global gdb_prompt
3058     send_gdb "print /x ${exp}\n"
3059     set test "get hexadecimal valueof \"${exp}\""
3060     gdb_expect {
3061         -re "\\$\[0-9\]* = (0x\[0-9a-zA-Z\]+).*$gdb_prompt $" {
3062             set val $expect_out(1,string)
3063             pass "$test"
3064         }
3065         timeout {
3066             set val ${default}
3067             fail "$test (timeout)"
3068         }
3069     }
3070     return ${val}
3071 }
3072
3073 proc get_sizeof { type default } {
3074     return [get_integer_valueof "sizeof (${type})" $default]
3075 }
3076
3077 # Log gdb command line and script if requested.
3078 if {[info exists TRANSCRIPT]} {
3079   rename send_gdb real_send_gdb
3080   rename remote_spawn real_remote_spawn
3081   rename remote_close real_remote_close
3082
3083   global gdb_transcript
3084   set gdb_transcript ""
3085
3086   global gdb_trans_count
3087   set gdb_trans_count 1
3088
3089   proc remote_spawn {args} {
3090     global gdb_transcript gdb_trans_count outdir
3091
3092     if {$gdb_transcript != ""} {
3093       close $gdb_transcript
3094     }
3095     set gdb_transcript [open [file join $outdir transcript.$gdb_trans_count] w]
3096     puts $gdb_transcript [lindex $args 1]
3097     incr gdb_trans_count
3098
3099     return [uplevel real_remote_spawn $args]
3100   }
3101
3102   proc remote_close {args} {
3103     global gdb_transcript
3104
3105     if {$gdb_transcript != ""} {
3106       close $gdb_transcript
3107       set gdb_transcript ""
3108     }
3109
3110     return [uplevel real_remote_close $args]
3111   }
3112
3113   proc send_gdb {args} {
3114     global gdb_transcript
3115
3116     if {$gdb_transcript != ""} {
3117       puts -nonewline $gdb_transcript [lindex $args 0]
3118     }
3119
3120     return [uplevel real_send_gdb $args]
3121   }
3122 }