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