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