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