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