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