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