xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/testsuite/lib/gdb.exp (revision 8b657b0747480f8989760d71343d6dd33f8d4cf9)
1# Copyright 1992-2023 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
28# Execute BODY, if COND wrapped in proc WRAP.
29# Instead of writing the verbose and repetitive:
30#   if { $cond } {
31#     wrap $body
32#   } else {
33#     $body
34#   }
35# we can use instead:
36#   cond_wrap $cond wrap $body
37
38proc cond_wrap { cond wrap body } {
39    if { $cond } {
40	$wrap {
41	    uplevel 1 $body
42	}
43    } else {
44	uplevel 1 $body
45    }
46}
47
48# Add VAR_ID=VAL to ENV_VAR, unless ENV_VAR already contains a VAR_ID setting.
49
50proc set_sanitizer_default { env_var var_id val } {
51    global env
52
53    if { ![info exists env($env_var) ]
54	 || $env($env_var) == "" } {
55	# Set var_id (env_var non-existing / empty case).
56	append env($env_var) $var_id=$val
57	return
58    }
59
60    if { [regexp $var_id= $env($env_var)] } {
61	# Don't set var_id.  It's already set by the user, leave as is.
62	# Note that we could probably get the same result by unconditionally
63	# prepending it, but this way is less likely to cause confusion.
64	return
65    }
66
67    # Set var_id (env_var not empty case).
68    append env($env_var) : $var_id=$val
69}
70
71set_sanitizer_default TSAN_OPTIONS suppressions \
72    $srcdir/../tsan-suppressions.txt
73
74# If GDB is built with ASAN (and because there are leaks), it will output a
75# leak report when exiting as well as exit with a non-zero (failure) status.
76# This can affect tests that are sensitive to what GDB prints on stderr or its
77# exit status.  Add `detect_leaks=0` to the ASAN_OPTIONS environment variable
78# (which will affect any spawned sub-process) to avoid this.
79set_sanitizer_default ASAN_OPTIONS detect_leaks 0
80
81# List of procs to run in gdb_finish.
82set gdb_finish_hooks [list]
83
84# Variable in which we keep track of globals that are allowed to be live
85# across test-cases.
86array set gdb_persistent_globals {}
87
88# Mark variable names in ARG as a persistent global, and declare them as
89# global in the calling context.  Can be used to rewrite "global var_a var_b"
90# into "gdb_persistent_global var_a var_b".
91proc gdb_persistent_global { args } {
92    global gdb_persistent_globals
93    foreach varname $args {
94	uplevel 1 global $varname
95	set gdb_persistent_globals($varname) 1
96    }
97}
98
99# Mark variable names in ARG as a persistent global.
100proc gdb_persistent_global_no_decl { args } {
101    global gdb_persistent_globals
102    foreach varname $args {
103	set gdb_persistent_globals($varname) 1
104    }
105}
106
107# Override proc load_lib.
108rename load_lib saved_load_lib
109# Run the runtest version of load_lib, and mark all variables that were
110# created by this call as persistent.
111proc load_lib { file } {
112    array set known_global {}
113    foreach varname [info globals] {
114       set known_globals($varname) 1
115    }
116
117    set code [catch "saved_load_lib $file" result]
118
119    foreach varname [info globals] {
120       if { ![info exists known_globals($varname)] } {
121           gdb_persistent_global_no_decl $varname
122       }
123    }
124
125    if {$code == 1} {
126	global errorInfo errorCode
127	return -code error -errorinfo $errorInfo -errorcode $errorCode $result
128    } elseif {$code > 1} {
129	return -code $code $result
130    }
131
132    return $result
133}
134
135load_lib libgloss.exp
136load_lib cache.exp
137load_lib gdb-utils.exp
138load_lib memory.exp
139load_lib check-test-names.exp
140
141# The path to the GDB binary to test.
142global GDB
143
144# The data directory to use for testing.  If this is the empty string,
145# then we let GDB use its own configured data directory.
146global GDB_DATA_DIRECTORY
147
148# The spawn ID used for I/O interaction with the inferior.  For native
149# targets, or remote targets that can do I/O through GDB
150# (semi-hosting) this will be the same as the host/GDB's spawn ID.
151# Otherwise, the board may set this to some other spawn ID.  E.g.,
152# when debugging with GDBserver, this is set to GDBserver's spawn ID,
153# so input/output is done on gdbserver's tty.
154global inferior_spawn_id
155
156if [info exists TOOL_EXECUTABLE] {
157    set GDB $TOOL_EXECUTABLE
158}
159if ![info exists GDB] {
160    if ![is_remote host] {
161	set GDB [findfile $base_dir/../../gdb/gdb "$base_dir/../../gdb/gdb" [transform gdb]]
162    } else {
163	set GDB [transform gdb]
164    }
165} else {
166    # If the user specifies GDB on the command line, and doesn't
167    # specify GDB_DATA_DIRECTORY, then assume we're testing an
168    # installed GDB, and let it use its own configured data directory.
169    if ![info exists GDB_DATA_DIRECTORY] {
170	set GDB_DATA_DIRECTORY ""
171    }
172}
173verbose "using GDB = $GDB" 2
174
175# The data directory the testing GDB will use.  By default, assume
176# we're testing a non-installed GDB in the build directory.  Users may
177# also explictly override the -data-directory from the command line.
178if ![info exists GDB_DATA_DIRECTORY] {
179    set GDB_DATA_DIRECTORY "[pwd]/../data-directory"
180}
181verbose "using GDB_DATA_DIRECTORY = $GDB_DATA_DIRECTORY" 2
182
183# GDBFLAGS is available for the user to set on the command line.
184# E.g. make check RUNTESTFLAGS=GDBFLAGS=mumble
185# Testcases may use it to add additional flags, but they must:
186# - append new flags, not overwrite
187# - restore the original value when done
188global GDBFLAGS
189if ![info exists GDBFLAGS] {
190    set GDBFLAGS ""
191}
192verbose "using GDBFLAGS = $GDBFLAGS" 2
193
194# Append the -data-directory option to pass to GDB to CMDLINE and
195# return the resulting string.  If GDB_DATA_DIRECTORY is empty,
196# nothing is appended.
197proc append_gdb_data_directory_option {cmdline} {
198    global GDB_DATA_DIRECTORY
199
200    if { $GDB_DATA_DIRECTORY != "" } {
201	return "$cmdline -data-directory $GDB_DATA_DIRECTORY"
202    } else {
203	return $cmdline
204    }
205}
206
207# INTERNAL_GDBFLAGS contains flags that the testsuite requires.
208# `-nw' disables any of the windowed interfaces.
209# `-nx' disables ~/.gdbinit, so that it doesn't interfere with the tests.
210# `-iex "set {height,width} 0"' disables pagination.
211# `-data-directory' points to the data directory, usually in the build
212# directory.
213global INTERNAL_GDBFLAGS
214if ![info exists INTERNAL_GDBFLAGS] {
215    set INTERNAL_GDBFLAGS \
216	[join [list \
217		   "-nw" \
218		   "-nx" \
219		   {-iex "set height 0"} \
220		   {-iex "set width 0"}]]
221
222    set INTERNAL_GDBFLAGS [append_gdb_data_directory_option $INTERNAL_GDBFLAGS]
223}
224
225# The variable gdb_prompt is a regexp which matches the gdb prompt.
226# Set it if it is not already set.  This is also set by default_gdb_init
227# but it's not clear what removing one of them will break.
228# See with_gdb_prompt for more details on prompt handling.
229global gdb_prompt
230if {![info exists gdb_prompt]} {
231    set gdb_prompt "\\(gdb\\)"
232}
233
234# A regexp that matches the pagination prompt.
235set pagination_prompt \
236    "--Type <RET> for more, q to quit, c to continue without paging--"
237
238# The variable fullname_syntax_POSIX is a regexp which matches a POSIX
239# absolute path ie. /foo/
240set fullname_syntax_POSIX {/[^\n]*/}
241# The variable fullname_syntax_UNC is a regexp which matches a Windows
242# UNC path ie. \\D\foo\
243set fullname_syntax_UNC {\\\\[^\\]+\\[^\n]+\\}
244# The variable fullname_syntax_DOS_CASE is a regexp which matches a
245# particular DOS case that GDB most likely will output
246# ie. \foo\, but don't match \\.*\
247set fullname_syntax_DOS_CASE {\\[^\\][^\n]*\\}
248# The variable fullname_syntax_DOS is a regexp which matches a DOS path
249# ie. a:\foo\ && a:foo\
250set fullname_syntax_DOS {[a-zA-Z]:[^\n]*\\}
251# The variable fullname_syntax is a regexp which matches what GDB considers
252# an absolute path. It is currently debatable if the Windows style paths
253# d:foo and \abc should be considered valid as an absolute path.
254# Also, the purpse of this regexp is not to recognize a well formed
255# absolute path, but to say with certainty that a path is absolute.
256set fullname_syntax "($fullname_syntax_POSIX|$fullname_syntax_UNC|$fullname_syntax_DOS_CASE|$fullname_syntax_DOS)"
257
258# Needed for some tests under Cygwin.
259global EXEEXT
260global env
261
262if ![info exists env(EXEEXT)] {
263    set EXEEXT ""
264} else {
265    set EXEEXT $env(EXEEXT)
266}
267
268set octal "\[0-7\]+"
269
270set inferior_exited_re "(?:\\\[Inferior \[0-9\]+ \\(\[^\n\r\]*\\) exited)"
271
272# A regular expression that matches a value history number.
273# E.g., $1, $2, etc.
274set valnum_re "\\\$$decimal"
275
276# A regular expression that matches a breakpoint hit with a breakpoint
277# having several code locations.
278set bkptno_num_re "$decimal\\.$decimal"
279
280# A regular expression that matches a breakpoint hit
281# with one or several code locations.
282set bkptno_numopt_re "($decimal\\.$decimal|$decimal)"
283
284### Only procedures should come after this point.
285
286#
287# gdb_version -- extract and print the version number of GDB
288#
289proc default_gdb_version {} {
290    global GDB
291    global INTERNAL_GDBFLAGS GDBFLAGS
292    global gdb_prompt
293    global inotify_pid
294
295    if {[info exists inotify_pid]} {
296	eval exec kill $inotify_pid
297    }
298
299    set output [remote_exec host "$GDB $INTERNAL_GDBFLAGS --version"]
300    set tmp [lindex $output 1]
301    set version ""
302    regexp " \[0-9\]\[^ \t\n\r\]+" "$tmp" version
303    if ![is_remote host] {
304	clone_output "[which $GDB] version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
305    } else {
306	clone_output "$GDB on remote host version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
307    }
308}
309
310proc gdb_version { } {
311    return [default_gdb_version]
312}
313
314# gdb_unload -- unload a file if one is loaded
315#
316# Returns the same as gdb_test_multiple.
317
318proc gdb_unload { {msg "file"} } {
319    global GDB
320    global gdb_prompt
321    return [gdb_test_multiple "file" $msg {
322	-re "A program is being debugged already.\r\nAre you sure you want to change the file. .y or n. $" {
323	    send_gdb "y\n" answer
324	    exp_continue
325	}
326
327	-re "No executable file now\\.\r\n" {
328	    exp_continue
329	}
330
331	-re "Discard symbol table from `.*'. .y or n. $" {
332	    send_gdb "y\n" answer
333	    exp_continue
334	}
335
336	-re -wrap "No symbol file now\\." {
337	    pass $gdb_test_name
338	}
339    }]
340}
341
342# Many of the tests depend on setting breakpoints at various places and
343# running until that breakpoint is reached.  At times, we want to start
344# with a clean-slate with respect to breakpoints, so this utility proc
345# lets us do this without duplicating this code everywhere.
346#
347
348proc delete_breakpoints {} {
349    global gdb_prompt
350
351    # we need a larger timeout value here or this thing just confuses
352    # itself.  May need a better implementation if possible. - guo
353    #
354    set timeout 100
355
356    set msg "delete all breakpoints in delete_breakpoints"
357    set deleted 0
358    gdb_test_multiple "delete breakpoints" "$msg" {
359	-re "Delete all breakpoints.*y or n.*$" {
360	    send_gdb "y\n" answer
361	    exp_continue
362	}
363	-re "$gdb_prompt $" {
364	    set deleted 1
365	}
366    }
367
368    if {$deleted} {
369	# Confirm with "info breakpoints".
370	set deleted 0
371	set msg "info breakpoints"
372	gdb_test_multiple $msg $msg {
373	    -re "No breakpoints or watchpoints..*$gdb_prompt $" {
374		set deleted 1
375	    }
376	    -re "$gdb_prompt $" {
377	    }
378	}
379    }
380
381    if {!$deleted} {
382	perror "breakpoints not deleted"
383    }
384}
385
386# Returns true iff the target supports using the "run" command.
387
388proc target_can_use_run_cmd {} {
389    if [target_info exists use_gdb_stub] {
390	# In this case, when we connect, the inferior is already
391	# running.
392	return 0
393    }
394
395    # Assume yes.
396    return 1
397}
398
399# Generic run command.
400#
401# Return 0 if we could start the program, -1 if we could not.
402#
403# The second pattern below matches up to the first newline *only*.
404# Using ``.*$'' could swallow up output that we attempt to match
405# elsewhere.
406#
407# INFERIOR_ARGS is passed as arguments to the start command, so may contain
408# inferior arguments.
409#
410# N.B. This function does not wait for gdb to return to the prompt,
411# that is the caller's responsibility.
412
413proc gdb_run_cmd { {inferior_args {}} } {
414    global gdb_prompt use_gdb_stub
415
416    foreach command [gdb_init_commands] {
417	send_gdb "$command\n"
418	gdb_expect 30 {
419	    -re "$gdb_prompt $" { }
420	    default {
421		perror "gdb_init_command for target failed"
422		return
423	    }
424	}
425    }
426
427    if $use_gdb_stub {
428	if [target_info exists gdb,do_reload_on_run] {
429	    if { [gdb_reload $inferior_args] != 0 } {
430		return -1
431	    }
432	    send_gdb "continue\n"
433	    gdb_expect 60 {
434		-re "Continu\[^\r\n\]*\[\r\n\]" {}
435		default {}
436	    }
437	    return 0
438	}
439
440	if [target_info exists gdb,start_symbol] {
441	    set start [target_info gdb,start_symbol]
442	} else {
443	    set start "start"
444	}
445	send_gdb  "jump *$start\n"
446	set start_attempt 1
447	while { $start_attempt } {
448	    # Cap (re)start attempts at three to ensure that this loop
449	    # always eventually fails.  Don't worry about trying to be
450	    # clever and not send a command when it has failed.
451	    if [expr $start_attempt > 3] {
452		perror "Jump to start() failed (retry count exceeded)"
453		return -1
454	    }
455	    set start_attempt [expr $start_attempt + 1]
456	    gdb_expect 30 {
457		-re "Continuing at \[^\r\n\]*\[\r\n\]" {
458		    set start_attempt 0
459		}
460		-re "No symbol \"_start\" in current.*$gdb_prompt $" {
461		    perror "Can't find start symbol to run in gdb_run"
462		    return -1
463		}
464		-re "No symbol \"start\" in current.*$gdb_prompt $" {
465		    send_gdb "jump *_start\n"
466		}
467		-re "No symbol.*context.*$gdb_prompt $" {
468		    set start_attempt 0
469		}
470		-re "Line.* Jump anyway.*y or n. $" {
471		    send_gdb "y\n" answer
472		}
473		-re "The program is not being run.*$gdb_prompt $" {
474		    if { [gdb_reload $inferior_args] != 0 } {
475			return -1
476		    }
477		    send_gdb "jump *$start\n"
478		}
479		timeout {
480		    perror "Jump to start() failed (timeout)"
481		    return -1
482		}
483	    }
484	}
485
486	return 0
487    }
488
489    if [target_info exists gdb,do_reload_on_run] {
490	if { [gdb_reload $inferior_args] != 0 } {
491	    return -1
492	}
493    }
494    send_gdb "run $inferior_args\n"
495# This doesn't work quite right yet.
496# Use -notransfer here so that test cases (like chng-sym.exp)
497# may test for additional start-up messages.
498   gdb_expect 60 {
499	-re "The program .* has been started already.*y or n. $" {
500	    send_gdb "y\n" answer
501	    exp_continue
502	}
503	-notransfer -re "Starting program: \[^\r\n\]*" {}
504	-notransfer -re "$gdb_prompt $" {
505	    # There is no more input expected.
506	}
507	-notransfer -re "A problem internal to GDB has been detected" {
508	    # Let caller handle this.
509	}
510    }
511
512    return 0
513}
514
515# Generic start command.  Return 0 if we could start the program, -1
516# if we could not.
517#
518# INFERIOR_ARGS is passed as arguments to the start command, so may contain
519# inferior arguments.
520#
521# N.B. This function does not wait for gdb to return to the prompt,
522# that is the caller's responsibility.
523
524proc gdb_start_cmd { {inferior_args {}} } {
525    global gdb_prompt use_gdb_stub
526
527    foreach command [gdb_init_commands] {
528	send_gdb "$command\n"
529	gdb_expect 30 {
530	    -re "$gdb_prompt $" { }
531	    default {
532		perror "gdb_init_command for target failed"
533		return -1
534	    }
535	}
536    }
537
538    if $use_gdb_stub {
539	return -1
540    }
541
542    send_gdb "start $inferior_args\n"
543    # Use -notransfer here so that test cases (like chng-sym.exp)
544    # may test for additional start-up messages.
545    gdb_expect 60 {
546	-re "The program .* has been started already.*y or n. $" {
547	    send_gdb "y\n" answer
548	    exp_continue
549	}
550	-notransfer -re "Starting program: \[^\r\n\]*" {
551	    return 0
552	}
553	-re "$gdb_prompt $" { }
554    }
555    return -1
556}
557
558# Generic starti command.  Return 0 if we could start the program, -1
559# if we could not.
560#
561# INFERIOR_ARGS is passed as arguments to the starti command, so may contain
562# inferior arguments.
563#
564# N.B. This function does not wait for gdb to return to the prompt,
565# that is the caller's responsibility.
566
567proc gdb_starti_cmd { {inferior_args {}} } {
568    global gdb_prompt use_gdb_stub
569
570    foreach command [gdb_init_commands] {
571	send_gdb "$command\n"
572	gdb_expect 30 {
573	    -re "$gdb_prompt $" { }
574	    default {
575		perror "gdb_init_command for target failed"
576		return -1
577	    }
578	}
579    }
580
581    if $use_gdb_stub {
582	return -1
583    }
584
585    send_gdb "starti $inferior_args\n"
586    gdb_expect 60 {
587	-re "The program .* has been started already.*y or n. $" {
588	    send_gdb "y\n" answer
589	    exp_continue
590	}
591	-re "Starting program: \[^\r\n\]*" {
592	    return 0
593	}
594    }
595    return -1
596}
597
598# Set a breakpoint using LINESPEC.
599#
600# If there is an additional argument it is a list of options; the supported
601# options are allow-pending, temporary, message, no-message and qualified.
602#
603# The result is 1 for success, 0 for failure.
604#
605# Note: The handling of message vs no-message is messed up, but it's based
606# on historical usage.  By default this function does not print passes,
607# only fails.
608# no-message: turns off printing of fails (and passes, but they're already off)
609# message: turns on printing of passes (and fails, but they're already on)
610
611proc gdb_breakpoint { linespec args } {
612    global gdb_prompt
613    global decimal
614
615    set pending_response n
616    if {[lsearch -exact $args allow-pending] != -1} {
617	set pending_response y
618    }
619
620    set break_command "break"
621    set break_message "Breakpoint"
622    if {[lsearch -exact $args temporary] != -1} {
623	set break_command "tbreak"
624	set break_message "Temporary breakpoint"
625    }
626
627    if {[lsearch -exact $args qualified] != -1} {
628	append break_command " -qualified"
629    }
630
631    set print_pass 0
632    set print_fail 1
633    set no_message_loc [lsearch -exact $args no-message]
634    set message_loc [lsearch -exact $args message]
635    # The last one to appear in args wins.
636    if { $no_message_loc > $message_loc } {
637	set print_fail 0
638    } elseif { $message_loc > $no_message_loc } {
639	set print_pass 1
640    }
641
642    set test_name "gdb_breakpoint: set breakpoint at $linespec"
643
644    send_gdb "$break_command $linespec\n"
645    # The first two regexps are what we get with -g, the third is without -g.
646    gdb_expect 30 {
647	-re "$break_message \[0-9\]* at .*: file .*, line $decimal.\r\n$gdb_prompt $" {}
648	-re "$break_message \[0-9\]*: file .*, line $decimal.\r\n$gdb_prompt $" {}
649	-re "$break_message \[0-9\]* at .*$gdb_prompt $" {}
650	-re "$break_message \[0-9\]* \\(.*\\) pending.*$gdb_prompt $" {
651		if {$pending_response == "n"} {
652			if { $print_fail } {
653				fail $test_name
654			}
655			return 0
656		}
657	}
658	-re "Make breakpoint pending.*y or \\\[n\\\]. $" {
659		send_gdb "$pending_response\n"
660		exp_continue
661	}
662	-re "A problem internal to GDB has been detected" {
663		if { $print_fail } {
664		    fail "$test_name (GDB internal error)"
665		}
666		gdb_internal_error_resync
667		return 0
668	}
669	-re "$gdb_prompt $" {
670		if { $print_fail } {
671			fail $test_name
672		}
673		return 0
674	}
675	eof {
676		perror "GDB process no longer exists"
677		global gdb_spawn_id
678		set wait_status [wait -i $gdb_spawn_id]
679		verbose -log "GDB process exited with wait status $wait_status"
680		if { $print_fail } {
681			fail "$test_name (eof)"
682		}
683		return 0
684	}
685	timeout {
686		if { $print_fail } {
687			fail "$test_name (timeout)"
688		}
689		return 0
690	}
691    }
692    if { $print_pass } {
693	pass $test_name
694    }
695    return 1
696}
697
698# Set breakpoint at function and run gdb until it breaks there.
699# Since this is the only breakpoint that will be set, if it stops
700# at a breakpoint, we will assume it is the one we want.  We can't
701# just compare to "function" because it might be a fully qualified,
702# single quoted C++ function specifier.
703#
704# If there are additional arguments, pass them to gdb_breakpoint.
705# We recognize no-message/message ourselves.
706#
707# no-message is messed up here, like gdb_breakpoint: to preserve
708# historical usage fails are always printed by default.
709# no-message: turns off printing of fails (and passes, but they're already off)
710# message: turns on printing of passes (and fails, but they're already on)
711
712proc runto { linespec args } {
713    global gdb_prompt
714    global bkptno_numopt_re
715    global decimal
716
717    delete_breakpoints
718
719    set print_pass 0
720    set print_fail 1
721    set no_message_loc [lsearch -exact $args no-message]
722    set message_loc [lsearch -exact $args message]
723    # The last one to appear in args wins.
724    if { $no_message_loc > $message_loc } {
725	set print_fail 0
726    } elseif { $message_loc > $no_message_loc } {
727	set print_pass 1
728    }
729
730    set test_name "runto: run to $linespec"
731
732    # We need to use eval here to pass our varargs args to gdb_breakpoint
733    # which is also a varargs function.
734    # But we also have to be careful because $linespec may have multiple
735    # elements, and we don't want Tcl to move the remaining elements after
736    # the first to $args.  That is why $linespec is wrapped in {}.
737    if ![eval gdb_breakpoint {$linespec} $args] {
738	return 0
739    }
740
741    gdb_run_cmd
742
743    # the "at foo.c:36" output we get with -g.
744    # the "in func" output we get without -g.
745    gdb_expect 30 {
746	-re "Break.* at .*:$decimal.*$gdb_prompt $" {
747	    if { $print_pass } {
748		pass $test_name
749	    }
750	    return 1
751	}
752	-re "Breakpoint $bkptno_numopt_re, \[0-9xa-f\]* in .*$gdb_prompt $" {
753	    if { $print_pass } {
754		pass $test_name
755	    }
756	    return 1
757	}
758	-re "The target does not support running in non-stop mode.\r\n$gdb_prompt $" {
759	    if { $print_fail } {
760		unsupported "non-stop mode not supported"
761	    }
762	    return 0
763	}
764	-re ".*A problem internal to GDB has been detected" {
765	    # Always emit a FAIL if we encounter an internal error: internal
766	    # errors are never expected.
767	    fail "$test_name (GDB internal error)"
768	    gdb_internal_error_resync
769	    return 0
770	}
771	-re "$gdb_prompt $" {
772	    if { $print_fail } {
773		fail $test_name
774	    }
775	    return 0
776	}
777	eof {
778	    if { $print_fail } {
779		fail "$test_name (eof)"
780	    }
781	    return 0
782	}
783	timeout {
784	    if { $print_fail } {
785		fail "$test_name (timeout)"
786	    }
787	    return 0
788	}
789    }
790    if { $print_pass } {
791	pass $test_name
792    }
793    return 1
794}
795
796# Ask gdb to run until we hit a breakpoint at main.
797#
798# N.B. This function deletes all existing breakpoints.
799# If you don't want that, use gdb_start_cmd.
800
801proc runto_main { } {
802    return [runto main qualified]
803}
804
805### Continue, and expect to hit a breakpoint.
806### Report a pass or fail, depending on whether it seems to have
807### worked.  Use NAME as part of the test name; each call to
808### continue_to_breakpoint should use a NAME which is unique within
809### that test file.
810proc gdb_continue_to_breakpoint {name {location_pattern .*}} {
811    global gdb_prompt
812    set full_name "continue to breakpoint: $name"
813
814    set kfail_pattern "Process record does not support instruction 0xfae64 at.*"
815    gdb_test_multiple "continue" $full_name {
816	-re "(?:Breakpoint|Temporary breakpoint) .* (at|in) $location_pattern\r\n$gdb_prompt $" {
817	    pass $full_name
818	}
819	-re "\[\r\n\]*(?:$kfail_pattern)\[\r\n\]+$gdb_prompt $" {
820	    kfail "gdb/25038" $full_name
821	}
822    }
823}
824
825
826# gdb_internal_error_resync:
827#
828# Answer the questions GDB asks after it reports an internal error
829# until we get back to a GDB prompt.  Decline to quit the debugging
830# session, and decline to create a core file.  Return non-zero if the
831# resync succeeds.
832#
833# This procedure just answers whatever questions come up until it sees
834# a GDB prompt; it doesn't require you to have matched the input up to
835# any specific point.  However, it only answers questions it sees in
836# the output itself, so if you've matched a question, you had better
837# answer it yourself before calling this.
838#
839# You can use this function thus:
840#
841# gdb_expect {
842#     ...
843#     -re ".*A problem internal to GDB has been detected" {
844#         gdb_internal_error_resync
845#     }
846#     ...
847# }
848#
849proc gdb_internal_error_resync {} {
850    global gdb_prompt
851
852    verbose -log "Resyncing due to internal error."
853
854    set count 0
855    while {$count < 10} {
856	gdb_expect {
857	    -re "Recursive internal problem\\." {
858		perror "Could not resync from internal error (recursive internal problem)"
859		return 0
860	    }
861	    -re "Quit this debugging session\\? \\(y or n\\) $" {
862		send_gdb "n\n" answer
863		incr count
864	    }
865	    -re "Create a core file of GDB\\? \\(y or n\\) $" {
866		send_gdb "n\n" answer
867		incr count
868	    }
869	    -re "$gdb_prompt $" {
870		# We're resynchronized.
871		return 1
872	    }
873	    timeout {
874		perror "Could not resync from internal error (timeout)"
875		return 0
876	    }
877	    eof {
878		perror "Could not resync from internal error (eof)"
879		return 0
880	    }
881	}
882    }
883    perror "Could not resync from internal error (resync count exceeded)"
884    return 0
885}
886
887# Fill in the default prompt if PROMPT_REGEXP is empty.
888#
889# If WITH_ANCHOR is true and the default prompt is used, append a `$` at the end
890# of the regexp, to anchor the match at the end of the buffer.
891proc fill_in_default_prompt {prompt_regexp with_anchor} {
892    if { "$prompt_regexp" == "" } {
893	set prompt "$::gdb_prompt "
894
895	if { $with_anchor } {
896	    append prompt "$"
897	}
898
899	return $prompt
900    }
901    return $prompt_regexp
902}
903
904# gdb_test_multiple COMMAND MESSAGE [ -prompt PROMPT_REGEXP] [ -lbl ]
905#                   EXPECT_ARGUMENTS
906# Send a command to gdb; test the result.
907#
908# COMMAND is the command to execute, send to GDB with send_gdb.  If
909#   this is the null string no command is sent.
910# MESSAGE is a message to be printed with the built-in failure patterns
911#   if one of them matches.  If MESSAGE is empty COMMAND will be used.
912# -prompt PROMPT_REGEXP specifies a regexp matching the expected prompt
913#   after the command output.  If empty, defaults to "$gdb_prompt $".
914# -lbl specifies that line-by-line matching will be used.
915# EXPECT_ARGUMENTS will be fed to expect in addition to the standard
916#   patterns.  Pattern elements will be evaluated in the caller's
917#   context; action elements will be executed in the caller's context.
918#   Unlike patterns for gdb_test, these patterns should generally include
919#   the final newline and prompt.
920#
921# Returns:
922#    1 if the test failed, according to a built-in failure pattern
923#    0 if only user-supplied patterns matched
924#   -1 if there was an internal error.
925#
926# You can use this function thus:
927#
928# gdb_test_multiple "print foo" "test foo" {
929#    -re "expected output 1" {
930#        pass "test foo"
931#    }
932#    -re "expected output 2" {
933#        fail "test foo"
934#    }
935# }
936#
937# Within action elements you can also make use of the variable
938# gdb_test_name.  This variable is setup automatically by
939# gdb_test_multiple, and contains the value of MESSAGE.  You can then
940# write this, which is equivalent to the above:
941#
942# gdb_test_multiple "print foo" "test foo" {
943#    -re "expected output 1" {
944#        pass $gdb_test_name
945#    }
946#    -re "expected output 2" {
947#        fail $gdb_test_name
948#    }
949# }
950#
951# Like with "expect", you can also specify the spawn id to match with
952# -i "$id".  Interesting spawn ids are $inferior_spawn_id and
953# $gdb_spawn_id.  The former matches inferior I/O, while the latter
954# matches GDB I/O.  E.g.:
955#
956# send_inferior "hello\n"
957# gdb_test_multiple "continue" "test echo" {
958#    -i "$inferior_spawn_id" -re "^hello\r\nhello\r\n$" {
959#        pass "got echo"
960#    }
961#    -i "$gdb_spawn_id" -re "Breakpoint.*$gdb_prompt $" {
962#        fail "hit breakpoint"
963#    }
964# }
965#
966# The standard patterns, such as "Inferior exited..." and "A problem
967# ...", all being implicitly appended to that list.  These are always
968# expected from $gdb_spawn_id.  IOW, callers do not need to worry
969# about resetting "-i" back to $gdb_spawn_id explicitly.
970#
971# In EXPECT_ARGUMENTS we can use a -wrap pattern flag, that wraps the regexp
972# pattern as gdb_test wraps its message argument.
973# This allows us to rewrite:
974#   gdb_test <command> <pattern> <message>
975# into:
976#   gdb_test_multiple <command> <message> {
977#       -re -wrap <pattern> {
978#           pass $gdb_test_name
979#       }
980#   }
981#
982# In EXPECT_ARGUMENTS, a pattern flag -early can be used.  It makes sure the
983# pattern is inserted before any implicit pattern added by gdb_test_multiple.
984# Using this pattern flag, we can f.i. setup a kfail for an assertion failure
985# <assert> during gdb_continue_to_breakpoint by the rewrite:
986#   gdb_continue_to_breakpoint <msg> <pattern>
987# into:
988#   set breakpoint_pattern "(?:Breakpoint|Temporary breakpoint) .* (at|in)"
989#   gdb_test_multiple "continue" "continue to breakpoint: <msg>"  {
990#	-early -re "internal-error: <assert>" {
991#	    setup_kfail gdb/nnnnn "*-*-*"
992#	    exp_continue
993#	}
994#	-re "$breakpoint_pattern <pattern>\r\n$gdb_prompt $" {
995#	    pass $gdb_test_name
996#	}
997#    }
998#
999proc gdb_test_multiple { command message args } {
1000    global verbose use_gdb_stub
1001    global gdb_prompt pagination_prompt
1002    global GDB
1003    global gdb_spawn_id
1004    global inferior_exited_re
1005    upvar timeout timeout
1006    upvar expect_out expect_out
1007    global any_spawn_id
1008
1009    set line_by_line 0
1010    set prompt_regexp ""
1011    for {set i 0} {$i < [llength $args]} {incr i} {
1012	set arg [lindex $args $i]
1013	if { $arg  == "-prompt" } {
1014	    incr i
1015	    set prompt_regexp [lindex $args $i]
1016	} elseif { $arg == "-lbl" } {
1017	    set line_by_line 1
1018	} else {
1019	    set user_code $arg
1020	    break
1021	}
1022    }
1023    if { [expr $i + 1] < [llength $args] } {
1024	error "Too many arguments to gdb_test_multiple"
1025    } elseif { ![info exists user_code] } {
1026	error "Too few arguments to gdb_test_multiple"
1027    }
1028
1029    set prompt_regexp [fill_in_default_prompt $prompt_regexp true]
1030
1031    if { $message == "" } {
1032	set message $command
1033    }
1034
1035    if [string match "*\[\r\n\]" $command] {
1036	error "Invalid trailing newline in \"$command\" command"
1037    }
1038
1039    if [string match "*\[\003\004\]" $command] {
1040	error "Invalid trailing control code in \"$command\" command"
1041    }
1042
1043    if [string match "*\[\r\n\]*" $message] {
1044	error "Invalid newline in \"$message\" test"
1045    }
1046
1047    if {$use_gdb_stub
1048	&& [regexp -nocase {^\s*(r|run|star|start|at|att|atta|attac|attach)\M} \
1049	    $command]} {
1050	error "gdbserver does not support $command without extended-remote"
1051    }
1052
1053    # TCL/EXPECT WART ALERT
1054    # Expect does something very strange when it receives a single braced
1055    # argument.  It splits it along word separators and performs substitutions.
1056    # This means that { "[ab]" } is evaluated as "[ab]", but { "\[ab\]" } is
1057    # evaluated as "\[ab\]".  But that's not how TCL normally works; inside a
1058    # double-quoted list item, "\[ab\]" is just a long way of representing
1059    # "[ab]", because the backslashes will be removed by lindex.
1060
1061    # Unfortunately, there appears to be no easy way to duplicate the splitting
1062    # that expect will do from within TCL.  And many places make use of the
1063    # "\[0-9\]" construct, so we need to support that; and some places make use
1064    # of the "[func]" construct, so we need to support that too.  In order to
1065    # get this right we have to substitute quoted list elements differently
1066    # from braced list elements.
1067
1068    # We do this roughly the same way that Expect does it.  We have to use two
1069    # lists, because if we leave unquoted newlines in the argument to uplevel
1070    # they'll be treated as command separators, and if we escape newlines
1071    # we mangle newlines inside of command blocks.  This assumes that the
1072    # input doesn't contain a pattern which contains actual embedded newlines
1073    # at this point!
1074
1075    regsub -all {\n} ${user_code} { } subst_code
1076    set subst_code [uplevel list $subst_code]
1077
1078    set processed_code ""
1079    set early_processed_code ""
1080    # The variable current_list holds the name of the currently processed
1081    # list, either processed_code or early_processed_code.
1082    set current_list "processed_code"
1083    set patterns ""
1084    set expecting_action 0
1085    set expecting_arg 0
1086    set wrap_pattern 0
1087    foreach item $user_code subst_item $subst_code {
1088	if { $item == "-n" || $item == "-notransfer" || $item == "-nocase" } {
1089	    lappend $current_list $item
1090	    continue
1091	}
1092	if { $item == "-indices" || $item == "-re" || $item == "-ex" } {
1093	    lappend $current_list $item
1094	    continue
1095	}
1096	if { $item == "-early" } {
1097	    set current_list "early_processed_code"
1098	    continue
1099	}
1100	if { $item == "-timeout" || $item == "-i" } {
1101	    set expecting_arg 1
1102	    lappend $current_list $item
1103	    continue
1104	}
1105	if { $item == "-wrap" } {
1106	    set wrap_pattern 1
1107	    continue
1108	}
1109	if { $expecting_arg } {
1110	    set expecting_arg 0
1111	    lappend $current_list $subst_item
1112	    continue
1113	}
1114	if { $expecting_action } {
1115	    lappend $current_list "uplevel [list $item]"
1116	    set expecting_action 0
1117	    # Cosmetic, no effect on the list.
1118	    append $current_list "\n"
1119	    # End the effect of -early, it only applies to one action.
1120	    set current_list "processed_code"
1121	    continue
1122	}
1123	set expecting_action 1
1124	if { $wrap_pattern } {
1125	    # Wrap subst_item as is done for the gdb_test PATTERN argument.
1126	    lappend $current_list \
1127		"\[\r\n\]*(?:$subst_item)\[\r\n\]+$gdb_prompt $"
1128	    set wrap_pattern 0
1129	} else {
1130	    lappend $current_list $subst_item
1131	}
1132	if {$patterns != ""} {
1133	    append patterns "; "
1134	}
1135	append patterns "\"$subst_item\""
1136    }
1137
1138    # Also purely cosmetic.
1139    regsub -all {\r} $patterns {\\r} patterns
1140    regsub -all {\n} $patterns {\\n} patterns
1141
1142    if {$verbose > 2} {
1143	send_user "Sending \"$command\" to gdb\n"
1144	send_user "Looking to match \"$patterns\"\n"
1145	send_user "Message is \"$message\"\n"
1146    }
1147
1148    set result -1
1149    set string "${command}\n"
1150    if { $command != "" } {
1151	set multi_line_re "\[\r\n\] *>"
1152	while { "$string" != "" } {
1153	    set foo [string first "\n" "$string"]
1154	    set len [string length "$string"]
1155	    if { $foo < [expr $len - 1] } {
1156		set str [string range "$string" 0 $foo]
1157		if { [send_gdb "$str"] != "" } {
1158		    verbose -log "Couldn't send $command to GDB."
1159		    unresolved $message
1160		    return -1
1161		}
1162		# since we're checking if each line of the multi-line
1163		# command are 'accepted' by GDB here,
1164		# we need to set -notransfer expect option so that
1165		# command output is not lost for pattern matching
1166		# - guo
1167		gdb_expect 2 {
1168		    -notransfer -re "$multi_line_re$" { verbose "partial: match" 3 }
1169		    timeout { verbose "partial: timeout" 3 }
1170		}
1171		set string [string range "$string" [expr $foo + 1] end]
1172		set multi_line_re "$multi_line_re.*\[\r\n\] *>"
1173	    } else {
1174		break
1175	    }
1176	}
1177	if { "$string" != "" } {
1178	    if { [send_gdb "$string"] != "" } {
1179		verbose -log "Couldn't send $command to GDB."
1180		unresolved $message
1181		return -1
1182	    }
1183	}
1184    }
1185
1186    set code $early_processed_code
1187    append code {
1188	-re ".*A problem internal to GDB has been detected" {
1189	    fail "$message (GDB internal error)"
1190	    gdb_internal_error_resync
1191	    set result -1
1192	}
1193	-re "\\*\\*\\* DOSEXIT code.*" {
1194	    if { $message != "" } {
1195		fail "$message"
1196	    }
1197	    set result -1
1198	}
1199	-re "Corrupted shared library list.*$prompt_regexp" {
1200	    fail "$message (shared library list corrupted)"
1201	    set result -1
1202	}
1203	-re "Invalid cast\.\r\nwarning: Probes-based dynamic linker interface failed.*$prompt_regexp" {
1204	    fail "$message (probes interface failure)"
1205	    set result -1
1206	}
1207    }
1208    append code $processed_code
1209
1210    # Reset the spawn id, in case the processed code used -i.
1211    append code {
1212	-i "$gdb_spawn_id"
1213    }
1214
1215    append code {
1216	-re "Ending remote debugging.*$prompt_regexp" {
1217	    if {![isnative]} {
1218		warning "Can`t communicate to remote target."
1219	    }
1220	    gdb_exit
1221	    gdb_start
1222	    set result -1
1223	}
1224	-re "Undefined\[a-z\]* command:.*$prompt_regexp" {
1225	    perror "Undefined command \"$command\"."
1226	    fail "$message"
1227	    set result 1
1228	}
1229	-re "Ambiguous command.*$prompt_regexp" {
1230	    perror "\"$command\" is not a unique command name."
1231	    fail "$message"
1232	    set result 1
1233	}
1234	-re "$inferior_exited_re with code \[0-9\]+.*$prompt_regexp" {
1235	    if {![string match "" $message]} {
1236		set errmsg "$message (the program exited)"
1237	    } else {
1238		set errmsg "$command (the program exited)"
1239	    }
1240	    fail "$errmsg"
1241	    set result -1
1242	}
1243	-re "$inferior_exited_re normally.*$prompt_regexp" {
1244	    if {![string match "" $message]} {
1245		set errmsg "$message (the program exited)"
1246	    } else {
1247		set errmsg "$command (the program exited)"
1248	    }
1249	    fail "$errmsg"
1250	    set result -1
1251	}
1252	-re "The program is not being run.*$prompt_regexp" {
1253	    if {![string match "" $message]} {
1254		set errmsg "$message (the program is no longer running)"
1255	    } else {
1256		set errmsg "$command (the program is no longer running)"
1257	    }
1258	    fail "$errmsg"
1259	    set result -1
1260	}
1261	-re "\r\n$prompt_regexp" {
1262	    if {![string match "" $message]} {
1263		fail "$message"
1264	    }
1265	    set result 1
1266	}
1267	-re "$pagination_prompt" {
1268	    send_gdb "\n"
1269	    perror "Window too small."
1270	    fail "$message"
1271	    set result -1
1272	}
1273	-re "\\((y or n|y or \\\[n\\\]|\\\[y\\\] or n)\\) " {
1274	    send_gdb "n\n" answer
1275	    gdb_expect -re "$prompt_regexp"
1276	    fail "$message (got interactive prompt)"
1277	    set result -1
1278	}
1279	-re "\\\[0\\\] cancel\r\n\\\[1\\\] all.*\r\n> $" {
1280	    send_gdb "0\n"
1281	    gdb_expect -re "$prompt_regexp"
1282	    fail "$message (got breakpoint menu)"
1283	    set result -1
1284	}
1285
1286	-i $gdb_spawn_id
1287	eof {
1288	    perror "GDB process no longer exists"
1289	    set wait_status [wait -i $gdb_spawn_id]
1290	    verbose -log "GDB process exited with wait status $wait_status"
1291	    if { $message != "" } {
1292		fail "$message"
1293	    }
1294	    return -1
1295	}
1296    }
1297
1298    if {$line_by_line} {
1299       append code {
1300           -re "\r\n\[^\r\n\]*(?=\r\n)" {
1301               exp_continue
1302           }
1303       }
1304    }
1305
1306    # Now patterns that apply to any spawn id specified.
1307    append code {
1308	-i $any_spawn_id
1309	eof {
1310	    perror "Process no longer exists"
1311	    if { $message != "" } {
1312		fail "$message"
1313	    }
1314	    return -1
1315	}
1316	full_buffer {
1317	    perror "internal buffer is full."
1318	    fail "$message"
1319	    set result -1
1320	}
1321	timeout	{
1322	    if {![string match "" $message]} {
1323		fail "$message (timeout)"
1324	    }
1325	    set result 1
1326	}
1327    }
1328
1329    # remote_expect calls the eof section if there is an error on the
1330    # expect call.  We already have eof sections above, and we don't
1331    # want them to get called in that situation.  Since the last eof
1332    # section becomes the error section, here we define another eof
1333    # section, but with an empty spawn_id list, so that it won't ever
1334    # match.
1335    append code {
1336	-i "" eof {
1337	    # This comment is here because the eof section must not be
1338	    # the empty string, otherwise remote_expect won't realize
1339	    # it exists.
1340	}
1341    }
1342
1343    # Create gdb_test_name in the parent scope.  If this variable
1344    # already exists, which it might if we have nested calls to
1345    # gdb_test_multiple, then preserve the old value, otherwise,
1346    # create a new variable in the parent scope.
1347    upvar gdb_test_name gdb_test_name
1348    if { [info exists gdb_test_name] } {
1349	set gdb_test_name_old "$gdb_test_name"
1350    }
1351    set gdb_test_name "$message"
1352
1353    set result 0
1354    set code [catch {gdb_expect $code} string]
1355
1356    # Clean up the gdb_test_name variable.  If we had a
1357    # previous value then restore it, otherwise, delete the variable
1358    # from the parent scope.
1359    if { [info exists gdb_test_name_old] } {
1360	set gdb_test_name "$gdb_test_name_old"
1361    } else {
1362	unset gdb_test_name
1363    }
1364
1365    if {$code == 1} {
1366	global errorInfo errorCode
1367	return -code error -errorinfo $errorInfo -errorcode $errorCode $string
1368    } elseif {$code > 1} {
1369	return -code $code $string
1370    }
1371    return $result
1372}
1373
1374# Usage: gdb_test_multiline NAME INPUT RESULT {INPUT RESULT} ...
1375# Run a test named NAME, consisting of multiple lines of input.
1376# After each input line INPUT, search for result line RESULT.
1377# Succeed if all results are seen; fail otherwise.
1378
1379proc gdb_test_multiline { name args } {
1380    global gdb_prompt
1381    set inputnr 0
1382    foreach {input result} $args {
1383	incr inputnr
1384	if {[gdb_test_multiple $input "$name: input $inputnr: $input" {
1385	    -re "\[\r\n\]*($result)\[\r\n\]+($gdb_prompt | *>)$" {
1386		pass $gdb_test_name
1387	    }
1388	}]} {
1389	    return 1
1390	}
1391    }
1392    return 0
1393}
1394
1395
1396# gdb_test [-prompt PROMPT_REGEXP] [-lbl]
1397#          COMMAND [PATTERN] [MESSAGE] [QUESTION RESPONSE]
1398# Send a command to gdb; test the result.
1399#
1400# COMMAND is the command to execute, send to GDB with send_gdb.  If
1401#   this is the null string no command is sent.
1402# PATTERN is the pattern to match for a PASS, and must NOT include
1403#   the \r\n sequence immediately before the gdb prompt.  This argument
1404#   may be omitted to just match the prompt, ignoring whatever output
1405#   precedes it.
1406# MESSAGE is an optional message to be printed.  If this is
1407#   omitted, then the pass/fail messages use the command string as the
1408#   message.  (If this is the empty string, then sometimes we don't
1409#   call pass or fail at all; I don't understand this at all.)
1410# QUESTION is a question GDB should ask in response to COMMAND, like
1411#   "are you sure?"  If this is specified, the test fails if GDB
1412#   doesn't print the question.
1413# RESPONSE is the response to send when QUESTION appears.
1414#
1415# -prompt PROMPT_REGEXP specifies a regexp matching the expected prompt
1416#   after the command output.  If empty, defaults to "$gdb_prompt $".
1417# -no-prompt-anchor specifies that if the default prompt regexp is used, it
1418#   should not be anchored at the end of the buffer.  This means that the
1419#   pattern can match even if there is stuff output after the prompt.  Does not
1420#   have any effect if -prompt is specified.
1421# -lbl specifies that line-by-line matching will be used.
1422# -nopass specifies that a PASS should not be issued.
1423#
1424# Returns:
1425#    1 if the test failed,
1426#    0 if the test passes,
1427#   -1 if there was an internal error.
1428#
1429proc gdb_test { args } {
1430    global gdb_prompt
1431    upvar timeout timeout
1432
1433    parse_args {
1434	{prompt ""}
1435	{no-prompt-anchor}
1436	{lbl}
1437	{nopass}
1438    }
1439
1440    lassign $args command pattern message question response
1441
1442    # Can't have a question without a response.
1443    if { $question != "" && $response == "" || [llength $args] > 5 } {
1444	error "Unexpected arguments: $args"
1445    }
1446
1447    if { $message == "" } {
1448	set message $command
1449    }
1450
1451    set prompt [fill_in_default_prompt $prompt [expr !${no-prompt-anchor}]]
1452
1453    set saw_question 0
1454
1455    set user_code {}
1456    lappend user_code {
1457	-re "\[\r\n\]*(?:$pattern)\[\r\n\]+$prompt" {
1458	    if { $question != "" & !$saw_question} {
1459		fail $message
1460	    } elseif {!$nopass} {
1461		pass $message
1462	    }
1463	}
1464    }
1465
1466    if { $question != "" } {
1467	lappend user_code {
1468	    -re "$question$" {
1469		set saw_question 1
1470		send_gdb "$response\n"
1471		exp_continue
1472	    }
1473	}
1474    }
1475
1476    set user_code [join $user_code]
1477
1478    set opts {}
1479    lappend opts "-prompt" "$prompt"
1480    if {$lbl} {
1481	lappend opts "-lbl"
1482    }
1483
1484    return [gdb_test_multiple $command $message {*}$opts $user_code]
1485}
1486
1487# Return 1 if version MAJOR.MINOR is at least AT_LEAST_MAJOR.AT_LEAST_MINOR.
1488proc version_at_least { major minor at_least_major at_least_minor} {
1489    if { $major > $at_least_major } {
1490        return 1
1491    } elseif { $major == $at_least_major \
1492		   && $minor >= $at_least_minor } {
1493        return 1
1494    } else {
1495        return 0
1496    }
1497}
1498
1499# Return 1 if tcl version used is at least MAJOR.MINOR
1500proc tcl_version_at_least { major minor } {
1501    global tcl_version
1502    regexp {^([0-9]+)\.([0-9]+)$} $tcl_version \
1503	dummy tcl_version_major tcl_version_minor
1504    return [version_at_least $tcl_version_major $tcl_version_minor \
1505		$major $minor]
1506}
1507
1508if { [tcl_version_at_least 8 5] == 0 } {
1509    # lrepeat was added in tcl 8.5.  Only add if missing.
1510    proc lrepeat { n element } {
1511        if { [string is integer -strict $n] == 0 } {
1512            error "expected integer but got \"$n\""
1513        }
1514        if { $n < 0 } {
1515            error "bad count \"$n\": must be integer >= 0"
1516        }
1517        set res [list]
1518        for {set i 0} {$i < $n} {incr i} {
1519            lappend res $element
1520        }
1521        return $res
1522    }
1523}
1524
1525# gdb_test_no_output [-prompt PROMPT_REGEXP] [-nopass] COMMAND [MESSAGE]
1526# Send a command to GDB and verify that this command generated no output.
1527#
1528# See gdb_test for a description of the -prompt, -no-prompt-anchor, -nopass,
1529# COMMAND, and MESSAGE parameters.
1530
1531proc gdb_test_no_output { args } {
1532    global gdb_prompt
1533
1534    parse_args {
1535	{prompt ""}
1536	{no-prompt-anchor}
1537	{nopass}
1538    }
1539
1540    lassign $args command message
1541
1542    set prompt [fill_in_default_prompt $prompt [expr !${no-prompt-anchor}]]
1543
1544    set command_regex [string_to_regexp $command]
1545    gdb_test_multiple $command $message -prompt $prompt {
1546	-re "^$command_regex\r\n$prompt" {
1547	    if {!$nopass} {
1548		pass $gdb_test_name
1549	    }
1550	}
1551    }
1552}
1553
1554# Send a command and then wait for a sequence of outputs.
1555# This is useful when the sequence is long and contains ".*", a single
1556# regexp to match the entire output can get a timeout much easier.
1557#
1558# COMMAND is the command to execute, send to GDB with send_gdb.  If
1559#   this is the null string no command is sent.
1560# TEST_NAME is passed to pass/fail.  COMMAND is used if TEST_NAME is "".
1561# EXPECTED_OUTPUT_LIST is a list of regexps of expected output, which are
1562# processed in order, and all must be present in the output.
1563#
1564# The -prompt switch can be used to override the prompt expected at the end of
1565# the output sequence.
1566#
1567# It is unnecessary to specify ".*" at the beginning or end of any regexp,
1568# there is an implicit ".*" between each element of EXPECTED_OUTPUT_LIST.
1569# There is also an implicit ".*" between the last regexp and the gdb prompt.
1570#
1571# Like gdb_test and gdb_test_multiple, the output is expected to end with the
1572# gdb prompt, which must not be specified in EXPECTED_OUTPUT_LIST.
1573#
1574# Returns:
1575#    1 if the test failed,
1576#    0 if the test passes,
1577#   -1 if there was an internal error.
1578
1579proc gdb_test_sequence { args } {
1580    global gdb_prompt
1581
1582    parse_args {{prompt ""}}
1583
1584    if { $prompt == "" } {
1585	set prompt "$gdb_prompt $"
1586    }
1587
1588    if { [llength $args] != 3 } {
1589	error "Unexpected # of arguments, expecting: COMMAND TEST_NAME EXPECTED_OUTPUT_LIST"
1590    }
1591
1592    lassign $args command test_name expected_output_list
1593
1594    if { $test_name == "" } {
1595	set test_name $command
1596    }
1597
1598    lappend expected_output_list ""; # implicit ".*" before gdb prompt
1599
1600    if { $command != "" } {
1601	send_gdb "$command\n"
1602    }
1603
1604    return [gdb_expect_list $test_name $prompt $expected_output_list]
1605}
1606
1607
1608# Match output of COMMAND using RE.  Read output line-by-line.
1609# Report pass/fail with MESSAGE.
1610# For a command foo with output:
1611#   (gdb) foo^M
1612#   <line1>^M
1613#   <line2>^M
1614#   (gdb)
1615# the portion matched using RE is:
1616#  '<line1>^M
1617#   <line2>^M
1618#  '
1619#
1620# Optionally, additional -re-not <regexp> arguments can be specified, to
1621# ensure that a regexp is not match by the COMMAND output.
1622# Such an additional argument generates an additional PASS/FAIL of the form:
1623#   PASS: test-case.exp: $message: pattern not matched: <regexp>
1624
1625proc gdb_test_lines { command message re args } {
1626    set re_not [list]
1627
1628    for {set i 0} {$i < [llength $args]} {incr i} {
1629	set arg [lindex $args $i]
1630	if { $arg == "-re-not" } {
1631	    incr i
1632	    if { [llength $args] == $i } {
1633		error "Missing argument for -re-not"
1634		break
1635	    }
1636	    set arg [lindex $args $i]
1637	    lappend re_not $arg
1638	} else {
1639	    error "Unhandled argument: $arg"
1640	}
1641    }
1642
1643    if { $message == ""} {
1644	set message $command
1645    }
1646
1647    set lines ""
1648    gdb_test_multiple $command $message {
1649	-re "\r\n(\[^\r\n\]*)(?=\r\n)" {
1650	    set line $expect_out(1,string)
1651	    if { $lines eq "" } {
1652		append lines "$line"
1653	    } else {
1654		append lines "\r\n$line"
1655	    }
1656	    exp_continue
1657	}
1658	-re -wrap "" {
1659	    append lines "\r\n"
1660	}
1661    }
1662
1663    gdb_assert { [regexp $re $lines] } $message
1664
1665    foreach re $re_not {
1666	gdb_assert { ![regexp $re $lines] } "$message: pattern not matched: $re"
1667    }
1668}
1669
1670# Test that a command gives an error.  For pass or fail, return
1671# a 1 to indicate that more tests can proceed.  However a timeout
1672# is a serious error, generates a special fail message, and causes
1673# a 0 to be returned to indicate that more tests are likely to fail
1674# as well.
1675
1676proc test_print_reject { args } {
1677    global gdb_prompt
1678    global verbose
1679
1680    if {[llength $args] == 2} {
1681	set expectthis [lindex $args 1]
1682    } else {
1683	set expectthis "should never match this bogus string"
1684    }
1685    set sendthis [lindex $args 0]
1686    if {$verbose > 2} {
1687	send_user "Sending \"$sendthis\" to gdb\n"
1688	send_user "Looking to match \"$expectthis\"\n"
1689    }
1690    send_gdb "$sendthis\n"
1691    #FIXME: Should add timeout as parameter.
1692    gdb_expect {
1693	-re "A .* in expression.*\\.*$gdb_prompt $" {
1694	    pass "reject $sendthis"
1695	    return 1
1696	}
1697	-re "Invalid syntax in expression.*$gdb_prompt $" {
1698	    pass "reject $sendthis"
1699	    return 1
1700	}
1701	-re "Junk after end of expression.*$gdb_prompt $" {
1702	    pass "reject $sendthis"
1703	    return 1
1704	}
1705	-re "Invalid number.*$gdb_prompt $" {
1706	    pass "reject $sendthis"
1707	    return 1
1708	}
1709	-re "Invalid character constant.*$gdb_prompt $" {
1710	    pass "reject $sendthis"
1711	    return 1
1712	}
1713	-re "No symbol table is loaded.*$gdb_prompt $" {
1714	    pass "reject $sendthis"
1715	    return 1
1716	}
1717	-re "No symbol .* in current context.*$gdb_prompt $" {
1718	    pass "reject $sendthis"
1719	    return 1
1720	}
1721        -re "Unmatched single quote.*$gdb_prompt $" {
1722            pass "reject $sendthis"
1723            return 1
1724        }
1725        -re "A character constant must contain at least one character.*$gdb_prompt $" {
1726            pass "reject $sendthis"
1727            return 1
1728        }
1729	-re "$expectthis.*$gdb_prompt $" {
1730	    pass "reject $sendthis"
1731	    return 1
1732	}
1733	-re ".*$gdb_prompt $" {
1734	    fail "reject $sendthis"
1735	    return 1
1736	}
1737	default {
1738	    fail "reject $sendthis (eof or timeout)"
1739	    return 0
1740	}
1741    }
1742}
1743
1744
1745# Same as gdb_test, but the second parameter is not a regexp,
1746# but a string that must match exactly.
1747
1748proc gdb_test_exact { args } {
1749    upvar timeout timeout
1750
1751    set command [lindex $args 0]
1752
1753    # This applies a special meaning to a null string pattern.  Without
1754    # this, "$pattern\r\n$gdb_prompt $" will match anything, including error
1755    # messages from commands that should have no output except a new
1756    # prompt.  With this, only results of a null string will match a null
1757    # string pattern.
1758
1759    set pattern [lindex $args 1]
1760    if [string match $pattern ""] {
1761	set pattern [string_to_regexp [lindex $args 0]]
1762    } else {
1763	set pattern [string_to_regexp [lindex $args 1]]
1764    }
1765
1766    # It is most natural to write the pattern argument with only
1767    # embedded \n's, especially if you are trying to avoid Tcl quoting
1768    # problems.  But gdb_expect really wants to see \r\n in patterns.  So
1769    # transform the pattern here.  First transform \r\n back to \n, in
1770    # case some users of gdb_test_exact already do the right thing.
1771    regsub -all "\r\n" $pattern "\n" pattern
1772    regsub -all "\n" $pattern "\r\n" pattern
1773    if {[llength $args] == 3} {
1774	set message [lindex $args 2]
1775	return [gdb_test $command $pattern $message]
1776    }
1777
1778    return [gdb_test $command $pattern]
1779}
1780
1781# Wrapper around gdb_test_multiple that looks for a list of expected
1782# output elements, but which can appear in any order.
1783# CMD is the gdb command.
1784# NAME is the name of the test.
1785# ELM_FIND_REGEXP specifies how to partition the output into elements to
1786# compare.
1787# ELM_EXTRACT_REGEXP specifies the part of ELM_FIND_REGEXP to compare.
1788# RESULT_MATCH_LIST is a list of exact matches for each expected element.
1789# All elements of RESULT_MATCH_LIST must appear for the test to pass.
1790#
1791# A typical use of ELM_FIND_REGEXP/ELM_EXTRACT_REGEXP is to extract one line
1792# of text per element and then strip trailing \r\n's.
1793# Example:
1794# gdb_test_list_exact "foo" "bar" \
1795#    "\[^\r\n\]+\[\r\n\]+" \
1796#    "\[^\r\n\]+" \
1797#     { \
1798#	{expected result 1} \
1799#	{expected result 2} \
1800#     }
1801
1802proc gdb_test_list_exact { cmd name elm_find_regexp elm_extract_regexp result_match_list } {
1803    global gdb_prompt
1804
1805    set matches [lsort $result_match_list]
1806    set seen {}
1807    gdb_test_multiple $cmd $name {
1808	"$cmd\[\r\n\]" { exp_continue }
1809	-re $elm_find_regexp {
1810	    set str $expect_out(0,string)
1811	    verbose -log "seen: $str" 3
1812	    regexp -- $elm_extract_regexp $str elm_seen
1813	    verbose -log "extracted: $elm_seen" 3
1814	    lappend seen $elm_seen
1815	    exp_continue
1816	}
1817	-re "$gdb_prompt $" {
1818	    set failed ""
1819	    foreach got [lsort $seen] have $matches {
1820		if {![string equal $got $have]} {
1821		    set failed $have
1822		    break
1823		}
1824	    }
1825	    if {[string length $failed] != 0} {
1826		fail "$name ($failed not found)"
1827	    } else {
1828		pass $name
1829	    }
1830	}
1831    }
1832}
1833
1834# gdb_test_stdio COMMAND INFERIOR_PATTERN GDB_PATTERN MESSAGE
1835# Send a command to gdb; expect inferior and gdb output.
1836#
1837# See gdb_test_multiple for a description of the COMMAND and MESSAGE
1838# parameters.
1839#
1840# INFERIOR_PATTERN is the pattern to match against inferior output.
1841#
1842# GDB_PATTERN is the pattern to match against gdb output, and must NOT
1843# include the \r\n sequence immediately before the gdb prompt, nor the
1844# prompt.  The default is empty.
1845#
1846# Both inferior and gdb patterns must match for a PASS.
1847#
1848# If MESSAGE is ommitted, then COMMAND will be used as the message.
1849#
1850# Returns:
1851#    1 if the test failed,
1852#    0 if the test passes,
1853#   -1 if there was an internal error.
1854#
1855
1856proc gdb_test_stdio {command inferior_pattern {gdb_pattern ""} {message ""}} {
1857    global inferior_spawn_id gdb_spawn_id
1858    global gdb_prompt
1859
1860    if {$message == ""} {
1861	set message $command
1862    }
1863
1864    set inferior_matched 0
1865    set gdb_matched 0
1866
1867    # Use an indirect spawn id list, and remove the inferior spawn id
1868    # from the expected output as soon as it matches, in case
1869    # $inferior_pattern happens to be a prefix of the resulting full
1870    # gdb pattern below (e.g., "\r\n").
1871    global gdb_test_stdio_spawn_id_list
1872    set gdb_test_stdio_spawn_id_list "$inferior_spawn_id"
1873
1874    # Note that if $inferior_spawn_id and $gdb_spawn_id are different,
1875    # then we may see gdb's output arriving before the inferior's
1876    # output.
1877    set res [gdb_test_multiple $command $message {
1878	-i gdb_test_stdio_spawn_id_list -re "$inferior_pattern" {
1879	    set inferior_matched 1
1880	    if {!$gdb_matched} {
1881		set gdb_test_stdio_spawn_id_list ""
1882		exp_continue
1883	    }
1884	}
1885	-i $gdb_spawn_id -re "$gdb_pattern\r\n$gdb_prompt $" {
1886	    set gdb_matched 1
1887	    if {!$inferior_matched} {
1888		exp_continue
1889	    }
1890	}
1891    }]
1892    if {$res == 0} {
1893	pass $message
1894    } else {
1895	verbose -log "inferior_matched=$inferior_matched, gdb_matched=$gdb_matched"
1896    }
1897    return $res
1898}
1899
1900# Wrapper around gdb_test_multiple to be used when testing expression
1901# evaluation while 'set debug expression 1' is in effect.
1902# Looks for some patterns that indicates the expression was rejected.
1903#
1904# CMD is the command to execute, which should include an expression
1905# that GDB will need to parse.
1906#
1907# OUTPUT is the expected output pattern.
1908#
1909# TESTNAME is the name to be used for the test, defaults to CMD if not
1910# given.
1911proc gdb_test_debug_expr { cmd output {testname "" }} {
1912    global gdb_prompt
1913
1914    if { ${testname} == "" } {
1915	set testname $cmd
1916    }
1917
1918    gdb_test_multiple $cmd $testname {
1919	-re ".*Invalid expression.*\r\n$gdb_prompt $" {
1920	    fail $gdb_test_name
1921	}
1922	-re ".*\[\r\n\]$output\r\n$gdb_prompt $" {
1923	    pass $gdb_test_name
1924	}
1925    }
1926}
1927
1928# get_print_expr_at_depths EXP OUTPUTS
1929#
1930# Used for testing 'set print max-depth'.  Prints the expression EXP
1931# with 'set print max-depth' set to various depths.  OUTPUTS is a list
1932# of `n` different patterns to match at each of the depths from 0 to
1933# (`n` - 1).
1934#
1935# This proc does one final check with the max-depth set to 'unlimited'
1936# which is tested against the last pattern in the OUTPUTS list.  The
1937# OUTPUTS list is therefore required to match every depth from 0 to a
1938# depth where the whole of EXP is printed with no ellipsis.
1939#
1940# This proc leaves the 'set print max-depth' set to 'unlimited'.
1941proc gdb_print_expr_at_depths {exp outputs} {
1942    for { set depth 0 } { $depth <= [llength $outputs] } { incr depth } {
1943	if { $depth == [llength $outputs] } {
1944	    set expected_result [lindex $outputs [expr [llength $outputs] - 1]]
1945	    set depth_string "unlimited"
1946	} else {
1947	    set expected_result [lindex $outputs $depth]
1948	    set depth_string $depth
1949	}
1950
1951	with_test_prefix "exp='$exp': depth=${depth_string}" {
1952	    gdb_test_no_output "set print max-depth ${depth_string}"
1953	    gdb_test "p $exp" "$expected_result"
1954	}
1955    }
1956}
1957
1958
1959
1960# Issue a PASS and return true if evaluating CONDITION in the caller's
1961# frame returns true, and issue a FAIL and return false otherwise.
1962# MESSAGE is the pass/fail message to be printed.  If MESSAGE is
1963# omitted or is empty, then the pass/fail messages use the condition
1964# string as the message.
1965
1966proc gdb_assert { condition {message ""} } {
1967    if { $message == ""} {
1968	set message $condition
1969    }
1970
1971    set code [catch {uplevel 1 expr $condition} res]
1972    if {$code == 1} {
1973	# If code is 1 (TCL_ERROR), it means evaluation failed and res contains
1974	# an error message.  Print the error message, and set res to 0 since we
1975	# want to return a boolean.
1976	warning "While evaluating expression in gdb_assert: $res"
1977	unresolved $message
1978	set res 0
1979    } elseif { !$res } {
1980	fail $message
1981    } else {
1982	pass $message
1983    }
1984    return $res
1985}
1986
1987proc gdb_reinitialize_dir { subdir } {
1988    global gdb_prompt
1989
1990    if [is_remote host] {
1991	return ""
1992    }
1993    send_gdb "dir\n"
1994    gdb_expect 60 {
1995	-re "Reinitialize source path to empty.*y or n. " {
1996	    send_gdb "y\n" answer
1997	    gdb_expect 60 {
1998		-re "Source directories searched.*$gdb_prompt $" {
1999		    send_gdb "dir $subdir\n"
2000		    gdb_expect 60 {
2001			-re "Source directories searched.*$gdb_prompt $" {
2002			    verbose "Dir set to $subdir"
2003			}
2004			-re "$gdb_prompt $" {
2005			    perror "Dir \"$subdir\" failed."
2006			}
2007		    }
2008		}
2009		-re "$gdb_prompt $" {
2010		    perror "Dir \"$subdir\" failed."
2011		}
2012	    }
2013	}
2014	-re "$gdb_prompt $" {
2015	    perror "Dir \"$subdir\" failed."
2016	}
2017    }
2018}
2019
2020#
2021# gdb_exit -- exit the GDB, killing the target program if necessary
2022#
2023proc default_gdb_exit {} {
2024    global GDB
2025    global INTERNAL_GDBFLAGS GDBFLAGS
2026    global gdb_spawn_id inferior_spawn_id
2027    global inotify_log_file
2028
2029    if ![info exists gdb_spawn_id] {
2030	return
2031    }
2032
2033    verbose "Quitting $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
2034
2035    if {[info exists inotify_log_file] && [file exists $inotify_log_file]} {
2036	set fd [open $inotify_log_file]
2037	set data [read -nonewline $fd]
2038	close $fd
2039
2040	if {[string compare $data ""] != 0} {
2041	    warning "parallel-unsafe file creations noticed"
2042
2043	    # Clear the log.
2044	    set fd [open $inotify_log_file w]
2045	    close $fd
2046	}
2047    }
2048
2049    if { [is_remote host] && [board_info host exists fileid] } {
2050	send_gdb "quit\n"
2051	gdb_expect 10 {
2052	    -re "y or n" {
2053		send_gdb "y\n" answer
2054		exp_continue
2055	    }
2056	    -re "DOSEXIT code" { }
2057	    default { }
2058	}
2059    }
2060
2061    if ![is_remote host] {
2062	remote_close host
2063    }
2064    unset gdb_spawn_id
2065    unset ::gdb_tty_name
2066    unset inferior_spawn_id
2067}
2068
2069# Load a file into the debugger.
2070# The return value is 0 for success, -1 for failure.
2071#
2072# This procedure also set the global variable GDB_FILE_CMD_DEBUG_INFO
2073# to one of these values:
2074#
2075#   debug    file was loaded successfully and has debug information
2076#   nodebug  file was loaded successfully and has no debug information
2077#   lzma     file was loaded, .gnu_debugdata found, but no LZMA support
2078#            compiled in
2079#   fail     file was not loaded
2080#
2081# This procedure also set the global variable GDB_FILE_CMD_MSG to the
2082# output of the file command in case of success.
2083#
2084# I tried returning this information as part of the return value,
2085# but ran into a mess because of the many re-implementations of
2086# gdb_load in config/*.exp.
2087#
2088# TODO: gdb.base/sepdebug.exp and gdb.stabs/weird.exp might be able to use
2089# this if they can get more information set.
2090
2091proc gdb_file_cmd { arg } {
2092    global gdb_prompt
2093    global GDB
2094    global last_loaded_file
2095
2096    # GCC for Windows target may create foo.exe given "-o foo".
2097    if { ![file exists $arg] && [file exists "$arg.exe"] } {
2098	set arg "$arg.exe"
2099    }
2100
2101    # Save this for the benefit of gdbserver-support.exp.
2102    set last_loaded_file $arg
2103
2104    # Set whether debug info was found.
2105    # Default to "fail".
2106    global gdb_file_cmd_debug_info gdb_file_cmd_msg
2107    set gdb_file_cmd_debug_info "fail"
2108
2109    if [is_remote host] {
2110	set arg [remote_download host $arg]
2111	if { $arg == "" } {
2112	    perror "download failed"
2113	    return -1
2114	}
2115    }
2116
2117    # The file command used to kill the remote target.  For the benefit
2118    # of the testsuite, preserve this behavior.  Mark as optional so it doesn't
2119    # get written to the stdin log.
2120    send_gdb "kill\n" optional
2121    gdb_expect 120 {
2122	-re "Kill the program being debugged. .y or n. $" {
2123	    send_gdb "y\n" answer
2124	    verbose "\t\tKilling previous program being debugged"
2125	    exp_continue
2126	}
2127	-re "$gdb_prompt $" {
2128	    # OK.
2129	}
2130    }
2131
2132    send_gdb "file $arg\n"
2133    set new_symbol_table 0
2134    set basename [file tail $arg]
2135    gdb_expect 120 {
2136	-re "(Reading symbols from.*LZMA support was disabled.*$gdb_prompt $)" {
2137	    verbose "\t\tLoaded $arg into $GDB; .gnu_debugdata found but no LZMA available"
2138	    set gdb_file_cmd_msg $expect_out(1,string)
2139	    set gdb_file_cmd_debug_info "lzma"
2140	    return 0
2141	}
2142	-re "(Reading symbols from.*No debugging symbols found.*$gdb_prompt $)" {
2143	    verbose "\t\tLoaded $arg into $GDB with no debugging symbols"
2144	    set gdb_file_cmd_msg $expect_out(1,string)
2145	    set gdb_file_cmd_debug_info "nodebug"
2146	    return 0
2147	}
2148        -re "(Reading symbols from.*$gdb_prompt $)" {
2149            verbose "\t\tLoaded $arg into $GDB"
2150	    set gdb_file_cmd_msg $expect_out(1,string)
2151	    set gdb_file_cmd_debug_info "debug"
2152	    return 0
2153        }
2154        -re "Load new symbol table from \".*\".*y or n. $" {
2155	    if { $new_symbol_table > 0 } {
2156		perror [join [list "Couldn't load $basename,"
2157			      "interactive prompt loop detected."]]
2158		return -1
2159	    }
2160            send_gdb "y\n" answer
2161	    incr new_symbol_table
2162	    set suffix "-- with new symbol table"
2163	    set arg "$arg $suffix"
2164	    set basename "$basename $suffix"
2165	    exp_continue
2166	}
2167        -re "No such file or directory.*$gdb_prompt $" {
2168            perror "($basename) No such file or directory"
2169	    return -1
2170        }
2171	-re "A problem internal to GDB has been detected" {
2172	    perror "Couldn't load $basename into GDB (GDB internal error)."
2173	    gdb_internal_error_resync
2174	    return -1
2175	}
2176        -re "$gdb_prompt $" {
2177            perror "Couldn't load $basename into GDB."
2178	    return -1
2179            }
2180        timeout {
2181            perror "Couldn't load $basename into GDB (timeout)."
2182	    return -1
2183        }
2184        eof {
2185            # This is an attempt to detect a core dump, but seems not to
2186            # work.  Perhaps we need to match .* followed by eof, in which
2187            # gdb_expect does not seem to have a way to do that.
2188            perror "Couldn't load $basename into GDB (eof)."
2189	    return -1
2190        }
2191    }
2192}
2193
2194# The expect "spawn" function puts the tty name into the spawn_out
2195# array; but dejagnu doesn't export this globally.  So, we have to
2196# wrap spawn with our own function and poke in the built-in spawn
2197# so that we can capture this value.
2198#
2199# If available, the TTY name is saved to the LAST_SPAWN_TTY_NAME global.
2200# Otherwise, LAST_SPAWN_TTY_NAME is unset.
2201
2202proc spawn_capture_tty_name { args } {
2203    set result [uplevel builtin_spawn $args]
2204    upvar spawn_out spawn_out
2205    if { [info exists spawn_out(slave,name)] } {
2206	set ::last_spawn_tty_name $spawn_out(slave,name)
2207    } else {
2208	# If a process is spawned as part of a pipe line (e.g. passing
2209	# -leaveopen to the spawn proc) then the spawned process is no
2210	# assigned a tty and spawn_out(slave,name) will not be set.
2211	# In that case we want to ensure that last_spawn_tty_name is
2212	# not set.
2213	#
2214	# If the previous process spawned was also not assigned a tty
2215	# (e.g. multiple processed chained in a pipeline) then
2216	# last_spawn_tty_name will already be unset, so, if we don't
2217	# use -nocomplain here we would otherwise get an error.
2218	unset -nocomplain ::last_spawn_tty_name
2219    }
2220    return $result
2221}
2222
2223rename spawn builtin_spawn
2224rename spawn_capture_tty_name spawn
2225
2226# Default gdb_spawn procedure.
2227
2228proc default_gdb_spawn { } {
2229    global use_gdb_stub
2230    global GDB
2231    global INTERNAL_GDBFLAGS GDBFLAGS
2232    global gdb_spawn_id
2233
2234    # Set the default value, it may be overriden later by specific testfile.
2235    #
2236    # Use `set_board_info use_gdb_stub' for the board file to flag the inferior
2237    # is already started after connecting and run/attach are not supported.
2238    # This is used for the "remote" protocol.  After GDB starts you should
2239    # check global $use_gdb_stub instead of the board as the testfile may force
2240    # a specific different target protocol itself.
2241    set use_gdb_stub [target_info exists use_gdb_stub]
2242
2243    verbose "Spawning $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
2244    gdb_write_cmd_file "$GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
2245
2246    if [info exists gdb_spawn_id] {
2247	return 0
2248    }
2249
2250    if ![is_remote host] {
2251	if {[which $GDB] == 0} {
2252	    perror "$GDB does not exist."
2253	    exit 1
2254	}
2255    }
2256
2257    # Put GDBFLAGS last so that tests can put "--args ..." in it.
2258    set res [remote_spawn host "$GDB $INTERNAL_GDBFLAGS [host_info gdb_opts] $GDBFLAGS"]
2259    if { $res < 0 || $res == "" } {
2260	perror "Spawning $GDB failed."
2261	return 1
2262    }
2263
2264    set gdb_spawn_id $res
2265    set ::gdb_tty_name $::last_spawn_tty_name
2266    return 0
2267}
2268
2269# Default gdb_start procedure.
2270
2271proc default_gdb_start { } {
2272    global gdb_prompt
2273    global gdb_spawn_id
2274    global inferior_spawn_id
2275
2276    if [info exists gdb_spawn_id] {
2277	return 0
2278    }
2279
2280    # Keep track of the number of times GDB has been launched.
2281    global gdb_instances
2282    incr gdb_instances
2283
2284    gdb_stdin_log_init
2285
2286    set res [gdb_spawn]
2287    if { $res != 0} {
2288	return $res
2289    }
2290
2291    # Default to assuming inferior I/O is done on GDB's terminal.
2292    if {![info exists inferior_spawn_id]} {
2293	set inferior_spawn_id $gdb_spawn_id
2294    }
2295
2296    # When running over NFS, particularly if running many simultaneous
2297    # tests on different hosts all using the same server, things can
2298    # get really slow.  Give gdb at least 3 minutes to start up.
2299    gdb_expect 360 {
2300	-re "\[\r\n\]$gdb_prompt $" {
2301	    verbose "GDB initialized."
2302	}
2303	-re "\[\r\n\]\033\\\[.2004h$gdb_prompt $" {
2304	    # This special case detects what happens when GDB is
2305	    # started with bracketed paste mode enabled.  This mode is
2306	    # usually forced off (see setting of INPUTRC in
2307	    # default_gdb_init), but for at least one test we turn
2308	    # bracketed paste mode back on, and then start GDB.  In
2309	    # that case, this case is hit.
2310	    verbose "GDB initialized."
2311	}
2312	-re "$gdb_prompt $"	{
2313	    perror "GDB never initialized."
2314	    unset gdb_spawn_id
2315	    return -1
2316	}
2317	timeout	{
2318	    perror "(timeout) GDB never initialized after 10 seconds."
2319	    remote_close host
2320	    unset gdb_spawn_id
2321	    return -1
2322	}
2323	eof {
2324	    perror "(eof) GDB never initialized."
2325	    unset gdb_spawn_id
2326	    return -1
2327	}
2328    }
2329
2330    # force the height to "unlimited", so no pagers get used
2331
2332    send_gdb "set height 0\n"
2333    gdb_expect 10 {
2334	-re "$gdb_prompt $" {
2335	    verbose "Setting height to 0." 2
2336	}
2337	timeout {
2338	    warning "Couldn't set the height to 0"
2339	}
2340    }
2341    # force the width to "unlimited", so no wraparound occurs
2342    send_gdb "set width 0\n"
2343    gdb_expect 10 {
2344	-re "$gdb_prompt $" {
2345	    verbose "Setting width to 0." 2
2346	}
2347	timeout {
2348	    warning "Couldn't set the width to 0."
2349	}
2350    }
2351
2352    gdb_debug_init
2353    return 0
2354}
2355
2356# Utility procedure to give user control of the gdb prompt in a script. It is
2357# meant to be used for debugging test cases, and should not be left in the
2358# test cases code.
2359
2360proc gdb_interact { } {
2361    global gdb_spawn_id
2362    set spawn_id $gdb_spawn_id
2363
2364    send_user "+------------------------------------------+\n"
2365    send_user "| Script interrupted, you can now interact |\n"
2366    send_user "| with by gdb. Type >>> to continue.       |\n"
2367    send_user "+------------------------------------------+\n"
2368
2369    interact {
2370	">>>" return
2371    }
2372}
2373
2374# Examine the output of compilation to determine whether compilation
2375# failed or not.  If it failed determine whether it is due to missing
2376# compiler or due to compiler error.  Report pass, fail or unsupported
2377# as appropriate.
2378
2379proc gdb_compile_test {src output} {
2380    set msg "compilation [file tail $src]"
2381
2382    if { $output == "" } {
2383	pass $msg
2384	return
2385    }
2386
2387    if { [regexp {^[a-zA-Z_0-9]+: Can't find [^ ]+\.$} $output]
2388	 || [regexp {.*: command not found[\r|\n]*$} $output]
2389	 || [regexp {.*: [^\r\n]*compiler not installed[^\r\n]*[\r|\n]*$} $output] } {
2390	unsupported "$msg (missing compiler)"
2391	return
2392    }
2393
2394    set gcc_re ".*: error: unrecognized command line option "
2395    set clang_re ".*: error: unsupported option "
2396    if { [regexp "(?:$gcc_re|$clang_re)(\[^ \t;\r\n\]*)" $output dummy option]
2397	 && $option != "" } {
2398	unsupported "$msg (unsupported option $option)"
2399	return
2400    }
2401
2402    # Unclassified compilation failure, be more verbose.
2403    verbose -log "compilation failed: $output" 2
2404    fail "$msg"
2405}
2406
2407# Return a 1 for configurations for which we don't even want to try to
2408# test C++.
2409
2410proc skip_cplus_tests {} {
2411    if { [istarget "h8300-*-*"] } {
2412	return 1
2413    }
2414
2415    # The C++ IO streams are too large for HC11/HC12 and are thus not
2416    # available.  The gdb C++ tests use them and don't compile.
2417    if { [istarget "m6811-*-*"] } {
2418	return 1
2419    }
2420    if { [istarget "m6812-*-*"] } {
2421	return 1
2422    }
2423    return 0
2424}
2425
2426# Return a 1 for configurations for which don't have both C++ and the STL.
2427
2428proc skip_stl_tests {} {
2429    return [skip_cplus_tests]
2430}
2431
2432# Return a 1 if I don't even want to try to test FORTRAN.
2433
2434proc skip_fortran_tests {} {
2435    return 0
2436}
2437
2438# Return a 1 if I don't even want to try to test ada.
2439
2440proc skip_ada_tests {} {
2441    return 0
2442}
2443
2444# Return a 1 if I don't even want to try to test GO.
2445
2446proc skip_go_tests {} {
2447    return 0
2448}
2449
2450# Return a 1 if I don't even want to try to test D.
2451
2452proc skip_d_tests {} {
2453    return 0
2454}
2455
2456# Return 1 to skip Rust tests, 0 to try them.
2457proc skip_rust_tests {} {
2458    if { ![isnative] } {
2459	return 1
2460    }
2461
2462    # The rust compiler does not support "-m32", skip.
2463    global board board_info
2464    set board [target_info name]
2465    if {[board_info $board exists multilib_flags]} {
2466	foreach flag [board_info $board multilib_flags] {
2467	    if { $flag == "-m32" } {
2468		return 1
2469	    }
2470	}
2471    }
2472
2473    return 0
2474}
2475
2476# Return a 1 for configurations that do not support Python scripting.
2477# PROMPT_REGEXP is the expected prompt.
2478
2479proc skip_python_tests_prompt { prompt_regexp } {
2480    gdb_test_multiple "python print ('test')" "verify python support" \
2481	-prompt "$prompt_regexp" {
2482	    -re "not supported.*$prompt_regexp" {
2483		unsupported "Python support is disabled."
2484		return 1
2485	    }
2486	    -re "$prompt_regexp" {}
2487	}
2488
2489    return 0
2490}
2491
2492# Return a 1 for configurations that do not support Python scripting.
2493# Note: This also sets various globals that specify which version of Python
2494# is in use.  See skip_python_tests_prompt.
2495
2496proc skip_python_tests {} {
2497    global gdb_prompt
2498    return [skip_python_tests_prompt "$gdb_prompt $"]
2499}
2500
2501# Return a 1 if we should skip shared library tests.
2502
2503proc skip_shlib_tests {} {
2504    # Run the shared library tests on native systems.
2505    if {[isnative]} {
2506	return 0
2507    }
2508
2509    # An abbreviated list of remote targets where we should be able to
2510    # run shared library tests.
2511    if {([istarget *-*-linux*]
2512	 || [istarget *-*-*bsd*]
2513	 || [istarget *-*-solaris2*]
2514	 || [istarget *-*-mingw*]
2515	 || [istarget *-*-cygwin*]
2516	 || [istarget *-*-pe*])} {
2517	return 0
2518    }
2519
2520    return 1
2521}
2522
2523# Return 1 if we should skip dlmopen tests, 0 if we should not.
2524
2525gdb_caching_proc skip_dlmopen_tests {
2526    global srcdir subdir gdb_prompt inferior_exited_re
2527
2528    # We need shared library support.
2529    if { [skip_shlib_tests] } {
2530	return 1
2531    }
2532
2533    set me "skip_dlmopen_tests"
2534    set lib {
2535	int foo (void) {
2536	    return 42;
2537	}
2538    }
2539    set src {
2540	#define _GNU_SOURCE
2541	#include <dlfcn.h>
2542	#include <link.h>
2543	#include <stdio.h>
2544	#include <errno.h>
2545
2546	int  main (void) {
2547	    struct r_debug *r_debug;
2548	    ElfW(Dyn) *dyn;
2549	    void *handle;
2550
2551	    /* The version is kept at 1 until we create a new namespace.  */
2552	    handle = dlmopen (LM_ID_NEWLM, DSO_NAME, RTLD_LAZY | RTLD_LOCAL);
2553	    if (!handle) {
2554		printf ("dlmopen failed: %s.\n", dlerror ());
2555		return 1;
2556	    }
2557
2558	    r_debug = 0;
2559	    /* Taken from /usr/include/link.h.  */
2560	    for (dyn = _DYNAMIC; dyn->d_tag != DT_NULL; ++dyn)
2561	        if (dyn->d_tag == DT_DEBUG)
2562	            r_debug = (struct r_debug *) dyn->d_un.d_ptr;
2563
2564	    if (!r_debug) {
2565	        printf ("r_debug not found.\n");
2566		return 1;
2567	    }
2568	    if (r_debug->r_version < 2) {
2569	        printf ("dlmopen debug not supported.\n");
2570		return 1;
2571	    }
2572	    printf ("dlmopen debug supported.\n");
2573	    return 0;
2574	}
2575    }
2576
2577    set libsrc [standard_temp_file "libfoo.c"]
2578    set libout [standard_temp_file "libfoo.so"]
2579    gdb_produce_source $libsrc $lib
2580
2581    if { [gdb_compile_shlib $libsrc $libout {debug}] != "" } {
2582	verbose -log "failed to build library"
2583	return 1
2584    }
2585    if { ![gdb_simple_compile $me $src executable \
2586	       [list shlib_load debug \
2587		    additional_flags=-DDSO_NAME=\"$libout\"]] } {
2588	verbose -log "failed to build executable"
2589        return 1
2590    }
2591
2592    gdb_exit
2593    gdb_start
2594    gdb_reinitialize_dir $srcdir/$subdir
2595    gdb_load $obj
2596
2597    if { [gdb_run_cmd] != 0 } {
2598	verbose -log "failed to start skip test"
2599	return 1
2600    }
2601    gdb_expect {
2602        -re "$inferior_exited_re normally.*${gdb_prompt} $" {
2603            set skip_dlmopen_tests 0
2604        }
2605        -re "$inferior_exited_re with code.*${gdb_prompt} $" {
2606            set skip_dlmopen_tests 1
2607        }
2608        default {
2609	    warning "\n$me: default case taken"
2610            set skip_dlmopen_tests 1
2611        }
2612    }
2613    gdb_exit
2614
2615    verbose "$me:  returning $skip_dlmopen_tests" 2
2616    return $skip_dlmopen_tests
2617}
2618
2619# Return 1 if we should skip tui related tests.
2620
2621proc skip_tui_tests {} {
2622    global gdb_prompt
2623
2624    gdb_test_multiple "help layout" "verify tui support" {
2625	-re "Undefined command: \"layout\".*$gdb_prompt $" {
2626	    return 1
2627	}
2628	-re "$gdb_prompt $" {
2629	}
2630    }
2631
2632    return 0
2633}
2634
2635# Test files shall make sure all the test result lines in gdb.sum are
2636# unique in a test run, so that comparing the gdb.sum files of two
2637# test runs gives correct results.  Test files that exercise
2638# variations of the same tests more than once, shall prefix the
2639# different test invocations with different identifying strings in
2640# order to make them unique.
2641#
2642# About test prefixes:
2643#
2644# $pf_prefix is the string that dejagnu prints after the result (FAIL,
2645# PASS, etc.), and before the test message/name in gdb.sum.  E.g., the
2646# underlined substring in
2647#
2648#  PASS: gdb.base/mytest.exp: some test
2649#        ^^^^^^^^^^^^^^^^^^^^
2650#
2651# is $pf_prefix.
2652#
2653# The easiest way to adjust the test prefix is to append a test
2654# variation prefix to the $pf_prefix, using the with_test_prefix
2655# procedure.  E.g.,
2656#
2657# proc do_tests {} {
2658#   gdb_test ... ... "test foo"
2659#   gdb_test ... ... "test bar"
2660#
2661#   with_test_prefix "subvariation a" {
2662#     gdb_test ... ... "test x"
2663#   }
2664#
2665#   with_test_prefix "subvariation b" {
2666#     gdb_test ... ... "test x"
2667#   }
2668# }
2669#
2670# with_test_prefix "variation1" {
2671#   ...do setup for variation 1...
2672#   do_tests
2673# }
2674#
2675# with_test_prefix "variation2" {
2676#   ...do setup for variation 2...
2677#   do_tests
2678# }
2679#
2680# Results in:
2681#
2682#  PASS: gdb.base/mytest.exp: variation1: test foo
2683#  PASS: gdb.base/mytest.exp: variation1: test bar
2684#  PASS: gdb.base/mytest.exp: variation1: subvariation a: test x
2685#  PASS: gdb.base/mytest.exp: variation1: subvariation b: test x
2686#  PASS: gdb.base/mytest.exp: variation2: test foo
2687#  PASS: gdb.base/mytest.exp: variation2: test bar
2688#  PASS: gdb.base/mytest.exp: variation2: subvariation a: test x
2689#  PASS: gdb.base/mytest.exp: variation2: subvariation b: test x
2690#
2691# If for some reason more flexibility is necessary, one can also
2692# manipulate the pf_prefix global directly, treating it as a string.
2693# E.g.,
2694#
2695#   global pf_prefix
2696#   set saved_pf_prefix
2697#   append pf_prefix "${foo}: bar"
2698#   ... actual tests ...
2699#   set pf_prefix $saved_pf_prefix
2700#
2701
2702# Run BODY in the context of the caller, with the current test prefix
2703# (pf_prefix) appended with one space, then PREFIX, and then a colon.
2704# Returns the result of BODY.
2705#
2706proc with_test_prefix { prefix body } {
2707  global pf_prefix
2708
2709  set saved $pf_prefix
2710  append pf_prefix " " $prefix ":"
2711  set code [catch {uplevel 1 $body} result]
2712  set pf_prefix $saved
2713
2714  if {$code == 1} {
2715      global errorInfo errorCode
2716      return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2717  } else {
2718      return -code $code $result
2719  }
2720}
2721
2722# Wrapper for foreach that calls with_test_prefix on each iteration,
2723# including the iterator's name and current value in the prefix.
2724
2725proc foreach_with_prefix {var list body} {
2726    upvar 1 $var myvar
2727    foreach myvar $list {
2728	with_test_prefix "$var=$myvar" {
2729	    set code [catch {uplevel 1 $body} result]
2730	}
2731
2732	if {$code == 1} {
2733	    global errorInfo errorCode
2734	    return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2735	} elseif {$code == 3} {
2736	    break
2737	} elseif {$code == 2} {
2738	    return -code $code $result
2739	}
2740    }
2741}
2742
2743# Like TCL's native proc, but defines a procedure that wraps its body
2744# within 'with_test_prefix "$proc_name" { ... }'.
2745proc proc_with_prefix {name arguments body} {
2746    # Define the advertised proc.
2747    proc $name $arguments [list with_test_prefix $name $body]
2748}
2749
2750# Return an id corresponding to the test prefix stored in $pf_prefix, which
2751# is more suitable for use in a file name.
2752# F.i., for a pf_prefix:
2753#   gdb.dwarf2/dw2-lines.exp: \
2754#     cv=5: cdw=64: lv=5: ldw=64: string_form=line_strp:
2755# return an id:
2756#   cv-5-cdw-32-lv-5-ldw-64-string_form-line_strp
2757
2758proc prefix_id {} {
2759    global pf_prefix
2760    set id $pf_prefix
2761
2762    # Strip ".exp: " prefix.
2763    set id [regsub  {.*\.exp: } $id {}]
2764
2765    # Strip colon suffix.
2766    set id [regsub  {:$} $id {}]
2767
2768    # Strip spaces.
2769    set id [regsub -all { } $id {}]
2770
2771    # Replace colons, equal signs.
2772    set id [regsub -all \[:=\] $id -]
2773
2774    return $id
2775}
2776
2777# Run BODY in the context of the caller.  After BODY is run, the variables
2778# listed in VARS will be reset to the values they had before BODY was run.
2779#
2780# This is useful for providing a scope in which it is safe to temporarily
2781# modify global variables, e.g.
2782#
2783#   global INTERNAL_GDBFLAGS
2784#   global env
2785#
2786#   set foo GDBHISTSIZE
2787#
2788#   save_vars { INTERNAL_GDBFLAGS env($foo) env(HOME) } {
2789#       append INTERNAL_GDBFLAGS " -nx"
2790#       unset -nocomplain env(GDBHISTSIZE)
2791#       gdb_start
2792#       gdb_test ...
2793#   }
2794#
2795# Here, although INTERNAL_GDBFLAGS, env(GDBHISTSIZE) and env(HOME) may be
2796# modified inside BODY, this proc guarantees that the modifications will be
2797# undone after BODY finishes executing.
2798
2799proc save_vars { vars body } {
2800    array set saved_scalars { }
2801    array set saved_arrays { }
2802    set unset_vars { }
2803
2804    foreach var $vars {
2805	# First evaluate VAR in the context of the caller in case the variable
2806	# name may be a not-yet-interpolated string like env($foo)
2807	set var [uplevel 1 list $var]
2808
2809	if [uplevel 1 [list info exists $var]] {
2810	    if [uplevel 1 [list array exists $var]] {
2811		set saved_arrays($var) [uplevel 1 [list array get $var]]
2812	    } else {
2813		set saved_scalars($var) [uplevel 1 [list set $var]]
2814	    }
2815	} else {
2816	    lappend unset_vars $var
2817	}
2818    }
2819
2820    set code [catch {uplevel 1 $body} result]
2821
2822    foreach {var value} [array get saved_scalars] {
2823	uplevel 1 [list set $var $value]
2824    }
2825
2826    foreach {var value} [array get saved_arrays] {
2827	uplevel 1 [list unset $var]
2828	uplevel 1 [list array set $var $value]
2829    }
2830
2831    foreach var $unset_vars {
2832	uplevel 1 [list unset -nocomplain $var]
2833    }
2834
2835    if {$code == 1} {
2836	global errorInfo errorCode
2837	return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2838    } else {
2839	return -code $code $result
2840    }
2841}
2842
2843# As save_vars, but for variables stored in the board_info for the
2844# target board.
2845#
2846# Usage example:
2847#
2848#   save_target_board_info { multilib_flags } {
2849#       global board
2850#       set board [target_info name]
2851#       unset_board_info multilib_flags
2852#       set_board_info multilib_flags "$multilib_flags"
2853#       ...
2854#   }
2855
2856proc save_target_board_info { vars body } {
2857    global board board_info
2858    set board [target_info name]
2859
2860    array set saved_target_board_info { }
2861    set unset_target_board_info { }
2862
2863    foreach var $vars {
2864	if { [info exists board_info($board,$var)] } {
2865	    set saved_target_board_info($var) [board_info $board $var]
2866	} else {
2867	    lappend unset_target_board_info $var
2868	}
2869    }
2870
2871    set code [catch {uplevel 1 $body} result]
2872
2873    foreach {var value} [array get saved_target_board_info] {
2874	unset_board_info $var
2875	set_board_info $var $value
2876    }
2877
2878    foreach var $unset_target_board_info {
2879	unset_board_info $var
2880    }
2881
2882    if {$code == 1} {
2883	global errorInfo errorCode
2884	return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2885    } else {
2886	return -code $code $result
2887    }
2888}
2889
2890# Run tests in BODY with the current working directory (CWD) set to
2891# DIR.  When BODY is finished, restore the original CWD.  Return the
2892# result of BODY.
2893#
2894# This procedure doesn't check if DIR is a valid directory, so you
2895# have to make sure of that.
2896
2897proc with_cwd { dir body } {
2898    set saved_dir [pwd]
2899    verbose -log "Switching to directory $dir (saved CWD: $saved_dir)."
2900    cd $dir
2901
2902    set code [catch {uplevel 1 $body} result]
2903
2904    verbose -log "Switching back to $saved_dir."
2905    cd $saved_dir
2906
2907    if {$code == 1} {
2908	global errorInfo errorCode
2909	return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2910    } else {
2911	return -code $code $result
2912    }
2913}
2914
2915# Use GDB's 'cd' command to switch to DIR.  Return true if the switch
2916# was successful, otherwise, call perror and return false.
2917
2918proc gdb_cd { dir } {
2919    set new_dir ""
2920    gdb_test_multiple "cd $dir" "" {
2921	-re "^cd \[^\r\n\]+\r\n" {
2922	    exp_continue
2923	}
2924
2925	-re "^Working directory (\[^\r\n\]+)\\.\r\n" {
2926	    set new_dir $expect_out(1,string)
2927	    exp_continue
2928	}
2929
2930	-re "^$::gdb_prompt $" {
2931	    if { $new_dir == "" || $new_dir != $dir } {
2932		perror "failed to switch to $dir"
2933		return false
2934	    }
2935	}
2936    }
2937
2938    return true
2939}
2940
2941# Use GDB's 'pwd' command to figure out the current working directory.
2942# Return the directory as a string.  If we can't figure out the
2943# current working directory, then call perror, and return the empty
2944# string.
2945
2946proc gdb_pwd { } {
2947    set dir ""
2948    gdb_test_multiple "pwd" "" {
2949	-re "^pwd\r\n" {
2950	    exp_continue
2951	}
2952
2953	-re "^Working directory (\[^\r\n\]+)\\.\r\n" {
2954	    set dir $expect_out(1,string)
2955	    exp_continue
2956	}
2957
2958	-re "^$::gdb_prompt $" {
2959	}
2960    }
2961
2962    if { $dir == "" } {
2963	perror "failed to read GDB's current working directory"
2964    }
2965
2966    return $dir
2967}
2968
2969# Similar to the with_cwd proc, this proc runs BODY with the current
2970# working directory changed to CWD.
2971#
2972# Unlike with_cwd, the directory change here is done within GDB
2973# itself, so GDB must be running before this proc is called.
2974
2975proc with_gdb_cwd { dir body } {
2976    set saved_dir [gdb_pwd]
2977    if { $saved_dir == "" } {
2978	return
2979    }
2980
2981    verbose -log "Switching to directory $dir (saved CWD: $saved_dir)."
2982    if ![gdb_cd $dir] {
2983	return
2984    }
2985
2986    set code [catch {uplevel 1 $body} result]
2987
2988    verbose -log "Switching back to $saved_dir."
2989    if ![gdb_cd $saved_dir] {
2990	return
2991    }
2992
2993    # Check that GDB is still alive.  If GDB crashed in the above code
2994    # then any corefile will have been left in DIR, not the root
2995    # testsuite directory.  As a result the corefile will not be
2996    # brought to the users attention.  Instead, if GDB crashed, then
2997    # this check should cause a FAIL, which should be enough to alert
2998    # the user.
2999    set saw_result false
3000    gdb_test_multiple "p 123" "" {
3001	-re "p 123\r\n" {
3002	    exp_continue
3003	}
3004
3005	-re "^\\\$$::decimal = 123\r\n" {
3006	    set saw_result true
3007	    exp_continue
3008	}
3009
3010	-re "^$::gdb_prompt $" {
3011	    if { !$saw_result } {
3012		fail "check gdb is alive in with_gdb_cwd"
3013	    }
3014	}
3015    }
3016
3017    if {$code == 1} {
3018	global errorInfo errorCode
3019	return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3020    } else {
3021	return -code $code $result
3022    }
3023}
3024
3025# Run tests in BODY with GDB prompt and variable $gdb_prompt set to
3026# PROMPT.  When BODY is finished, restore GDB prompt and variable
3027# $gdb_prompt.
3028# Returns the result of BODY.
3029#
3030# Notes:
3031#
3032# 1) If you want to use, for example, "(foo)" as the prompt you must pass it
3033# as "(foo)", and not the regexp form "\(foo\)" (expressed as "\\(foo\\)" in
3034# TCL).  PROMPT is internally converted to a suitable regexp for matching.
3035# We do the conversion from "(foo)" to "\(foo\)" here for a few reasons:
3036#   a) It's more intuitive for callers to pass the plain text form.
3037#   b) We need two forms of the prompt:
3038#      - a regexp to use in output matching,
3039#      - a value to pass to the "set prompt" command.
3040#   c) It's easier to convert the plain text form to its regexp form.
3041#
3042# 2) Don't add a trailing space, we do that here.
3043
3044proc with_gdb_prompt { prompt body } {
3045    global gdb_prompt
3046
3047    # Convert "(foo)" to "\(foo\)".
3048    # We don't use string_to_regexp because while it works today it's not
3049    # clear it will work tomorrow: the value we need must work as both a
3050    # regexp *and* as the argument to the "set prompt" command, at least until
3051    # we start recording both forms separately instead of just $gdb_prompt.
3052    # The testsuite is pretty-much hardwired to interpret $gdb_prompt as the
3053    # regexp form.
3054    regsub -all {[]*+.|()^$\[\\]} $prompt {\\&} prompt
3055
3056    set saved $gdb_prompt
3057
3058    verbose -log "Setting gdb prompt to \"$prompt \"."
3059    set gdb_prompt $prompt
3060    gdb_test_no_output "set prompt $prompt " ""
3061
3062    set code [catch {uplevel 1 $body} result]
3063
3064    verbose -log "Restoring gdb prompt to \"$saved \"."
3065    set gdb_prompt $saved
3066    gdb_test_no_output "set prompt $saved " ""
3067
3068    if {$code == 1} {
3069	global errorInfo errorCode
3070	return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3071    } else {
3072	return -code $code $result
3073    }
3074}
3075
3076# Run tests in BODY with target-charset setting to TARGET_CHARSET.  When
3077# BODY is finished, restore target-charset.
3078
3079proc with_target_charset { target_charset body } {
3080    global gdb_prompt
3081
3082    set saved ""
3083    gdb_test_multiple "show target-charset" "" {
3084	-re "The target character set is \".*; currently (.*)\"\..*$gdb_prompt " {
3085	    set saved $expect_out(1,string)
3086	}
3087	-re "The target character set is \"(.*)\".*$gdb_prompt " {
3088	    set saved $expect_out(1,string)
3089	}
3090	-re ".*$gdb_prompt " {
3091	    fail "get target-charset"
3092	}
3093    }
3094
3095    gdb_test_no_output -nopass "set target-charset $target_charset"
3096
3097    set code [catch {uplevel 1 $body} result]
3098
3099    gdb_test_no_output -nopass "set target-charset $saved"
3100
3101    if {$code == 1} {
3102	global errorInfo errorCode
3103	return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3104    } else {
3105	return -code $code $result
3106    }
3107}
3108
3109# Switch the default spawn id to SPAWN_ID, so that gdb_test,
3110# mi_gdb_test etc. default to using it.
3111
3112proc switch_gdb_spawn_id {spawn_id} {
3113    global gdb_spawn_id
3114    global board board_info
3115
3116    set gdb_spawn_id $spawn_id
3117    set board [host_info name]
3118    set board_info($board,fileid) $spawn_id
3119}
3120
3121# Clear the default spawn id.
3122
3123proc clear_gdb_spawn_id {} {
3124    global gdb_spawn_id
3125    global board board_info
3126
3127    unset -nocomplain gdb_spawn_id
3128    set board [host_info name]
3129    unset -nocomplain board_info($board,fileid)
3130}
3131
3132# Run BODY with SPAWN_ID as current spawn id.
3133
3134proc with_spawn_id { spawn_id body } {
3135    global gdb_spawn_id
3136
3137    if [info exists gdb_spawn_id] {
3138	set saved_spawn_id $gdb_spawn_id
3139    }
3140
3141    switch_gdb_spawn_id $spawn_id
3142
3143    set code [catch {uplevel 1 $body} result]
3144
3145    if [info exists saved_spawn_id] {
3146	switch_gdb_spawn_id $saved_spawn_id
3147    } else {
3148	clear_gdb_spawn_id
3149    }
3150
3151    if {$code == 1} {
3152	global errorInfo errorCode
3153	return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3154    } else {
3155	return -code $code $result
3156    }
3157}
3158
3159# Select the largest timeout from all the timeouts:
3160# - the local "timeout" variable of the scope two levels above,
3161# - the global "timeout" variable,
3162# - the board variable "gdb,timeout".
3163
3164proc get_largest_timeout {} {
3165    upvar #0 timeout gtimeout
3166    upvar 2 timeout timeout
3167
3168    set tmt 0
3169    if [info exists timeout] {
3170      set tmt $timeout
3171    }
3172    if { [info exists gtimeout] && $gtimeout > $tmt } {
3173	set tmt $gtimeout
3174    }
3175    if { [target_info exists gdb,timeout]
3176	 && [target_info gdb,timeout] > $tmt } {
3177	set tmt [target_info gdb,timeout]
3178    }
3179    if { $tmt == 0 } {
3180	# Eeeeew.
3181	set tmt 60
3182    }
3183
3184    return $tmt
3185}
3186
3187# Run tests in BODY with timeout increased by factor of FACTOR.  When
3188# BODY is finished, restore timeout.
3189
3190proc with_timeout_factor { factor body } {
3191    global timeout
3192
3193    set savedtimeout $timeout
3194
3195    set timeout [expr [get_largest_timeout] * $factor]
3196    set code [catch {uplevel 1 $body} result]
3197
3198    set timeout $savedtimeout
3199    if {$code == 1} {
3200	global errorInfo errorCode
3201	return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3202    } else {
3203	return -code $code $result
3204    }
3205}
3206
3207# Run BODY with timeout factor FACTOR if check-read1 is used.
3208
3209proc with_read1_timeout_factor { factor body } {
3210    if { [info exists ::env(READ1)] == 1 && $::env(READ1) == 1 } {
3211	# Use timeout factor
3212    } else {
3213	# Reset timeout factor
3214	set factor 1
3215    }
3216    return [uplevel [list with_timeout_factor $factor $body]]
3217}
3218
3219# Return 1 if _Complex types are supported, otherwise, return 0.
3220
3221gdb_caching_proc support_complex_tests {
3222
3223    if { [gdb_skip_float_test] } {
3224	# If floating point is not supported, _Complex is not
3225	# supported.
3226	return 0
3227    }
3228
3229    # Compile a test program containing _Complex types.
3230
3231    return [gdb_can_simple_compile complex {
3232	int main() {
3233	    _Complex float cf;
3234	    _Complex double cd;
3235	    _Complex long double cld;
3236	    return 0;
3237	}
3238    } executable]
3239}
3240
3241# Return 1 if compiling go is supported.
3242gdb_caching_proc support_go_compile {
3243
3244    return [gdb_can_simple_compile go-hello {
3245	package main
3246	import "fmt"
3247	func main() {
3248	    fmt.Println("hello world")
3249	}
3250    } executable go]
3251}
3252
3253# Return 1 if GDB can get a type for siginfo from the target, otherwise
3254# return 0.
3255
3256proc supports_get_siginfo_type {} {
3257    if { [istarget "*-*-linux*"] } {
3258	return 1
3259    } else {
3260	return 0
3261    }
3262}
3263
3264# Return 1 if memory tagging is supported at runtime, otherwise return 0.
3265
3266gdb_caching_proc supports_memtag {
3267    global gdb_prompt
3268
3269    gdb_test_multiple "memory-tag check" "" {
3270	-re "Memory tagging not supported or disabled by the current architecture\..*$gdb_prompt $" {
3271	  return 0
3272	}
3273	-re "Argument required \\(address or pointer\\).*$gdb_prompt $" {
3274	    return 1
3275	}
3276    }
3277    return 0
3278}
3279
3280# Return 1 if the target supports hardware single stepping.
3281
3282proc can_hardware_single_step {} {
3283
3284    if { [istarget "arm*-*-*"] || [istarget "mips*-*-*"]
3285	 || [istarget "tic6x-*-*"] || [istarget "sparc*-*-linux*"]
3286	 || [istarget "nios2-*-*"] || [istarget "riscv*-*-linux*"] } {
3287	return 0
3288    }
3289
3290    return 1
3291}
3292
3293# Return 1 if target hardware or OS supports single stepping to signal
3294# handler, otherwise, return 0.
3295
3296proc can_single_step_to_signal_handler {} {
3297    # Targets don't have hardware single step.  On these targets, when
3298    # a signal is delivered during software single step, gdb is unable
3299    # to determine the next instruction addresses, because start of signal
3300    # handler is one of them.
3301    return [can_hardware_single_step]
3302}
3303
3304# Return 1 if target supports process record, otherwise return 0.
3305
3306proc supports_process_record {} {
3307
3308    if [target_info exists gdb,use_precord] {
3309	return [target_info gdb,use_precord]
3310    }
3311
3312    if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
3313         || [istarget "i\[34567\]86-*-linux*"]
3314         || [istarget "aarch64*-*-linux*"]
3315         || [istarget "powerpc*-*-linux*"]
3316         || [istarget "s390*-*-linux*"] } {
3317	return 1
3318    }
3319
3320    return 0
3321}
3322
3323# Return 1 if target supports reverse debugging, otherwise return 0.
3324
3325proc supports_reverse {} {
3326
3327    if [target_info exists gdb,can_reverse] {
3328	return [target_info gdb,can_reverse]
3329    }
3330
3331    if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
3332         || [istarget "i\[34567\]86-*-linux*"]
3333         || [istarget "aarch64*-*-linux*"]
3334         || [istarget "powerpc*-*-linux*"]
3335         || [istarget "s390*-*-linux*"] } {
3336	return 1
3337    }
3338
3339    return 0
3340}
3341
3342# Return 1 if readline library is used.
3343
3344proc readline_is_used { } {
3345    global gdb_prompt
3346
3347    gdb_test_multiple "show editing" "" {
3348	-re ".*Editing of command lines as they are typed is on\..*$gdb_prompt $" {
3349	    return 1
3350	}
3351	-re ".*$gdb_prompt $" {
3352	    return 0
3353	}
3354    }
3355}
3356
3357# Return 1 if target is ELF.
3358gdb_caching_proc is_elf_target {
3359    set me "is_elf_target"
3360
3361    set src { int foo () {return 0;} }
3362    if {![gdb_simple_compile elf_target $src]} {
3363        return 0
3364    }
3365
3366    set fp_obj [open $obj "r"]
3367    fconfigure $fp_obj -translation binary
3368    set data [read $fp_obj]
3369    close $fp_obj
3370
3371    file delete $obj
3372
3373    set ELFMAG "\u007FELF"
3374
3375    if {[string compare -length 4 $data $ELFMAG] != 0} {
3376	verbose "$me:  returning 0" 2
3377	return 0
3378    }
3379
3380    verbose "$me:  returning 1" 2
3381    return 1
3382}
3383
3384# Return 1 if the memory at address zero is readable.
3385
3386gdb_caching_proc is_address_zero_readable {
3387    global gdb_prompt
3388
3389    set ret 0
3390    gdb_test_multiple "x 0" "" {
3391	-re "Cannot access memory at address 0x0.*$gdb_prompt $" {
3392	    set ret 0
3393	}
3394	-re ".*$gdb_prompt $" {
3395	    set ret 1
3396	}
3397    }
3398
3399    return $ret
3400}
3401
3402# Produce source file NAME and write SOURCES into it.
3403
3404proc gdb_produce_source { name sources } {
3405    set index 0
3406    set f [open $name "w"]
3407
3408    puts $f $sources
3409    close $f
3410}
3411
3412# Return 1 if target is ILP32.
3413# This cannot be decided simply from looking at the target string,
3414# as it might depend on externally passed compiler options like -m64.
3415gdb_caching_proc is_ilp32_target {
3416    return [gdb_can_simple_compile is_ilp32_target {
3417	int dummy[sizeof (int) == 4
3418		  && sizeof (void *) == 4
3419		  && sizeof (long) == 4 ? 1 : -1];
3420    }]
3421}
3422
3423# Return 1 if target is LP64.
3424# This cannot be decided simply from looking at the target string,
3425# as it might depend on externally passed compiler options like -m64.
3426gdb_caching_proc is_lp64_target {
3427    return [gdb_can_simple_compile is_lp64_target {
3428	int dummy[sizeof (int) == 4
3429		  && sizeof (void *) == 8
3430		  && sizeof (long) == 8 ? 1 : -1];
3431    }]
3432}
3433
3434# Return 1 if target has 64 bit addresses.
3435# This cannot be decided simply from looking at the target string,
3436# as it might depend on externally passed compiler options like -m64.
3437gdb_caching_proc is_64_target {
3438    return [gdb_can_simple_compile is_64_target {
3439	int function(void) { return 3; }
3440	int dummy[sizeof (&function) == 8 ? 1 : -1];
3441    }]
3442}
3443
3444# Return 1 if target has x86_64 registers - either amd64 or x32.
3445# x32 target identifies as x86_64-*-linux*, therefore it cannot be determined
3446# just from the target string.
3447gdb_caching_proc is_amd64_regs_target {
3448    if {![istarget "x86_64-*-*"] && ![istarget "i?86-*"]} {
3449	return 0
3450    }
3451
3452    return [gdb_can_simple_compile is_amd64_regs_target {
3453	int main (void) {
3454	    asm ("incq %rax");
3455	    asm ("incq %r15");
3456
3457	    return 0;
3458	}
3459    }]
3460}
3461
3462# Return 1 if this target is an x86 or x86-64 with -m32.
3463proc is_x86_like_target {} {
3464    if {![istarget "x86_64-*-*"] && ![istarget i?86-*]} {
3465	return 0
3466    }
3467    return [expr [is_ilp32_target] && ![is_amd64_regs_target]]
3468}
3469
3470# Return 1 if this target is an arm or aarch32 on aarch64.
3471
3472gdb_caching_proc is_aarch32_target {
3473    if { [istarget "arm*-*-*"] } {
3474	return 1
3475    }
3476
3477    if { ![istarget "aarch64*-*-*"] } {
3478	return 0
3479    }
3480
3481    set list {}
3482    foreach reg \
3483	{r0 r1 r2 r3} {
3484	    lappend list "\tmov $reg, $reg"
3485	}
3486
3487    return [gdb_can_simple_compile aarch32 [join $list \n]]
3488}
3489
3490# Return 1 if this target is an aarch64, either lp64 or ilp32.
3491
3492proc is_aarch64_target {} {
3493    if { ![istarget "aarch64*-*-*"] } {
3494	return 0
3495    }
3496
3497    return [expr ![is_aarch32_target]]
3498}
3499
3500# Return 1 if displaced stepping is supported on target, otherwise, return 0.
3501proc support_displaced_stepping {} {
3502
3503    if { [istarget "x86_64-*-linux*"] || [istarget "i\[34567\]86-*-linux*"]
3504	 || [istarget "arm*-*-linux*"] || [istarget "powerpc-*-linux*"]
3505	 || [istarget "powerpc64-*-linux*"] || [istarget "s390*-*-*"]
3506	 || [istarget "aarch64*-*-linux*"] || [istarget "loongarch*-*-linux*"] } {
3507	return 1
3508    }
3509
3510    return 0
3511}
3512
3513# Run a test on the target to see if it supports vmx hardware.  Return 0 if so,
3514# 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
3515
3516gdb_caching_proc skip_altivec_tests {
3517    global srcdir subdir gdb_prompt inferior_exited_re
3518
3519    set me "skip_altivec_tests"
3520
3521    # Some simulators are known to not support VMX instructions.
3522    if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
3523        verbose "$me:  target known to not support VMX, returning 1" 2
3524        return 1
3525    }
3526
3527    # Make sure we have a compiler that understands altivec.
3528    if [test_compiler_info gcc*] {
3529        set compile_flags "additional_flags=-maltivec"
3530    } elseif [test_compiler_info xlc*] {
3531        set compile_flags "additional_flags=-qaltivec"
3532    } else {
3533        verbose "Could not compile with altivec support, returning 1" 2
3534        return 1
3535    }
3536
3537    # Compile a test program containing VMX instructions.
3538    set src {
3539	int main() {
3540	    #ifdef __MACH__
3541	    asm volatile ("vor v0,v0,v0");
3542	    #else
3543	    asm volatile ("vor 0,0,0");
3544	    #endif
3545	    return 0;
3546	}
3547    }
3548    if {![gdb_simple_compile $me $src executable $compile_flags]} {
3549        return 1
3550    }
3551
3552    # Compilation succeeded so now run it via gdb.
3553
3554    gdb_exit
3555    gdb_start
3556    gdb_reinitialize_dir $srcdir/$subdir
3557    gdb_load "$obj"
3558    gdb_run_cmd
3559    gdb_expect {
3560        -re ".*Illegal instruction.*${gdb_prompt} $" {
3561            verbose -log "\n$me altivec hardware not detected"
3562            set skip_vmx_tests 1
3563        }
3564        -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3565            verbose -log "\n$me: altivec hardware detected"
3566            set skip_vmx_tests 0
3567        }
3568        default {
3569          warning "\n$me: default case taken"
3570            set skip_vmx_tests 1
3571        }
3572    }
3573    gdb_exit
3574    remote_file build delete $obj
3575
3576    verbose "$me:  returning $skip_vmx_tests" 2
3577    return $skip_vmx_tests
3578}
3579
3580# Run a test on the power target to see if it supports ISA 3.1 instructions
3581gdb_caching_proc skip_power_isa_3_1_tests {
3582    global srcdir subdir gdb_prompt inferior_exited_re
3583
3584    set me "skip_power_isa_3_1_tests"
3585
3586    # Compile a test program containing ISA 3.1 instructions.
3587    set src {
3588	int main() {
3589	asm volatile ("pnop"); // marker
3590		asm volatile ("nop");
3591		return 0;
3592	    }
3593	}
3594
3595    if {![gdb_simple_compile $me $src executable ]} {
3596        return 1
3597    }
3598
3599    # No error message, compilation succeeded so now run it via gdb.
3600
3601    gdb_exit
3602    gdb_start
3603    gdb_reinitialize_dir $srcdir/$subdir
3604    gdb_load "$obj"
3605    gdb_run_cmd
3606    gdb_expect {
3607        -re ".*Illegal instruction.*${gdb_prompt} $" {
3608            verbose -log "\n$me Power ISA 3.1 hardware not detected"
3609            set skip_power_isa_3_1_tests 1
3610        }
3611        -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3612            verbose -log "\n$me: Power ISA 3.1 hardware detected"
3613            set skip_power_isa_3_1_tests 0
3614        }
3615        default {
3616          warning "\n$me: default case taken"
3617            set skip_power_isa_3_1_tests 1
3618        }
3619    }
3620    gdb_exit
3621    remote_file build delete $obj
3622
3623    verbose "$me:  returning $skip_power_isa_3_1_tests" 2
3624    return $skip_power_isa_3_1_tests
3625}
3626
3627# Run a test on the target to see if it supports vmx hardware.  Return 0 if so,
3628# 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
3629
3630gdb_caching_proc skip_vsx_tests {
3631    global srcdir subdir gdb_prompt inferior_exited_re
3632
3633    set me "skip_vsx_tests"
3634
3635    # Some simulators are known to not support Altivec instructions, so
3636    # they won't support VSX instructions as well.
3637    if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
3638        verbose "$me:  target known to not support VSX, returning 1" 2
3639        return 1
3640    }
3641
3642    # Make sure we have a compiler that understands altivec.
3643    if [test_compiler_info gcc*] {
3644        set compile_flags "additional_flags=-mvsx"
3645    } elseif [test_compiler_info xlc*] {
3646        set compile_flags "additional_flags=-qasm=gcc"
3647    } else {
3648        verbose "Could not compile with vsx support, returning 1" 2
3649        return 1
3650    }
3651
3652    # Compile a test program containing VSX instructions.
3653    set src {
3654	int main() {
3655	    double a[2] = { 1.0, 2.0 };
3656	    #ifdef __MACH__
3657	    asm volatile ("lxvd2x v0,v0,%[addr]" : : [addr] "r" (a));
3658	    #else
3659	    asm volatile ("lxvd2x 0,0,%[addr]" : : [addr] "r" (a));
3660	    #endif
3661	    return 0;
3662	}
3663    }
3664    if {![gdb_simple_compile $me $src executable $compile_flags]} {
3665        return 1
3666    }
3667
3668    # No error message, compilation succeeded so now run it via gdb.
3669
3670    gdb_exit
3671    gdb_start
3672    gdb_reinitialize_dir $srcdir/$subdir
3673    gdb_load "$obj"
3674    gdb_run_cmd
3675    gdb_expect {
3676        -re ".*Illegal instruction.*${gdb_prompt} $" {
3677            verbose -log "\n$me VSX hardware not detected"
3678            set skip_vsx_tests 1
3679        }
3680        -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3681            verbose -log "\n$me: VSX hardware detected"
3682            set skip_vsx_tests 0
3683        }
3684        default {
3685          warning "\n$me: default case taken"
3686            set skip_vsx_tests 1
3687        }
3688    }
3689    gdb_exit
3690    remote_file build delete $obj
3691
3692    verbose "$me:  returning $skip_vsx_tests" 2
3693    return $skip_vsx_tests
3694}
3695
3696# Run a test on the target to see if it supports TSX hardware.  Return 0 if so,
3697# 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
3698
3699gdb_caching_proc skip_tsx_tests {
3700    global srcdir subdir gdb_prompt inferior_exited_re
3701
3702    set me "skip_tsx_tests"
3703
3704    # Compile a test program.
3705    set src {
3706        int main() {
3707            asm volatile ("xbegin .L0");
3708            asm volatile ("xend");
3709            asm volatile (".L0: nop");
3710            return 0;
3711        }
3712    }
3713    if {![gdb_simple_compile $me $src executable]} {
3714        return 1
3715    }
3716
3717    # No error message, compilation succeeded so now run it via gdb.
3718
3719    gdb_exit
3720    gdb_start
3721    gdb_reinitialize_dir $srcdir/$subdir
3722    gdb_load "$obj"
3723    gdb_run_cmd
3724    gdb_expect {
3725        -re ".*Illegal instruction.*${gdb_prompt} $" {
3726            verbose -log "$me:  TSX hardware not detected."
3727            set skip_tsx_tests 1
3728        }
3729        -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3730            verbose -log "$me:  TSX hardware detected."
3731            set skip_tsx_tests 0
3732        }
3733        default {
3734            warning "\n$me:  default case taken."
3735            set skip_tsx_tests 1
3736        }
3737    }
3738    gdb_exit
3739    remote_file build delete $obj
3740
3741    verbose "$me:  returning $skip_tsx_tests" 2
3742    return $skip_tsx_tests
3743}
3744
3745# Run a test on the target to see if it supports avx512bf16.  Return 0 if so,
3746# 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
3747
3748gdb_caching_proc skip_avx512bf16_tests {
3749    global srcdir subdir gdb_prompt inferior_exited_re
3750
3751    set me "skip_avx512bf16_tests"
3752    if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
3753        verbose "$me:  target does not support avx512bf16, returning 1" 2
3754        return 1
3755    }
3756
3757    # Compile a test program.
3758    set src {
3759        int main() {
3760            asm volatile ("vcvtne2ps2bf16 %xmm0, %xmm1, %xmm0");
3761            return 0;
3762        }
3763    }
3764    if {![gdb_simple_compile $me $src executable]} {
3765        return 1
3766    }
3767
3768    # No error message, compilation succeeded so now run it via gdb.
3769
3770    gdb_exit
3771    gdb_start
3772    gdb_reinitialize_dir $srcdir/$subdir
3773    gdb_load "$obj"
3774    gdb_run_cmd
3775    gdb_expect {
3776        -re ".*Illegal instruction.*${gdb_prompt} $" {
3777            verbose -log "$me:  avx512bf16 hardware not detected."
3778            set skip_avx512bf16_tests 1
3779        }
3780        -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3781            verbose -log "$me:  avx512bf16 hardware detected."
3782            set skip_avx512bf16_tests 0
3783        }
3784        default {
3785            warning "\n$me:  default case taken."
3786            set skip_avx512bf16_tests 1
3787        }
3788    }
3789    gdb_exit
3790    remote_file build delete $obj
3791
3792    verbose "$me:  returning $skip_avx512bf16_tests" 2
3793    return $skip_avx512bf16_tests
3794}
3795
3796# Run a test on the target to see if it supports avx512fp16.  Return 0 if so,
3797# 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
3798
3799gdb_caching_proc skip_avx512fp16_tests {
3800    global srcdir subdir gdb_prompt inferior_exited_re
3801
3802    set me "skip_avx512fp16_tests"
3803    if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
3804        verbose "$me:  target does not support avx512fp16, returning 1" 2
3805        return 1
3806    }
3807
3808    # Compile a test program.
3809    set src {
3810        int main() {
3811            asm volatile ("vcvtps2phx %xmm1, %xmm0");
3812            return 0;
3813        }
3814    }
3815    if {![gdb_simple_compile $me $src executable]} {
3816        return 1
3817    }
3818
3819    # No error message, compilation succeeded so now run it via gdb.
3820
3821    gdb_exit
3822    gdb_start
3823    gdb_reinitialize_dir $srcdir/$subdir
3824    gdb_load "$obj"
3825    gdb_run_cmd
3826    gdb_expect {
3827        -re ".*Illegal instruction.*${gdb_prompt} $" {
3828            verbose -log "$me:  avx512fp16 hardware not detected."
3829            set skip_avx512fp16_tests 1
3830        }
3831        -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3832            verbose -log "$me:  avx512fp16 hardware detected."
3833            set skip_avx512fp16_tests 0
3834        }
3835        default {
3836            warning "\n$me:  default case taken."
3837            set skip_avx512fp16_tests 1
3838        }
3839    }
3840    gdb_exit
3841    remote_file build delete $obj
3842
3843    verbose "$me:  returning $skip_avx512fp16_tests" 2
3844    return $skip_avx512fp16_tests
3845}
3846
3847# Run a test on the target to see if it supports btrace hardware.  Return 0 if so,
3848# 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
3849
3850gdb_caching_proc skip_btrace_tests {
3851    global srcdir subdir gdb_prompt inferior_exited_re
3852
3853    set me "skip_btrace_tests"
3854    if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
3855        verbose "$me:  target does not support btrace, returning 1" 2
3856        return 1
3857    }
3858
3859    # Compile a test program.
3860    set src { int main() { return 0; } }
3861    if {![gdb_simple_compile $me $src executable]} {
3862        return 1
3863    }
3864
3865    # No error message, compilation succeeded so now run it via gdb.
3866
3867    gdb_exit
3868    gdb_start
3869    gdb_reinitialize_dir $srcdir/$subdir
3870    gdb_load $obj
3871    if ![runto_main] {
3872        return 1
3873    }
3874    # In case of an unexpected output, we return 2 as a fail value.
3875    set skip_btrace_tests 2
3876    gdb_test_multiple "record btrace" "check btrace support" {
3877        -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
3878            set skip_btrace_tests 1
3879        }
3880        -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
3881            set skip_btrace_tests 1
3882        }
3883        -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
3884            set skip_btrace_tests 1
3885        }
3886        -re "^record btrace\r\n$gdb_prompt $" {
3887            set skip_btrace_tests 0
3888        }
3889    }
3890    gdb_exit
3891    remote_file build delete $obj
3892
3893    verbose "$me:  returning $skip_btrace_tests" 2
3894    return $skip_btrace_tests
3895}
3896
3897# Run a test on the target to see if it supports btrace pt hardware.
3898# Return 0 if so, 1 if it does not.  Based on 'check_vmx_hw_available'
3899# from the GCC testsuite.
3900
3901gdb_caching_proc skip_btrace_pt_tests {
3902    global srcdir subdir gdb_prompt inferior_exited_re
3903
3904    set me "skip_btrace_tests"
3905    if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
3906        verbose "$me:  target does not support btrace, returning 1" 2
3907        return 1
3908    }
3909
3910    # Compile a test program.
3911    set src { int main() { return 0; } }
3912    if {![gdb_simple_compile $me $src executable]} {
3913        return 1
3914    }
3915
3916    # No error message, compilation succeeded so now run it via gdb.
3917
3918    gdb_exit
3919    gdb_start
3920    gdb_reinitialize_dir $srcdir/$subdir
3921    gdb_load $obj
3922    if ![runto_main] {
3923        return 1
3924    }
3925    # In case of an unexpected output, we return 2 as a fail value.
3926    set skip_btrace_tests 2
3927    gdb_test_multiple "record btrace pt" "check btrace pt support" {
3928        -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
3929            set skip_btrace_tests 1
3930        }
3931        -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
3932            set skip_btrace_tests 1
3933        }
3934        -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
3935            set skip_btrace_tests 1
3936        }
3937        -re "support was disabled at compile time.*\r\n$gdb_prompt $" {
3938            set skip_btrace_tests 1
3939        }
3940        -re "^record btrace pt\r\n$gdb_prompt $" {
3941            set skip_btrace_tests 0
3942        }
3943    }
3944    gdb_exit
3945    remote_file build delete $obj
3946
3947    verbose "$me:  returning $skip_btrace_tests" 2
3948    return $skip_btrace_tests
3949}
3950
3951# Run a test on the target to see if it supports Aarch64 SVE hardware.
3952# Return 0 if so, 1 if it does not.  Note this causes a restart of GDB.
3953
3954gdb_caching_proc skip_aarch64_sve_tests {
3955    global srcdir subdir gdb_prompt inferior_exited_re
3956
3957    set me "skip_aarch64_sve_tests"
3958
3959    if { ![is_aarch64_target]} {
3960	return 1
3961    }
3962
3963    set compile_flags "{additional_flags=-march=armv8-a+sve}"
3964
3965    # Compile a test program containing SVE instructions.
3966    set src {
3967	int main() {
3968	    asm volatile ("ptrue p0.b");
3969	    return 0;
3970	}
3971    }
3972    if {![gdb_simple_compile $me $src executable $compile_flags]} {
3973        return 1
3974    }
3975
3976    # Compilation succeeded so now run it via gdb.
3977    clean_restart $obj
3978    gdb_run_cmd
3979    gdb_expect {
3980        -re ".*Illegal instruction.*${gdb_prompt} $" {
3981            verbose -log "\n$me sve hardware not detected"
3982            set skip_sve_tests 1
3983        }
3984        -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3985            verbose -log "\n$me: sve hardware detected"
3986            set skip_sve_tests 0
3987        }
3988        default {
3989          warning "\n$me: default case taken"
3990            set skip_sve_tests 1
3991        }
3992    }
3993    gdb_exit
3994    remote_file build delete $obj
3995
3996    verbose "$me:  returning $skip_sve_tests" 2
3997    return $skip_sve_tests
3998}
3999
4000
4001# A helper that compiles a test case to see if __int128 is supported.
4002proc gdb_int128_helper {lang} {
4003    return [gdb_can_simple_compile "i128-for-$lang" {
4004	__int128 x;
4005	int main() { return 0; }
4006    } executable $lang]
4007}
4008
4009# Return true if the C compiler understands the __int128 type.
4010gdb_caching_proc has_int128_c {
4011    return [gdb_int128_helper c]
4012}
4013
4014# Return true if the C++ compiler understands the __int128 type.
4015gdb_caching_proc has_int128_cxx {
4016    return [gdb_int128_helper c++]
4017}
4018
4019# Return true if the IFUNC feature is unsupported.
4020gdb_caching_proc skip_ifunc_tests {
4021    if [gdb_can_simple_compile ifunc {
4022	extern void f_ ();
4023	typedef void F (void);
4024	F* g (void) { return &f_; }
4025	void f () __attribute__ ((ifunc ("g")));
4026    } object] {
4027	return 0
4028    } else {
4029	return 1
4030    }
4031}
4032
4033# Return whether we should skip tests for showing inlined functions in
4034# backtraces.  Requires get_compiler_info and get_debug_format.
4035
4036proc skip_inline_frame_tests {} {
4037    # GDB only recognizes inlining information in DWARF.
4038    if { ! [test_debug_format "DWARF \[0-9\]"] } {
4039	return 1
4040    }
4041
4042    # GCC before 4.1 does not emit DW_AT_call_file / DW_AT_call_line.
4043    if { ([test_compiler_info "gcc-2-*"]
4044	  || [test_compiler_info "gcc-3-*"]
4045	  || [test_compiler_info "gcc-4-0-*"]) } {
4046	return 1
4047    }
4048
4049    return 0
4050}
4051
4052# Return whether we should skip tests for showing variables from
4053# inlined functions.  Requires get_compiler_info and get_debug_format.
4054
4055proc skip_inline_var_tests {} {
4056    # GDB only recognizes inlining information in DWARF.
4057    if { ! [test_debug_format "DWARF \[0-9\]"] } {
4058	return 1
4059    }
4060
4061    return 0
4062}
4063
4064# Return a 1 if we should skip tests that require hardware breakpoints
4065
4066proc skip_hw_breakpoint_tests {} {
4067    # Skip tests if requested by the board (note that no_hardware_watchpoints
4068    # disables both watchpoints and breakpoints)
4069    if { [target_info exists gdb,no_hardware_watchpoints]} {
4070	return 1
4071    }
4072
4073    # These targets support hardware breakpoints natively
4074    if { [istarget "i?86-*-*"]
4075	 || [istarget "x86_64-*-*"]
4076	 || [istarget "ia64-*-*"]
4077	 || [istarget "arm*-*-*"]
4078	 || [istarget "aarch64*-*-*"]
4079	 || [istarget "s390*-*-*"] } {
4080	return 0
4081    }
4082
4083    return 1
4084}
4085
4086# Return a 1 if we should skip tests that require hardware watchpoints
4087
4088proc skip_hw_watchpoint_tests {} {
4089    # Skip tests if requested by the board
4090    if { [target_info exists gdb,no_hardware_watchpoints]} {
4091	return 1
4092    }
4093
4094    # These targets support hardware watchpoints natively
4095    # Note, not all Power 9 processors support hardware watchpoints due to a HW
4096    # bug.  Use has_hw_wp_support to check do a runtime check for hardware
4097    # watchpoint support on Powerpc.
4098    if { [istarget "i?86-*-*"]
4099	 || [istarget "x86_64-*-*"]
4100	 || [istarget "ia64-*-*"]
4101	 || [istarget "arm*-*-*"]
4102	 || [istarget "aarch64*-*-*"]
4103	 || ([istarget "powerpc*-*-linux*"] && [has_hw_wp_support])
4104	 || [istarget "s390*-*-*"] } {
4105	return 0
4106    }
4107
4108    return 1
4109}
4110
4111# Return a 1 if we should skip tests that require *multiple* hardware
4112# watchpoints to be active at the same time
4113
4114proc skip_hw_watchpoint_multi_tests {} {
4115    if { [skip_hw_watchpoint_tests] } {
4116	return 1
4117    }
4118
4119    # These targets support just a single hardware watchpoint
4120    if { [istarget "arm*-*-*"]
4121	 || [istarget "powerpc*-*-linux*"] } {
4122	return 1
4123    }
4124
4125    return 0
4126}
4127
4128# Return a 1 if we should skip tests that require read/access watchpoints
4129
4130proc skip_hw_watchpoint_access_tests {} {
4131    if { [skip_hw_watchpoint_tests] } {
4132	return 1
4133    }
4134
4135    # These targets support just write watchpoints
4136    if { [istarget "s390*-*-*"] } {
4137	return 1
4138    }
4139
4140    return 0
4141}
4142
4143# Return 1 if we should skip tests that require the runtime unwinder
4144# hook.  This must be invoked while gdb is running, after shared
4145# libraries have been loaded.  This is needed because otherwise a
4146# shared libgcc won't be visible.
4147
4148proc skip_unwinder_tests {} {
4149    global gdb_prompt
4150
4151    set ok 0
4152    gdb_test_multiple "print _Unwind_DebugHook" "check for unwinder hook" {
4153	-re "= .*no debug info.*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
4154	}
4155	-re "= .*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
4156	    set ok 1
4157	}
4158	-re "No symbol .* in current context.\r\n$gdb_prompt $" {
4159	}
4160    }
4161    if {!$ok} {
4162	gdb_test_multiple "info probe" "check for stap probe in unwinder" {
4163	    -re ".*libgcc.*unwind.*\r\n$gdb_prompt $" {
4164		set ok 1
4165	    }
4166	    -re "\r\n$gdb_prompt $" {
4167	    }
4168	}
4169    }
4170    return $ok
4171}
4172
4173# Return 1 if we should skip tests that require the libstdc++ stap
4174# probes.  This must be invoked while gdb is running, after shared
4175# libraries have been loaded.  PROMPT_REGEXP is the expected prompt.
4176
4177proc skip_libstdcxx_probe_tests_prompt { prompt_regexp } {
4178    set supported 0
4179    gdb_test_multiple "info probe" "check for stap probe in libstdc++" \
4180	-prompt "$prompt_regexp" {
4181	    -re ".*libstdcxx.*catch.*\r\n$prompt_regexp" {
4182		set supported 1
4183	    }
4184	    -re "\r\n$prompt_regexp" {
4185	    }
4186	}
4187    set skip [expr !$supported]
4188    return $skip
4189}
4190
4191# As skip_libstdcxx_probe_tests_prompt, with gdb_prompt.
4192
4193proc skip_libstdcxx_probe_tests {} {
4194    global gdb_prompt
4195    return [skip_libstdcxx_probe_tests_prompt "$gdb_prompt $"]
4196}
4197
4198# Helper for gdb_is_target_* procs.  TARGET_NAME is the name of the target
4199# we're looking for (used to build the test name).  TARGET_STACK_REGEXP
4200# is a regexp that will match the output of "maint print target-stack" if
4201# the target in question is currently pushed.  PROMPT_REGEXP is a regexp
4202# matching the expected prompt after the command output.
4203#
4204# NOTE: GDB must be running BEFORE this procedure is called!
4205
4206proc gdb_is_target_1 { target_name target_stack_regexp prompt_regexp } {
4207    global gdb_spawn_id
4208
4209    # Throw a Tcl error if gdb isn't already started.
4210    if {![info exists gdb_spawn_id]} {
4211	error "gdb_is_target_1 called with no running gdb instance"
4212    }
4213
4214    set test "probe for target ${target_name}"
4215    gdb_test_multiple "maint print target-stack" $test \
4216	-prompt "$prompt_regexp" {
4217	    -re "${target_stack_regexp}${prompt_regexp}" {
4218		pass $test
4219		return 1
4220	    }
4221	    -re "$prompt_regexp" {
4222		pass $test
4223	    }
4224	}
4225    return 0
4226}
4227
4228# Helper for gdb_is_target_remote where the expected prompt is variable.
4229#
4230# NOTE: GDB must be running BEFORE this procedure is called!
4231
4232proc gdb_is_target_remote_prompt { prompt_regexp } {
4233    return [gdb_is_target_1 "remote" ".*emote target using gdb-specific protocol.*" $prompt_regexp]
4234}
4235
4236# Check whether we're testing with the remote or extended-remote
4237# targets.
4238#
4239# NOTE: GDB must be running BEFORE this procedure is called!
4240
4241proc gdb_is_target_remote { } {
4242    global gdb_prompt
4243
4244    return [gdb_is_target_remote_prompt "$gdb_prompt $"]
4245}
4246
4247# Check whether we're testing with the native target.
4248#
4249# NOTE: GDB must be running BEFORE this procedure is called!
4250
4251proc gdb_is_target_native { } {
4252    global gdb_prompt
4253
4254    return [gdb_is_target_1 "native" ".*native \\(Native process\\).*" "$gdb_prompt $"]
4255}
4256
4257# Return the effective value of use_gdb_stub.
4258#
4259# If the use_gdb_stub global has been set (it is set when the gdb process is
4260# spawned), return that.  Otherwise, return the value of the use_gdb_stub
4261# property from the board file.
4262#
4263# This is the preferred way of checking use_gdb_stub, since it allows to check
4264# the value before the gdb has been spawned and it will return the correct value
4265# even when it was overriden by the test.
4266#
4267# Note that stub targets are not able to spawn new inferiors.  Use this
4268# check for skipping respective tests.
4269
4270proc use_gdb_stub {} {
4271  global use_gdb_stub
4272
4273  if [info exists use_gdb_stub] {
4274     return $use_gdb_stub
4275  }
4276
4277  return [target_info exists use_gdb_stub]
4278}
4279
4280# Return 1 if the current remote target is an instance of our GDBserver, 0
4281# otherwise.  Return -1 if there was an error and we can't tell.
4282
4283gdb_caching_proc target_is_gdbserver {
4284    global gdb_prompt
4285
4286    set is_gdbserver -1
4287    set test "probing for GDBserver"
4288
4289    gdb_test_multiple "monitor help" $test {
4290	-re "The following monitor commands are supported.*Quit GDBserver.*$gdb_prompt $" {
4291	    set is_gdbserver 1
4292	}
4293	-re "$gdb_prompt $" {
4294	    set is_gdbserver 0
4295	}
4296    }
4297
4298    if { $is_gdbserver == -1 } {
4299	verbose -log "Unable to tell whether we are using GDBserver or not."
4300    }
4301
4302    return $is_gdbserver
4303}
4304
4305# N.B. compiler_info is intended to be local to this file.
4306# Call test_compiler_info with no arguments to fetch its value.
4307# Yes, this is counterintuitive when there's get_compiler_info,
4308# but that's the current API.
4309if [info exists compiler_info] {
4310    unset compiler_info
4311}
4312
4313# Figure out what compiler I am using.
4314# The result is cached so only the first invocation runs the compiler.
4315#
4316# ARG can be empty or "C++".  If empty, "C" is assumed.
4317#
4318# There are several ways to do this, with various problems.
4319#
4320# [ gdb_compile -E $ifile -o $binfile.ci ]
4321# source $binfile.ci
4322#
4323#   Single Unix Spec v3 says that "-E -o ..." together are not
4324#   specified.  And in fact, the native compiler on hp-ux 11 (among
4325#   others) does not work with "-E -o ...".  Most targets used to do
4326#   this, and it mostly worked, because it works with gcc.
4327#
4328# [ catch "exec $compiler -E $ifile > $binfile.ci" exec_output ]
4329# source $binfile.ci
4330#
4331#   This avoids the problem with -E and -o together.  This almost works
4332#   if the build machine is the same as the host machine, which is
4333#   usually true of the targets which are not gcc.  But this code does
4334#   not figure which compiler to call, and it always ends up using the C
4335#   compiler.  Not good for setting hp_aCC_compiler.  Target
4336#   hppa*-*-hpux* used to do this.
4337#
4338# [ gdb_compile -E $ifile > $binfile.ci ]
4339# source $binfile.ci
4340#
4341#   dejagnu target_compile says that it supports output redirection,
4342#   but the code is completely different from the normal path and I
4343#   don't want to sweep the mines from that path.  So I didn't even try
4344#   this.
4345#
4346# set cppout [ gdb_compile $ifile "" preprocess $args quiet ]
4347# eval $cppout
4348#
4349#   I actually do this for all targets now.  gdb_compile runs the right
4350#   compiler, and TCL captures the output, and I eval the output.
4351#
4352#   Unfortunately, expect logs the output of the command as it goes by,
4353#   and dejagnu helpfully prints a second copy of it right afterwards.
4354#   So I turn off expect logging for a moment.
4355#
4356# [ gdb_compile $ifile $ciexe_file executable $args ]
4357# [ remote_exec $ciexe_file ]
4358# [ source $ci_file.out ]
4359#
4360#   I could give up on -E and just do this.
4361#   I didn't get desperate enough to try this.
4362#
4363# -- chastain 2004-01-06
4364
4365proc get_compiler_info {{language "c"}} {
4366
4367    # For compiler.c, compiler.cc and compiler.F90.
4368    global srcdir
4369
4370    # I am going to play with the log to keep noise out.
4371    global outdir
4372    global tool
4373
4374    # These come from compiler.c, compiler.cc or compiler.F90.
4375    gdb_persistent_global compiler_info_cache
4376
4377    if [info exists compiler_info_cache($language)] {
4378	# Already computed.
4379	return 0
4380    }
4381
4382    # Choose which file to preprocess.
4383    if { $language == "c++" } {
4384	set ifile "${srcdir}/lib/compiler.cc"
4385    } elseif { $language == "f90" } {
4386	set ifile "${srcdir}/lib/compiler.F90"
4387    } elseif { $language == "c" } {
4388	set ifile "${srcdir}/lib/compiler.c"
4389    } else {
4390	perror "Unable to fetch compiler version for language: $language"
4391	return -1
4392    }
4393
4394    # Run $ifile through the right preprocessor.
4395    # Toggle gdb.log to keep the compiler output out of the log.
4396    set saved_log [log_file -info]
4397    log_file
4398    if [is_remote host] {
4399	# We have to use -E and -o together, despite the comments
4400	# above, because of how DejaGnu handles remote host testing.
4401	set ppout "$outdir/compiler.i"
4402	gdb_compile "${ifile}" "$ppout" preprocess [list "$language" quiet getting_compiler_info]
4403	set file [open $ppout r]
4404	set cppout [read $file]
4405	close $file
4406    } else {
4407	# Copy $ifile to temp dir, to work around PR gcc/60447.  This will leave the
4408	# superfluous .s file in the temp dir instead of in the source dir.
4409	set tofile [file tail $ifile]
4410	set tofile [standard_temp_file $tofile]
4411	file copy -force $ifile $tofile
4412	set ifile $tofile
4413	set cppout [ gdb_compile "${ifile}" "" preprocess [list "$language" quiet getting_compiler_info] ]
4414    }
4415    eval log_file $saved_log
4416
4417    # Eval the output.
4418    set unknown 0
4419    foreach cppline [ split "$cppout" "\n" ] {
4420	if { [ regexp "^#" "$cppline" ] } {
4421	    # line marker
4422	} elseif { [ regexp "^\[\n\r\t \]*$" "$cppline" ] } {
4423	    # blank line
4424	} elseif { [ regexp "^\[\n\r\t \]*set\[\n\r\t \]" "$cppline" ] } {
4425	    # eval this line
4426	    verbose "get_compiler_info: $cppline" 2
4427	    eval "$cppline"
4428	} elseif { [ regexp "flang.*warning.*'-fdiagnostics-color=never'" "$cppline"] } {
4429	    # Both flang preprocessors (llvm flang and classic flang) print a
4430	    # warning for the unused -fdiagnostics-color=never, so we skip this
4431	    # output line here.
4432	} else {
4433	    # unknown line
4434	    verbose -log "get_compiler_info: $cppline"
4435	    set unknown 1
4436	}
4437    }
4438
4439    # Set to unknown if for some reason compiler_info didn't get defined.
4440    if ![info exists compiler_info] {
4441	verbose -log "get_compiler_info: compiler_info not provided"
4442	set compiler_info "unknown"
4443    }
4444    # Also set to unknown compiler if any diagnostics happened.
4445    if { $unknown } {
4446	verbose -log "get_compiler_info: got unexpected diagnostics"
4447	set compiler_info "unknown"
4448    }
4449
4450    set compiler_info_cache($language) $compiler_info
4451
4452    # Log what happened.
4453    verbose -log "get_compiler_info: $compiler_info"
4454
4455    return 0
4456}
4457
4458# Return the compiler_info string if no arg is provided.
4459# Otherwise the argument is a glob-style expression to match against
4460# compiler_info.
4461
4462proc test_compiler_info { {compiler ""} {language "c"} } {
4463    gdb_persistent_global compiler_info_cache
4464
4465    if [get_compiler_info $language] {
4466	# An error will already have been printed in this case.  Just
4467	# return a suitable result depending on how the user called
4468	# this function.
4469	if [string match "" $compiler] {
4470	    return ""
4471	} else {
4472	    return false
4473	}
4474    }
4475
4476    # If no arg, return the compiler_info string.
4477    if [string match "" $compiler] {
4478	return $compiler_info_cache($language)
4479    }
4480
4481    return [string match $compiler $compiler_info_cache($language)]
4482}
4483
4484# Return true if the C compiler is GCC, otherwise, return false.
4485
4486proc is_c_compiler_gcc {} {
4487    set compiler_info [test_compiler_info]
4488    set gcc_compiled false
4489    regexp "^gcc-(\[0-9\]+)-" "$compiler_info" matchall gcc_compiled
4490    return $gcc_compiled
4491}
4492
4493# Return the gcc major version, or -1.
4494# For gcc 4.8.5, the major version is 4.8.
4495# For gcc 7.5.0, the major version 7.
4496# The COMPILER and LANGUAGE arguments are as for test_compiler_info.
4497
4498proc gcc_major_version { {compiler "gcc-*"} {language "c"} } {
4499    global decimal
4500    if { ![test_compiler_info $compiler $language] } {
4501	return -1
4502    }
4503    # Strip "gcc-*" to "gcc".
4504    regsub -- {-.*} $compiler "" compiler
4505    set res [regexp $compiler-($decimal)-($decimal)- \
4506		 [test_compiler_info "" $language] \
4507		 dummy_var major minor]
4508    if { $res != 1 } {
4509	return -1
4510    }
4511    if { $major >= 5} {
4512	return $major
4513    }
4514    return $major.$minor
4515}
4516
4517proc current_target_name { } {
4518    global target_info
4519    if [info exists target_info(target,name)] {
4520        set answer $target_info(target,name)
4521    } else {
4522        set answer ""
4523    }
4524    return $answer
4525}
4526
4527set gdb_wrapper_initialized 0
4528set gdb_wrapper_target ""
4529set gdb_wrapper_file ""
4530set gdb_wrapper_flags ""
4531
4532proc gdb_wrapper_init { args } {
4533    global gdb_wrapper_initialized
4534    global gdb_wrapper_file
4535    global gdb_wrapper_flags
4536    global gdb_wrapper_target
4537
4538    if { $gdb_wrapper_initialized == 1 } { return; }
4539
4540    if {[target_info exists needs_status_wrapper] && \
4541	    [target_info needs_status_wrapper] != "0"} {
4542	set result [build_wrapper "testglue.o"]
4543	if { $result != "" } {
4544	    set gdb_wrapper_file [lindex $result 0]
4545	    if ![is_remote host] {
4546		set gdb_wrapper_file [file join [pwd] $gdb_wrapper_file]
4547	    }
4548	    set gdb_wrapper_flags [lindex $result 1]
4549	} else {
4550	    warning "Status wrapper failed to build."
4551	}
4552    } else {
4553	set gdb_wrapper_file ""
4554	set gdb_wrapper_flags ""
4555    }
4556    verbose "set gdb_wrapper_file = $gdb_wrapper_file"
4557    set gdb_wrapper_initialized 1
4558    set gdb_wrapper_target [current_target_name]
4559}
4560
4561# Determine options that we always want to pass to the compiler.
4562gdb_caching_proc universal_compile_options {
4563    set me "universal_compile_options"
4564    set options {}
4565
4566    set src [standard_temp_file ccopts[pid].c]
4567    set obj [standard_temp_file ccopts[pid].o]
4568
4569    gdb_produce_source $src {
4570	int foo(void) { return 0; }
4571    }
4572
4573    # Try an option for disabling colored diagnostics.  Some compilers
4574    # yield colored diagnostics by default (when run from a tty) unless
4575    # such an option is specified.
4576    set opt "additional_flags=-fdiagnostics-color=never"
4577    set lines [target_compile $src $obj object [list "quiet" $opt]]
4578    if {[string match "" $lines]} {
4579	# Seems to have worked; use the option.
4580	lappend options $opt
4581    }
4582    file delete $src
4583    file delete $obj
4584
4585    verbose "$me:  returning $options" 2
4586    return $options
4587}
4588
4589# Compile the code in $code to a file based on $name, using the flags
4590# $compile_flag as well as debug, nowarning and quiet.
4591# Return 1 if code can be compiled
4592# Leave the file name of the resulting object in the upvar object.
4593
4594proc gdb_simple_compile {name code {type object} {compile_flags {}} {object obj}} {
4595    upvar $object obj
4596
4597    switch -regexp -- $type {
4598        "executable" {
4599            set postfix "x"
4600        }
4601        "object" {
4602            set postfix "o"
4603        }
4604        "preprocess" {
4605            set postfix "i"
4606        }
4607        "assembly" {
4608            set postfix "s"
4609        }
4610    }
4611    set ext "c"
4612    foreach flag $compile_flags {
4613	if { "$flag" == "go" } {
4614	    set ext "go"
4615	    break
4616	}
4617    }
4618    set src [standard_temp_file $name-[pid].$ext]
4619    set obj [standard_temp_file $name-[pid].$postfix]
4620    set compile_flags [concat $compile_flags {debug nowarnings quiet}]
4621
4622    gdb_produce_source $src $code
4623
4624    verbose "$name:  compiling testfile $src" 2
4625    set lines [gdb_compile $src $obj $type $compile_flags]
4626
4627    file delete $src
4628
4629    if {![string match "" $lines]} {
4630        verbose "$name:  compilation failed, returning 0" 2
4631        return 0
4632    }
4633    return 1
4634}
4635
4636# Compile the code in $code to a file based on $name, using the flags
4637# $compile_flag as well as debug, nowarning and quiet.
4638# Return 1 if code can be compiled
4639# Delete all created files and objects.
4640
4641proc gdb_can_simple_compile {name code {type object} {compile_flags ""}} {
4642    set ret [gdb_simple_compile $name $code $type $compile_flags temp_obj]
4643    file delete $temp_obj
4644    return $ret
4645}
4646
4647# Some targets need to always link a special object in.  Save its path here.
4648global gdb_saved_set_unbuffered_mode_obj
4649set gdb_saved_set_unbuffered_mode_obj ""
4650
4651# Compile source files specified by SOURCE into a binary of type TYPE at path
4652# DEST.  gdb_compile is implemented using DejaGnu's target_compile, so the type
4653# parameter and most options are passed directly to it.
4654#
4655# The type can be one of the following:
4656#
4657#   - object: Compile into an object file.
4658#   - executable: Compile and link into an executable.
4659#   - preprocess: Preprocess the source files.
4660#   - assembly: Generate assembly listing.
4661#
4662# The following options are understood and processed by gdb_compile:
4663#
4664#   - shlib=so_path: Add SO_PATH to the sources, and enable some target-specific
4665#     quirks to be able to use shared libraries.
4666#   - shlib_load: Link with appropriate libraries to allow the test to
4667#     dynamically load libraries at runtime.  For example, on Linux, this adds
4668#     -ldl so that the test can use dlopen.
4669#   - nowarnings:  Inhibit all compiler warnings.
4670#   - pie: Force creation of PIE executables.
4671#   - nopie: Prevent creation of PIE executables.
4672#   - macros: Add the required compiler flag to include macro information in
4673#     debug information
4674#   - text_segment=addr: Tell the linker to place the text segment at ADDR.
4675#   - build-id: Ensure the final binary includes a build-id.
4676#
4677# And here are some of the not too obscure options understood by DejaGnu that
4678# influence the compilation:
4679#
4680#   - additional_flags=flag: Add FLAG to the compiler flags.
4681#   - libs=library: Add LIBRARY to the libraries passed to the linker.  The
4682#     argument can be a file, in which case it's added to the sources, or a
4683#     linker flag.
4684#   - ldflags=flag: Add FLAG to the linker flags.
4685#   - incdir=path: Add PATH to the searched include directories.
4686#   - libdir=path: Add PATH to the linker searched directories.
4687#   - ada, c++, f90, go, rust: Compile the file as Ada, C++,
4688#     Fortran 90, Go or Rust.
4689#   - debug: Build with debug information.
4690#   - optimize: Build with optimization.
4691
4692proc gdb_compile {source dest type options} {
4693    global GDB_TESTCASE_OPTIONS
4694    global gdb_wrapper_file
4695    global gdb_wrapper_flags
4696    global srcdir
4697    global objdir
4698    global gdb_saved_set_unbuffered_mode_obj
4699
4700    set outdir [file dirname $dest]
4701
4702    # If this is set, calling test_compiler_info will cause recursion.
4703    if { [lsearch -exact $options getting_compiler_info] == -1 } {
4704	set getting_compiler_info false
4705    } else {
4706	set getting_compiler_info true
4707    }
4708
4709    # Add platform-specific options if a shared library was specified using
4710    # "shlib=librarypath" in OPTIONS.
4711    set new_options {}
4712    if {[lsearch -exact $options rust] != -1} {
4713	# -fdiagnostics-color is not a rustcc option.
4714    } else {
4715	set new_options [universal_compile_options]
4716    }
4717
4718    # Some C/C++ testcases unconditionally pass -Wno-foo as additional
4719    # options to disable some warning.  That is OK with GCC, because
4720    # by design, GCC accepts any -Wno-foo option, even if it doesn't
4721    # support -Wfoo.  Clang however warns about unknown -Wno-foo by
4722    # default, unless you pass -Wno-unknown-warning-option as well.
4723    # We do that here, so that individual testcases don't have to
4724    # worry about it.
4725    if {!$getting_compiler_info
4726	&& [lsearch -exact $options rust] == -1
4727	&& [lsearch -exact $options ada] == -1
4728	&& [lsearch -exact $options f90] == -1
4729	&& [lsearch -exact $options go] == -1} {
4730	if {[test_compiler_info "clang-*"] || [test_compiler_info "icx-*"]} {
4731	    lappend new_options "additional_flags=-Wno-unknown-warning-option"
4732	} elseif {[test_compiler_info "icc-*"]} {
4733	    # This is the equivalent for the icc compiler.
4734	    lappend new_options "additional_flags=-diag-disable=10148"
4735	}
4736    }
4737
4738    # If the 'build-id' option is used, then ensure that we generate a
4739    # build-id.  GCC does this by default, but Clang does not, so
4740    # enable it now.
4741    if {[lsearch -exact $options build-id] > 0
4742	&& [test_compiler_info "clang-*"]} {
4743	lappend new_options "additional_flags=-Wl,--build-id"
4744    }
4745
4746    # Treating .c input files as C++ is deprecated in Clang, so
4747    # explicitly force C++ language.
4748    if { !$getting_compiler_info
4749	 && [lsearch -exact $options c++] != -1
4750	 && [string match *.c $source] != 0 } {
4751
4752	# gdb_compile cannot handle this combination of options, the
4753	# result is a command like "clang -x c++ foo.c bar.so -o baz"
4754	# which tells Clang to treat bar.so as C++.  The solution is
4755	# to call gdb_compile twice--once to compile, once to link--
4756	# either directly, or via build_executable_from_specs.
4757	if { [lsearch $options shlib=*] != -1 } {
4758	    error "incompatible gdb_compile options"
4759	}
4760
4761	if {[test_compiler_info "clang-*"]} {
4762	    lappend new_options early_flags=-x\ c++
4763	}
4764    }
4765
4766    # Place (and look for) Fortran `.mod` files in the output
4767    # directory for this specific test.  For Intel compilers the -J
4768    # option is not supported so instead use the -module flag.
4769    # Additionally, Intel compilers need the -debug-parameters flag set to
4770    # emit debug info for all parameters in modules.
4771    if { !$getting_compiler_info && [lsearch -exact $options f90] != -1 } {
4772	# Fortran compile.
4773	set mod_path [standard_output_file ""]
4774	if { [test_compiler_info {gfortran-*} f90] } {
4775	    lappend new_options "additional_flags=-J${mod_path}"
4776	} elseif { [test_compiler_info {ifort-*} f90]
4777		   || [test_compiler_info {ifx-*} f90] } {
4778	    lappend new_options "additional_flags=-module ${mod_path}"
4779	    lappend new_options "additional_flags=-debug-parameters all"
4780	}
4781    }
4782
4783    set shlib_found 0
4784    set shlib_load 0
4785    foreach opt $options {
4786        if {[regexp {^shlib=(.*)} $opt dummy_var shlib_name]
4787	    && $type == "executable"} {
4788            if [test_compiler_info "xlc-*"] {
4789		# IBM xlc compiler doesn't accept shared library named other
4790		# than .so: use "-Wl," to bypass this
4791		lappend source "-Wl,$shlib_name"
4792	    } elseif { ([istarget "*-*-mingw*"]
4793			|| [istarget *-*-cygwin*]
4794			|| [istarget *-*-pe*])} {
4795		lappend source "${shlib_name}.a"
4796            } else {
4797               lappend source $shlib_name
4798            }
4799            if { $shlib_found == 0 } {
4800                set shlib_found 1
4801		if { ([istarget "*-*-mingw*"]
4802		      || [istarget *-*-cygwin*]) } {
4803		    lappend new_options "ldflags=-Wl,--enable-auto-import"
4804		}
4805		if { [test_compiler_info "gcc-*"] || [test_compiler_info "clang-*"] } {
4806		    # Undo debian's change in the default.
4807		    # Put it at the front to not override any user-provided
4808		    # value, and to make sure it appears in front of all the
4809		    # shlibs!
4810		    lappend new_options "early_flags=-Wl,--no-as-needed"
4811		}
4812            }
4813	} elseif { $opt == "shlib_load" && $type == "executable" } {
4814	    set shlib_load 1
4815	} elseif { $opt == "getting_compiler_info" } {
4816	    # Ignore this setting here as it has been handled earlier in this
4817	    # procedure.  Do not append it to new_options as this will cause
4818	    # recursion.
4819        } elseif {[regexp "^text_segment=(.*)" $opt dummy_var addr]} {
4820            if { [linker_supports_Ttext_segment_flag] } {
4821                # For GNU ld.
4822                lappend new_options "ldflags=-Wl,-Ttext-segment=$addr"
4823            } elseif { [linker_supports_image_base_flag] } {
4824                # For LLVM's lld.
4825                lappend new_options "ldflags=-Wl,--image-base=$addr"
4826            } elseif { [linker_supports_Ttext_flag] } {
4827                # For old GNU gold versions.
4828                lappend new_options "ldflags=-Wl,-Ttext=$addr"
4829            } else {
4830                error "Don't know how to handle text_segment option."
4831            }
4832        } else {
4833            lappend new_options $opt
4834        }
4835    }
4836
4837    # Ensure stack protector is disabled for GCC, as this causes problems with
4838    # DWARF line numbering.
4839    # See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88432
4840    # This option defaults to on for Debian/Ubuntu.
4841    if { !$getting_compiler_info
4842	 && [test_compiler_info {gcc-*-*}]
4843	 && !([test_compiler_info {gcc-[0-3]-*}]
4844	      || [test_compiler_info {gcc-4-0-*}])
4845	 && [lsearch -exact $options rust] == -1} {
4846        # Put it at the front to not override any user-provided value.
4847        lappend new_options "early_flags=-fno-stack-protector"
4848    }
4849
4850    # Because we link with libraries using their basename, we may need
4851    # (depending on the platform) to set a special rpath value, to allow
4852    # the executable to find the libraries it depends on.
4853    if { $shlib_load || $shlib_found } {
4854	if { ([istarget "*-*-mingw*"]
4855	      || [istarget *-*-cygwin*]
4856	      || [istarget *-*-pe*]) } {
4857	    # Do not need anything.
4858	} elseif { [istarget *-*-freebsd*] || [istarget *-*-openbsd*] } {
4859	    lappend new_options "ldflags=-Wl,-rpath,${outdir}"
4860	} else {
4861	    if { $shlib_load } {
4862		lappend new_options "libs=-ldl"
4863	    }
4864	    lappend new_options "ldflags=-Wl,-rpath,\\\$ORIGIN"
4865	}
4866    }
4867    set options $new_options
4868
4869    if [info exists GDB_TESTCASE_OPTIONS] {
4870	lappend options "additional_flags=$GDB_TESTCASE_OPTIONS"
4871    }
4872    verbose "options are $options"
4873    verbose "source is $source $dest $type $options"
4874
4875    gdb_wrapper_init
4876
4877    if {[target_info exists needs_status_wrapper] && \
4878	    [target_info needs_status_wrapper] != "0" && \
4879	    $gdb_wrapper_file != "" } {
4880	lappend options "libs=${gdb_wrapper_file}"
4881	lappend options "ldflags=${gdb_wrapper_flags}"
4882    }
4883
4884    # Replace the "nowarnings" option with the appropriate additional_flags
4885    # to disable compiler warnings.
4886    set nowarnings [lsearch -exact $options nowarnings]
4887    if {$nowarnings != -1} {
4888	if [target_info exists gdb,nowarnings_flag] {
4889	    set flag "additional_flags=[target_info gdb,nowarnings_flag]"
4890	} else {
4891	    set flag "additional_flags=-w"
4892	}
4893	set options [lreplace $options $nowarnings $nowarnings $flag]
4894    }
4895
4896    # Replace the "pie" option with the appropriate compiler and linker flags
4897    # to enable PIE executables.
4898    set pie [lsearch -exact $options pie]
4899    if {$pie != -1} {
4900	if [target_info exists gdb,pie_flag] {
4901	    set flag "additional_flags=[target_info gdb,pie_flag]"
4902	} else {
4903	    # For safety, use fPIE rather than fpie. On AArch64, m68k, PowerPC
4904	    # and SPARC, fpie can cause compile errors due to the GOT exceeding
4905	    # a maximum size.  On other architectures the two flags are
4906	    # identical (see the GCC manual). Note Debian9 and Ubuntu16.10
4907	    # onwards default GCC to using fPIE.  If you do require fpie, then
4908	    # it can be set using the pie_flag.
4909	    set flag "additional_flags=-fPIE"
4910	}
4911	set options [lreplace $options $pie $pie $flag]
4912
4913	if [target_info exists gdb,pie_ldflag] {
4914	    set flag "ldflags=[target_info gdb,pie_ldflag]"
4915	} else {
4916	    set flag "ldflags=-pie"
4917	}
4918	lappend options "$flag"
4919    }
4920
4921    # Replace the "nopie" option with the appropriate compiler and linker
4922    # flags to disable PIE executables.
4923    set nopie [lsearch -exact $options nopie]
4924    if {$nopie != -1} {
4925	if [target_info exists gdb,nopie_flag] {
4926	    set flag "additional_flags=[target_info gdb,nopie_flag]"
4927	} else {
4928	    set flag "additional_flags=-fno-pie"
4929	}
4930	set options [lreplace $options $nopie $nopie $flag]
4931
4932	if [target_info exists gdb,nopie_ldflag] {
4933	    set flag "ldflags=[target_info gdb,nopie_ldflag]"
4934	} else {
4935	    set flag "ldflags=-no-pie"
4936	}
4937	lappend options "$flag"
4938    }
4939
4940  set macros [lsearch -exact $options macros]
4941  if {$macros != -1} {
4942      if { [test_compiler_info "clang-*"] } {
4943	  set flag "additional_flags=-fdebug-macro"
4944      } else {
4945	  set flag "additional_flags=-g3"
4946      }
4947
4948      set options [lreplace $options $macros $macros $flag]
4949  }
4950
4951    if { $type == "executable" } {
4952	if { ([istarget "*-*-mingw*"]
4953	      || [istarget "*-*-*djgpp"]
4954	      || [istarget "*-*-cygwin*"])} {
4955	    # Force output to unbuffered mode, by linking in an object file
4956	    # with a global contructor that calls setvbuf.
4957	    #
4958	    # Compile the special object separately for two reasons:
4959	    #  1) Insulate it from $options.
4960	    #  2) Avoid compiling it for every gdb_compile invocation,
4961	    #  which is time consuming, especially if we're remote
4962	    #  host testing.
4963	    #
4964	    if { $gdb_saved_set_unbuffered_mode_obj == "" } {
4965		verbose "compiling gdb_saved_set_unbuffered_obj"
4966		set unbuf_src ${srcdir}/lib/set_unbuffered_mode.c
4967		set unbuf_obj ${objdir}/set_unbuffered_mode.o
4968
4969		set result [gdb_compile "${unbuf_src}" "${unbuf_obj}" object {nowarnings}]
4970		if { $result != "" } {
4971		    return $result
4972		}
4973		if {[is_remote host]} {
4974		    set gdb_saved_set_unbuffered_mode_obj set_unbuffered_mode_saved.o
4975		} else {
4976		    set gdb_saved_set_unbuffered_mode_obj ${objdir}/set_unbuffered_mode_saved.o
4977		}
4978		# Link a copy of the output object, because the
4979		# original may be automatically deleted.
4980		remote_download host $unbuf_obj $gdb_saved_set_unbuffered_mode_obj
4981	    } else {
4982		verbose "gdb_saved_set_unbuffered_obj already compiled"
4983	    }
4984
4985	    # Rely on the internal knowledge that the global ctors are ran in
4986	    # reverse link order.  In that case, we can use ldflags to
4987	    # avoid copying the object file to the host multiple
4988	    # times.
4989	    # This object can only be added if standard libraries are
4990	    # used. Thus, we need to disable it if -nostdlib option is used
4991	    if {[lsearch -regexp $options "-nostdlib"] < 0 } {
4992		lappend options "ldflags=$gdb_saved_set_unbuffered_mode_obj"
4993	    }
4994	}
4995    }
4996
4997    cond_wrap [expr $pie != -1 || $nopie != -1] \
4998	with_PIE_multilib_flags_filtered {
4999	set result [target_compile $source $dest $type $options]
5000    }
5001
5002    # Prune uninteresting compiler (and linker) output.
5003    regsub "Creating library file: \[^\r\n\]*\[\r\n\]+" $result "" result
5004
5005    regsub "\[\r\n\]*$" "$result" "" result
5006    regsub "^\[\r\n\]*" "$result" "" result
5007
5008    if { $type == "executable" && $result == "" \
5009	     && ($nopie != -1 || $pie != -1) } {
5010	set is_pie [exec_is_pie "$dest"]
5011	if { $nopie != -1 && $is_pie == 1 } {
5012	    set result "nopie failed to prevent PIE executable"
5013	} elseif { $pie != -1 && $is_pie == 0 } {
5014	    set result "pie failed to generate PIE executable"
5015	}
5016    }
5017
5018    if {[lsearch $options quiet] < 0} {
5019	if { $result != "" } {
5020	    clone_output "gdb compile failed, $result"
5021	}
5022    }
5023    return $result
5024}
5025
5026
5027# This is just like gdb_compile, above, except that it tries compiling
5028# against several different thread libraries, to see which one this
5029# system has.
5030proc gdb_compile_pthreads {source dest type options} {
5031    if {$type != "executable"} {
5032	return [gdb_compile $source $dest $type $options]
5033    }
5034    set built_binfile 0
5035    set why_msg "unrecognized error"
5036    foreach lib {-lpthreads -lpthread -lthread ""} {
5037        # This kind of wipes out whatever libs the caller may have
5038        # set.  Or maybe theirs will override ours.  How infelicitous.
5039        set options_with_lib [concat $options [list libs=$lib quiet]]
5040        set ccout [gdb_compile $source $dest $type $options_with_lib]
5041        switch -regexp -- $ccout {
5042            ".*no posix threads support.*" {
5043                set why_msg "missing threads include file"
5044                break
5045            }
5046            ".*cannot open -lpthread.*" {
5047                set why_msg "missing runtime threads library"
5048            }
5049            ".*Can't find library for -lpthread.*" {
5050                set why_msg "missing runtime threads library"
5051            }
5052            {^$} {
5053                pass "successfully compiled posix threads test case"
5054                set built_binfile 1
5055                break
5056            }
5057        }
5058    }
5059    if {!$built_binfile} {
5060	unsupported "couldn't compile [file tail $source]: ${why_msg}"
5061        return -1
5062    }
5063}
5064
5065# Build a shared library from SOURCES.
5066
5067proc gdb_compile_shlib_1 {sources dest options} {
5068    set obj_options $options
5069
5070    set ada 0
5071    if { [lsearch -exact $options "ada"] >= 0 } {
5072	set ada 1
5073    }
5074
5075    if { [lsearch -exact $options "c++"] >= 0 } {
5076	set info_options "c++"
5077    } elseif { [lsearch -exact $options "f90"] >= 0 } {
5078	set info_options "f90"
5079    } else {
5080	set info_options "c"
5081    }
5082
5083    switch -glob [test_compiler_info "" ${info_options}] {
5084        "xlc-*" {
5085            lappend obj_options "additional_flags=-qpic"
5086        }
5087	"clang-*" {
5088	    if { [istarget "*-*-cygwin*"]
5089		 || [istarget "*-*-mingw*"] } {
5090		lappend obj_options "additional_flags=-fPIC"
5091	    } else {
5092		lappend obj_options "additional_flags=-fpic"
5093	    }
5094	}
5095        "gcc-*" {
5096            if { [istarget "powerpc*-*-aix*"]
5097                   || [istarget "rs6000*-*-aix*"]
5098                   || [istarget "*-*-cygwin*"]
5099                   || [istarget "*-*-mingw*"]
5100                   || [istarget "*-*-pe*"] } {
5101                lappend obj_options "additional_flags=-fPIC"
5102	    } else {
5103                lappend obj_options "additional_flags=-fpic"
5104            }
5105        }
5106        "icc-*" {
5107                lappend obj_options "additional_flags=-fpic"
5108        }
5109        default {
5110	    # don't know what the compiler is...
5111	    lappend obj_options "additional_flags=-fPIC"
5112        }
5113    }
5114
5115    set outdir [file dirname $dest]
5116    set objects ""
5117    foreach source $sources {
5118	if {[file extension $source] == ".o"} {
5119	    # Already a .o file.
5120	    lappend objects $source
5121	    continue
5122	}
5123
5124	set sourcebase [file tail $source]
5125
5126	if { $ada } {
5127	    # Gnatmake doesn't like object name foo.adb.o, use foo.o.
5128	    set sourcebase [file rootname $sourcebase]
5129	}
5130	set object ${outdir}/${sourcebase}.o
5131
5132	if { $ada } {
5133	    # Use gdb_compile_ada_1 instead of gdb_compile_ada to avoid the
5134	    # PASS message.
5135	    if {[gdb_compile_ada_1 $source $object object \
5136		     $obj_options] != ""} {
5137		return -1
5138	    }
5139	} else {
5140	    if {[gdb_compile $source $object object \
5141		     $obj_options] != ""} {
5142		return -1
5143	    }
5144	}
5145
5146	lappend objects $object
5147    }
5148
5149    set link_options $options
5150    if { $ada } {
5151	# If we try to use gnatmake for the link, it will interpret the
5152	# object file as an .adb file.  Remove ada from the options to
5153	# avoid it.
5154	set idx [lsearch $link_options "ada"]
5155	set link_options [lreplace $link_options $idx $idx]
5156    }
5157    if [test_compiler_info "xlc-*"] {
5158	lappend link_options "additional_flags=-qmkshrobj"
5159    } else {
5160	lappend link_options "additional_flags=-shared"
5161
5162	if { ([istarget "*-*-mingw*"]
5163	      || [istarget *-*-cygwin*]
5164	      || [istarget *-*-pe*]) } {
5165	    if { [is_remote host] } {
5166		set name [file tail ${dest}]
5167	    } else {
5168		set name ${dest}
5169	    }
5170	    lappend link_options "ldflags=-Wl,--out-implib,${name}.a"
5171	} else {
5172	    # Set the soname of the library.  This causes the linker on ELF
5173	    # systems to create the DT_NEEDED entry in the executable referring
5174	    # to the soname of the library, and not its absolute path.  This
5175	    # (using the absolute path) would be problem when testing on a
5176	    # remote target.
5177	    #
5178	    # In conjunction with setting the soname, we add the special
5179	    # rpath=$ORIGIN value when building the executable, so that it's
5180	    # able to find the library in its own directory.
5181	    set destbase [file tail $dest]
5182	    lappend link_options "ldflags=-Wl,-soname,$destbase"
5183	}
5184    }
5185    if {[gdb_compile "${objects}" "${dest}" executable $link_options] != ""} {
5186	return -1
5187    }
5188    if { [is_remote host]
5189	 && ([istarget "*-*-mingw*"]
5190	     || [istarget *-*-cygwin*]
5191	     || [istarget *-*-pe*]) } {
5192	set dest_tail_name [file tail ${dest}]
5193	remote_upload host $dest_tail_name.a ${dest}.a
5194	remote_file host delete $dest_tail_name.a
5195    }
5196
5197    return ""
5198}
5199
5200# Ignore FLAGS in target board multilib_flags while executing BODY.
5201
5202proc with_multilib_flags_filtered { flags body } {
5203    global board
5204
5205    # Ignore flags in multilib_flags.
5206    set board [target_info name]
5207    set multilib_flags_orig [board_info $board multilib_flags]
5208    set multilib_flags ""
5209    foreach op $multilib_flags_orig {
5210	if { [lsearch -exact $flags $op] == -1 } {
5211	    append multilib_flags " $op"
5212	}
5213    }
5214
5215    save_target_board_info { multilib_flags } {
5216	unset_board_info multilib_flags
5217	set_board_info multilib_flags "$multilib_flags"
5218	set result [uplevel 1 $body]
5219    }
5220
5221    return $result
5222}
5223
5224# Ignore PIE-related flags in target board multilib_flags while executing BODY.
5225
5226proc with_PIE_multilib_flags_filtered { body } {
5227    set pie_flags [list "-pie" "-no-pie" "-fPIE" "-fno-PIE"]
5228    return [uplevel 1 [list with_multilib_flags_filtered $pie_flags $body]]
5229}
5230
5231# Build a shared library from SOURCES.  Ignore target boards PIE-related
5232# multilib_flags.
5233
5234proc gdb_compile_shlib {sources dest options} {
5235    with_PIE_multilib_flags_filtered {
5236	set result [gdb_compile_shlib_1 $sources $dest $options]
5237    }
5238
5239    return $result
5240}
5241
5242# This is just like gdb_compile_shlib, above, except that it tries compiling
5243# against several different thread libraries, to see which one this
5244# system has.
5245proc gdb_compile_shlib_pthreads {sources dest options} {
5246    set built_binfile 0
5247    set why_msg "unrecognized error"
5248    foreach lib {-lpthreads -lpthread -lthread ""} {
5249        # This kind of wipes out whatever libs the caller may have
5250        # set.  Or maybe theirs will override ours.  How infelicitous.
5251        set options_with_lib [concat $options [list libs=$lib quiet]]
5252        set ccout [gdb_compile_shlib $sources $dest $options_with_lib]
5253        switch -regexp -- $ccout {
5254            ".*no posix threads support.*" {
5255                set why_msg "missing threads include file"
5256                break
5257            }
5258            ".*cannot open -lpthread.*" {
5259                set why_msg "missing runtime threads library"
5260            }
5261            ".*Can't find library for -lpthread.*" {
5262                set why_msg "missing runtime threads library"
5263            }
5264            {^$} {
5265                pass "successfully compiled posix threads shlib test case"
5266                set built_binfile 1
5267                break
5268            }
5269        }
5270    }
5271    if {!$built_binfile} {
5272        unsupported "couldn't compile $sources: ${why_msg}"
5273        return -1
5274    }
5275}
5276
5277# This is just like gdb_compile_pthreads, above, except that we always add the
5278# objc library for compiling Objective-C programs
5279proc gdb_compile_objc {source dest type options} {
5280    set built_binfile 0
5281    set why_msg "unrecognized error"
5282    foreach lib {-lobjc -lpthreads -lpthread -lthread solaris} {
5283        # This kind of wipes out whatever libs the caller may have
5284        # set.  Or maybe theirs will override ours.  How infelicitous.
5285        if { $lib == "solaris" } {
5286            set lib "-lpthread -lposix4"
5287	}
5288        if { $lib != "-lobjc" } {
5289	  set lib "-lobjc $lib"
5290	}
5291        set options_with_lib [concat $options [list libs=$lib quiet]]
5292        set ccout [gdb_compile $source $dest $type $options_with_lib]
5293        switch -regexp -- $ccout {
5294            ".*no posix threads support.*" {
5295                set why_msg "missing threads include file"
5296                break
5297            }
5298            ".*cannot open -lpthread.*" {
5299                set why_msg "missing runtime threads library"
5300            }
5301            ".*Can't find library for -lpthread.*" {
5302                set why_msg "missing runtime threads library"
5303            }
5304            {^$} {
5305                pass "successfully compiled objc with posix threads test case"
5306                set built_binfile 1
5307                break
5308            }
5309        }
5310    }
5311    if {!$built_binfile} {
5312        unsupported "couldn't compile [file tail $source]: ${why_msg}"
5313        return -1
5314    }
5315}
5316
5317# Build an OpenMP program from SOURCE.  See prefatory comment for
5318# gdb_compile, above, for discussion of the parameters to this proc.
5319
5320proc gdb_compile_openmp {source dest type options} {
5321    lappend options "additional_flags=-fopenmp"
5322    return [gdb_compile $source $dest $type $options]
5323}
5324
5325# Send a command to GDB.
5326# For options for TYPE see gdb_stdin_log_write
5327
5328proc send_gdb { string {type standard}} {
5329    gdb_stdin_log_write $string $type
5330    return [remote_send host "$string"]
5331}
5332
5333# Send STRING to the inferior's terminal.
5334
5335proc send_inferior { string } {
5336    global inferior_spawn_id
5337
5338    if {[catch "send -i $inferior_spawn_id -- \$string" errorInfo]} {
5339	return "$errorInfo"
5340    } else {
5341	return ""
5342    }
5343}
5344
5345#
5346#
5347
5348proc gdb_expect { args } {
5349    if { [llength $args] == 2  && [lindex $args 0] != "-re" } {
5350	set atimeout [lindex $args 0]
5351	set expcode [list [lindex $args 1]]
5352    } else {
5353	set expcode $args
5354    }
5355
5356    # A timeout argument takes precedence, otherwise of all the timeouts
5357    # select the largest.
5358    if [info exists atimeout] {
5359	set tmt $atimeout
5360    } else {
5361	set tmt [get_largest_timeout]
5362    }
5363
5364    set code [catch \
5365	{uplevel remote_expect host $tmt $expcode} string]
5366
5367    if {$code == 1} {
5368        global errorInfo errorCode
5369
5370	return -code error -errorinfo $errorInfo -errorcode $errorCode $string
5371    } else {
5372	return -code $code $string
5373    }
5374}
5375
5376# gdb_expect_list TEST SENTINEL LIST -- expect a sequence of outputs
5377#
5378# Check for long sequence of output by parts.
5379# TEST: is the test message to be printed with the test success/fail.
5380# SENTINEL: Is the terminal pattern indicating that output has finished.
5381# LIST: is the sequence of outputs to match.
5382# If the sentinel is recognized early, it is considered an error.
5383#
5384# Returns:
5385#    1 if the test failed,
5386#    0 if the test passes,
5387#   -1 if there was an internal error.
5388
5389proc gdb_expect_list {test sentinel list} {
5390    global gdb_prompt
5391    set index 0
5392    set ok 1
5393
5394    while { ${index} < [llength ${list}] } {
5395	set pattern [lindex ${list} ${index}]
5396        set index [expr ${index} + 1]
5397	verbose -log "gdb_expect_list pattern: /$pattern/" 2
5398	if { ${index} == [llength ${list}] } {
5399	    if { ${ok} } {
5400		gdb_expect {
5401		    -re "${pattern}${sentinel}" {
5402			# pass "${test}, pattern ${index} + sentinel"
5403		    }
5404		    -re "${sentinel}" {
5405			fail "${test} (pattern ${index} + sentinel)"
5406			set ok 0
5407		    }
5408		    -re ".*A problem internal to GDB has been detected" {
5409			fail "${test} (GDB internal error)"
5410			set ok 0
5411			gdb_internal_error_resync
5412		    }
5413		    timeout {
5414			fail "${test} (pattern ${index} + sentinel) (timeout)"
5415			set ok 0
5416		    }
5417		}
5418	    } else {
5419		# unresolved "${test}, pattern ${index} + sentinel"
5420	    }
5421	} else {
5422	    if { ${ok} } {
5423		gdb_expect {
5424		    -re "${pattern}" {
5425			# pass "${test}, pattern ${index}"
5426		    }
5427		    -re "${sentinel}" {
5428			fail "${test} (pattern ${index})"
5429			set ok 0
5430		    }
5431		    -re ".*A problem internal to GDB has been detected" {
5432			fail "${test} (GDB internal error)"
5433			set ok 0
5434			gdb_internal_error_resync
5435		    }
5436		    timeout {
5437			fail "${test} (pattern ${index}) (timeout)"
5438			set ok 0
5439		    }
5440		}
5441	    } else {
5442		# unresolved "${test}, pattern ${index}"
5443	    }
5444	}
5445    }
5446    if { ${ok} } {
5447	pass "${test}"
5448	return 0
5449    } else {
5450	return 1
5451    }
5452}
5453
5454# Spawn the gdb process.
5455#
5456# This doesn't expect any output or do any other initialization,
5457# leaving those to the caller.
5458#
5459# Overridable function -- you can override this function in your
5460# baseboard file.
5461
5462proc gdb_spawn { } {
5463    default_gdb_spawn
5464}
5465
5466# Spawn GDB with CMDLINE_FLAGS appended to the GDBFLAGS global.
5467
5468proc gdb_spawn_with_cmdline_opts { cmdline_flags } {
5469    global GDBFLAGS
5470
5471    set saved_gdbflags $GDBFLAGS
5472
5473    if {$GDBFLAGS != ""} {
5474	append GDBFLAGS " "
5475    }
5476    append GDBFLAGS $cmdline_flags
5477
5478    set res [gdb_spawn]
5479
5480    set GDBFLAGS $saved_gdbflags
5481
5482    return $res
5483}
5484
5485# Start gdb running, wait for prompt, and disable the pagers.
5486
5487# Overridable function -- you can override this function in your
5488# baseboard file.
5489
5490proc gdb_start { } {
5491    default_gdb_start
5492}
5493
5494proc gdb_exit { } {
5495    catch default_gdb_exit
5496}
5497
5498# Return true if we can spawn a program on the target and attach to
5499# it.
5500
5501proc can_spawn_for_attach { } {
5502    # We use exp_pid to get the inferior's pid, assuming that gives
5503    # back the pid of the program.  On remote boards, that would give
5504    # us instead the PID of e.g., the ssh client, etc.
5505    if {[is_remote target]} {
5506	verbose -log "can't spawn for attach (target is remote)"
5507	return 0
5508    }
5509
5510    # The "attach" command doesn't make sense when the target is
5511    # stub-like, where GDB finds the program already started on
5512    # initial connection.
5513    if {[target_info exists use_gdb_stub]} {
5514	verbose -log "can't spawn for attach (target is stub)"
5515	return 0
5516    }
5517
5518    # Assume yes.
5519    return 1
5520}
5521
5522# Centralize the failure checking of "attach" command.
5523# Return 0 if attach failed, otherwise return 1.
5524
5525proc gdb_attach { testpid args } {
5526    parse_args {
5527	{pattern ""}
5528    }
5529
5530    if { [llength $args] != 0 } {
5531	error "Unexpected arguments: $args"
5532    }
5533
5534    gdb_test_multiple "attach $testpid" "attach" {
5535	-re -wrap "Attaching to.*ptrace: Operation not permitted\\." {
5536	    unsupported "$gdb_test_name (Operation not permitted)"
5537	    return 0
5538	}
5539	-re -wrap "$pattern" {
5540	    pass $gdb_test_name
5541	    return 1
5542	}
5543    }
5544
5545    return 0
5546}
5547
5548# Start gdb with "--pid $TESTPID" on the command line and wait for the prompt.
5549# Return 1 if GDB managed to start and attach to the process, 0 otherwise.
5550
5551proc_with_prefix gdb_spawn_attach_cmdline { testpid } {
5552    if ![can_spawn_for_attach] {
5553	# The caller should have checked can_spawn_for_attach itself
5554	# before getting here.
5555	error "can't spawn for attach with this target/board"
5556    }
5557
5558    set test "start gdb with --pid"
5559    set res [gdb_spawn_with_cmdline_opts "-quiet --pid=$testpid"]
5560    if { $res != 0 } {
5561	fail $test
5562	return 0
5563    }
5564
5565    gdb_test_multiple "" "$test" {
5566	-re -wrap "ptrace: Operation not permitted\\." {
5567	    unsupported "$gdb_test_name (operation not permitted)"
5568	    return 0
5569	}
5570	-re -wrap "ptrace: No such process\\." {
5571	    fail "$gdb_test_name (no such process)"
5572	    return 0
5573	}
5574	-re -wrap "Attaching to process $testpid\r\n.*" {
5575	    pass $gdb_test_name
5576	}
5577    }
5578
5579    # Check that we actually attached to a process, in case the
5580    # error message is not caught by the patterns above.
5581    gdb_test_multiple "info thread" "" {
5582	-re -wrap "No threads\\." {
5583	    fail "$gdb_test_name (no thread)"
5584	}
5585	-re -wrap "Id.*" {
5586	    pass $gdb_test_name
5587	    return 1
5588	}
5589    }
5590
5591    return 0
5592}
5593
5594# Kill a progress previously started with spawn_wait_for_attach, and
5595# reap its wait status.  PROC_SPAWN_ID is the spawn id associated with
5596# the process.
5597
5598proc kill_wait_spawned_process { proc_spawn_id } {
5599    set pid [exp_pid -i $proc_spawn_id]
5600
5601    verbose -log "killing ${pid}"
5602    remote_exec build "kill -9 ${pid}"
5603
5604    verbose -log "closing ${proc_spawn_id}"
5605    catch "close -i $proc_spawn_id"
5606    verbose -log "waiting for ${proc_spawn_id}"
5607
5608    # If somehow GDB ends up still attached to the process here, a
5609    # blocking wait hangs until gdb is killed (or until gdb / the
5610    # ptracer reaps the exit status too, but that won't happen because
5611    # something went wrong.)  Passing -nowait makes expect tell Tcl to
5612    # wait for the PID in the background.  That's fine because we
5613    # don't care about the exit status.  */
5614    wait -nowait -i $proc_spawn_id
5615}
5616
5617# Returns the process id corresponding to the given spawn id.
5618
5619proc spawn_id_get_pid { spawn_id } {
5620    set testpid [exp_pid -i $spawn_id]
5621
5622    if { [istarget "*-*-cygwin*"] } {
5623	# testpid is the Cygwin PID, GDB uses the Windows PID, which
5624	# might be different due to the way fork/exec works.
5625	set testpid [ exec ps -e | gawk "{ if (\$1 == $testpid) print \$4; }" ]
5626    }
5627
5628    return $testpid
5629}
5630
5631# Start a set of programs running and then wait for a bit, to be sure
5632# that they can be attached to.  Return a list of processes spawn IDs,
5633# one element for each process spawned.  It's a test error to call
5634# this when [can_spawn_for_attach] is false.
5635
5636proc spawn_wait_for_attach { executable_list } {
5637    set spawn_id_list {}
5638
5639    if ![can_spawn_for_attach] {
5640	# The caller should have checked can_spawn_for_attach itself
5641	# before getting here.
5642	error "can't spawn for attach with this target/board"
5643    }
5644
5645    foreach {executable} $executable_list {
5646	# Note we use Expect's spawn, not Tcl's exec, because with
5647	# spawn we control when to wait for/reap the process.  That
5648	# allows killing the process by PID without being subject to
5649	# pid-reuse races.
5650	lappend spawn_id_list [remote_spawn target $executable]
5651    }
5652
5653    sleep 2
5654
5655    return $spawn_id_list
5656}
5657
5658#
5659# gdb_load_cmd -- load a file into the debugger.
5660#		  ARGS - additional args to load command.
5661#                 return a -1 if anything goes wrong.
5662#
5663proc gdb_load_cmd { args } {
5664    global gdb_prompt
5665
5666    if [target_info exists gdb_load_timeout] {
5667	set loadtimeout [target_info gdb_load_timeout]
5668    } else {
5669	set loadtimeout 1600
5670    }
5671    send_gdb "load $args\n"
5672    verbose "Timeout is now $loadtimeout seconds" 2
5673    gdb_expect $loadtimeout {
5674	-re "Loading section\[^\r\]*\r\n" {
5675	    exp_continue
5676	}
5677	-re "Start address\[\r\]*\r\n" {
5678	    exp_continue
5679	}
5680	-re "Transfer rate\[\r\]*\r\n" {
5681	    exp_continue
5682	}
5683	-re "Memory access error\[^\r\]*\r\n" {
5684	    perror "Failed to load program"
5685	    return -1
5686	}
5687	-re "$gdb_prompt $" {
5688	    return 0
5689	}
5690	-re "(.*)\r\n$gdb_prompt " {
5691	    perror "Unexpected reponse from 'load' -- $expect_out(1,string)"
5692	    return -1
5693	}
5694	timeout {
5695	    perror "Timed out trying to load $args."
5696	    return -1
5697	}
5698    }
5699    return -1
5700}
5701
5702# Invoke "gcore".  CORE is the name of the core file to write.  TEST
5703# is the name of the test case.  This will return 1 if the core file
5704# was created, 0 otherwise.  If this fails to make a core file because
5705# this configuration of gdb does not support making core files, it
5706# will call "unsupported", not "fail".  However, if this fails to make
5707# a core file for some other reason, then it will call "fail".
5708
5709proc gdb_gcore_cmd {core test} {
5710    global gdb_prompt
5711
5712    set result 0
5713
5714    set re_unsupported \
5715	"(?:Can't create a corefile|Target does not support core file generation\\.)"
5716
5717    with_timeout_factor 3 {
5718	gdb_test_multiple "gcore $core" $test {
5719	    -re -wrap "Saved corefile .*" {
5720		pass $test
5721		set result 1
5722	    }
5723	    -re -wrap $re_unsupported {
5724		unsupported $test
5725	    }
5726	}
5727    }
5728
5729    return $result
5730}
5731
5732# Load core file CORE.  TEST is the name of the test case.
5733# This will record a pass/fail for loading the core file.
5734# Returns:
5735#  1 - core file is successfully loaded
5736#  0 - core file loaded but has a non fatal error
5737# -1 - core file failed to load
5738
5739proc gdb_core_cmd { core test } {
5740    global gdb_prompt
5741
5742    gdb_test_multiple "core $core" "$test" {
5743	-re "\\\[Thread debugging using \[^ \r\n\]* enabled\\\]\r\n" {
5744	    exp_continue
5745	}
5746	-re " is not a core dump:.*\r\n$gdb_prompt $" {
5747	    fail "$test (bad file format)"
5748	    return -1
5749	}
5750	-re -wrap "[string_to_regexp $core]: No such file or directory.*" {
5751	    fail "$test (file not found)"
5752	    return -1
5753	}
5754	-re "Couldn't find .* registers in core file.*\r\n$gdb_prompt $" {
5755	    fail "$test (incomplete note section)"
5756	    return 0
5757	}
5758	-re "Core was generated by .*\r\n$gdb_prompt $" {
5759	    pass "$test"
5760	    return 1
5761	}
5762	-re ".*$gdb_prompt $" {
5763	    fail "$test"
5764	    return -1
5765	}
5766	timeout {
5767	    fail "$test (timeout)"
5768	    return -1
5769	}
5770    }
5771    fail "unsupported output from 'core' command"
5772    return -1
5773}
5774
5775# Return the filename to download to the target and load on the target
5776# for this shared library.  Normally just LIBNAME, unless shared libraries
5777# for this target have separate link and load images.
5778
5779proc shlib_target_file { libname } {
5780    return $libname
5781}
5782
5783# Return the filename GDB will load symbols from when debugging this
5784# shared library.  Normally just LIBNAME, unless shared libraries for
5785# this target have separate link and load images.
5786
5787proc shlib_symbol_file { libname } {
5788    return $libname
5789}
5790
5791# Return the filename to download to the target and load for this
5792# executable.  Normally just BINFILE unless it is renamed to something
5793# else for this target.
5794
5795proc exec_target_file { binfile } {
5796    return $binfile
5797}
5798
5799# Return the filename GDB will load symbols from when debugging this
5800# executable.  Normally just BINFILE unless executables for this target
5801# have separate files for symbols.
5802
5803proc exec_symbol_file { binfile } {
5804    return $binfile
5805}
5806
5807# Rename the executable file.  Normally this is just BINFILE1 being renamed
5808# to BINFILE2, but some targets require multiple binary files.
5809proc gdb_rename_execfile { binfile1 binfile2 } {
5810    file rename -force [exec_target_file ${binfile1}] \
5811		       [exec_target_file ${binfile2}]
5812    if { [exec_target_file ${binfile1}] != [exec_symbol_file ${binfile1}] } {
5813	file rename -force [exec_symbol_file ${binfile1}] \
5814			   [exec_symbol_file ${binfile2}]
5815    }
5816}
5817
5818# "Touch" the executable file to update the date.  Normally this is just
5819# BINFILE, but some targets require multiple files.
5820proc gdb_touch_execfile { binfile } {
5821    set time [clock seconds]
5822    file mtime [exec_target_file ${binfile}] $time
5823    if { [exec_target_file ${binfile}] != [exec_symbol_file ${binfile}] } {
5824	file mtime [exec_symbol_file ${binfile}] $time
5825    }
5826}
5827
5828# Like remote_download but provides a gdb-specific behavior.
5829#
5830# If the destination board is remote, the local file FROMFILE is transferred as
5831# usual with remote_download to TOFILE on the remote board.  The destination
5832# filename is added to the CLEANFILES global, so it can be cleaned up at the
5833# end of the test.
5834#
5835# If the destination board is local, the destination path TOFILE is passed
5836# through standard_output_file, and FROMFILE is copied there.
5837#
5838# In both cases, if TOFILE is omitted, it defaults to the [file tail] of
5839# FROMFILE.
5840
5841proc gdb_remote_download {dest fromfile {tofile {}}} {
5842    # If TOFILE is not given, default to the same filename as FROMFILE.
5843    if {[string length $tofile] == 0} {
5844	set tofile [file tail $fromfile]
5845    }
5846
5847    if {[is_remote $dest]} {
5848	# When the DEST is remote, we simply send the file to DEST.
5849	global cleanfiles_target cleanfiles_host
5850
5851	set destname [remote_download $dest $fromfile $tofile]
5852	if { $dest == "target" } {
5853	    lappend cleanfiles_target $destname
5854	} elseif { $dest == "host" } {
5855	    lappend cleanfiles_host $destname
5856	}
5857
5858	return $destname
5859    } else {
5860	# When the DEST is local, we copy the file to the test directory (where
5861	# the executable is).
5862	#
5863	# Note that we pass TOFILE through standard_output_file, regardless of
5864	# whether it is absolute or relative, because we don't want the tests
5865	# to be able to write outside their standard output directory.
5866
5867	set tofile [standard_output_file $tofile]
5868
5869	file copy -force $fromfile $tofile
5870
5871	return $tofile
5872    }
5873}
5874
5875# Copy shlib FILE to the target.
5876
5877proc gdb_download_shlib { file } {
5878    return [gdb_remote_download target [shlib_target_file $file]]
5879}
5880
5881# Set solib-search-path to allow gdb to locate shlib FILE.
5882
5883proc gdb_locate_shlib { file } {
5884    global gdb_spawn_id
5885
5886    if ![info exists gdb_spawn_id] {
5887	perror "gdb_load_shlib: GDB is not running"
5888    }
5889
5890    # If the target is remote, we need to tell gdb where to find the
5891    # libraries.
5892    if { ![is_remote target] } {
5893	return
5894    }
5895
5896    # We could set this even when not testing remotely, but a user
5897    # generally won't set it unless necessary.  In order to make the tests
5898    # more like the real-life scenarios, we don't set it for local testing.
5899    gdb_test "set solib-search-path [file dirname $file]" "" \
5900	"set solib-search-path for [file tail $file]"
5901}
5902
5903# Copy shlib FILE to the target and set solib-search-path to allow gdb to
5904# locate it.
5905
5906proc gdb_load_shlib { file } {
5907    set dest [gdb_download_shlib $file]
5908    gdb_locate_shlib $file
5909    return $dest
5910}
5911
5912#
5913# gdb_load -- load a file into the debugger.  Specifying no file
5914# defaults to the executable currently being debugged.
5915# The return value is 0 for success, -1 for failure.
5916# Many files in config/*.exp override this procedure.
5917#
5918proc gdb_load { arg } {
5919    if { $arg != "" } {
5920	return [gdb_file_cmd $arg]
5921    }
5922    return 0
5923}
5924
5925#
5926# with_set -- Execute BODY and set VAR temporary to VAL for the
5927# duration.
5928#
5929proc with_set { var val body } {
5930    set save ""
5931    set show_re \
5932	"is (\[^\r\n\]+)\\."
5933    gdb_test_multiple "show $var" "" {
5934	-re -wrap $show_re {
5935	    set save $expect_out(1,string)
5936	}
5937    }
5938
5939    # Handle 'set to "auto" (currently "i386")'.
5940    set save [regsub {^set to} $save ""]
5941    set save [regsub {\([^\r\n]+\)$} $save ""]
5942    set save [string trim $save]
5943    set save [regsub -all {^"|"$} $save ""]
5944
5945    if { $save == "" } {
5946	perror "Did not manage to set $var"
5947    } else {
5948	# Set var.
5949	set cmd "set $var $val"
5950	gdb_test_multiple $cmd "" {
5951	    -re -wrap "^$cmd" {
5952	    }
5953	    -re -wrap " is set to \"?$val\"?\\." {
5954	    }
5955	}
5956    }
5957
5958    set code [catch {uplevel 1 $body} result]
5959
5960    # Restore saved setting.
5961    if { $save != "" } {
5962	set cmd "set $var $save"
5963	gdb_test_multiple $cmd "" {
5964	    -re -wrap "^$cmd" {
5965	    }
5966	    -re -wrap "is set to \"?$save\"?( \\(\[^)\]*\\))?\\." {
5967	    }
5968	}
5969    }
5970
5971    if {$code == 1} {
5972	global errorInfo errorCode
5973	return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
5974    } else {
5975	return -code $code $result
5976    }
5977}
5978
5979#
5980# with_complaints -- Execute BODY and set complaints temporary to N for the
5981# duration.
5982#
5983proc with_complaints { n body } {
5984    return [uplevel [list with_set complaints $n $body]]
5985}
5986
5987#
5988# gdb_load_no_complaints -- As gdb_load, but in addition verifies that
5989# loading caused no symbol reading complaints.
5990#
5991proc gdb_load_no_complaints { arg } {
5992    global gdb_prompt gdb_file_cmd_msg decimal
5993
5994    # Temporarily set complaint to a small non-zero number.
5995    with_complaints 5 {
5996	gdb_load $arg
5997    }
5998
5999    # Verify that there were no complaints.
6000    set re \
6001	[multi_line \
6002	     "^(Reading symbols from \[^\r\n\]*" \
6003	     ")+(Expanding full symbols from \[^\r\n\]*" \
6004	     ")?$gdb_prompt $"]
6005    gdb_assert {[regexp $re $gdb_file_cmd_msg]} "No complaints"
6006}
6007
6008# gdb_reload -- load a file into the target.  Called before "running",
6009# either the first time or after already starting the program once,
6010# for remote targets.  Most files that override gdb_load should now
6011# override this instead.
6012#
6013# INFERIOR_ARGS contains the arguments to pass to the inferiors, as a
6014# single string to get interpreted by a shell.  If the target board
6015# overriding gdb_reload is a "stub", then it should arrange things such
6016# these arguments make their way to the inferior process.
6017
6018proc gdb_reload { {inferior_args {}} } {
6019    # For the benefit of existing configurations, default to gdb_load.
6020    # Specifying no file defaults to the executable currently being
6021    # debugged.
6022    return [gdb_load ""]
6023}
6024
6025proc gdb_continue { function } {
6026    global decimal
6027
6028    return [gdb_test "continue" ".*Breakpoint $decimal, $function .*" "continue to $function"]
6029}
6030
6031# Default implementation of gdb_init.
6032proc default_gdb_init { test_file_name } {
6033    global gdb_wrapper_initialized
6034    global gdb_wrapper_target
6035    global gdb_test_file_name
6036    global cleanfiles_target
6037    global cleanfiles_host
6038    global pf_prefix
6039
6040    # Reset the timeout value to the default.  This way, any testcase
6041    # that changes the timeout value without resetting it cannot affect
6042    # the timeout used in subsequent testcases.
6043    global gdb_test_timeout
6044    global timeout
6045    set timeout $gdb_test_timeout
6046
6047    if { [regexp ".*gdb\.reverse\/.*" $test_file_name]
6048	 && [target_info exists gdb_reverse_timeout] } {
6049	set timeout [target_info gdb_reverse_timeout]
6050    }
6051
6052    # If GDB_INOTIFY is given, check for writes to '.'.  This is a
6053    # debugging tool to help confirm that the test suite is
6054    # parallel-safe.  You need "inotifywait" from the
6055    # inotify-tools package to use this.
6056    global GDB_INOTIFY inotify_pid
6057    if {[info exists GDB_INOTIFY] && ![info exists inotify_pid]} {
6058	global outdir tool inotify_log_file
6059
6060	set exclusions {outputs temp gdb[.](log|sum) cache}
6061	set exclusion_re ([join $exclusions |])
6062
6063	set inotify_log_file [standard_temp_file inotify.out]
6064	set inotify_pid [exec inotifywait -r -m -e move,create,delete . \
6065			     --exclude $exclusion_re \
6066			     |& tee -a $outdir/$tool.log $inotify_log_file &]
6067
6068	# Wait for the watches; hopefully this is long enough.
6069	sleep 2
6070
6071	# Clear the log so that we don't emit a warning the first time
6072	# we check it.
6073	set fd [open $inotify_log_file w]
6074	close $fd
6075    }
6076
6077    # Block writes to all banned variables, and invocation of all
6078    # banned procedures...
6079    global banned_variables
6080    global banned_procedures
6081    global banned_traced
6082    if (!$banned_traced) {
6083	foreach banned_var $banned_variables {
6084            global "$banned_var"
6085            trace add variable "$banned_var" write error
6086	}
6087	foreach banned_proc $banned_procedures {
6088	    global "$banned_proc"
6089	    trace add execution "$banned_proc" enter error
6090	}
6091	set banned_traced 1
6092    }
6093
6094    # We set LC_ALL, LC_CTYPE, and LANG to C so that we get the same
6095    # messages as expected.
6096    setenv LC_ALL C
6097    setenv LC_CTYPE C
6098    setenv LANG C
6099
6100    # Don't let a .inputrc file or an existing setting of INPUTRC mess
6101    # up the test results.  Certain tests (style tests and TUI tests)
6102    # want to set the terminal to a non-"dumb" value, and for those we
6103    # want to disable bracketed paste mode.  Versions of Readline
6104    # before 8.0 will not understand this and will issue a warning.
6105    # We tried using a $if to guard it, but Readline 8.1 had a bug in
6106    # its version-comparison code that prevented this for working.
6107    setenv INPUTRC [cached_file inputrc "set enable-bracketed-paste off"]
6108
6109    # This disables style output, which would interfere with many
6110    # tests.
6111    setenv TERM "dumb"
6112
6113    # If DEBUGINFOD_URLS is set, gdb will try to download sources and
6114    # debug info for f.i. system libraries.  Prevent this.
6115    unset -nocomplain ::env(DEBUGINFOD_URLS)
6116
6117    # Ensure that GDBHISTFILE and GDBHISTSIZE are removed from the
6118    # environment, we don't want these modifications to the history
6119    # settings.
6120    unset -nocomplain ::env(GDBHISTFILE)
6121    unset -nocomplain ::env(GDBHISTSIZE)
6122
6123    # Ensure that XDG_CONFIG_HOME is not set.  Some tests setup a fake
6124    # home directory in order to test loading settings from gdbinit.
6125    # If XDG_CONFIG_HOME is set then GDB will load a gdbinit from
6126    # there (if one is present) rather than the home directory setup
6127    # in the test.
6128    unset -nocomplain ::env(XDG_CONFIG_HOME)
6129
6130    # Initialize GDB's pty with a fixed size, to make sure we avoid pagination
6131    # during startup.  See "man expect" for details about stty_init.
6132    global stty_init
6133    set stty_init "rows 25 cols 80"
6134
6135    # Some tests (for example gdb.base/maint.exp) shell out from gdb to use
6136    # grep.  Clear GREP_OPTIONS to make the behavior predictable,
6137    # especially having color output turned on can cause tests to fail.
6138    setenv GREP_OPTIONS ""
6139
6140    # Clear $gdbserver_reconnect_p.
6141    global gdbserver_reconnect_p
6142    set gdbserver_reconnect_p 1
6143    unset gdbserver_reconnect_p
6144
6145    # Clear $last_loaded_file
6146    global last_loaded_file
6147    unset -nocomplain last_loaded_file
6148
6149    # Reset GDB number of instances
6150    global gdb_instances
6151    set gdb_instances 0
6152
6153    set cleanfiles_target {}
6154    set cleanfiles_host {}
6155
6156    set gdb_test_file_name [file rootname [file tail $test_file_name]]
6157
6158    # Make sure that the wrapper is rebuilt
6159    # with the appropriate multilib option.
6160    if { $gdb_wrapper_target != [current_target_name] } {
6161	set gdb_wrapper_initialized 0
6162    }
6163
6164    # Unlike most tests, we have a small number of tests that generate
6165    # a very large amount of output.  We therefore increase the expect
6166    # buffer size to be able to contain the entire test output.  This
6167    # is especially needed by gdb.base/info-macros.exp.
6168    match_max -d 65536
6169    # Also set this value for the currently running GDB.
6170    match_max [match_max -d]
6171
6172    # We want to add the name of the TCL testcase to the PASS/FAIL messages.
6173    set pf_prefix "[file tail [file dirname $test_file_name]]/[file tail $test_file_name]:"
6174
6175    global gdb_prompt
6176    if [target_info exists gdb_prompt] {
6177	set gdb_prompt [target_info gdb_prompt]
6178    } else {
6179	set gdb_prompt "\\(gdb\\)"
6180    }
6181    global use_gdb_stub
6182    if [info exists use_gdb_stub] {
6183	unset use_gdb_stub
6184    }
6185
6186    gdb_setup_known_globals
6187
6188    if { [info procs ::gdb_tcl_unknown] != "" } {
6189	# Dejagnu overrides proc unknown.  The dejagnu version may trigger in a
6190	# test-case but abort the entire test run.  To fix this, we install a
6191	# local version here, which reverts dejagnu's override, and restore
6192	# dejagnu's version in gdb_finish.
6193	rename ::unknown ::dejagnu_unknown
6194	proc unknown { args } {
6195	    # Use tcl's unknown.
6196	    set cmd [lindex $args 0]
6197	    unresolved "testcase aborted due to invalid command name: $cmd"
6198	    return [uplevel 1 ::gdb_tcl_unknown $args]
6199	}
6200    }
6201}
6202
6203# Return a path using GDB_PARALLEL.
6204# ARGS is a list of path elements to append to "$objdir/$GDB_PARALLEL".
6205# GDB_PARALLEL must be defined, the caller must check.
6206#
6207# The default value for GDB_PARALLEL is, canonically, ".".
6208# The catch is that tests don't expect an additional "./" in file paths so
6209# omit any directory for the default case.
6210# GDB_PARALLEL is written as "yes" for the default case in Makefile.in to mark
6211# its special handling.
6212
6213proc make_gdb_parallel_path { args } {
6214    global GDB_PARALLEL objdir
6215    set joiner [list "file" "join" $objdir]
6216    if { [info exists GDB_PARALLEL] && $GDB_PARALLEL != "yes" } {
6217	lappend joiner $GDB_PARALLEL
6218    }
6219    set joiner [concat $joiner $args]
6220    return [eval $joiner]
6221}
6222
6223# Turn BASENAME into a full file name in the standard output
6224# directory.  It is ok if BASENAME is the empty string; in this case
6225# the directory is returned.
6226
6227proc standard_output_file {basename} {
6228    global objdir subdir gdb_test_file_name
6229
6230    set dir [make_gdb_parallel_path outputs $subdir $gdb_test_file_name]
6231    file mkdir $dir
6232    # If running on MinGW, replace /c/foo with c:/foo
6233    if { [ishost *-*-mingw*] } {
6234        set dir [exec sh -c "cd ${dir} && pwd -W"]
6235    }
6236    return [file join $dir $basename]
6237}
6238
6239# Turn BASENAME into a full file name in the standard output directory.  If
6240# GDB has been launched more than once then append the count, starting with
6241# a ".1" postfix.
6242
6243proc standard_output_file_with_gdb_instance {basename} {
6244    global gdb_instances
6245    set count $gdb_instances
6246
6247    if {$count == 0} {
6248      return [standard_output_file $basename]
6249    }
6250    return [standard_output_file ${basename}.${count}]
6251}
6252
6253# Return the name of a file in our standard temporary directory.
6254
6255proc standard_temp_file {basename} {
6256    # Since a particular runtest invocation is only executing a single test
6257    # file at any given time, we can use the runtest pid to build the
6258    # path of the temp directory.
6259    set dir [make_gdb_parallel_path temp [pid]]
6260    file mkdir $dir
6261    return [file join $dir $basename]
6262}
6263
6264# Rename file A to file B, if B does not already exists.  Otherwise, leave B
6265# as is and delete A.  Return 1 if rename happened.
6266
6267proc tentative_rename { a b } {
6268    global errorInfo errorCode
6269    set code [catch {file rename -- $a $b} result]
6270    if { $code == 1 && [lindex $errorCode 0] == "POSIX" \
6271	     && [lindex $errorCode 1] == "EEXIST" } {
6272	file delete $a
6273	return 0
6274    }
6275    if {$code == 1} {
6276	return -code error -errorinfo $errorInfo -errorcode $errorCode $result
6277    } elseif {$code > 1} {
6278	return -code $code $result
6279    }
6280    return 1
6281}
6282
6283# Create a file with name FILENAME and contents TXT in the cache directory.
6284# If EXECUTABLE, mark the new file for execution.
6285
6286proc cached_file { filename txt {executable 0}} {
6287    set filename [make_gdb_parallel_path cache $filename]
6288
6289    if { [file exists $filename] } {
6290	return $filename
6291    }
6292
6293    set dir [file dirname $filename]
6294    file mkdir $dir
6295
6296    set tmp_filename $filename.[pid]
6297    set fd [open $tmp_filename w]
6298    puts $fd $txt
6299    close $fd
6300
6301    if { $executable } {
6302	exec chmod +x $tmp_filename
6303    }
6304    tentative_rename $tmp_filename $filename
6305
6306    return $filename
6307}
6308
6309# Return a wrapper around gdb that prevents generating a core file.
6310
6311proc gdb_no_core { } {
6312    set script \
6313	[list \
6314	     "ulimit -c 0" \
6315	     [join [list exec $::GDB {"$@"}]]]
6316    set script [join $script "\n"]
6317    return [cached_file gdb-no-core.sh $script 1]
6318}
6319
6320# Set 'testfile', 'srcfile', and 'binfile'.
6321#
6322# ARGS is a list of source file specifications.
6323# Without any arguments, the .exp file's base name is used to
6324# compute the source file name.  The ".c" extension is added in this case.
6325# If ARGS is not empty, each entry is a source file specification.
6326# If the specification starts with a "." or "-", it is treated as a suffix
6327# to append to the .exp file's base name.
6328# If the specification is the empty string, it is treated as if it
6329# were ".c".
6330# Otherwise it is a file name.
6331# The first file in the list is used to set the 'srcfile' global.
6332# Each subsequent name is used to set 'srcfile2', 'srcfile3', etc.
6333#
6334# Most tests should call this without arguments.
6335#
6336# If a completely different binary file name is needed, then it
6337# should be handled in the .exp file with a suitable comment.
6338
6339proc standard_testfile {args} {
6340    global gdb_test_file_name
6341    global subdir
6342    global gdb_test_file_last_vars
6343
6344    # Outputs.
6345    global testfile binfile
6346
6347    set testfile $gdb_test_file_name
6348    set binfile [standard_output_file ${testfile}]
6349
6350    if {[llength $args] == 0} {
6351	set args .c
6352    }
6353
6354    # Unset our previous output variables.
6355    # This can help catch hidden bugs.
6356    if {[info exists gdb_test_file_last_vars]} {
6357	foreach varname $gdb_test_file_last_vars {
6358	    global $varname
6359	    catch {unset $varname}
6360	}
6361    }
6362    # 'executable' is often set by tests.
6363    set gdb_test_file_last_vars {executable}
6364
6365    set suffix ""
6366    foreach arg $args {
6367	set varname srcfile$suffix
6368	global $varname
6369
6370	# Handle an extension.
6371	if {$arg == ""} {
6372	    set arg $testfile.c
6373	} else {
6374	    set first [string range $arg 0 0]
6375	    if { $first == "." || $first == "-" } {
6376		set arg $testfile$arg
6377	    }
6378	}
6379
6380	set $varname $arg
6381	lappend gdb_test_file_last_vars $varname
6382
6383	if {$suffix == ""} {
6384	    set suffix 2
6385	} else {
6386	    incr suffix
6387	}
6388    }
6389}
6390
6391# The default timeout used when testing GDB commands.  We want to use
6392# the same timeout as the default dejagnu timeout, unless the user has
6393# already provided a specific value (probably through a site.exp file).
6394global gdb_test_timeout
6395if ![info exists gdb_test_timeout] {
6396    set gdb_test_timeout $timeout
6397}
6398
6399# A list of global variables that GDB testcases should not use.
6400# We try to prevent their use by monitoring write accesses and raising
6401# an error when that happens.
6402set banned_variables { bug_id prms_id }
6403
6404# A list of procedures that GDB testcases should not use.
6405# We try to prevent their use by monitoring invocations and raising
6406# an error when that happens.
6407set banned_procedures { strace }
6408
6409# gdb_init is called by runtest at start, but also by several
6410# tests directly; gdb_finish is only called from within runtest after
6411# each test source execution.
6412# Placing several traces by repetitive calls to gdb_init leads
6413# to problems, as only one trace is removed in gdb_finish.
6414# To overcome this possible problem, we add a variable that records
6415# if the banned variables and procedures are already traced.
6416set banned_traced 0
6417
6418# Global array that holds the name of all global variables at the time
6419# a test script is started.  After the test script has completed any
6420# global not in this list is deleted.
6421array set gdb_known_globals {}
6422
6423# Setup the GDB_KNOWN_GLOBALS array with the names of all current
6424# global variables.
6425proc gdb_setup_known_globals {} {
6426    global gdb_known_globals
6427
6428    array set gdb_known_globals {}
6429    foreach varname [info globals] {
6430	set gdb_known_globals($varname) 1
6431    }
6432}
6433
6434# Cleanup the global namespace.  Any global not in the
6435# GDB_KNOWN_GLOBALS array is unset, this ensures we don't "leak"
6436# globals from one test script to another.
6437proc gdb_cleanup_globals {} {
6438    global gdb_known_globals gdb_persistent_globals
6439
6440    foreach varname [info globals] {
6441	if {![info exists gdb_known_globals($varname)]} {
6442	    if { [info exists gdb_persistent_globals($varname)] } {
6443		continue
6444	    }
6445	    uplevel #0 unset $varname
6446	}
6447    }
6448}
6449
6450# Create gdb_tcl_unknown, a copy tcl's ::unknown, provided it's present as a
6451# proc.
6452set temp [interp create]
6453if { [interp eval $temp "info procs ::unknown"] != "" } {
6454    set old_args [interp eval $temp "info args ::unknown"]
6455    set old_body [interp eval $temp "info body ::unknown"]
6456    eval proc gdb_tcl_unknown {$old_args} {$old_body}
6457}
6458interp delete $temp
6459unset temp
6460
6461# GDB implementation of ${tool}_init.  Called right before executing the
6462# test-case.
6463# Overridable function -- you can override this function in your
6464# baseboard file.
6465proc gdb_init { args } {
6466    # A baseboard file overriding this proc and calling the default version
6467    # should behave the same as this proc.  So, don't add code here, but to
6468    # the default version instead.
6469    return [default_gdb_init {*}$args]
6470}
6471
6472# GDB implementation of ${tool}_finish.  Called right after executing the
6473# test-case.
6474proc gdb_finish { } {
6475    global gdbserver_reconnect_p
6476    global gdb_prompt
6477    global cleanfiles_target
6478    global cleanfiles_host
6479    global known_globals
6480
6481    if { [info procs ::gdb_tcl_unknown] != "" } {
6482	# Restore dejagnu's version of proc unknown.
6483	rename ::unknown ""
6484	rename ::dejagnu_unknown ::unknown
6485    }
6486
6487    # Exit first, so that the files are no longer in use.
6488    gdb_exit
6489
6490    if { [llength $cleanfiles_target] > 0 } {
6491	eval remote_file target delete $cleanfiles_target
6492	set cleanfiles_target {}
6493    }
6494    if { [llength $cleanfiles_host] > 0 } {
6495	eval remote_file host delete $cleanfiles_host
6496	set cleanfiles_host {}
6497    }
6498
6499    # Unblock write access to the banned variables.  Dejagnu typically
6500    # resets some of them between testcases.
6501    global banned_variables
6502    global banned_procedures
6503    global banned_traced
6504    if ($banned_traced) {
6505    	foreach banned_var $banned_variables {
6506            global "$banned_var"
6507            trace remove variable "$banned_var" write error
6508	}
6509	foreach banned_proc $banned_procedures {
6510	    global "$banned_proc"
6511	    trace remove execution "$banned_proc" enter error
6512	}
6513	set banned_traced 0
6514    }
6515
6516    global gdb_finish_hooks
6517    foreach gdb_finish_hook $gdb_finish_hooks {
6518	$gdb_finish_hook
6519    }
6520    set gdb_finish_hooks [list]
6521
6522    gdb_cleanup_globals
6523}
6524
6525global debug_format
6526set debug_format "unknown"
6527
6528# Run the gdb command "info source" and extract the debugging format
6529# information from the output and save it in debug_format.
6530
6531proc get_debug_format { } {
6532    global gdb_prompt
6533    global expect_out
6534    global debug_format
6535
6536    set debug_format "unknown"
6537    send_gdb "info source\n"
6538    gdb_expect 10 {
6539	-re "Compiled with (.*) debugging format.\r\n.*$gdb_prompt $" {
6540	    set debug_format $expect_out(1,string)
6541	    verbose "debug format is $debug_format"
6542	    return 1
6543	}
6544	-re "No current source file.\r\n$gdb_prompt $" {
6545	    perror "get_debug_format used when no current source file"
6546	    return 0
6547	}
6548	-re "$gdb_prompt $" {
6549	    warning "couldn't check debug format (no valid response)."
6550	    return 1
6551	}
6552	timeout {
6553	    warning "couldn't check debug format (timeout)."
6554	    return 1
6555	}
6556    }
6557}
6558
6559# Return true if FORMAT matches the debug format the current test was
6560# compiled with.  FORMAT is a shell-style globbing pattern; it can use
6561# `*', `[...]', and so on.
6562#
6563# This function depends on variables set by `get_debug_format', above.
6564
6565proc test_debug_format {format} {
6566    global debug_format
6567
6568    return [expr [string match $format $debug_format] != 0]
6569}
6570
6571# Like setup_xfail, but takes the name of a debug format (DWARF 1,
6572# COFF, stabs, etc).  If that format matches the format that the
6573# current test was compiled with, then the next test is expected to
6574# fail for any target.  Returns 1 if the next test or set of tests is
6575# expected to fail, 0 otherwise (or if it is unknown).  Must have
6576# previously called get_debug_format.
6577proc setup_xfail_format { format } {
6578    set ret [test_debug_format $format]
6579
6580    if {$ret} {
6581	setup_xfail "*-*-*"
6582    }
6583    return $ret
6584}
6585
6586# gdb_get_line_number TEXT [FILE]
6587#
6588# Search the source file FILE, and return the line number of the
6589# first line containing TEXT.  If no match is found, an error is thrown.
6590#
6591# TEXT is a string literal, not a regular expression.
6592#
6593# The default value of FILE is "$srcdir/$subdir/$srcfile".  If FILE is
6594# specified, and does not start with "/", then it is assumed to be in
6595# "$srcdir/$subdir".  This is awkward, and can be fixed in the future,
6596# by changing the callers and the interface at the same time.
6597# In particular: gdb.base/break.exp, gdb.base/condbreak.exp,
6598# gdb.base/ena-dis-br.exp.
6599#
6600# Use this function to keep your test scripts independent of the
6601# exact line numbering of the source file.  Don't write:
6602#
6603#   send_gdb "break 20"
6604#
6605# This means that if anyone ever edits your test's source file,
6606# your test could break.  Instead, put a comment like this on the
6607# source file line you want to break at:
6608#
6609#   /* breakpoint spot: frotz.exp: test name */
6610#
6611# and then write, in your test script (which we assume is named
6612# frotz.exp):
6613#
6614#   send_gdb "break [gdb_get_line_number "frotz.exp: test name"]\n"
6615#
6616# (Yes, Tcl knows how to handle the nested quotes and brackets.
6617# Try this:
6618# 	$ tclsh
6619# 	% puts "foo [lindex "bar baz" 1]"
6620# 	foo baz
6621# 	%
6622# Tcl is quite clever, for a little stringy language.)
6623#
6624# ===
6625#
6626# The previous implementation of this procedure used the gdb search command.
6627# This version is different:
6628#
6629#   . It works with MI, and it also works when gdb is not running.
6630#
6631#   . It operates on the build machine, not the host machine.
6632#
6633#   . For now, this implementation fakes a current directory of
6634#     $srcdir/$subdir to be compatible with the old implementation.
6635#     This will go away eventually and some callers will need to
6636#     be changed.
6637#
6638#   . The TEXT argument is literal text and matches literally,
6639#     not a regular expression as it was before.
6640#
6641#   . State changes in gdb, such as changing the current file
6642#     and setting $_, no longer happen.
6643#
6644# After a bit of time we can forget about the differences from the
6645# old implementation.
6646#
6647# --chastain 2004-08-05
6648
6649proc gdb_get_line_number { text { file "" } } {
6650    global srcdir
6651    global subdir
6652    global srcfile
6653
6654    if {"$file" == ""} {
6655	set file "$srcfile"
6656    }
6657    if {![regexp "^/" "$file"]} {
6658	set file "$srcdir/$subdir/$file"
6659    }
6660
6661    if {[catch { set fd [open "$file"] } message]} {
6662	error "$message"
6663    }
6664
6665    set found -1
6666    for { set line 1 } { 1 } { incr line } {
6667	if {[catch { set nchar [gets "$fd" body] } message]} {
6668	    error "$message"
6669	}
6670	if {$nchar < 0} {
6671	    break
6672	}
6673	if {[string first "$text" "$body"] >= 0} {
6674	    set found $line
6675	    break
6676	}
6677    }
6678
6679    if {[catch { close "$fd" } message]} {
6680	error "$message"
6681    }
6682
6683    if {$found == -1} {
6684        error "undefined tag \"$text\""
6685    }
6686
6687    return $found
6688}
6689
6690# Continue the program until it ends.
6691#
6692# MSSG is the error message that gets printed.  If not given, a
6693#	default is used.
6694# COMMAND is the command to invoke.  If not given, "continue" is
6695#	used.
6696# ALLOW_EXTRA is a flag indicating whether the test should expect
6697#	extra output between the "Continuing." line and the program
6698#	exiting.  By default it is zero; if nonzero, any extra output
6699#	is accepted.
6700
6701proc gdb_continue_to_end {{mssg ""} {command continue} {allow_extra 0}} {
6702  global inferior_exited_re use_gdb_stub
6703
6704  if {$mssg == ""} {
6705      set text "continue until exit"
6706  } else {
6707      set text "continue until exit at $mssg"
6708  }
6709  if {$allow_extra} {
6710      set extra ".*"
6711  } else {
6712      set extra ""
6713  }
6714
6715  # By default, we don't rely on exit() behavior of remote stubs --
6716  # it's common for exit() to be implemented as a simple infinite
6717  # loop, or a forced crash/reset.  For native targets, by default, we
6718  # assume process exit is reported as such.  If a non-reliable target
6719  # is used, we set a breakpoint at exit, and continue to that.
6720  if { [target_info exists exit_is_reliable] } {
6721      set exit_is_reliable [target_info exit_is_reliable]
6722  } else {
6723      set exit_is_reliable [expr ! $use_gdb_stub]
6724  }
6725
6726  if { ! $exit_is_reliable } {
6727    if {![gdb_breakpoint "exit"]} {
6728      return 0
6729    }
6730    gdb_test $command "Continuing..*Breakpoint .*exit.*" \
6731	$text
6732  } else {
6733    # Continue until we exit.  Should not stop again.
6734    # Don't bother to check the output of the program, that may be
6735    # extremely tough for some remote systems.
6736    gdb_test $command \
6737      "Continuing.\[\r\n0-9\]+${extra}(... EXIT code 0\[\r\n\]+|$inferior_exited_re normally).*"\
6738	$text
6739  }
6740}
6741
6742proc rerun_to_main {} {
6743  global gdb_prompt use_gdb_stub
6744
6745  if $use_gdb_stub {
6746    gdb_run_cmd
6747    gdb_expect {
6748      -re ".*Breakpoint .*main .*$gdb_prompt $"\
6749	      {pass "rerun to main" ; return 0}
6750      -re "$gdb_prompt $"\
6751	      {fail "rerun to main" ; return 0}
6752      timeout {fail "(timeout) rerun to main" ; return 0}
6753    }
6754  } else {
6755    send_gdb "run\n"
6756    gdb_expect {
6757      -re "The program .* has been started already.*y or n. $" {
6758	  send_gdb "y\n" answer
6759	  exp_continue
6760      }
6761      -re "Starting program.*$gdb_prompt $"\
6762	      {pass "rerun to main" ; return 0}
6763      -re "$gdb_prompt $"\
6764	      {fail "rerun to main" ; return 0}
6765      timeout {fail "(timeout) rerun to main" ; return 0}
6766    }
6767  }
6768}
6769
6770# Return true if EXECUTABLE contains a .gdb_index or .debug_names index section.
6771
6772proc exec_has_index_section { executable } {
6773    set readelf_program [gdb_find_readelf]
6774    set res [catch {exec $readelf_program -S $executable \
6775			| grep -E "\.gdb_index|\.debug_names" }]
6776    if { $res == 0 } {
6777	return 1
6778    }
6779    return 0
6780}
6781
6782# Return list with major and minor version of readelf, or an empty list.
6783gdb_caching_proc readelf_version {
6784    set readelf_program [gdb_find_readelf]
6785    set res [catch {exec $readelf_program --version} output]
6786    if { $res != 0 } {
6787	return [list]
6788    }
6789    set lines [split $output \n]
6790    set line [lindex $lines 0]
6791    set res [regexp {[ \t]+([0-9]+)[.]([0-9]+)[^ \t]*$} \
6792		 $line dummy major minor]
6793    if { $res != 1 } {
6794	return [list]
6795    }
6796    return [list $major $minor]
6797}
6798
6799# Return 1 if readelf prints the PIE flag, 0 if is doesn't, and -1 if unknown.
6800proc readelf_prints_pie { } {
6801    set version [readelf_version]
6802    if { [llength $version] == 0 } {
6803	return -1
6804    }
6805    set major [lindex $version 0]
6806    set minor [lindex $version 1]
6807    # It would be better to construct a PIE executable and test if the PIE
6808    # flag is printed by readelf, but we cannot reliably construct a PIE
6809    # executable if the multilib_flags dictate otherwise
6810    # (--target_board=unix/-no-pie/-fno-PIE).
6811    return [version_at_least $major $minor 2 26]
6812}
6813
6814# Return 1 if EXECUTABLE is a Position Independent Executable, 0 if it is not,
6815# and -1 if unknown.
6816
6817proc exec_is_pie { executable } {
6818    set res [readelf_prints_pie]
6819    if { $res != 1 } {
6820	return -1
6821    }
6822    set readelf_program [gdb_find_readelf]
6823    # We're not testing readelf -d | grep "FLAGS_1.*Flags:.*PIE"
6824    # because the PIE flag is not set by all versions of gold, see PR
6825    # binutils/26039.
6826    set res [catch {exec $readelf_program -h $executable} output]
6827    if { $res != 0 } {
6828	return -1
6829    }
6830    set res [regexp -line {^[ \t]*Type:[ \t]*DYN \((Position-Independent Executable|Shared object) file\)$} \
6831		 $output]
6832    if { $res == 1 } {
6833	return 1
6834    }
6835    return 0
6836}
6837
6838# Return true if a test should be skipped due to lack of floating
6839# point support or GDB can't fetch the contents from floating point
6840# registers.
6841
6842gdb_caching_proc gdb_skip_float_test {
6843    if [target_info exists gdb,skip_float_tests] {
6844	return 1
6845    }
6846
6847    # There is an ARM kernel ptrace bug that hardware VFP registers
6848    # are not updated after GDB ptrace set VFP registers.  The bug
6849    # was introduced by kernel commit 8130b9d7b9d858aa04ce67805e8951e3cb6e9b2f
6850    # in 2012 and is fixed in e2dfb4b880146bfd4b6aa8e138c0205407cebbaf
6851    # in May 2016.  In other words, kernels older than 4.6.3, 4.4.14,
6852    # 4.1.27, 3.18.36, and 3.14.73 have this bug.
6853    # This kernel bug is detected by check how does GDB change the
6854    # program result by changing one VFP register.
6855    if { [istarget "arm*-*-linux*"] } {
6856
6857	set compile_flags {debug nowarnings }
6858
6859	# Set up, compile, and execute a test program having VFP
6860	# operations.
6861	set src [standard_temp_file arm_vfp[pid].c]
6862	set exe [standard_temp_file arm_vfp[pid].x]
6863
6864	gdb_produce_source $src {
6865	    int main() {
6866		double d = 4.0;
6867		int ret;
6868
6869		asm ("vldr d0, [%0]" : : "r" (&d));
6870		asm ("vldr d1, [%0]" : : "r" (&d));
6871		asm (".global break_here\n"
6872		     "break_here:");
6873		asm ("vcmp.f64 d0, d1\n"
6874		     "vmrs APSR_nzcv, fpscr\n"
6875		     "bne L_value_different\n"
6876		     "movs %0, #0\n"
6877		     "b L_end\n"
6878		     "L_value_different:\n"
6879		     "movs %0, #1\n"
6880		     "L_end:\n" : "=r" (ret) :);
6881
6882		/* Return $d0 != $d1.  */
6883		return ret;
6884	    }
6885	}
6886
6887	verbose "compiling testfile $src" 2
6888	set lines [gdb_compile $src $exe executable $compile_flags]
6889	file delete $src
6890
6891	if {![string match "" $lines]} {
6892	    verbose "testfile compilation failed, returning 1" 2
6893	    return 0
6894	}
6895
6896	# No error message, compilation succeeded so now run it via gdb.
6897	# Run the test up to 5 times to detect whether ptrace can
6898	# correctly update VFP registers or not.
6899	set skip_vfp_test 0
6900	for {set i 0} {$i < 5} {incr i} {
6901	    global gdb_prompt srcdir subdir
6902
6903	    gdb_exit
6904	    gdb_start
6905	    gdb_reinitialize_dir $srcdir/$subdir
6906	    gdb_load "$exe"
6907
6908	    runto_main
6909	    gdb_test "break *break_here"
6910	    gdb_continue_to_breakpoint "break_here"
6911
6912	    # Modify $d0 to a different value, so the exit code should
6913	    # be 1.
6914	    gdb_test "set \$d0 = 5.0"
6915
6916	    set test "continue to exit"
6917	    gdb_test_multiple "continue" "$test" {
6918		-re "exited with code 01.*$gdb_prompt $" {
6919		}
6920		-re "exited normally.*$gdb_prompt $" {
6921		    # However, the exit code is 0.  That means something
6922		    # wrong in setting VFP registers.
6923		    set skip_vfp_test 1
6924		    break
6925		}
6926	    }
6927	}
6928
6929	gdb_exit
6930	remote_file build delete $exe
6931
6932	return $skip_vfp_test
6933    }
6934    return 0
6935}
6936
6937# Print a message and return true if a test should be skipped
6938# due to lack of stdio support.
6939
6940proc gdb_skip_stdio_test { msg } {
6941    if [target_info exists gdb,noinferiorio] {
6942	verbose "Skipping test '$msg': no inferior i/o."
6943	return 1
6944    }
6945    return 0
6946}
6947
6948proc gdb_skip_bogus_test { msg } {
6949    return 0
6950}
6951
6952# Return true if a test should be skipped due to lack of XML support
6953# in the host GDB.
6954# NOTE: This must be called while gdb is *not* running.
6955
6956gdb_caching_proc gdb_skip_xml_test {
6957    global gdb_spawn_id
6958    global gdb_prompt
6959    global srcdir
6960
6961    if { [info exists gdb_spawn_id] } {
6962        error "GDB must not be running in gdb_skip_xml_tests."
6963    }
6964
6965    set xml_file [gdb_remote_download host "${srcdir}/gdb.xml/trivial.xml"]
6966
6967    gdb_start
6968    set xml_missing 0
6969    gdb_test_multiple "set tdesc filename $xml_file" "" {
6970	-re ".*XML support was disabled at compile time.*$gdb_prompt $" {
6971	    set xml_missing 1
6972	}
6973	-re ".*$gdb_prompt $" { }
6974    }
6975    gdb_exit
6976    return $xml_missing
6977}
6978
6979# Return true if argv[0] is available.
6980
6981gdb_caching_proc gdb_has_argv0 {
6982    set result 0
6983
6984    # Compile and execute a test program to check whether argv[0] is available.
6985    gdb_simple_compile has_argv0 {
6986	int main (int argc, char **argv) {
6987	    return 0;
6988	}
6989    } executable
6990
6991
6992    # Helper proc.
6993    proc gdb_has_argv0_1 { exe } {
6994	global srcdir subdir
6995	global gdb_prompt hex
6996
6997	gdb_exit
6998	gdb_start
6999	gdb_reinitialize_dir $srcdir/$subdir
7000	gdb_load "$exe"
7001
7002	# Set breakpoint on main.
7003	gdb_test_multiple "break -q main" "break -q main" {
7004	    -re "Breakpoint.*${gdb_prompt} $" {
7005	    }
7006	    -re "${gdb_prompt} $" {
7007		return 0
7008	    }
7009	}
7010
7011	# Run to main.
7012	gdb_run_cmd
7013	gdb_test_multiple "" "run to main" {
7014	    -re "Breakpoint.*${gdb_prompt} $" {
7015	    }
7016	    -re "${gdb_prompt} $" {
7017		return 0
7018	    }
7019	}
7020
7021	set old_elements "200"
7022	set test "show print elements"
7023	gdb_test_multiple $test $test {
7024	    -re "Limit on string chars or array elements to print is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
7025		set old_elements $expect_out(1,string)
7026	    }
7027	}
7028	set old_repeats "200"
7029	set test "show print repeats"
7030	gdb_test_multiple $test $test {
7031	    -re "Threshold for repeated print elements is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
7032		set old_repeats $expect_out(1,string)
7033	    }
7034	}
7035	gdb_test_no_output "set print elements unlimited" ""
7036	gdb_test_no_output "set print repeats unlimited" ""
7037
7038	set retval 0
7039	# Check whether argc is 1.
7040	gdb_test_multiple "p argc" "p argc" {
7041	    -re " = 1\r\n${gdb_prompt} $" {
7042
7043		gdb_test_multiple "p argv\[0\]" "p argv\[0\]" {
7044		    -re " = $hex \".*[file tail $exe]\"\r\n${gdb_prompt} $" {
7045			set retval 1
7046		    }
7047		    -re "${gdb_prompt} $" {
7048		    }
7049		}
7050	    }
7051	    -re "${gdb_prompt} $" {
7052	    }
7053	}
7054
7055	gdb_test_no_output "set print elements $old_elements" ""
7056	gdb_test_no_output "set print repeats $old_repeats" ""
7057
7058	return $retval
7059    }
7060
7061    set result [gdb_has_argv0_1 $obj]
7062
7063    gdb_exit
7064    file delete $obj
7065
7066    if { !$result
7067      && ([istarget *-*-linux*]
7068	  || [istarget *-*-freebsd*] || [istarget *-*-kfreebsd*]
7069	  || [istarget *-*-netbsd*] || [istarget *-*-knetbsd*]
7070	  || [istarget *-*-openbsd*]
7071	  || [istarget *-*-darwin*]
7072	  || [istarget *-*-solaris*]
7073	  || [istarget *-*-aix*]
7074	  || [istarget *-*-gnu*]
7075	  || [istarget *-*-cygwin*] || [istarget *-*-mingw32*]
7076	  || [istarget *-*-*djgpp*] || [istarget *-*-go32*]
7077	  || [istarget *-wince-pe] || [istarget *-*-mingw32ce*]
7078	  || [istarget *-*-osf*]
7079	  || [istarget *-*-dicos*]
7080	  || [istarget *-*-nto*]
7081	  || [istarget *-*-*vms*]
7082	  || [istarget *-*-lynx*178]) } {
7083	fail "argv\[0\] should be available on this target"
7084    }
7085
7086    return $result
7087}
7088
7089# Note: the procedure gdb_gnu_strip_debug will produce an executable called
7090# ${binfile}.dbglnk, which is just like the executable ($binfile) but without
7091# the debuginfo. Instead $binfile has a .gnu_debuglink section which contains
7092# the name of a debuginfo only file. This file will be stored in the same
7093# subdirectory.
7094
7095# Functions for separate debug info testing
7096
7097# starting with an executable:
7098# foo --> original executable
7099
7100# at the end of the process we have:
7101# foo.stripped --> foo w/o debug info
7102# foo.debug --> foo's debug info
7103# foo --> like foo, but with a new .gnu_debuglink section pointing to foo.debug.
7104
7105# Fetch the build id from the file.
7106# Returns "" if there is none.
7107
7108proc get_build_id { filename } {
7109    if { ([istarget "*-*-mingw*"]
7110	  || [istarget *-*-cygwin*]) } {
7111	set objdump_program [gdb_find_objdump]
7112	set result [catch {set data [exec $objdump_program -p $filename | grep signature | cut "-d " -f4]} output]
7113	verbose "result is $result"
7114	verbose "output is $output"
7115	if {$result == 1} {
7116	    return ""
7117	}
7118	return $data
7119    } else {
7120	set tmp [standard_output_file "${filename}-tmp"]
7121	set objcopy_program [gdb_find_objcopy]
7122	set result [catch "exec $objcopy_program -j .note.gnu.build-id -O binary $filename $tmp" output]
7123	verbose "result is $result"
7124	verbose "output is $output"
7125	if {$result == 1} {
7126	    return ""
7127	}
7128	set fi [open $tmp]
7129	fconfigure $fi -translation binary
7130	# Skip the NOTE header.
7131	read $fi 16
7132	set data [read $fi]
7133	close $fi
7134	file delete $tmp
7135	if {![string compare $data ""]} {
7136	    return ""
7137	}
7138	# Convert it to hex.
7139	binary scan $data H* data
7140	return $data
7141    }
7142}
7143
7144# Return the build-id hex string (usually 160 bits as 40 hex characters)
7145# converted to the form: .build-id/ab/cdef1234...89.debug
7146# Return "" if no build-id found.
7147proc build_id_debug_filename_get { filename } {
7148    set data [get_build_id $filename]
7149    if { $data == "" } {
7150	return ""
7151    }
7152    regsub {^..} $data {\0/} data
7153    return ".build-id/${data}.debug"
7154}
7155
7156# Create stripped files for DEST, replacing it.  If ARGS is passed, it is a
7157# list of optional flags.  The only currently supported flag is no-main,
7158# which removes the symbol entry for main from the separate debug file.
7159#
7160# Function returns zero on success.  Function will return non-zero failure code
7161# on some targets not supporting separate debug info (such as i386-msdos).
7162
7163proc gdb_gnu_strip_debug { dest args } {
7164
7165    # Use the first separate debug info file location searched by GDB so the
7166    # run cannot be broken by some stale file searched with higher precedence.
7167    set debug_file "${dest}.debug"
7168
7169    set strip_to_file_program [transform strip]
7170    set objcopy_program [gdb_find_objcopy]
7171
7172    set debug_link [file tail $debug_file]
7173    set stripped_file "${dest}.stripped"
7174
7175    # Get rid of the debug info, and store result in stripped_file
7176    # something like gdb/testsuite/gdb.base/blah.stripped.
7177    set result [catch "exec $strip_to_file_program --strip-debug ${dest} -o ${stripped_file}" output]
7178    verbose "result is $result"
7179    verbose "output is $output"
7180    if {$result == 1} {
7181      return 1
7182    }
7183
7184    # Workaround PR binutils/10802:
7185    # Preserve the 'x' bit also for PIEs (Position Independent Executables).
7186    set perm [file attributes ${dest} -permissions]
7187    file attributes ${stripped_file} -permissions $perm
7188
7189    # Get rid of everything but the debug info, and store result in debug_file
7190    # This will be in the .debug subdirectory, see above.
7191    set result [catch "exec $strip_to_file_program --only-keep-debug ${dest} -o ${debug_file}" output]
7192    verbose "result is $result"
7193    verbose "output is $output"
7194    if {$result == 1} {
7195      return 1
7196    }
7197
7198    # If no-main is passed, strip the symbol for main from the separate
7199    # file.  This is to simulate the behavior of elfutils's eu-strip, which
7200    # leaves the symtab in the original file only.  There's no way to get
7201    # objcopy or strip to remove the symbol table without also removing the
7202    # debugging sections, so this is as close as we can get.
7203    if { [llength $args] == 1 && [lindex $args 0] == "no-main" } {
7204	set result [catch "exec $objcopy_program -N main ${debug_file} ${debug_file}-tmp" output]
7205	verbose "result is $result"
7206	verbose "output is $output"
7207	if {$result == 1} {
7208	    return 1
7209	}
7210	file delete "${debug_file}"
7211	file rename "${debug_file}-tmp" "${debug_file}"
7212    }
7213
7214    # Link the two previous output files together, adding the .gnu_debuglink
7215    # section to the stripped_file, containing a pointer to the debug_file,
7216    # save the new file in dest.
7217    # This will be the regular executable filename, in the usual location.
7218    set result [catch "exec $objcopy_program --add-gnu-debuglink=${debug_file} ${stripped_file} ${dest}" output]
7219    verbose "result is $result"
7220    verbose "output is $output"
7221    if {$result == 1} {
7222      return 1
7223    }
7224
7225    # Workaround PR binutils/10802:
7226    # Preserve the 'x' bit also for PIEs (Position Independent Executables).
7227    set perm [file attributes ${stripped_file} -permissions]
7228    file attributes ${dest} -permissions $perm
7229
7230    return 0
7231}
7232
7233# Test the output of GDB_COMMAND matches the pattern obtained
7234# by concatenating all elements of EXPECTED_LINES.  This makes
7235# it possible to split otherwise very long string into pieces.
7236# If third argument TESTNAME is not empty, it's used as the name of the
7237# test to be printed on pass/fail.
7238proc help_test_raw { gdb_command expected_lines {testname {}} } {
7239    set expected_output [join $expected_lines ""]
7240    if {$testname != {}} {
7241	gdb_test "${gdb_command}" "${expected_output}" $testname
7242	return
7243    }
7244
7245    gdb_test "${gdb_command}" "${expected_output}"
7246}
7247
7248# A regexp that matches the end of help CLASS|PREFIX_COMMAND
7249set help_list_trailer {
7250    "Type \"apropos word\" to search for commands related to \"word\"\.[\r\n]+"
7251    "Type \"apropos -v word\" for full documentation of commands related to \"word\"\.[\r\n]+"
7252    "Command name abbreviations are allowed if unambiguous\."
7253}
7254
7255# Test the output of "help COMMAND_CLASS".  EXPECTED_INITIAL_LINES
7256# are regular expressions that should match the beginning of output,
7257# before the list of commands in that class.
7258# LIST_OF_COMMANDS are regular expressions that should match the
7259# list of commands in that class.  If empty, the command list will be
7260# matched automatically.  The presence of standard epilogue will be tested
7261# automatically.
7262# If last argument TESTNAME is not empty, it's used as the name of the
7263# test to be printed on pass/fail.
7264# Notice that the '[' and ']' characters don't need to be escaped for strings
7265# wrapped in {} braces.
7266proc test_class_help { command_class expected_initial_lines {list_of_commands {}} {testname {}} } {
7267    global help_list_trailer
7268    if {[llength $list_of_commands]>0} {
7269	set l_list_of_commands {"List of commands:[\r\n]+[\r\n]+"}
7270        set l_list_of_commands [concat $l_list_of_commands $list_of_commands]
7271	set l_list_of_commands [concat $l_list_of_commands {"[\r\n]+[\r\n]+"}]
7272    } else {
7273        set l_list_of_commands {"List of commands\:.*[\r\n]+"}
7274    }
7275    set l_stock_body {
7276        "Type \"help\" followed by command name for full documentation\.[\r\n]+"
7277    }
7278    set l_entire_body [concat $expected_initial_lines $l_list_of_commands \
7279		       $l_stock_body $help_list_trailer]
7280
7281    help_test_raw "help ${command_class}" $l_entire_body $testname
7282}
7283
7284# Like test_class_help but specialised to test "help user-defined".
7285proc test_user_defined_class_help { {list_of_commands {}} {testname {}} } {
7286    test_class_help "user-defined" {
7287	"User-defined commands\.[\r\n]+"
7288	"The commands in this class are those defined by the user\.[\r\n]+"
7289	"Use the \"define\" command to define a command\.[\r\n]+"
7290    } $list_of_commands $testname
7291}
7292
7293
7294# COMMAND_LIST should have either one element -- command to test, or
7295# two elements -- abbreviated command to test, and full command the first
7296# element is abbreviation of.
7297# The command must be a prefix command.  EXPECTED_INITIAL_LINES
7298# are regular expressions that should match the beginning of output,
7299# before the list of subcommands.  The presence of
7300# subcommand list and standard epilogue will be tested automatically.
7301proc test_prefix_command_help { command_list expected_initial_lines args } {
7302    global help_list_trailer
7303    set command [lindex $command_list 0]
7304    if {[llength $command_list]>1} {
7305        set full_command [lindex $command_list 1]
7306    } else {
7307        set full_command $command
7308    }
7309    # Use 'list' and not just {} because we want variables to
7310    # be expanded in this list.
7311    set l_stock_body [list\
7312         "List of $full_command subcommands\:.*\[\r\n\]+"\
7313         "Type \"help $full_command\" followed by $full_command subcommand name for full documentation\.\[\r\n\]+"]
7314    set l_entire_body [concat $expected_initial_lines $l_stock_body $help_list_trailer]
7315    if {[llength $args]>0} {
7316        help_test_raw "help ${command}" $l_entire_body [lindex $args 0]
7317    } else {
7318        help_test_raw "help ${command}" $l_entire_body
7319    }
7320}
7321
7322# Build executable named EXECUTABLE from specifications that allow
7323# different options to be passed to different sub-compilations.
7324# TESTNAME is the name of the test; this is passed to 'untested' if
7325# something fails.
7326# OPTIONS is passed to the final link, using gdb_compile.  If OPTIONS
7327# contains the option "pthreads", then gdb_compile_pthreads is used.
7328# ARGS is a flat list of source specifications, of the form:
7329#    { SOURCE1 OPTIONS1 [ SOURCE2 OPTIONS2 ]... }
7330# Each SOURCE is compiled to an object file using its OPTIONS,
7331# using gdb_compile.
7332# Returns 0 on success, -1 on failure.
7333proc build_executable_from_specs {testname executable options args} {
7334    global subdir
7335    global srcdir
7336
7337    set binfile [standard_output_file $executable]
7338
7339    set func gdb_compile
7340    set func_index [lsearch -regexp $options {^(pthreads|shlib|shlib_pthreads|openmp)$}]
7341    if {$func_index != -1} {
7342	set func "${func}_[lindex $options $func_index]"
7343    }
7344
7345    # gdb_compile_shlib and gdb_compile_shlib_pthreads do not use the 3rd
7346    # parameter.  They also requires $sources while gdb_compile and
7347    # gdb_compile_pthreads require $objects.  Moreover they ignore any options.
7348    if [string match gdb_compile_shlib* $func] {
7349	set sources_path {}
7350	foreach {s local_options} $args {
7351	    if {[regexp "^/" "$s"]} {
7352		lappend sources_path "$s"
7353	    } else {
7354		lappend sources_path "$srcdir/$subdir/$s"
7355	    }
7356	}
7357	set ret [$func $sources_path "${binfile}" $options]
7358    } elseif {[lsearch -exact $options rust] != -1} {
7359	set sources_path {}
7360	foreach {s local_options} $args {
7361	    if {[regexp "^/" "$s"]} {
7362		lappend sources_path "$s"
7363	    } else {
7364		lappend sources_path "$srcdir/$subdir/$s"
7365	    }
7366	}
7367	set ret [gdb_compile_rust $sources_path "${binfile}" $options]
7368    } else {
7369	set objects {}
7370	set i 0
7371	foreach {s local_options} $args {
7372	    if {![regexp "^/" "$s"]} {
7373		set s "$srcdir/$subdir/$s"
7374	    }
7375	    if  { [$func "${s}" "${binfile}${i}.o" object $local_options] != "" } {
7376		untested $testname
7377		return -1
7378	    }
7379	    lappend objects "${binfile}${i}.o"
7380	    incr i
7381	}
7382	set ret [$func $objects "${binfile}" executable $options]
7383    }
7384    if  { $ret != "" } {
7385        untested $testname
7386        return -1
7387    }
7388
7389    return 0
7390}
7391
7392# Build executable named EXECUTABLE, from SOURCES.  If SOURCES are not
7393# provided, uses $EXECUTABLE.c.  The TESTNAME paramer is the name of test
7394# to pass to untested, if something is wrong.  OPTIONS are passed
7395# to gdb_compile directly.
7396proc build_executable { testname executable {sources ""} {options {debug}} } {
7397    if {[llength $sources]==0} {
7398        set sources ${executable}.c
7399    }
7400
7401    set arglist [list $testname $executable $options]
7402    foreach source $sources {
7403	lappend arglist $source $options
7404    }
7405
7406    return [eval build_executable_from_specs $arglist]
7407}
7408
7409# Starts fresh GDB binary and loads an optional executable into GDB.
7410# Usage: clean_restart [executable]
7411# EXECUTABLE is the basename of the binary.
7412# Return -1 if starting gdb or loading the executable failed.
7413
7414proc clean_restart { args } {
7415    global srcdir
7416    global subdir
7417    global errcnt
7418    global warncnt
7419
7420    if { [llength $args] > 1 } {
7421	error "bad number of args: [llength $args]"
7422    }
7423
7424    gdb_exit
7425
7426    # This is a clean restart, so reset error and warning count.
7427    set errcnt 0
7428    set warncnt 0
7429
7430    # We'd like to do:
7431    #   if { [gdb_start] == -1 } {
7432    #     return -1
7433    #   }
7434    # but gdb_start is a ${tool}_start proc, which doesn't have a defined
7435    # return value.  So instead, we test for errcnt.
7436    gdb_start
7437    if { $errcnt > 0 } {
7438	return -1
7439    }
7440
7441    gdb_reinitialize_dir $srcdir/$subdir
7442
7443    if { [llength $args] >= 1 } {
7444	set executable [lindex $args 0]
7445	set binfile [standard_output_file ${executable}]
7446	return [gdb_load ${binfile}]
7447    }
7448
7449    return 0
7450}
7451
7452# Prepares for testing by calling build_executable_full, then
7453# clean_restart.
7454# TESTNAME is the name of the test.
7455# Each element in ARGS is a list of the form
7456#    { EXECUTABLE OPTIONS SOURCE_SPEC... }
7457# These are passed to build_executable_from_specs, which see.
7458# The last EXECUTABLE is passed to clean_restart.
7459# Returns 0 on success, non-zero on failure.
7460proc prepare_for_testing_full {testname args} {
7461    foreach spec $args {
7462	if {[eval build_executable_from_specs [list $testname] $spec] == -1} {
7463	    return -1
7464	}
7465	set executable [lindex $spec 0]
7466    }
7467    clean_restart $executable
7468    return 0
7469}
7470
7471# Prepares for testing, by calling build_executable, and then clean_restart.
7472# Please refer to build_executable for parameter description.
7473proc prepare_for_testing { testname executable {sources ""} {options {debug}}} {
7474
7475    if {[build_executable $testname $executable $sources $options] == -1} {
7476        return -1
7477    }
7478    clean_restart $executable
7479
7480    return 0
7481}
7482
7483# Retrieve the value of EXP in the inferior, represented in format
7484# specified in FMT (using "printFMT").  DEFAULT is used as fallback if
7485# print fails.  TEST is the test message to use.  It can be omitted,
7486# in which case a test message is built from EXP.
7487
7488proc get_valueof { fmt exp default {test ""} } {
7489    global gdb_prompt
7490
7491    if {$test == "" } {
7492	set test "get valueof \"${exp}\""
7493    }
7494
7495    set val ${default}
7496    gdb_test_multiple "print${fmt} ${exp}" "$test" {
7497	-re "\\$\[0-9\]* = (\[^\r\n\]*)\[\r\n\]*$gdb_prompt $" {
7498	    set val $expect_out(1,string)
7499	    pass "$test"
7500	}
7501	timeout {
7502	    fail "$test (timeout)"
7503	}
7504    }
7505    return ${val}
7506}
7507
7508# Retrieve the value of local var EXP in the inferior.  DEFAULT is used as
7509# fallback if print fails.  TEST is the test message to use.  It can be
7510# omitted, in which case a test message is built from EXP.
7511
7512proc get_local_valueof { exp default {test ""} } {
7513    global gdb_prompt
7514
7515    if {$test == "" } {
7516	set test "get local valueof \"${exp}\""
7517    }
7518
7519    set val ${default}
7520    gdb_test_multiple "info locals ${exp}" "$test" {
7521	-re "$exp = (\[^\r\n\]*)\[\r\n\]*$gdb_prompt $" {
7522	    set val $expect_out(1,string)
7523	    pass "$test"
7524	}
7525	timeout {
7526	    fail "$test (timeout)"
7527	}
7528    }
7529    return ${val}
7530}
7531
7532# Retrieve the value of EXP in the inferior, as a signed decimal value
7533# (using "print /d").  DEFAULT is used as fallback if print fails.
7534# TEST is the test message to use.  It can be omitted, in which case
7535# a test message is built from EXP.
7536
7537proc get_integer_valueof { exp default {test ""} } {
7538    global gdb_prompt
7539
7540    if {$test == ""} {
7541	set test "get integer valueof \"${exp}\""
7542    }
7543
7544    set val ${default}
7545    gdb_test_multiple "print /d ${exp}" "$test" {
7546	-re "\\$\[0-9\]* = (\[-\]*\[0-9\]*).*$gdb_prompt $" {
7547	    set val $expect_out(1,string)
7548	    pass "$test"
7549	}
7550	timeout {
7551	    fail "$test (timeout)"
7552	}
7553    }
7554    return ${val}
7555}
7556
7557# Retrieve the value of EXP in the inferior, as an hexadecimal value
7558# (using "print /x").  DEFAULT is used as fallback if print fails.
7559# TEST is the test message to use.  It can be omitted, in which case
7560# a test message is built from EXP.
7561
7562proc get_hexadecimal_valueof { exp default {test ""} } {
7563    global gdb_prompt
7564
7565    if {$test == ""} {
7566	set test "get hexadecimal valueof \"${exp}\""
7567    }
7568
7569    set val ${default}
7570    gdb_test_multiple "print /x ${exp}" $test {
7571	-re "\\$\[0-9\]* = (0x\[0-9a-zA-Z\]+).*$gdb_prompt $" {
7572	    set val $expect_out(1,string)
7573	    pass "$test"
7574	}
7575    }
7576    return ${val}
7577}
7578
7579# Retrieve the size of TYPE in the inferior, as a decimal value.  DEFAULT
7580# is used as fallback if print fails.  TEST is the test message to use.
7581# It can be omitted, in which case a test message is 'sizeof (TYPE)'.
7582
7583proc get_sizeof { type default {test ""} } {
7584    return [get_integer_valueof "sizeof (${type})" $default $test]
7585}
7586
7587proc get_target_charset { } {
7588    global gdb_prompt
7589
7590    gdb_test_multiple "show target-charset" "" {
7591	-re "The target character set is \"auto; currently (\[^\"\]*)\".*$gdb_prompt $" {
7592	    return $expect_out(1,string)
7593	}
7594	-re "The target character set is \"(\[^\"\]*)\".*$gdb_prompt $" {
7595	    return $expect_out(1,string)
7596	}
7597    }
7598
7599    # Pick a reasonable default.
7600    warning "Unable to read target-charset."
7601    return "UTF-8"
7602}
7603
7604# Get the address of VAR.
7605
7606proc get_var_address { var } {
7607    global gdb_prompt hex
7608
7609    # Match output like:
7610    # $1 = (int *) 0x0
7611    # $5 = (int (*)()) 0
7612    # $6 = (int (*)()) 0x24 <function_bar>
7613
7614    gdb_test_multiple "print &${var}" "get address of ${var}" {
7615	-re "\\\$\[0-9\]+ = \\(.*\\) (0|$hex)( <${var}>)?\[\r\n\]+${gdb_prompt} $"
7616	{
7617	    pass "get address of ${var}"
7618	    if { $expect_out(1,string) == "0" } {
7619		return "0x0"
7620	    } else {
7621		return $expect_out(1,string)
7622	    }
7623	}
7624    }
7625    return ""
7626}
7627
7628# Return the frame number for the currently selected frame
7629proc get_current_frame_number {{test_name ""}} {
7630    global gdb_prompt
7631
7632    if { $test_name == "" } {
7633	set test_name "get current frame number"
7634    }
7635    set frame_num -1
7636    gdb_test_multiple "frame" $test_name {
7637	-re "#(\[0-9\]+) .*$gdb_prompt $" {
7638	    set frame_num $expect_out(1,string)
7639	}
7640    }
7641    return $frame_num
7642}
7643
7644# Get the current value for remotetimeout and return it.
7645proc get_remotetimeout { } {
7646    global gdb_prompt
7647    global decimal
7648
7649    gdb_test_multiple "show remotetimeout" "" {
7650	-re "Timeout limit to wait for target to respond is ($decimal).*$gdb_prompt $" {
7651	    return $expect_out(1,string)
7652	}
7653    }
7654
7655    # Pick the default that gdb uses
7656    warning "Unable to read remotetimeout"
7657    return 300
7658}
7659
7660# Set the remotetimeout to the specified timeout.  Nothing is returned.
7661proc set_remotetimeout { timeout } {
7662    global gdb_prompt
7663
7664    gdb_test_multiple "set remotetimeout $timeout" "" {
7665	-re "$gdb_prompt $" {
7666	    verbose "Set remotetimeout to $timeout\n"
7667	}
7668    }
7669}
7670
7671# Get the target's current endianness and return it.
7672proc get_endianness { } {
7673    global gdb_prompt
7674
7675    gdb_test_multiple "show endian" "determine endianness" {
7676	-re ".* (little|big) endian.*\r\n$gdb_prompt $" {
7677	    # Pass silently.
7678	    return $expect_out(1,string)
7679	}
7680    }
7681    return "little"
7682}
7683
7684# Get the target's default endianness and return it.
7685gdb_caching_proc target_endianness {
7686    global gdb_prompt
7687
7688    set me "target_endianness"
7689
7690    set src { int main() { return 0; } }
7691    if {![gdb_simple_compile $me $src executable]} {
7692        return 0
7693    }
7694
7695    clean_restart $obj
7696    if ![runto_main] {
7697        return 0
7698    }
7699    set res [get_endianness]
7700
7701    gdb_exit
7702    remote_file build delete $obj
7703
7704    return $res
7705}
7706
7707# ROOT and FULL are file names.  Returns the relative path from ROOT
7708# to FULL.  Note that FULL must be in a subdirectory of ROOT.
7709# For example, given ROOT = /usr/bin and FULL = /usr/bin/ls, this
7710# will return "ls".
7711
7712proc relative_filename {root full} {
7713    set root_split [file split $root]
7714    set full_split [file split $full]
7715
7716    set len [llength $root_split]
7717
7718    if {[eval file join $root_split]
7719	!= [eval file join [lrange $full_split 0 [expr {$len - 1}]]]} {
7720	error "$full not a subdir of $root"
7721    }
7722
7723    return [eval file join [lrange $full_split $len end]]
7724}
7725
7726# If GDB_PARALLEL exists, then set up the parallel-mode directories.
7727if {[info exists GDB_PARALLEL]} {
7728    if {[is_remote host]} {
7729	unset GDB_PARALLEL
7730    } else {
7731	file mkdir \
7732	    [make_gdb_parallel_path outputs] \
7733	    [make_gdb_parallel_path temp] \
7734	    [make_gdb_parallel_path cache]
7735    }
7736}
7737
7738# Set the inferior's cwd to the output directory, in order to have it
7739# dump core there.  This must be called before the inferior is
7740# started.
7741
7742proc set_inferior_cwd_to_output_dir {} {
7743    # Note this sets the inferior's cwd ("set cwd"), not GDB's ("cd").
7744    # If GDB crashes, we want its core dump in gdb/testsuite/, not in
7745    # the testcase's dir, so we can detect the unexpected core at the
7746    # end of the test run.
7747    if {![is_remote host]} {
7748	set output_dir [standard_output_file ""]
7749	gdb_test_no_output "set cwd $output_dir" \
7750	    "set inferior cwd to test directory"
7751    }
7752}
7753
7754# Get the inferior's PID.
7755
7756proc get_inferior_pid {} {
7757    set pid -1
7758    gdb_test_multiple "inferior" "get inferior pid" {
7759	-re "process (\[0-9\]*).*$::gdb_prompt $" {
7760	    set pid $expect_out(1,string)
7761	    pass $gdb_test_name
7762	}
7763    }
7764    return $pid
7765}
7766
7767# Find the kernel-produced core file dumped for the current testfile
7768# program.  PID was the inferior's pid, saved before the inferior
7769# exited with a signal, or -1 if not known.  If not on a remote host,
7770# this assumes the core was generated in the output directory.
7771# Returns the name of the core dump, or empty string if not found.
7772
7773proc find_core_file {pid} {
7774    # For non-remote hosts, since cores are assumed to be in the
7775    # output dir, which we control, we use a laxer "core.*" glob.  For
7776    # remote hosts, as we don't know whether the dir is being reused
7777    # for parallel runs, we use stricter names with no globs.  It is
7778    # not clear whether this is really important, but it preserves
7779    # status quo ante.
7780    set files {}
7781    if {![is_remote host]} {
7782	lappend files core.*
7783    } elseif {$pid != -1} {
7784	lappend files core.$pid
7785    }
7786    lappend files ${::testfile}.core
7787    lappend files core
7788
7789    foreach file $files {
7790	if {![is_remote host]} {
7791	    set names [glob -nocomplain [standard_output_file $file]]
7792	    if {[llength $names] == 1} {
7793		return [lindex $names 0]
7794	    }
7795	} else {
7796	    if {[remote_file host exists $file]} {
7797		return $file
7798	    }
7799	}
7800    }
7801    return ""
7802}
7803
7804# Check for production of a core file and remove it.  PID is the
7805# inferior's pid or -1 if not known.  TEST is the test's message.
7806
7807proc remove_core {pid {test ""}} {
7808    if {$test == ""} {
7809	set test "cleanup core file"
7810    }
7811
7812    set file [find_core_file $pid]
7813    if {$file != ""} {
7814	remote_file host delete $file
7815	pass "$test (removed)"
7816    } else {
7817	pass "$test (not found)"
7818    }
7819}
7820
7821proc core_find {binfile {deletefiles {}} {arg ""}} {
7822    global objdir subdir
7823
7824    set destcore "$binfile.core"
7825    file delete $destcore
7826
7827    # Create a core file named "$destcore" rather than just "core", to
7828    # avoid problems with sys admin types that like to regularly prune all
7829    # files named "core" from the system.
7830    #
7831    # Arbitrarily try setting the core size limit to "unlimited" since
7832    # this does not hurt on systems where the command does not work and
7833    # allows us to generate a core on systems where it does.
7834    #
7835    # Some systems append "core" to the name of the program; others append
7836    # the name of the program to "core"; still others (like Linux, as of
7837    # May 2003) create cores named "core.PID".  In the latter case, we
7838    # could have many core files lying around, and it may be difficult to
7839    # tell which one is ours, so let's run the program in a subdirectory.
7840    set found 0
7841    set coredir [standard_output_file coredir.[getpid]]
7842    file mkdir $coredir
7843    catch "system \"(cd ${coredir}; ulimit -c unlimited; ${binfile} ${arg}; true) >/dev/null 2>&1\""
7844    #      remote_exec host "${binfile}"
7845    foreach i "${coredir}/core ${coredir}/core.coremaker.c ${binfile}.core" {
7846	if [remote_file build exists $i] {
7847	    remote_exec build "mv $i $destcore"
7848	    set found 1
7849	}
7850    }
7851    # Check for "core.PID", "core.EXEC.PID.HOST.TIME", etc.  It's fine
7852    # to use a glob here as we're looking inside a directory we
7853    # created.  Also, this procedure only works on non-remote hosts.
7854    if { $found == 0 } {
7855	set names [glob -nocomplain -directory $coredir core.*]
7856	if {[llength $names] == 1} {
7857	    set corefile [file join $coredir [lindex $names 0]]
7858	    remote_exec build "mv $corefile $destcore"
7859	    set found 1
7860	}
7861    }
7862    if { $found == 0 } {
7863	# The braindamaged HPUX shell quits after the ulimit -c above
7864	# without executing ${binfile}.  So we try again without the
7865	# ulimit here if we didn't find a core file above.
7866	# Oh, I should mention that any "braindamaged" non-Unix system has
7867	# the same problem. I like the cd bit too, it's really neat'n stuff.
7868	catch "system \"(cd ${objdir}/${subdir}; ${binfile}; true) >/dev/null 2>&1\""
7869	foreach i "${objdir}/${subdir}/core ${objdir}/${subdir}/core.coremaker.c ${binfile}.core" {
7870	    if [remote_file build exists $i] {
7871		remote_exec build "mv $i $destcore"
7872		set found 1
7873	    }
7874	}
7875    }
7876
7877    # Try to clean up after ourselves.
7878    foreach deletefile $deletefiles {
7879	remote_file build delete [file join $coredir $deletefile]
7880    }
7881    remote_exec build "rmdir $coredir"
7882
7883    if { $found == 0  } {
7884	warning "can't generate a core file - core tests suppressed - check ulimit -c"
7885	return ""
7886    }
7887    return $destcore
7888}
7889
7890# gdb_target_symbol_prefix compiles a test program and then examines
7891# the output from objdump to determine the prefix (such as underscore)
7892# for linker symbol prefixes.
7893
7894gdb_caching_proc gdb_target_symbol_prefix {
7895    # Compile a simple test program...
7896    set src { int main() { return 0; } }
7897    if {![gdb_simple_compile target_symbol_prefix $src executable]} {
7898        return 0
7899    }
7900
7901    set prefix ""
7902
7903    set objdump_program [gdb_find_objdump]
7904    set result [catch "exec $objdump_program --syms $obj" output]
7905
7906    if { $result == 0 \
7907	&& ![regexp -lineanchor \
7908	     { ([^ a-zA-Z0-9]*)main$} $output dummy prefix] } {
7909	verbose "gdb_target_symbol_prefix: Could not find main in objdump output; returning null prefix" 2
7910    }
7911
7912    file delete $obj
7913
7914    return $prefix
7915}
7916
7917# Return 1 if target supports scheduler locking, otherwise return 0.
7918
7919gdb_caching_proc target_supports_scheduler_locking {
7920    global gdb_prompt
7921
7922    set me "gdb_target_supports_scheduler_locking"
7923
7924    set src { int main() { return 0; } }
7925    if {![gdb_simple_compile $me $src executable]} {
7926        return 0
7927    }
7928
7929    clean_restart $obj
7930    if ![runto_main] {
7931        return 0
7932    }
7933
7934    set supports_schedule_locking -1
7935    set current_schedule_locking_mode ""
7936
7937    set test "reading current scheduler-locking mode"
7938    gdb_test_multiple "show scheduler-locking" $test {
7939	-re "Mode for locking scheduler during execution is \"(\[\^\"\]*)\".*$gdb_prompt" {
7940	    set current_schedule_locking_mode $expect_out(1,string)
7941	}
7942	-re "$gdb_prompt $" {
7943	    set supports_schedule_locking 0
7944	}
7945	timeout {
7946	    set supports_schedule_locking 0
7947	}
7948    }
7949
7950    if { $supports_schedule_locking == -1 } {
7951	set test "checking for scheduler-locking support"
7952	gdb_test_multiple "set scheduler-locking $current_schedule_locking_mode" $test {
7953	    -re "Target '\[^'\]+' cannot support this command\..*$gdb_prompt $" {
7954		set supports_schedule_locking 0
7955	    }
7956	    -re "$gdb_prompt $" {
7957		set supports_schedule_locking 1
7958	    }
7959	    timeout {
7960		set supports_schedule_locking 0
7961	    }
7962	}
7963    }
7964
7965    if { $supports_schedule_locking == -1 } {
7966	set supports_schedule_locking 0
7967    }
7968
7969    gdb_exit
7970    remote_file build delete $obj
7971    verbose "$me:  returning $supports_schedule_locking" 2
7972    return $supports_schedule_locking
7973}
7974
7975# Return 1 if compiler supports use of nested functions.  Otherwise,
7976# return 0.
7977
7978gdb_caching_proc support_nested_function_tests {
7979    # Compile a test program containing a nested function
7980    return [gdb_can_simple_compile nested_func {
7981	int main () {
7982	    int foo () {
7983	        return 0;
7984	    }
7985	    return foo ();
7986	}
7987    } executable]
7988}
7989
7990# gdb_target_symbol returns the provided symbol with the correct prefix
7991# prepended.  (See gdb_target_symbol_prefix, above.)
7992
7993proc gdb_target_symbol { symbol } {
7994  set prefix [gdb_target_symbol_prefix]
7995  return "${prefix}${symbol}"
7996}
7997
7998# gdb_target_symbol_prefix_flags_asm returns a string that can be
7999# added to gdb_compile options to define the C-preprocessor macro
8000# SYMBOL_PREFIX with a value that can be prepended to symbols
8001# for targets which require a prefix, such as underscore.
8002#
8003# This version (_asm) defines the prefix without double quotes
8004# surrounding the prefix.  It is used to define the macro
8005# SYMBOL_PREFIX for assembly language files.  Another version, below,
8006# is used for symbols in inline assembler in C/C++ files.
8007#
8008# The lack of quotes in this version (_asm) makes it possible to
8009# define supporting macros in the .S file.  (The version which
8010# uses quotes for the prefix won't work for such files since it's
8011# impossible to define a quote-stripping macro in C.)
8012#
8013# It's possible to use this version (_asm) for C/C++ source files too,
8014# but a string is usually required in such files; providing a version
8015# (no _asm) which encloses the prefix with double quotes makes it
8016# somewhat easier to define the supporting macros in the test case.
8017
8018proc gdb_target_symbol_prefix_flags_asm {} {
8019    set prefix [gdb_target_symbol_prefix]
8020    if {$prefix ne ""} {
8021	return "additional_flags=-DSYMBOL_PREFIX=$prefix"
8022    } else {
8023	return "";
8024    }
8025}
8026
8027# gdb_target_symbol_prefix_flags returns the same string as
8028# gdb_target_symbol_prefix_flags_asm, above, but with the prefix
8029# enclosed in double quotes if there is a prefix.
8030#
8031# See the comment for gdb_target_symbol_prefix_flags_asm for an
8032# extended discussion.
8033
8034proc gdb_target_symbol_prefix_flags {} {
8035    set prefix [gdb_target_symbol_prefix]
8036    if {$prefix ne ""} {
8037	return "additional_flags=-DSYMBOL_PREFIX=\"$prefix\""
8038    } else {
8039	return "";
8040    }
8041}
8042
8043# A wrapper for 'remote_exec host' that passes or fails a test.
8044# Returns 0 if all went well, nonzero on failure.
8045# TEST is the name of the test, other arguments are as for remote_exec.
8046
8047proc run_on_host { test program args } {
8048    verbose -log "run_on_host: $program $args"
8049    # remote_exec doesn't work properly if the output is set but the
8050    # input is the empty string -- so replace an empty input with
8051    # /dev/null.
8052    if {[llength $args] > 1 && [lindex $args 1] == ""} {
8053	set args [lreplace $args 1 1 "/dev/null"]
8054    }
8055    set result [eval remote_exec host [list $program] $args]
8056    verbose "result is $result"
8057    set status [lindex $result 0]
8058    set output [lindex $result 1]
8059    if {$status == 0} {
8060 	pass $test
8061 	return 0
8062    } else {
8063	verbose -log "run_on_host failed: $output"
8064	if { $output == "spawn failed" } {
8065	    unsupported $test
8066	} else {
8067	    fail $test
8068	}
8069	return -1
8070    }
8071}
8072
8073# Return non-zero if "board_info debug_flags" mentions Fission.
8074# http://gcc.gnu.org/wiki/DebugFission
8075# Fission doesn't support everything yet.
8076# This supports working around bug 15954.
8077
8078proc using_fission { } {
8079    set debug_flags [board_info [target_info name] debug_flags]
8080    return [regexp -- "-gsplit-dwarf" $debug_flags]
8081}
8082
8083# Search LISTNAME in uplevel LEVEL caller and set variables according to the
8084# list of valid options with prefix PREFIX described by ARGSET.
8085#
8086# The first member of each one- or two-element list in ARGSET defines the
8087# name of a variable that will be added to the caller's scope.
8088#
8089# If only one element is given to describe an option, it the value is
8090# 0 if the option is not present in (the caller's) ARGS or 1 if
8091# it is.
8092#
8093# If two elements are given, the second element is the default value of
8094# the variable.  This is then overwritten if the option exists in ARGS.
8095# If EVAL, then subst is called on the value, which allows variables
8096# to be used.
8097#
8098# Any parse_args elements in (the caller's) ARGS will be removed, leaving
8099# any optional components.
8100#
8101# Example:
8102# proc myproc {foo args} {
8103#   parse_list args 1 {{bar} {baz "abc"} {qux}} "-" false
8104#    # ...
8105# }
8106# myproc ABC -bar -baz DEF peanut butter
8107# will define the following variables in myproc:
8108# foo (=ABC), bar (=1), baz (=DEF), and qux (=0)
8109# args will be the list {peanut butter}
8110
8111proc parse_list { level listname argset prefix eval } {
8112    upvar $level $listname args
8113
8114    foreach argument $argset {
8115	if {[llength $argument] == 1} {
8116	    # Normalize argument, strip leading/trailing whitespace.
8117	    # Allows us to treat {foo} and { foo } the same.
8118	    set argument [string trim $argument]
8119
8120	    # No default specified, so we assume that we should set
8121	    # the value to 1 if the arg is present and 0 if it's not.
8122	    # It is assumed that no value is given with the argument.
8123	    set pattern "$prefix$argument"
8124	    set result [lsearch -exact $args $pattern]
8125
8126	    if {$result != -1} {
8127		set value 1
8128		set args [lreplace $args $result $result]
8129	    } else {
8130		set value 0
8131	    }
8132	    uplevel $level [list set $argument $value]
8133	} elseif {[llength $argument] == 2} {
8134	    # There are two items in the argument.  The second is a
8135	    # default value to use if the item is not present.
8136	    # Otherwise, the variable is set to whatever is provided
8137	    # after the item in the args.
8138	    set arg [lindex $argument 0]
8139	    set pattern "$prefix[lindex $arg 0]"
8140	    set result [lsearch -exact $args $pattern]
8141
8142	    if {$result != -1} {
8143		set value [lindex $args [expr $result+1]]
8144		if { $eval } {
8145		    set value [uplevel [expr $level + 1] [list subst $value]]
8146		}
8147		set args [lreplace $args $result [expr $result+1]]
8148	    } else {
8149		set value [lindex $argument 1]
8150		if { $eval } {
8151		    set value [uplevel $level [list subst $value]]
8152		}
8153	    }
8154	    uplevel $level [list set $arg $value]
8155	} else {
8156	    error "Badly formatted argument \"$argument\" in argument set"
8157	}
8158    }
8159}
8160
8161# Search the caller's args variable and set variables according to the list of
8162# valid options described by ARGSET.
8163
8164proc parse_args { argset } {
8165    parse_list 2 args $argset "-" false
8166
8167    # The remaining args should be checked to see that they match the
8168    # number of items expected to be passed into the procedure...
8169}
8170
8171# Process the caller's options variable and set variables according
8172# to the list of valid options described by OPTIONSET.
8173
8174proc parse_options { optionset } {
8175    parse_list 2 options $optionset "" true
8176
8177    # Require no remaining options.
8178    upvar 1 options options
8179    if { [llength $options] != 0 } {
8180	error "Options left unparsed: $options"
8181    }
8182}
8183
8184# Capture the output of COMMAND in a string ignoring PREFIX (a regexp);
8185# return that string.
8186
8187proc capture_command_output { command prefix } {
8188    global gdb_prompt
8189    global expect_out
8190
8191    set test "capture_command_output for $command"
8192
8193    set output_string ""
8194    gdb_test_multiple $command $test {
8195	-re "^(\[^\r\n\]+\r\n)" {
8196	    if { ![string equal $output_string ""] } {
8197		set output_string [join [list $output_string $expect_out(1,string)] ""]
8198	    } else {
8199		set output_string $expect_out(1,string)
8200	    }
8201	    exp_continue
8202	}
8203
8204	-re "^$gdb_prompt $" {
8205	}
8206    }
8207
8208    # Strip the command.
8209    set command_re [string_to_regexp ${command}]
8210    set output_string [regsub ^$command_re\r\n $output_string ""]
8211
8212    # Strip the prefix.
8213    if { $prefix != "" } {
8214	set output_string [regsub ^$prefix $output_string ""]
8215    }
8216
8217    # Strip a trailing newline.
8218    set output_string [regsub "\r\n$" $output_string ""]
8219
8220    return $output_string
8221}
8222
8223# A convenience function that joins all the arguments together, with a
8224# regexp that matches exactly one end of line in between each argument.
8225# This function is ideal to write the expected output of a GDB command
8226# that generates more than a couple of lines, as this allows us to write
8227# each line as a separate string, which is easier to read by a human
8228# being.
8229
8230proc multi_line { args } {
8231    if { [llength $args] == 1 } {
8232	set hint "forgot {*} before list argument?"
8233	error "multi_line called with one argument ($hint)"
8234    }
8235    return [join $args "\r\n"]
8236}
8237
8238# Similar to the above, but while multi_line is meant to be used to
8239# match GDB output, this one is meant to be used to build strings to
8240# send as GDB input.
8241
8242proc multi_line_input { args } {
8243    return [join $args "\n"]
8244}
8245
8246# Return how many newlines there are in the given string.
8247
8248proc count_newlines { string } {
8249    return [regexp -all "\n" $string]
8250}
8251
8252# Return the version of the DejaGnu framework.
8253#
8254# The return value is a list containing the major, minor and patch version
8255# numbers.  If the version does not contain a minor or patch number, they will
8256# be set to 0.  For example:
8257#
8258#   1.6   -> {1 6 0}
8259#   1.6.1 -> {1 6 1}
8260#   2     -> {2 0 0}
8261
8262proc dejagnu_version { } {
8263    # The frame_version variable is defined by DejaGnu, in runtest.exp.
8264    global frame_version
8265
8266    verbose -log "DejaGnu version: $frame_version"
8267    verbose -log "Expect version: [exp_version]"
8268    verbose -log "Tcl version: [info tclversion]"
8269
8270    set dg_ver [split $frame_version .]
8271
8272    while { [llength $dg_ver] < 3 } {
8273	lappend dg_ver 0
8274    }
8275
8276    return $dg_ver
8277}
8278
8279# Define user-defined command COMMAND using the COMMAND_LIST as the
8280# command's definition.  The terminating "end" is added automatically.
8281
8282proc gdb_define_cmd {command command_list} {
8283    global gdb_prompt
8284
8285    set input [multi_line_input {*}$command_list "end"]
8286    set test "define $command"
8287
8288    gdb_test_multiple "define $command" $test {
8289	-re "End with"  {
8290	    gdb_test_multiple $input $test {
8291		-re "\r\n$gdb_prompt " {
8292		}
8293	    }
8294	}
8295    }
8296}
8297
8298# Override the 'cd' builtin with a version that ensures that the
8299# log file keeps pointing at the same file.  We need this because
8300# unfortunately the path to the log file is recorded using an
8301# relative path name, and, we sometimes need to close/reopen the log
8302# after changing the current directory.  See get_compiler_info.
8303
8304rename cd builtin_cd
8305
8306proc cd { dir } {
8307
8308    # Get the existing log file flags.
8309    set log_file_info [log_file -info]
8310
8311    # Split the flags into args and file name.
8312    set log_file_flags ""
8313    set log_file_file ""
8314    foreach arg [ split "$log_file_info" " "] {
8315	if [string match "-*" $arg] {
8316	    lappend log_file_flags $arg
8317	} else {
8318	    lappend log_file_file $arg
8319	}
8320    }
8321
8322    # If there was an existing file, ensure it is an absolute path, and then
8323    # reset logging.
8324    if { $log_file_file != "" } {
8325	set log_file_file [file normalize $log_file_file]
8326	log_file
8327	log_file $log_file_flags "$log_file_file"
8328    }
8329
8330    # Call the builtin version of cd.
8331    builtin_cd $dir
8332}
8333
8334# Return a list of all languages supported by GDB, suitable for use in
8335# 'set language NAME'.  This doesn't include either the 'local' or
8336# 'auto' keywords.
8337proc gdb_supported_languages {} {
8338    return [list c objective-c c++ d go fortran modula-2 asm pascal \
8339		opencl rust minimal ada]
8340}
8341
8342# Check if debugging is enabled for gdb.
8343
8344proc gdb_debug_enabled { } {
8345    global gdbdebug
8346
8347    # If not already read, get the debug setting from environment or board setting.
8348    if {![info exists gdbdebug]} {
8349	global env
8350	if [info exists env(GDB_DEBUG)] {
8351	    set gdbdebug $env(GDB_DEBUG)
8352	} elseif [target_info exists gdb,debug] {
8353	    set gdbdebug [target_info gdb,debug]
8354	} else {
8355	    return 0
8356	}
8357    }
8358
8359    # Ensure it not empty.
8360    return [expr { $gdbdebug != "" }]
8361}
8362
8363# Turn on debugging if enabled, or reset if already on.
8364
8365proc gdb_debug_init { } {
8366
8367    global gdb_prompt
8368
8369    if ![gdb_debug_enabled] {
8370      return;
8371    }
8372
8373    # First ensure logging is off.
8374    send_gdb "set logging enabled off\n"
8375
8376    set debugfile [standard_output_file gdb.debug]
8377    send_gdb "set logging file $debugfile\n"
8378
8379    send_gdb "set logging debugredirect\n"
8380
8381    global gdbdebug
8382    foreach entry [split $gdbdebug ,] {
8383      send_gdb "set debug $entry 1\n"
8384    }
8385
8386    # Now that everything is set, enable logging.
8387    send_gdb "set logging enabled on\n"
8388    gdb_expect 10 {
8389	-re "Copying output to $debugfile.*Redirecting debug output to $debugfile.*$gdb_prompt $" {}
8390	timeout { warning "Couldn't set logging file" }
8391    }
8392}
8393
8394# Check if debugging is enabled for gdbserver.
8395
8396proc gdbserver_debug_enabled { } {
8397    # Always disabled for GDB only setups.
8398    return 0
8399}
8400
8401# Open the file for logging gdb input
8402
8403proc gdb_stdin_log_init { } {
8404    gdb_persistent_global in_file
8405
8406    if {[info exists in_file]} {
8407      # Close existing file.
8408      catch "close $in_file"
8409    }
8410
8411    set logfile [standard_output_file_with_gdb_instance gdb.in]
8412    set in_file [open $logfile w]
8413}
8414
8415# Write to the file for logging gdb input.
8416# TYPE can be one of the following:
8417# "standard" : Default. Standard message written to the log
8418# "answer" : Answer to a question (eg "Y"). Not written the log.
8419# "optional" : Optional message. Not written to the log.
8420
8421proc gdb_stdin_log_write { message {type standard} } {
8422
8423    global in_file
8424    if {![info exists in_file]} {
8425      return
8426    }
8427
8428    # Check message types.
8429    switch -regexp -- $type {
8430        "answer" {
8431            return
8432        }
8433        "optional" {
8434            return
8435        }
8436    }
8437
8438    # Write to the log and make sure the output is there, even in case
8439    # of crash.
8440    puts -nonewline $in_file "$message"
8441    flush $in_file
8442}
8443
8444# Write the command line used to invocate gdb to the cmd file.
8445
8446proc gdb_write_cmd_file { cmdline } {
8447    set logfile [standard_output_file_with_gdb_instance gdb.cmd]
8448    set cmd_file [open $logfile w]
8449    puts $cmd_file $cmdline
8450    catch "close $cmd_file"
8451}
8452
8453# Compare contents of FILE to string STR.  Pass with MSG if equal, otherwise
8454# fail with MSG.
8455
8456proc cmp_file_string { file str msg } {
8457    if { ![file exists $file]} {
8458	fail "$msg"
8459	return
8460    }
8461
8462    set caught_error [catch {
8463	set fp [open "$file" r]
8464	set file_contents [read $fp]
8465	close $fp
8466    } error_message]
8467    if {$caught_error} {
8468	error "$error_message"
8469	fail "$msg"
8470	return
8471    }
8472
8473    if { $file_contents == $str } {
8474	pass "$msg"
8475    } else {
8476	fail "$msg"
8477    }
8478}
8479
8480# Compare FILE1 and FILE2 as binary files.  Return 0 if the files are
8481# equal, otherwise, return non-zero.
8482
8483proc cmp_binary_files { file1 file2 } {
8484    set fd1 [open $file1]
8485    fconfigure $fd1 -translation binary
8486    set fd2 [open $file2]
8487    fconfigure $fd2 -translation binary
8488
8489    set blk_size 1024
8490    while {true} {
8491	set blk1 [read $fd1 $blk_size]
8492	set blk2 [read $fd2 $blk_size]
8493	set diff [string compare $blk1 $blk2]
8494	if {$diff != 0 || [eof $fd1] || [eof $fd2]} {
8495	    close $fd1
8496	    close $fd2
8497	    return $diff
8498	}
8499    }
8500}
8501
8502# Does the compiler support CTF debug output using '-gctf' compiler
8503# flag?  If not then we should skip these tests.  We should also
8504# skip them if libctf was explicitly disabled.
8505
8506gdb_caching_proc skip_ctf_tests {
8507    global enable_libctf
8508
8509    if {$enable_libctf eq "no"} {
8510	return 1
8511    }
8512
8513    set can_ctf [gdb_can_simple_compile ctfdebug {
8514	int main () {
8515	    return 0;
8516	}
8517    } executable "additional_flags=-gctf"]
8518
8519    return [expr {!$can_ctf}]
8520}
8521
8522# Return 1 if compiler supports -gstatement-frontiers.  Otherwise,
8523# return 0.
8524
8525gdb_caching_proc supports_statement_frontiers {
8526    return [gdb_can_simple_compile supports_statement_frontiers {
8527	int main () {
8528	    return 0;
8529	}
8530    } executable "additional_flags=-gstatement-frontiers"]
8531}
8532
8533# Return 1 if compiler supports -mmpx -fcheck-pointer-bounds.  Otherwise,
8534# return 0.
8535
8536gdb_caching_proc supports_mpx_check_pointer_bounds {
8537    set flags "additional_flags=-mmpx additional_flags=-fcheck-pointer-bounds"
8538    return [gdb_can_simple_compile supports_mpx_check_pointer_bounds {
8539	int main () {
8540	    return 0;
8541	}
8542    } executable $flags]
8543}
8544
8545# Return 1 if compiler supports -fcf-protection=.  Otherwise,
8546# return 0.
8547
8548gdb_caching_proc supports_fcf_protection {
8549    return [gdb_can_simple_compile supports_fcf_protection {
8550	int main () {
8551	    return 0;
8552	}
8553  } executable "additional_flags=-fcf-protection=full"]
8554}
8555
8556# Return true if symbols were read in using -readnow.  Otherwise,
8557# return false.
8558
8559proc readnow { } {
8560    return [expr {[lsearch -exact $::GDBFLAGS -readnow] != -1
8561		  || [lsearch -exact $::GDBFLAGS --readnow] != -1}]
8562}
8563
8564# Return index name if symbols were read in using an index.
8565# Otherwise, return "".
8566
8567proc have_index { objfile } {
8568
8569    set res ""
8570    set cmd "maint print objfiles $objfile"
8571    gdb_test_multiple $cmd "" -lbl {
8572	-re "\r\n.gdb_index: faked for \"readnow\"" {
8573	    set res ""
8574	    exp_continue
8575	}
8576	-re "\r\n.gdb_index:" {
8577	    set res "gdb_index"
8578	    exp_continue
8579	}
8580	-re "\r\n.debug_names:" {
8581	    set res "debug_names"
8582	    exp_continue
8583	}
8584	-re -wrap "" {
8585	    # We don't care about any other input.
8586	}
8587    }
8588
8589    return $res
8590}
8591
8592# Return 1 if partial symbols are available.  Otherwise, return 0.
8593
8594proc psymtabs_p {  } {
8595    global gdb_prompt
8596
8597    set cmd "maint info psymtab"
8598    gdb_test_multiple $cmd "" {
8599	-re "$cmd\r\n$gdb_prompt $" {
8600	    return 0
8601	}
8602	-re -wrap "" {
8603	    return 1
8604	}
8605    }
8606
8607    return 0
8608}
8609
8610# Verify that partial symtab expansion for $filename has state $readin.
8611
8612proc verify_psymtab_expanded { filename readin } {
8613    global gdb_prompt
8614
8615    set cmd "maint info psymtab"
8616    set test "$cmd: $filename: $readin"
8617    set re [multi_line \
8618		"  \{ psymtab \[^\r\n\]*$filename\[^\r\n\]*" \
8619		"    readin $readin" \
8620		".*"]
8621
8622    gdb_test_multiple $cmd $test {
8623	-re "$cmd\r\n$gdb_prompt $" {
8624	    unsupported $gdb_test_name
8625	}
8626	-re -wrap $re {
8627	    pass $gdb_test_name
8628	}
8629    }
8630}
8631
8632# Add a .gdb_index section to PROGRAM.
8633# PROGRAM is assumed to be the output of standard_output_file.
8634# Returns the 0 if there is a failure, otherwise 1.
8635#
8636# STYLE controls which style of index to add, if needed.  The empty
8637# string (the default) means .gdb_index; "-dwarf-5" means .debug_names.
8638
8639proc add_gdb_index { program {style ""} } {
8640    global srcdir GDB env
8641    set contrib_dir "$srcdir/../contrib"
8642    set env(GDB) [append_gdb_data_directory_option $GDB]
8643    set result [catch "exec $contrib_dir/gdb-add-index.sh $style $program" output]
8644    if { $result != 0 } {
8645	verbose -log "result is $result"
8646	verbose -log "output is $output"
8647	return 0
8648    }
8649
8650    return 1
8651}
8652
8653# Add a .gdb_index section to PROGRAM, unless it alread has an index
8654# (.gdb_index/.debug_names).  Gdb doesn't support building an index from a
8655# program already using one.  Return 1 if a .gdb_index was added, return 0
8656# if it already contained an index, and -1 if an error occurred.
8657#
8658# STYLE controls which style of index to add, if needed.  The empty
8659# string (the default) means .gdb_index; "-dwarf-5" means .debug_names.
8660
8661proc ensure_gdb_index { binfile {style ""} } {
8662    global decimal
8663
8664    set testfile [file tail $binfile]
8665    set test "check if index present"
8666    set has_index 0
8667    set has_readnow 0
8668    gdb_test_multiple "mt print objfiles ${testfile}" $test -lbl {
8669	-re "\r\n\\.gdb_index: version ${decimal}(?=\r\n)" {
8670	    set has_index 1
8671	    gdb_test_lines "" $gdb_test_name ".*"
8672	}
8673	-re "\r\n\\.debug_names: exists(?=\r\n)" {
8674	    set has_index 1
8675	    gdb_test_lines "" $gdb_test_name ".*"
8676	}
8677	-re "\r\n(Cooked index in use|Psymtabs)(?=\r\n)" {
8678	    gdb_test_lines "" $gdb_test_name ".*"
8679	}
8680	-re ".gdb_index: faked for \"readnow\"" {
8681	    set has_readnow 1
8682	    gdb_test_lines "" $gdb_test_name ".*"
8683	}
8684	-re -wrap "" {
8685	    fail $gdb_test_name
8686	}
8687    }
8688
8689    if { $has_index } {
8690	return 0
8691    }
8692
8693    if { $has_readnow } {
8694	return -1
8695    }
8696
8697    if { [add_gdb_index $binfile $style] == "1" } {
8698	return 1
8699    }
8700
8701    return -1
8702}
8703
8704# Return 1 if executable contains .debug_types section.  Otherwise, return 0.
8705
8706proc debug_types { } {
8707    global hex
8708
8709    set cmd "maint info sections"
8710    gdb_test_multiple $cmd "" {
8711	-re -wrap "at $hex: .debug_types.*" {
8712	    return 1
8713	}
8714	-re -wrap "" {
8715	    return 0
8716	}
8717    }
8718
8719    return 0
8720}
8721
8722# Return the addresses in the line table for FILE for which is_stmt is true.
8723
8724proc is_stmt_addresses { file } {
8725    global decimal
8726    global hex
8727
8728    set is_stmt [list]
8729
8730    gdb_test_multiple "maint info line-table $file" "" {
8731	-re "\r\n$decimal\[ \t\]+$decimal\[ \t\]+($hex)\[ \t\]+Y\[^\r\n\]*" {
8732	    lappend is_stmt $expect_out(1,string)
8733	    exp_continue
8734	}
8735	-re -wrap "" {
8736	}
8737    }
8738
8739    return $is_stmt
8740}
8741
8742# Return 1 if hex number VAL is an element of HEXLIST.
8743
8744proc hex_in_list { val hexlist } {
8745    # Normalize val by removing 0x prefix, and leading zeros.
8746    set val [regsub ^0x $val ""]
8747    set val [regsub ^0+ $val "0"]
8748
8749    set re 0x0*$val
8750    set index [lsearch -regexp $hexlist $re]
8751    return [expr $index != -1]
8752}
8753
8754# Override proc NAME to proc OVERRIDE for the duration of the execution of
8755# BODY.
8756
8757proc with_override { name override body } {
8758    # Implementation note: It's possible to implement the override using
8759    # rename, like this:
8760    #   rename $name save_$name
8761    #   rename $override $name
8762    #   set code [catch {uplevel 1 $body} result]
8763    #   rename $name $override
8764    #   rename save_$name $name
8765    # but there are two issues here:
8766    # - the save_$name might clash with an existing proc
8767    # - the override is no longer available under its original name during
8768    #   the override
8769    # So, we use this more elaborate but cleaner mechanism.
8770
8771    # Save the old proc, if it exists.
8772    if { [info procs $name] != "" } {
8773	set old_args [info args $name]
8774	set old_body [info body $name]
8775	set existed true
8776    } else {
8777	set existed false
8778    }
8779
8780    # Install the override.
8781    set new_args [info args $override]
8782    set new_body [info body $override]
8783    eval proc $name {$new_args} {$new_body}
8784
8785    # Execute body.
8786    set code [catch {uplevel 1 $body} result]
8787
8788    # Restore old proc if it existed on entry, else delete it.
8789    if { $existed } {
8790	eval proc $name {$old_args} {$old_body}
8791    } else {
8792	rename $name ""
8793    }
8794
8795    # Return as appropriate.
8796    if { $code == 1 } {
8797        global errorInfo errorCode
8798        return -code error -errorinfo $errorInfo -errorcode $errorCode $result
8799    } elseif { $code > 1 } {
8800        return -code $code $result
8801    }
8802
8803    return $result
8804}
8805
8806# Setup tuiterm.exp environment.  To be used in test-cases instead of
8807# "load_lib tuiterm.exp".  Calls initialization function and schedules
8808# finalization function.
8809proc tuiterm_env { } {
8810    load_lib tuiterm.exp
8811}
8812
8813# Dejagnu has a version of note, but usage is not allowed outside of dejagnu.
8814# Define a local version.
8815proc gdb_note { message } {
8816    verbose -- "NOTE: $message" 0
8817}
8818
8819# Return 1 if compiler supports -fuse-ld=gold, otherwise return 0.
8820gdb_caching_proc have_fuse_ld_gold {
8821    set me "have_fuse_ld_gold"
8822    set flags "additional_flags=-fuse-ld=gold"
8823    set src { int main() { return 0; } }
8824    return [gdb_simple_compile $me $src executable $flags]
8825}
8826
8827# Return 1 if compiler supports fvar-tracking, otherwise return 0.
8828gdb_caching_proc have_fvar_tracking {
8829    set me "have_fvar_tracking"
8830    set flags "additional_flags=-fvar-tracking"
8831    set src { int main() { return 0; } }
8832    return [gdb_simple_compile $me $src executable $flags]
8833}
8834
8835# Return 1 if linker supports -Ttext-segment, otherwise return 0.
8836gdb_caching_proc linker_supports_Ttext_segment_flag {
8837    set me "linker_supports_Ttext_segment_flag"
8838    set flags ldflags="-Wl,-Ttext-segment=0x7000000"
8839    set src { int main() { return 0; } }
8840    return [gdb_simple_compile $me $src executable $flags]
8841}
8842
8843# Return 1 if linker supports -Ttext, otherwise return 0.
8844gdb_caching_proc linker_supports_Ttext_flag {
8845    set me "linker_supports_Ttext_flag"
8846    set flags ldflags="-Wl,-Ttext=0x7000000"
8847    set src { int main() { return 0; } }
8848    return [gdb_simple_compile $me $src executable $flags]
8849}
8850
8851# Return 1 if linker supports --image-base, otherwise 0.
8852gdb_caching_proc linker_supports_image_base_flag {
8853    set me "linker_supports_image_base_flag"
8854    set flags ldflags="-Wl,--image-base=0x7000000"
8855    set src { int main() { return 0; } }
8856    return [gdb_simple_compile $me $src executable $flags]
8857}
8858
8859
8860# Return 1 if compiler supports scalar_storage_order attribute, otherwise
8861# return 0.
8862gdb_caching_proc supports_scalar_storage_order_attribute {
8863    set me "supports_scalar_storage_order_attribute"
8864    set src {
8865	#include <string.h>
8866	struct sle {
8867	    int v;
8868	} __attribute__((scalar_storage_order("little-endian")));
8869	struct sbe {
8870	    int v;
8871	} __attribute__((scalar_storage_order("big-endian")));
8872	struct sle sle;
8873	struct sbe sbe;
8874	int main () {
8875	    sle.v = sbe.v = 0x11223344;
8876	    int same = memcmp (&sle, &sbe, sizeof (int)) == 0;
8877	    int sso = !same;
8878	    return sso;
8879	}
8880    }
8881    if { ![gdb_simple_compile $me $src executable ""] } {
8882	return 0
8883    }
8884
8885    set result [remote_exec target $obj]
8886    set status [lindex $result 0]
8887    set output [lindex $result 1]
8888    if { $output != "" } {
8889	return 0
8890    }
8891
8892    return $status
8893}
8894
8895# Return 1 if compiler supports __GNUC__, otherwise return 0.
8896gdb_caching_proc supports_gnuc {
8897    set me "supports_gnuc"
8898    set src {
8899	#ifndef __GNUC__
8900	#error "No gnuc"
8901	#endif
8902    }
8903    return [gdb_simple_compile $me $src object ""]
8904}
8905
8906# Return 1 if target supports mpx, otherwise return 0.
8907gdb_caching_proc have_mpx {
8908    global srcdir
8909
8910    set me "have_mpx"
8911    if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
8912        verbose "$me: target does not support mpx, returning 0" 2
8913        return 0
8914    }
8915
8916    # Compile a test program.
8917    set src {
8918       #include "nat/x86-cpuid.h"
8919
8920        int main() {
8921	  unsigned int eax, ebx, ecx, edx;
8922
8923	  if (!__get_cpuid (1, &eax, &ebx, &ecx, &edx))
8924	    return 0;
8925
8926	  if ((ecx & bit_OSXSAVE) == bit_OSXSAVE)
8927	    {
8928	      if (__get_cpuid_max (0, (void *)0) < 7)
8929		return 0;
8930
8931		__cpuid_count (7, 0, eax, ebx, ecx, edx);
8932
8933		if ((ebx & bit_MPX) == bit_MPX)
8934		  return 1;
8935
8936	    }
8937	  return 0;
8938	}
8939    }
8940    set compile_flags "incdir=${srcdir}/.."
8941    if {![gdb_simple_compile $me $src executable $compile_flags]} {
8942        return 0
8943    }
8944
8945    set result [remote_exec target $obj]
8946    set status [lindex $result 0]
8947    set output [lindex $result 1]
8948    if { $output != "" } {
8949	set status 0
8950    }
8951
8952    remote_file build delete $obj
8953
8954    if { $status == 0 } {
8955	verbose "$me:  returning $status" 2
8956	return $status
8957    }
8958
8959    # Compile program with -mmpx -fcheck-pointer-bounds, try to trigger
8960    # 'No MPX support', in other words, see if kernel supports mpx.
8961    set src { int main (void) { return 0; } }
8962    set comp_flags {}
8963    append comp_flags " additional_flags=-mmpx"
8964    append comp_flags " additional_flags=-fcheck-pointer-bounds"
8965    if {![gdb_simple_compile $me-2 $src executable $comp_flags]} {
8966        return 0
8967    }
8968
8969    set result [remote_exec target $obj]
8970    set status [lindex $result 0]
8971    set output [lindex $result 1]
8972    set status [expr ($status == 0) \
8973		    && ![regexp "^No MPX support\r?\n" $output]]
8974
8975    remote_file build delete $obj
8976
8977    verbose "$me:  returning $status" 2
8978    return $status
8979}
8980
8981# Return 1 if target supports avx, otherwise return 0.
8982gdb_caching_proc have_avx {
8983    global srcdir
8984
8985    set me "have_avx"
8986    if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
8987        verbose "$me: target does not support avx, returning 0" 2
8988        return 0
8989    }
8990
8991    # Compile a test program.
8992    set src {
8993       #include "nat/x86-cpuid.h"
8994
8995	int main() {
8996	  unsigned int eax, ebx, ecx, edx;
8997
8998	if (!x86_cpuid (1, &eax, &ebx, &ecx, &edx))
8999	  return 0;
9000
9001	if ((ecx & (bit_AVX | bit_OSXSAVE)) == (bit_AVX | bit_OSXSAVE))
9002	  return 1;
9003	else
9004	  return 0;
9005	}
9006    }
9007    set compile_flags "incdir=${srcdir}/.."
9008    if {![gdb_simple_compile $me $src executable $compile_flags]} {
9009        return 0
9010    }
9011
9012    set result [remote_exec target $obj]
9013    set status [lindex $result 0]
9014    set output [lindex $result 1]
9015    if { $output != "" } {
9016	set status 0
9017    }
9018
9019    remote_file build delete $obj
9020
9021    verbose "$me: returning $status" 2
9022    return $status
9023}
9024
9025# Called as either:
9026# - require EXPR VAL
9027# - require EXPR OP VAL
9028# In the first case, OP is ==.
9029#
9030# Require EXPR OP VAL, where EXPR is evaluated in caller context.  If not,
9031# return in the caller's context.
9032
9033proc require { fn arg1 {arg2 ""} } {
9034    if { $arg2 == "" } {
9035	set op ==
9036	set val $arg1
9037    } else {
9038	set op $arg1
9039	set val $arg2
9040    }
9041    set res [uplevel 1 $fn]
9042    if { [expr $res $op $val] } {
9043	return
9044    }
9045
9046    switch "$fn $op $val" {
9047	"gdb_skip_xml_test == 0" { set msg "missing xml support" }
9048	"ensure_gdb_index $binfile != -1" -
9049	"ensure_gdb_index $binfile -dwarf-5 != -1" {
9050	    set msg "Couldn't ensure index in binfile"
9051	}
9052	"use_gdb_stub == 0" {
9053	    set msg "Remote stub used"
9054	}
9055	default { set msg "$fn != $val" }
9056    }
9057
9058    untested $msg
9059    return -code return 0
9060}
9061
9062# Wait up to ::TIMEOUT seconds for file PATH to exist on the target system.
9063# Return 1 if it does exist, 0 otherwise.
9064
9065proc target_file_exists_with_timeout { path } {
9066    for {set i 0} {$i < $::timeout} {incr i} {
9067	if { [remote_file target exists $path] } {
9068	    return 1
9069	}
9070
9071	sleep 1
9072    }
9073
9074    return 0
9075}
9076
9077gdb_caching_proc has_hw_wp_support {
9078    # Power 9, proc rev 2.2 does not support HW watchpoints due to HW bug.
9079    # Need to use a runtime test to determine if the Power processor has
9080    # support for HW watchpoints.
9081    global srcdir subdir gdb_prompt inferior_exited_re
9082
9083    set me "has_hw_wp_support"
9084
9085    global gdb_spawn_id
9086    if { [info exists gdb_spawn_id] } {
9087	error "$me called with running gdb instance"
9088    }
9089
9090    set compile_flags {debug nowarnings quiet}
9091
9092    # Compile a test program to test if HW watchpoints are supported
9093    set src {
9094	int main (void) {
9095	    volatile int local;
9096	    local = 1;
9097	    if (local == 1)
9098		return 1;
9099	    return 0;
9100	}
9101    }
9102
9103    if {![gdb_simple_compile $me $src executable $compile_flags]} {
9104        return 0
9105    }
9106
9107    gdb_start
9108    gdb_reinitialize_dir $srcdir/$subdir
9109    gdb_load "$obj"
9110
9111    if ![runto_main] {
9112	gdb_exit
9113	remote_file build delete $obj
9114
9115	set has_hw_wp_support 0
9116	return $has_hw_wp_support
9117    }
9118
9119    # The goal is to determine if HW watchpoints are available in general.
9120    # Use "watch" and then check if gdb responds with hardware watch point.
9121    set test "watch local"
9122
9123    gdb_test_multiple  $test "Check for HW watchpoint support" {
9124	-re ".*Hardware watchpoint.*" {
9125	    #  HW watchpoint supported by platform
9126	    verbose -log "\n$me: Hardware watchpoint detected"
9127            set has_hw_wp_support 1
9128	}
9129	-re ".*$gdb_prompt $" {
9130	    set has_hw_wp_support 0
9131	    verbose -log "\n$me: Default, hardware watchpoint not deteced"
9132	}
9133    }
9134
9135    gdb_exit
9136    remote_file build delete $obj
9137
9138    verbose "$me: returning $has_hw_wp_support" 2
9139    return $has_hw_wp_support
9140}
9141
9142# Return a list of all the accepted values of the set command
9143# "SET_CMD SET_ARG".
9144# For example get_set_option_choices "set architecture" "i386".
9145
9146proc get_set_option_choices { set_cmd {set_arg ""} } {
9147    set values {}
9148
9149    if { $set_arg == "" } {
9150	# Add trailing space to signal that we need completion of the choices,
9151	# not of set_cmd itself.
9152	set cmd "complete $set_cmd "
9153    } else {
9154	set cmd "complete $set_cmd $set_arg"
9155    }
9156
9157    # Set test name without trailing space.
9158    set test [string trim $cmd]
9159
9160    with_set max-completions unlimited {
9161	gdb_test_multiple $cmd $test {
9162	    -re "^[string_to_regexp $cmd]\r\n" {
9163		exp_continue
9164	    }
9165
9166	    -re "^$set_cmd (\[^\r\n\]+)\r\n" {
9167		lappend values $expect_out(1,string)
9168		exp_continue
9169	    }
9170
9171	    -re "^$::gdb_prompt $" {
9172		pass $gdb_test_name
9173	    }
9174	}
9175    }
9176
9177    return $values
9178}
9179
9180# Return the compiler that can generate 32-bit ARM executables.  Used
9181# when testing biarch support on Aarch64.  If ARM_CC_FOR_TARGET is
9182# set, use that.  If not, try a few common compiler names, making sure
9183# that the executable they produce can run.
9184
9185gdb_caching_proc arm_cc_for_target {
9186    if {[info exists ::ARM_CC_FOR_TARGET]} {
9187	# If the user specified the compiler explicitly, then don't
9188	# check whether the resulting binary runs outside GDB.  Assume
9189	# that it does, and if it turns out it doesn't, then the user
9190	# should get loud FAILs, instead of UNSUPPORTED.
9191	return $::ARM_CC_FOR_TARGET
9192    }
9193
9194    # Fallback to a few common compiler names.  Also confirm the
9195    # produced binary actually runs on the system before declaring
9196    # we've found the right compiler.
9197
9198    if [istarget "*-linux*-*"] {
9199	set compilers {
9200	    arm-linux-gnueabi-gcc
9201	    arm-none-linux-gnueabi-gcc
9202	    arm-linux-gnueabihf-gcc
9203	}
9204    } else {
9205	set compilers {}
9206    }
9207
9208    foreach compiler $compilers {
9209	if {![is_remote host] && [which $compiler] == 0} {
9210	    # Avoid "default_target_compile: Can't find
9211	    # $compiler." warning issued from gdb_compile.
9212	    continue
9213	}
9214
9215	set src { int main() { return 0; } }
9216	if {[gdb_simple_compile aarch64-32bit \
9217		 $src \
9218		 executable [list compiler=$compiler]]} {
9219
9220	    set result [remote_exec target $obj]
9221	    set status [lindex $result 0]
9222	    set output [lindex $result 1]
9223
9224	    file delete $obj
9225
9226	    if { $output == "" && $status == 0} {
9227		return $compiler
9228	    }
9229	}
9230    }
9231
9232    return ""
9233}
9234
9235# Step until the pattern REGEXP is found.  Step at most
9236# MAX_STEPS times, but stop stepping once REGEXP is found.
9237#
9238# If REGEXP is found then a single pass is emitted, otherwise, after
9239# MAX_STEPS steps, a single fail is emitted.
9240#
9241# TEST_NAME is the name used in the pass/fail calls.
9242
9243proc gdb_step_until { regexp {test_name ""} {max_steps 10} } {
9244    if { $test_name == "" } {
9245	set test_name "stepping until regexp"
9246    }
9247
9248    set count 0
9249    gdb_test_multiple "step" "$test_name" {
9250	-re "$regexp\r\n$::gdb_prompt $" {
9251	    pass $test_name
9252	}
9253	-re ".*$::gdb_prompt $" {
9254	    if {$count < $max_steps} {
9255		incr count
9256		send_gdb "step\n"
9257		exp_continue
9258	    } else {
9259		fail $test_name
9260	    }
9261	}
9262    }
9263}
9264
9265# Check if the compiler emits epilogue information associated
9266# with the closing brace or with the last statement line.
9267#
9268# This proc restarts GDB
9269#
9270# Returns True if it is associated with the closing brace,
9271# False if it is the last statement
9272gdb_caching_proc have_epilogue_line_info {
9273
9274    set main {
9275	int
9276	main ()
9277	{
9278	    return 0;
9279	}
9280    }
9281    if {![gdb_simple_compile "simple_program" $main]} {
9282	 return False
9283    }
9284
9285    clean_restart $obj
9286
9287    gdb_test_multiple "info line 6" "epilogue test" {
9288	-re -wrap ".*starts at address.*and ends at.*" {
9289	    return True
9290	}
9291	-re -wrap ".*" {
9292	    return False
9293	}
9294    }
9295}
9296
9297# Decompress file BZ2, and return it.
9298
9299proc decompress_bz2 { bz2 } {
9300    set copy [standard_output_file [file tail $bz2]]
9301    set copy [remote_download build $bz2 $copy]
9302    if { $copy == "" } {
9303	return $copy
9304    }
9305
9306    set res [remote_exec build "bzip2" "-df $copy"]
9307    if { [lindex $res 0] == -1 } {
9308	return ""
9309    }
9310
9311    set copy [regsub {.bz2$} $copy ""]
9312    if { ![remote_file build exists $copy] } {
9313	return ""
9314    }
9315
9316    return $copy
9317}
9318
9319# Always load compatibility stuff.
9320load_lib future.exp
9321