50f2481fcc4b094c015da18820b498efa12c10d9
[platform/upstream/binutils.git] / gdb / testsuite / lib / gdb.exp
1 # Copyright 1992-2014 Free Software Foundation, Inc.
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 3 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16 # This file was written by Fred Fish. (fnf@cygnus.com)
17
18 # Generic gdb subroutines that should work for any target.  If these
19 # need to be modified for any target, it can be done with a variable
20 # or by passing arguments.
21
22 if {$tool == ""} {
23     # Tests would fail, logs on get_compiler_info() would be missing.
24     send_error "`site.exp' not found, run `make site.exp'!\n"
25     exit 2
26 }
27
28 load_lib libgloss.exp
29 load_lib cache.exp
30 load_lib gdb-utils.exp
31
32 global GDB
33
34 if [info exists TOOL_EXECUTABLE] {
35     set GDB $TOOL_EXECUTABLE
36 }
37 if ![info exists GDB] {
38     if ![is_remote host] {
39         set GDB [findfile $base_dir/../../gdb/gdb "$base_dir/../../gdb/gdb" [transform gdb]]
40     } else {
41         set GDB [transform gdb]
42     }
43 }
44 verbose "using GDB = $GDB" 2
45
46 # GDBFLAGS is available for the user to set on the command line.
47 # E.g. make check RUNTESTFLAGS=GDBFLAGS=mumble
48 # Testcases may use it to add additional flags, but they must:
49 # - append new flags, not overwrite
50 # - restore the original value when done
51 global GDBFLAGS
52 if ![info exists GDBFLAGS] {
53     set GDBFLAGS ""
54 }
55 verbose "using GDBFLAGS = $GDBFLAGS" 2
56
57 # Make the build data directory available to tests.
58 set BUILD_DATA_DIRECTORY "[pwd]/../data-directory"
59
60 # INTERNAL_GDBFLAGS contains flags that the testsuite requires.
61 global INTERNAL_GDBFLAGS
62 if ![info exists INTERNAL_GDBFLAGS] {
63     set INTERNAL_GDBFLAGS "-nw -nx -data-directory $BUILD_DATA_DIRECTORY"
64 }
65
66 # The variable gdb_prompt is a regexp which matches the gdb prompt.
67 # Set it if it is not already set.
68 global gdb_prompt
69 if ![info exists gdb_prompt] then {
70     set gdb_prompt "\[(\]gdb\[)\]"
71 }
72
73 # The variable fullname_syntax_POSIX is a regexp which matches a POSIX 
74 # absolute path ie. /foo/ 
75 set fullname_syntax_POSIX {/[^\n]*/}
76 # The variable fullname_syntax_UNC is a regexp which matches a Windows 
77 # UNC path ie. \\D\foo\ 
78 set fullname_syntax_UNC {\\\\[^\\]+\\[^\n]+\\}
79 # The variable fullname_syntax_DOS_CASE is a regexp which matches a 
80 # particular DOS case that GDB most likely will output
81 # ie. \foo\, but don't match \\.*\ 
82 set fullname_syntax_DOS_CASE {\\[^\\][^\n]*\\}
83 # The variable fullname_syntax_DOS is a regexp which matches a DOS path
84 # ie. a:\foo\ && a:foo\ 
85 set fullname_syntax_DOS {[a-zA-Z]:[^\n]*\\}
86 # The variable fullname_syntax is a regexp which matches what GDB considers
87 # an absolute path. It is currently debatable if the Windows style paths 
88 # d:foo and \abc should be considered valid as an absolute path.
89 # Also, the purpse of this regexp is not to recognize a well formed 
90 # absolute path, but to say with certainty that a path is absolute.
91 set fullname_syntax "($fullname_syntax_POSIX|$fullname_syntax_UNC|$fullname_syntax_DOS_CASE|$fullname_syntax_DOS)"
92
93 # Needed for some tests under Cygwin.
94 global EXEEXT
95 global env
96
97 if ![info exists env(EXEEXT)] {
98     set EXEEXT ""
99 } else {
100     set EXEEXT $env(EXEEXT)
101 }
102
103 set octal "\[0-7\]+"
104
105 set inferior_exited_re "(\\\[Inferior \[0-9\]+ \\(.*\\) exited)"
106
107 ### Only procedures should come after this point.
108
109 #
110 # gdb_version -- extract and print the version number of GDB
111 #
112 proc default_gdb_version {} {
113     global GDB
114     global INTERNAL_GDBFLAGS GDBFLAGS
115     global gdb_prompt
116     global inotify_pid
117
118     if {[info exists inotify_pid]} {
119         eval exec kill $inotify_pid
120     }
121
122     set output [remote_exec host "$GDB $INTERNAL_GDBFLAGS --version"]
123     set tmp [lindex $output 1]
124     set version ""
125     regexp " \[0-9\]\[^ \t\n\r\]+" "$tmp" version
126     if ![is_remote host] {
127         clone_output "[which $GDB] version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
128     } else {
129         clone_output "$GDB on remote host version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
130     }
131 }
132
133 proc gdb_version { } {
134     return [default_gdb_version]
135 }
136
137 #
138 # gdb_unload -- unload a file if one is loaded
139 # Return 0 on success, -1 on error.
140 #
141
142 proc gdb_unload {} {
143     global verbose
144     global GDB
145     global gdb_prompt
146     send_gdb "file\n"
147     gdb_expect 60 {
148         -re "No executable file now\[^\r\n\]*\[\r\n\]" { exp_continue }
149         -re "No symbol file now\[^\r\n\]*\[\r\n\]" { exp_continue }
150         -re "A program is being debugged already.*Are you sure you want to change the file.*y or n. $" {
151             send_gdb "y\n"
152             exp_continue
153         }
154         -re "Discard symbol table from .*y or n.*$" {
155             send_gdb "y\n"
156             exp_continue
157         }
158         -re "$gdb_prompt $" {}
159         timeout {
160             perror "couldn't unload file in $GDB (timeout)."
161             return -1
162         }
163     }
164     return 0
165 }
166
167 # Many of the tests depend on setting breakpoints at various places and
168 # running until that breakpoint is reached.  At times, we want to start
169 # with a clean-slate with respect to breakpoints, so this utility proc 
170 # lets us do this without duplicating this code everywhere.
171 #
172
173 proc delete_breakpoints {} {
174     global gdb_prompt
175
176     # we need a larger timeout value here or this thing just confuses
177     # itself.  May need a better implementation if possible. - guo
178     #
179     send_gdb "delete breakpoints\n"
180     gdb_expect 100 {
181          -re "Delete all breakpoints.*y or n.*$" {
182             send_gdb "y\n"
183             exp_continue
184         }
185          -re "$gdb_prompt $" { # This happens if there were no breakpoints
186             }
187          timeout { perror "Delete all breakpoints in delete_breakpoints (timeout)" ; return }
188     }
189     send_gdb "info breakpoints\n"
190     gdb_expect 100 {
191          -re "No breakpoints or watchpoints..*$gdb_prompt $" {}
192          -re "$gdb_prompt $" { perror "breakpoints not deleted" ; return }
193          -re "Delete all breakpoints.*or n.*$" {
194             send_gdb "y\n"
195             exp_continue
196         }
197          timeout { perror "info breakpoints (timeout)" ; return }
198     }
199 }
200
201 # Generic run command.
202 #
203 # The second pattern below matches up to the first newline *only*.
204 # Using ``.*$'' could swallow up output that we attempt to match
205 # elsewhere.
206 #
207 # N.B. This function does not wait for gdb to return to the prompt,
208 # that is the caller's responsibility.
209
210 proc gdb_run_cmd {args} {
211     global gdb_prompt use_gdb_stub
212
213     foreach command [gdb_init_commands] {
214         send_gdb "$command\n"
215         gdb_expect 30 {
216             -re "$gdb_prompt $" { }
217             default {
218                 perror "gdb_init_command for target failed"
219                 return
220             }
221         }
222     }
223
224     if $use_gdb_stub {
225         if [target_info exists gdb,do_reload_on_run] {
226             if { [gdb_reload] != 0 } {
227                 return
228             }
229             send_gdb "continue\n"
230             gdb_expect 60 {
231                 -re "Continu\[^\r\n\]*\[\r\n\]" {}
232                 default {}
233             }
234             return
235         }
236
237         if [target_info exists gdb,start_symbol] {
238             set start [target_info gdb,start_symbol]
239         } else {
240             set start "start"
241         }
242         send_gdb  "jump *$start\n"
243         set start_attempt 1
244         while { $start_attempt } {
245             # Cap (re)start attempts at three to ensure that this loop
246             # always eventually fails.  Don't worry about trying to be
247             # clever and not send a command when it has failed.
248             if [expr $start_attempt > 3] {
249                 perror "Jump to start() failed (retry count exceeded)"
250                 return
251             }
252             set start_attempt [expr $start_attempt + 1]
253             gdb_expect 30 {
254                 -re "Continuing at \[^\r\n\]*\[\r\n\]" {
255                     set start_attempt 0
256                 }
257                 -re "No symbol \"_start\" in current.*$gdb_prompt $" {
258                     perror "Can't find start symbol to run in gdb_run"
259                     return
260                 }
261                 -re "No symbol \"start\" in current.*$gdb_prompt $" {
262                     send_gdb "jump *_start\n"
263                 }
264                 -re "No symbol.*context.*$gdb_prompt $" {
265                     set start_attempt 0
266                 }
267                 -re "Line.* Jump anyway.*y or n. $" {
268                     send_gdb "y\n"
269                 }
270                 -re "The program is not being run.*$gdb_prompt $" {
271                     if { [gdb_reload] != 0 } {
272                         return
273                     }
274                     send_gdb "jump *$start\n"
275                 }
276                 timeout {
277                     perror "Jump to start() failed (timeout)"
278                     return
279                 }
280             }
281         }
282         return
283     }
284
285     if [target_info exists gdb,do_reload_on_run] {
286         if { [gdb_reload] != 0 } {
287             return
288         }
289     }
290     send_gdb "run $args\n"
291 # This doesn't work quite right yet.
292 # Use -notransfer here so that test cases (like chng-sym.exp)
293 # may test for additional start-up messages.
294    gdb_expect 60 {
295         -re "The program .* has been started already.*y or n. $" {
296             send_gdb "y\n"
297             exp_continue
298         }
299         -notransfer -re "Starting program: \[^\r\n\]*" {}
300         -notransfer -re "$gdb_prompt $" {
301             # There is no more input expected.
302         }
303     }
304 }
305
306 # Generic start command.  Return 0 if we could start the program, -1
307 # if we could not.
308 #
309 # N.B. This function does not wait for gdb to return to the prompt,
310 # that is the caller's responsibility.
311
312 proc gdb_start_cmd {args} {
313     global gdb_prompt use_gdb_stub
314
315     foreach command [gdb_init_commands] {
316         send_gdb "$command\n"
317         gdb_expect 30 {
318             -re "$gdb_prompt $" { }
319             default {
320                 perror "gdb_init_command for target failed"
321                 return -1
322             }
323         }
324     }
325
326     if $use_gdb_stub {
327         return -1
328     }
329
330     send_gdb "start $args\n"
331     # Use -notransfer here so that test cases (like chng-sym.exp)
332     # may test for additional start-up messages.
333     gdb_expect 60 {
334         -re "The program .* has been started already.*y or n. $" {
335             send_gdb "y\n"
336             exp_continue
337         }
338         -notransfer -re "Starting program: \[^\r\n\]*" {
339             return 0
340         }
341     }
342     return -1
343 }
344
345 # Set a breakpoint at FUNCTION.  If there is an additional argument it is
346 # a list of options; the supported options are allow-pending, temporary,
347 # message, no-message, and passfail.
348 # The result is 1 for success, 0 for failure.
349 #
350 # Note: The handling of message vs no-message is messed up, but it's based
351 # on historical usage.  By default this function does not print passes,
352 # only fails.
353 # no-message: turns off printing of fails (and passes, but they're already off)
354 # message: turns on printing of passes (and fails, but they're already on)
355
356 proc gdb_breakpoint { function args } {
357     global gdb_prompt
358     global decimal
359
360     set pending_response n
361     if {[lsearch -exact $args allow-pending] != -1} {
362         set pending_response y
363     }
364
365     set break_command "break"
366     set break_message "Breakpoint"
367     if {[lsearch -exact $args temporary] != -1} {
368         set break_command "tbreak"
369         set break_message "Temporary breakpoint"
370     }
371
372     set print_pass 0
373     set print_fail 1
374     set no_message_loc [lsearch -exact $args no-message]
375     set message_loc [lsearch -exact $args message]
376     # The last one to appear in args wins.
377     if { $no_message_loc > $message_loc } {
378         set print_fail 0
379     } elseif { $message_loc > $no_message_loc } {
380         set print_pass 1
381     }
382
383     set test_name "setting breakpoint at $function"
384
385     send_gdb "$break_command $function\n"
386     # The first two regexps are what we get with -g, the third is without -g.
387     gdb_expect 30 {
388         -re "$break_message \[0-9\]* at .*: file .*, line $decimal.\r\n$gdb_prompt $" {}
389         -re "$break_message \[0-9\]*: file .*, line $decimal.\r\n$gdb_prompt $" {}
390         -re "$break_message \[0-9\]* at .*$gdb_prompt $" {}
391         -re "$break_message \[0-9\]* \\(.*\\) pending.*$gdb_prompt $" {
392                 if {$pending_response == "n"} {
393                         if { $print_fail } {
394                                 fail $test_name
395                         }
396                         return 0
397                 }
398         }
399         -re "Make breakpoint pending.*y or \\\[n\\\]. $" { 
400                 send_gdb "$pending_response\n"
401                 exp_continue
402         }
403         -re "A problem internal to GDB has been detected" {
404                 if { $print_fail } {
405                     fail "$test_name (GDB internal error)"
406                 }
407                 gdb_internal_error_resync
408                 return 0
409         }
410         -re "$gdb_prompt $" {
411                 if { $print_fail } {
412                         fail $test_name
413                 }
414                 return 0
415         }
416         eof {
417                 if { $print_fail } {
418                         fail "$test_name (eof)"
419                 }
420                 return 0
421         }
422         timeout {
423                 if { $print_fail } {
424                         fail "$test_name (timeout)"
425                 }
426                 return 0
427         }
428     }
429     if { $print_pass } {
430         pass $test_name
431     }
432     return 1
433 }    
434
435 # Set breakpoint at function and run gdb until it breaks there.
436 # Since this is the only breakpoint that will be set, if it stops
437 # at a breakpoint, we will assume it is the one we want.  We can't
438 # just compare to "function" because it might be a fully qualified,
439 # single quoted C++ function specifier.
440 #
441 # If there are additional arguments, pass them to gdb_breakpoint.
442 # We recognize no-message/message ourselves.
443 # The default is no-message.
444 # no-message is messed up here, like gdb_breakpoint: to preserve
445 # historical usage fails are always printed by default.
446 # no-message: turns off printing of fails (and passes, but they're already off)
447 # message: turns on printing of passes (and fails, but they're already on)
448
449 proc runto { function args } {
450     global gdb_prompt
451     global decimal
452
453     delete_breakpoints
454
455     # Default to "no-message".
456     set args "no-message $args"
457
458     set print_pass 0
459     set print_fail 1
460     set no_message_loc [lsearch -exact $args no-message]
461     set message_loc [lsearch -exact $args message]
462     # The last one to appear in args wins.
463     if { $no_message_loc > $message_loc } {
464         set print_fail 0
465     } elseif { $message_loc > $no_message_loc } {
466         set print_pass 1
467     }
468
469     set test_name "running to $function in runto"
470
471     # We need to use eval here to pass our varargs args to gdb_breakpoint
472     # which is also a varargs function.
473     # But we also have to be careful because $function may have multiple
474     # elements, and we don't want Tcl to move the remaining elements after
475     # the first to $args.  That is why $function is wrapped in {}.
476     if ![eval gdb_breakpoint {$function} $args] {
477         return 0
478     }
479
480     gdb_run_cmd
481     
482     # the "at foo.c:36" output we get with -g.
483     # the "in func" output we get without -g.
484     gdb_expect 30 {
485         -re "Break.* at .*:$decimal.*$gdb_prompt $" {
486             if { $print_pass } {
487                 pass $test_name
488             }
489             return 1
490         }
491         -re "Breakpoint \[0-9\]*, \[0-9xa-f\]* in .*$gdb_prompt $" { 
492             if { $print_pass } {
493                 pass $test_name
494             }
495             return 1
496         }
497         -re "The target does not support running in non-stop mode.\r\n$gdb_prompt $" {
498             if { $print_fail } {
499                 unsupported "Non-stop mode not supported"
500             }
501             return 0
502         }
503         -re ".*A problem internal to GDB has been detected" {
504             if { $print_fail } {
505                 fail "$test_name (GDB internal error)"
506             }
507             gdb_internal_error_resync
508             return 0
509         }
510         -re "$gdb_prompt $" { 
511             if { $print_fail } {
512                 fail $test_name
513             }
514             return 0
515         }
516         eof { 
517             if { $print_fail } {
518                 fail "$test_name (eof)"
519             }
520             return 0
521         }
522         timeout { 
523             if { $print_fail } {
524                 fail "$test_name (timeout)"
525             }
526             return 0
527         }
528     }
529     if { $print_pass } {
530         pass $test_name
531     }
532     return 1
533 }
534
535 # Ask gdb to run until we hit a breakpoint at main.
536 #
537 # N.B. This function deletes all existing breakpoints.
538 # If you don't want that, use gdb_start_cmd.
539
540 proc runto_main { } {
541     return [runto main no-message]
542 }
543
544 ### Continue, and expect to hit a breakpoint.
545 ### Report a pass or fail, depending on whether it seems to have
546 ### worked.  Use NAME as part of the test name; each call to
547 ### continue_to_breakpoint should use a NAME which is unique within
548 ### that test file.
549 proc gdb_continue_to_breakpoint {name {location_pattern .*}} {
550     global gdb_prompt
551     set full_name "continue to breakpoint: $name"
552
553     gdb_test_multiple "continue" $full_name {
554         -re "(?:Breakpoint|Temporary breakpoint) .* (at|in) $location_pattern\r\n$gdb_prompt $" {
555             pass $full_name
556         }
557     }
558 }
559
560
561 # gdb_internal_error_resync:
562 #
563 # Answer the questions GDB asks after it reports an internal error
564 # until we get back to a GDB prompt.  Decline to quit the debugging
565 # session, and decline to create a core file.  Return non-zero if the
566 # resync succeeds.
567 #
568 # This procedure just answers whatever questions come up until it sees
569 # a GDB prompt; it doesn't require you to have matched the input up to
570 # any specific point.  However, it only answers questions it sees in
571 # the output itself, so if you've matched a question, you had better
572 # answer it yourself before calling this.
573 #
574 # You can use this function thus:
575 #
576 # gdb_expect {
577 #     ...
578 #     -re ".*A problem internal to GDB has been detected" {
579 #         gdb_internal_error_resync
580 #     }
581 #     ...
582 # }
583 #
584 proc gdb_internal_error_resync {} {
585     global gdb_prompt
586
587     verbose -log "Resyncing due to internal error."
588
589     set count 0
590     while {$count < 10} {
591         gdb_expect {
592             -re "Quit this debugging session\\? \\(y or n\\) $" {
593                 send_gdb "n\n"
594                 incr count
595             }
596             -re "Create a core file of GDB\\? \\(y or n\\) $" {
597                 send_gdb "n\n"
598                 incr count
599             }
600             -re "$gdb_prompt $" {
601                 # We're resynchronized.
602                 return 1
603             }
604             timeout {
605                 perror "Could not resync from internal error (timeout)"
606                 return 0
607             }
608         }
609     }
610     perror "Could not resync from internal error (resync count exceeded)"
611     return 0
612 }
613
614
615 # gdb_test_multiple COMMAND MESSAGE EXPECT_ARGUMENTS
616 # Send a command to gdb; test the result.
617 #
618 # COMMAND is the command to execute, send to GDB with send_gdb.  If
619 #   this is the null string no command is sent.
620 # MESSAGE is a message to be printed with the built-in failure patterns
621 #   if one of them matches.  If MESSAGE is empty COMMAND will be used.
622 # EXPECT_ARGUMENTS will be fed to expect in addition to the standard
623 #   patterns.  Pattern elements will be evaluated in the caller's
624 #   context; action elements will be executed in the caller's context.
625 #   Unlike patterns for gdb_test, these patterns should generally include
626 #   the final newline and prompt.
627 #
628 # Returns:
629 #    1 if the test failed, according to a built-in failure pattern
630 #    0 if only user-supplied patterns matched
631 #   -1 if there was an internal error.
632 #  
633 # You can use this function thus:
634 #
635 # gdb_test_multiple "print foo" "test foo" {
636 #    -re "expected output 1" {
637 #        pass "print foo"
638 #    }
639 #    -re "expected output 2" {
640 #        fail "print foo"
641 #    }
642 # }
643 #
644 # The standard patterns, such as "Inferior exited..." and "A problem
645 # ...", all being implicitly appended to that list.
646 #
647 proc gdb_test_multiple { command message user_code } {
648     global verbose use_gdb_stub
649     global gdb_prompt
650     global GDB
651     global inferior_exited_re
652     upvar timeout timeout
653     upvar expect_out expect_out
654
655     if { $message == "" } {
656         set message $command
657     }
658
659     if [string match "*\[\r\n\]" $command] {
660         error "Invalid trailing newline in \"$message\" test"
661     }
662
663     if [string match "*\[\r\n\]*" $message] {
664         error "Invalid newline in \"$message\" test"
665     }
666
667     if {$use_gdb_stub
668         && [regexp -nocase {^\s*(r|run|star|start|at|att|atta|attac|attach)\M} \
669             $command]} {
670         error "gdbserver does not support $command without extended-remote"
671     }
672
673     # TCL/EXPECT WART ALERT
674     # Expect does something very strange when it receives a single braced
675     # argument.  It splits it along word separators and performs substitutions.
676     # This means that { "[ab]" } is evaluated as "[ab]", but { "\[ab\]" } is
677     # evaluated as "\[ab\]".  But that's not how TCL normally works; inside a
678     # double-quoted list item, "\[ab\]" is just a long way of representing
679     # "[ab]", because the backslashes will be removed by lindex.
680
681     # Unfortunately, there appears to be no easy way to duplicate the splitting
682     # that expect will do from within TCL.  And many places make use of the
683     # "\[0-9\]" construct, so we need to support that; and some places make use
684     # of the "[func]" construct, so we need to support that too.  In order to
685     # get this right we have to substitute quoted list elements differently
686     # from braced list elements.
687
688     # We do this roughly the same way that Expect does it.  We have to use two
689     # lists, because if we leave unquoted newlines in the argument to uplevel
690     # they'll be treated as command separators, and if we escape newlines
691     # we mangle newlines inside of command blocks.  This assumes that the
692     # input doesn't contain a pattern which contains actual embedded newlines
693     # at this point!
694
695     regsub -all {\n} ${user_code} { } subst_code
696     set subst_code [uplevel list $subst_code]
697
698     set processed_code ""
699     set patterns ""
700     set expecting_action 0
701     set expecting_arg 0
702     foreach item $user_code subst_item $subst_code {
703         if { $item == "-n" || $item == "-notransfer" || $item == "-nocase" } {
704             lappend processed_code $item
705             continue
706         }
707         if { $item == "-indices" || $item == "-re" || $item == "-ex" } {
708             lappend processed_code $item
709             continue
710         }
711         if { $item == "-timeout" } {
712             set expecting_arg 1
713             lappend processed_code $item
714             continue
715         }
716         if { $expecting_arg } {
717             set expecting_arg 0
718             lappend processed_code $item
719             continue
720         }
721         if { $expecting_action } {
722             lappend processed_code "uplevel [list $item]"
723             set expecting_action 0
724             # Cosmetic, no effect on the list.
725             append processed_code "\n"
726             continue
727         }
728         set expecting_action 1
729         lappend processed_code $subst_item
730         if {$patterns != ""} {
731             append patterns "; "
732         }
733         append patterns "\"$subst_item\""
734     }
735
736     # Also purely cosmetic.
737     regsub -all {\r} $patterns {\\r} patterns
738     regsub -all {\n} $patterns {\\n} patterns
739
740     if $verbose>2 then {
741         send_user "Sending \"$command\" to gdb\n"
742         send_user "Looking to match \"$patterns\"\n"
743         send_user "Message is \"$message\"\n"
744     }
745
746     set result -1
747     set string "${command}\n"
748     if { $command != "" } {
749         set multi_line_re "\[\r\n\] *>"
750         while { "$string" != "" } {
751             set foo [string first "\n" "$string"]
752             set len [string length "$string"]
753             if { $foo < [expr $len - 1] } {
754                 set str [string range "$string" 0 $foo]
755                 if { [send_gdb "$str"] != "" } {
756                     global suppress_flag
757
758                     if { ! $suppress_flag } {
759                         perror "Couldn't send $command to GDB."
760                     }
761                     fail "$message"
762                     return $result
763                 }
764                 # since we're checking if each line of the multi-line
765                 # command are 'accepted' by GDB here,
766                 # we need to set -notransfer expect option so that
767                 # command output is not lost for pattern matching
768                 # - guo
769                 gdb_expect 2 {
770                     -notransfer -re "$multi_line_re$" { verbose "partial: match" 3 }
771                     timeout { verbose "partial: timeout" 3 }
772                 }
773                 set string [string range "$string" [expr $foo + 1] end]
774                 set multi_line_re "$multi_line_re.*\[\r\n\] *>"
775             } else {
776                 break
777             }
778         }
779         if { "$string" != "" } {
780             if { [send_gdb "$string"] != "" } {
781                 global suppress_flag
782
783                 if { ! $suppress_flag } {
784                     perror "Couldn't send $command to GDB."
785                 }
786                 fail "$message"
787                 return $result
788             }
789         }
790     }
791
792     if [target_info exists gdb,timeout] {
793         set tmt [target_info gdb,timeout]
794     } else {
795         if [info exists timeout] {
796             set tmt $timeout
797         } else {
798             global timeout
799             if [info exists timeout] {
800                 set tmt $timeout
801             } else {
802                 set tmt 60
803             }
804         }
805     }
806
807     set code {
808         -re ".*A problem internal to GDB has been detected" {
809             fail "$message (GDB internal error)"
810             gdb_internal_error_resync
811         }
812         -re "\\*\\*\\* DOSEXIT code.*" {
813             if { $message != "" } {
814                 fail "$message"
815             }
816             gdb_suppress_entire_file "GDB died"
817             set result -1
818         }
819     }
820     append code $processed_code
821     append code {
822         -re "Ending remote debugging.*$gdb_prompt $" {
823             if ![isnative] then {
824                 warning "Can`t communicate to remote target."
825             }
826             gdb_exit
827             gdb_start
828             set result -1
829         }
830         -re "Undefined\[a-z\]* command:.*$gdb_prompt $" {
831             perror "Undefined command \"$command\"."
832             fail "$message"
833             set result 1
834         }
835         -re "Ambiguous command.*$gdb_prompt $" {
836             perror "\"$command\" is not a unique command name."
837             fail "$message"
838             set result 1
839         }
840         -re "$inferior_exited_re with code \[0-9\]+.*$gdb_prompt $" {
841             if ![string match "" $message] then {
842                 set errmsg "$message (the program exited)"
843             } else {
844                 set errmsg "$command (the program exited)"
845             }
846             fail "$errmsg"
847             set result -1
848         }
849         -re "$inferior_exited_re normally.*$gdb_prompt $" {
850             if ![string match "" $message] then {
851                 set errmsg "$message (the program exited)"
852             } else {
853                 set errmsg "$command (the program exited)"
854             }
855             fail "$errmsg"
856             set result -1
857         }
858         -re "The program is not being run.*$gdb_prompt $" {
859             if ![string match "" $message] then {
860                 set errmsg "$message (the program is no longer running)"
861             } else {
862                 set errmsg "$command (the program is no longer running)"
863             }
864             fail "$errmsg"
865             set result -1
866         }
867         -re "\r\n$gdb_prompt $" {
868             if ![string match "" $message] then {
869                 fail "$message"
870             }
871             set result 1
872         }
873         "<return>" {
874             send_gdb "\n"
875             perror "Window too small."
876             fail "$message"
877             set result -1
878         }
879         -re "\\((y or n|y or \\\[n\\\]|\\\[y\\\] or n)\\) " {
880             send_gdb "n\n"
881             gdb_expect -re "$gdb_prompt $"
882             fail "$message (got interactive prompt)"
883             set result -1
884         }
885         -re "\\\[0\\\] cancel\r\n\\\[1\\\] all.*\r\n> $" {
886             send_gdb "0\n"
887             gdb_expect -re "$gdb_prompt $"
888             fail "$message (got breakpoint menu)"
889             set result -1
890         }
891         eof {
892             perror "Process no longer exists"
893             if { $message != "" } {
894                 fail "$message"
895             }
896             return -1
897         }
898         full_buffer {
899             perror "internal buffer is full."
900             fail "$message"
901             set result -1
902         }
903         timeout {
904             if ![string match "" $message] then {
905                 fail "$message (timeout)"
906             }
907             set result 1
908         }
909     }
910
911     set result 0
912     set code [catch {gdb_expect $tmt $code} string]
913     if {$code == 1} {
914         global errorInfo errorCode
915         return -code error -errorinfo $errorInfo -errorcode $errorCode $string
916     } elseif {$code > 1} {
917         return -code $code $string
918     }
919     return $result
920 }
921
922 # gdb_test COMMAND PATTERN MESSAGE QUESTION RESPONSE
923 # Send a command to gdb; test the result.
924 #
925 # COMMAND is the command to execute, send to GDB with send_gdb.  If
926 #   this is the null string no command is sent.
927 # PATTERN is the pattern to match for a PASS, and must NOT include
928 #   the \r\n sequence immediately before the gdb prompt.
929 # MESSAGE is an optional message to be printed.  If this is
930 #   omitted, then the pass/fail messages use the command string as the
931 #   message.  (If this is the empty string, then sometimes we don't
932 #   call pass or fail at all; I don't understand this at all.)
933 # QUESTION is a question GDB may ask in response to COMMAND, like
934 #   "are you sure?"
935 # RESPONSE is the response to send if QUESTION appears.
936 #
937 # Returns:
938 #    1 if the test failed,
939 #    0 if the test passes,
940 #   -1 if there was an internal error.
941 #  
942 proc gdb_test { args } {
943     global verbose
944     global gdb_prompt
945     global GDB
946     upvar timeout timeout
947
948     if [llength $args]>2 then {
949         set message [lindex $args 2]
950     } else {
951         set message [lindex $args 0]
952     }
953     set command [lindex $args 0]
954     set pattern [lindex $args 1]
955
956     if [llength $args]==5 {
957         set question_string [lindex $args 3]
958         set response_string [lindex $args 4]
959     } else {
960         set question_string "^FOOBAR$"
961     }
962
963     return [gdb_test_multiple $command $message {
964         -re "\[\r\n\]*($pattern)\[\r\n\]+$gdb_prompt $" {
965             if ![string match "" $message] then {
966                 pass "$message"
967             }
968         }
969         -re "(${question_string})$" {
970             send_gdb "$response_string\n"
971             exp_continue
972         }
973      }]
974 }
975
976 # gdb_test_no_output COMMAND MESSAGE
977 # Send a command to GDB and verify that this command generated no output.
978 #
979 # See gdb_test_multiple for a description of the COMMAND and MESSAGE
980 # parameters.  If MESSAGE is ommitted, then COMMAND will be used as
981 # the message.  (If MESSAGE is the empty string, then sometimes we do not
982 # call pass or fail at all; I don't understand this at all.)
983
984 proc gdb_test_no_output { args } {
985     global gdb_prompt
986     set command [lindex $args 0]
987     if [llength $args]>1 then {
988         set message [lindex $args 1]
989     } else {
990         set message $command
991     }
992
993     set command_regex [string_to_regexp $command]
994     gdb_test_multiple $command $message {
995         -re "^$command_regex\r\n$gdb_prompt $" {
996             if ![string match "" $message] then {
997                 pass "$message"
998             }
999         }
1000     }
1001 }
1002
1003 # Send a command and then wait for a sequence of outputs.
1004 # This is useful when the sequence is long and contains ".*", a single
1005 # regexp to match the entire output can get a timeout much easier.
1006 #
1007 # COMMAND is the command to send.
1008 # TEST_NAME is passed to pass/fail.  COMMAND is used if TEST_NAME is "".
1009 # EXPECTED_OUTPUT_LIST is a list of regexps of expected output, which are
1010 # processed in order, and all must be present in the output.
1011 #
1012 # It is unnecessary to specify ".*" at the beginning or end of any regexp,
1013 # there is an implicit ".*" between each element of EXPECTED_OUTPUT_LIST.
1014 # There is also an implicit ".*" between the last regexp and the gdb prompt.
1015 #
1016 # Like gdb_test and gdb_test_multiple, the output is expected to end with the
1017 # gdb prompt, which must not be specified in EXPECTED_OUTPUT_LIST.
1018 #
1019 # Returns:
1020 #    1 if the test failed,
1021 #    0 if the test passes,
1022 #   -1 if there was an internal error.
1023
1024 proc gdb_test_sequence { command test_name expected_output_list } {
1025     global gdb_prompt
1026     if { $test_name == "" } {
1027         set test_name $command
1028     }
1029     lappend expected_output_list ""; # implicit ".*" before gdb prompt
1030     send_gdb "$command\n"
1031     return [gdb_expect_list $test_name "$gdb_prompt $" $expected_output_list]
1032 }
1033
1034 \f
1035 # Test that a command gives an error.  For pass or fail, return
1036 # a 1 to indicate that more tests can proceed.  However a timeout
1037 # is a serious error, generates a special fail message, and causes
1038 # a 0 to be returned to indicate that more tests are likely to fail
1039 # as well.
1040
1041 proc test_print_reject { args } {
1042     global gdb_prompt
1043     global verbose
1044
1045     if [llength $args]==2 then {
1046         set expectthis [lindex $args 1]
1047     } else {
1048         set expectthis "should never match this bogus string"
1049     }
1050     set sendthis [lindex $args 0]
1051     if $verbose>2 then {
1052         send_user "Sending \"$sendthis\" to gdb\n"
1053         send_user "Looking to match \"$expectthis\"\n"
1054     }
1055     send_gdb "$sendthis\n"
1056     #FIXME: Should add timeout as parameter.
1057     gdb_expect {
1058         -re "A .* in expression.*\\.*$gdb_prompt $" {
1059             pass "reject $sendthis"
1060             return 1
1061         }
1062         -re "Invalid syntax in expression.*$gdb_prompt $" {
1063             pass "reject $sendthis"
1064             return 1
1065         }
1066         -re "Junk after end of expression.*$gdb_prompt $" {
1067             pass "reject $sendthis"
1068             return 1
1069         }
1070         -re "Invalid number.*$gdb_prompt $" {
1071             pass "reject $sendthis"
1072             return 1
1073         }
1074         -re "Invalid character constant.*$gdb_prompt $" {
1075             pass "reject $sendthis"
1076             return 1
1077         }
1078         -re "No symbol table is loaded.*$gdb_prompt $" {
1079             pass "reject $sendthis"
1080             return 1
1081         }
1082         -re "No symbol .* in current context.*$gdb_prompt $" {
1083             pass "reject $sendthis"
1084             return 1
1085         }
1086         -re "Unmatched single quote.*$gdb_prompt $" {
1087             pass "reject $sendthis"
1088             return 1
1089         }
1090         -re "A character constant must contain at least one character.*$gdb_prompt $" {
1091             pass "reject $sendthis"
1092             return 1
1093         }
1094         -re "$expectthis.*$gdb_prompt $" {
1095             pass "reject $sendthis"
1096             return 1
1097         }
1098         -re ".*$gdb_prompt $" {
1099             fail "reject $sendthis"
1100             return 1
1101         }
1102         default {
1103             fail "reject $sendthis (eof or timeout)"
1104             return 0
1105         }
1106     }
1107 }
1108 \f
1109 # Given an input string, adds backslashes as needed to create a
1110 # regexp that will match the string.
1111
1112 proc string_to_regexp {str} {
1113     set result $str
1114     regsub -all {[]*+.|()^$\[\\]} $str {\\&} result
1115     return $result
1116 }
1117
1118 # Same as gdb_test, but the second parameter is not a regexp,
1119 # but a string that must match exactly.
1120
1121 proc gdb_test_exact { args } {
1122     upvar timeout timeout
1123
1124     set command [lindex $args 0]
1125
1126     # This applies a special meaning to a null string pattern.  Without
1127     # this, "$pattern\r\n$gdb_prompt $" will match anything, including error
1128     # messages from commands that should have no output except a new
1129     # prompt.  With this, only results of a null string will match a null
1130     # string pattern.
1131
1132     set pattern [lindex $args 1]
1133     if [string match $pattern ""] {
1134         set pattern [string_to_regexp [lindex $args 0]]
1135     } else {
1136         set pattern [string_to_regexp [lindex $args 1]]
1137     }
1138
1139     # It is most natural to write the pattern argument with only
1140     # embedded \n's, especially if you are trying to avoid Tcl quoting
1141     # problems.  But gdb_expect really wants to see \r\n in patterns.  So
1142     # transform the pattern here.  First transform \r\n back to \n, in
1143     # case some users of gdb_test_exact already do the right thing.
1144     regsub -all "\r\n" $pattern "\n" pattern
1145     regsub -all "\n" $pattern "\r\n" pattern
1146     if [llength $args]==3 then {
1147         set message [lindex $args 2]
1148     } else {
1149         set message $command
1150     }
1151
1152     return [gdb_test $command $pattern $message]
1153 }
1154
1155 # Wrapper around gdb_test_multiple that looks for a list of expected
1156 # output elements, but which can appear in any order.
1157 # CMD is the gdb command.
1158 # NAME is the name of the test.
1159 # ELM_FIND_REGEXP specifies how to partition the output into elements to
1160 # compare.
1161 # ELM_EXTRACT_REGEXP specifies the part of ELM_FIND_REGEXP to compare.
1162 # RESULT_MATCH_LIST is a list of exact matches for each expected element.
1163 # All elements of RESULT_MATCH_LIST must appear for the test to pass.
1164 #
1165 # A typical use of ELM_FIND_REGEXP/ELM_EXTRACT_REGEXP is to extract one line
1166 # of text per element and then strip trailing \r\n's.
1167 # Example:
1168 # gdb_test_list_exact "foo" "bar" \
1169 #    "\[^\r\n\]+\[\r\n\]+" \
1170 #    "\[^\r\n\]+" \
1171 #     { \
1172 #       {expected result 1} \
1173 #       {expected result 2} \
1174 #     }
1175
1176 proc gdb_test_list_exact { cmd name elm_find_regexp elm_extract_regexp result_match_list } {
1177     global gdb_prompt
1178
1179     set matches [lsort $result_match_list]
1180     set seen {}
1181     gdb_test_multiple $cmd $name {
1182         "$cmd\[\r\n\]" { exp_continue }
1183         -re $elm_find_regexp {
1184             set str $expect_out(0,string)
1185             verbose -log "seen: $str" 3
1186             regexp -- $elm_extract_regexp $str elm_seen
1187             verbose -log "extracted: $elm_seen" 3
1188             lappend seen $elm_seen
1189             exp_continue
1190         }
1191         -re "$gdb_prompt $" {
1192             set failed ""
1193             foreach got [lsort $seen] have $matches {
1194                 if {![string equal $got $have]} {
1195                     set failed $have
1196                     break
1197                 }
1198             }
1199             if {[string length $failed] != 0} {
1200                 fail "$name ($failed not found)"
1201             } else {
1202                 pass $name
1203             }
1204         }
1205     }
1206 }
1207 \f
1208
1209 # Issue a PASS and return true if evaluating CONDITION in the caller's
1210 # frame returns true, and issue a FAIL and return false otherwise.
1211 # MESSAGE is the pass/fail message to be printed.  If MESSAGE is
1212 # omitted or is empty, then the pass/fail messages use the condition
1213 # string as the message.
1214
1215 proc gdb_assert { condition {message ""} } {
1216     if { $message == ""} {
1217         set message $condition
1218     }
1219
1220     set res [uplevel 1 expr $condition]
1221     if {!$res} {
1222         fail $message
1223     } else {
1224         pass $message
1225     }
1226     return $res
1227 }
1228
1229 proc gdb_reinitialize_dir { subdir } {
1230     global gdb_prompt
1231
1232     if [is_remote host] {
1233         return ""
1234     }
1235     send_gdb "dir\n"
1236     gdb_expect 60 {
1237         -re "Reinitialize source path to empty.*y or n. " {
1238             send_gdb "y\n"
1239             gdb_expect 60 {
1240                 -re "Source directories searched.*$gdb_prompt $" {
1241                     send_gdb "dir $subdir\n"
1242                     gdb_expect 60 {
1243                         -re "Source directories searched.*$gdb_prompt $" {
1244                             verbose "Dir set to $subdir"
1245                         }
1246                         -re "$gdb_prompt $" {
1247                             perror "Dir \"$subdir\" failed."
1248                         }
1249                     }
1250                 }
1251                 -re "$gdb_prompt $" {
1252                     perror "Dir \"$subdir\" failed."
1253                 }
1254             }
1255         }
1256         -re "$gdb_prompt $" {
1257             perror "Dir \"$subdir\" failed."
1258         }
1259     }
1260 }
1261
1262 #
1263 # gdb_exit -- exit the GDB, killing the target program if necessary
1264 #
1265 proc default_gdb_exit {} {
1266     global GDB
1267     global INTERNAL_GDBFLAGS GDBFLAGS
1268     global verbose
1269     global gdb_spawn_id
1270     global inotify_log_file
1271
1272     gdb_stop_suppressing_tests
1273
1274     if ![info exists gdb_spawn_id] {
1275         return
1276     }
1277
1278     verbose "Quitting $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
1279
1280     if {[info exists inotify_log_file] && [file exists $inotify_log_file]} {
1281         set fd [open $inotify_log_file]
1282         set data [read -nonewline $fd]
1283         close $fd
1284
1285         if {[string compare $data ""] != 0} {
1286             warning "parallel-unsafe file creations noticed"
1287
1288             # Clear the log.
1289             set fd [open $inotify_log_file w]
1290             close $fd
1291         }
1292     }
1293
1294     if { [is_remote host] && [board_info host exists fileid] } {
1295         send_gdb "quit\n"
1296         gdb_expect 10 {
1297             -re "y or n" {
1298                 send_gdb "y\n"
1299                 exp_continue
1300             }
1301             -re "DOSEXIT code" { }
1302             default { }
1303         }
1304     }
1305
1306     if ![is_remote host] {
1307         remote_close host
1308     }
1309     unset gdb_spawn_id
1310 }
1311
1312 # Load a file into the debugger.
1313 # The return value is 0 for success, -1 for failure.
1314 #
1315 # This procedure also set the global variable GDB_FILE_CMD_DEBUG_INFO
1316 # to one of these values:
1317 #
1318 #   debug    file was loaded successfully and has debug information
1319 #   nodebug  file was loaded successfully and has no debug information
1320 #   lzma     file was loaded, .gnu_debugdata found, but no LZMA support
1321 #            compiled in
1322 #   fail     file was not loaded
1323 #
1324 # I tried returning this information as part of the return value,
1325 # but ran into a mess because of the many re-implementations of
1326 # gdb_load in config/*.exp.
1327 #
1328 # TODO: gdb.base/sepdebug.exp and gdb.stabs/weird.exp might be able to use
1329 # this if they can get more information set.
1330
1331 proc gdb_file_cmd { arg } {
1332     global gdb_prompt
1333     global verbose
1334     global GDB
1335     global last_loaded_file
1336
1337     # Save this for the benefit of gdbserver-support.exp.
1338     set last_loaded_file $arg
1339
1340     # Set whether debug info was found.
1341     # Default to "fail".
1342     global gdb_file_cmd_debug_info
1343     set gdb_file_cmd_debug_info "fail"
1344
1345     if [is_remote host] {
1346         set arg [remote_download host $arg]
1347         if { $arg == "" } {
1348             perror "download failed"
1349             return -1
1350         }
1351     }
1352
1353     # The file command used to kill the remote target.  For the benefit
1354     # of the testsuite, preserve this behavior.
1355     send_gdb "kill\n"
1356     gdb_expect 120 {
1357         -re "Kill the program being debugged. .y or n. $" {
1358             send_gdb "y\n"
1359             verbose "\t\tKilling previous program being debugged"
1360             exp_continue
1361         }
1362         -re "$gdb_prompt $" {
1363             # OK.
1364         }
1365     }
1366
1367     send_gdb "file $arg\n"
1368     gdb_expect 120 {
1369         -re "Reading symbols from.*LZMA support was disabled.*done.*$gdb_prompt $" {
1370             verbose "\t\tLoaded $arg into $GDB; .gnu_debugdata found but no LZMA available"
1371             set gdb_file_cmd_debug_info "lzma"
1372             return 0
1373         }
1374         -re "Reading symbols from.*no debugging symbols found.*done.*$gdb_prompt $" {
1375             verbose "\t\tLoaded $arg into $GDB with no debugging symbols"
1376             set gdb_file_cmd_debug_info "nodebug"
1377             return 0
1378         }
1379         -re "Reading symbols from.*done.*$gdb_prompt $" {
1380             verbose "\t\tLoaded $arg into $GDB"
1381             set gdb_file_cmd_debug_info "debug"
1382             return 0
1383         }
1384         -re "Load new symbol table from \".*\".*y or n. $" {
1385             send_gdb "y\n"
1386             gdb_expect 120 {
1387                 -re "Reading symbols from.*done.*$gdb_prompt $" {
1388                     verbose "\t\tLoaded $arg with new symbol table into $GDB"
1389                     set gdb_file_cmd_debug_info "debug"
1390                     return 0
1391                 }
1392                 timeout {
1393                     perror "Couldn't load $arg, other program already loaded (timeout)."
1394                     return -1
1395                 }
1396                 eof {
1397                     perror "Couldn't load $arg, other program already loaded (eof)."
1398                     return -1
1399                 }
1400             }
1401         }
1402         -re "No such file or directory.*$gdb_prompt $" {
1403             perror "($arg) No such file or directory"
1404             return -1
1405         }
1406         -re "A problem internal to GDB has been detected" {
1407             fail "($arg) (GDB internal error)"
1408             gdb_internal_error_resync
1409             return -1
1410         }
1411         -re "$gdb_prompt $" {
1412             perror "Couldn't load $arg into $GDB."
1413             return -1
1414             }
1415         timeout {
1416             perror "Couldn't load $arg into $GDB (timeout)."
1417             return -1
1418         }
1419         eof {
1420             # This is an attempt to detect a core dump, but seems not to
1421             # work.  Perhaps we need to match .* followed by eof, in which
1422             # gdb_expect does not seem to have a way to do that.
1423             perror "Couldn't load $arg into $GDB (eof)."
1424             return -1
1425         }
1426     }
1427 }
1428
1429 #
1430 # start gdb -- start gdb running, default procedure
1431 #
1432 # When running over NFS, particularly if running many simultaneous
1433 # tests on different hosts all using the same server, things can
1434 # get really slow.  Give gdb at least 3 minutes to start up.
1435 #
1436 proc default_gdb_start { } {
1437     global verbose use_gdb_stub
1438     global GDB
1439     global INTERNAL_GDBFLAGS GDBFLAGS
1440     global gdb_prompt
1441     global timeout
1442     global gdb_spawn_id
1443
1444     gdb_stop_suppressing_tests
1445
1446     # Set the default value, it may be overriden later by specific testfile.
1447     #
1448     # Use `set_board_info use_gdb_stub' for the board file to flag the inferior
1449     # is already started after connecting and run/attach are not supported.
1450     # This is used for the "remote" protocol.  After GDB starts you should
1451     # check global $use_gdb_stub instead of the board as the testfile may force
1452     # a specific different target protocol itself.
1453     set use_gdb_stub [target_info exists use_gdb_stub]
1454
1455     verbose "Spawning $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
1456
1457     if [info exists gdb_spawn_id] {
1458         return 0
1459     }
1460
1461     if ![is_remote host] {
1462         if { [which $GDB] == 0 } then {
1463             perror "$GDB does not exist."
1464             exit 1
1465         }
1466     }
1467     set res [remote_spawn host "$GDB $INTERNAL_GDBFLAGS $GDBFLAGS [host_info gdb_opts]"]
1468     if { $res < 0 || $res == "" } {
1469         perror "Spawning $GDB failed."
1470         return 1
1471     }
1472     gdb_expect 360 {
1473         -re "\[\r\n\]$gdb_prompt $" {
1474             verbose "GDB initialized."
1475         }
1476         -re "$gdb_prompt $"     {
1477             perror "GDB never initialized."
1478             return -1
1479         }
1480         timeout {
1481             perror "(timeout) GDB never initialized after 10 seconds."
1482             remote_close host
1483             return -1
1484         }
1485     }
1486     set gdb_spawn_id -1
1487     # force the height to "unlimited", so no pagers get used
1488
1489     send_gdb "set height 0\n"
1490     gdb_expect 10 {
1491         -re "$gdb_prompt $" { 
1492             verbose "Setting height to 0." 2
1493         }
1494         timeout {
1495             warning "Couldn't set the height to 0"
1496         }
1497     }
1498     # force the width to "unlimited", so no wraparound occurs
1499     send_gdb "set width 0\n"
1500     gdb_expect 10 {
1501         -re "$gdb_prompt $" {
1502             verbose "Setting width to 0." 2
1503         }
1504         timeout {
1505             warning "Couldn't set the width to 0."
1506         }
1507     }
1508     return 0
1509 }
1510
1511 # Examine the output of compilation to determine whether compilation
1512 # failed or not.  If it failed determine whether it is due to missing
1513 # compiler or due to compiler error.  Report pass, fail or unsupported
1514 # as appropriate
1515
1516 proc gdb_compile_test {src output} {
1517     if { $output == "" } {
1518         pass "compilation [file tail $src]"
1519     } elseif { [regexp {^[a-zA-Z_0-9]+: Can't find [^ ]+\.$} $output] } {
1520         unsupported "compilation [file tail $src]"
1521     } elseif { [regexp {.*: command not found[\r|\n]*$} $output] } {
1522         unsupported "compilation [file tail $src]"
1523     } elseif { [regexp {.*: [^\r\n]*compiler not installed[^\r\n]*[\r|\n]*$} $output] } {
1524         unsupported "compilation [file tail $src]"
1525     } else {
1526         verbose -log "compilation failed: $output" 2
1527         fail "compilation [file tail $src]"
1528     }
1529 }
1530
1531 # Return a 1 for configurations for which we don't even want to try to
1532 # test C++.
1533
1534 proc skip_cplus_tests {} {
1535     if { [istarget "h8300-*-*"] } {
1536         return 1
1537     }
1538
1539     # The C++ IO streams are too large for HC11/HC12 and are thus not
1540     # available.  The gdb C++ tests use them and don't compile.
1541     if { [istarget "m6811-*-*"] } {
1542         return 1
1543     }
1544     if { [istarget "m6812-*-*"] } {
1545         return 1
1546     }
1547     return 0
1548 }
1549
1550 # Return a 1 for configurations for which don't have both C++ and the STL.
1551
1552 proc skip_stl_tests {} {
1553     # Symbian supports the C++ language, but the STL is missing
1554     # (both headers and libraries).
1555     if { [istarget "arm*-*-symbianelf*"] } {
1556         return 1
1557     }
1558
1559     return [skip_cplus_tests]
1560 }
1561
1562 # Return a 1 if I don't even want to try to test FORTRAN.
1563
1564 proc skip_fortran_tests {} {
1565     return 0
1566 }
1567
1568 # Return a 1 if I don't even want to try to test ada.
1569
1570 proc skip_ada_tests {} {
1571     return 0
1572 }
1573
1574 # Return a 1 if I don't even want to try to test GO.
1575
1576 proc skip_go_tests {} {
1577     return 0
1578 }
1579
1580 # Return a 1 if I don't even want to try to test java.
1581
1582 proc skip_java_tests {} {
1583     return 0
1584 }
1585
1586 # Return a 1 if I don't even want to try to test D.
1587
1588 proc skip_d_tests {} {
1589     return 0
1590 }
1591
1592 # Return a 1 for configurations that do not support Python scripting.
1593
1594 proc skip_python_tests {} {
1595     global gdb_prompt
1596     global gdb_py_is_py3k
1597     global gdb_py_is_py24
1598
1599     gdb_test_multiple "python print ('test')" "verify python support" {
1600         -re "not supported.*$gdb_prompt $"      {
1601             unsupported "Python support is disabled."
1602             return 1
1603         }
1604         -re "$gdb_prompt $"     {}
1605     }
1606
1607     set gdb_py_is_py24 0
1608     gdb_test_multiple "python print (sys.version_info\[0\])" "check if python 3" {
1609         -re "3.*$gdb_prompt $"  {
1610             set gdb_py_is_py3k 1
1611         }
1612         -re ".*$gdb_prompt $"   {
1613             set gdb_py_is_py3k 0
1614         }
1615     }
1616     if { $gdb_py_is_py3k == 0 } {
1617         gdb_test_multiple "python print (sys.version_info\[1\])" "check if python 2.4" {
1618             -re "\[45\].*$gdb_prompt $" {
1619                 set gdb_py_is_py24 1
1620             }
1621             -re ".*$gdb_prompt $" {
1622                 set gdb_py_is_py24 0
1623             }
1624         }
1625     }
1626
1627     return 0
1628 }
1629
1630 # Return a 1 if we should skip shared library tests.
1631
1632 proc skip_shlib_tests {} {
1633     # Run the shared library tests on native systems.
1634     if {[isnative]} {
1635         return 0
1636     }
1637
1638     # An abbreviated list of remote targets where we should be able to
1639     # run shared library tests.
1640     if {([istarget *-*-linux*]
1641          || [istarget *-*-*bsd*]
1642          || [istarget *-*-solaris2*]
1643          || [istarget arm*-*-symbianelf*]
1644          || [istarget *-*-mingw*]
1645          || [istarget *-*-cygwin*]
1646          || [istarget *-*-pe*])} {
1647         return 0
1648     }
1649
1650     return 1
1651 }
1652
1653 # Test files shall make sure all the test result lines in gdb.sum are
1654 # unique in a test run, so that comparing the gdb.sum files of two
1655 # test runs gives correct results.  Test files that exercise
1656 # variations of the same tests more than once, shall prefix the
1657 # different test invocations with different identifying strings in
1658 # order to make them unique.
1659 #
1660 # About test prefixes:
1661 #
1662 # $pf_prefix is the string that dejagnu prints after the result (FAIL,
1663 # PASS, etc.), and before the test message/name in gdb.sum.  E.g., the
1664 # underlined substring in
1665 #
1666 #  PASS: gdb.base/mytest.exp: some test
1667 #        ^^^^^^^^^^^^^^^^^^^^
1668 #
1669 # is $pf_prefix.
1670 #
1671 # The easiest way to adjust the test prefix is to append a test
1672 # variation prefix to the $pf_prefix, using the with_test_prefix
1673 # procedure.  E.g.,
1674 #
1675 # proc do_tests {} {
1676 #   gdb_test ... ... "test foo"
1677 #   gdb_test ... ... "test bar"
1678 #
1679 #   with_test_prefix "subvariation a" {
1680 #     gdb_test ... ... "test x"
1681 #   }
1682 #
1683 #   with_test_prefix "subvariation b" {
1684 #     gdb_test ... ... "test x"
1685 #   }
1686 # }
1687 #
1688 # with_test_prefix "variation1" {
1689 #   ...do setup for variation 1...
1690 #   do_tests
1691 # }
1692 #
1693 # with_test_prefix "variation2" {
1694 #   ...do setup for variation 2...
1695 #   do_tests
1696 # }
1697 #
1698 # Results in:
1699 #
1700 #  PASS: gdb.base/mytest.exp: variation1: test foo
1701 #  PASS: gdb.base/mytest.exp: variation1: test bar
1702 #  PASS: gdb.base/mytest.exp: variation1: subvariation a: test x
1703 #  PASS: gdb.base/mytest.exp: variation1: subvariation b: test x
1704 #  PASS: gdb.base/mytest.exp: variation2: test foo
1705 #  PASS: gdb.base/mytest.exp: variation2: test bar
1706 #  PASS: gdb.base/mytest.exp: variation2: subvariation a: test x
1707 #  PASS: gdb.base/mytest.exp: variation2: subvariation b: test x
1708 #
1709 # If for some reason more flexibility is necessary, one can also
1710 # manipulate the pf_prefix global directly, treating it as a string.
1711 # E.g.,
1712 #
1713 #   global pf_prefix
1714 #   set saved_pf_prefix
1715 #   append pf_prefix "${foo}: bar"
1716 #   ... actual tests ...
1717 #   set pf_prefix $saved_pf_prefix
1718 #
1719
1720 # Run BODY in the context of the caller, with the current test prefix
1721 # (pf_prefix) appended with one space, then PREFIX, and then a colon.
1722 # Returns the result of BODY.
1723 #
1724 proc with_test_prefix { prefix body } {
1725   global pf_prefix
1726
1727   set saved $pf_prefix
1728   append pf_prefix " " $prefix ":"
1729   set code [catch {uplevel 1 $body} result]
1730   set pf_prefix $saved
1731
1732   if {$code == 1} {
1733       global errorInfo errorCode
1734       return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
1735   } else {
1736       return -code $code $result
1737   }
1738 }
1739
1740 # Run tests in BODY with GDB prompt and variable $gdb_prompt set to
1741 # PROMPT.  When BODY is finished, restore GDB prompt and variable
1742 # $gdb_prompt.
1743 # Returns the result of BODY.
1744
1745 proc with_gdb_prompt { prompt body } {
1746     global gdb_prompt
1747
1748     set saved $gdb_prompt
1749
1750     set gdb_prompt $prompt
1751     gdb_test_no_output "set prompt $prompt " ""
1752
1753     set code [catch {uplevel 1 $body} result]
1754
1755     set gdb_prompt $saved
1756     gdb_test_no_output "set prompt $saved " ""
1757
1758     if {$code == 1} {
1759         global errorInfo errorCode
1760         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
1761     } else {
1762         return -code $code $result
1763     }
1764 }
1765
1766 # Run tests in BODY with target-charset setting to TARGET_CHARSET.  When
1767 # BODY is finished, restore target-charset.
1768
1769 proc with_target_charset { target_charset body } {
1770     global gdb_prompt
1771
1772     set saved ""
1773     gdb_test_multiple "show target-charset" "" {
1774         -re "The target character set is \".*; currently (.*)\"\..*$gdb_prompt " {
1775             set saved $expect_out(1,string)
1776         }
1777         -re "The target character set is \"(.*)\".*$gdb_prompt " {
1778             set saved $expect_out(1,string)
1779         }
1780         -re ".*$gdb_prompt " {
1781             fail "get target-charset"
1782         }
1783     }
1784
1785     gdb_test_no_output "set target-charset $target_charset" ""
1786
1787     set code [catch {uplevel 1 $body} result]
1788
1789     gdb_test_no_output "set target-charset $saved" ""
1790
1791     if {$code == 1} {
1792         global errorInfo errorCode
1793         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
1794     } else {
1795         return -code $code $result
1796     }
1797 }
1798
1799 # Return 1 if _Complex types are supported, otherwise, return 0.
1800
1801 gdb_caching_proc support_complex_tests {
1802     # Set up, compile, and execute a test program containing _Complex types.
1803     # Include the current process ID in the file names to prevent conflicts
1804     # with invocations for multiple testsuites.
1805     set src [standard_temp_file complex[pid].c]
1806     set exe [standard_temp_file complex[pid].x]
1807
1808     gdb_produce_source $src {
1809         int main() {
1810             _Complex float cf;
1811             _Complex double cd;
1812             _Complex long double cld;
1813             return 0;
1814         }
1815     }
1816
1817     verbose "compiling testfile $src" 2
1818     set compile_flags {debug nowarnings quiet}
1819     set lines [gdb_compile $src $exe executable $compile_flags]
1820     file delete $src
1821     file delete $exe
1822
1823     if ![string match "" $lines] then {
1824         verbose "testfile compilation failed, returning 0" 2
1825         set result 0
1826     } else {
1827         set result 1
1828     }
1829
1830     return $result
1831 }
1832
1833 # Return 1 if target hardware or OS supports single stepping to signal
1834 # handler, otherwise, return 0.
1835
1836 proc can_single_step_to_signal_handler {} {
1837
1838     # Targets don't have hardware single step.  On these targets, when
1839     # a signal is delivered during software single step, gdb is unable
1840     # to determine the next instruction addresses, because start of signal
1841     # handler is one of them.
1842     if { [istarget "arm*-*-*"] || [istarget "mips*-*-*"]
1843          || [istarget "tic6x-*-*"] || [istarget "sparc*-*-linux*"]
1844          || [istarget "nios2-*-*"] } {
1845         return 0
1846     }
1847
1848     return 1
1849 }
1850
1851 # Return 1 if target supports process record, otherwise return 0.
1852
1853 proc supports_process_record {} {
1854
1855     if [target_info exists gdb,use_precord] {
1856         return [target_info gdb,use_precord]
1857     }
1858
1859     if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
1860          || [istarget "i\[34567\]86-*-linux*"] } {
1861         return 1
1862     }
1863
1864     return 0
1865 }
1866
1867 # Return 1 if target supports reverse debugging, otherwise return 0.
1868
1869 proc supports_reverse {} {
1870
1871     if [target_info exists gdb,can_reverse] {
1872         return [target_info gdb,can_reverse]
1873     }
1874
1875     if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
1876          || [istarget "i\[34567\]86-*-linux*"] } {
1877         return 1
1878     }
1879
1880     return 0
1881 }
1882
1883 # Return 1 if readline library is used.
1884
1885 proc readline_is_used { } {
1886     global gdb_prompt
1887
1888     gdb_test_multiple "show editing" "" {
1889         -re ".*Editing of command lines as they are typed is on\..*$gdb_prompt $" {
1890             return 1
1891         }
1892         -re ".*$gdb_prompt $" {
1893             return 0
1894         }
1895     }
1896 }
1897
1898 # Return 1 if target is ELF.
1899 gdb_caching_proc is_elf_target {
1900     set me "is_elf_target"
1901
1902     set src [standard_temp_file is_elf_target[pid].c]
1903     set obj [standard_temp_file is_elf_target[pid].o]
1904
1905     gdb_produce_source $src {
1906         int foo () {return 0;}
1907     }
1908
1909     verbose "$me:  compiling testfile $src" 2
1910     set lines [gdb_compile $src $obj object {quiet}]
1911
1912     file delete $src
1913
1914     if ![string match "" $lines] then {
1915         verbose "$me:  testfile compilation failed, returning 0" 2
1916         return 0
1917     }
1918
1919     set fp_obj [open $obj "r"]
1920     fconfigure $fp_obj -translation binary
1921     set data [read $fp_obj]
1922     close $fp_obj
1923
1924     file delete $obj
1925
1926     set ELFMAG "\u007FELF"
1927
1928     if {[string compare -length 4 $data $ELFMAG] != 0} {
1929         verbose "$me:  returning 0" 2
1930         return 0
1931     }
1932
1933     verbose "$me:  returning 1" 2
1934     return 1
1935 }
1936
1937 # Produce source file NAME and write SOURCES into it.
1938
1939 proc gdb_produce_source { name sources } {
1940     set index 0
1941     set f [open $name "w"]
1942
1943     puts $f $sources
1944     close $f
1945 }
1946
1947 # Return 1 if target is ILP32.
1948 # This cannot be decided simply from looking at the target string,
1949 # as it might depend on externally passed compiler options like -m64.
1950 gdb_caching_proc is_ilp32_target {
1951     set me "is_ilp32_target"
1952
1953     set src [standard_temp_file ilp32[pid].c]
1954     set obj [standard_temp_file ilp32[pid].o]
1955
1956     gdb_produce_source $src {
1957         int dummy[sizeof (int) == 4
1958                   && sizeof (void *) == 4
1959                   && sizeof (long) == 4 ? 1 : -1];
1960     }
1961
1962     verbose "$me:  compiling testfile $src" 2
1963     set lines [gdb_compile $src $obj object {quiet}]
1964     file delete $src
1965     file delete $obj
1966
1967     if ![string match "" $lines] then {
1968         verbose "$me:  testfile compilation failed, returning 0" 2
1969         return 0
1970     }
1971
1972     verbose "$me:  returning 1" 2
1973     return 1
1974 }
1975
1976 # Return 1 if target is LP64.
1977 # This cannot be decided simply from looking at the target string,
1978 # as it might depend on externally passed compiler options like -m64.
1979 gdb_caching_proc is_lp64_target {
1980     set me "is_lp64_target"
1981
1982     set src [standard_temp_file lp64[pid].c]
1983     set obj [standard_temp_file lp64[pid].o]
1984
1985     gdb_produce_source $src {
1986         int dummy[sizeof (int) == 4
1987                   && sizeof (void *) == 8
1988                   && sizeof (long) == 8 ? 1 : -1];
1989     }
1990
1991     verbose "$me:  compiling testfile $src" 2
1992     set lines [gdb_compile $src $obj object {quiet}]
1993     file delete $src
1994     file delete $obj
1995
1996     if ![string match "" $lines] then {
1997         verbose "$me:  testfile compilation failed, returning 0" 2
1998         return 0
1999     }
2000
2001     verbose "$me:  returning 1" 2
2002     return 1
2003 }
2004
2005 # Return 1 if target has 64 bit addresses.
2006 # This cannot be decided simply from looking at the target string,
2007 # as it might depend on externally passed compiler options like -m64.
2008 gdb_caching_proc is_64_target {
2009     set me "is_64_target"
2010
2011     set src [standard_temp_file is64[pid].c]
2012     set obj [standard_temp_file is64[pid].o]
2013
2014     gdb_produce_source $src {
2015         int function(void) { return 3; }
2016         int dummy[sizeof (&function) == 8 ? 1 : -1];
2017     }
2018
2019     verbose "$me:  compiling testfile $src" 2
2020     set lines [gdb_compile $src $obj object {quiet}]
2021     file delete $src
2022     file delete $obj
2023
2024     if ![string match "" $lines] then {
2025         verbose "$me:  testfile compilation failed, returning 0" 2
2026         return 0
2027     }
2028
2029     verbose "$me:  returning 1" 2
2030     return 1
2031 }
2032
2033 # Return 1 if target has x86_64 registers - either amd64 or x32.
2034 # x32 target identifies as x86_64-*-linux*, therefore it cannot be determined
2035 # just from the target string.
2036 gdb_caching_proc is_amd64_regs_target {
2037     if {![istarget "x86_64-*-*"] && ![istarget "i?86-*"]} {
2038         return 0
2039     }
2040
2041     set me "is_amd64_regs_target"
2042
2043     set src [standard_temp_file reg64[pid].s]
2044     set obj [standard_temp_file reg64[pid].o]
2045
2046     set list {}
2047     foreach reg \
2048         {rax rbx rcx rdx rsi rdi rbp rsp r8 r9 r10 r11 r12 r13 r14 r15} {
2049             lappend list "\tincq %$reg"
2050         }
2051     gdb_produce_source $src [join $list \n]
2052
2053     verbose "$me:  compiling testfile $src" 2
2054     set lines [gdb_compile $src $obj object {quiet}]
2055     file delete $src
2056     file delete $obj
2057
2058     if ![string match "" $lines] then {
2059         verbose "$me:  testfile compilation failed, returning 0" 2
2060         return 0
2061     }
2062
2063     verbose "$me:  returning 1" 2
2064     return 1
2065 }
2066
2067 # Return 1 if this target is an x86 or x86-64 with -m32.
2068 proc is_x86_like_target {} {
2069     if {![istarget "x86_64-*-*"] && ![istarget i?86-*]} {
2070         return 0
2071     }
2072     return [expr [is_ilp32_target] && ![is_amd64_regs_target]]
2073 }
2074
2075 # Return 1 if displaced stepping is supported on target, otherwise, return 0.
2076 proc support_displaced_stepping {} {
2077
2078     if { [istarget "x86_64-*-linux*"] || [istarget "i\[34567\]86-*-linux*"]
2079          || [istarget "arm*-*-linux*"] || [istarget "powerpc-*-linux*"]
2080          || [istarget "powerpc64-*-linux*"] || [istarget "s390*-*-*"] } {
2081         return 1
2082     }
2083
2084     return 0
2085 }
2086
2087 # Run a test on the target to see if it supports vmx hardware.  Return 0 if so, 
2088 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
2089
2090 gdb_caching_proc skip_altivec_tests {
2091     global srcdir subdir gdb_prompt inferior_exited_re
2092
2093     set me "skip_altivec_tests"
2094
2095     # Some simulators are known to not support VMX instructions.
2096     if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
2097         verbose "$me:  target known to not support VMX, returning 1" 2
2098         return 1
2099     }
2100
2101     # Make sure we have a compiler that understands altivec.
2102     set compile_flags {debug nowarnings}
2103     if [get_compiler_info] {
2104        warning "Could not get compiler info"
2105        return 1
2106     }
2107     if [test_compiler_info gcc*] {
2108         set compile_flags "$compile_flags additional_flags=-maltivec"
2109     } elseif [test_compiler_info xlc*] {
2110         set compile_flags "$compile_flags additional_flags=-qaltivec"
2111     } else {
2112         verbose "Could not compile with altivec support, returning 1" 2
2113         return 1
2114     }
2115
2116     # Set up, compile, and execute a test program containing VMX instructions.
2117     # Include the current process ID in the file names to prevent conflicts
2118     # with invocations for multiple testsuites.
2119     set src [standard_temp_file vmx[pid].c]
2120     set exe [standard_temp_file vmx[pid].x]
2121
2122     gdb_produce_source $src {
2123         int main() {
2124             #ifdef __MACH__
2125             asm volatile ("vor v0,v0,v0");
2126             #else
2127             asm volatile ("vor 0,0,0");
2128             #endif
2129             return 0;
2130         }
2131     }
2132
2133     verbose "$me:  compiling testfile $src" 2
2134     set lines [gdb_compile $src $exe executable $compile_flags]
2135     file delete $src
2136
2137     if ![string match "" $lines] then {
2138         verbose "$me:  testfile compilation failed, returning 1" 2
2139         return 1
2140     }
2141
2142     # No error message, compilation succeeded so now run it via gdb.
2143
2144     gdb_exit
2145     gdb_start
2146     gdb_reinitialize_dir $srcdir/$subdir
2147     gdb_load "$exe"
2148     gdb_run_cmd
2149     gdb_expect {
2150         -re ".*Illegal instruction.*${gdb_prompt} $" {
2151             verbose -log "\n$me altivec hardware not detected" 
2152             set skip_vmx_tests 1
2153         }
2154         -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
2155             verbose -log "\n$me: altivec hardware detected" 
2156             set skip_vmx_tests 0
2157         }
2158         default {
2159           warning "\n$me: default case taken"
2160             set skip_vmx_tests 1
2161         }
2162     }
2163     gdb_exit
2164     remote_file build delete $exe
2165
2166     verbose "$me:  returning $skip_vmx_tests" 2
2167     return $skip_vmx_tests
2168 }
2169
2170 # Run a test on the target to see if it supports vmx hardware.  Return 0 if so,
2171 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
2172
2173 gdb_caching_proc skip_vsx_tests {
2174     global srcdir subdir gdb_prompt inferior_exited_re
2175
2176     set me "skip_vsx_tests"
2177
2178     # Some simulators are known to not support Altivec instructions, so
2179     # they won't support VSX instructions as well.
2180     if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
2181         verbose "$me:  target known to not support VSX, returning 1" 2
2182         return 1
2183     }
2184
2185     # Make sure we have a compiler that understands altivec.
2186     set compile_flags {debug nowarnings quiet}
2187     if [get_compiler_info] {
2188        warning "Could not get compiler info"
2189        return 1
2190     }
2191     if [test_compiler_info gcc*] {
2192         set compile_flags "$compile_flags additional_flags=-mvsx"
2193     } elseif [test_compiler_info xlc*] {
2194         set compile_flags "$compile_flags additional_flags=-qasm=gcc"
2195     } else {
2196         verbose "Could not compile with vsx support, returning 1" 2
2197         return 1
2198     }
2199
2200     set src [standard_temp_file vsx[pid].c]
2201     set exe [standard_temp_file vsx[pid].x]
2202
2203     gdb_produce_source $src {
2204         int main() {
2205             double a[2] = { 1.0, 2.0 };
2206             #ifdef __MACH__
2207             asm volatile ("lxvd2x v0,v0,%[addr]" : : [addr] "r" (a));
2208             #else
2209             asm volatile ("lxvd2x 0,0,%[addr]" : : [addr] "r" (a));
2210             #endif
2211             return 0;
2212         }
2213     }
2214
2215     verbose "$me:  compiling testfile $src" 2
2216     set lines [gdb_compile $src $exe executable $compile_flags]
2217     file delete $src
2218
2219     if ![string match "" $lines] then {
2220         verbose "$me:  testfile compilation failed, returning 1" 2
2221         return 1
2222     }
2223
2224     # No error message, compilation succeeded so now run it via gdb.
2225
2226     gdb_exit
2227     gdb_start
2228     gdb_reinitialize_dir $srcdir/$subdir
2229     gdb_load "$exe"
2230     gdb_run_cmd
2231     gdb_expect {
2232         -re ".*Illegal instruction.*${gdb_prompt} $" {
2233             verbose -log "\n$me VSX hardware not detected"
2234             set skip_vsx_tests 1
2235         }
2236         -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
2237             verbose -log "\n$me: VSX hardware detected"
2238             set skip_vsx_tests 0
2239         }
2240         default {
2241           warning "\n$me: default case taken"
2242             set skip_vsx_tests 1
2243         }
2244     }
2245     gdb_exit
2246     remote_file build delete $exe
2247
2248     verbose "$me:  returning $skip_vsx_tests" 2
2249     return $skip_vsx_tests
2250 }
2251
2252 # Run a test on the target to see if it supports btrace hardware.  Return 0 if so,
2253 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
2254
2255 gdb_caching_proc skip_btrace_tests {
2256     global srcdir subdir gdb_prompt inferior_exited_re
2257
2258     set me "skip_btrace_tests"
2259     if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
2260         verbose "$me:  target does not support btrace, returning 1" 2
2261         return 1
2262     }
2263
2264     # Set up, compile, and execute a test program.
2265     # Include the current process ID in the file names to prevent conflicts
2266     # with invocations for multiple testsuites.
2267     set src [standard_temp_file btrace[pid].c]
2268     set exe [standard_temp_file btrace[pid].x]
2269
2270     gdb_produce_source $src {
2271         int main(void) { return 0; }
2272     }
2273
2274     verbose "$me:  compiling testfile $src" 2
2275     set compile_flags {debug nowarnings quiet}
2276     set lines [gdb_compile $src $exe executable $compile_flags]
2277
2278     if ![string match "" $lines] then {
2279         verbose "$me:  testfile compilation failed, returning 1" 2
2280         file delete $src
2281         return 1
2282     }
2283
2284     # No error message, compilation succeeded so now run it via gdb.
2285
2286     gdb_exit
2287     gdb_start
2288     gdb_reinitialize_dir $srcdir/$subdir
2289     gdb_load $exe
2290     if ![runto_main] {
2291         file delete $src
2292         return 1
2293     }
2294     file delete $src
2295     # In case of an unexpected output, we return 2 as a fail value.
2296     set skip_btrace_tests 2
2297     gdb_test_multiple "record btrace" "check btrace support" {
2298         -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
2299             set skip_btrace_tests 1
2300         }
2301         -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
2302             set skip_btrace_tests 1
2303         }
2304         -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
2305             set skip_btrace_tests 1
2306         }
2307         -re "^record btrace\r\n$gdb_prompt $" {
2308             set skip_btrace_tests 0
2309         }
2310     }
2311     gdb_exit
2312     remote_file build delete $exe
2313
2314     verbose "$me:  returning $skip_btrace_tests" 2
2315     return $skip_btrace_tests
2316 }
2317
2318 # Skip all the tests in the file if you are not on an hppa running
2319 # hpux target.
2320
2321 proc skip_hp_tests {} {
2322     eval set skip_hp [ expr ![isnative] || ![istarget "hppa*-*-hpux*"] ]
2323     verbose "Skip hp tests is $skip_hp"
2324     return $skip_hp
2325 }
2326
2327 # Return whether we should skip tests for showing inlined functions in
2328 # backtraces.  Requires get_compiler_info and get_debug_format.
2329
2330 proc skip_inline_frame_tests {} {
2331     # GDB only recognizes inlining information in DWARF 2 (DWARF 3).
2332     if { ! [test_debug_format "DWARF 2"] } {
2333         return 1
2334     }
2335
2336     # GCC before 4.1 does not emit DW_AT_call_file / DW_AT_call_line.
2337     if { ([test_compiler_info "gcc-2-*"]
2338           || [test_compiler_info "gcc-3-*"]
2339           || [test_compiler_info "gcc-4-0-*"]) } {
2340         return 1
2341     }
2342
2343     return 0
2344 }
2345
2346 # Return whether we should skip tests for showing variables from
2347 # inlined functions.  Requires get_compiler_info and get_debug_format.
2348
2349 proc skip_inline_var_tests {} {
2350     # GDB only recognizes inlining information in DWARF 2 (DWARF 3).
2351     if { ! [test_debug_format "DWARF 2"] } {
2352         return 1
2353     }
2354
2355     return 0
2356 }
2357
2358 # Return a 1 if we should skip tests that require hardware breakpoints
2359
2360 proc skip_hw_breakpoint_tests {} {
2361     # Skip tests if requested by the board (note that no_hardware_watchpoints
2362     # disables both watchpoints and breakpoints)
2363     if { [target_info exists gdb,no_hardware_watchpoints]} {
2364         return 1
2365     }
2366
2367     # These targets support hardware breakpoints natively
2368     if { [istarget "i?86-*-*"] 
2369          || [istarget "x86_64-*-*"]
2370          || [istarget "ia64-*-*"] 
2371          || [istarget "arm*-*-*"]} {
2372         return 0
2373     }
2374
2375     return 1
2376 }
2377
2378 # Return a 1 if we should skip tests that require hardware watchpoints
2379
2380 proc skip_hw_watchpoint_tests {} {
2381     # Skip tests if requested by the board
2382     if { [target_info exists gdb,no_hardware_watchpoints]} {
2383         return 1
2384     }
2385
2386     # These targets support hardware watchpoints natively
2387     if { [istarget "i?86-*-*"] 
2388          || [istarget "x86_64-*-*"]
2389          || [istarget "ia64-*-*"] 
2390          || [istarget "arm*-*-*"]
2391          || [istarget "powerpc*-*-linux*"]
2392          || [istarget "s390*-*-*"] } {
2393         return 0
2394     }
2395
2396     return 1
2397 }
2398
2399 # Return a 1 if we should skip tests that require *multiple* hardware
2400 # watchpoints to be active at the same time
2401
2402 proc skip_hw_watchpoint_multi_tests {} {
2403     if { [skip_hw_watchpoint_tests] } {
2404         return 1
2405     }
2406
2407     # These targets support just a single hardware watchpoint
2408     if { [istarget "arm*-*-*"]
2409          || [istarget "powerpc*-*-linux*"] } {
2410         return 1
2411     }
2412
2413     return 0
2414 }
2415
2416 # Return a 1 if we should skip tests that require read/access watchpoints
2417
2418 proc skip_hw_watchpoint_access_tests {} {
2419     if { [skip_hw_watchpoint_tests] } {
2420         return 1
2421     }
2422
2423     # These targets support just write watchpoints
2424     if { [istarget "s390*-*-*"] } {
2425         return 1
2426     }
2427
2428     return 0
2429 }
2430
2431 # Return 1 if we should skip tests that require the runtime unwinder
2432 # hook.  This must be invoked while gdb is running, after shared
2433 # libraries have been loaded.  This is needed because otherwise a
2434 # shared libgcc won't be visible.
2435
2436 proc skip_unwinder_tests {} {
2437     global gdb_prompt
2438
2439     set ok 0
2440     gdb_test_multiple "print _Unwind_DebugHook" "check for unwinder hook" {
2441         -re "= .*no debug info.*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
2442         }
2443         -re "= .*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
2444             set ok 1
2445         }
2446         -re "No symbol .* in current context.\r\n$gdb_prompt $" {
2447         }
2448     }
2449     if {!$ok} {
2450         gdb_test_multiple "info probe" "check for stap probe in unwinder" {
2451             -re ".*libgcc.*unwind.*\r\n$gdb_prompt $" {
2452                 set ok 1
2453             }
2454             -re "\r\n$gdb_prompt $" {
2455             }
2456         }
2457     }
2458     return $ok
2459 }
2460
2461 # Return 0 if we should skip tests that require the libstdc++ stap
2462 # probes.  This must be invoked while gdb is running, after shared
2463 # libraries have been loaded.
2464
2465 proc skip_libstdcxx_probe_tests {} {
2466     global gdb_prompt
2467
2468     set ok 0
2469     gdb_test_multiple "info probe" "check for stap probe in libstdc++" {
2470         -re ".*libstdcxx.*catch.*\r\n$gdb_prompt $" {
2471             set ok 1
2472         }
2473         -re "\r\n$gdb_prompt $" {
2474         }
2475     }
2476     return $ok
2477 }
2478
2479 # Check whether we're testing with the remote or extended-remote
2480 # targets.
2481
2482 proc gdb_is_target_remote {} {
2483     global gdb_prompt
2484
2485     set test "probe for target remote"
2486     gdb_test_multiple "maint print target-stack" $test {
2487         -re ".*emote serial target in gdb-specific protocol.*$gdb_prompt $" {
2488             pass $test
2489             return 1
2490         }
2491         -re "$gdb_prompt $" {
2492             pass $test
2493         }
2494     }
2495     return 0
2496 }
2497
2498 set compiler_info               "unknown"
2499 set gcc_compiled                0
2500 set hp_cc_compiler              0
2501 set hp_aCC_compiler             0
2502
2503 # Figure out what compiler I am using.
2504 #
2505 # ARG can be empty or "C++".  If empty, "C" is assumed.
2506 #
2507 # There are several ways to do this, with various problems.
2508 #
2509 # [ gdb_compile -E $ifile -o $binfile.ci ]
2510 # source $binfile.ci
2511 #
2512 #   Single Unix Spec v3 says that "-E -o ..." together are not
2513 #   specified.  And in fact, the native compiler on hp-ux 11 (among
2514 #   others) does not work with "-E -o ...".  Most targets used to do
2515 #   this, and it mostly worked, because it works with gcc.
2516 #
2517 # [ catch "exec $compiler -E $ifile > $binfile.ci" exec_output ]
2518 # source $binfile.ci
2519
2520 #   This avoids the problem with -E and -o together.  This almost works
2521 #   if the build machine is the same as the host machine, which is
2522 #   usually true of the targets which are not gcc.  But this code does
2523 #   not figure which compiler to call, and it always ends up using the C
2524 #   compiler.  Not good for setting hp_aCC_compiler.  Targets
2525 #   hppa*-*-hpux* and mips*-*-irix* used to do this.
2526 #
2527 # [ gdb_compile -E $ifile > $binfile.ci ]
2528 # source $binfile.ci
2529 #
2530 #   dejagnu target_compile says that it supports output redirection,
2531 #   but the code is completely different from the normal path and I
2532 #   don't want to sweep the mines from that path.  So I didn't even try
2533 #   this.
2534 #
2535 # set cppout [ gdb_compile $ifile "" preprocess $args quiet ]
2536 # eval $cppout
2537 #
2538 #   I actually do this for all targets now.  gdb_compile runs the right
2539 #   compiler, and TCL captures the output, and I eval the output.
2540 #
2541 #   Unfortunately, expect logs the output of the command as it goes by,
2542 #   and dejagnu helpfully prints a second copy of it right afterwards.
2543 #   So I turn off expect logging for a moment.
2544 #   
2545 # [ gdb_compile $ifile $ciexe_file executable $args ]
2546 # [ remote_exec $ciexe_file ]
2547 # [ source $ci_file.out ]
2548 #
2549 #   I could give up on -E and just do this.
2550 #   I didn't get desperate enough to try this.
2551 #
2552 # -- chastain 2004-01-06
2553
2554 proc get_compiler_info {{arg ""}} {
2555     # For compiler.c and compiler.cc
2556     global srcdir
2557
2558     # I am going to play with the log to keep noise out.
2559     global outdir
2560     global tool
2561
2562     # These come from compiler.c or compiler.cc
2563     global compiler_info
2564
2565     # Legacy global data symbols.
2566     global gcc_compiled
2567     global hp_cc_compiler
2568     global hp_aCC_compiler
2569
2570     # Choose which file to preprocess.
2571     set ifile "${srcdir}/lib/compiler.c"
2572     if { $arg == "c++" } {
2573         set ifile "${srcdir}/lib/compiler.cc"
2574     }
2575
2576     # Run $ifile through the right preprocessor.
2577     # Toggle gdb.log to keep the compiler output out of the log.
2578     set saved_log [log_file -info]
2579     log_file
2580     if [is_remote host] {
2581         # We have to use -E and -o together, despite the comments
2582         # above, because of how DejaGnu handles remote host testing.
2583         set ppout "$outdir/compiler.i"
2584         gdb_compile "${ifile}" "$ppout" preprocess [list "$arg" quiet]
2585         set file [open $ppout r]
2586         set cppout [read $file]
2587         close $file
2588     } else {
2589         set cppout [ gdb_compile "${ifile}" "" preprocess [list "$arg" quiet] ]
2590     }
2591     eval log_file $saved_log
2592
2593     # Eval the output.
2594     set unknown 0
2595     foreach cppline [ split "$cppout" "\n" ] {
2596         if { [ regexp "^#" "$cppline" ] } {
2597             # line marker
2598         } elseif { [ regexp "^\[\n\r\t \]*$" "$cppline" ] } {
2599             # blank line
2600         } elseif { [ regexp "^\[\n\r\t \]*set\[\n\r\t \]" "$cppline" ] } {
2601             # eval this line
2602             verbose "get_compiler_info: $cppline" 2
2603             eval "$cppline"
2604         } else {
2605             # unknown line
2606             verbose -log "get_compiler_info: $cppline"
2607             set unknown 1
2608         }
2609     }
2610
2611     # Reset to unknown compiler if any diagnostics happened.
2612     if { $unknown } {
2613         set compiler_info "unknown"
2614     }
2615
2616     # Set the legacy symbols.
2617     set gcc_compiled     0
2618     set hp_cc_compiler   0
2619     set hp_aCC_compiler  0
2620     if { [regexp "^gcc-1-" "$compiler_info" ] } { set gcc_compiled 1 }
2621     if { [regexp "^gcc-2-" "$compiler_info" ] } { set gcc_compiled 2 }
2622     if { [regexp "^gcc-3-" "$compiler_info" ] } { set gcc_compiled 3 }
2623     if { [regexp "^gcc-4-" "$compiler_info" ] } { set gcc_compiled 4 }
2624     if { [regexp "^gcc-5-" "$compiler_info" ] } { set gcc_compiled 5 }
2625     if { [regexp "^hpcc-"  "$compiler_info" ] } { set hp_cc_compiler 1 }
2626     if { [regexp "^hpacc-" "$compiler_info" ] } { set hp_aCC_compiler 1 }
2627
2628     # Log what happened.
2629     verbose -log "get_compiler_info: $compiler_info"
2630
2631     # Most compilers will evaluate comparisons and other boolean
2632     # operations to 0 or 1.
2633     uplevel \#0 { set true 1 }
2634     uplevel \#0 { set false 0 }
2635
2636     # Use of aCC results in boolean results being displayed as
2637     # "true" or "false"
2638     if { $hp_aCC_compiler } {
2639       uplevel \#0 { set true true }
2640       uplevel \#0 { set false false }
2641     }
2642
2643     return 0
2644 }
2645
2646 proc test_compiler_info { {compiler ""} } {
2647     global compiler_info
2648
2649      # if no arg, return the compiler_info string
2650
2651      if [string match "" $compiler] {
2652          if [info exists compiler_info] {
2653              return $compiler_info
2654          } else {
2655              perror "No compiler info found."
2656          }
2657      }
2658
2659     return [string match $compiler $compiler_info]
2660 }
2661
2662 proc current_target_name { } {
2663     global target_info
2664     if [info exists target_info(target,name)] {
2665         set answer $target_info(target,name)
2666     } else {
2667         set answer ""
2668     }
2669     return $answer
2670 }
2671
2672 set gdb_wrapper_initialized 0
2673 set gdb_wrapper_target ""
2674
2675 proc gdb_wrapper_init { args } {
2676     global gdb_wrapper_initialized
2677     global gdb_wrapper_file
2678     global gdb_wrapper_flags
2679     global gdb_wrapper_target
2680
2681     if { $gdb_wrapper_initialized == 1 } { return; }
2682
2683     if {[target_info exists needs_status_wrapper] && \
2684             [target_info needs_status_wrapper] != "0"} {
2685         set result [build_wrapper "testglue.o"]
2686         if { $result != "" } {
2687             set gdb_wrapper_file [lindex $result 0]
2688             set gdb_wrapper_flags [lindex $result 1]
2689         } else {
2690             warning "Status wrapper failed to build."
2691         }
2692     }
2693     set gdb_wrapper_initialized 1
2694     set gdb_wrapper_target [current_target_name]
2695 }
2696
2697 # Some targets need to always link a special object in.  Save its path here.
2698 global gdb_saved_set_unbuffered_mode_obj
2699 set gdb_saved_set_unbuffered_mode_obj ""
2700
2701 proc gdb_compile {source dest type options} {
2702     global GDB_TESTCASE_OPTIONS
2703     global gdb_wrapper_file
2704     global gdb_wrapper_flags
2705     global gdb_wrapper_initialized
2706     global srcdir
2707     global objdir
2708     global gdb_saved_set_unbuffered_mode_obj
2709
2710     set outdir [file dirname $dest]
2711
2712     # Add platform-specific options if a shared library was specified using
2713     # "shlib=librarypath" in OPTIONS.
2714     set new_options ""
2715     set shlib_found 0
2716     set shlib_load 0
2717     foreach opt $options {
2718         if [regexp {^shlib=(.*)} $opt dummy_var shlib_name] {
2719             if [test_compiler_info "xlc-*"] {
2720                 # IBM xlc compiler doesn't accept shared library named other
2721                 # than .so: use "-Wl," to bypass this
2722                 lappend source "-Wl,$shlib_name"
2723             } elseif { ([istarget "*-*-mingw*"]
2724                         || [istarget *-*-cygwin*]
2725                         || [istarget *-*-pe*])} {
2726                 lappend source "${shlib_name}.a"
2727             } else {
2728                lappend source $shlib_name
2729             }
2730             if { $shlib_found == 0 } {
2731                 set shlib_found 1
2732                 if { ([istarget "*-*-mingw*"]
2733                       || [istarget *-*-cygwin*]) } {
2734                     lappend new_options "additional_flags=-Wl,--enable-auto-import"
2735                 }
2736             }
2737         } elseif { $opt == "shlib_load" } {
2738             set shlib_load 1
2739         } else {
2740             lappend new_options $opt
2741         }
2742     }
2743
2744     # We typically link to shared libraries using an absolute path, and
2745     # that's how they are found at runtime.  If we are going to
2746     # dynamically load one by basename, we must specify rpath.  If we
2747     # are using a remote host, DejaGNU will link to the shared library
2748     # using a relative path, so again we must specify an rpath.
2749     if { $shlib_load || ($shlib_found && [is_remote target]) } {
2750         if { ([istarget "*-*-mingw*"]
2751               || [istarget *-*-cygwin*]
2752               || [istarget *-*-pe*]
2753               || [istarget hppa*-*-hpux*])} {
2754             # Do not need anything.
2755         } elseif { [istarget *-*-freebsd*] || [istarget *-*-openbsd*] } {
2756             lappend new_options "ldflags=-Wl,-rpath,${outdir}"
2757         } elseif { [istarget arm*-*-symbianelf*] } {
2758             if { $shlib_load } {
2759                 lappend new_options "libs=-ldl"
2760             }
2761         } else {
2762             if { $shlib_load } {
2763                 lappend new_options "libs=-ldl"
2764             }
2765             lappend new_options "ldflags=-Wl,-rpath,\\\$ORIGIN"
2766         }
2767     }
2768     set options $new_options
2769
2770     if [target_info exists is_vxworks] {
2771         set options2 { "additional_flags=-Dvxworks" }
2772         set options [concat $options2 $options]
2773     }
2774     if [info exists GDB_TESTCASE_OPTIONS] {
2775         lappend options "additional_flags=$GDB_TESTCASE_OPTIONS"
2776     }
2777     verbose "options are $options"
2778     verbose "source is $source $dest $type $options"
2779
2780     if { $gdb_wrapper_initialized == 0 } { gdb_wrapper_init }
2781
2782     if {[target_info exists needs_status_wrapper] && \
2783             [target_info needs_status_wrapper] != "0" && \
2784             [info exists gdb_wrapper_file]} {
2785         lappend options "libs=${gdb_wrapper_file}"
2786         lappend options "ldflags=${gdb_wrapper_flags}"
2787     }
2788
2789     # Replace the "nowarnings" option with the appropriate additional_flags
2790     # to disable compiler warnings.
2791     set nowarnings [lsearch -exact $options nowarnings]
2792     if {$nowarnings != -1} {
2793         if [target_info exists gdb,nowarnings_flag] {
2794             set flag "additional_flags=[target_info gdb,nowarnings_flag]"
2795         } else {
2796             set flag "additional_flags=-w"
2797         }
2798         set options [lreplace $options $nowarnings $nowarnings $flag]
2799     }
2800
2801     if { $type == "executable" } {
2802         if { ([istarget "*-*-mingw*"]
2803               || [istarget "*-*-*djgpp"]
2804               || [istarget "*-*-cygwin*"])} {
2805             # Force output to unbuffered mode, by linking in an object file
2806             # with a global contructor that calls setvbuf.
2807             #
2808             # Compile the special object seperatelly for two reasons:
2809             #  1) Insulate it from $options.
2810             #  2) Avoid compiling it for every gdb_compile invocation,
2811             #  which is time consuming, especially if we're remote
2812             #  host testing.
2813             #
2814             if { $gdb_saved_set_unbuffered_mode_obj == "" } {
2815                 verbose "compiling gdb_saved_set_unbuffered_obj"
2816                 set unbuf_src ${srcdir}/lib/set_unbuffered_mode.c
2817                 set unbuf_obj ${objdir}/set_unbuffered_mode.o
2818
2819                 set result [gdb_compile "${unbuf_src}" "${unbuf_obj}" object {nowarnings}]
2820                 if { $result != "" } {
2821                     return $result
2822                 }
2823                 if {[is_remote host]} {
2824                     set gdb_saved_set_unbuffered_mode_obj set_unbuffered_mode_saved.o
2825                 } else {
2826                     set gdb_saved_set_unbuffered_mode_obj ${objdir}/set_unbuffered_mode_saved.o
2827                 }
2828                 # Link a copy of the output object, because the
2829                 # original may be automatically deleted.
2830                 remote_download host $unbuf_obj $gdb_saved_set_unbuffered_mode_obj
2831             } else {
2832                 verbose "gdb_saved_set_unbuffered_obj already compiled"
2833             }
2834
2835             # Rely on the internal knowledge that the global ctors are ran in
2836             # reverse link order.  In that case, we can use ldflags to
2837             # avoid copying the object file to the host multiple
2838             # times.
2839             # This object can only be added if standard libraries are
2840             # used. Thus, we need to disable it if -nostdlib option is used
2841             if {[lsearch -regexp $options "-nostdlib"] < 0 } {
2842                 lappend options "ldflags=$gdb_saved_set_unbuffered_mode_obj"
2843             }
2844         }
2845     }
2846
2847     set result [target_compile $source $dest $type $options]
2848
2849     # Prune uninteresting compiler (and linker) output.
2850     regsub "Creating library file: \[^\r\n\]*\[\r\n\]+" $result "" result
2851
2852     regsub "\[\r\n\]*$" "$result" "" result
2853     regsub "^\[\r\n\]*" "$result" "" result
2854     
2855     if {[lsearch $options quiet] < 0} {
2856         # We shall update this on a per language basis, to avoid
2857         # changing the entire testsuite in one go.
2858         if {[lsearch $options f77] >= 0} {
2859             gdb_compile_test $source $result
2860         } elseif { $result != "" } {
2861             clone_output "gdb compile failed, $result"
2862         }
2863     }
2864     return $result
2865 }
2866
2867
2868 # This is just like gdb_compile, above, except that it tries compiling
2869 # against several different thread libraries, to see which one this
2870 # system has.
2871 proc gdb_compile_pthreads {source dest type options} {
2872     set built_binfile 0
2873     set why_msg "unrecognized error"
2874     foreach lib {-lpthreads -lpthread -lthread ""} {
2875         # This kind of wipes out whatever libs the caller may have
2876         # set.  Or maybe theirs will override ours.  How infelicitous.
2877         set options_with_lib [concat $options [list libs=$lib quiet]]
2878         set ccout [gdb_compile $source $dest $type $options_with_lib]
2879         switch -regexp -- $ccout {
2880             ".*no posix threads support.*" {
2881                 set why_msg "missing threads include file"
2882                 break
2883             }
2884             ".*cannot open -lpthread.*" {
2885                 set why_msg "missing runtime threads library"
2886             }
2887             ".*Can't find library for -lpthread.*" {
2888                 set why_msg "missing runtime threads library"
2889             }
2890             {^$} {
2891                 pass "successfully compiled posix threads test case"
2892                 set built_binfile 1
2893                 break
2894             }
2895         }
2896     }
2897     if {!$built_binfile} {
2898         unsupported "Couldn't compile [file tail $source]: ${why_msg}"
2899         return -1
2900     }
2901 }
2902
2903 # Build a shared library from SOURCES.
2904
2905 proc gdb_compile_shlib {sources dest options} {
2906     set obj_options $options
2907
2908     set info_options ""
2909     if { [lsearch -exact $options "c++"] >= 0 } {
2910         set info_options "c++"
2911     }
2912     if [get_compiler_info ${info_options}] {
2913        return -1
2914     }
2915
2916     switch -glob [test_compiler_info] {
2917         "xlc-*" {
2918             lappend obj_options "additional_flags=-qpic"
2919         }
2920         "gcc-*" {
2921             if { !([istarget "powerpc*-*-aix*"]
2922                    || [istarget "rs6000*-*-aix*"]
2923                    || [istarget "*-*-cygwin*"]
2924                    || [istarget "*-*-mingw*"]
2925                    || [istarget "*-*-pe*"]) } {
2926                 lappend obj_options "additional_flags=-fpic"
2927             }
2928         }
2929         default {
2930             switch -glob [istarget] {
2931                 "hppa*-hp-hpux*" {
2932                     lappend obj_options "additional_flags=+z"
2933                 }
2934                 "mips-sgi-irix*" {
2935                     # Disable SGI compiler's implicit -Dsgi
2936                     lappend obj_options "additional_flags=-Usgi"
2937                 } 
2938                 default {
2939                     # don't know what the compiler is...
2940                 }
2941             }
2942         }
2943     }
2944
2945     set outdir [file dirname $dest]
2946     set objects ""
2947     foreach source $sources {
2948        set sourcebase [file tail $source]
2949        if {[gdb_compile $source "${outdir}/${sourcebase}.o" object $obj_options] != ""} {
2950            return -1
2951        }
2952        lappend objects ${outdir}/${sourcebase}.o
2953     }
2954
2955     if [istarget "hppa*-*-hpux*"] {
2956        remote_exec build "ld -b ${objects} -o ${dest}"
2957     } else {
2958        set link_options $options
2959        if [test_compiler_info "xlc-*"] {
2960           lappend link_options "additional_flags=-qmkshrobj"
2961        } else {
2962           lappend link_options "additional_flags=-shared"
2963
2964            if { ([istarget "*-*-mingw*"]
2965                  || [istarget *-*-cygwin*]
2966                  || [istarget *-*-pe*]) } {
2967                if { [is_remote host] } {
2968                    set name [file tail ${dest}]
2969                } else {
2970                    set name ${dest}
2971                }
2972                lappend link_options "additional_flags=-Wl,--out-implib,${name}.a"
2973            } elseif [is_remote target] {
2974              # By default, we do not set the soname.  This causes the linker
2975              # on ELF systems to create a DT_NEEDED entry in the executable
2976              # refering to the full path name of the library.  This is a
2977              # problem in remote testing if the library is in a different
2978              # directory there.  To fix this, we set a soname of just the
2979              # base filename for the library, and add an appropriate -rpath
2980              # to the main executable (in gdb_compile).
2981              set destbase [file tail $dest]
2982              lappend link_options "additional_flags=-Wl,-soname,$destbase"
2983            }
2984        }
2985        if {[gdb_compile "${objects}" "${dest}" executable $link_options] != ""} {
2986            return -1
2987        }
2988         if { [is_remote host]
2989              && ([istarget "*-*-mingw*"]
2990                  || [istarget *-*-cygwin*]
2991                  || [istarget *-*-pe*]) } {
2992             set dest_tail_name [file tail ${dest}]
2993             remote_upload host $dest_tail_name.a ${dest}.a
2994             remote_file host delete $dest_tail_name.a
2995         }
2996     }
2997   return ""
2998 }
2999
3000 # This is just like gdb_compile_shlib, above, except that it tries compiling
3001 # against several different thread libraries, to see which one this
3002 # system has.
3003 proc gdb_compile_shlib_pthreads {sources dest options} {
3004     set built_binfile 0
3005     set why_msg "unrecognized error"
3006     foreach lib {-lpthreads -lpthread -lthread ""} {
3007         # This kind of wipes out whatever libs the caller may have
3008         # set.  Or maybe theirs will override ours.  How infelicitous.
3009         set options_with_lib [concat $options [list libs=$lib quiet]]
3010         set ccout [gdb_compile_shlib $sources $dest $options_with_lib]
3011         switch -regexp -- $ccout {
3012             ".*no posix threads support.*" {
3013                 set why_msg "missing threads include file"
3014                 break
3015             }
3016             ".*cannot open -lpthread.*" {
3017                 set why_msg "missing runtime threads library"
3018             }
3019             ".*Can't find library for -lpthread.*" {
3020                 set why_msg "missing runtime threads library"
3021             }
3022             {^$} {
3023                 pass "successfully compiled posix threads test case"
3024                 set built_binfile 1
3025                 break
3026             }
3027         }
3028     }
3029     if {!$built_binfile} {
3030         unsupported "Couldn't compile $sources: ${why_msg}"
3031         return -1
3032     }
3033 }
3034
3035 # This is just like gdb_compile_pthreads, above, except that we always add the
3036 # objc library for compiling Objective-C programs
3037 proc gdb_compile_objc {source dest type options} {
3038     set built_binfile 0
3039     set why_msg "unrecognized error"
3040     foreach lib {-lobjc -lpthreads -lpthread -lthread solaris} {
3041         # This kind of wipes out whatever libs the caller may have
3042         # set.  Or maybe theirs will override ours.  How infelicitous.
3043         if { $lib == "solaris" } {
3044             set lib "-lpthread -lposix4"
3045         }
3046         if { $lib != "-lobjc" } {
3047           set lib "-lobjc $lib"
3048         }
3049         set options_with_lib [concat $options [list libs=$lib quiet]]
3050         set ccout [gdb_compile $source $dest $type $options_with_lib]
3051         switch -regexp -- $ccout {
3052             ".*no posix threads support.*" {
3053                 set why_msg "missing threads include file"
3054                 break
3055             }
3056             ".*cannot open -lpthread.*" {
3057                 set why_msg "missing runtime threads library"
3058             }
3059             ".*Can't find library for -lpthread.*" {
3060                 set why_msg "missing runtime threads library"
3061             }
3062             {^$} {
3063                 pass "successfully compiled objc with posix threads test case"
3064                 set built_binfile 1
3065                 break
3066             }
3067         }
3068     }
3069     if {!$built_binfile} {
3070         unsupported "Couldn't compile [file tail $source]: ${why_msg}"
3071         return -1
3072     }
3073 }
3074
3075 proc send_gdb { string } {
3076     global suppress_flag
3077     if { $suppress_flag } {
3078         return "suppressed"
3079     }
3080     return [remote_send host "$string"]
3081 }
3082
3083 #
3084 #
3085
3086 proc gdb_expect { args } {
3087     if { [llength $args] == 2  && [lindex $args 0] != "-re" } {
3088         set atimeout [lindex $args 0]
3089         set expcode [list [lindex $args 1]]
3090     } else {
3091         set expcode $args
3092     }
3093
3094     upvar timeout timeout
3095
3096     if [target_info exists gdb,timeout] {
3097         if [info exists timeout] {
3098             if { $timeout < [target_info gdb,timeout] } {
3099                 set gtimeout [target_info gdb,timeout]
3100             } else {
3101                 set gtimeout $timeout
3102             }
3103         } else {
3104             set gtimeout [target_info gdb,timeout]
3105         }
3106     }
3107
3108     if ![info exists gtimeout] {
3109         global timeout
3110         if [info exists timeout] {
3111             set gtimeout $timeout
3112         }
3113     }
3114
3115     if [info exists atimeout] {
3116         if { ![info exists gtimeout] || $gtimeout < $atimeout } {
3117             set gtimeout $atimeout
3118         }
3119     } else {
3120         if ![info exists gtimeout] {
3121             # Eeeeew.
3122             set gtimeout 60
3123         }
3124     }
3125
3126     global suppress_flag
3127     global remote_suppress_flag
3128     if [info exists remote_suppress_flag] {
3129         set old_val $remote_suppress_flag
3130     }
3131     if [info exists suppress_flag] {
3132         if { $suppress_flag } {
3133             set remote_suppress_flag 1
3134         }
3135     }
3136     set code [catch \
3137         {uplevel remote_expect host $gtimeout $expcode} string]
3138     if [info exists old_val] {
3139         set remote_suppress_flag $old_val
3140     } else {
3141         if [info exists remote_suppress_flag] {
3142             unset remote_suppress_flag
3143         }
3144     }
3145
3146     if {$code == 1} {
3147         global errorInfo errorCode
3148
3149         return -code error -errorinfo $errorInfo -errorcode $errorCode $string
3150     } else {
3151         return -code $code $string
3152     }
3153 }
3154
3155 # gdb_expect_list TEST SENTINEL LIST -- expect a sequence of outputs
3156 #
3157 # Check for long sequence of output by parts.
3158 # TEST: is the test message to be printed with the test success/fail.
3159 # SENTINEL: Is the terminal pattern indicating that output has finished.
3160 # LIST: is the sequence of outputs to match.
3161 # If the sentinel is recognized early, it is considered an error.
3162 #
3163 # Returns:
3164 #    1 if the test failed,
3165 #    0 if the test passes,
3166 #   -1 if there was an internal error.
3167
3168 proc gdb_expect_list {test sentinel list} {
3169     global gdb_prompt
3170     global suppress_flag
3171     set index 0
3172     set ok 1
3173     if { $suppress_flag } {
3174         set ok 0
3175         unresolved "${test}"
3176     }
3177     while { ${index} < [llength ${list}] } {
3178         set pattern [lindex ${list} ${index}]
3179         set index [expr ${index} + 1]
3180         verbose -log "gdb_expect_list pattern: /$pattern/" 2
3181         if { ${index} == [llength ${list}] } {
3182             if { ${ok} } {
3183                 gdb_expect {
3184                     -re "${pattern}${sentinel}" {
3185                         # pass "${test}, pattern ${index} + sentinel"
3186                     }
3187                     -re "${sentinel}" {
3188                         fail "${test} (pattern ${index} + sentinel)"
3189                         set ok 0
3190                     }
3191                     -re ".*A problem internal to GDB has been detected" {
3192                         fail "${test} (GDB internal error)"
3193                         set ok 0
3194                         gdb_internal_error_resync
3195                     }
3196                     timeout {
3197                         fail "${test} (pattern ${index} + sentinel) (timeout)"
3198                         set ok 0
3199                     }
3200                 }
3201             } else {
3202                 # unresolved "${test}, pattern ${index} + sentinel"
3203             }
3204         } else {
3205             if { ${ok} } {
3206                 gdb_expect {
3207                     -re "${pattern}" {
3208                         # pass "${test}, pattern ${index}"
3209                     }
3210                     -re "${sentinel}" {
3211                         fail "${test} (pattern ${index})"
3212                         set ok 0
3213                     }
3214                     -re ".*A problem internal to GDB has been detected" {
3215                         fail "${test} (GDB internal error)"
3216                         set ok 0
3217                         gdb_internal_error_resync
3218                     }
3219                     timeout {
3220                         fail "${test} (pattern ${index}) (timeout)"
3221                         set ok 0
3222                     }
3223                 }
3224             } else {
3225                 # unresolved "${test}, pattern ${index}"
3226             }
3227         }
3228     }
3229     if { ${ok} } {
3230         pass "${test}"
3231         return 0
3232     } else {
3233         return 1
3234     }
3235 }
3236
3237 #
3238 #
3239 proc gdb_suppress_entire_file { reason } {
3240     global suppress_flag
3241
3242     warning "$reason\n"
3243     set suppress_flag -1
3244 }
3245
3246 #
3247 # Set suppress_flag, which will cause all subsequent calls to send_gdb and
3248 # gdb_expect to fail immediately (until the next call to 
3249 # gdb_stop_suppressing_tests).
3250 #
3251 proc gdb_suppress_tests { args } {
3252     global suppress_flag
3253
3254     return;  # fnf - disable pending review of results where
3255              # testsuite ran better without this
3256     incr suppress_flag
3257
3258     if { $suppress_flag == 1 } {
3259         if { [llength $args] > 0 } {
3260             warning "[lindex $args 0]\n"
3261         } else {
3262             warning "Because of previous failure, all subsequent tests in this group will automatically fail.\n"
3263         }
3264     }
3265 }
3266
3267 #
3268 # Clear suppress_flag.
3269 #
3270 proc gdb_stop_suppressing_tests { } {
3271     global suppress_flag
3272
3273     if [info exists suppress_flag] {
3274         if { $suppress_flag > 0 } {
3275             set suppress_flag 0
3276             clone_output "Tests restarted.\n"
3277         }
3278     } else {
3279         set suppress_flag 0
3280     }
3281 }
3282
3283 proc gdb_clear_suppressed { } {
3284     global suppress_flag
3285
3286     set suppress_flag 0
3287 }
3288
3289 proc gdb_start { } {
3290     default_gdb_start
3291 }
3292
3293 proc gdb_exit { } {
3294     catch default_gdb_exit
3295 }
3296
3297 #
3298 # gdb_load_cmd -- load a file into the debugger.
3299 #                 ARGS - additional args to load command.
3300 #                 return a -1 if anything goes wrong.
3301 #
3302 proc gdb_load_cmd { args } {
3303     global gdb_prompt
3304
3305     if [target_info exists gdb_load_timeout] {
3306         set loadtimeout [target_info gdb_load_timeout]
3307     } else {
3308         set loadtimeout 1600
3309     }
3310     send_gdb "load $args\n"
3311     verbose "Timeout is now $loadtimeout seconds" 2
3312     gdb_expect $loadtimeout {
3313         -re "Loading section\[^\r\]*\r\n" {
3314             exp_continue
3315         }
3316         -re "Start address\[\r\]*\r\n" {
3317             exp_continue
3318         }
3319         -re "Transfer rate\[\r\]*\r\n" {
3320             exp_continue
3321         }
3322         -re "Memory access error\[^\r\]*\r\n" {
3323             perror "Failed to load program"
3324             return -1
3325         }
3326         -re "$gdb_prompt $" {
3327             return 0
3328         }
3329         -re "(.*)\r\n$gdb_prompt " {
3330             perror "Unexpected reponse from 'load' -- $expect_out(1,string)"
3331             return -1
3332         }
3333         timeout {
3334             perror "Timed out trying to load $args."
3335             return -1
3336         }
3337     }
3338     return -1
3339 }
3340
3341 # Invoke "gcore".  CORE is the name of the core file to write.  TEST
3342 # is the name of the test case.  This will return 1 if the core file
3343 # was created, 0 otherwise.  If this fails to make a core file because
3344 # this configuration of gdb does not support making core files, it
3345 # will call "unsupported", not "fail".  However, if this fails to make
3346 # a core file for some other reason, then it will call "fail".
3347
3348 proc gdb_gcore_cmd {core test} {
3349     global gdb_prompt
3350
3351     set result 0
3352     gdb_test_multiple "gcore $core" $test {
3353         -re "Saved corefile .*\[\r\n\]+$gdb_prompt $" {
3354             pass $test
3355             set result 1
3356         }
3357
3358         -re "Undefined command.*$gdb_prompt $" {
3359             unsupported $test
3360             verbose -log "'gcore' command undefined in gdb_gcore_cmd"
3361         }
3362
3363         -re "(?:Can't create a corefile|Target does not support core file generation\\.)\[\r\n\]+$gdb_prompt $" {
3364             unsupported $test
3365         }
3366     }
3367
3368     return $result
3369 }
3370
3371 # Load core file CORE.  TEST is the name of the test case.
3372 # This will record a pass/fail for loading the core file.
3373 # Returns:
3374 #  1 - core file is successfully loaded
3375 #  0 - core file loaded but has a non fatal error
3376 # -1 - core file failed to load
3377
3378 proc gdb_core_cmd { core test } {
3379     global gdb_prompt
3380
3381     gdb_test_multiple "core $core" "$test" {
3382         -re "\\\[Thread debugging using \[^ \r\n\]* enabled\\\]\r\n" {
3383             exp_continue
3384         }
3385         -re " is not a core dump:.*\r\n$gdb_prompt $" {
3386             fail "$test (bad file format)"
3387             return -1
3388         }
3389         -re ": No such file or directory.*\r\n$gdb_prompt $" {
3390             fail "$test (file not found)"
3391             return -1
3392         }
3393         -re "Couldn't find .* registers in core file.*\r\n$gdb_prompt $" {
3394             fail "$test (incomplete note section)"
3395             return 0
3396         }
3397         -re "Core was generated by .*\r\n$gdb_prompt $" {
3398             pass "$test"
3399             return 1
3400         }
3401         -re ".*$gdb_prompt $" {
3402             fail "$test"
3403             return -1
3404         }
3405         timeout {
3406             fail "$test (timeout)"
3407             return -1
3408         }
3409     }
3410     fail "unsupported output from 'core' command"
3411     return -1
3412 }
3413
3414 # Return the filename to download to the target and load on the target
3415 # for this shared library.  Normally just LIBNAME, unless shared libraries
3416 # for this target have separate link and load images.
3417
3418 proc shlib_target_file { libname } {
3419     return $libname
3420 }
3421
3422 # Return the filename GDB will load symbols from when debugging this
3423 # shared library.  Normally just LIBNAME, unless shared libraries for
3424 # this target have separate link and load images.
3425
3426 proc shlib_symbol_file { libname } {
3427     return $libname
3428 }
3429
3430 # Return the filename to download to the target and load for this
3431 # executable.  Normally just BINFILE unless it is renamed to something
3432 # else for this target.
3433
3434 proc exec_target_file { binfile } {
3435     return $binfile
3436 }
3437
3438 # Return the filename GDB will load symbols from when debugging this
3439 # executable.  Normally just BINFILE unless executables for this target
3440 # have separate files for symbols.
3441
3442 proc exec_symbol_file { binfile } {
3443     return $binfile
3444 }
3445
3446 # Rename the executable file.  Normally this is just BINFILE1 being renamed
3447 # to BINFILE2, but some targets require multiple binary files.
3448 proc gdb_rename_execfile { binfile1 binfile2 } {
3449     file rename -force [exec_target_file ${binfile1}] \
3450                        [exec_target_file ${binfile2}]
3451     if { [exec_target_file ${binfile1}] != [exec_symbol_file ${binfile1}] } {
3452         file rename -force [exec_symbol_file ${binfile1}] \
3453                            [exec_symbol_file ${binfile2}]
3454     }
3455 }
3456
3457 # "Touch" the executable file to update the date.  Normally this is just
3458 # BINFILE, but some targets require multiple files.
3459 proc gdb_touch_execfile { binfile } {
3460     set time [clock seconds]
3461     file mtime [exec_target_file ${binfile}] $time
3462     if { [exec_target_file ${binfile}] != [exec_symbol_file ${binfile}] } {
3463         file mtime [exec_symbol_file ${binfile}] $time
3464     }
3465 }
3466
3467 # Like remote_download but provides a gdb-specific behavior.  If DEST
3468 # is "host", and the host is not remote, and TOFILE is not specified,
3469 # then the [file tail] of FROMFILE is passed through
3470 # standard_output_file to compute the destination.
3471
3472 proc gdb_remote_download {dest fromfile {tofile {}}} {
3473     if {$dest == "host" && ![is_remote host] && $tofile == ""} {
3474         set tofile [standard_output_file [file tail $fromfile]]
3475     }
3476
3477     if { $tofile == "" } {
3478         return [remote_download $dest $fromfile]
3479     } else {
3480         return [remote_download $dest $fromfile $tofile]
3481     }
3482 }
3483
3484 # gdb_download
3485 #
3486 # Copy a file to the remote target and return its target filename.
3487 # Schedule the file to be deleted at the end of this test.
3488
3489 proc gdb_download { filename } {
3490     global cleanfiles
3491
3492     set destname [remote_download target $filename]
3493     lappend cleanfiles $destname
3494     return $destname
3495 }
3496
3497 # gdb_load_shlibs LIB...
3498 #
3499 # Copy the listed libraries to the target.
3500
3501 proc gdb_load_shlibs { args } {
3502     if {![is_remote target]} {
3503         return
3504     }
3505
3506     foreach file $args {
3507         gdb_download [shlib_target_file $file]
3508     }
3509
3510     # Even if the target supplies full paths for shared libraries,
3511     # they may not be paths for this system.
3512     gdb_test "set solib-search-path [file dirname [lindex $args 0]]" "" ""
3513 }
3514
3515 #
3516 # gdb_load -- load a file into the debugger.  Specifying no file
3517 # defaults to the executable currently being debugged.
3518 # Many files in config/*.exp override this procedure.
3519 #
3520 proc gdb_load { arg } {
3521     if { $arg != "" } {
3522         return [gdb_file_cmd $arg]
3523     }
3524 }
3525
3526 # gdb_reload -- load a file into the target.  Called before "running",
3527 # either the first time or after already starting the program once,
3528 # for remote targets.  Most files that override gdb_load should now
3529 # override this instead.
3530
3531 proc gdb_reload { } {
3532     # For the benefit of existing configurations, default to gdb_load.
3533     # Specifying no file defaults to the executable currently being
3534     # debugged.
3535     return [gdb_load ""]
3536 }
3537
3538 proc gdb_continue { function } {
3539     global decimal
3540
3541     return [gdb_test "continue" ".*Breakpoint $decimal, $function .*" "continue to $function"]
3542 }
3543
3544 proc default_gdb_init { test_file_name } {
3545     global gdb_wrapper_initialized
3546     global gdb_wrapper_target
3547     global gdb_test_file_name
3548     global cleanfiles
3549     global pf_prefix
3550     
3551     set cleanfiles {}
3552
3553     gdb_clear_suppressed
3554
3555     set gdb_test_file_name [file rootname [file tail $test_file_name]]
3556
3557     # Make sure that the wrapper is rebuilt
3558     # with the appropriate multilib option.
3559     if { $gdb_wrapper_target != [current_target_name] } {
3560         set gdb_wrapper_initialized 0
3561     }
3562     
3563     # Unlike most tests, we have a small number of tests that generate
3564     # a very large amount of output.  We therefore increase the expect
3565     # buffer size to be able to contain the entire test output.  This
3566     # is especially needed by gdb.base/info-macros.exp.
3567     match_max -d 65536
3568     # Also set this value for the currently running GDB. 
3569     match_max [match_max -d]
3570
3571     # We want to add the name of the TCL testcase to the PASS/FAIL messages.
3572     set pf_prefix "[file tail [file dirname $test_file_name]]/[file tail $test_file_name]:"
3573
3574     global gdb_prompt
3575     if [target_info exists gdb_prompt] {
3576         set gdb_prompt [target_info gdb_prompt]
3577     } else {
3578         set gdb_prompt "\\(gdb\\)"
3579     }
3580     global use_gdb_stub
3581     if [info exists use_gdb_stub] {
3582         unset use_gdb_stub
3583     }
3584 }
3585
3586 # Turn BASENAME into a full file name in the standard output
3587 # directory.  It is ok if BASENAME is the empty string; in this case
3588 # the directory is returned.
3589
3590 proc standard_output_file {basename} {
3591     global objdir subdir gdb_test_file_name GDB_PARALLEL
3592
3593     if {[info exists GDB_PARALLEL]} {
3594         set dir [file join $objdir outputs $subdir $gdb_test_file_name]
3595         file mkdir $dir
3596         return [file join $dir $basename]
3597     } else {
3598         return [file join $objdir $subdir $basename]
3599     }
3600 }
3601
3602 # Return the name of a file in our standard temporary directory.
3603
3604 proc standard_temp_file {basename} {
3605     global objdir GDB_PARALLEL
3606
3607     if {[info exists GDB_PARALLEL]} {
3608         return [file join $objdir temp $basename]
3609     } else {
3610         return $basename
3611     }
3612 }
3613
3614 # Set 'testfile', 'srcfile', and 'binfile'.
3615 #
3616 # ARGS is a list of source file specifications.
3617 # Without any arguments, the .exp file's base name is used to
3618 # compute the source file name.  The ".c" extension is added in this case.
3619 # If ARGS is not empty, each entry is a source file specification.
3620 # If the specification starts with a ".", it is treated as a suffix
3621 # to append to the .exp file's base name.
3622 # If the specification is the empty string, it is treated as if it
3623 # were ".c".
3624 # Otherwise it is a file name.
3625 # The first file in the list is used to set the 'srcfile' global.
3626 # Each subsequent name is used to set 'srcfile2', 'srcfile3', etc.
3627 #
3628 # Most tests should call this without arguments.
3629 #
3630 # If a completely different binary file name is needed, then it
3631 # should be handled in the .exp file with a suitable comment.
3632
3633 proc standard_testfile {args} {
3634     global gdb_test_file_name
3635     global subdir
3636     global gdb_test_file_last_vars
3637
3638     # Outputs.
3639     global testfile binfile
3640
3641     set testfile $gdb_test_file_name
3642     set binfile [standard_output_file ${testfile}]
3643
3644     if {[llength $args] == 0} {
3645         set args .c
3646     }
3647
3648     # Unset our previous output variables.
3649     # This can help catch hidden bugs.
3650     if {[info exists gdb_test_file_last_vars]} {
3651         foreach varname $gdb_test_file_last_vars {
3652             global $varname
3653             catch {unset $varname}
3654         }
3655     }
3656     # 'executable' is often set by tests.
3657     set gdb_test_file_last_vars {executable}
3658
3659     set suffix ""
3660     foreach arg $args {
3661         set varname srcfile$suffix
3662         global $varname
3663
3664         # Handle an extension.
3665         if {$arg == ""} {
3666             set arg $testfile.c
3667         } elseif {[string range $arg 0 0] == "."} {
3668             set arg $testfile$arg
3669         }
3670
3671         set $varname $arg
3672         lappend gdb_test_file_last_vars $varname
3673
3674         if {$suffix == ""} {
3675             set suffix 2
3676         } else {
3677             incr suffix
3678         }
3679     }
3680 }
3681
3682 # The default timeout used when testing GDB commands.  We want to use
3683 # the same timeout as the default dejagnu timeout, unless the user has
3684 # already provided a specific value (probably through a site.exp file).
3685 global gdb_test_timeout
3686 if ![info exists gdb_test_timeout] {
3687     set gdb_test_timeout $timeout
3688 }
3689
3690 # A list of global variables that GDB testcases should not use.
3691 # We try to prevent their use by monitoring write accesses and raising
3692 # an error when that happens.
3693 set banned_variables { bug_id prms_id }
3694
3695 # A list of procedures that GDB testcases should not use.
3696 # We try to prevent their use by monitoring invocations and raising
3697 # an error when that happens.
3698 set banned_procedures { strace }
3699
3700 # gdb_init is called by runtest at start, but also by several
3701 # tests directly; gdb_finish is only called from within runtest after
3702 # each test source execution.
3703 # Placing several traces by repetitive calls to gdb_init leads
3704 # to problems, as only one trace is removed in gdb_finish.
3705 # To overcome this possible problem, we add a variable that records
3706 # if the banned variables and procedures are already traced.
3707 set banned_traced 0
3708
3709 proc gdb_init { test_file_name } {
3710     # Reset the timeout value to the default.  This way, any testcase
3711     # that changes the timeout value without resetting it cannot affect
3712     # the timeout used in subsequent testcases.
3713     global gdb_test_timeout
3714     global timeout
3715     set timeout $gdb_test_timeout
3716
3717     if { [regexp ".*gdb\.reverse\/.*" $test_file_name]
3718          && [target_info exists gdb_reverse_timeout] } {
3719         set timeout [target_info gdb_reverse_timeout]
3720     }
3721
3722     # If GDB_INOTIFY is given, check for writes to '.'.  This is a
3723     # debugging tool to help confirm that the test suite is
3724     # parallel-safe.  You need "inotifywait" from the
3725     # inotify-tools package to use this.
3726     global GDB_INOTIFY inotify_pid
3727     if {[info exists GDB_INOTIFY] && ![info exists inotify_pid]} {
3728         global outdir tool inotify_log_file
3729
3730         set exclusions {outputs temp gdb[.](log|sum) cache}
3731         set exclusion_re ([join $exclusions |])
3732
3733         set inotify_log_file [standard_temp_file inotify.out]
3734         set inotify_pid [exec inotifywait -r -m -e move,create,delete . \
3735                              --exclude $exclusion_re \
3736                              |& tee -a $outdir/$tool.log $inotify_log_file &]
3737
3738         # Wait for the watches; hopefully this is long enough.
3739         sleep 2
3740
3741         # Clear the log so that we don't emit a warning the first time
3742         # we check it.
3743         set fd [open $inotify_log_file w]
3744         close $fd
3745     }
3746
3747     # Block writes to all banned variables, and invocation of all
3748     # banned procedures...
3749     global banned_variables
3750     global banned_procedures
3751     global banned_traced
3752     if (!$banned_traced) {
3753         foreach banned_var $banned_variables {
3754             global "$banned_var"
3755             trace add variable "$banned_var" write error
3756         }
3757         foreach banned_proc $banned_procedures {
3758             global "$banned_proc"
3759             trace add execution "$banned_proc" enter error
3760         }
3761         set banned_traced 1
3762     }
3763
3764     # We set LC_ALL, LC_CTYPE, and LANG to C so that we get the same
3765     # messages as expected.
3766     setenv LC_ALL C
3767     setenv LC_CTYPE C
3768     setenv LANG C
3769
3770     # Don't let a .inputrc file or an existing setting of INPUTRC mess up
3771     # the test results.  Even if /dev/null doesn't exist on the particular
3772     # platform, the readline library will use the default setting just by
3773     # failing to open the file.  OTOH, opening /dev/null successfully will
3774     # also result in the default settings being used since nothing will be
3775     # read from this file.
3776     setenv INPUTRC "/dev/null"
3777
3778     # The gdb.base/readline.exp arrow key test relies on the standard VT100
3779     # bindings, so make sure that an appropriate terminal is selected.
3780     # The same bug doesn't show up if we use ^P / ^N instead.
3781     setenv TERM "vt100"
3782
3783     # Some tests (for example gdb.base/maint.exp) shell out from gdb to use
3784     # grep.  Clear GREP_OPTIONS to make the behavior predictable,
3785     # especially having color output turned on can cause tests to fail.
3786     setenv GREP_OPTIONS ""
3787
3788     # Clear $gdbserver_reconnect_p.
3789     global gdbserver_reconnect_p
3790     set gdbserver_reconnect_p 1
3791     unset gdbserver_reconnect_p
3792
3793     return [default_gdb_init $test_file_name]
3794 }
3795
3796 proc gdb_finish { } {
3797     global gdbserver_reconnect_p
3798     global gdb_prompt
3799     global cleanfiles
3800
3801     # Give persistent gdbserver a chance to terminate before GDB is killed.
3802     if {[info exists gdbserver_reconnect_p] && $gdbserver_reconnect_p
3803         && [info exists gdb_spawn_id]} {
3804         send_gdb "kill\n";
3805         gdb_expect 10 {
3806             -re "y or n" {
3807                 send_gdb "y\n";
3808                 exp_continue;
3809             }
3810             -re "$gdb_prompt $" {
3811             }
3812         }
3813     }
3814
3815     # Exit first, so that the files are no longer in use.
3816     gdb_exit
3817
3818     if { [llength $cleanfiles] > 0 } {
3819         eval remote_file target delete $cleanfiles
3820         set cleanfiles {}
3821     }
3822
3823     # Unblock write access to the banned variables.  Dejagnu typically
3824     # resets some of them between testcases.
3825     global banned_variables
3826     global banned_procedures
3827     global banned_traced
3828     if ($banned_traced) {
3829         foreach banned_var $banned_variables {
3830             global "$banned_var"
3831             trace remove variable "$banned_var" write error
3832         }
3833         foreach banned_proc $banned_procedures {
3834             global "$banned_proc"
3835             trace remove execution "$banned_proc" enter error
3836         }
3837         set banned_traced 0
3838     }
3839 }
3840
3841 global debug_format
3842 set debug_format "unknown"
3843
3844 # Run the gdb command "info source" and extract the debugging format
3845 # information from the output and save it in debug_format.
3846
3847 proc get_debug_format { } {
3848     global gdb_prompt
3849     global verbose
3850     global expect_out
3851     global debug_format
3852
3853     set debug_format "unknown"
3854     send_gdb "info source\n"
3855     gdb_expect 10 {
3856         -re "Compiled with (.*) debugging format.\r\n.*$gdb_prompt $" {
3857             set debug_format $expect_out(1,string)
3858             verbose "debug format is $debug_format"
3859             return 1
3860         }
3861         -re "No current source file.\r\n$gdb_prompt $" {
3862             perror "get_debug_format used when no current source file"
3863             return 0
3864         }
3865         -re "$gdb_prompt $" {
3866             warning "couldn't check debug format (no valid response)."
3867             return 1
3868         }
3869         timeout {
3870             warning "couldn't check debug format (timeout)."
3871             return 1
3872         }
3873     }
3874 }
3875
3876 # Return true if FORMAT matches the debug format the current test was
3877 # compiled with.  FORMAT is a shell-style globbing pattern; it can use
3878 # `*', `[...]', and so on.
3879 #
3880 # This function depends on variables set by `get_debug_format', above.
3881
3882 proc test_debug_format {format} {
3883     global debug_format
3884
3885     return [expr [string match $format $debug_format] != 0]
3886 }
3887
3888 # Like setup_xfail, but takes the name of a debug format (DWARF 1,
3889 # COFF, stabs, etc).  If that format matches the format that the
3890 # current test was compiled with, then the next test is expected to
3891 # fail for any target.  Returns 1 if the next test or set of tests is
3892 # expected to fail, 0 otherwise (or if it is unknown).  Must have
3893 # previously called get_debug_format.
3894 proc setup_xfail_format { format } {
3895     set ret [test_debug_format $format]
3896
3897     if {$ret} then {
3898         setup_xfail "*-*-*"
3899     }
3900     return $ret
3901 }
3902
3903 # gdb_get_line_number TEXT [FILE]
3904 #
3905 # Search the source file FILE, and return the line number of the
3906 # first line containing TEXT.  If no match is found, an error is thrown.
3907
3908 # TEXT is a string literal, not a regular expression.
3909 #
3910 # The default value of FILE is "$srcdir/$subdir/$srcfile".  If FILE is
3911 # specified, and does not start with "/", then it is assumed to be in
3912 # "$srcdir/$subdir".  This is awkward, and can be fixed in the future,
3913 # by changing the callers and the interface at the same time.
3914 # In particular: gdb.base/break.exp, gdb.base/condbreak.exp,
3915 # gdb.base/ena-dis-br.exp.
3916 #
3917 # Use this function to keep your test scripts independent of the
3918 # exact line numbering of the source file.  Don't write:
3919
3920 #   send_gdb "break 20"
3921
3922 # This means that if anyone ever edits your test's source file, 
3923 # your test could break.  Instead, put a comment like this on the
3924 # source file line you want to break at:
3925
3926 #   /* breakpoint spot: frotz.exp: test name */
3927
3928 # and then write, in your test script (which we assume is named
3929 # frotz.exp):
3930
3931 #   send_gdb "break [gdb_get_line_number "frotz.exp: test name"]\n"
3932 #
3933 # (Yes, Tcl knows how to handle the nested quotes and brackets.
3934 # Try this:
3935 #       $ tclsh
3936 #       % puts "foo [lindex "bar baz" 1]"
3937 #       foo baz
3938 #       % 
3939 # Tcl is quite clever, for a little stringy language.)
3940 #
3941 # ===
3942 #
3943 # The previous implementation of this procedure used the gdb search command.
3944 # This version is different:
3945 #
3946 #   . It works with MI, and it also works when gdb is not running.
3947 #
3948 #   . It operates on the build machine, not the host machine.
3949 #
3950 #   . For now, this implementation fakes a current directory of
3951 #     $srcdir/$subdir to be compatible with the old implementation.
3952 #     This will go away eventually and some callers will need to
3953 #     be changed.
3954 #
3955 #   . The TEXT argument is literal text and matches literally,
3956 #     not a regular expression as it was before.
3957 #
3958 #   . State changes in gdb, such as changing the current file
3959 #     and setting $_, no longer happen.
3960 #
3961 # After a bit of time we can forget about the differences from the
3962 # old implementation.
3963 #
3964 # --chastain 2004-08-05
3965
3966 proc gdb_get_line_number { text { file "" } } {
3967     global srcdir
3968     global subdir
3969     global srcfile
3970
3971     if { "$file" == "" } then {
3972         set file "$srcfile"
3973     }
3974     if { ! [regexp "^/" "$file"] } then {
3975         set file "$srcdir/$subdir/$file"
3976     }
3977
3978     if { [ catch { set fd [open "$file"] } message ] } then {
3979         error "$message"
3980     }
3981
3982     set found -1
3983     for { set line 1 } { 1 } { incr line } {
3984         if { [ catch { set nchar [gets "$fd" body] } message ] } then {
3985             error "$message"
3986         }
3987         if { $nchar < 0 } then {
3988             break
3989         }
3990         if { [string first "$text" "$body"] >= 0 } then {
3991             set found $line
3992             break
3993         }
3994     }
3995
3996     if { [ catch { close "$fd" } message ] } then {
3997         error "$message"
3998     }
3999
4000     if {$found == -1} {
4001         error "undefined tag \"$text\""
4002     }
4003
4004     return $found
4005 }
4006
4007 # Continue the program until it ends.
4008 #
4009 # MSSG is the error message that gets printed.  If not given, a
4010 #       default is used.
4011 # COMMAND is the command to invoke.  If not given, "continue" is
4012 #       used.
4013 # ALLOW_EXTRA is a flag indicating whether the test should expect
4014 #       extra output between the "Continuing." line and the program
4015 #       exiting.  By default it is zero; if nonzero, any extra output
4016 #       is accepted.
4017
4018 proc gdb_continue_to_end {{mssg ""} {command continue} {allow_extra 0}} {
4019   global inferior_exited_re use_gdb_stub
4020
4021   if {$mssg == ""} {
4022       set text "continue until exit"
4023   } else {
4024       set text "continue until exit at $mssg"
4025   }
4026   if {$allow_extra} {
4027       set extra ".*"
4028   } else {
4029       set extra ""
4030   }
4031
4032   # By default, we don't rely on exit() behavior of remote stubs --
4033   # it's common for exit() to be implemented as a simple infinite
4034   # loop, or a forced crash/reset.  For native targets, by default, we
4035   # assume process exit is reported as such.  If a non-reliable target
4036   # is used, we set a breakpoint at exit, and continue to that.
4037   if { [target_info exists exit_is_reliable] } {
4038       set exit_is_reliable [target_info exit_is_reliable]
4039   } else {
4040       set exit_is_reliable [expr ! $use_gdb_stub]
4041   }
4042
4043   if { ! $exit_is_reliable } {
4044     if {![gdb_breakpoint "exit"]} {
4045       return 0
4046     }
4047     gdb_test $command "Continuing..*Breakpoint .*exit.*" \
4048         $text
4049   } else {
4050     # Continue until we exit.  Should not stop again.
4051     # Don't bother to check the output of the program, that may be
4052     # extremely tough for some remote systems.
4053     gdb_test $command \
4054       "Continuing.\[\r\n0-9\]+${extra}(... EXIT code 0\[\r\n\]+|$inferior_exited_re normally).*"\
4055         $text
4056   }
4057 }
4058
4059 proc rerun_to_main {} {
4060   global gdb_prompt use_gdb_stub
4061
4062   if $use_gdb_stub {
4063     gdb_run_cmd
4064     gdb_expect {
4065       -re ".*Breakpoint .*main .*$gdb_prompt $"\
4066               {pass "rerun to main" ; return 0}
4067       -re "$gdb_prompt $"\
4068               {fail "rerun to main" ; return 0}
4069       timeout {fail "(timeout) rerun to main" ; return 0}
4070     }
4071   } else {
4072     send_gdb "run\n"
4073     gdb_expect {
4074       -re "The program .* has been started already.*y or n. $" {
4075           send_gdb "y\n"
4076           exp_continue
4077       }
4078       -re "Starting program.*$gdb_prompt $"\
4079               {pass "rerun to main" ; return 0}
4080       -re "$gdb_prompt $"\
4081               {fail "rerun to main" ; return 0}
4082       timeout {fail "(timeout) rerun to main" ; return 0}
4083     }
4084   }
4085 }
4086
4087 # Print a message and return true if a test should be skipped
4088 # due to lack of floating point suport.
4089
4090 proc gdb_skip_float_test { msg } {
4091     if [target_info exists gdb,skip_float_tests] {
4092         verbose "Skipping test '$msg': no float tests."
4093         return 1
4094     }
4095     return 0
4096 }
4097
4098 # Print a message and return true if a test should be skipped
4099 # due to lack of stdio support.
4100
4101 proc gdb_skip_stdio_test { msg } {
4102     if [target_info exists gdb,noinferiorio] {
4103         verbose "Skipping test '$msg': no inferior i/o."
4104         return 1
4105     }
4106     return 0
4107 }
4108
4109 proc gdb_skip_bogus_test { msg } {
4110     return 0
4111 }
4112
4113 # Return true if a test should be skipped due to lack of XML support
4114 # in the host GDB.
4115 # NOTE: This must be called while gdb is *not* running.
4116
4117 gdb_caching_proc gdb_skip_xml_test {
4118     global gdb_prompt
4119     global srcdir
4120
4121     gdb_start
4122     set xml_missing 0
4123     gdb_test_multiple "set tdesc filename ${srcdir}/gdb.xml/trivial.xml" "" {
4124         -re ".*XML support was disabled at compile time.*$gdb_prompt $" {
4125             set xml_missing 1
4126         }
4127         -re ".*$gdb_prompt $" { }
4128     }
4129     gdb_exit
4130     return $xml_missing
4131 }
4132
4133 # Note: the procedure gdb_gnu_strip_debug will produce an executable called
4134 # ${binfile}.dbglnk, which is just like the executable ($binfile) but without
4135 # the debuginfo. Instead $binfile has a .gnu_debuglink section which contains
4136 # the name of a debuginfo only file. This file will be stored in the same
4137 # subdirectory.
4138
4139 # Functions for separate debug info testing
4140
4141 # starting with an executable:
4142 # foo --> original executable
4143
4144 # at the end of the process we have:
4145 # foo.stripped --> foo w/o debug info
4146 # foo.debug --> foo's debug info
4147 # foo --> like foo, but with a new .gnu_debuglink section pointing to foo.debug.
4148
4149 # Return the build-id hex string (usually 160 bits as 40 hex characters)
4150 # converted to the form: .build-id/ab/cdef1234...89.debug
4151 # Return "" if no build-id found.
4152 proc build_id_debug_filename_get { exec } {
4153     set tmp [standard_output_file "${exec}-tmp"]
4154     set objcopy_program [gdb_find_objcopy]
4155
4156     set result [catch "exec $objcopy_program -j .note.gnu.build-id -O binary $exec $tmp" output]
4157     verbose "result is $result"
4158     verbose "output is $output"
4159     if {$result == 1} {
4160         return ""
4161     }
4162     set fi [open $tmp]
4163     fconfigure $fi -translation binary
4164     # Skip the NOTE header.
4165     read $fi 16
4166     set data [read $fi]
4167     close $fi
4168     file delete $tmp
4169     if ![string compare $data ""] then {
4170         return ""
4171     }
4172     # Convert it to hex.
4173     binary scan $data H* data
4174     regsub {^..} $data {\0/} data
4175     return ".build-id/${data}.debug"
4176 }
4177
4178 # Create stripped files for DEST, replacing it.  If ARGS is passed, it is a
4179 # list of optional flags.  The only currently supported flag is no-main,
4180 # which removes the symbol entry for main from the separate debug file.
4181 #
4182 # Function returns zero on success.  Function will return non-zero failure code
4183 # on some targets not supporting separate debug info (such as i386-msdos).
4184
4185 proc gdb_gnu_strip_debug { dest args } {
4186
4187     # Use the first separate debug info file location searched by GDB so the
4188     # run cannot be broken by some stale file searched with higher precedence.
4189     set debug_file "${dest}.debug"
4190
4191     set strip_to_file_program [transform strip]
4192     set objcopy_program [gdb_find_objcopy]
4193
4194     set debug_link [file tail $debug_file]
4195     set stripped_file "${dest}.stripped"
4196
4197     # Get rid of the debug info, and store result in stripped_file
4198     # something like gdb/testsuite/gdb.base/blah.stripped.
4199     set result [catch "exec $strip_to_file_program --strip-debug ${dest} -o ${stripped_file}" output]
4200     verbose "result is $result"
4201     verbose "output is $output"
4202     if {$result == 1} {
4203       return 1
4204     }
4205
4206     # Workaround PR binutils/10802:
4207     # Preserve the 'x' bit also for PIEs (Position Independent Executables).
4208     set perm [file attributes ${dest} -permissions]
4209     file attributes ${stripped_file} -permissions $perm
4210
4211     # Get rid of everything but the debug info, and store result in debug_file
4212     # This will be in the .debug subdirectory, see above.
4213     set result [catch "exec $strip_to_file_program --only-keep-debug ${dest} -o ${debug_file}" output]
4214     verbose "result is $result"
4215     verbose "output is $output"
4216     if {$result == 1} {
4217       return 1
4218     }
4219
4220     # If no-main is passed, strip the symbol for main from the separate
4221     # file.  This is to simulate the behavior of elfutils's eu-strip, which
4222     # leaves the symtab in the original file only.  There's no way to get
4223     # objcopy or strip to remove the symbol table without also removing the
4224     # debugging sections, so this is as close as we can get.
4225     if { [llength $args] == 1 && [lindex $args 0] == "no-main" } {
4226         set result [catch "exec $objcopy_program -N main ${debug_file} ${debug_file}-tmp" output]
4227         verbose "result is $result"
4228         verbose "output is $output"
4229         if {$result == 1} {
4230             return 1
4231         }
4232         file delete "${debug_file}"
4233         file rename "${debug_file}-tmp" "${debug_file}"
4234     }
4235
4236     # Link the two previous output files together, adding the .gnu_debuglink
4237     # section to the stripped_file, containing a pointer to the debug_file,
4238     # save the new file in dest.
4239     # This will be the regular executable filename, in the usual location.
4240     set result [catch "exec $objcopy_program --add-gnu-debuglink=${debug_file} ${stripped_file} ${dest}" output]
4241     verbose "result is $result"
4242     verbose "output is $output"
4243     if {$result == 1} {
4244       return 1
4245     }
4246
4247     # Workaround PR binutils/10802:
4248     # Preserve the 'x' bit also for PIEs (Position Independent Executables).
4249     set perm [file attributes ${stripped_file} -permissions]
4250     file attributes ${dest} -permissions $perm
4251
4252     return 0
4253 }
4254
4255 # Test the output of GDB_COMMAND matches the pattern obtained
4256 # by concatenating all elements of EXPECTED_LINES.  This makes
4257 # it possible to split otherwise very long string into pieces.
4258 # If third argument is not empty, it's used as the name of the
4259 # test to be printed on pass/fail.
4260 proc help_test_raw { gdb_command expected_lines args } {
4261     set message $gdb_command
4262     if [llength $args]>0 then {
4263         set message [lindex $args 0]
4264     } 
4265     set expected_output [join $expected_lines ""]
4266     gdb_test "${gdb_command}" "${expected_output}" $message
4267 }
4268
4269 # Test the output of "help COMMAND_CLASS". EXPECTED_INITIAL_LINES
4270 # are regular expressions that should match the beginning of output,
4271 # before the list of commands in that class.  The presence of 
4272 # command list and standard epilogue will be tested automatically.
4273 proc test_class_help { command_class expected_initial_lines args } {
4274     set l_stock_body {
4275         "List of commands\:.*\[\r\n\]+"
4276         "Type \"help\" followed by command name for full documentation\.\[\r\n\]+"
4277         "Type \"apropos word\" to search for commands related to \"word\"\.[\r\n\]+"
4278         "Command name abbreviations are allowed if unambiguous\." 
4279     }
4280     set l_entire_body [concat $expected_initial_lines $l_stock_body]
4281
4282     eval [list help_test_raw "help ${command_class}" $l_entire_body] $args
4283 }
4284
4285 # COMMAND_LIST should have either one element -- command to test, or
4286 # two elements -- abbreviated command to test, and full command the first
4287 # element is abbreviation of.
4288 # The command must be a prefix command.  EXPECTED_INITIAL_LINES
4289 # are regular expressions that should match the beginning of output,
4290 # before the list of subcommands.  The presence of 
4291 # subcommand list and standard epilogue will be tested automatically.
4292 proc test_prefix_command_help { command_list expected_initial_lines args } {
4293     set command [lindex $command_list 0]   
4294     if {[llength $command_list]>1} {        
4295         set full_command [lindex $command_list 1]
4296     } else {
4297         set full_command $command
4298     }
4299     # Use 'list' and not just {} because we want variables to
4300     # be expanded in this list.
4301     set l_stock_body [list\
4302          "List of $full_command subcommands\:.*\[\r\n\]+"\
4303          "Type \"help $full_command\" followed by $full_command subcommand name for full documentation\.\[\r\n\]+"\
4304          "Type \"apropos word\" to search for commands related to \"word\"\.\[\r\n\]+"\
4305          "Command name abbreviations are allowed if unambiguous\."]
4306     set l_entire_body [concat $expected_initial_lines $l_stock_body]
4307     if {[llength $args]>0} {
4308         help_test_raw "help ${command}" $l_entire_body [lindex $args 0]
4309     } else {
4310         help_test_raw "help ${command}" $l_entire_body
4311     }
4312 }
4313
4314 # Build executable named EXECUTABLE from specifications that allow
4315 # different options to be passed to different sub-compilations.
4316 # TESTNAME is the name of the test; this is passed to 'untested' if
4317 # something fails.
4318 # OPTIONS is passed to the final link, using gdb_compile.  If OPTIONS
4319 # contains the option "pthreads", then gdb_compile_pthreads is used.
4320 # ARGS is a flat list of source specifications, of the form:
4321 #    { SOURCE1 OPTIONS1 [ SOURCE2 OPTIONS2 ]... }
4322 # Each SOURCE is compiled to an object file using its OPTIONS,
4323 # using gdb_compile.
4324 # Returns 0 on success, -1 on failure.
4325 proc build_executable_from_specs {testname executable options args} {
4326     global subdir
4327     global srcdir
4328
4329     set binfile [standard_output_file $executable]
4330
4331     set info_options ""
4332     if { [lsearch -exact $options "c++"] >= 0 } {
4333         set info_options "c++"
4334     }
4335     if [get_compiler_info ${info_options}] {
4336         return -1
4337     }
4338
4339     set func gdb_compile
4340     set func_index [lsearch -regexp $options {^(pthreads|shlib|shlib_pthreads)$}]
4341     if {$func_index != -1} {
4342         set func "${func}_[lindex $options $func_index]"
4343     }
4344
4345     # gdb_compile_shlib and gdb_compile_shlib_pthreads do not use the 3rd
4346     # parameter.  They also requires $sources while gdb_compile and
4347     # gdb_compile_pthreads require $objects.  Moreover they ignore any options.
4348     if [string match gdb_compile_shlib* $func] {
4349         set sources_path {}
4350         foreach {s local_options} $args {
4351             if { [regexp "^/" "$s"] } then {
4352                 lappend sources_path "$s"
4353             } else {
4354                 lappend sources_path "$srcdir/$subdir/$s"
4355             }
4356         }
4357         set ret [$func $sources_path "${binfile}" $options]
4358     } else {
4359         set objects {}
4360         set i 0
4361         foreach {s local_options} $args {
4362             if { ! [regexp "^/" "$s"] } then {
4363                 set s "$srcdir/$subdir/$s"
4364             }
4365             if  { [gdb_compile "${s}" "${binfile}${i}.o" object $local_options] != "" } {
4366                 untested $testname
4367                 return -1
4368             }
4369             lappend objects "${binfile}${i}.o"
4370             incr i
4371         }
4372         set ret [$func $objects "${binfile}" executable $options]
4373     }
4374     if  { $ret != "" } {
4375         untested $testname
4376         return -1
4377     }
4378
4379     return 0
4380 }
4381
4382 # Build executable named EXECUTABLE, from SOURCES.  If SOURCES are not
4383 # provided, uses $EXECUTABLE.c.  The TESTNAME paramer is the name of test
4384 # to pass to untested, if something is wrong.  OPTIONS are passed
4385 # to gdb_compile directly.
4386 proc build_executable { testname executable {sources ""} {options {debug}} } {
4387     if {[llength $sources]==0} {
4388         set sources ${executable}.c
4389     }
4390
4391     set arglist [list $testname $executable $options]
4392     foreach source $sources {
4393         lappend arglist $source $options
4394     }
4395
4396     return [eval build_executable_from_specs $arglist]
4397 }
4398
4399 # Starts fresh GDB binary and loads EXECUTABLE into GDB. EXECUTABLE is
4400 # the basename of the binary.
4401 proc clean_restart { executable } {
4402     global srcdir
4403     global subdir
4404     set binfile [standard_output_file ${executable}]
4405
4406     gdb_exit
4407     gdb_start
4408     gdb_reinitialize_dir $srcdir/$subdir
4409     gdb_load ${binfile}
4410 }
4411
4412 # Prepares for testing by calling build_executable_full, then
4413 # clean_restart.
4414 # TESTNAME is the name of the test.
4415 # Each element in ARGS is a list of the form
4416 #    { EXECUTABLE OPTIONS SOURCE_SPEC... }
4417 # These are passed to build_executable_from_specs, which see.
4418 # The last EXECUTABLE is passed to clean_restart.
4419 # Returns 0 on success, non-zero on failure.
4420 proc prepare_for_testing_full {testname args} {
4421     foreach spec $args {
4422         if {[eval build_executable_from_specs [list $testname] $spec] == -1} {
4423             return -1
4424         }
4425         set executable [lindex $spec 0]
4426     }
4427     clean_restart $executable
4428     return 0
4429 }
4430
4431 # Prepares for testing, by calling build_executable, and then clean_restart.
4432 # Please refer to build_executable for parameter description.
4433 proc prepare_for_testing { testname executable {sources ""} {options {debug}}} {
4434
4435     if {[build_executable $testname $executable $sources $options] == -1} {
4436         return -1
4437     }
4438     clean_restart $executable
4439
4440     return 0
4441 }
4442
4443 proc get_valueof { fmt exp default } {
4444     global gdb_prompt
4445
4446     set test "get valueof \"${exp}\""
4447     set val ${default}
4448     gdb_test_multiple "print${fmt} ${exp}" "$test" {
4449         -re "\\$\[0-9\]* = (.*)\[\r\n\]*$gdb_prompt $" {
4450             set val $expect_out(1,string)
4451             pass "$test ($val)"
4452         }
4453         timeout {
4454             fail "$test (timeout)"
4455         }
4456     }
4457     return ${val}
4458 }
4459
4460 proc get_integer_valueof { exp default } {
4461     global gdb_prompt
4462
4463     set test "get integer valueof \"${exp}\""
4464     set val ${default}
4465     gdb_test_multiple "print /d ${exp}" "$test" {
4466         -re "\\$\[0-9\]* = (\[-\]*\[0-9\]*).*$gdb_prompt $" {
4467             set val $expect_out(1,string)
4468             pass "$test ($val)"
4469         }
4470         timeout {
4471             fail "$test (timeout)"
4472         }
4473     }
4474     return ${val}
4475 }
4476
4477 proc get_hexadecimal_valueof { exp default } {
4478     global gdb_prompt
4479     send_gdb "print /x ${exp}\n"
4480     set test "get hexadecimal valueof \"${exp}\""
4481     gdb_expect {
4482         -re "\\$\[0-9\]* = (0x\[0-9a-zA-Z\]+).*$gdb_prompt $" {
4483             set val $expect_out(1,string)
4484             pass "$test"
4485         }
4486         timeout {
4487             set val ${default}
4488             fail "$test (timeout)"
4489         }
4490     }
4491     return ${val}
4492 }
4493
4494 proc get_sizeof { type default } {
4495     return [get_integer_valueof "sizeof (${type})" $default]
4496 }
4497
4498 proc get_target_charset { } {
4499     global gdb_prompt
4500
4501     gdb_test_multiple "show target-charset" "" {
4502         -re "The target character set is \"auto; currently (\[^\"\]*)\".*$gdb_prompt $" {
4503             return $expect_out(1,string)
4504         }
4505         -re "The target character set is \"(\[^\"\]*)\".*$gdb_prompt $" {
4506             return $expect_out(1,string)
4507         }
4508     }
4509
4510     # Pick a reasonable default.
4511     warning "Unable to read target-charset."
4512     return "UTF-8"
4513 }
4514
4515 # Get the current value for remotetimeout and return it.
4516 proc get_remotetimeout { } {
4517     global gdb_prompt
4518     global decimal
4519
4520     gdb_test_multiple "show remotetimeout" "" {
4521         -re "Timeout limit to wait for target to respond is ($decimal).*$gdb_prompt $" {
4522             return $expect_out(1,string)
4523         }
4524     }
4525
4526     # Pick the default that gdb uses
4527     warning "Unable to read remotetimeout"
4528     return 300
4529 }
4530
4531 # Set the remotetimeout to the specified timeout.  Nothing is returned.
4532 proc set_remotetimeout { timeout } {
4533     global gdb_prompt
4534
4535     gdb_test_multiple "set remotetimeout $timeout" "" {
4536         -re "$gdb_prompt $" {
4537             verbose "Set remotetimeout to $timeout\n"
4538         }
4539     }
4540 }
4541
4542 # ROOT and FULL are file names.  Returns the relative path from ROOT
4543 # to FULL.  Note that FULL must be in a subdirectory of ROOT.
4544 # For example, given ROOT = /usr/bin and FULL = /usr/bin/ls, this
4545 # will return "ls".
4546
4547 proc relative_filename {root full} {
4548     set root_split [file split $root]
4549     set full_split [file split $full]
4550
4551     set len [llength $root_split]
4552
4553     if {[eval file join $root_split]
4554         != [eval file join [lrange $full_split 0 [expr {$len - 1}]]]} {
4555         error "$full not a subdir of $root"
4556     }
4557
4558     return [eval file join [lrange $full_split $len end]]
4559 }
4560
4561 # Log gdb command line and script if requested.
4562 if {[info exists TRANSCRIPT]} {
4563   rename send_gdb real_send_gdb
4564   rename remote_spawn real_remote_spawn
4565   rename remote_close real_remote_close
4566
4567   global gdb_transcript
4568   set gdb_transcript ""
4569
4570   global gdb_trans_count
4571   set gdb_trans_count 1
4572
4573   proc remote_spawn {args} {
4574     global gdb_transcript gdb_trans_count outdir
4575
4576     if {$gdb_transcript != ""} {
4577       close $gdb_transcript
4578     }
4579     set gdb_transcript [open [file join $outdir transcript.$gdb_trans_count] w]
4580     puts $gdb_transcript [lindex $args 1]
4581     incr gdb_trans_count
4582
4583     return [uplevel real_remote_spawn $args]
4584   }
4585
4586   proc remote_close {args} {
4587     global gdb_transcript
4588
4589     if {$gdb_transcript != ""} {
4590       close $gdb_transcript
4591       set gdb_transcript ""
4592     }
4593
4594     return [uplevel real_remote_close $args]
4595   }
4596
4597   proc send_gdb {args} {
4598     global gdb_transcript
4599
4600     if {$gdb_transcript != ""} {
4601       puts -nonewline $gdb_transcript [lindex $args 0]
4602     }
4603
4604     return [uplevel real_send_gdb $args]
4605   }
4606 }
4607
4608 # If GDB_PARALLEL exists, then set up the parallel-mode directories.
4609 if {[info exists GDB_PARALLEL]} {
4610     if {[is_remote host]} {
4611         unset GDB_PARALLEL
4612     } else {
4613         file mkdir outputs temp cache
4614     }
4615 }
4616
4617 proc core_find {binfile {deletefiles {}} {arg ""}} {
4618     global objdir subdir
4619
4620     set destcore "$binfile.core"
4621     file delete $destcore
4622
4623     # Create a core file named "$destcore" rather than just "core", to
4624     # avoid problems with sys admin types that like to regularly prune all
4625     # files named "core" from the system.
4626     #
4627     # Arbitrarily try setting the core size limit to "unlimited" since
4628     # this does not hurt on systems where the command does not work and
4629     # allows us to generate a core on systems where it does.
4630     #
4631     # Some systems append "core" to the name of the program; others append
4632     # the name of the program to "core"; still others (like Linux, as of
4633     # May 2003) create cores named "core.PID".  In the latter case, we
4634     # could have many core files lying around, and it may be difficult to
4635     # tell which one is ours, so let's run the program in a subdirectory.
4636     set found 0
4637     set coredir [standard_output_file coredir.[getpid]]
4638     file mkdir $coredir
4639     catch "system \"(cd ${coredir}; ulimit -c unlimited; ${binfile} ${arg}; true) >/dev/null 2>&1\""
4640     #      remote_exec host "${binfile}"
4641     foreach i "${coredir}/core ${coredir}/core.coremaker.c ${binfile}.core" {
4642         if [remote_file build exists $i] {
4643             remote_exec build "mv $i $destcore"
4644             set found 1
4645         }
4646     }
4647     # Check for "core.PID".
4648     if { $found == 0 } {
4649         set names [glob -nocomplain -directory $coredir core.*]
4650         if {[llength $names] == 1} {
4651             set corefile [file join $coredir [lindex $names 0]]
4652             remote_exec build "mv $corefile $destcore"
4653             set found 1
4654         }
4655     }
4656     if { $found == 0 } {
4657         # The braindamaged HPUX shell quits after the ulimit -c above
4658         # without executing ${binfile}.  So we try again without the
4659         # ulimit here if we didn't find a core file above.
4660         # Oh, I should mention that any "braindamaged" non-Unix system has
4661         # the same problem. I like the cd bit too, it's really neat'n stuff.
4662         catch "system \"(cd ${objdir}/${subdir}; ${binfile}; true) >/dev/null 2>&1\""
4663         foreach i "${objdir}/${subdir}/core ${objdir}/${subdir}/core.coremaker.c ${binfile}.core" {
4664             if [remote_file build exists $i] {
4665                 remote_exec build "mv $i $destcore"
4666                 set found 1
4667             }
4668         }
4669     }
4670
4671     # Try to clean up after ourselves. 
4672     foreach deletefile $deletefiles {
4673         remote_file build delete [file join $coredir $deletefile]
4674     }
4675     remote_exec build "rmdir $coredir"
4676         
4677     if { $found == 0  } {
4678         warning "can't generate a core file - core tests suppressed - check ulimit -c"
4679         return ""
4680     }
4681     return $destcore
4682 }
4683
4684 # gdb_target_symbol_prefix_flags returns a string that can be added
4685 # to gdb_compile options to define SYMBOL_PREFIX macro value
4686 # symbol_prefix_flags returns a string that can be added
4687 # for targets that use underscore as symbol prefix.
4688 # TODO: find out automatically if the target needs this.
4689
4690 proc gdb_target_symbol_prefix_flags {} {
4691     if { [istarget "*-*-cygwin*"] || [istarget "i?86-*-mingw*"]
4692          || [istarget "*-*-msdosdjgpp*"] || [istarget "*-*-go32*"] } {
4693         return "additional_flags=-DSYMBOL_PREFIX=\"_\""
4694     } else {
4695         return ""
4696     }
4697 }
4698
4699 # A wrapper for 'remote_exec host' that passes or fails a test.
4700 # Returns 0 if all went well, nonzero on failure.
4701 # TEST is the name of the test, other arguments are as for remote_exec.
4702
4703 proc run_on_host { test program args } {
4704     verbose -log "run_on_host: $program $args"
4705     # remote_exec doesn't work properly if the output is set but the
4706     # input is the empty string -- so replace an empty input with
4707     # /dev/null.
4708     if {[llength $args] > 1 && [lindex $args 1] == ""} {
4709         set args [lreplace $args 1 1 "/dev/null"]
4710     }
4711     set result [eval remote_exec host [list $program] $args]
4712     verbose "result is $result"
4713     set status [lindex $result 0]
4714     set output [lindex $result 1]
4715     if {$status == 0} {
4716         pass $test
4717         return 0
4718     } else {
4719         verbose -log "run_on_host failed: $output"
4720         fail $test
4721         return -1
4722     }
4723 }
4724
4725 # Return non-zero if "board_info debug_flags" mentions Fission.
4726 # http://gcc.gnu.org/wiki/DebugFission
4727 # Fission doesn't support everything yet.
4728 # This supports working around bug 15954.
4729
4730 proc using_fission { } {
4731     set debug_flags [board_info [target_info name] debug_flags]
4732     return [regexp -- "-gsplit-dwarf" $debug_flags]
4733 }
4734
4735 # Search the caller's ARGS list and set variables according to the list of
4736 # valid options described by ARGSET.
4737 #
4738 # The first member of each one- or two-element list in ARGSET defines the
4739 # name of a variable that will be added to the caller's scope.
4740 #
4741 # If only one element is given to describe an option, it the value is
4742 # 0 if the option is not present in (the caller's) ARGS or 1 if
4743 # it is.
4744 #
4745 # If two elements are given, the second element is the default value of
4746 # the variable.  This is then overwritten if the option exists in ARGS.
4747 #
4748 # Any parse_args elements in (the caller's) ARGS will be removed, leaving
4749 # any optional components.
4750
4751 # Example:
4752 # proc myproc {foo args} {
4753 #  parse_args {{bar} {baz "abc"} {qux}}
4754 #    # ...
4755 # }
4756 # myproc ABC -bar -baz DEF peanut butter
4757 # will define the following variables in myproc:
4758 # foo (=ABC), bar (=1), baz (=DEF), and qux (=0)
4759 # args will be the list {peanut butter}
4760
4761 proc parse_args { argset } {
4762     upvar args args
4763
4764     foreach argument $argset {
4765         if {[llength $argument] == 1} {
4766             # No default specified, so we assume that we should set
4767             # the value to 1 if the arg is present and 0 if it's not.
4768             # It is assumed that no value is given with the argument.
4769             set result [lsearch -exact $args "-$argument"]
4770             if {$result != -1} then {
4771                 uplevel 1 [list set $argument 1]
4772                 set args [lreplace $args $result $result]
4773             } else {
4774                 uplevel 1 [list set $argument 0]
4775             }
4776         } elseif {[llength $argument] == 2} {
4777             # There are two items in the argument.  The second is a
4778             # default value to use if the item is not present.
4779             # Otherwise, the variable is set to whatever is provided
4780             # after the item in the args.
4781             set arg [lindex $argument 0]
4782             set result [lsearch -exact $args "-[lindex $arg 0]"]
4783             if {$result != -1} then {
4784                 uplevel 1 [list set $arg [lindex $args [expr $result+1]]]
4785                 set args [lreplace $args $result [expr $result+1]]
4786             } else {
4787                 uplevel 1 [list set $arg [lindex $argument 1]]
4788             }
4789         } else {
4790             error "Badly formatted argument \"$argument\" in argument set"
4791         }
4792     }
4793
4794     # The remaining args should be checked to see that they match the
4795     # number of items expected to be passed into the procedure...
4796 }
4797
4798 # Capture the output of COMMAND in a string ignoring PREFIX; return that string.
4799 proc capture_command_output { command prefix } {
4800     global gdb_prompt
4801     global expect_out
4802
4803     set output_string ""
4804     gdb_test_multiple "$command" "capture_command_output for $command" {
4805         -re "${command}\[\r\n\]+${prefix}(.*)\[\r\n\]+$gdb_prompt $" {
4806             set output_string $expect_out(1,string)
4807         }
4808     }
4809     return $output_string
4810 }
4811
4812 # Always load compatibility stuff.
4813 load_lib future.exp