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