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