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