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