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