]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/testsuite/lib/gdb.exp
Adjust gdb_continue_to_end for Windows
[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
c7a2ee64
PA
4716# Returns true if gdb_protocol is empty, indicating use of the native
4717# target.
4718
4719proc gdb_protocol_is_native { } {
4720 return [expr {[target_info gdb_protocol] == ""}]
4721}
4722
5fec7411
PA
4723# Returns true if gdb_protocol is either "remote" or
4724# "extended-remote".
4725
4726proc gdb_protocol_is_remote { } {
4727 return [expr {[target_info gdb_protocol] == "remote"
4728 || [target_info gdb_protocol] == "extended-remote"}]
4729}
4730
c7ccb471
TT
4731# Like istarget, but checks a list of targets.
4732proc is_any_target {args} {
4733 foreach targ $args {
4734 if {[istarget $targ]} {
4735 return 1
4736 }
4737 }
4738 return 0
4739}
4740
8929ad8b
SM
4741# Return the effective value of use_gdb_stub.
4742#
4743# If the use_gdb_stub global has been set (it is set when the gdb process is
4744# spawned), return that. Otherwise, return the value of the use_gdb_stub
4745# property from the board file.
4746#
4747# This is the preferred way of checking use_gdb_stub, since it allows to check
4748# the value before the gdb has been spawned and it will return the correct value
4749# even when it was overriden by the test.
cb51b708
MM
4750#
4751# Note that stub targets are not able to spawn new inferiors. Use this
4752# check for skipping respective tests.
8929ad8b
SM
4753
4754proc use_gdb_stub {} {
4755 global use_gdb_stub
4756
4757 if [info exists use_gdb_stub] {
4758 return $use_gdb_stub
4759 }
4760
4761 return [target_info exists use_gdb_stub]
4762}
4763
0a46d518
SM
4764# Return 1 if the current remote target is an instance of our GDBserver, 0
4765# otherwise. Return -1 if there was an error and we can't tell.
4766
b50420fd 4767gdb_caching_proc target_is_gdbserver {} {
0a46d518
SM
4768 global gdb_prompt
4769
4770 set is_gdbserver -1
bc6c7af4 4771 set test "probing for GDBserver"
0a46d518
SM
4772
4773 gdb_test_multiple "monitor help" $test {
4774 -re "The following monitor commands are supported.*Quit GDBserver.*$gdb_prompt $" {
4775 set is_gdbserver 1
4776 }
4777 -re "$gdb_prompt $" {
4778 set is_gdbserver 0
4779 }
4780 }
4781
4782 if { $is_gdbserver == -1 } {
4783 verbose -log "Unable to tell whether we are using GDBserver or not."
4784 }
4785
4786 return $is_gdbserver
4787}
4788
a97b16b8
DE
4789# N.B. compiler_info is intended to be local to this file.
4790# Call test_compiler_info with no arguments to fetch its value.
4791# Yes, this is counterintuitive when there's get_compiler_info,
4792# but that's the current API.
4793if [info exists compiler_info] {
4794 unset compiler_info
4795}
4796
94b8e876 4797# Figure out what compiler I am using.
a97b16b8 4798# The result is cached so only the first invocation runs the compiler.
94b8e876 4799#
4c93b1db 4800# ARG can be empty or "C++". If empty, "C" is assumed.
94b8e876
MC
4801#
4802# There are several ways to do this, with various problems.
4803#
4804# [ gdb_compile -E $ifile -o $binfile.ci ]
4805# source $binfile.ci
4806#
4807# Single Unix Spec v3 says that "-E -o ..." together are not
4808# specified. And in fact, the native compiler on hp-ux 11 (among
4809# others) does not work with "-E -o ...". Most targets used to do
4810# this, and it mostly worked, because it works with gcc.
4811#
4812# [ catch "exec $compiler -E $ifile > $binfile.ci" exec_output ]
4813# source $binfile.ci
4814#
4815# This avoids the problem with -E and -o together. This almost works
4816# if the build machine is the same as the host machine, which is
4817# usually true of the targets which are not gcc. But this code does
4818# not figure which compiler to call, and it always ends up using the C
3831839c
PA
4819# compiler. Not good for setting hp_aCC_compiler. Target
4820# hppa*-*-hpux* used to do this.
94b8e876
MC
4821#
4822# [ gdb_compile -E $ifile > $binfile.ci ]
4823# source $binfile.ci
4824#
4825# dejagnu target_compile says that it supports output redirection,
4826# but the code is completely different from the normal path and I
4827# don't want to sweep the mines from that path. So I didn't even try
4828# this.
4829#
4830# set cppout [ gdb_compile $ifile "" preprocess $args quiet ]
4831# eval $cppout
4832#
4833# I actually do this for all targets now. gdb_compile runs the right
4834# compiler, and TCL captures the output, and I eval the output.
4835#
4836# Unfortunately, expect logs the output of the command as it goes by,
4837# and dejagnu helpfully prints a second copy of it right afterwards.
4838# So I turn off expect logging for a moment.
4839#
4840# [ gdb_compile $ifile $ciexe_file executable $args ]
4841# [ remote_exec $ciexe_file ]
4842# [ source $ci_file.out ]
4843#
4844# I could give up on -E and just do this.
4845# I didn't get desperate enough to try this.
4846#
4847# -- chastain 2004-01-06
853d6e5b 4848
08b326ee 4849proc get_compiler_info {{language "c"}} {
575a212a 4850
44d469c5 4851 # For compiler.c, compiler.cc and compiler.F90.
c906108c 4852 global srcdir
94b8e876
MC
4853
4854 # I am going to play with the log to keep noise out.
4855 global outdir
4856 global tool
4857
44d469c5 4858 # These come from compiler.c, compiler.cc or compiler.F90.
575a212a 4859 gdb_persistent_global compiler_info_cache
c906108c 4860
575a212a 4861 if [info exists compiler_info_cache($language)] {
a97b16b8
DE
4862 # Already computed.
4863 return 0
4864 }
4865
94b8e876 4866 # Choose which file to preprocess.
08b326ee 4867 if { $language == "c++" } {
94b8e876 4868 set ifile "${srcdir}/lib/compiler.cc"
08b326ee 4869 } elseif { $language == "f90" } {
44d469c5 4870 set ifile "${srcdir}/lib/compiler.F90"
08b326ee
AB
4871 } elseif { $language == "c" } {
4872 set ifile "${srcdir}/lib/compiler.c"
4873 } else {
4874 perror "Unable to fetch compiler version for language: $language"
4875 return -1
c906108c 4876 }
085dd6e6 4877
94b8e876
MC
4878 # Run $ifile through the right preprocessor.
4879 # Toggle gdb.log to keep the compiler output out of the log.
95d7853e 4880 set saved_log [log_file -info]
94b8e876 4881 log_file
e7f86de9
JM
4882 if [is_remote host] {
4883 # We have to use -E and -o together, despite the comments
4884 # above, because of how DejaGnu handles remote host testing.
347775ed 4885 set ppout [standard_temp_file compiler.i]
08b326ee 4886 gdb_compile "${ifile}" "$ppout" preprocess [list "$language" quiet getting_compiler_info]
e7f86de9
JM
4887 set file [open $ppout r]
4888 set cppout [read $file]
4889 close $file
4890 } else {
cdcec216
TV
4891 # Copy $ifile to temp dir, to work around PR gcc/60447. This will leave the
4892 # superfluous .s file in the temp dir instead of in the source dir.
4893 set tofile [file tail $ifile]
4894 set tofile [standard_temp_file $tofile]
4895 file copy -force $ifile $tofile
4896 set ifile $tofile
08b326ee 4897 set cppout [ gdb_compile "${ifile}" "" preprocess [list "$language" quiet getting_compiler_info] ]
e7f86de9 4898 }
95d7853e 4899 eval log_file $saved_log
94b8e876 4900
4f70a4c9
MC
4901 # Eval the output.
4902 set unknown 0
94b8e876 4903 foreach cppline [ split "$cppout" "\n" ] {
4f70a4c9
MC
4904 if { [ regexp "^#" "$cppline" ] } {
4905 # line marker
4906 } elseif { [ regexp "^\[\n\r\t \]*$" "$cppline" ] } {
4907 # blank line
4908 } elseif { [ regexp "^\[\n\r\t \]*set\[\n\r\t \]" "$cppline" ] } {
4909 # eval this line
4910 verbose "get_compiler_info: $cppline" 2
4911 eval "$cppline"
2e3aff27 4912 } elseif { [ regexp {[fc]lang.*warning.*'-fdiagnostics-color=never'} "$cppline"] } {
44d469c5
CS
4913 # Both flang preprocessors (llvm flang and classic flang) print a
4914 # warning for the unused -fdiagnostics-color=never, so we skip this
4915 # output line here.
2e3aff27
RB
4916 # The armflang preprocessor has been observed to output the
4917 # warning prefixed with "clang", so the regex also accepts
4918 # this.
4f70a4c9
MC
4919 } else {
4920 # unknown line
4921 verbose -log "get_compiler_info: $cppline"
4922 set unknown 1
94b8e876 4923 }
085dd6e6 4924 }
4f70a4c9 4925
a97b16b8
DE
4926 # Set to unknown if for some reason compiler_info didn't get defined.
4927 if ![info exists compiler_info] {
4928 verbose -log "get_compiler_info: compiler_info not provided"
4929 set compiler_info "unknown"
4930 }
4931 # Also set to unknown compiler if any diagnostics happened.
4f70a4c9 4932 if { $unknown } {
a97b16b8 4933 verbose -log "get_compiler_info: got unexpected diagnostics"
4f70a4c9 4934 set compiler_info "unknown"
4f70a4c9
MC
4935 }
4936
575a212a
AB
4937 set compiler_info_cache($language) $compiler_info
4938
4f70a4c9 4939 # Log what happened.
94b8e876 4940 verbose -log "get_compiler_info: $compiler_info"
085dd6e6 4941
ae59b1da 4942 return 0
c906108c
SS
4943}
4944
a97b16b8
DE
4945# Return the compiler_info string if no arg is provided.
4946# Otherwise the argument is a glob-style expression to match against
4947# compiler_info.
4948
08b326ee 4949proc test_compiler_info { {compiler ""} {language "c"} } {
575a212a 4950 gdb_persistent_global compiler_info_cache
0e471fde
AB
4951
4952 if [get_compiler_info $language] {
4953 # An error will already have been printed in this case. Just
4954 # return a suitable result depending on how the user called
4955 # this function.
4956 if [string match "" $compiler] {
4957 return ""
4958 } else {
4959 return false
4960 }
4961 }
6e87504d 4962
a97b16b8
DE
4963 # If no arg, return the compiler_info string.
4964 if [string match "" $compiler] {
575a212a 4965 return $compiler_info_cache($language)
a97b16b8 4966 }
6e87504d 4967
575a212a 4968 return [string match $compiler $compiler_info_cache($language)]
853d6e5b
AC
4969}
4970
ef7a6b97
AB
4971# Return true if the C compiler is GCC, otherwise, return false.
4972
4973proc is_c_compiler_gcc {} {
4974 set compiler_info [test_compiler_info]
4975 set gcc_compiled false
4976 regexp "^gcc-(\[0-9\]+)-" "$compiler_info" matchall gcc_compiled
4977 return $gcc_compiled
4978}
4979
8f5d31b8
TV
4980# Return the gcc major version, or -1.
4981# For gcc 4.8.5, the major version is 4.8.
4982# For gcc 7.5.0, the major version 7.
2043638b 4983# The COMPILER and LANGUAGE arguments are as for test_compiler_info.
8f5d31b8 4984
2043638b 4985proc gcc_major_version { {compiler "gcc-*"} {language "c"} } {
8f5d31b8 4986 global decimal
2043638b 4987 if { ![test_compiler_info $compiler $language] } {
8f5d31b8
TV
4988 return -1
4989 }
2043638b
TV
4990 # Strip "gcc-*" to "gcc".
4991 regsub -- {-.*} $compiler "" compiler
4992 set res [regexp $compiler-($decimal)-($decimal)- \
4993 [test_compiler_info "" $language] \
8f5d31b8
TV
4994 dummy_var major minor]
4995 if { $res != 1 } {
4996 return -1
4997 }
4998 if { $major >= 5} {
4999 return $major
5000 }
5001 return $major.$minor
5002}
5003
f6838f81
DJ
5004proc current_target_name { } {
5005 global target_info
5006 if [info exists target_info(target,name)] {
5007 set answer $target_info(target,name)
5008 } else {
5009 set answer ""
5010 }
5011 return $answer
5012}
5013
f1c47eb2 5014set gdb_wrapper_initialized 0
f6838f81 5015set gdb_wrapper_target ""
25dfed24
SL
5016set gdb_wrapper_file ""
5017set gdb_wrapper_flags ""
f1c47eb2
MS
5018
5019proc gdb_wrapper_init { args } {
4ec70201
PA
5020 global gdb_wrapper_initialized
5021 global gdb_wrapper_file
5022 global gdb_wrapper_flags
f6838f81 5023 global gdb_wrapper_target
f1c47eb2
MS
5024
5025 if { $gdb_wrapper_initialized == 1 } { return; }
5026
5027 if {[target_info exists needs_status_wrapper] && \
277254ba 5028 [target_info needs_status_wrapper] != "0"} {
25dfed24 5029 set result [build_wrapper "testglue.o"]
f1c47eb2 5030 if { $result != "" } {
4ec70201 5031 set gdb_wrapper_file [lindex $result 0]
25dfed24
SL
5032 if ![is_remote host] {
5033 set gdb_wrapper_file [file join [pwd] $gdb_wrapper_file]
5034 }
4ec70201 5035 set gdb_wrapper_flags [lindex $result 1]
f1c47eb2
MS
5036 } else {
5037 warning "Status wrapper failed to build."
5038 }
25dfed24
SL
5039 } else {
5040 set gdb_wrapper_file ""
5041 set gdb_wrapper_flags ""
f1c47eb2 5042 }
25dfed24 5043 verbose "set gdb_wrapper_file = $gdb_wrapper_file"
f1c47eb2 5044 set gdb_wrapper_initialized 1
f6838f81 5045 set gdb_wrapper_target [current_target_name]
f1c47eb2
MS
5046}
5047
bf0ec4c2 5048# Determine options that we always want to pass to the compiler.
b50420fd 5049gdb_caching_proc universal_compile_options {} {
bf0ec4c2
AA
5050 set me "universal_compile_options"
5051 set options {}
5052
16fbc917
TV
5053 set src [standard_temp_file ccopts.c]
5054 set obj [standard_temp_file ccopts.o]
bf0ec4c2
AA
5055
5056 gdb_produce_source $src {
5057 int foo(void) { return 0; }
5058 }
5059
5060 # Try an option for disabling colored diagnostics. Some compilers
5061 # yield colored diagnostics by default (when run from a tty) unless
5062 # such an option is specified.
5063 set opt "additional_flags=-fdiagnostics-color=never"
5064 set lines [target_compile $src $obj object [list "quiet" $opt]]
d4c45423 5065 if {[string match "" $lines]} {
bf0ec4c2
AA
5066 # Seems to have worked; use the option.
5067 lappend options $opt
5068 }
5069 file delete $src
5070 file delete $obj
5071
5072 verbose "$me: returning $options" 2
5073 return $options
5074}
5075
c221b2f7 5076# Compile the code in $code to a file based on $name, using the flags
29dd2d27
TV
5077# $compile_flag as well as debug, nowarning and quiet (unless otherwise
5078# specified in default_compile_flags).
c221b2f7 5079# Return 1 if code can be compiled
bf326452 5080# Leave the file name of the resulting object in the upvar object.
c221b2f7 5081
29dd2d27 5082proc gdb_simple_compile {name code {type object} {compile_flags {}} {object obj} {default_compile_flags {}}} {
bf326452 5083 upvar $object obj
c221b2f7
AH
5084
5085 switch -regexp -- $type {
5086 "executable" {
5087 set postfix "x"
5088 }
5089 "object" {
5090 set postfix "o"
5091 }
5092 "preprocess" {
5093 set postfix "i"
5094 }
5095 "assembly" {
5096 set postfix "s"
5097 }
5098 }
d7445728
TV
5099 set ext "c"
5100 foreach flag $compile_flags {
5101 if { "$flag" == "go" } {
5102 set ext "go"
5103 break
5104 }
39f6d7c6
LS
5105 if { "$flag" eq "hip" } {
5106 set ext "cpp"
5107 break
5108 }
1770eca6
TV
5109 if { "$flag" eq "d" } {
5110 set ext "d"
5111 break
5112 }
d7445728 5113 }
16fbc917
TV
5114 set src [standard_temp_file $name.$ext]
5115 set obj [standard_temp_file $name.$postfix]
29dd2d27
TV
5116 if { $default_compile_flags == "" } {
5117 set compile_flags [concat $compile_flags {debug nowarnings quiet}]
5118 } else {
5119 set compile_flags [concat $compile_flags $default_compile_flags]
5120 }
c221b2f7
AH
5121
5122 gdb_produce_source $src $code
5123
5124 verbose "$name: compiling testfile $src" 2
5125 set lines [gdb_compile $src $obj $type $compile_flags]
5126
5127 file delete $src
c221b2f7 5128
d4c45423 5129 if {![string match "" $lines]} {
c221b2f7
AH
5130 verbose "$name: compilation failed, returning 0" 2
5131 return 0
5132 }
5133 return 1
5134}
5135
bf326452 5136# Compile the code in $code to a file based on $name, using the flags
29dd2d27
TV
5137# $compile_flag as well as debug, nowarning and quiet (unless otherwise
5138# specified in default_compile_flags).
bf326452
AH
5139# Return 1 if code can be compiled
5140# Delete all created files and objects.
5141
29dd2d27
TV
5142proc gdb_can_simple_compile {name code {type object} {compile_flags ""} {default_compile_flags ""}} {
5143 set ret [gdb_simple_compile $name $code $type $compile_flags temp_obj \
5144 $default_compile_flags]
bf326452
AH
5145 file delete $temp_obj
5146 return $ret
5147}
5148
388f63c1
TV
5149# As gdb_can_simple_compile, but defaults to using nodebug instead of debug.
5150proc gdb_can_simple_compile_nodebug {name code {type object} {compile_flags ""}
5151 {default_compile_flags "nodebug nowarning quiet"}} {
5152 return [gdb_can_simple_compile $name $code $type $compile_flags \
5153 $default_compile_flags]
5154}
5155
f747e0ce
PA
5156# Some targets need to always link a special object in. Save its path here.
5157global gdb_saved_set_unbuffered_mode_obj
5158set gdb_saved_set_unbuffered_mode_obj ""
5159
ff000c4d
TV
5160# Escape STR sufficiently for use on host commandline.
5161
5162proc escape_for_host { str } {
a14e3d11
TV
5163 if { [is_remote host] } {
5164 set map {
5165 {$} {\\$}
5166 }
5167 } else {
5168 set map {
5169 {$} {\$}
5170 }
ff000c4d
TV
5171 }
5172
5173 return [string map $map $str]
5174}
5175
d0498b32
TV
5176# Add double quotes around ARGS, sufficiently escaped for use on host
5177# commandline.
5178
5179proc quote_for_host { args } {
5180 set str [join $args]
5181 if { [is_remote host] } {
5182 set str [join [list {\"} $str {\"}] ""]
5183 } else {
5184 set str [join [list {"} $str {"}] ""]
5185 }
5186 return $str
5187}
5188
aff9c0f8
SM
5189# Compile source files specified by SOURCE into a binary of type TYPE at path
5190# DEST. gdb_compile is implemented using DejaGnu's target_compile, so the type
5191# parameter and most options are passed directly to it.
5192#
5193# The type can be one of the following:
5194#
5195# - object: Compile into an object file.
5196# - executable: Compile and link into an executable.
5197# - preprocess: Preprocess the source files.
5198# - assembly: Generate assembly listing.
5199#
5200# The following options are understood and processed by gdb_compile:
5201#
5202# - shlib=so_path: Add SO_PATH to the sources, and enable some target-specific
5203# quirks to be able to use shared libraries.
5204# - shlib_load: Link with appropriate libraries to allow the test to
5205# dynamically load libraries at runtime. For example, on Linux, this adds
5206# -ldl so that the test can use dlopen.
5207# - nowarnings: Inhibit all compiler warnings.
968aa7ae 5208# - pie: Force creation of PIE executables.
6e8b1ab2 5209# - nopie: Prevent creation of PIE executables.
9be5d742
SM
5210# - macros: Add the required compiler flag to include macro information in
5211# debug information
2bb8c72b 5212# - text_segment=addr: Tell the linker to place the text segment at ADDR.
f2509bee 5213# - build-id: Ensure the final binary includes a build-id.
29deb422
CL
5214# - column-info/no-column-info: Enable/Disable generation of column table
5215# information.
aff9c0f8
SM
5216#
5217# And here are some of the not too obscure options understood by DejaGnu that
5218# influence the compilation:
5219#
5220# - additional_flags=flag: Add FLAG to the compiler flags.
5221# - libs=library: Add LIBRARY to the libraries passed to the linker. The
5222# argument can be a file, in which case it's added to the sources, or a
5223# linker flag.
5224# - ldflags=flag: Add FLAG to the linker flags.
5225# - incdir=path: Add PATH to the searched include directories.
5226# - libdir=path: Add PATH to the linker searched directories.
cffe02ac
NCK
5227# - ada, c++, f90, go, rust: Compile the file as Ada, C++,
5228# Fortran 90, Go or Rust.
aff9c0f8
SM
5229# - debug: Build with debug information.
5230# - optimize: Build with optimization.
5231
c906108c 5232proc gdb_compile {source dest type options} {
4ec70201
PA
5233 global GDB_TESTCASE_OPTIONS
5234 global gdb_wrapper_file
5235 global gdb_wrapper_flags
f747e0ce
PA
5236 global srcdir
5237 global objdir
5238 global gdb_saved_set_unbuffered_mode_obj
c906108c 5239
695e2681
MK
5240 set outdir [file dirname $dest]
5241
7ce4a6d1
NCK
5242 # If this is set, calling test_compiler_info will cause recursion.
5243 if { [lsearch -exact $options getting_compiler_info] == -1 } {
5244 set getting_compiler_info false
5245 } else {
5246 set getting_compiler_info true
5247 }
5248
695e2681
MK
5249 # Add platform-specific options if a shared library was specified using
5250 # "shlib=librarypath" in OPTIONS.
dcc06925 5251 set new_options {}
5eb5f850
TT
5252 if {[lsearch -exact $options rust] != -1} {
5253 # -fdiagnostics-color is not a rustcc option.
5254 } else {
5255 set new_options [universal_compile_options]
5256 }
8d70a9f0 5257
0046ff60 5258 # C/C++ specific settings.
7ce4a6d1 5259 if {!$getting_compiler_info
331733cd
PA
5260 && [lsearch -exact $options rust] == -1
5261 && [lsearch -exact $options ada] == -1
331733cd 5262 && [lsearch -exact $options f90] == -1
6232b843 5263 && [lsearch -exact $options go] == -1} {
0046ff60
NCK
5264
5265 # Some C/C++ testcases unconditionally pass -Wno-foo as additional
5266 # options to disable some warning. That is OK with GCC, because
5267 # by design, GCC accepts any -Wno-foo option, even if it doesn't
5268 # support -Wfoo. Clang however warns about unknown -Wno-foo by
5269 # default, unless you pass -Wno-unknown-warning-option as well.
5270 # We do that here, so that individual testcases don't have to
5271 # worry about it.
6232b843
FW
5272 if {[test_compiler_info "clang-*"] || [test_compiler_info "icx-*"]} {
5273 lappend new_options "additional_flags=-Wno-unknown-warning-option"
5274 } elseif {[test_compiler_info "icc-*"]} {
5275 # This is the equivalent for the icc compiler.
5276 lappend new_options "additional_flags=-diag-disable=10148"
5277 }
0046ff60 5278
23f34158
TBA
5279 # icpx/icx give the following warning if '-g' is used without '-O'.
5280 #
5281 # icpx: remark: Note that use of '-g' without any
5282 # optimization-level option will turn off most compiler
5283 # optimizations similar to use of '-O0'
5284 #
5285 # The warning makes dejagnu think that compilation has failed.
5286 #
5287 # Furthermore, if no -O flag is passed, icx and icc optimize
5288 # the code by default. This breaks assumptions in many GDB
5289 # tests that the code is unoptimized by default.
5290 #
5291 # To fix both problems, pass the -O0 flag explicitly, if no
5292 # optimization option is given.
5293 if {[test_compiler_info "icx-*"] || [test_compiler_info "icc-*"]} {
5294 if {[lsearch $options optimize=*] == -1
5295 && [lsearch $options additional_flags=-O*] == -1} {
5296 lappend new_options "optimize=-O0"
5297 }
5298 }
5299
0046ff60
NCK
5300 # Starting with 2021.7.0 (recognized as icc-20-21-7 by GDB) icc and
5301 # icpc are marked as deprecated and both compilers emit the remark
5302 # #10441. To let GDB still compile successfully, we disable these
5303 # warnings here.
5304 if {([lsearch -exact $options c++] != -1
5305 && [test_compiler_info {icc-20-21-[7-9]} c++])
5306 || [test_compiler_info {icc-20-21-[7-9]}]} {
5307 lappend new_options "additional_flags=-diag-disable=10441"
5308 }
331733cd
PA
5309 }
5310
f2509bee
AB
5311 # If the 'build-id' option is used, then ensure that we generate a
5312 # build-id. GCC does this by default, but Clang does not, so
5313 # enable it now.
5314 if {[lsearch -exact $options build-id] > 0
5315 && [test_compiler_info "clang-*"]} {
5316 lappend new_options "additional_flags=-Wl,--build-id"
5317 }
5318
221db974
PA
5319 # Treating .c input files as C++ is deprecated in Clang, so
5320 # explicitly force C++ language.
7ce4a6d1 5321 if { !$getting_compiler_info
221db974 5322 && [lsearch -exact $options c++] != -1
6539a36d
GB
5323 && [string match *.c $source] != 0 } {
5324
5325 # gdb_compile cannot handle this combination of options, the
5326 # result is a command like "clang -x c++ foo.c bar.so -o baz"
5327 # which tells Clang to treat bar.so as C++. The solution is
5328 # to call gdb_compile twice--once to compile, once to link--
5329 # either directly, or via build_executable_from_specs.
5330 if { [lsearch $options shlib=*] != -1 } {
5331 error "incompatible gdb_compile options"
5332 }
5333
5334 if {[test_compiler_info "clang-*"]} {
5335 lappend new_options early_flags=-x\ c++
5336 }
221db974
PA
5337 }
5338
8d70a9f0 5339 # Place (and look for) Fortran `.mod` files in the output
7c07eaec
ABI
5340 # directory for this specific test. For Intel compilers the -J
5341 # option is not supported so instead use the -module flag.
4212a8c9
NCK
5342 # Additionally, Intel compilers need the -debug-parameters flag set to
5343 # emit debug info for all parameters in modules.
23f34158
TBA
5344 #
5345 # ifx gives the following warning if '-g' is used without '-O'.
5346 #
5347 # ifx: remark #10440: Note that use of a debug option
5348 # without any optimization-level option will turnoff most
5349 # compiler optimizations similar to use of '-O0'
5350 #
5351 # The warning makes dejagnu think that compilation has failed.
5352 #
5353 # Furthermore, if no -O flag is passed, Intel compilers optimize
5354 # the code by default. This breaks assumptions in many GDB
5355 # tests that the code is unoptimized by default.
5356 #
5357 # To fix both problems, pass the -O0 flag explicitly, if no
5358 # optimization option is given.
7ce4a6d1 5359 if { !$getting_compiler_info && [lsearch -exact $options f90] != -1 } {
8d70a9f0
AB
5360 # Fortran compile.
5361 set mod_path [standard_output_file ""]
44d469c5 5362 if { [test_compiler_info {gfortran-*} f90] } {
f2d42111 5363 lappend new_options "additional_flags=-J${mod_path}"
44d469c5
CS
5364 } elseif { [test_compiler_info {ifort-*} f90]
5365 || [test_compiler_info {ifx-*} f90] } {
7c07eaec 5366 lappend new_options "additional_flags=-module ${mod_path}"
4212a8c9 5367 lappend new_options "additional_flags=-debug-parameters all"
23f34158
TBA
5368
5369 if {[lsearch $options optimize=*] == -1
5370 && [lsearch $options additional_flags=-O*] == -1} {
5371 lappend new_options "optimize=-O0"
5372 }
f2d42111 5373 }
8d70a9f0
AB
5374 }
5375
695e2681 5376 set shlib_found 0
bdf7534a 5377 set shlib_load 0
695e2681 5378 foreach opt $options {
6181e9c2
SM
5379 if {[regexp {^shlib=(.*)} $opt dummy_var shlib_name]
5380 && $type == "executable"} {
57bf0e56 5381 if [test_compiler_info "xlc-*"] {
93f02886
DJ
5382 # IBM xlc compiler doesn't accept shared library named other
5383 # than .so: use "-Wl," to bypass this
5384 lappend source "-Wl,$shlib_name"
5385 } elseif { ([istarget "*-*-mingw*"]
5386 || [istarget *-*-cygwin*]
5387 || [istarget *-*-pe*])} {
5388 lappend source "${shlib_name}.a"
57bf0e56
DJ
5389 } else {
5390 lappend source $shlib_name
5391 }
0413d738 5392 if { $shlib_found == 0 } {
57bf0e56 5393 set shlib_found 1
0413d738
PA
5394 if { ([istarget "*-*-mingw*"]
5395 || [istarget *-*-cygwin*]) } {
21f507ef 5396 lappend new_options "ldflags=-Wl,--enable-auto-import"
0413d738 5397 }
6ebea266
DE
5398 if { [test_compiler_info "gcc-*"] || [test_compiler_info "clang-*"] } {
5399 # Undo debian's change in the default.
5400 # Put it at the front to not override any user-provided
5401 # value, and to make sure it appears in front of all the
5402 # shlibs!
5403 lappend new_options "early_flags=-Wl,--no-as-needed"
5404 }
57bf0e56 5405 }
6181e9c2 5406 } elseif { $opt == "shlib_load" && $type == "executable" } {
bdf7534a 5407 set shlib_load 1
fc65c7db 5408 } elseif { $opt == "getting_compiler_info" } {
7ce4a6d1
NCK
5409 # Ignore this setting here as it has been handled earlier in this
5410 # procedure. Do not append it to new_options as this will cause
5411 # recursion.
2bb8c72b
VB
5412 } elseif {[regexp "^text_segment=(.*)" $opt dummy_var addr]} {
5413 if { [linker_supports_Ttext_segment_flag] } {
5414 # For GNU ld.
5415 lappend new_options "ldflags=-Wl,-Ttext-segment=$addr"
5416 } elseif { [linker_supports_image_base_flag] } {
5417 # For LLVM's lld.
5418 lappend new_options "ldflags=-Wl,--image-base=$addr"
5419 } elseif { [linker_supports_Ttext_flag] } {
5420 # For old GNU gold versions.
5421 lappend new_options "ldflags=-Wl,-Ttext=$addr"
5422 } else {
5423 error "Don't know how to handle text_segment option."
5424 }
29deb422
CL
5425 } elseif { $opt == "column-info" } {
5426 # If GCC or clang does not support column-info, compilation
5427 # will fail and the usupported column-info option will be
5428 # reported as such.
5429 if {[test_compiler_info {gcc-*}]} {
5430 lappend new_options "additional_flags=-gcolumn-info"
5431
5432 } elseif {[test_compiler_info {clang-*}]} {
5433 lappend new_options "additional_flags=-gcolumn-info"
5434
5435 } else {
5436 error "Option gcolumn-info not supported by compiler."
5437 }
5438
5439 } elseif { $opt == "no-column-info" } {
5440 if {[test_compiler_info {gcc-*}]} {
5441 if {[test_compiler_info {gcc-[1-6]-*}]} {
5442 # In this case, don't add the compile line option and
5443 # the result will be the same as using no-column-info
5444 # on a version that supports the option.
5445 warning "gdb_compile option no-column-info not supported, ignoring."
5446 } else {
5447 lappend new_options "additional_flags=-gno-column-info"
5448 }
5449
5450 } elseif {[test_compiler_info {clang-*}]} {
5451 lappend new_options "additional_flags=-gno-column-info"
5452
5453 } else {
5454 error "Option gno-column-info not supported by compiler."
5455 }
5456
57bf0e56
DJ
5457 } else {
5458 lappend new_options $opt
5459 }
695e2681 5460 }
bdf7534a 5461
fc65c7db
AH
5462 # Ensure stack protector is disabled for GCC, as this causes problems with
5463 # DWARF line numbering.
5464 # See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88432
5465 # This option defaults to on for Debian/Ubuntu.
7ce4a6d1 5466 if { !$getting_compiler_info
fc65c7db
AH
5467 && [test_compiler_info {gcc-*-*}]
5468 && !([test_compiler_info {gcc-[0-3]-*}]
1670072e
TT
5469 || [test_compiler_info {gcc-4-0-*}])
5470 && [lsearch -exact $options rust] == -1} {
fc65c7db
AH
5471 # Put it at the front to not override any user-provided value.
5472 lappend new_options "early_flags=-fno-stack-protector"
5473 }
5474
18b4d073
SM
5475 # hipcc defaults to -O2, so add -O0 to early flags for the hip language.
5476 # If "optimize" is also requested, another -O flag (e.g. -O2) will be added
5477 # to the flags, overriding this -O0.
5478 if {[lsearch -exact $options hip] != -1} {
5479 lappend new_options "early_flags=-O0"
5480 }
5481
6e774b13
SM
5482 # Because we link with libraries using their basename, we may need
5483 # (depending on the platform) to set a special rpath value, to allow
5484 # the executable to find the libraries it depends on.
5485 if { $shlib_load || $shlib_found } {
bdf7534a
NF
5486 if { ([istarget "*-*-mingw*"]
5487 || [istarget *-*-cygwin*]
3ca22649 5488 || [istarget *-*-pe*]) } {
bdf7534a 5489 # Do not need anything.
b2a6bdeb 5490 } elseif { [istarget *-*-freebsd*] || [istarget *-*-openbsd*] } {
d8b34041 5491 lappend new_options "ldflags=-Wl,-rpath,${outdir}"
bdf7534a
NF
5492 } else {
5493 if { $shlib_load } {
5494 lappend new_options "libs=-ldl"
5495 }
ff000c4d 5496 lappend new_options [escape_for_host {ldflags=-Wl,-rpath,$ORIGIN}]
bdf7534a
NF
5497 }
5498 }
695e2681 5499 set options $new_options
57bf0e56 5500
c906108c 5501 if [info exists GDB_TESTCASE_OPTIONS] {
4ec70201 5502 lappend options "additional_flags=$GDB_TESTCASE_OPTIONS"
c906108c
SS
5503 }
5504 verbose "options are $options"
5505 verbose "source is $source $dest $type $options"
5506
24ac169a 5507 gdb_wrapper_init
f1c47eb2
MS
5508
5509 if {[target_info exists needs_status_wrapper] && \
5510 [target_info needs_status_wrapper] != "0" && \
25dfed24 5511 $gdb_wrapper_file != "" } {
f1c47eb2
MS
5512 lappend options "libs=${gdb_wrapper_file}"
5513 lappend options "ldflags=${gdb_wrapper_flags}"
5514 }
5515
fc91c6c2
PB
5516 # Replace the "nowarnings" option with the appropriate additional_flags
5517 # to disable compiler warnings.
5518 set nowarnings [lsearch -exact $options nowarnings]
5519 if {$nowarnings != -1} {
5520 if [target_info exists gdb,nowarnings_flag] {
5521 set flag "additional_flags=[target_info gdb,nowarnings_flag]"
5522 } else {
5523 set flag "additional_flags=-w"
5524 }
5525 set options [lreplace $options $nowarnings $nowarnings $flag]
5526 }
5527
968aa7ae
AH
5528 # Replace the "pie" option with the appropriate compiler and linker flags
5529 # to enable PIE executables.
5530 set pie [lsearch -exact $options pie]
5531 if {$pie != -1} {
5532 if [target_info exists gdb,pie_flag] {
5533 set flag "additional_flags=[target_info gdb,pie_flag]"
5534 } else {
5535 # For safety, use fPIE rather than fpie. On AArch64, m68k, PowerPC
5536 # and SPARC, fpie can cause compile errors due to the GOT exceeding
5537 # a maximum size. On other architectures the two flags are
5538 # identical (see the GCC manual). Note Debian9 and Ubuntu16.10
5539 # onwards default GCC to using fPIE. If you do require fpie, then
5540 # it can be set using the pie_flag.
5541 set flag "additional_flags=-fPIE"
5542 }
5543 set options [lreplace $options $pie $pie $flag]
5544
5545 if [target_info exists gdb,pie_ldflag] {
5546 set flag "ldflags=[target_info gdb,pie_ldflag]"
5547 } else {
5548 set flag "ldflags=-pie"
5549 }
5550 lappend options "$flag"
5551 }
5552
b93a3ed0
MM
5553 # Replace the "nopie" option with the appropriate compiler and linker
5554 # flags to disable PIE executables.
6e8b1ab2
JV
5555 set nopie [lsearch -exact $options nopie]
5556 if {$nopie != -1} {
5557 if [target_info exists gdb,nopie_flag] {
b93a3ed0 5558 set flag "additional_flags=[target_info gdb,nopie_flag]"
6e8b1ab2 5559 } else {
b93a3ed0 5560 set flag "additional_flags=-fno-pie"
6e8b1ab2
JV
5561 }
5562 set options [lreplace $options $nopie $nopie $flag]
b93a3ed0
MM
5563
5564 if [target_info exists gdb,nopie_ldflag] {
5565 set flag "ldflags=[target_info gdb,nopie_ldflag]"
5566 } else {
5567 set flag "ldflags=-no-pie"
5568 }
5569 lappend options "$flag"
6e8b1ab2
JV
5570 }
5571
9be5d742
SM
5572 set macros [lsearch -exact $options macros]
5573 if {$macros != -1} {
5574 if { [test_compiler_info "clang-*"] } {
5575 set flag "additional_flags=-fdebug-macro"
5576 } else {
5577 set flag "additional_flags=-g3"
5578 }
5579
5580 set options [lreplace $options $macros $macros $flag]
5581 }
5582
f747e0ce
PA
5583 if { $type == "executable" } {
5584 if { ([istarget "*-*-mingw*"]
56643c5e 5585 || [istarget "*-*-*djgpp"]
f747e0ce
PA
5586 || [istarget "*-*-cygwin*"])} {
5587 # Force output to unbuffered mode, by linking in an object file
5588 # with a global contructor that calls setvbuf.
5589 #
40c94099 5590 # Compile the special object separately for two reasons:
f747e0ce
PA
5591 # 1) Insulate it from $options.
5592 # 2) Avoid compiling it for every gdb_compile invocation,
5593 # which is time consuming, especially if we're remote
5594 # host testing.
5595 #
02d02fc7
PA
5596 # Note the special care for GDB_PARALLEL. In that
5597 # scenario, multiple expect instances will potentially try
5598 # to compile the object file at the same time. The result
5599 # should be identical for every one of them, so we just
5600 # need to make sure that the final objfile is written to
5601 # atomically.
5602
f747e0ce
PA
5603 if { $gdb_saved_set_unbuffered_mode_obj == "" } {
5604 verbose "compiling gdb_saved_set_unbuffered_obj"
5605 set unbuf_src ${srcdir}/lib/set_unbuffered_mode.c
02d02fc7
PA
5606 # This gives us a per-expect-instance unique filename,
5607 # which is important for GDB_PARALLEL. See comments
5608 # above.
5609 set unbuf_obj [standard_temp_file set_unbuffered_mode.o]
f747e0ce
PA
5610
5611 set result [gdb_compile "${unbuf_src}" "${unbuf_obj}" object {nowarnings}]
5612 if { $result != "" } {
5613 return $result
5614 }
f6dc277e
YQ
5615 if {[is_remote host]} {
5616 set gdb_saved_set_unbuffered_mode_obj set_unbuffered_mode_saved.o
5617 } else {
5618 set gdb_saved_set_unbuffered_mode_obj ${objdir}/set_unbuffered_mode_saved.o
5619 }
f747e0ce
PA
5620 # Link a copy of the output object, because the
5621 # original may be automatically deleted.
02d02fc7
PA
5622 if {[info exists ::GDB_PARALLEL]} {
5623 # Make sure to write the .o file atomically.
5624 # (Note GDB_PARALLEL mode does not support remote
5625 # host testing.)
5626 file rename -force -- $unbuf_obj $gdb_saved_set_unbuffered_mode_obj
5627 } else {
5628 remote_download host $unbuf_obj $gdb_saved_set_unbuffered_mode_obj
5629 }
f747e0ce
PA
5630 } else {
5631 verbose "gdb_saved_set_unbuffered_obj already compiled"
5632 }
5633
5634 # Rely on the internal knowledge that the global ctors are ran in
5635 # reverse link order. In that case, we can use ldflags to
5636 # avoid copying the object file to the host multiple
5637 # times.
ace5c364
PM
5638 # This object can only be added if standard libraries are
5639 # used. Thus, we need to disable it if -nostdlib option is used
5640 if {[lsearch -regexp $options "-nostdlib"] < 0 } {
5641 lappend options "ldflags=$gdb_saved_set_unbuffered_mode_obj"
5642 }
f747e0ce
PA
5643 }
5644 }
5645
68f7bda9
TV
5646 cond_wrap [expr $pie != -1 || $nopie != -1] \
5647 with_PIE_multilib_flags_filtered {
5648 set result [target_compile $source $dest $type $options]
5649 }
93f02886
DJ
5650
5651 # Prune uninteresting compiler (and linker) output.
5652 regsub "Creating library file: \[^\r\n\]*\[\r\n\]+" $result "" result
5653
0046ff60
NCK
5654 # Starting with 2021.7.0 icc and icpc are marked as deprecated and both
5655 # compilers emit a remark #10441. To let GDB still compile successfully,
5656 # we disable these warnings. When $getting_compiler_info is true however,
5657 # we do not yet know the compiler (nor its version) and instead prune these
5658 # lines from the compiler output to let the get_compiler_info pass.
5659 if {$getting_compiler_info} {
5660 regsub \
5661 "(icc|icpc): remark #10441: The Intel\\(R\\) C\\+\\+ Compiler Classic \\(ICC\\) is deprecated\[^\r\n\]*" \
5662 "$result" "" result
5663 }
5664
4ec70201
PA
5665 regsub "\[\r\n\]*$" "$result" "" result
5666 regsub "^\[\r\n\]*" "$result" "" result
ec3c07fc 5667
a80cf5d8
TV
5668 if { $type == "executable" && $result == "" \
5669 && ($nopie != -1 || $pie != -1) } {
5670 set is_pie [exec_is_pie "$dest"]
5671 if { $nopie != -1 && $is_pie == 1 } {
b13057d9 5672 set result "nopie failed to prevent PIE executable"
a80cf5d8
TV
5673 } elseif { $pie != -1 && $is_pie == 0 } {
5674 set result "pie failed to generate PIE executable"
b13057d9
TV
5675 }
5676 }
5677
ec3c07fc 5678 if {[lsearch $options quiet] < 0} {
cffe02ac 5679 if { $result != "" } {
ec3c07fc
NS
5680 clone_output "gdb compile failed, $result"
5681 }
c906108c 5682 }
ae59b1da 5683 return $result
c906108c
SS
5684}
5685
b6ff0e81
JB
5686
5687# This is just like gdb_compile, above, except that it tries compiling
5688# against several different thread libraries, to see which one this
5689# system has.
5690proc gdb_compile_pthreads {source dest type options} {
26b911fb
KB
5691 if {$type != "executable"} {
5692 return [gdb_compile $source $dest $type $options]
5693 }
0ae67eb3 5694 set built_binfile 0
b6ff0e81 5695 set why_msg "unrecognized error"
24486cb7 5696 foreach lib {-lpthreads -lpthread -lthread ""} {
b6ff0e81
JB
5697 # This kind of wipes out whatever libs the caller may have
5698 # set. Or maybe theirs will override ours. How infelicitous.
b5ab8ff3 5699 set options_with_lib [concat $options [list libs=$lib quiet]]
b6ff0e81
JB
5700 set ccout [gdb_compile $source $dest $type $options_with_lib]
5701 switch -regexp -- $ccout {
5702 ".*no posix threads support.*" {
5703 set why_msg "missing threads include file"
5704 break
5705 }
5706 ".*cannot open -lpthread.*" {
5707 set why_msg "missing runtime threads library"
5708 }
5709 ".*Can't find library for -lpthread.*" {
5710 set why_msg "missing runtime threads library"
5711 }
5712 {^$} {
5713 pass "successfully compiled posix threads test case"
5714 set built_binfile 1
5715 break
5716 }
5717 }
5718 }
0ae67eb3 5719 if {!$built_binfile} {
bc6c7af4 5720 unsupported "couldn't compile [file tail $source]: ${why_msg}"
b6ff0e81
JB
5721 return -1
5722 }
57bf0e56
DJ
5723}
5724
409d8f48 5725# Build a shared library from SOURCES.
57bf0e56 5726
1e61189d 5727proc gdb_compile_shlib_1 {sources dest options} {
57bf0e56
DJ
5728 set obj_options $options
5729
a406a98e
TV
5730 set ada 0
5731 if { [lsearch -exact $options "ada"] >= 0 } {
5732 set ada 1
5733 }
5734
409d8f48
AB
5735 if { [lsearch -exact $options "c++"] >= 0 } {
5736 set info_options "c++"
44d469c5
CS
5737 } elseif { [lsearch -exact $options "f90"] >= 0 } {
5738 set info_options "f90"
08b326ee
AB
5739 } else {
5740 set info_options "c"
409d8f48 5741 }
409d8f48 5742
1562f64f 5743 switch -glob [test_compiler_info "" ${info_options}] {
57bf0e56
DJ
5744 "xlc-*" {
5745 lappend obj_options "additional_flags=-qpic"
5746 }
ee92b0dd 5747 "clang-*" {
2f413264
TV
5748 if { [istarget "*-*-cygwin*"]
5749 || [istarget "*-*-mingw*"] } {
5750 lappend obj_options "additional_flags=-fPIC"
5751 } else {
ee92b0dd
DE
5752 lappend obj_options "additional_flags=-fpic"
5753 }
5754 }
57bf0e56 5755 "gcc-*" {
2f413264 5756 if { [istarget "powerpc*-*-aix*"]
227c54da
DJ
5757 || [istarget "rs6000*-*-aix*"]
5758 || [istarget "*-*-cygwin*"]
5759 || [istarget "*-*-mingw*"]
2f413264
TV
5760 || [istarget "*-*-pe*"] } {
5761 lappend obj_options "additional_flags=-fPIC"
5762 } else {
57bf0e56
DJ
5763 lappend obj_options "additional_flags=-fpic"
5764 }
5765 }
9b9b09e9
BH
5766 "icc-*" {
5767 lappend obj_options "additional_flags=-fpic"
5768 }
57bf0e56 5769 default {
3ca22649 5770 # don't know what the compiler is...
2f413264 5771 lappend obj_options "additional_flags=-fPIC"
57bf0e56
DJ
5772 }
5773 }
5774
5775 set outdir [file dirname $dest]
5776 set objects ""
5777 foreach source $sources {
2ff0a947
TT
5778 if {[file extension $source] == ".o"} {
5779 # Already a .o file.
5780 lappend objects $source
a406a98e
TV
5781 continue
5782 }
5783
5784 set sourcebase [file tail $source]
5785
5786 if { $ada } {
5787 # Gnatmake doesn't like object name foo.adb.o, use foo.o.
5788 set sourcebase [file rootname $sourcebase]
5789 }
5790 set object ${outdir}/${sourcebase}.o
5791
5792 if { $ada } {
5793 # Use gdb_compile_ada_1 instead of gdb_compile_ada to avoid the
5794 # PASS message.
5795 if {[gdb_compile_ada_1 $source $object object \
5796 $obj_options] != ""} {
5797 return -1
5798 }
2ff0a947 5799 } else {
a406a98e
TV
5800 if {[gdb_compile $source $object object \
5801 $obj_options] != ""} {
5802 return -1
5803 }
2ff0a947 5804 }
a406a98e
TV
5805
5806 lappend objects $object
57bf0e56
DJ
5807 }
5808
3ca22649 5809 set link_options $options
a406a98e
TV
5810 if { $ada } {
5811 # If we try to use gnatmake for the link, it will interpret the
5812 # object file as an .adb file. Remove ada from the options to
5813 # avoid it.
5814 set idx [lsearch $link_options "ada"]
5815 set link_options [lreplace $link_options $idx $idx]
5816 }
3ca22649
SM
5817 if [test_compiler_info "xlc-*"] {
5818 lappend link_options "additional_flags=-qmkshrobj"
57bf0e56 5819 } else {
3ca22649
SM
5820 lappend link_options "additional_flags=-shared"
5821
5822 if { ([istarget "*-*-mingw*"]
5823 || [istarget *-*-cygwin*]
5824 || [istarget *-*-pe*]) } {
5825 if { [is_remote host] } {
5826 set name [file tail ${dest}]
5827 } else {
5828 set name ${dest}
5829 }
21f507ef 5830 lappend link_options "ldflags=-Wl,--out-implib,${name}.a"
6e774b13
SM
5831 } else {
5832 # Set the soname of the library. This causes the linker on ELF
5833 # systems to create the DT_NEEDED entry in the executable referring
5834 # to the soname of the library, and not its absolute path. This
5835 # (using the absolute path) would be problem when testing on a
5836 # remote target.
5837 #
5838 # In conjunction with setting the soname, we add the special
5839 # rpath=$ORIGIN value when building the executable, so that it's
5840 # able to find the library in its own directory.
3ca22649 5841 set destbase [file tail $dest]
21f507ef 5842 lappend link_options "ldflags=-Wl,-soname,$destbase"
3ca22649
SM
5843 }
5844 }
5845 if {[gdb_compile "${objects}" "${dest}" executable $link_options] != ""} {
5846 return -1
57bf0e56 5847 }
3ca22649
SM
5848 if { [is_remote host]
5849 && ([istarget "*-*-mingw*"]
5850 || [istarget *-*-cygwin*]
5851 || [istarget *-*-pe*]) } {
5852 set dest_tail_name [file tail ${dest}]
5853 remote_upload host $dest_tail_name.a ${dest}.a
5854 remote_file host delete $dest_tail_name.a
5855 }
5856
5857 return ""
b6ff0e81
JB
5858}
5859
18060543 5860# Ignore FLAGS in target board multilib_flags while executing BODY.
1e61189d 5861
18060543 5862proc with_multilib_flags_filtered { flags body } {
1e61189d
TV
5863 global board
5864
18060543 5865 # Ignore flags in multilib_flags.
c541fa7c
TV
5866 set board [target_info name]
5867 set multilib_flags_orig [board_info $board multilib_flags]
5868 set multilib_flags ""
5869 foreach op $multilib_flags_orig {
18060543 5870 if { [lsearch -exact $flags $op] == -1 } {
c541fa7c 5871 append multilib_flags " $op"
1e61189d
TV
5872 }
5873 }
1e61189d 5874
c541fa7c
TV
5875 save_target_board_info { multilib_flags } {
5876 unset_board_info multilib_flags
5877 set_board_info multilib_flags "$multilib_flags"
18060543
TV
5878 set result [uplevel 1 $body]
5879 }
5880
5881 return $result
5882}
5883
5884# Ignore PIE-related flags in target board multilib_flags while executing BODY.
5885
5886proc with_PIE_multilib_flags_filtered { body } {
5887 set pie_flags [list "-pie" "-no-pie" "-fPIE" "-fno-PIE"]
5888 return [uplevel 1 [list with_multilib_flags_filtered $pie_flags $body]]
5889}
5890
5891# Build a shared library from SOURCES. Ignore target boards PIE-related
5892# multilib_flags.
5893
5894proc gdb_compile_shlib {sources dest options} {
5895 with_PIE_multilib_flags_filtered {
c541fa7c 5896 set result [gdb_compile_shlib_1 $sources $dest $options]
1e61189d
TV
5897 }
5898
5899 return $result
5900}
5901
756d88a7
UW
5902# This is just like gdb_compile_shlib, above, except that it tries compiling
5903# against several different thread libraries, to see which one this
5904# system has.
5905proc gdb_compile_shlib_pthreads {sources dest options} {
5906 set built_binfile 0
5907 set why_msg "unrecognized error"
5908 foreach lib {-lpthreads -lpthread -lthread ""} {
5909 # This kind of wipes out whatever libs the caller may have
5910 # set. Or maybe theirs will override ours. How infelicitous.
5911 set options_with_lib [concat $options [list libs=$lib quiet]]
5912 set ccout [gdb_compile_shlib $sources $dest $options_with_lib]
5913 switch -regexp -- $ccout {
5914 ".*no posix threads support.*" {
5915 set why_msg "missing threads include file"
5916 break
5917 }
5918 ".*cannot open -lpthread.*" {
5919 set why_msg "missing runtime threads library"
5920 }
5921 ".*Can't find library for -lpthread.*" {
5922 set why_msg "missing runtime threads library"
5923 }
5924 {^$} {
f302f9e2 5925 pass "successfully compiled posix threads shlib test case"
756d88a7
UW
5926 set built_binfile 1
5927 break
5928 }
5929 }
5930 }
5931 if {!$built_binfile} {
bc6c7af4 5932 unsupported "couldn't compile $sources: ${why_msg}"
756d88a7
UW
5933 return -1
5934 }
5935}
5936
130cacce
AF
5937# This is just like gdb_compile_pthreads, above, except that we always add the
5938# objc library for compiling Objective-C programs
5939proc gdb_compile_objc {source dest type options} {
5940 set built_binfile 0
5941 set why_msg "unrecognized error"
5942 foreach lib {-lobjc -lpthreads -lpthread -lthread solaris} {
5943 # This kind of wipes out whatever libs the caller may have
5944 # set. Or maybe theirs will override ours. How infelicitous.
5945 if { $lib == "solaris" } {
5946 set lib "-lpthread -lposix4"
5947 }
5948 if { $lib != "-lobjc" } {
5949 set lib "-lobjc $lib"
5950 }
5951 set options_with_lib [concat $options [list libs=$lib quiet]]
5952 set ccout [gdb_compile $source $dest $type $options_with_lib]
5953 switch -regexp -- $ccout {
5954 ".*no posix threads support.*" {
5955 set why_msg "missing threads include file"
5956 break
5957 }
5958 ".*cannot open -lpthread.*" {
5959 set why_msg "missing runtime threads library"
5960 }
5961 ".*Can't find library for -lpthread.*" {
5962 set why_msg "missing runtime threads library"
5963 }
5964 {^$} {
5965 pass "successfully compiled objc with posix threads test case"
5966 set built_binfile 1
5967 break
5968 }
5969 }
5970 }
5971 if {!$built_binfile} {
bc6c7af4 5972 unsupported "couldn't compile [file tail $source]: ${why_msg}"
130cacce
AF
5973 return -1
5974 }
5975}
5976
26b911fb
KB
5977# Build an OpenMP program from SOURCE. See prefatory comment for
5978# gdb_compile, above, for discussion of the parameters to this proc.
5979
5980proc gdb_compile_openmp {source dest type options} {
5981 lappend options "additional_flags=-fopenmp"
5982 return [gdb_compile $source $dest $type $options]
5983}
5984
f9e2e39d
AH
5985# Send a command to GDB.
5986# For options for TYPE see gdb_stdin_log_write
5987
5988proc send_gdb { string {type standard}} {
f9e2e39d 5989 gdb_stdin_log_write $string $type
ae59b1da 5990 return [remote_send host "$string"]
c906108c
SS
5991}
5992
f71c18e7
PA
5993# Send STRING to the inferior's terminal.
5994
5995proc send_inferior { string } {
5996 global inferior_spawn_id
5997
5998 if {[catch "send -i $inferior_spawn_id -- \$string" errorInfo]} {
5999 return "$errorInfo"
6000 } else {
6001 return ""
6002 }
6003}
6004
c906108c
SS
6005#
6006#
6007
6008proc gdb_expect { args } {
6009 if { [llength $args] == 2 && [lindex $args 0] != "-re" } {
4ec70201
PA
6010 set atimeout [lindex $args 0]
6011 set expcode [list [lindex $args 1]]
c906108c 6012 } else {
4ec70201 6013 set expcode $args
2f34202f
MR
6014 }
6015
4a40f85a
MR
6016 # A timeout argument takes precedence, otherwise of all the timeouts
6017 # select the largest.
4a40f85a
MR
6018 if [info exists atimeout] {
6019 set tmt $atimeout
6020 } else {
45fd756c 6021 set tmt [get_largest_timeout]
c906108c 6022 }
2f34202f 6023
a0b3c4fd 6024 set code [catch \
4a40f85a 6025 {uplevel remote_expect host $tmt $expcode} string]
c906108c
SS
6026
6027 if {$code == 1} {
4ec70201 6028 global errorInfo errorCode
c906108c
SS
6029
6030 return -code error -errorinfo $errorInfo -errorcode $errorCode $string
d6d7a51a 6031 } else {
c906108c
SS
6032 return -code $code $string
6033 }
6034}
6035
5fa290c1 6036# gdb_expect_list TEST SENTINEL LIST -- expect a sequence of outputs
085dd6e6
JM
6037#
6038# Check for long sequence of output by parts.
5fa290c1 6039# TEST: is the test message to be printed with the test success/fail.
085dd6e6
JM
6040# SENTINEL: Is the terminal pattern indicating that output has finished.
6041# LIST: is the sequence of outputs to match.
6042# If the sentinel is recognized early, it is considered an error.
6043#
11cf8741
JM
6044# Returns:
6045# 1 if the test failed,
6046# 0 if the test passes,
6047# -1 if there was an internal error.
5fa290c1 6048
c2d11a7d 6049proc gdb_expect_list {test sentinel list} {
085dd6e6
JM
6050 global gdb_prompt
6051 set index 0
43ff13b4 6052 set ok 1
0ac85db5 6053
43ff13b4 6054 while { ${index} < [llength ${list}] } {
085dd6e6
JM
6055 set pattern [lindex ${list} ${index}]
6056 set index [expr ${index} + 1]
6b0ecdc2 6057 verbose -log "gdb_expect_list pattern: /$pattern/" 2
085dd6e6 6058 if { ${index} == [llength ${list}] } {
43ff13b4
JM
6059 if { ${ok} } {
6060 gdb_expect {
c2d11a7d 6061 -re "${pattern}${sentinel}" {
a20ce2c3 6062 # pass "${test}, pattern ${index} + sentinel"
c2d11a7d
JM
6063 }
6064 -re "${sentinel}" {
a20ce2c3 6065 fail "${test} (pattern ${index} + sentinel)"
c2d11a7d 6066 set ok 0
43ff13b4 6067 }
5c5455dc
AC
6068 -re ".*A problem internal to GDB has been detected" {
6069 fail "${test} (GDB internal error)"
6070 set ok 0
6071 gdb_internal_error_resync
6072 }
43ff13b4 6073 timeout {
a20ce2c3 6074 fail "${test} (pattern ${index} + sentinel) (timeout)"
43ff13b4
JM
6075 set ok 0
6076 }
085dd6e6 6077 }
43ff13b4 6078 } else {
a20ce2c3 6079 # unresolved "${test}, pattern ${index} + sentinel"
085dd6e6
JM
6080 }
6081 } else {
43ff13b4
JM
6082 if { ${ok} } {
6083 gdb_expect {
6084 -re "${pattern}" {
a20ce2c3 6085 # pass "${test}, pattern ${index}"
43ff13b4 6086 }
c2d11a7d 6087 -re "${sentinel}" {
a20ce2c3 6088 fail "${test} (pattern ${index})"
43ff13b4
JM
6089 set ok 0
6090 }
5c5455dc
AC
6091 -re ".*A problem internal to GDB has been detected" {
6092 fail "${test} (GDB internal error)"
6093 set ok 0
6094 gdb_internal_error_resync
6095 }
43ff13b4 6096 timeout {
a20ce2c3 6097 fail "${test} (pattern ${index}) (timeout)"
43ff13b4
JM
6098 set ok 0
6099 }
085dd6e6 6100 }
43ff13b4 6101 } else {
a20ce2c3 6102 # unresolved "${test}, pattern ${index}"
085dd6e6
JM
6103 }
6104 }
6105 }
11cf8741 6106 if { ${ok} } {
a20ce2c3 6107 pass "${test}"
11cf8741
JM
6108 return 0
6109 } else {
6110 return 1
6111 }
085dd6e6
JM
6112}
6113
94696ad3
PA
6114# Spawn the gdb process.
6115#
6116# This doesn't expect any output or do any other initialization,
6117# leaving those to the caller.
6118#
6119# Overridable function -- you can override this function in your
6120# baseboard file.
6121
6122proc gdb_spawn { } {
6123 default_gdb_spawn
6124}
6125
98880d46
PA
6126# Spawn GDB with CMDLINE_FLAGS appended to the GDBFLAGS global.
6127
6128proc gdb_spawn_with_cmdline_opts { cmdline_flags } {
6129 global GDBFLAGS
6130
9dd1e642
TV
6131 save_vars { GDBFLAGS } {
6132 if {$GDBFLAGS != ""} {
6133 append GDBFLAGS " "
6134 }
6135 append GDBFLAGS $cmdline_flags
98880d46 6136
9dd1e642 6137 set res [gdb_spawn]
0bbeccb1 6138 }
98880d46
PA
6139
6140 return $res
6141}
6142
94696ad3
PA
6143# Start gdb running, wait for prompt, and disable the pagers.
6144
6145# Overridable function -- you can override this function in your
6146# baseboard file.
6147
c906108c
SS
6148proc gdb_start { } {
6149 default_gdb_start
6150}
6151
6152proc gdb_exit { } {
6153 catch default_gdb_exit
6154}
6155
60b3033e
PA
6156# Return true if we can spawn a program on the target and attach to
6157# it.
6158
11c19d73 6159proc can_spawn_for_attach { } {
2c8c5d37
PA
6160 # We use exp_pid to get the inferior's pid, assuming that gives
6161 # back the pid of the program. On remote boards, that would give
6162 # us instead the PID of e.g., the ssh client, etc.
d4c45423 6163 if {[is_remote target]} {
11c19d73 6164 verbose -log "can't spawn for attach (target is remote)"
60b3033e
PA
6165 return 0
6166 }
6167
6168 # The "attach" command doesn't make sense when the target is
6169 # stub-like, where GDB finds the program already started on
6170 # initial connection.
6171 if {[target_info exists use_gdb_stub]} {
11c19d73 6172 verbose -log "can't spawn for attach (target is stub)"
60b3033e
PA
6173 return 0
6174 }
6175
6176 # Assume yes.
6177 return 1
6178}
6179
a7e6a19e
TY
6180# Centralize the failure checking of "attach" command.
6181# Return 0 if attach failed, otherwise return 1.
6182
6183proc gdb_attach { testpid args } {
6184 parse_args {
6185 {pattern ""}
6186 }
6187
6188 if { [llength $args] != 0 } {
6189 error "Unexpected arguments: $args"
6190 }
6191
6192 gdb_test_multiple "attach $testpid" "attach" {
6193 -re -wrap "Attaching to.*ptrace: Operation not permitted\\." {
6194 unsupported "$gdb_test_name (Operation not permitted)"
6195 return 0
6196 }
6197 -re -wrap "$pattern" {
6198 pass $gdb_test_name
6199 return 1
6200 }
6201 }
6202
6203 return 0
6204}
6205
b750766a
LS
6206# Start gdb with "--pid $TESTPID" on the command line and wait for the prompt.
6207# Return 1 if GDB managed to start and attach to the process, 0 otherwise.
6208
6209proc_with_prefix gdb_spawn_attach_cmdline { testpid } {
6210 if ![can_spawn_for_attach] {
6211 # The caller should have checked can_spawn_for_attach itself
6212 # before getting here.
6213 error "can't spawn for attach with this target/board"
6214 }
6215
6216 set test "start gdb with --pid"
6217 set res [gdb_spawn_with_cmdline_opts "-quiet --pid=$testpid"]
6218 if { $res != 0 } {
6219 fail $test
6220 return 0
6221 }
6222
6223 gdb_test_multiple "" "$test" {
6224 -re -wrap "ptrace: Operation not permitted\\." {
78088b89 6225 unsupported "$gdb_test_name (operation not permitted)"
b750766a
LS
6226 return 0
6227 }
6228 -re -wrap "ptrace: No such process\\." {
6229 fail "$gdb_test_name (no such process)"
6230 return 0
6231 }
6232 -re -wrap "Attaching to process $testpid\r\n.*" {
6233 pass $gdb_test_name
6234 }
6235 }
6236
6237 # Check that we actually attached to a process, in case the
6238 # error message is not caught by the patterns above.
6239 gdb_test_multiple "info thread" "" {
6240 -re -wrap "No threads\\." {
6241 fail "$gdb_test_name (no thread)"
6242 }
6243 -re -wrap "Id.*" {
6244 pass $gdb_test_name
6245 return 1
6246 }
6247 }
6248
6249 return 0
6250}
6251
2c8c5d37
PA
6252# Kill a progress previously started with spawn_wait_for_attach, and
6253# reap its wait status. PROC_SPAWN_ID is the spawn id associated with
6254# the process.
6255
6256proc kill_wait_spawned_process { proc_spawn_id } {
6257 set pid [exp_pid -i $proc_spawn_id]
6258
6259 verbose -log "killing ${pid}"
6260 remote_exec build "kill -9 ${pid}"
6261
6262 verbose -log "closing ${proc_spawn_id}"
6263 catch "close -i $proc_spawn_id"
6264 verbose -log "waiting for ${proc_spawn_id}"
6265
6266 # If somehow GDB ends up still attached to the process here, a
6267 # blocking wait hangs until gdb is killed (or until gdb / the
6268 # ptracer reaps the exit status too, but that won't happen because
6269 # something went wrong.) Passing -nowait makes expect tell Tcl to
6270 # wait for the PID in the background. That's fine because we
6271 # don't care about the exit status. */
6272 wait -nowait -i $proc_spawn_id
2518ce94 6273 clean_up_spawn_id target $proc_spawn_id
2c8c5d37
PA
6274}
6275
6276# Returns the process id corresponding to the given spawn id.
6277
6278proc spawn_id_get_pid { spawn_id } {
6279 set testpid [exp_pid -i $spawn_id]
6280
6281 if { [istarget "*-*-cygwin*"] } {
6282 # testpid is the Cygwin PID, GDB uses the Windows PID, which
6283 # might be different due to the way fork/exec works.
6284 set testpid [ exec ps -e | gawk "{ if (\$1 == $testpid) print \$4; }" ]
6285 }
6286
6287 return $testpid
6288}
6289
4c92ff2c 6290# Start a set of programs running and then wait for a bit, to be sure
2c8c5d37
PA
6291# that they can be attached to. Return a list of processes spawn IDs,
6292# one element for each process spawned. It's a test error to call
6293# this when [can_spawn_for_attach] is false.
4c92ff2c
PA
6294
6295proc spawn_wait_for_attach { executable_list } {
2c8c5d37 6296 set spawn_id_list {}
4c92ff2c 6297
11c19d73
TY
6298 if ![can_spawn_for_attach] {
6299 # The caller should have checked can_spawn_for_attach itself
6300 # before getting here.
6301 error "can't spawn for attach with this target/board"
6302 }
6303
4c92ff2c 6304 foreach {executable} $executable_list {
2c8c5d37
PA
6305 # Note we use Expect's spawn, not Tcl's exec, because with
6306 # spawn we control when to wait for/reap the process. That
6307 # allows killing the process by PID without being subject to
6308 # pid-reuse races.
6309 lappend spawn_id_list [remote_spawn target $executable]
4c92ff2c
PA
6310 }
6311
6312 sleep 2
6313
2c8c5d37 6314 return $spawn_id_list
4c92ff2c
PA
6315}
6316
e63b55d1
NS
6317#
6318# gdb_load_cmd -- load a file into the debugger.
6319# ARGS - additional args to load command.
6320# return a -1 if anything goes wrong.
6321#
6322proc gdb_load_cmd { args } {
6323 global gdb_prompt
6324
6325 if [target_info exists gdb_load_timeout] {
6326 set loadtimeout [target_info gdb_load_timeout]
6327 } else {
6328 set loadtimeout 1600
6329 }
6330 send_gdb "load $args\n"
e91528f0 6331 verbose "Timeout is now $loadtimeout seconds" 2
e63b55d1
NS
6332 gdb_expect $loadtimeout {
6333 -re "Loading section\[^\r\]*\r\n" {
6334 exp_continue
6335 }
6336 -re "Start address\[\r\]*\r\n" {
6337 exp_continue
6338 }
6339 -re "Transfer rate\[\r\]*\r\n" {
6340 exp_continue
6341 }
6342 -re "Memory access error\[^\r\]*\r\n" {
6343 perror "Failed to load program"
6344 return -1
6345 }
6346 -re "$gdb_prompt $" {
6347 return 0
6348 }
6349 -re "(.*)\r\n$gdb_prompt " {
30711c89 6350 perror "Unexpected response from 'load' -- $expect_out(1,string)"
e63b55d1
NS
6351 return -1
6352 }
6353 timeout {
c4b347c7 6354 perror "Timed out trying to load $args."
e63b55d1
NS
6355 return -1
6356 }
6357 }
6358 return -1
6359}
6360
2d338fa9
TT
6361# Invoke "gcore". CORE is the name of the core file to write. TEST
6362# is the name of the test case. This will return 1 if the core file
6363# was created, 0 otherwise. If this fails to make a core file because
6364# this configuration of gdb does not support making core files, it
6365# will call "unsupported", not "fail". However, if this fails to make
6366# a core file for some other reason, then it will call "fail".
6367
6368proc gdb_gcore_cmd {core test} {
6369 global gdb_prompt
6370
6371 set result 0
f0cb4aa9
TV
6372
6373 set re_unsupported \
6374 "(?:Can't create a corefile|Target does not support core file generation\\.)"
6375
6376 with_timeout_factor 3 {
6377 gdb_test_multiple "gcore $core" $test {
6378 -re -wrap "Saved corefile .*" {
6379 pass $test
6380 set result 1
6381 }
6382 -re -wrap $re_unsupported {
6383 unsupported $test
6384 }
2d338fa9
TT
6385 }
6386 }
6387
6388 return $result
6389}
6390
fac51dd9
DE
6391# Load core file CORE. TEST is the name of the test case.
6392# This will record a pass/fail for loading the core file.
6393# Returns:
6394# 1 - core file is successfully loaded
6395# 0 - core file loaded but has a non fatal error
6396# -1 - core file failed to load
6397
6398proc gdb_core_cmd { core test } {
6399 global gdb_prompt
6400
4f424bb1 6401 gdb_test_multiple "core $core" "$test" {
fac51dd9
DE
6402 -re "\\\[Thread debugging using \[^ \r\n\]* enabled\\\]\r\n" {
6403 exp_continue
6404 }
6405 -re " is not a core dump:.*\r\n$gdb_prompt $" {
4f424bb1 6406 fail "$test (bad file format)"
fac51dd9
DE
6407 return -1
6408 }
3217502e 6409 -re -wrap "[string_to_regexp $core]: No such file or directory.*" {
4f424bb1 6410 fail "$test (file not found)"
fac51dd9
DE
6411 return -1
6412 }
6413 -re "Couldn't find .* registers in core file.*\r\n$gdb_prompt $" {
4f424bb1 6414 fail "$test (incomplete note section)"
fac51dd9
DE
6415 return 0
6416 }
6417 -re "Core was generated by .*\r\n$gdb_prompt $" {
4f424bb1 6418 pass "$test"
fac51dd9
DE
6419 return 1
6420 }
6421 -re ".*$gdb_prompt $" {
4f424bb1 6422 fail "$test"
fac51dd9
DE
6423 return -1
6424 }
6425 timeout {
4f424bb1 6426 fail "$test (timeout)"
fac51dd9
DE
6427 return -1
6428 }
6429 }
6430 fail "unsupported output from 'core' command"
6431 return -1
6432}
6433
759f0f0b
PA
6434# Return the filename to download to the target and load on the target
6435# for this shared library. Normally just LIBNAME, unless shared libraries
6436# for this target have separate link and load images.
6437
6438proc shlib_target_file { libname } {
6439 return $libname
6440}
6441
6442# Return the filename GDB will load symbols from when debugging this
6443# shared library. Normally just LIBNAME, unless shared libraries for
6444# this target have separate link and load images.
6445
6446proc shlib_symbol_file { libname } {
6447 return $libname
6448}
6449
56744f0a
JJ
6450# Return the filename to download to the target and load for this
6451# executable. Normally just BINFILE unless it is renamed to something
6452# else for this target.
6453
6454proc exec_target_file { binfile } {
6455 return $binfile
6456}
6457
6458# Return the filename GDB will load symbols from when debugging this
6459# executable. Normally just BINFILE unless executables for this target
6460# have separate files for symbols.
6461
6462proc exec_symbol_file { binfile } {
6463 return $binfile
6464}
6465
6466# Rename the executable file. Normally this is just BINFILE1 being renamed
6467# to BINFILE2, but some targets require multiple binary files.
6468proc gdb_rename_execfile { binfile1 binfile2 } {
faf067f1
JK
6469 file rename -force [exec_target_file ${binfile1}] \
6470 [exec_target_file ${binfile2}]
56744f0a 6471 if { [exec_target_file ${binfile1}] != [exec_symbol_file ${binfile1}] } {
faf067f1
JK
6472 file rename -force [exec_symbol_file ${binfile1}] \
6473 [exec_symbol_file ${binfile2}]
56744f0a
JJ
6474 }
6475}
6476
6477# "Touch" the executable file to update the date. Normally this is just
6478# BINFILE, but some targets require multiple files.
6479proc gdb_touch_execfile { binfile } {
faf067f1
JK
6480 set time [clock seconds]
6481 file mtime [exec_target_file ${binfile}] $time
56744f0a 6482 if { [exec_target_file ${binfile}] != [exec_symbol_file ${binfile}] } {
faf067f1 6483 file mtime [exec_symbol_file ${binfile}] $time
56744f0a
JJ
6484 }
6485}
6486
80d6c798
TV
6487# Override of dejagnu's remote_upload, which doesn't handle remotedir.
6488
6489rename remote_upload dejagnu_remote_upload
6490proc remote_upload { dest srcfile args } {
6491 if { [is_remote $dest] && [board_info $dest exists remotedir] } {
6492 set remotedir [board_info $dest remotedir]
6493 if { ![string match "$remotedir*" $srcfile] } {
6494 # Use hardcoded '/' as separator, as in dejagnu's remote_download.
6495 set srcfile $remotedir/$srcfile
6496 }
6497 }
6498
6499 return [dejagnu_remote_upload $dest $srcfile {*}$args]
6500}
6501
7817ea46
SM
6502# Like remote_download but provides a gdb-specific behavior.
6503#
6504# If the destination board is remote, the local file FROMFILE is transferred as
6505# usual with remote_download to TOFILE on the remote board. The destination
6506# filename is added to the CLEANFILES global, so it can be cleaned up at the
6507# end of the test.
6508#
6509# If the destination board is local, the destination path TOFILE is passed
6510# through standard_output_file, and FROMFILE is copied there.
6511#
6512# In both cases, if TOFILE is omitted, it defaults to the [file tail] of
6513# FROMFILE.
44ee8174
TT
6514
6515proc gdb_remote_download {dest fromfile {tofile {}}} {
7817ea46
SM
6516 # If TOFILE is not given, default to the same filename as FROMFILE.
6517 if {[string length $tofile] == 0} {
6518 set tofile [file tail $fromfile]
44ee8174 6519 }
ce4ea2bb 6520
7817ea46
SM
6521 if {[is_remote $dest]} {
6522 # When the DEST is remote, we simply send the file to DEST.
7808a1f7 6523 global cleanfiles_target cleanfiles_host
44ee8174 6524
7817ea46 6525 set destname [remote_download $dest $fromfile $tofile]
7808a1f7
TV
6526 if { $dest == "target" } {
6527 lappend cleanfiles_target $destname
6528 } elseif { $dest == "host" } {
6529 lappend cleanfiles_host $destname
6530 }
93f02886 6531
7817ea46
SM
6532 return $destname
6533 } else {
8392fa22
SM
6534 # When the DEST is local, we copy the file to the test directory (where
6535 # the executable is).
6536 #
6537 # Note that we pass TOFILE through standard_output_file, regardless of
6538 # whether it is absolute or relative, because we don't want the tests
6539 # to be able to write outside their standard output directory.
6540
7817ea46 6541 set tofile [standard_output_file $tofile]
93f02886 6542
7817ea46
SM
6543 file copy -force $fromfile $tofile
6544
6545 return $tofile
6546 }
93f02886
DJ
6547}
6548
4b4f2a7d 6549# Copy shlib FILE to the target.
93f02886 6550
4b4f2a7d 6551proc gdb_download_shlib { file } {
1850ef87
TV
6552 set target_file [shlib_target_file $file]
6553 if { [is_remote host] } {
6554 remote_download host $target_file
6555 }
6556 return [gdb_remote_download target $target_file]
4b4f2a7d
TV
6557}
6558
6559# Set solib-search-path to allow gdb to locate shlib FILE.
6560
6561proc gdb_locate_shlib { file } {
c708f4d2
AB
6562 global gdb_spawn_id
6563
6564 if ![info exists gdb_spawn_id] {
6565 perror "gdb_load_shlib: GDB is not running"
6566 }
6567
1850ef87
TV
6568 if { [is_remote target] || [is_remote host] } {
6569 # If the target or host is remote, we need to tell gdb where to find
6570 # the libraries.
6571 } else {
4b4f2a7d 6572 return
6e774b13 6573 }
fca4cfd9 6574
4b4f2a7d
TV
6575 # We could set this even when not testing remotely, but a user
6576 # generally won't set it unless necessary. In order to make the tests
6577 # more like the real-life scenarios, we don't set it for local testing.
1850ef87
TV
6578 if { [is_remote host] } {
6579 set solib_search_path [board_info host remotedir]
6580 if { $solib_search_path == "" } {
6581 set solib_search_path .
6582 }
6583 } else {
6584 set solib_search_path [file dirname $file]
6585 }
6586
6587 gdb_test_no_output "set solib-search-path $solib_search_path" \
4b4f2a7d
TV
6588 "set solib-search-path for [file tail $file]"
6589}
6590
6591# Copy shlib FILE to the target and set solib-search-path to allow gdb to
6592# locate it.
6593
6594proc gdb_load_shlib { file } {
6595 set dest [gdb_download_shlib $file]
6596 gdb_locate_shlib $file
fca4cfd9 6597 return $dest
93f02886
DJ
6598}
6599
c906108c 6600#
5b80f00d
PA
6601# gdb_load -- load a file into the debugger. Specifying no file
6602# defaults to the executable currently being debugged.
7e60a48e 6603# The return value is 0 for success, -1 for failure.
2db8e78e 6604# Many files in config/*.exp override this procedure.
c906108c
SS
6605#
6606proc gdb_load { arg } {
5b80f00d
PA
6607 if { $arg != "" } {
6608 return [gdb_file_cmd $arg]
6609 }
7e60a48e 6610 return 0
c906108c
SS
6611}
6612
9f6c202e 6613#
8d45c3a8 6614# with_set -- Execute BODY and set VAR temporary to VAL for the
cf2b2075 6615# duration.
9f6c202e 6616#
8d45c3a8 6617proc with_set { var val body } {
9f6c202e 6618 set save ""
8d45c3a8
TV
6619 set show_re \
6620 "is (\[^\r\n\]+)\\."
6621 gdb_test_multiple "show $var" "" {
6622 -re -wrap $show_re {
9f6c202e
TV
6623 set save $expect_out(1,string)
6624 }
6625 }
6626
7f21d259
TV
6627 # Handle 'set to "auto" (currently "i386")'.
6628 set save [regsub {^set to} $save ""]
6629 set save [regsub {\([^\r\n]+\)$} $save ""]
6630 set save [string trim $save]
6631 set save [regsub -all {^"|"$} $save ""]
6632
9f6c202e 6633 if { $save == "" } {
8d45c3a8 6634 perror "Did not manage to set $var"
cf2b2075 6635 } else {
8d45c3a8 6636 # Set var.
a68f7e98
AB
6637 gdb_test_multiple "set $var $val" "" {
6638 -re -wrap "^" {
7f21d259
TV
6639 }
6640 -re -wrap " is set to \"?$val\"?\\." {
6641 }
6642 }
9f6c202e
TV
6643 }
6644
cf2b2075
TV
6645 set code [catch {uplevel 1 $body} result]
6646
8d45c3a8 6647 # Restore saved setting.
cf2b2075 6648 if { $save != "" } {
a68f7e98
AB
6649 gdb_test_multiple "set $var $save" "" {
6650 -re -wrap "^" {
7f21d259
TV
6651 }
6652 -re -wrap "is set to \"?$save\"?( \\(\[^)\]*\\))?\\." {
6653 }
6654 }
cf2b2075
TV
6655 }
6656
6657 if {$code == 1} {
6658 global errorInfo errorCode
6659 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
6660 } else {
6661 return -code $code $result
6662 }
6663}
6664
8d45c3a8
TV
6665#
6666# with_complaints -- Execute BODY and set complaints temporary to N for the
6667# duration.
6668#
6669proc with_complaints { n body } {
6670 return [uplevel [list with_set complaints $n $body]]
6671}
6672
cf2b2075
TV
6673#
6674# gdb_load_no_complaints -- As gdb_load, but in addition verifies that
6675# loading caused no symbol reading complaints.
6676#
6677proc gdb_load_no_complaints { arg } {
6678 global gdb_prompt gdb_file_cmd_msg decimal
9f6c202e 6679
cf2b2075
TV
6680 # Temporarily set complaint to a small non-zero number.
6681 with_complaints 5 {
6682 gdb_load $arg
6683 }
9f6c202e
TV
6684
6685 # Verify that there were no complaints.
d53f8a84
TV
6686 set re \
6687 [multi_line \
58eaf4e9
TV
6688 "^(Reading symbols from \[^\r\n\]*" \
6689 ")+(Expanding full symbols from \[^\r\n\]*" \
d53f8a84 6690 ")?$gdb_prompt $"]
9f6c202e 6691 gdb_assert {[regexp $re $gdb_file_cmd_msg]} "No complaints"
9f6c202e
TV
6692}
6693
b741e217
DJ
6694# gdb_reload -- load a file into the target. Called before "running",
6695# either the first time or after already starting the program once,
6696# for remote targets. Most files that override gdb_load should now
6697# override this instead.
75d04512
SM
6698#
6699# INFERIOR_ARGS contains the arguments to pass to the inferiors, as a
6700# single string to get interpreted by a shell. If the target board
6701# overriding gdb_reload is a "stub", then it should arrange things such
6702# these arguments make their way to the inferior process.
b741e217 6703
75d04512 6704proc gdb_reload { {inferior_args {}} } {
b741e217
DJ
6705 # For the benefit of existing configurations, default to gdb_load.
6706 # Specifying no file defaults to the executable currently being
6707 # debugged.
6708 return [gdb_load ""]
6709}
6710
c906108c
SS
6711proc gdb_continue { function } {
6712 global decimal
6713
ae59b1da 6714 return [gdb_test "continue" ".*Breakpoint $decimal, $function .*" "continue to $function"]
c906108c
SS
6715}
6716
d4d5b571
TV
6717# Clean the directory containing the standard output files.
6718
6719proc clean_standard_output_dir {} {
6720 if { [info exists ::GDB_PERFTEST_MODE] && $::GDB_PERFTEST_MODE == "run" } {
6721 # Don't clean, use $GDB_PERFTEST_MODE == compile results.
6722 return
6723 }
6724
6725 # Directory containing the standard output files.
6726 set standard_output_dir [file normalize [standard_output_file ""]]
6727
6728 # Ensure that standard_output_dir is clean, or only contains
6729 # gdb.log / gdb.sum.
6730 set log_file_info [split [log_file -info]]
6731 set log_file [file normalize [lindex $log_file_info end]]
6732 if { $log_file == [file normalize [standard_output_file gdb.log]] } {
6733 # Dir already contains active gdb.log. Don't remove the dir, but
6734 # check that it's clean otherwise.
6735 set res [glob -directory $standard_output_dir -tails *]
6736 set ok 1
6737 foreach f $res {
6738 if { $f == "gdb.log" } {
6739 continue
6740 }
6741 if { $f == "gdb.sum" } {
6742 continue
6743 }
6744 set ok 0
6745 }
6746 if { !$ok } {
6747 error "standard output dir not clean"
6748 }
6749 } else {
6750 # Start with a clean dir.
6751 remote_exec build "rm -rf $standard_output_dir"
6752 }
6753
6754}
6755
a8a56685 6756# Default implementation of gdb_init.
73c9764f 6757proc default_gdb_init { test_file_name } {
277254ba 6758 global gdb_wrapper_initialized
f6838f81 6759 global gdb_wrapper_target
0a6d0306 6760 global gdb_test_file_name
7808a1f7
TV
6761 global cleanfiles_target
6762 global cleanfiles_host
73c9764f 6763 global pf_prefix
277254ba 6764
a8a56685
TV
6765 # Reset the timeout value to the default. This way, any testcase
6766 # that changes the timeout value without resetting it cannot affect
6767 # the timeout used in subsequent testcases.
6768 global gdb_test_timeout
6769 global timeout
6770 set timeout $gdb_test_timeout
6771
6772 if { [regexp ".*gdb\.reverse\/.*" $test_file_name]
6773 && [target_info exists gdb_reverse_timeout] } {
6774 set timeout [target_info gdb_reverse_timeout]
6775 }
6776
6777 # If GDB_INOTIFY is given, check for writes to '.'. This is a
6778 # debugging tool to help confirm that the test suite is
6779 # parallel-safe. You need "inotifywait" from the
6780 # inotify-tools package to use this.
6781 global GDB_INOTIFY inotify_pid
6782 if {[info exists GDB_INOTIFY] && ![info exists inotify_pid]} {
6783 global outdir tool inotify_log_file
6784
6785 set exclusions {outputs temp gdb[.](log|sum) cache}
6786 set exclusion_re ([join $exclusions |])
6787
6788 set inotify_log_file [standard_temp_file inotify.out]
6789 set inotify_pid [exec inotifywait -r -m -e move,create,delete . \
6790 --exclude $exclusion_re \
6791 |& tee -a $outdir/$tool.log $inotify_log_file &]
6792
6793 # Wait for the watches; hopefully this is long enough.
6794 sleep 2
6795
6796 # Clear the log so that we don't emit a warning the first time
6797 # we check it.
6798 set fd [open $inotify_log_file w]
6799 close $fd
6800 }
6801
6802 # Block writes to all banned variables, and invocation of all
6803 # banned procedures...
6804 global banned_variables
6805 global banned_procedures
6806 global banned_traced
6807 if (!$banned_traced) {
6808 foreach banned_var $banned_variables {
6809 global "$banned_var"
6810 trace add variable "$banned_var" write error
6811 }
6812 foreach banned_proc $banned_procedures {
6813 global "$banned_proc"
6814 trace add execution "$banned_proc" enter error
6815 }
6816 set banned_traced 1
6817 }
6818
6819 # We set LC_ALL, LC_CTYPE, and LANG to C so that we get the same
6820 # messages as expected.
6821 setenv LC_ALL C
6822 setenv LC_CTYPE C
6823 setenv LANG C
6824
1af4c9c4
TT
6825 # Don't let a .inputrc file or an existing setting of INPUTRC mess
6826 # up the test results. Certain tests (style tests and TUI tests)
6827 # want to set the terminal to a non-"dumb" value, and for those we
6828 # want to disable bracketed paste mode. Versions of Readline
6829 # before 8.0 will not understand this and will issue a warning.
6830 # We tried using a $if to guard it, but Readline 8.1 had a bug in
6831 # its version-comparison code that prevented this for working.
6832 setenv INPUTRC [cached_file inputrc "set enable-bracketed-paste off"]
a8a56685
TV
6833
6834 # This disables style output, which would interfere with many
6835 # tests.
4ebfd53d 6836 setenv NO_COLOR sorry
a8a56685 6837
f717822d
TT
6838 # This setting helps detect bugs in the Python code and doesn't
6839 # seem to have a significant downside for the tests.
6840 setenv PYTHONMALLOC malloc_debug
6841
cfcbd506
TV
6842 # If DEBUGINFOD_URLS is set, gdb will try to download sources and
6843 # debug info for f.i. system libraries. Prevent this.
86091eae
TV
6844 if { [is_remote host] } {
6845 # See initialization of INTERNAL_GDBFLAGS.
6846 } else {
6847 # Using "set debuginfod enabled off" in INTERNAL_GDBFLAGS interferes
6848 # with the gdb.debuginfod test-cases, so use the unsetenv method for
6849 # non-remote host.
6850 unset -nocomplain ::env(DEBUGINFOD_URLS)
6851 }
cfcbd506 6852
a8a56685
TV
6853 # Ensure that GDBHISTFILE and GDBHISTSIZE are removed from the
6854 # environment, we don't want these modifications to the history
6855 # settings.
6856 unset -nocomplain ::env(GDBHISTFILE)
6857 unset -nocomplain ::env(GDBHISTSIZE)
6858
47918cca
AB
6859 # Ensure that XDG_CONFIG_HOME is not set. Some tests setup a fake
6860 # home directory in order to test loading settings from gdbinit.
6861 # If XDG_CONFIG_HOME is set then GDB will load a gdbinit from
6862 # there (if one is present) rather than the home directory setup
6863 # in the test.
6864 unset -nocomplain ::env(XDG_CONFIG_HOME)
6865
a8a56685
TV
6866 # Initialize GDB's pty with a fixed size, to make sure we avoid pagination
6867 # during startup. See "man expect" for details about stty_init.
6868 global stty_init
6869 set stty_init "rows 25 cols 80"
6870
6871 # Some tests (for example gdb.base/maint.exp) shell out from gdb to use
6872 # grep. Clear GREP_OPTIONS to make the behavior predictable,
6873 # especially having color output turned on can cause tests to fail.
6874 setenv GREP_OPTIONS ""
6875
6876 # Clear $gdbserver_reconnect_p.
6877 global gdbserver_reconnect_p
6878 set gdbserver_reconnect_p 1
6879 unset gdbserver_reconnect_p
6880
6881 # Clear $last_loaded_file
6882 global last_loaded_file
6883 unset -nocomplain last_loaded_file
6884
6885 # Reset GDB number of instances
6886 global gdb_instances
6887 set gdb_instances 0
6888
7808a1f7
TV
6889 set cleanfiles_target {}
6890 set cleanfiles_host {}
93f02886 6891
73c9764f 6892 set gdb_test_file_name [file rootname [file tail $test_file_name]]
0a6d0306 6893
d4d5b571
TV
6894 clean_standard_output_dir
6895
277254ba
MS
6896 # Make sure that the wrapper is rebuilt
6897 # with the appropriate multilib option.
f6838f81
DJ
6898 if { $gdb_wrapper_target != [current_target_name] } {
6899 set gdb_wrapper_initialized 0
6900 }
277254ba 6901
7b433602
JB
6902 # Unlike most tests, we have a small number of tests that generate
6903 # a very large amount of output. We therefore increase the expect
ff604a67
MR
6904 # buffer size to be able to contain the entire test output. This
6905 # is especially needed by gdb.base/info-macros.exp.
6906 match_max -d 65536
8d417781
PM
6907 # Also set this value for the currently running GDB.
6908 match_max [match_max -d]
c906108c
SS
6909
6910 # We want to add the name of the TCL testcase to the PASS/FAIL messages.
73c9764f 6911 set pf_prefix "[file tail [file dirname $test_file_name]]/[file tail $test_file_name]:"
c906108c 6912
4ec70201 6913 global gdb_prompt
c906108c 6914 if [target_info exists gdb_prompt] {
4ec70201 6915 set gdb_prompt [target_info gdb_prompt]
c906108c
SS
6916 } else {
6917 set gdb_prompt "\\(gdb\\)"
6918 }
e11ac3a3
JK
6919 global use_gdb_stub
6920 if [info exists use_gdb_stub] {
6921 unset use_gdb_stub
6922 }
a8a56685
TV
6923
6924 gdb_setup_known_globals
6925
6926 if { [info procs ::gdb_tcl_unknown] != "" } {
6927 # Dejagnu overrides proc unknown. The dejagnu version may trigger in a
6928 # test-case but abort the entire test run. To fix this, we install a
6929 # local version here, which reverts dejagnu's override, and restore
6930 # dejagnu's version in gdb_finish.
6931 rename ::unknown ::dejagnu_unknown
6932 proc unknown { args } {
6933 # Use tcl's unknown.
a3ca48cd
TV
6934 set cmd [lindex $args 0]
6935 unresolved "testcase aborted due to invalid command name: $cmd"
a8a56685
TV
6936 return [uplevel 1 ::gdb_tcl_unknown $args]
6937 }
6938 }
50c6682d
TV
6939
6940 # Dejagnu version 1.6.3 and later produce an unresolved at the end of a
6941 # testcase if an error triggered, resetting errcnt and warncnt to 0, in
6942 # order to avoid errors in one test-case influencing the following
6943 # test-case. Do this manually here, to support older versions.
6944 global errcnt
6945 global warncnt
6946 set errcnt 0
6947 set warncnt 0
c906108c
SS
6948}
6949
3d338901
DE
6950# Return a path using GDB_PARALLEL.
6951# ARGS is a list of path elements to append to "$objdir/$GDB_PARALLEL".
6952# GDB_PARALLEL must be defined, the caller must check.
6953#
6954# The default value for GDB_PARALLEL is, canonically, ".".
6955# The catch is that tests don't expect an additional "./" in file paths so
6956# omit any directory for the default case.
6957# GDB_PARALLEL is written as "yes" for the default case in Makefile.in to mark
6958# its special handling.
6959
6960proc make_gdb_parallel_path { args } {
6961 global GDB_PARALLEL objdir
6962 set joiner [list "file" "join" $objdir]
2151ccc5 6963 if { [info exists GDB_PARALLEL] && $GDB_PARALLEL != "yes" } {
3d338901
DE
6964 lappend joiner $GDB_PARALLEL
6965 }
6966 set joiner [concat $joiner $args]
6967 return [eval $joiner]
6968}
6969
0a6d0306 6970# Turn BASENAME into a full file name in the standard output
8a3e1f8d
TT
6971# directory. It is ok if BASENAME is the empty string; in this case
6972# the directory is returned.
0a6d0306
TT
6973
6974proc standard_output_file {basename} {
2151ccc5 6975 global objdir subdir gdb_test_file_name
0a6d0306 6976
2151ccc5
SM
6977 set dir [make_gdb_parallel_path outputs $subdir $gdb_test_file_name]
6978 file mkdir $dir
97dd8e07
CB
6979 # If running on MinGW, replace /c/foo with c:/foo
6980 if { [ishost *-*-mingw*] } {
038b97fc 6981 set dir [exec sh -c "cd ${dir} && pwd -W"]
97dd8e07 6982 }
2151ccc5 6983 return [file join $dir $basename]
0a6d0306
TT
6984}
6985
33ddd9fc
TV
6986# Turn BASENAME into a file name on host.
6987
6988proc host_standard_output_file { basename } {
6989 if { [is_remote host] } {
a653ec1f
TV
6990 set remotedir [board_info host remotedir]
6991 if { $remotedir == "" } {
623f8c6b
TV
6992 if { $basename == "" } {
6993 return "."
6994 }
a653ec1f
TV
6995 return $basename
6996 } else {
6997 return [join [list $remotedir $basename] "/"]
6998 }
33ddd9fc
TV
6999 } else {
7000 return [standard_output_file $basename]
7001 }
7002}
7003
f9e2e39d
AH
7004# Turn BASENAME into a full file name in the standard output directory. If
7005# GDB has been launched more than once then append the count, starting with
7006# a ".1" postfix.
7007
7008proc standard_output_file_with_gdb_instance {basename} {
7009 global gdb_instances
b3247276 7010 set count $gdb_instances
f9e2e39d
AH
7011
7012 if {$count == 0} {
7013 return [standard_output_file $basename]
7014 }
7015 return [standard_output_file ${basename}.${count}]
7016}
7017
4e234898
TT
7018# Return the name of a file in our standard temporary directory.
7019
7020proc standard_temp_file {basename} {
c4ef31bf
SM
7021 # Since a particular runtest invocation is only executing a single test
7022 # file at any given time, we can use the runtest pid to build the
7023 # path of the temp directory.
7024 set dir [make_gdb_parallel_path temp [pid]]
7025 file mkdir $dir
7026 return [file join $dir $basename]
4e234898
TT
7027}
7028
436b5e99
TV
7029# Rename file A to file B, if B does not already exists. Otherwise, leave B
7030# as is and delete A. Return 1 if rename happened.
7031
7032proc tentative_rename { a b } {
7033 global errorInfo errorCode
7034 set code [catch {file rename -- $a $b} result]
7035 if { $code == 1 && [lindex $errorCode 0] == "POSIX" \
7036 && [lindex $errorCode 1] == "EEXIST" } {
7037 file delete $a
7038 return 0
7039 }
7040 if {$code == 1} {
7041 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
7042 } elseif {$code > 1} {
7043 return -code $code $result
7044 }
7045 return 1
7046}
7047
7048# Create a file with name FILENAME and contents TXT in the cache directory.
7049# If EXECUTABLE, mark the new file for execution.
7050
7051proc cached_file { filename txt {executable 0}} {
7052 set filename [make_gdb_parallel_path cache $filename]
7053
7054 if { [file exists $filename] } {
7055 return $filename
7056 }
7057
0ba678c9
TV
7058 set dir [file dirname $filename]
7059 file mkdir $dir
7060
436b5e99
TV
7061 set tmp_filename $filename.[pid]
7062 set fd [open $tmp_filename w]
7063 puts $fd $txt
7064 close $fd
7065
7066 if { $executable } {
7067 exec chmod +x $tmp_filename
7068 }
7069 tentative_rename $tmp_filename $filename
7070
7071 return $filename
7072}
7073
7a0daa48
TV
7074# Return a wrapper around gdb that prevents generating a core file.
7075
7076proc gdb_no_core { } {
7077 set script \
7078 [list \
7079 "ulimit -c 0" \
7080 [join [list exec $::GDB {"$@"}]]]
7081 set script [join $script "\n"]
7082 return [cached_file gdb-no-core.sh $script 1]
7083}
7084
0a6d0306
TT
7085# Set 'testfile', 'srcfile', and 'binfile'.
7086#
7087# ARGS is a list of source file specifications.
7088# Without any arguments, the .exp file's base name is used to
7089# compute the source file name. The ".c" extension is added in this case.
7090# If ARGS is not empty, each entry is a source file specification.
d1c8a76d 7091# If the specification starts with a "." or "-", it is treated as a suffix
0a6d0306
TT
7092# to append to the .exp file's base name.
7093# If the specification is the empty string, it is treated as if it
7094# were ".c".
7095# Otherwise it is a file name.
7096# The first file in the list is used to set the 'srcfile' global.
7097# Each subsequent name is used to set 'srcfile2', 'srcfile3', etc.
7098#
7099# Most tests should call this without arguments.
7100#
7101# If a completely different binary file name is needed, then it
7102# should be handled in the .exp file with a suitable comment.
7103
7104proc standard_testfile {args} {
7105 global gdb_test_file_name
93c0ef37 7106 global subdir
686f09d0 7107 global gdb_test_file_last_vars
0a6d0306
TT
7108
7109 # Outputs.
7110 global testfile binfile
7111
7112 set testfile $gdb_test_file_name
7113 set binfile [standard_output_file ${testfile}]
7114
7115 if {[llength $args] == 0} {
7116 set args .c
7117 }
7118
686f09d0
TT
7119 # Unset our previous output variables.
7120 # This can help catch hidden bugs.
7121 if {[info exists gdb_test_file_last_vars]} {
7122 foreach varname $gdb_test_file_last_vars {
7123 global $varname
7124 catch {unset $varname}
7125 }
7126 }
7127 # 'executable' is often set by tests.
7128 set gdb_test_file_last_vars {executable}
7129
0a6d0306
TT
7130 set suffix ""
7131 foreach arg $args {
7132 set varname srcfile$suffix
7133 global $varname
7134
7135 # Handle an extension.
7136 if {$arg == ""} {
7137 set arg $testfile.c
d1c8a76d
TV
7138 } else {
7139 set first [string range $arg 0 0]
7140 if { $first == "." || $first == "-" } {
7141 set arg $testfile$arg
7142 }
0a6d0306
TT
7143 }
7144
7145 set $varname $arg
686f09d0 7146 lappend gdb_test_file_last_vars $varname
0a6d0306
TT
7147
7148 if {$suffix == ""} {
7149 set suffix 2
7150 } else {
7151 incr suffix
7152 }
7153 }
7154}
7155
7b356089
JB
7156# The default timeout used when testing GDB commands. We want to use
7157# the same timeout as the default dejagnu timeout, unless the user has
7158# already provided a specific value (probably through a site.exp file).
7159global gdb_test_timeout
7160if ![info exists gdb_test_timeout] {
7161 set gdb_test_timeout $timeout
7162}
7163
47050449
JB
7164# A list of global variables that GDB testcases should not use.
7165# We try to prevent their use by monitoring write accesses and raising
7166# an error when that happens.
7167set banned_variables { bug_id prms_id }
7168
abcc4978
PA
7169# A list of procedures that GDB testcases should not use.
7170# We try to prevent their use by monitoring invocations and raising
7171# an error when that happens.
7172set banned_procedures { strace }
7173
41b2c92d
PM
7174# gdb_init is called by runtest at start, but also by several
7175# tests directly; gdb_finish is only called from within runtest after
7176# each test source execution.
7177# Placing several traces by repetitive calls to gdb_init leads
7178# to problems, as only one trace is removed in gdb_finish.
7179# To overcome this possible problem, we add a variable that records
abcc4978
PA
7180# if the banned variables and procedures are already traced.
7181set banned_traced 0
41b2c92d 7182
a29d5112
AB
7183# Global array that holds the name of all global variables at the time
7184# a test script is started. After the test script has completed any
7185# global not in this list is deleted.
7186array set gdb_known_globals {}
7187
7188# Setup the GDB_KNOWN_GLOBALS array with the names of all current
7189# global variables.
7190proc gdb_setup_known_globals {} {
7191 global gdb_known_globals
7192
7193 array set gdb_known_globals {}
7194 foreach varname [info globals] {
7195 set gdb_known_globals($varname) 1
7196 }
7197}
7198
7199# Cleanup the global namespace. Any global not in the
7200# GDB_KNOWN_GLOBALS array is unset, this ensures we don't "leak"
7201# globals from one test script to another.
7202proc gdb_cleanup_globals {} {
7203 global gdb_known_globals gdb_persistent_globals
7204
7205 foreach varname [info globals] {
7206 if {![info exists gdb_known_globals($varname)]} {
7207 if { [info exists gdb_persistent_globals($varname)] } {
7208 continue
7209 }
7210 uplevel #0 unset $varname
7211 }
7212 }
7213}
7214
081e778c
TV
7215# Create gdb_tcl_unknown, a copy tcl's ::unknown, provided it's present as a
7216# proc.
7217set temp [interp create]
7218if { [interp eval $temp "info procs ::unknown"] != "" } {
7219 set old_args [interp eval $temp "info args ::unknown"]
7220 set old_body [interp eval $temp "info body ::unknown"]
7221 eval proc gdb_tcl_unknown {$old_args} {$old_body}
7222}
7223interp delete $temp
7224unset temp
7225
a8a56685
TV
7226# GDB implementation of ${tool}_init. Called right before executing the
7227# test-case.
7228# Overridable function -- you can override this function in your
7229# baseboard file.
7230proc gdb_init { args } {
7231 # A baseboard file overriding this proc and calling the default version
7232 # should behave the same as this proc. So, don't add code here, but to
7233 # the default version instead.
7234 return [default_gdb_init {*}$args]
c906108c
SS
7235}
7236
a8a56685
TV
7237# GDB implementation of ${tool}_finish. Called right after executing the
7238# test-case.
c906108c 7239proc gdb_finish { } {
a35cfb40
MR
7240 global gdbserver_reconnect_p
7241 global gdb_prompt
7808a1f7
TV
7242 global cleanfiles_target
7243 global cleanfiles_host
a29d5112 7244 global known_globals
93f02886 7245
081e778c
TV
7246 if { [info procs ::gdb_tcl_unknown] != "" } {
7247 # Restore dejagnu's version of proc unknown.
7248 rename ::unknown ""
7249 rename ::dejagnu_unknown ::unknown
7250 }
26783bce 7251
93f02886
DJ
7252 # Exit first, so that the files are no longer in use.
7253 gdb_exit
7254
7808a1f7
TV
7255 if { [llength $cleanfiles_target] > 0 } {
7256 eval remote_file target delete $cleanfiles_target
7257 set cleanfiles_target {}
7258 }
7259 if { [llength $cleanfiles_host] > 0 } {
7260 eval remote_file host delete $cleanfiles_host
7261 set cleanfiles_host {}
93f02886 7262 }
47050449
JB
7263
7264 # Unblock write access to the banned variables. Dejagnu typically
7265 # resets some of them between testcases.
7266 global banned_variables
abcc4978
PA
7267 global banned_procedures
7268 global banned_traced
7269 if ($banned_traced) {
41b2c92d
PM
7270 foreach banned_var $banned_variables {
7271 global "$banned_var"
7272 trace remove variable "$banned_var" write error
7273 }
abcc4978
PA
7274 foreach banned_proc $banned_procedures {
7275 global "$banned_proc"
7276 trace remove execution "$banned_proc" enter error
7277 }
7278 set banned_traced 0
47050449 7279 }
8c74a764
TV
7280
7281 global gdb_finish_hooks
7282 foreach gdb_finish_hook $gdb_finish_hooks {
7283 $gdb_finish_hook
7284 }
7285 set gdb_finish_hooks [list]
a29d5112
AB
7286
7287 gdb_cleanup_globals
c906108c
SS
7288}
7289
7290global debug_format
7a292a7a 7291set debug_format "unknown"
c906108c
SS
7292
7293# Run the gdb command "info source" and extract the debugging format
7294# information from the output and save it in debug_format.
7295
7296proc get_debug_format { } {
7297 global gdb_prompt
c906108c
SS
7298 global expect_out
7299 global debug_format
7300
7301 set debug_format "unknown"
7302 send_gdb "info source\n"
7303 gdb_expect 10 {
919d772c 7304 -re "Compiled with (.*) debugging format.\r\n.*$gdb_prompt $" {
c906108c
SS
7305 set debug_format $expect_out(1,string)
7306 verbose "debug format is $debug_format"
ae59b1da 7307 return 1
c906108c
SS
7308 }
7309 -re "No current source file.\r\n$gdb_prompt $" {
7310 perror "get_debug_format used when no current source file"
ae59b1da 7311 return 0
c906108c
SS
7312 }
7313 -re "$gdb_prompt $" {
7314 warning "couldn't check debug format (no valid response)."
ae59b1da 7315 return 1
c906108c
SS
7316 }
7317 timeout {
975531db 7318 warning "couldn't check debug format (timeout)."
ae59b1da 7319 return 1
c906108c
SS
7320 }
7321 }
7322}
7323
838ae6c4
JB
7324# Return true if FORMAT matches the debug format the current test was
7325# compiled with. FORMAT is a shell-style globbing pattern; it can use
7326# `*', `[...]', and so on.
7327#
7328# This function depends on variables set by `get_debug_format', above.
7329
7330proc test_debug_format {format} {
7331 global debug_format
7332
7333 return [expr [string match $format $debug_format] != 0]
7334}
7335
c906108c
SS
7336# Like setup_xfail, but takes the name of a debug format (DWARF 1,
7337# COFF, stabs, etc). If that format matches the format that the
7338# current test was compiled with, then the next test is expected to
7339# fail for any target. Returns 1 if the next test or set of tests is
7340# expected to fail, 0 otherwise (or if it is unknown). Must have
7341# previously called get_debug_format.
b55a4771 7342proc setup_xfail_format { format } {
4ec70201 7343 set ret [test_debug_format $format]
b55a4771 7344
d4c45423 7345 if {$ret} {
b55a4771
MS
7346 setup_xfail "*-*-*"
7347 }
ae59b1da 7348 return $ret
b55a4771 7349}
c906108c 7350
c6fee705
MC
7351# gdb_get_line_number TEXT [FILE]
7352#
7353# Search the source file FILE, and return the line number of the
0d7941a9 7354# first line containing TEXT. If no match is found, an error is thrown.
c6fee705
MC
7355#
7356# TEXT is a string literal, not a regular expression.
7357#
7358# The default value of FILE is "$srcdir/$subdir/$srcfile". If FILE is
7359# specified, and does not start with "/", then it is assumed to be in
7360# "$srcdir/$subdir". This is awkward, and can be fixed in the future,
7361# by changing the callers and the interface at the same time.
7362# In particular: gdb.base/break.exp, gdb.base/condbreak.exp,
7363# gdb.base/ena-dis-br.exp.
7364#
7365# Use this function to keep your test scripts independent of the
7366# exact line numbering of the source file. Don't write:
7367#
7368# send_gdb "break 20"
7369#
7370# This means that if anyone ever edits your test's source file,
7371# your test could break. Instead, put a comment like this on the
7372# source file line you want to break at:
7373#
7374# /* breakpoint spot: frotz.exp: test name */
7375#
7376# and then write, in your test script (which we assume is named
7377# frotz.exp):
7378#
7379# send_gdb "break [gdb_get_line_number "frotz.exp: test name"]\n"
7380#
7381# (Yes, Tcl knows how to handle the nested quotes and brackets.
7382# Try this:
7383# $ tclsh
7384# % puts "foo [lindex "bar baz" 1]"
7385# foo baz
7386# %
7387# Tcl is quite clever, for a little stringy language.)
7388#
7389# ===
7390#
7391# The previous implementation of this procedure used the gdb search command.
7392# This version is different:
7393#
7394# . It works with MI, and it also works when gdb is not running.
7395#
7396# . It operates on the build machine, not the host machine.
7397#
7398# . For now, this implementation fakes a current directory of
7399# $srcdir/$subdir to be compatible with the old implementation.
7400# This will go away eventually and some callers will need to
7401# be changed.
7402#
7403# . The TEXT argument is literal text and matches literally,
7404# not a regular expression as it was before.
7405#
7406# . State changes in gdb, such as changing the current file
7407# and setting $_, no longer happen.
7408#
7409# After a bit of time we can forget about the differences from the
7410# old implementation.
7411#
7412# --chastain 2004-08-05
7413
7414proc gdb_get_line_number { text { file "" } } {
7415 global srcdir
7416 global subdir
7417 global srcfile
c906108c 7418
d4c45423 7419 if {"$file" == ""} {
c6fee705
MC
7420 set file "$srcfile"
7421 }
d4c45423 7422 if {![regexp "^/" "$file"]} {
c6fee705 7423 set file "$srcdir/$subdir/$file"
c906108c
SS
7424 }
7425
d4c45423 7426 if {[catch { set fd [open "$file"] } message]} {
0d7941a9 7427 error "$message"
c906108c 7428 }
c6fee705
MC
7429
7430 set found -1
7431 for { set line 1 } { 1 } { incr line } {
d4c45423 7432 if {[catch { set nchar [gets "$fd" body] } message]} {
0d7941a9 7433 error "$message"
c6fee705 7434 }
d4c45423 7435 if {$nchar < 0} {
c6fee705
MC
7436 break
7437 }
d4c45423 7438 if {[string first "$text" "$body"] >= 0} {
c6fee705
MC
7439 set found $line
7440 break
7441 }
7442 }
7443
d4c45423 7444 if {[catch { close "$fd" } message]} {
0d7941a9
KS
7445 error "$message"
7446 }
7447
7448 if {$found == -1} {
7449 error "undefined tag \"$text\""
c6fee705
MC
7450 }
7451
7452 return $found
c906108c
SS
7453}
7454
b477a5e6
PA
7455# Continue the program until it ends.
7456#
fda326dd
TT
7457# MSSG is the error message that gets printed. If not given, a
7458# default is used.
7459# COMMAND is the command to invoke. If not given, "continue" is
7460# used.
eceb0c5f
TT
7461# ALLOW_EXTRA is a flag indicating whether the test should expect
7462# extra output between the "Continuing." line and the program
7463# exiting. By default it is zero; if nonzero, any extra output
7464# is accepted.
fda326dd 7465
eceb0c5f 7466proc gdb_continue_to_end {{mssg ""} {command continue} {allow_extra 0}} {
e11ac3a3 7467 global inferior_exited_re use_gdb_stub
7a292a7a 7468
fda326dd
TT
7469 if {$mssg == ""} {
7470 set text "continue until exit"
7471 } else {
7472 set text "continue until exit at $mssg"
7473 }
ccdb8875 7474
eceb0c5f
TT
7475 if {$allow_extra} {
7476 set extra ".*"
ccdb8875
PA
7477 } elseif {[istarget *-*-cygwin*] || [istarget *-*-mingw*]} {
7478 # On Windows, even on supposedly single-threaded programs, we
7479 # may see thread exit output when running to end, for threads
7480 # spawned by the runtime. E.g.:
7481 #
7482 # (gdb) continue
7483 # Continuing.
7484 # [Thread 14364.0x21d4 exited with code 0]
7485 # [Thread 14364.0x4374 exited with code 0]
7486 # [Thread 14364.0x3aec exited with code 0]
7487 # [Thread 14364.0x3368 exited with code 0]
7488 # [Inferior 1 (process 14364) exited normally]
7489 #
7490 set extra "(\\\[Thread \[^\r\n\]+ exited with code $::decimal\\\]\r\n)*"
eceb0c5f
TT
7491 } else {
7492 set extra ""
7493 }
b477a5e6
PA
7494
7495 # By default, we don't rely on exit() behavior of remote stubs --
7496 # it's common for exit() to be implemented as a simple infinite
7497 # loop, or a forced crash/reset. For native targets, by default, we
7498 # assume process exit is reported as such. If a non-reliable target
7499 # is used, we set a breakpoint at exit, and continue to that.
7500 if { [target_info exists exit_is_reliable] } {
7501 set exit_is_reliable [target_info exit_is_reliable]
7502 } else {
7503 set exit_is_reliable [expr ! $use_gdb_stub]
7504 }
7505
7506 if { ! $exit_is_reliable } {
7a292a7a
SS
7507 if {![gdb_breakpoint "exit"]} {
7508 return 0
7509 }
eceb0c5f 7510 gdb_test $command "Continuing..*Breakpoint .*exit.*" \
fda326dd 7511 $text
7a292a7a
SS
7512 } else {
7513 # Continue until we exit. Should not stop again.
7514 # Don't bother to check the output of the program, that may be
7515 # extremely tough for some remote systems.
eceb0c5f
TT
7516 gdb_test $command \
7517 "Continuing.\[\r\n0-9\]+${extra}(... EXIT code 0\[\r\n\]+|$inferior_exited_re normally).*"\
fda326dd 7518 $text
7a292a7a
SS
7519 }
7520}
7521
7522proc rerun_to_main {} {
e11ac3a3 7523 global gdb_prompt use_gdb_stub
7a292a7a 7524
e11ac3a3 7525 if $use_gdb_stub {
7a292a7a
SS
7526 gdb_run_cmd
7527 gdb_expect {
7528 -re ".*Breakpoint .*main .*$gdb_prompt $"\
7529 {pass "rerun to main" ; return 0}
7530 -re "$gdb_prompt $"\
7531 {fail "rerun to main" ; return 0}
7532 timeout {fail "(timeout) rerun to main" ; return 0}
7533 }
7534 } else {
7535 send_gdb "run\n"
7536 gdb_expect {
11350d2a 7537 -re "The program .* has been started already.*y or n. $" {
f9e2e39d 7538 send_gdb "y\n" answer
11350d2a
CV
7539 exp_continue
7540 }
7a292a7a
SS
7541 -re "Starting program.*$gdb_prompt $"\
7542 {pass "rerun to main" ; return 0}
7543 -re "$gdb_prompt $"\
7544 {fail "rerun to main" ; return 0}
7545 timeout {fail "(timeout) rerun to main" ; return 0}
7546 }
7547 }
7548}
c906108c 7549
5a56d6a6
TV
7550# Return true if EXECUTABLE contains a .gdb_index or .debug_names index section.
7551
7552proc exec_has_index_section { executable } {
7553 set readelf_program [gdb_find_readelf]
7554 set res [catch {exec $readelf_program -S $executable \
7555 | grep -E "\.gdb_index|\.debug_names" }]
7556 if { $res == 0 } {
7557 return 1
7558 }
7559 return 0
7560}
7561
a80cf5d8 7562# Return list with major and minor version of readelf, or an empty list.
b50420fd 7563gdb_caching_proc readelf_version {} {
a80cf5d8
TV
7564 set readelf_program [gdb_find_readelf]
7565 set res [catch {exec $readelf_program --version} output]
7566 if { $res != 0 } {
7567 return [list]
7568 }
7569 set lines [split $output \n]
7570 set line [lindex $lines 0]
7571 set res [regexp {[ \t]+([0-9]+)[.]([0-9]+)[^ \t]*$} \
7572 $line dummy major minor]
7573 if { $res != 1 } {
7574 return [list]
7575 }
7576 return [list $major $minor]
7577}
7578
7579# Return 1 if readelf prints the PIE flag, 0 if is doesn't, and -1 if unknown.
7580proc readelf_prints_pie { } {
7581 set version [readelf_version]
7582 if { [llength $version] == 0 } {
7583 return -1
7584 }
7585 set major [lindex $version 0]
7586 set minor [lindex $version 1]
7587 # It would be better to construct a PIE executable and test if the PIE
7588 # flag is printed by readelf, but we cannot reliably construct a PIE
7589 # executable if the multilib_flags dictate otherwise
7590 # (--target_board=unix/-no-pie/-fno-PIE).
b28937b8 7591 return [version_compare {2 26} <= [list $major $minor]]
a80cf5d8
TV
7592}
7593
7594# Return 1 if EXECUTABLE is a Position Independent Executable, 0 if it is not,
7595# and -1 if unknown.
b13057d9
TV
7596
7597proc exec_is_pie { executable } {
a80cf5d8
TV
7598 set res [readelf_prints_pie]
7599 if { $res != 1 } {
7600 return -1
7601 }
b13057d9 7602 set readelf_program [gdb_find_readelf]
42cf1844
TV
7603 # We're not testing readelf -d | grep "FLAGS_1.*Flags:.*PIE"
7604 # because the PIE flag is not set by all versions of gold, see PR
7605 # binutils/26039.
465e1b0f 7606 set res [catch {exec $readelf_program -h $executable} output]
a80cf5d8
TV
7607 if { $res != 0 } {
7608 return -1
7609 }
93df3340 7610 set res [regexp -line {^[ \t]*Type:[ \t]*DYN \((Position-Independent Executable|Shared object) file\)$} \
465e1b0f 7611 $output]
a80cf5d8 7612 if { $res == 1 } {
b13057d9
TV
7613 return 1
7614 }
7615 return 0
7616}
7617
42abd738 7618# Return false if a test should be skipped due to lack of floating
27aba047
YQ
7619# point support or GDB can't fetch the contents from floating point
7620# registers.
13a5e3b8 7621
b50420fd 7622gdb_caching_proc allow_float_test {} {
13a5e3b8 7623 if [target_info exists gdb,skip_float_tests] {
42abd738 7624 return 0
13a5e3b8 7625 }
27aba047
YQ
7626
7627 # There is an ARM kernel ptrace bug that hardware VFP registers
7628 # are not updated after GDB ptrace set VFP registers. The bug
7629 # was introduced by kernel commit 8130b9d7b9d858aa04ce67805e8951e3cb6e9b2f
7630 # in 2012 and is fixed in e2dfb4b880146bfd4b6aa8e138c0205407cebbaf
7631 # in May 2016. In other words, kernels older than 4.6.3, 4.4.14,
7632 # 4.1.27, 3.18.36, and 3.14.73 have this bug.
7633 # This kernel bug is detected by check how does GDB change the
7634 # program result by changing one VFP register.
7635 if { [istarget "arm*-*-linux*"] } {
7636
7637 set compile_flags {debug nowarnings }
7638
7639 # Set up, compile, and execute a test program having VFP
7640 # operations.
16fbc917
TV
7641 set src [standard_temp_file arm_vfp.c]
7642 set exe [standard_temp_file arm_vfp.x]
27aba047
YQ
7643
7644 gdb_produce_source $src {
7645 int main() {
7646 double d = 4.0;
7647 int ret;
7648
7649 asm ("vldr d0, [%0]" : : "r" (&d));
7650 asm ("vldr d1, [%0]" : : "r" (&d));
7651 asm (".global break_here\n"
7652 "break_here:");
7653 asm ("vcmp.f64 d0, d1\n"
7654 "vmrs APSR_nzcv, fpscr\n"
7655 "bne L_value_different\n"
7656 "movs %0, #0\n"
7657 "b L_end\n"
7658 "L_value_different:\n"
7659 "movs %0, #1\n"
7660 "L_end:\n" : "=r" (ret) :);
7661
7662 /* Return $d0 != $d1. */
7663 return ret;
7664 }
7665 }
7666
7667 verbose "compiling testfile $src" 2
7668 set lines [gdb_compile $src $exe executable $compile_flags]
7669 file delete $src
7670
d4c45423 7671 if {![string match "" $lines]} {
27aba047 7672 verbose "testfile compilation failed, returning 1" 2
42abd738 7673 return 1
27aba047
YQ
7674 }
7675
7676 # No error message, compilation succeeded so now run it via gdb.
7677 # Run the test up to 5 times to detect whether ptrace can
7678 # correctly update VFP registers or not.
42abd738 7679 set allow_vfp_test 1
27aba047
YQ
7680 for {set i 0} {$i < 5} {incr i} {
7681 global gdb_prompt srcdir subdir
7682
7683 gdb_exit
7684 gdb_start
7685 gdb_reinitialize_dir $srcdir/$subdir
7686 gdb_load "$exe"
7687
7688 runto_main
7689 gdb_test "break *break_here"
7690 gdb_continue_to_breakpoint "break_here"
7691
7692 # Modify $d0 to a different value, so the exit code should
7693 # be 1.
7694 gdb_test "set \$d0 = 5.0"
7695
7696 set test "continue to exit"
7697 gdb_test_multiple "continue" "$test" {
7698 -re "exited with code 01.*$gdb_prompt $" {
7699 }
7700 -re "exited normally.*$gdb_prompt $" {
7701 # However, the exit code is 0. That means something
7702 # wrong in setting VFP registers.
42abd738 7703 set allow_vfp_test 0
27aba047
YQ
7704 break
7705 }
7706 }
7707 }
7708
7709 gdb_exit
7710 remote_file build delete $exe
7711
42abd738 7712 return $allow_vfp_test
27aba047 7713 }
42abd738 7714 return 1
13a5e3b8
MS
7715}
7716
7717# Print a message and return true if a test should be skipped
7718# due to lack of stdio support.
7719
7720proc gdb_skip_stdio_test { msg } {
7721 if [target_info exists gdb,noinferiorio] {
4ec70201 7722 verbose "Skipping test '$msg': no inferior i/o."
ae59b1da 7723 return 1
13a5e3b8 7724 }
ae59b1da 7725 return 0
13a5e3b8
MS
7726}
7727
7728proc gdb_skip_bogus_test { msg } {
ae59b1da 7729 return 0
13a5e3b8
MS
7730}
7731
b963a97f 7732# Return true if XML support is enabled in the host GDB.
d0ef5df8 7733# NOTE: This must be called while gdb is *not* running.
e515b470 7734
b50420fd 7735gdb_caching_proc allow_xml_test {} {
787f0025 7736 global gdb_spawn_id
e515b470
DJ
7737 global gdb_prompt
7738 global srcdir
e515b470 7739
787f0025 7740 if { [info exists gdb_spawn_id] } {
b963a97f 7741 error "GDB must not be running in allow_xml_tests."
787f0025
MM
7742 }
7743
b22089ab
YQ
7744 set xml_file [gdb_remote_download host "${srcdir}/gdb.xml/trivial.xml"]
7745
e515b470 7746 gdb_start
17e1c970 7747 set xml_missing 0
b22089ab 7748 gdb_test_multiple "set tdesc filename $xml_file" "" {
e515b470 7749 -re ".*XML support was disabled at compile time.*$gdb_prompt $" {
17e1c970 7750 set xml_missing 1
e515b470
DJ
7751 }
7752 -re ".*$gdb_prompt $" { }
7753 }
7754 gdb_exit
b963a97f 7755 return [expr {!$xml_missing}]
e515b470 7756}
1f8a6abb 7757
673dc4a0
YQ
7758# Return true if argv[0] is available.
7759
b50420fd 7760gdb_caching_proc gdb_has_argv0 {} {
673dc4a0
YQ
7761 set result 0
7762
bf326452
AH
7763 # Compile and execute a test program to check whether argv[0] is available.
7764 gdb_simple_compile has_argv0 {
673dc4a0
YQ
7765 int main (int argc, char **argv) {
7766 return 0;
7767 }
bf326452 7768 } executable
673dc4a0 7769
673dc4a0
YQ
7770
7771 # Helper proc.
7772 proc gdb_has_argv0_1 { exe } {
7773 global srcdir subdir
7774 global gdb_prompt hex
7775
7776 gdb_exit
7777 gdb_start
7778 gdb_reinitialize_dir $srcdir/$subdir
7779 gdb_load "$exe"
7780
7781 # Set breakpoint on main.
e777225b 7782 gdb_test_multiple "break -q main" "break -q main" {
673dc4a0
YQ
7783 -re "Breakpoint.*${gdb_prompt} $" {
7784 }
7785 -re "${gdb_prompt} $" {
7786 return 0
7787 }
7788 }
7789
7790 # Run to main.
7791 gdb_run_cmd
7792 gdb_test_multiple "" "run to main" {
7793 -re "Breakpoint.*${gdb_prompt} $" {
7794 }
7795 -re "${gdb_prompt} $" {
7796 return 0
7797 }
7798 }
7799
c0ecb95f
JK
7800 set old_elements "200"
7801 set test "show print elements"
7802 gdb_test_multiple $test $test {
7803 -re "Limit on string chars or array elements to print is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
7804 set old_elements $expect_out(1,string)
7805 }
7806 }
7807 set old_repeats "200"
7808 set test "show print repeats"
7809 gdb_test_multiple $test $test {
7810 -re "Threshold for repeated print elements is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
7811 set old_repeats $expect_out(1,string)
7812 }
7813 }
7814 gdb_test_no_output "set print elements unlimited" ""
7815 gdb_test_no_output "set print repeats unlimited" ""
7816
7817 set retval 0
673dc4a0
YQ
7818 # Check whether argc is 1.
7819 gdb_test_multiple "p argc" "p argc" {
7820 -re " = 1\r\n${gdb_prompt} $" {
7821
7822 gdb_test_multiple "p argv\[0\]" "p argv\[0\]" {
7823 -re " = $hex \".*[file tail $exe]\"\r\n${gdb_prompt} $" {
c0ecb95f 7824 set retval 1
673dc4a0
YQ
7825 }
7826 -re "${gdb_prompt} $" {
673dc4a0
YQ
7827 }
7828 }
7829 }
7830 -re "${gdb_prompt} $" {
673dc4a0
YQ
7831 }
7832 }
c0ecb95f
JK
7833
7834 gdb_test_no_output "set print elements $old_elements" ""
7835 gdb_test_no_output "set print repeats $old_repeats" ""
7836
7837 return $retval
673dc4a0
YQ
7838 }
7839
bf326452 7840 set result [gdb_has_argv0_1 $obj]
673dc4a0
YQ
7841
7842 gdb_exit
bf326452 7843 file delete $obj
673dc4a0
YQ
7844
7845 if { !$result
7846 && ([istarget *-*-linux*]
7847 || [istarget *-*-freebsd*] || [istarget *-*-kfreebsd*]
7848 || [istarget *-*-netbsd*] || [istarget *-*-knetbsd*]
7849 || [istarget *-*-openbsd*]
7850 || [istarget *-*-darwin*]
7851 || [istarget *-*-solaris*]
7852 || [istarget *-*-aix*]
7853 || [istarget *-*-gnu*]
7854 || [istarget *-*-cygwin*] || [istarget *-*-mingw32*]
7855 || [istarget *-*-*djgpp*] || [istarget *-*-go32*]
7856 || [istarget *-wince-pe] || [istarget *-*-mingw32ce*]
673dc4a0 7857 || [istarget *-*-osf*]
673dc4a0
YQ
7858 || [istarget *-*-dicos*]
7859 || [istarget *-*-nto*]
7860 || [istarget *-*-*vms*]
7861 || [istarget *-*-lynx*178]) } {
7862 fail "argv\[0\] should be available on this target"
7863 }
7864
7865 return $result
7866}
7867
1f8a6abb
EZ
7868# Note: the procedure gdb_gnu_strip_debug will produce an executable called
7869# ${binfile}.dbglnk, which is just like the executable ($binfile) but without
7870# the debuginfo. Instead $binfile has a .gnu_debuglink section which contains
8e1d0c49
JK
7871# the name of a debuginfo only file. This file will be stored in the same
7872# subdirectory.
1f8a6abb
EZ
7873
7874# Functions for separate debug info testing
7875
7876# starting with an executable:
7877# foo --> original executable
7878
7879# at the end of the process we have:
7880# foo.stripped --> foo w/o debug info
8e1d0c49 7881# foo.debug --> foo's debug info
1f8a6abb
EZ
7882# foo --> like foo, but with a new .gnu_debuglink section pointing to foo.debug.
7883
7c50a931
DE
7884# Fetch the build id from the file.
7885# Returns "" if there is none.
7886
7887proc get_build_id { filename } {
c74f7d1c
JT
7888 if { ([istarget "*-*-mingw*"]
7889 || [istarget *-*-cygwin*]) } {
7890 set objdump_program [gdb_find_objdump]
7891 set result [catch {set data [exec $objdump_program -p $filename | grep signature | cut "-d " -f4]} output]
7892 verbose "result is $result"
7893 verbose "output is $output"
7894 if {$result == 1} {
7895 return ""
7896 }
7897 return $data
92046791 7898 } else {
c74f7d1c
JT
7899 set tmp [standard_output_file "${filename}-tmp"]
7900 set objcopy_program [gdb_find_objcopy]
7901 set result [catch "exec $objcopy_program -j .note.gnu.build-id -O binary $filename $tmp" output]
7902 verbose "result is $result"
7903 verbose "output is $output"
7904 if {$result == 1} {
7905 return ""
7906 }
7907 set fi [open $tmp]
7908 fconfigure $fi -translation binary
7909 # Skip the NOTE header.
7910 read $fi 16
7911 set data [read $fi]
7912 close $fi
7913 file delete $tmp
d4c45423 7914 if {![string compare $data ""]} {
c74f7d1c
JT
7915 return ""
7916 }
7917 # Convert it to hex.
7918 binary scan $data H* data
7919 return $data
4935890f 7920 }
7c50a931
DE
7921}
7922
7923# Return the build-id hex string (usually 160 bits as 40 hex characters)
7924# converted to the form: .build-id/ab/cdef1234...89.debug
7925# Return "" if no build-id found.
7926proc build_id_debug_filename_get { filename } {
7927 set data [get_build_id $filename]
7928 if { $data == "" } {
7929 return ""
7930 }
061b5285 7931 regsub {^..} $data {\0/} data
ae59b1da 7932 return ".build-id/${data}.debug"
4935890f
JK
7933}
7934
6647f05d
AH
7935# DEST should be a file compiled with debug information. This proc
7936# creates two new files DEST.debug which contains the debug
7937# information extracted from DEST, and DEST.stripped, which is a copy
7938# of DEST with the debug information removed. A '.gnu_debuglink'
7939# section will be added to DEST.stripped that points to DEST.debug.
7940#
7941# If ARGS is passed, it is a list of optional flags. The currently
7942# supported flags are:
7943#
7944# - no-main : remove the symbol entry for main from the separate
7945# debug file DEST.debug,
7946# - no-debuglink : don't add the '.gnu_debuglink' section to
7947# DEST.stripped.
c0201579
JK
7948#
7949# Function returns zero on success. Function will return non-zero failure code
7950# on some targets not supporting separate debug info (such as i386-msdos).
1f8a6abb 7951
94277a38
DJ
7952proc gdb_gnu_strip_debug { dest args } {
7953
8e1d0c49
JK
7954 # Use the first separate debug info file location searched by GDB so the
7955 # run cannot be broken by some stale file searched with higher precedence.
7956 set debug_file "${dest}.debug"
7957
b741e217 7958 set strip_to_file_program [transform strip]
4fa7d390 7959 set objcopy_program [gdb_find_objcopy]
1f8a6abb 7960
1f8a6abb
EZ
7961 set debug_link [file tail $debug_file]
7962 set stripped_file "${dest}.stripped"
7963
7964 # Get rid of the debug info, and store result in stripped_file
7965 # something like gdb/testsuite/gdb.base/blah.stripped.
7966 set result [catch "exec $strip_to_file_program --strip-debug ${dest} -o ${stripped_file}" output]
7967 verbose "result is $result"
7968 verbose "output is $output"
7969 if {$result == 1} {
7970 return 1
7971 }
7972
d521f563
JK
7973 # Workaround PR binutils/10802:
7974 # Preserve the 'x' bit also for PIEs (Position Independent Executables).
7975 set perm [file attributes ${dest} -permissions]
7976 file attributes ${stripped_file} -permissions $perm
7977
1f8a6abb
EZ
7978 # Get rid of everything but the debug info, and store result in debug_file
7979 # This will be in the .debug subdirectory, see above.
7980 set result [catch "exec $strip_to_file_program --only-keep-debug ${dest} -o ${debug_file}" output]
7981 verbose "result is $result"
7982 verbose "output is $output"
7983 if {$result == 1} {
7984 return 1
7985 }
7986
94277a38
DJ
7987 # If no-main is passed, strip the symbol for main from the separate
7988 # file. This is to simulate the behavior of elfutils's eu-strip, which
7989 # leaves the symtab in the original file only. There's no way to get
7990 # objcopy or strip to remove the symbol table without also removing the
7991 # debugging sections, so this is as close as we can get.
6647f05d 7992 if {[lsearch -exact $args "no-main"] != -1} {
94277a38
DJ
7993 set result [catch "exec $objcopy_program -N main ${debug_file} ${debug_file}-tmp" output]
7994 verbose "result is $result"
7995 verbose "output is $output"
7996 if {$result == 1} {
7997 return 1
7998 }
7999 file delete "${debug_file}"
8000 file rename "${debug_file}-tmp" "${debug_file}"
8001 }
8002
6647f05d
AH
8003 # Unless the "no-debuglink" flag is passed, then link the two
8004 # previous output files together, adding the .gnu_debuglink
8005 # section to the stripped_file, containing a pointer to the
8006 # debug_file, save the new file in dest.
8007 if {[lsearch -exact $args "no-debuglink"] == -1} {
8008 set result [catch "exec $objcopy_program --add-gnu-debuglink=${debug_file} ${stripped_file} ${dest}" output]
8009 verbose "result is $result"
8010 verbose "output is $output"
8011 if {$result == 1} {
8012 return 1
8013 }
1f8a6abb
EZ
8014 }
8015
d521f563
JK
8016 # Workaround PR binutils/10802:
8017 # Preserve the 'x' bit also for PIEs (Position Independent Executables).
8018 set perm [file attributes ${stripped_file} -permissions]
8019 file attributes ${dest} -permissions $perm
8020
8021 return 0
1f8a6abb
EZ
8022}
8023
d8295fe9
VP
8024# Test the output of GDB_COMMAND matches the pattern obtained
8025# by concatenating all elements of EXPECTED_LINES. This makes
8026# it possible to split otherwise very long string into pieces.
206584bd 8027# If third argument TESTNAME is not empty, it's used as the name of the
d8295fe9 8028# test to be printed on pass/fail.
206584bd 8029proc help_test_raw { gdb_command expected_lines {testname {}} } {
d8295fe9 8030 set expected_output [join $expected_lines ""]
d1e36019
TV
8031 if {$testname != {}} {
8032 gdb_test "${gdb_command}" "${expected_output}" $testname
8033 return
8034 }
8035
8036 gdb_test "${gdb_command}" "${expected_output}"
d8295fe9
VP
8037}
8038
206584bd
PW
8039# A regexp that matches the end of help CLASS|PREFIX_COMMAND
8040set help_list_trailer {
8041 "Type \"apropos word\" to search for commands related to \"word\"\.[\r\n]+"
8042 "Type \"apropos -v word\" for full documentation of commands related to \"word\"\.[\r\n]+"
8043 "Command name abbreviations are allowed if unambiguous\."
8044}
8045
8046# Test the output of "help COMMAND_CLASS". EXPECTED_INITIAL_LINES
d8295fe9 8047# are regular expressions that should match the beginning of output,
206584bd
PW
8048# before the list of commands in that class.
8049# LIST_OF_COMMANDS are regular expressions that should match the
8050# list of commands in that class. If empty, the command list will be
8051# matched automatically. The presence of standard epilogue will be tested
8052# automatically.
8053# If last argument TESTNAME is not empty, it's used as the name of the
8054# test to be printed on pass/fail.
06f810bd
MG
8055# Notice that the '[' and ']' characters don't need to be escaped for strings
8056# wrapped in {} braces.
206584bd
PW
8057proc test_class_help { command_class expected_initial_lines {list_of_commands {}} {testname {}} } {
8058 global help_list_trailer
8059 if {[llength $list_of_commands]>0} {
8060 set l_list_of_commands {"List of commands:[\r\n]+[\r\n]+"}
8061 set l_list_of_commands [concat $l_list_of_commands $list_of_commands]
8062 set l_list_of_commands [concat $l_list_of_commands {"[\r\n]+[\r\n]+"}]
8063 } else {
8064 set l_list_of_commands {"List of commands\:.*[\r\n]+"}
8065 }
d8295fe9 8066 set l_stock_body {
06f810bd 8067 "Type \"help\" followed by command name for full documentation\.[\r\n]+"
d8295fe9 8068 }
206584bd
PW
8069 set l_entire_body [concat $expected_initial_lines $l_list_of_commands \
8070 $l_stock_body $help_list_trailer]
d8295fe9 8071
206584bd 8072 help_test_raw "help ${command_class}" $l_entire_body $testname
d8295fe9
VP
8073}
8074
206584bd
PW
8075# Like test_class_help but specialised to test "help user-defined".
8076proc test_user_defined_class_help { {list_of_commands {}} {testname {}} } {
8077 test_class_help "user-defined" {
8078 "User-defined commands\.[\r\n]+"
8079 "The commands in this class are those defined by the user\.[\r\n]+"
8080 "Use the \"define\" command to define a command\.[\r\n]+"
8081 } $list_of_commands $testname
8082}
8083
8084
d8295fe9
VP
8085# COMMAND_LIST should have either one element -- command to test, or
8086# two elements -- abbreviated command to test, and full command the first
8087# element is abbreviation of.
8088# The command must be a prefix command. EXPECTED_INITIAL_LINES
8089# are regular expressions that should match the beginning of output,
8090# before the list of subcommands. The presence of
8091# subcommand list and standard epilogue will be tested automatically.
8092proc test_prefix_command_help { command_list expected_initial_lines args } {
206584bd 8093 global help_list_trailer
d8295fe9
VP
8094 set command [lindex $command_list 0]
8095 if {[llength $command_list]>1} {
8096 set full_command [lindex $command_list 1]
8097 } else {
8098 set full_command $command
8099 }
8100 # Use 'list' and not just {} because we want variables to
8101 # be expanded in this list.
8102 set l_stock_body [list\
8103 "List of $full_command subcommands\:.*\[\r\n\]+"\
206584bd
PW
8104 "Type \"help $full_command\" followed by $full_command subcommand name for full documentation\.\[\r\n\]+"]
8105 set l_entire_body [concat $expected_initial_lines $l_stock_body $help_list_trailer]
d8295fe9
VP
8106 if {[llength $args]>0} {
8107 help_test_raw "help ${command}" $l_entire_body [lindex $args 0]
8108 } else {
8109 help_test_raw "help ${command}" $l_entire_body
8110 }
8111}
dbc52822 8112
85b4440a
TT
8113# Build executable named EXECUTABLE from specifications that allow
8114# different options to be passed to different sub-compilations.
8115# TESTNAME is the name of the test; this is passed to 'untested' if
8116# something fails.
a0d3f2f5
SCR
8117# OPTIONS is passed to the final link, using gdb_compile. If OPTIONS
8118# contains the option "pthreads", then gdb_compile_pthreads is used.
85b4440a
TT
8119# ARGS is a flat list of source specifications, of the form:
8120# { SOURCE1 OPTIONS1 [ SOURCE2 OPTIONS2 ]... }
8121# Each SOURCE is compiled to an object file using its OPTIONS,
8122# using gdb_compile.
8123# Returns 0 on success, -1 on failure.
8124proc build_executable_from_specs {testname executable options args} {
dbc52822
VP
8125 global subdir
8126 global srcdir
dbc52822 8127
0a6d0306 8128 set binfile [standard_output_file $executable]
dbc52822 8129
a29a3fb7 8130 set func gdb_compile
26b911fb 8131 set func_index [lsearch -regexp $options {^(pthreads|shlib|shlib_pthreads|openmp)$}]
a29a3fb7
GB
8132 if {$func_index != -1} {
8133 set func "${func}_[lindex $options $func_index]"
8134 }
8135
8136 # gdb_compile_shlib and gdb_compile_shlib_pthreads do not use the 3rd
8137 # parameter. They also requires $sources while gdb_compile and
8138 # gdb_compile_pthreads require $objects. Moreover they ignore any options.
8139 if [string match gdb_compile_shlib* $func] {
8140 set sources_path {}
8141 foreach {s local_options} $args {
d4c45423 8142 if {[regexp "^/" "$s"]} {
0e5c4555
AA
8143 lappend sources_path "$s"
8144 } else {
8145 lappend sources_path "$srcdir/$subdir/$s"
8146 }
a29a3fb7
GB
8147 }
8148 set ret [$func $sources_path "${binfile}" $options]
67218854
TT
8149 } elseif {[lsearch -exact $options rust] != -1} {
8150 set sources_path {}
8151 foreach {s local_options} $args {
d4c45423 8152 if {[regexp "^/" "$s"]} {
67218854
TT
8153 lappend sources_path "$s"
8154 } else {
8155 lappend sources_path "$srcdir/$subdir/$s"
8156 }
8157 }
8158 set ret [gdb_compile_rust $sources_path "${binfile}" $options]
a29a3fb7
GB
8159 } else {
8160 set objects {}
8161 set i 0
8162 foreach {s local_options} $args {
d4c45423 8163 if {![regexp "^/" "$s"]} {
0e5c4555
AA
8164 set s "$srcdir/$subdir/$s"
8165 }
26b911fb 8166 if { [$func "${s}" "${binfile}${i}.o" object $local_options] != "" } {
a29a3fb7
GB
8167 untested $testname
8168 return -1
8169 }
8170 lappend objects "${binfile}${i}.o"
8171 incr i
8172 }
8173 set ret [$func $objects "${binfile}" executable $options]
8174 }
8175 if { $ret != "" } {
8176 untested $testname
8177 return -1
8178 }
8179
dbc52822
VP
8180 return 0
8181}
8182
85b4440a
TT
8183# Build executable named EXECUTABLE, from SOURCES. If SOURCES are not
8184# provided, uses $EXECUTABLE.c. The TESTNAME paramer is the name of test
8185# to pass to untested, if something is wrong. OPTIONS are passed
8186# to gdb_compile directly.
8187proc build_executable { testname executable {sources ""} {options {debug}} } {
8188 if {[llength $sources]==0} {
8189 set sources ${executable}.c
8190 }
8191
8192 set arglist [list $testname $executable $options]
8193 foreach source $sources {
8194 lappend arglist $source $options
8195 }
8196
8197 return [eval build_executable_from_specs $arglist]
8198}
8199
7b606f95 8200# Starts fresh GDB binary and loads an optional executable into GDB.
6b9276b7 8201# Usage: clean_restart [EXECUTABLE]
7b606f95 8202# EXECUTABLE is the basename of the binary.
2016d3e6 8203# Return -1 if starting gdb or loading the executable failed.
7b606f95 8204
6b9276b7 8205proc clean_restart {{executable ""}} {
dbc52822 8206 global srcdir
dbc52822 8207 global subdir
2016d3e6 8208 global errcnt
86e887ae 8209 global warncnt
7b606f95 8210
dbc52822 8211 gdb_exit
2016d3e6 8212
86e887ae
TV
8213 # This is a clean restart, so reset error and warning count.
8214 set errcnt 0
8215 set warncnt 0
8216
2016d3e6
TV
8217 # We'd like to do:
8218 # if { [gdb_start] == -1 } {
8219 # return -1
8220 # }
8221 # but gdb_start is a ${tool}_start proc, which doesn't have a defined
8222 # return value. So instead, we test for errcnt.
dbc52822 8223 gdb_start
86e887ae 8224 if { $errcnt > 0 } {
2016d3e6
TV
8225 return -1
8226 }
8227
dbc52822 8228 gdb_reinitialize_dir $srcdir/$subdir
7b606f95 8229
6b9276b7 8230 if {$executable != ""} {
7b606f95 8231 set binfile [standard_output_file ${executable}]
2016d3e6 8232 return [gdb_load ${binfile}]
7b606f95 8233 }
2016d3e6
TV
8234
8235 return 0
dbc52822
VP
8236}
8237
85b4440a
TT
8238# Prepares for testing by calling build_executable_full, then
8239# clean_restart.
8240# TESTNAME is the name of the test.
8241# Each element in ARGS is a list of the form
8242# { EXECUTABLE OPTIONS SOURCE_SPEC... }
8243# These are passed to build_executable_from_specs, which see.
8244# The last EXECUTABLE is passed to clean_restart.
8245# Returns 0 on success, non-zero on failure.
8246proc prepare_for_testing_full {testname args} {
8247 foreach spec $args {
8248 if {[eval build_executable_from_specs [list $testname] $spec] == -1} {
8249 return -1
8250 }
8251 set executable [lindex $spec 0]
8252 }
8253 clean_restart $executable
8254 return 0
8255}
8256
dbc52822
VP
8257# Prepares for testing, by calling build_executable, and then clean_restart.
8258# Please refer to build_executable for parameter description.
8259proc prepare_for_testing { testname executable {sources ""} {options {debug}}} {
8260
734a5c36 8261 if {[build_executable $testname $executable $sources $options] == -1} {
dbc52822
VP
8262 return -1
8263 }
8264 clean_restart $executable
8265
8266 return 0
8267}
7065b901 8268
0efcde63
AK
8269# Retrieve the value of EXP in the inferior, represented in format
8270# specified in FMT (using "printFMT"). DEFAULT is used as fallback if
8271# print fails. TEST is the test message to use. It can be omitted,
8272# in which case a test message is built from EXP.
8273
8274proc get_valueof { fmt exp default {test ""} } {
7065b901
TT
8275 global gdb_prompt
8276
0efcde63
AK
8277 if {$test == "" } {
8278 set test "get valueof \"${exp}\""
8279 }
8280
7065b901
TT
8281 set val ${default}
8282 gdb_test_multiple "print${fmt} ${exp}" "$test" {
a68f7e98 8283 -re -wrap "^\\$\[0-9\]* = (\[^\r\n\]*)" {
417e16e2 8284 set val $expect_out(1,string)
1443936e 8285 pass "$test"
417e16e2
PM
8286 }
8287 timeout {
8288 fail "$test (timeout)"
8289 }
8290 }
8291 return ${val}
8292}
8293
c623cc90
TV
8294# Retrieve the value of local var EXP in the inferior. DEFAULT is used as
8295# fallback if print fails. TEST is the test message to use. It can be
8296# omitted, in which case a test message is built from EXP.
8297
8298proc get_local_valueof { exp default {test ""} } {
8299 global gdb_prompt
8300
8301 if {$test == "" } {
8302 set test "get local valueof \"${exp}\""
8303 }
8304
8305 set val ${default}
8306 gdb_test_multiple "info locals ${exp}" "$test" {
a5d3f94c 8307 -re "$exp = (\[^\r\n\]*)\r\n$gdb_prompt $" {
c623cc90
TV
8308 set val $expect_out(1,string)
8309 pass "$test"
8310 }
8311 timeout {
8312 fail "$test (timeout)"
8313 }
8314 }
8315 return ${val}
8316}
8317
0efcde63
AK
8318# Retrieve the value of EXP in the inferior, as a signed decimal value
8319# (using "print /d"). DEFAULT is used as fallback if print fails.
8320# TEST is the test message to use. It can be omitted, in which case
8321# a test message is built from EXP.
8322
8323proc get_integer_valueof { exp default {test ""} } {
417e16e2
PM
8324 global gdb_prompt
8325
0efcde63
AK
8326 if {$test == ""} {
8327 set test "get integer valueof \"${exp}\""
8328 }
8329
417e16e2
PM
8330 set val ${default}
8331 gdb_test_multiple "print /d ${exp}" "$test" {
a68f7e98 8332 -re -wrap "^\\$\[0-9\]* = (\[-\]*\[0-9\]*).*" {
7065b901 8333 set val $expect_out(1,string)
2f20e312 8334 pass "$test"
7065b901
TT
8335 }
8336 timeout {
417e16e2 8337 fail "$test (timeout)"
7065b901
TT
8338 }
8339 }
8340 return ${val}
8341}
8342
20aa2c60
PA
8343# Retrieve the value of EXP in the inferior, as an hexadecimal value
8344# (using "print /x"). DEFAULT is used as fallback if print fails.
0efcde63 8345# TEST is the test message to use. It can be omitted, in which case
20aa2c60
PA
8346# a test message is built from EXP.
8347
8348proc get_hexadecimal_valueof { exp default {test ""} } {
faafb047 8349 global gdb_prompt
20aa2c60
PA
8350
8351 if {$test == ""} {
8352 set test "get hexadecimal valueof \"${exp}\""
8353 }
8354
8355 set val ${default}
8356 gdb_test_multiple "print /x ${exp}" $test {
faafb047
PM
8357 -re "\\$\[0-9\]* = (0x\[0-9a-zA-Z\]+).*$gdb_prompt $" {
8358 set val $expect_out(1,string)
8359 pass "$test"
8360 }
faafb047
PM
8361 }
8362 return ${val}
8363}
417e16e2 8364
0efcde63
AK
8365# Retrieve the size of TYPE in the inferior, as a decimal value. DEFAULT
8366# is used as fallback if print fails. TEST is the test message to use.
8367# It can be omitted, in which case a test message is 'sizeof (TYPE)'.
8368
8369proc get_sizeof { type default {test ""} } {
8370 return [get_integer_valueof "sizeof (${type})" $default $test]
7065b901
TT
8371}
8372
ed3ef339
DE
8373proc get_target_charset { } {
8374 global gdb_prompt
8375
8376 gdb_test_multiple "show target-charset" "" {
8377 -re "The target character set is \"auto; currently (\[^\"\]*)\".*$gdb_prompt $" {
8378 return $expect_out(1,string)
8379 }
8380 -re "The target character set is \"(\[^\"\]*)\".*$gdb_prompt $" {
8381 return $expect_out(1,string)
8382 }
8383 }
8384
8385 # Pick a reasonable default.
8386 warning "Unable to read target-charset."
8387 return "UTF-8"
8388}
8389
5ad9dba7
YQ
8390# Get the address of VAR.
8391
8392proc get_var_address { var } {
8393 global gdb_prompt hex
8394
8395 # Match output like:
8396 # $1 = (int *) 0x0
8397 # $5 = (int (*)()) 0
8398 # $6 = (int (*)()) 0x24 <function_bar>
8399
8400 gdb_test_multiple "print &${var}" "get address of ${var}" {
8401 -re "\\\$\[0-9\]+ = \\(.*\\) (0|$hex)( <${var}>)?\[\r\n\]+${gdb_prompt} $"
8402 {
8403 pass "get address of ${var}"
8404 if { $expect_out(1,string) == "0" } {
8405 return "0x0"
8406 } else {
8407 return $expect_out(1,string)
8408 }
8409 }
8410 }
8411 return ""
8412}
8413
45f25d6c
AB
8414# Return the frame number for the currently selected frame
8415proc get_current_frame_number {{test_name ""}} {
8416 global gdb_prompt
8417
8418 if { $test_name == "" } {
8419 set test_name "get current frame number"
8420 }
8421 set frame_num -1
8422 gdb_test_multiple "frame" $test_name {
8423 -re "#(\[0-9\]+) .*$gdb_prompt $" {
8424 set frame_num $expect_out(1,string)
8425 }
8426 }
8427 return $frame_num
8428}
8429
db863c42
MF
8430# Get the current value for remotetimeout and return it.
8431proc get_remotetimeout { } {
8432 global gdb_prompt
8433 global decimal
8434
8435 gdb_test_multiple "show remotetimeout" "" {
8436 -re "Timeout limit to wait for target to respond is ($decimal).*$gdb_prompt $" {
ae59b1da 8437 return $expect_out(1,string)
db863c42
MF
8438 }
8439 }
8440
8441 # Pick the default that gdb uses
8442 warning "Unable to read remotetimeout"
8443 return 300
8444}
8445
8446# Set the remotetimeout to the specified timeout. Nothing is returned.
8447proc set_remotetimeout { timeout } {
8448 global gdb_prompt
8449
8450 gdb_test_multiple "set remotetimeout $timeout" "" {
8451 -re "$gdb_prompt $" {
8452 verbose "Set remotetimeout to $timeout\n"
8453 }
8454 }
8455}
8456
805acca0
AA
8457# Get the target's current endianness and return it.
8458proc get_endianness { } {
8459 global gdb_prompt
8460
8461 gdb_test_multiple "show endian" "determine endianness" {
8462 -re ".* (little|big) endian.*\r\n$gdb_prompt $" {
8463 # Pass silently.
8464 return $expect_out(1,string)
8465 }
8466 }
8467 return "little"
8468}
8469
a5ac8e7f 8470# Get the target's default endianness and return it.
b50420fd 8471gdb_caching_proc target_endianness {} {
a5ac8e7f
TV
8472 global gdb_prompt
8473
8474 set me "target_endianness"
8475
8476 set src { int main() { return 0; } }
8477 if {![gdb_simple_compile $me $src executable]} {
8478 return 0
8479 }
8480
8481 clean_restart $obj
8482 if ![runto_main] {
8483 return 0
8484 }
8485 set res [get_endianness]
8486
8487 gdb_exit
8488 remote_file build delete $obj
8489
8490 return $res
8491}
8492
1e537771
TT
8493# ROOT and FULL are file names. Returns the relative path from ROOT
8494# to FULL. Note that FULL must be in a subdirectory of ROOT.
8495# For example, given ROOT = /usr/bin and FULL = /usr/bin/ls, this
8496# will return "ls".
8497
8498proc relative_filename {root full} {
8499 set root_split [file split $root]
8500 set full_split [file split $full]
8501
8502 set len [llength $root_split]
8503
8504 if {[eval file join $root_split]
8505 != [eval file join [lrange $full_split 0 [expr {$len - 1}]]]} {
8506 error "$full not a subdir of $root"
8507 }
8508
8509 return [eval file join [lrange $full_split $len end]]
8510}
8511
5e92f71a
TT
8512# If GDB_PARALLEL exists, then set up the parallel-mode directories.
8513if {[info exists GDB_PARALLEL]} {
8514 if {[is_remote host]} {
8515 unset GDB_PARALLEL
8516 } else {
3d338901
DE
8517 file mkdir \
8518 [make_gdb_parallel_path outputs] \
8519 [make_gdb_parallel_path temp] \
8520 [make_gdb_parallel_path cache]
5e92f71a
TT
8521 }
8522}
8523
c715d073
PA
8524# Set the inferior's cwd to the output directory, in order to have it
8525# dump core there. This must be called before the inferior is
8526# started.
8527
8528proc set_inferior_cwd_to_output_dir {} {
8529 # Note this sets the inferior's cwd ("set cwd"), not GDB's ("cd").
8530 # If GDB crashes, we want its core dump in gdb/testsuite/, not in
8531 # the testcase's dir, so we can detect the unexpected core at the
8532 # end of the test run.
8533 if {![is_remote host]} {
8534 set output_dir [standard_output_file ""]
8535 gdb_test_no_output "set cwd $output_dir" \
8536 "set inferior cwd to test directory"
8537 }
8538}
8539
8540# Get the inferior's PID.
8541
8542proc get_inferior_pid {} {
8543 set pid -1
8544 gdb_test_multiple "inferior" "get inferior pid" {
8545 -re "process (\[0-9\]*).*$::gdb_prompt $" {
8546 set pid $expect_out(1,string)
8547 pass $gdb_test_name
8548 }
8549 }
8550 return $pid
8551}
8552
8553# Find the kernel-produced core file dumped for the current testfile
8554# program. PID was the inferior's pid, saved before the inferior
8555# exited with a signal, or -1 if not known. If not on a remote host,
8556# this assumes the core was generated in the output directory.
8557# Returns the name of the core dump, or empty string if not found.
8558
8559proc find_core_file {pid} {
8560 # For non-remote hosts, since cores are assumed to be in the
8561 # output dir, which we control, we use a laxer "core.*" glob. For
8562 # remote hosts, as we don't know whether the dir is being reused
8563 # for parallel runs, we use stricter names with no globs. It is
8564 # not clear whether this is really important, but it preserves
8565 # status quo ante.
8566 set files {}
8567 if {![is_remote host]} {
8568 lappend files core.*
8569 } elseif {$pid != -1} {
8570 lappend files core.$pid
8571 }
e406987c
TV
8572 lappend files ${::testfile}.core
8573 lappend files core
c715d073
PA
8574
8575 foreach file $files {
8576 if {![is_remote host]} {
8577 set names [glob -nocomplain [standard_output_file $file]]
8578 if {[llength $names] == 1} {
8579 return [lindex $names 0]
8580 }
8581 } else {
8582 if {[remote_file host exists $file]} {
8583 return $file
8584 }
8585 }
8586 }
8587 return ""
8588}
8589
8590# Check for production of a core file and remove it. PID is the
8591# inferior's pid or -1 if not known. TEST is the test's message.
8592
8593proc remove_core {pid {test ""}} {
8594 if {$test == ""} {
8595 set test "cleanup core file"
8596 }
8597
8598 set file [find_core_file $pid]
8599 if {$file != ""} {
8600 remote_file host delete $file
8601 pass "$test (removed)"
8602 } else {
8603 pass "$test (not found)"
8604 }
8605}
8606
bbfba9ed 8607proc core_find {binfile {deletefiles {}} {arg ""}} {
37aeb5df
JK
8608 global objdir subdir
8609
8610 set destcore "$binfile.core"
8611 file delete $destcore
8612
8613 # Create a core file named "$destcore" rather than just "core", to
8614 # avoid problems with sys admin types that like to regularly prune all
8615 # files named "core" from the system.
8616 #
8617 # Arbitrarily try setting the core size limit to "unlimited" since
8618 # this does not hurt on systems where the command does not work and
8619 # allows us to generate a core on systems where it does.
8620 #
8621 # Some systems append "core" to the name of the program; others append
8622 # the name of the program to "core"; still others (like Linux, as of
8623 # May 2003) create cores named "core.PID". In the latter case, we
8624 # could have many core files lying around, and it may be difficult to
8625 # tell which one is ours, so let's run the program in a subdirectory.
8626 set found 0
93c0ef37 8627 set coredir [standard_output_file coredir.[getpid]]
37aeb5df 8628 file mkdir $coredir
bbfba9ed 8629 catch "system \"(cd ${coredir}; ulimit -c unlimited; ${binfile} ${arg}; true) >/dev/null 2>&1\""
37aeb5df
JK
8630 # remote_exec host "${binfile}"
8631 foreach i "${coredir}/core ${coredir}/core.coremaker.c ${binfile}.core" {
8632 if [remote_file build exists $i] {
8633 remote_exec build "mv $i $destcore"
8634 set found 1
8635 }
8636 }
c715d073
PA
8637 # Check for "core.PID", "core.EXEC.PID.HOST.TIME", etc. It's fine
8638 # to use a glob here as we're looking inside a directory we
8639 # created. Also, this procedure only works on non-remote hosts.
37aeb5df
JK
8640 if { $found == 0 } {
8641 set names [glob -nocomplain -directory $coredir core.*]
8642 if {[llength $names] == 1} {
8643 set corefile [file join $coredir [lindex $names 0]]
8644 remote_exec build "mv $corefile $destcore"
8645 set found 1
8646 }
8647 }
8648 if { $found == 0 } {
8649 # The braindamaged HPUX shell quits after the ulimit -c above
8650 # without executing ${binfile}. So we try again without the
8651 # ulimit here if we didn't find a core file above.
8652 # Oh, I should mention that any "braindamaged" non-Unix system has
8653 # the same problem. I like the cd bit too, it's really neat'n stuff.
8654 catch "system \"(cd ${objdir}/${subdir}; ${binfile}; true) >/dev/null 2>&1\""
8655 foreach i "${objdir}/${subdir}/core ${objdir}/${subdir}/core.coremaker.c ${binfile}.core" {
8656 if [remote_file build exists $i] {
8657 remote_exec build "mv $i $destcore"
8658 set found 1
8659 }
8660 }
8661 }
8662
8663 # Try to clean up after ourselves.
8664 foreach deletefile $deletefiles {
8665 remote_file build delete [file join $coredir $deletefile]
8666 }
8667 remote_exec build "rmdir $coredir"
8668
8669 if { $found == 0 } {
8670 warning "can't generate a core file - core tests suppressed - check ulimit -c"
8671 return ""
8672 }
8673 return $destcore
8674}
ee5683ab 8675
2223449a
KB
8676# gdb_target_symbol_prefix compiles a test program and then examines
8677# the output from objdump to determine the prefix (such as underscore)
8678# for linker symbol prefixes.
8679
b50420fd 8680gdb_caching_proc gdb_target_symbol_prefix {} {
bf326452
AH
8681 # Compile a simple test program...
8682 set src { int main() { return 0; } }
8683 if {![gdb_simple_compile target_symbol_prefix $src executable]} {
8684 return 0
2223449a
KB
8685 }
8686
2223449a
KB
8687 set prefix ""
8688
bf326452
AH
8689 set objdump_program [gdb_find_objdump]
8690 set result [catch "exec $objdump_program --syms $obj" output]
2223449a 8691
bf326452
AH
8692 if { $result == 0 \
8693 && ![regexp -lineanchor \
8694 { ([^ a-zA-Z0-9]*)main$} $output dummy prefix] } {
8695 verbose "gdb_target_symbol_prefix: Could not find main in objdump output; returning null prefix" 2
2223449a
KB
8696 }
8697
bf326452 8698 file delete $obj
2223449a
KB
8699
8700 return $prefix
8701}
8702
5bd18990
AB
8703# Return 1 if target supports scheduler locking, otherwise return 0.
8704
b50420fd 8705gdb_caching_proc target_supports_scheduler_locking {} {
5bd18990
AB
8706 global gdb_prompt
8707
8708 set me "gdb_target_supports_scheduler_locking"
8709
bf326452
AH
8710 set src { int main() { return 0; } }
8711 if {![gdb_simple_compile $me $src executable]} {
5bd18990
AB
8712 return 0
8713 }
8714
bf326452 8715 clean_restart $obj
58bbcd02
TV
8716 if ![runto_main] {
8717 return 0
8718 }
5bd18990
AB
8719
8720 set supports_schedule_locking -1
8721 set current_schedule_locking_mode ""
8722
8723 set test "reading current scheduler-locking mode"
8724 gdb_test_multiple "show scheduler-locking" $test {
8725 -re "Mode for locking scheduler during execution is \"(\[\^\"\]*)\".*$gdb_prompt" {
8726 set current_schedule_locking_mode $expect_out(1,string)
8727 }
8728 -re "$gdb_prompt $" {
8729 set supports_schedule_locking 0
8730 }
8731 timeout {
8732 set supports_schedule_locking 0
8733 }
8734 }
8735
8736 if { $supports_schedule_locking == -1 } {
8737 set test "checking for scheduler-locking support"
8738 gdb_test_multiple "set scheduler-locking $current_schedule_locking_mode" $test {
8739 -re "Target '\[^'\]+' cannot support this command\..*$gdb_prompt $" {
8740 set supports_schedule_locking 0
8741 }
8742 -re "$gdb_prompt $" {
8743 set supports_schedule_locking 1
8744 }
8745 timeout {
8746 set supports_schedule_locking 0
8747 }
8748 }
8749 }
8750
8751 if { $supports_schedule_locking == -1 } {
8752 set supports_schedule_locking 0
8753 }
8754
8755 gdb_exit
bf326452 8756 remote_file build delete $obj
5bd18990
AB
8757 verbose "$me: returning $supports_schedule_locking" 2
8758 return $supports_schedule_locking
8759}
8760
bb47f919
KB
8761# Return 1 if compiler supports use of nested functions. Otherwise,
8762# return 0.
8763
b50420fd 8764gdb_caching_proc support_nested_function_tests {} {
bb47f919
KB
8765 # Compile a test program containing a nested function
8766 return [gdb_can_simple_compile nested_func {
8767 int main () {
8768 int foo () {
8769 return 0;
8770 }
8771 return foo ();
8772 }
8773 } executable]
8774}
8775
2223449a
KB
8776# gdb_target_symbol returns the provided symbol with the correct prefix
8777# prepended. (See gdb_target_symbol_prefix, above.)
8778
8779proc gdb_target_symbol { symbol } {
8780 set prefix [gdb_target_symbol_prefix]
8781 return "${prefix}${symbol}"
8782}
8783
f01dcfd9
KB
8784# gdb_target_symbol_prefix_flags_asm returns a string that can be
8785# added to gdb_compile options to define the C-preprocessor macro
8786# SYMBOL_PREFIX with a value that can be prepended to symbols
8787# for targets which require a prefix, such as underscore.
8788#
8789# This version (_asm) defines the prefix without double quotes
8790# surrounding the prefix. It is used to define the macro
8791# SYMBOL_PREFIX for assembly language files. Another version, below,
8792# is used for symbols in inline assembler in C/C++ files.
8793#
8794# The lack of quotes in this version (_asm) makes it possible to
8795# define supporting macros in the .S file. (The version which
8796# uses quotes for the prefix won't work for such files since it's
8797# impossible to define a quote-stripping macro in C.)
8798#
8799# It's possible to use this version (_asm) for C/C++ source files too,
8800# but a string is usually required in such files; providing a version
8801# (no _asm) which encloses the prefix with double quotes makes it
8802# somewhat easier to define the supporting macros in the test case.
8803
8804proc gdb_target_symbol_prefix_flags_asm {} {
8805 set prefix [gdb_target_symbol_prefix]
8806 if {$prefix ne ""} {
8807 return "additional_flags=-DSYMBOL_PREFIX=$prefix"
8808 } else {
8809 return "";
8810 }
8811}
8812
8813# gdb_target_symbol_prefix_flags returns the same string as
8814# gdb_target_symbol_prefix_flags_asm, above, but with the prefix
8815# enclosed in double quotes if there is a prefix.
8816#
8817# See the comment for gdb_target_symbol_prefix_flags_asm for an
8818# extended discussion.
ee5683ab
PM
8819
8820proc gdb_target_symbol_prefix_flags {} {
f01dcfd9
KB
8821 set prefix [gdb_target_symbol_prefix]
8822 if {$prefix ne ""} {
8823 return "additional_flags=-DSYMBOL_PREFIX=\"$prefix\""
ee5683ab 8824 } else {
f01dcfd9 8825 return "";
ee5683ab
PM
8826 }
8827}
8828
6e45f158
DE
8829# A wrapper for 'remote_exec host' that passes or fails a test.
8830# Returns 0 if all went well, nonzero on failure.
8831# TEST is the name of the test, other arguments are as for remote_exec.
8832
8833proc run_on_host { test program args } {
8834 verbose -log "run_on_host: $program $args"
8835 # remote_exec doesn't work properly if the output is set but the
8836 # input is the empty string -- so replace an empty input with
8837 # /dev/null.
8838 if {[llength $args] > 1 && [lindex $args 1] == ""} {
8839 set args [lreplace $args 1 1 "/dev/null"]
8840 }
8841 set result [eval remote_exec host [list $program] $args]
8842 verbose "result is $result"
8843 set status [lindex $result 0]
8844 set output [lindex $result 1]
8845 if {$status == 0} {
8846 pass $test
8847 return 0
8848 } else {
50cc37c8 8849 verbose -log "run_on_host failed: $output"
18f1cb1f
TV
8850 if { $output == "spawn failed" } {
8851 unsupported $test
8852 } else {
8853 fail $test
8854 }
6e45f158
DE
8855 return -1
8856 }
8857}
8858
a587b477
DE
8859# Return non-zero if "board_info debug_flags" mentions Fission.
8860# http://gcc.gnu.org/wiki/DebugFission
8861# Fission doesn't support everything yet.
8862# This supports working around bug 15954.
8863
8864proc using_fission { } {
8865 set debug_flags [board_info [target_info name] debug_flags]
8866 return [regexp -- "-gsplit-dwarf" $debug_flags]
8867}
8868
590d3faa
TV
8869# Search LISTNAME in uplevel LEVEL caller and set variables according to the
8870# list of valid options with prefix PREFIX described by ARGSET.
4b48d439
KS
8871#
8872# The first member of each one- or two-element list in ARGSET defines the
8873# name of a variable that will be added to the caller's scope.
8874#
8875# If only one element is given to describe an option, it the value is
8876# 0 if the option is not present in (the caller's) ARGS or 1 if
8877# it is.
8878#
8879# If two elements are given, the second element is the default value of
8880# the variable. This is then overwritten if the option exists in ARGS.
590d3faa
TV
8881# If EVAL, then subst is called on the value, which allows variables
8882# to be used.
4b48d439
KS
8883#
8884# Any parse_args elements in (the caller's) ARGS will be removed, leaving
8885# any optional components.
590d3faa 8886#
4b48d439
KS
8887# Example:
8888# proc myproc {foo args} {
590d3faa 8889# parse_list args 1 {{bar} {baz "abc"} {qux}} "-" false
4b48d439
KS
8890# # ...
8891# }
8892# myproc ABC -bar -baz DEF peanut butter
8893# will define the following variables in myproc:
8894# foo (=ABC), bar (=1), baz (=DEF), and qux (=0)
8895# args will be the list {peanut butter}
8896
590d3faa
TV
8897proc parse_list { level listname argset prefix eval } {
8898 upvar $level $listname args
4b48d439
KS
8899
8900 foreach argument $argset {
590d3faa
TV
8901 if {[llength $argument] == 1} {
8902 # Normalize argument, strip leading/trailing whitespace.
8903 # Allows us to treat {foo} and { foo } the same.
8904 set argument [string trim $argument]
8905
8906 # No default specified, so we assume that we should set
8907 # the value to 1 if the arg is present and 0 if it's not.
8908 # It is assumed that no value is given with the argument.
8909 set pattern "$prefix$argument"
8910 set result [lsearch -exact $args $pattern]
8911
d4c45423 8912 if {$result != -1} {
590d3faa
TV
8913 set value 1
8914 set args [lreplace $args $result $result]
8915 } else {
8916 set value 0
8917 }
8918 uplevel $level [list set $argument $value]
8919 } elseif {[llength $argument] == 2} {
8920 # There are two items in the argument. The second is a
8921 # default value to use if the item is not present.
8922 # Otherwise, the variable is set to whatever is provided
8923 # after the item in the args.
8924 set arg [lindex $argument 0]
8925 set pattern "$prefix[lindex $arg 0]"
8926 set result [lsearch -exact $args $pattern]
8927
d4c45423 8928 if {$result != -1} {
590d3faa
TV
8929 set value [lindex $args [expr $result+1]]
8930 if { $eval } {
8931 set value [uplevel [expr $level + 1] [list subst $value]]
8932 }
8933 set args [lreplace $args $result [expr $result+1]]
8934 } else {
8935 set value [lindex $argument 1]
8936 if { $eval } {
8937 set value [uplevel $level [list subst $value]]
8938 }
8939 }
8940 uplevel $level [list set $arg $value]
8941 } else {
8942 error "Badly formatted argument \"$argument\" in argument set"
8943 }
4b48d439 8944 }
590d3faa
TV
8945}
8946
8947# Search the caller's args variable and set variables according to the list of
8948# valid options described by ARGSET.
8949
8950proc parse_args { argset } {
8951 parse_list 2 args $argset "-" false
4b48d439
KS
8952
8953 # The remaining args should be checked to see that they match the
8954 # number of items expected to be passed into the procedure...
8955}
8956
590d3faa
TV
8957# Process the caller's options variable and set variables according
8958# to the list of valid options described by OPTIONSET.
8959
8960proc parse_options { optionset } {
8961 parse_list 2 options $optionset "" true
8962
8963 # Require no remaining options.
8964 upvar 1 options options
8965 if { [llength $options] != 0 } {
8966 error "Options left unparsed: $options"
8967 }
8968}
8969
87f0e720
KS
8970# Capture the output of COMMAND in a string ignoring PREFIX (a regexp);
8971# return that string.
8972
e9089e05
MM
8973proc capture_command_output { command prefix } {
8974 global gdb_prompt
8975 global expect_out
8976
86b4a00f 8977 set test "capture_command_output for $command"
e7b1ba07 8978
e9089e05 8979 set output_string ""
86b4a00f 8980 gdb_test_multiple $command $test {
e7b1ba07
AB
8981 -re "^(\[^\r\n\]+\r\n)" {
8982 if { ![string equal $output_string ""] } {
8983 set output_string [join [list $output_string $expect_out(1,string)] ""]
8984 } else {
8985 set output_string $expect_out(1,string)
8986 }
8987 exp_continue
8988 }
8989
8990 -re "^$gdb_prompt $" {
e9089e05
MM
8991 }
8992 }
e7b1ba07 8993
86b4a00f
TV
8994 # Strip the command.
8995 set command_re [string_to_regexp ${command}]
8996 set output_string [regsub ^$command_re\r\n $output_string ""]
8997
8998 # Strip the prefix.
8999 if { $prefix != "" } {
9000 set output_string [regsub ^$prefix $output_string ""]
9001 }
9002
9003 # Strip a trailing newline.
e7b1ba07 9004 set output_string [regsub "\r\n$" $output_string ""]
86b4a00f 9005
e9089e05
MM
9006 return $output_string
9007}
9008
3c724c8c
PMR
9009# A convenience function that joins all the arguments together, with a
9010# regexp that matches exactly one end of line in between each argument.
9011# This function is ideal to write the expected output of a GDB command
9012# that generates more than a couple of lines, as this allows us to write
9013# each line as a separate string, which is easier to read by a human
9014# being.
9015
9016proc multi_line { args } {
fdae5c22
TV
9017 if { [llength $args] == 1 } {
9018 set hint "forgot {*} before list argument?"
9019 error "multi_line called with one argument ($hint)"
9020 }
3c724c8c
PMR
9021 return [join $args "\r\n"]
9022}
9023
fad0c9fb
PA
9024# Similar to the above, but while multi_line is meant to be used to
9025# match GDB output, this one is meant to be used to build strings to
9026# send as GDB input.
9027
9028proc multi_line_input { args } {
9029 return [join $args "\n"]
9030}
9031
a960d5f9
TJB
9032# Return how many newlines there are in the given string.
9033
9034proc count_newlines { string } {
9035 return [regexp -all "\n" $string]
9036}
9037
896c0c1e
SM
9038# Return the version of the DejaGnu framework.
9039#
9040# The return value is a list containing the major, minor and patch version
9041# numbers. If the version does not contain a minor or patch number, they will
9042# be set to 0. For example:
9043#
9044# 1.6 -> {1 6 0}
9045# 1.6.1 -> {1 6 1}
9046# 2 -> {2 0 0}
9047
9048proc dejagnu_version { } {
9049 # The frame_version variable is defined by DejaGnu, in runtest.exp.
9050 global frame_version
9051
9052 verbose -log "DejaGnu version: $frame_version"
9053 verbose -log "Expect version: [exp_version]"
9054 verbose -log "Tcl version: [info tclversion]"
9055
9056 set dg_ver [split $frame_version .]
9057
9058 while { [llength $dg_ver] < 3 } {
9059 lappend dg_ver 0
9060 }
9061
9062 return $dg_ver
9063}
fad0c9fb 9064
3a3fd0fd
PA
9065# Define user-defined command COMMAND using the COMMAND_LIST as the
9066# command's definition. The terminating "end" is added automatically.
9067
9068proc gdb_define_cmd {command command_list} {
9069 global gdb_prompt
9070
9071 set input [multi_line_input {*}$command_list "end"]
9072 set test "define $command"
9073
9074 gdb_test_multiple "define $command" $test {
89447229 9075 -re "End with \[^\r\n\]*\r\n *>$" {
3a3fd0fd
PA
9076 gdb_test_multiple $input $test {
9077 -re "\r\n$gdb_prompt " {
9078 }
9079 }
9080 }
9081 }
9082}
9083
c3734e09
AH
9084# Override the 'cd' builtin with a version that ensures that the
9085# log file keeps pointing at the same file. We need this because
9086# unfortunately the path to the log file is recorded using an
9087# relative path name, and, we sometimes need to close/reopen the log
9088# after changing the current directory. See get_compiler_info.
9089
9090rename cd builtin_cd
9091
9092proc cd { dir } {
9093
9094 # Get the existing log file flags.
9095 set log_file_info [log_file -info]
9096
9097 # Split the flags into args and file name.
9098 set log_file_flags ""
9099 set log_file_file ""
9100 foreach arg [ split "$log_file_info" " "] {
9101 if [string match "-*" $arg] {
9102 lappend log_file_flags $arg
9103 } else {
9104 lappend log_file_file $arg
9105 }
9106 }
9107
9108 # If there was an existing file, ensure it is an absolute path, and then
9109 # reset logging.
9110 if { $log_file_file != "" } {
9111 set log_file_file [file normalize $log_file_file]
9112 log_file
9113 log_file $log_file_flags "$log_file_file"
9114 }
9115
9116 # Call the builtin version of cd.
9117 builtin_cd $dir
9118}
9119
d7df6549 9120# Return a list of all languages supported by GDB, suitable for use in
4473d4f9
AB
9121# 'set language NAME'. This doesn't include the languages auto,
9122# local, or unknown.
9123gdb_caching_proc gdb_supported_languages {} {
9124 # The extra space after 'complete set language ' in the command below is
9125 # critical. Only with that space will GDB complete the next level of
9126 # the command, i.e. fill in the actual language names.
9127 set output [remote_exec host $::GDB "$::INTERNAL_GDBFLAGS -batch -ex \"complete set language \""]
9128
9129 if {[lindex $output 0] != 0} {
9130 error "failed to get list of supported languages"
9131 }
9132
9133 set langs {}
9134 foreach line [split [lindex $output 1] \n] {
9135 if {[regexp "set language (\[^\r\]+)" $line full_match lang]} {
9136 # If LANG is not one of the languages that we ignore, then
9137 # add it to our list of languages.
9138 if {[lsearch -exact {auto local unknown} $lang] == -1} {
9139 lappend langs $lang
9140 }
9141 }
9142 }
9143 return $langs
d7df6549
AB
9144}
9145
29b52314
AH
9146# Check if debugging is enabled for gdb.
9147
9148proc gdb_debug_enabled { } {
9149 global gdbdebug
9150
9151 # If not already read, get the debug setting from environment or board setting.
9152 if {![info exists gdbdebug]} {
9153 global env
9154 if [info exists env(GDB_DEBUG)] {
9155 set gdbdebug $env(GDB_DEBUG)
9156 } elseif [target_info exists gdb,debug] {
9157 set gdbdebug [target_info gdb,debug]
9158 } else {
9159 return 0
9160 }
9161 }
9162
9163 # Ensure it not empty.
9164 return [expr { $gdbdebug != "" }]
9165}
9166
9167# Turn on debugging if enabled, or reset if already on.
9168
9169proc gdb_debug_init { } {
9170
9171 global gdb_prompt
9172
9173 if ![gdb_debug_enabled] {
9174 return;
9175 }
9176
9177 # First ensure logging is off.
6ff96754 9178 send_gdb "set logging enabled off\n"
29b52314
AH
9179
9180 set debugfile [standard_output_file gdb.debug]
9181 send_gdb "set logging file $debugfile\n"
9182
9183 send_gdb "set logging debugredirect\n"
9184
9185 global gdbdebug
9186 foreach entry [split $gdbdebug ,] {
9187 send_gdb "set debug $entry 1\n"
9188 }
9189
9190 # Now that everything is set, enable logging.
6ff96754 9191 send_gdb "set logging enabled on\n"
29b52314
AH
9192 gdb_expect 10 {
9193 -re "Copying output to $debugfile.*Redirecting debug output to $debugfile.*$gdb_prompt $" {}
9194 timeout { warning "Couldn't set logging file" }
9195 }
9196}
9197
dd06d4d6
AH
9198# Check if debugging is enabled for gdbserver.
9199
9200proc gdbserver_debug_enabled { } {
9201 # Always disabled for GDB only setups.
9202 return 0
9203}
9204
f9e2e39d
AH
9205# Open the file for logging gdb input
9206
9207proc gdb_stdin_log_init { } {
a29d5112 9208 gdb_persistent_global in_file
f9e2e39d
AH
9209
9210 if {[info exists in_file]} {
9211 # Close existing file.
9212 catch "close $in_file"
9213 }
9214
9215 set logfile [standard_output_file_with_gdb_instance gdb.in]
9216 set in_file [open $logfile w]
9217}
9218
9219# Write to the file for logging gdb input.
9220# TYPE can be one of the following:
9221# "standard" : Default. Standard message written to the log
9222# "answer" : Answer to a question (eg "Y"). Not written the log.
9223# "optional" : Optional message. Not written to the log.
9224
9225proc gdb_stdin_log_write { message {type standard} } {
9226
9227 global in_file
9228 if {![info exists in_file]} {
9229 return
9230 }
9231
9232 # Check message types.
9233 switch -regexp -- $type {
9234 "answer" {
9235 return
9236 }
9237 "optional" {
9238 return
9239 }
9240 }
9241
b3247276
TT
9242 # Write to the log and make sure the output is there, even in case
9243 # of crash.
f9e2e39d 9244 puts -nonewline $in_file "$message"
b3247276 9245 flush $in_file
f9e2e39d
AH
9246}
9247
408e9b8b
AH
9248# Write the command line used to invocate gdb to the cmd file.
9249
9250proc gdb_write_cmd_file { cmdline } {
9251 set logfile [standard_output_file_with_gdb_instance gdb.cmd]
9252 set cmd_file [open $logfile w]
9253 puts $cmd_file $cmdline
9254 catch "close $cmd_file"
9255}
9256
30331a6c
TV
9257# Compare contents of FILE to string STR. Pass with MSG if equal, otherwise
9258# fail with MSG.
9259
9260proc cmp_file_string { file str msg } {
9261 if { ![file exists $file]} {
9262 fail "$msg"
9263 return
9264 }
9265
9266 set caught_error [catch {
9267 set fp [open "$file" r]
9268 set file_contents [read $fp]
9269 close $fp
9270 } error_message]
d4c45423 9271 if {$caught_error} {
30331a6c
TV
9272 error "$error_message"
9273 fail "$msg"
9274 return
9275 }
9276
9277 if { $file_contents == $str } {
9278 pass "$msg"
9279 } else {
9280 fail "$msg"
9281 }
9282}
9283
66984afd
AB
9284# Compare FILE1 and FILE2 as binary files. Return 0 if the files are
9285# equal, otherwise, return non-zero.
9286
9287proc cmp_binary_files { file1 file2 } {
9288 set fd1 [open $file1]
9289 fconfigure $fd1 -translation binary
9290 set fd2 [open $file2]
9291 fconfigure $fd2 -translation binary
9292
9293 set blk_size 1024
9294 while {true} {
9295 set blk1 [read $fd1 $blk_size]
9296 set blk2 [read $fd2 $blk_size]
9297 set diff [string compare $blk1 $blk2]
9298 if {$diff != 0 || [eof $fd1] || [eof $fd2]} {
9299 close $fd1
9300 close $fd2
9301 return $diff
9302 }
9303 }
9304}
9305
ffb3f587 9306# Does the compiler support CTF debug output using '-gctf' compiler
1776e3e5
NA
9307# flag? If not then we should skip these tests. We should also
9308# skip them if libctf was explicitly disabled.
30d0a636 9309
b50420fd 9310gdb_caching_proc allow_ctf_tests {} {
1776e3e5
NA
9311 global enable_libctf
9312
9313 if {$enable_libctf eq "no"} {
30ce6aa4 9314 return 0
1776e3e5
NA
9315 }
9316
573dc0cc 9317 set can_ctf [gdb_can_simple_compile ctfdebug {
30d0a636
AB
9318 int main () {
9319 return 0;
9320 }
ffb3f587 9321 } executable "additional_flags=-gctf"]
573dc0cc 9322
30ce6aa4 9323 return $can_ctf
30d0a636
AB
9324}
9325
2ac70237
TV
9326# Return 1 if compiler supports -gstatement-frontiers. Otherwise,
9327# return 0.
9328
b50420fd 9329gdb_caching_proc supports_statement_frontiers {} {
2ac70237
TV
9330 return [gdb_can_simple_compile supports_statement_frontiers {
9331 int main () {
9332 return 0;
9333 }
9334 } executable "additional_flags=-gstatement-frontiers"]
9335}
9336
5beb4d17
TV
9337# Return 1 if compiler supports -mmpx -fcheck-pointer-bounds. Otherwise,
9338# return 0.
9339
b50420fd 9340gdb_caching_proc supports_mpx_check_pointer_bounds {} {
5beb4d17
TV
9341 set flags "additional_flags=-mmpx additional_flags=-fcheck-pointer-bounds"
9342 return [gdb_can_simple_compile supports_mpx_check_pointer_bounds {
9343 int main () {
9344 return 0;
9345 }
9346 } executable $flags]
9347}
9348
ac4a4f1c
SM
9349# Return 1 if compiler supports -fcf-protection=. Otherwise,
9350# return 0.
9351
b50420fd 9352gdb_caching_proc supports_fcf_protection {} {
ac4a4f1c
SM
9353 return [gdb_can_simple_compile supports_fcf_protection {
9354 int main () {
9355 return 0;
9356 }
9357 } executable "additional_flags=-fcf-protection=full"]
9358}
9359
9399ac88
AB
9360# Return true if symbols were read in using -readnow. Otherwise,
9361# return false.
c0502da6 9362
9399ac88
AB
9363proc readnow { } {
9364 return [expr {[lsearch -exact $::GDBFLAGS -readnow] != -1
9365 || [lsearch -exact $::GDBFLAGS --readnow] != -1}]
c0502da6
TV
9366}
9367
5c5e642d
AB
9368# Return 'gdb_index' if the symbols from OBJFILE were read using a
9369# .gdb_index index. Return 'debug_names' if the symbols were read
9370# using a DWARF-5 style .debug_names index. Otherwise, return an
9371# empty string.
be36c6e3
TV
9372
9373proc have_index { objfile } {
5c5e642d 9374
845d99df
TV
9375 # This proc is mostly used with $binfile, but that gives problems with
9376 # remote host, while using $testfile would work.
9377 # Fix this by reducing $binfile to $testfile.
9378 set objfile [file tail $objfile]
be36c6e3 9379
5c5e642d 9380 set index_type [get_index_type $objfile]
be36c6e3 9381
5c5e642d
AB
9382 if { $index_type eq "gdb" } {
9383 return "gdb_index"
9384 } elseif { $index_type eq "dwarf5" } {
9385 return "debug_names"
9386 } else {
9387 return ""
9388 }
be36c6e3
TV
9389}
9390
14ca8ecf
TV
9391# Return 1 if partial symbols are available. Otherwise, return 0.
9392
9393proc psymtabs_p { } {
9394 global gdb_prompt
9395
9396 set cmd "maint info psymtab"
9397 gdb_test_multiple $cmd "" {
9398 -re "$cmd\r\n$gdb_prompt $" {
9399 return 0
9400 }
9401 -re -wrap "" {
9402 return 1
9403 }
9404 }
9405
9406 return 0
9407}
9408
c0502da6
TV
9409# Verify that partial symtab expansion for $filename has state $readin.
9410
9411proc verify_psymtab_expanded { filename readin } {
9412 global gdb_prompt
9413
9414 set cmd "maint info psymtab"
9415 set test "$cmd: $filename: $readin"
9416 set re [multi_line \
9417 " \{ psymtab \[^\r\n\]*$filename\[^\r\n\]*" \
9418 " readin $readin" \
9419 ".*"]
9420
9421 gdb_test_multiple $cmd $test {
9422 -re "$cmd\r\n$gdb_prompt $" {
9423 unsupported $gdb_test_name
9424 }
9425 -re -wrap $re {
9426 pass $gdb_test_name
9427 }
9428 }
9429}
9430
efba5c23
TV
9431# Add a .gdb_index section to PROGRAM.
9432# PROGRAM is assumed to be the output of standard_output_file.
9433# Returns the 0 if there is a failure, otherwise 1.
3da4c644
TT
9434#
9435# STYLE controls which style of index to add, if needed. The empty
9436# string (the default) means .gdb_index; "-dwarf-5" means .debug_names.
efba5c23 9437
3da4c644 9438proc add_gdb_index { program {style ""} } {
9170b70c 9439 global srcdir GDB env
efba5c23 9440 set contrib_dir "$srcdir/../contrib"
9170b70c 9441 set env(GDB) [append_gdb_data_directory_option $GDB]
3da4c644 9442 set result [catch "exec $contrib_dir/gdb-add-index.sh $style $program" output]
efba5c23
TV
9443 if { $result != 0 } {
9444 verbose -log "result is $result"
9445 verbose -log "output is $output"
9446 return 0
9447 }
9448
9449 return 1
9450}
9451
5c5e642d
AB
9452# Use 'maint print objfiles OBJFILE' to determine what (if any) type
9453# of index is present in OBJFILE. Return a string indicating the
9454# index type:
3da4c644 9455#
5c5e642d
AB
9456# 'gdb' - Contains a .gdb_index style index,
9457#
9458# 'dwarf5' - Contain DWARF5 style index sections,
9459#
9460# 'readnow' - A fake .gdb_index as a result of readnow being used,
9461#
9462# 'cooked' - The cooked index created when reading non-indexed debug
9463# information,
9464#
9465# 'none' - There's no index, and no debug information to create a
9466# cooked index from.
9467#
9468# If something goes wrong then this proc will emit a FAIL and return
9469# an empty string.
9470#
9471# TESTNAME is used as part of any pass/fail emitted from this proc.
9472proc get_index_type { objfile { testname "" } } {
9473 if { $testname eq "" } {
9474 set testname "find index type"
9475 }
6010fb0c 9476
5c5e642d
AB
9477 set index_type "unknown"
9478 gdb_test_multiple "maint print objfiles ${objfile}" $testname -lbl {
9479 -re "\r\n\\.gdb_index: version ${::decimal}(?=\r\n)" {
9480 set index_type "gdb"
6010fb0c 9481 gdb_test_lines "" $gdb_test_name ".*"
efba5c23 9482 }
6010fb0c 9483 -re "\r\n\\.debug_names: exists(?=\r\n)" {
5c5e642d 9484 set index_type "dwarf5"
6010fb0c 9485 gdb_test_lines "" $gdb_test_name ".*"
efba5c23 9486 }
95cbab2b 9487 -re "\r\n(Cooked index in use:|Psymtabs)(?=\r\n)" {
5c5e642d 9488 set index_type "cooked"
6010fb0c 9489 gdb_test_lines "" $gdb_test_name ".*"
efba5c23 9490 }
dbfc69be 9491 -re ".gdb_index: faked for \"readnow\"" {
5c5e642d 9492 set index_type "readnow"
dbfc69be
TV
9493 gdb_test_lines "" $gdb_test_name ".*"
9494 }
6010fb0c 9495 -re -wrap "" {
5c5e642d 9496 set index_type "none"
6010fb0c
TV
9497 }
9498 }
9499
5c5e642d
AB
9500 gdb_assert { $index_type ne "unknown" } \
9501 "$testname, check type is valid"
9502
9503 if { $index_type eq "unknown" } {
9504 set index_type ""
9505 }
9506
9507 return $index_type
9508}
9509
9510# Add a .gdb_index section to PROGRAM, unless it alread has an index
9511# (.gdb_index/.debug_names). Gdb doesn't support building an index from a
9512# program already using one. Return 1 if a .gdb_index was added, return 0
9513# if it already contained an index, and -1 if an error occurred.
9514#
9515# STYLE controls which style of index to add, if needed. The empty
9516# string (the default) means .gdb_index; "-dwarf-5" means .debug_names.
9517
9518proc ensure_gdb_index { binfile {style ""} } {
9519 set testfile [file tail $binfile]
9520
9521 set test "check if index present"
9522 set index_type [get_index_type $testfile $test]
9523
9524 if { $index_type eq "gdb" || $index_type eq "dwarf5" } {
6010fb0c 9525 return 0
efba5c23 9526 }
6010fb0c 9527
5c5e642d 9528 if { $index_type eq "readnow" } {
dbfc69be
TV
9529 return -1
9530 }
9531
6010fb0c
TV
9532 if { [add_gdb_index $binfile $style] == "1" } {
9533 return 1
9534 }
9535
efba5c23
TV
9536 return -1
9537}
9538
6e4e3fe1
TV
9539# Return 1 if executable contains .debug_types section. Otherwise, return 0.
9540
9541proc debug_types { } {
9542 global hex
9543
9544 set cmd "maint info sections"
9545 gdb_test_multiple $cmd "" {
9546 -re -wrap "at $hex: .debug_types.*" {
9547 return 1
9548 }
9549 -re -wrap "" {
9550 return 0
9551 }
9552 }
9553
9554 return 0
9555}
9556
7c99e7e2
TV
9557# Return the addresses in the line table for FILE for which is_stmt is true.
9558
9559proc is_stmt_addresses { file } {
9560 global decimal
9561 global hex
9562
9563 set is_stmt [list]
9564
9565 gdb_test_multiple "maint info line-table $file" "" {
904d9b02 9566 -re "\r\n$decimal\[ \t\]+$decimal\[ \t\]+($hex)\[ \t\]+$hex\[ \t\]+Y\[^\r\n\]*" {
7c99e7e2
TV
9567 lappend is_stmt $expect_out(1,string)
9568 exp_continue
9569 }
9570 -re -wrap "" {
9571 }
9572 }
9573
9574 return $is_stmt
9575}
9576
9577# Return 1 if hex number VAL is an element of HEXLIST.
9578
9579proc hex_in_list { val hexlist } {
9580 # Normalize val by removing 0x prefix, and leading zeros.
9581 set val [regsub ^0x $val ""]
9582 set val [regsub ^0+ $val "0"]
9583
9584 set re 0x0*$val
9585 set index [lsearch -regexp $hexlist $re]
9586 return [expr $index != -1]
9587}
9588
cc313a1d
TV
9589# As info args, but also add the default values.
9590
9591proc info_args_with_defaults { name } {
9592 set args {}
9593
9594 foreach arg [info args $name] {
9595 if { [info default $name $arg default_value] } {
9596 lappend args [list $arg $default_value]
9597 } else {
9598 lappend args $arg
9599 }
9600 }
9601
9602 return $args
9603}
9604
a8baf0a3
TV
9605# Override proc NAME to proc OVERRIDE for the duration of the execution of
9606# BODY.
9607
9608proc with_override { name override body } {
9609 # Implementation note: It's possible to implement the override using
9610 # rename, like this:
9611 # rename $name save_$name
9612 # rename $override $name
9613 # set code [catch {uplevel 1 $body} result]
9614 # rename $name $override
9615 # rename save_$name $name
9616 # but there are two issues here:
9617 # - the save_$name might clash with an existing proc
9618 # - the override is no longer available under its original name during
9619 # the override
9620 # So, we use this more elaborate but cleaner mechanism.
9621
c5dfcc21
SM
9622 # Save the old proc, if it exists.
9623 if { [info procs $name] != "" } {
cc313a1d 9624 set old_args [info_args_with_defaults $name]
c5dfcc21
SM
9625 set old_body [info body $name]
9626 set existed true
9627 } else {
9628 set existed false
9629 }
a8baf0a3
TV
9630
9631 # Install the override.
cc313a1d 9632 set new_args [info_args_with_defaults $override]
a8baf0a3
TV
9633 set new_body [info body $override]
9634 eval proc $name {$new_args} {$new_body}
9635
9636 # Execute body.
9637 set code [catch {uplevel 1 $body} result]
9638
c5dfcc21
SM
9639 # Restore old proc if it existed on entry, else delete it.
9640 if { $existed } {
9641 eval proc $name {$old_args} {$old_body}
9642 } else {
9643 rename $name ""
9644 }
a8baf0a3
TV
9645
9646 # Return as appropriate.
9647 if { $code == 1 } {
9648 global errorInfo errorCode
9649 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
9650 } elseif { $code > 1 } {
9651 return -code $code $result
9652 }
9653
9654 return $result
9655}
9656
4ebfd53d
TT
9657# Run BODY after setting the TERM environment variable to 'ansi', and
9658# unsetting the NO_COLOR environment variable.
9659proc with_ansi_styling_terminal { body } {
9660 save_vars { ::env(TERM) ::env(NO_COLOR) } {
9661 # Set environment variables to allow styling.
9662 setenv TERM ansi
9663 unset -nocomplain ::env(NO_COLOR)
9664
9665 set code [catch {uplevel 1 $body} result]
9666 }
9667
9668 if {$code == 1} {
9669 global errorInfo errorCode
9670 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
9671 } else {
9672 return -code $code $result
9673 }
9674}
9675
8c74a764
TV
9676# Setup tuiterm.exp environment. To be used in test-cases instead of
9677# "load_lib tuiterm.exp". Calls initialization function and schedules
9678# finalization function.
9679proc tuiterm_env { } {
9680 load_lib tuiterm.exp
8c74a764
TV
9681}
9682
37ab8655
TV
9683# Dejagnu has a version of note, but usage is not allowed outside of dejagnu.
9684# Define a local version.
9685proc gdb_note { message } {
9686 verbose -- "NOTE: $message" 0
9687}
9688
963eeee4 9689# Return 1 if compiler supports -fuse-ld=gold, otherwise return 0.
b50420fd 9690gdb_caching_proc have_fuse_ld_gold {} {
963eeee4
TV
9691 set me "have_fuse_ld_gold"
9692 set flags "additional_flags=-fuse-ld=gold"
9693 set src { int main() { return 0; } }
9694 return [gdb_simple_compile $me $src executable $flags]
9695}
9696
a0eda3df 9697# Return 1 if compiler supports fvar-tracking, otherwise return 0.
b50420fd 9698gdb_caching_proc have_fvar_tracking {} {
a0eda3df
CL
9699 set me "have_fvar_tracking"
9700 set flags "additional_flags=-fvar-tracking"
9701 set src { int main() { return 0; } }
9702 return [gdb_simple_compile $me $src executable $flags]
9703}
9704
2bb8c72b 9705# Return 1 if linker supports -Ttext-segment, otherwise return 0.
b50420fd 9706gdb_caching_proc linker_supports_Ttext_segment_flag {} {
2bb8c72b 9707 set me "linker_supports_Ttext_segment_flag"
21f507ef 9708 set flags ldflags="-Wl,-Ttext-segment=0x7000000"
2bb8c72b
VB
9709 set src { int main() { return 0; } }
9710 return [gdb_simple_compile $me $src executable $flags]
9711}
9712
9713# Return 1 if linker supports -Ttext, otherwise return 0.
b50420fd 9714gdb_caching_proc linker_supports_Ttext_flag {} {
2bb8c72b 9715 set me "linker_supports_Ttext_flag"
21f507ef 9716 set flags ldflags="-Wl,-Ttext=0x7000000"
2bb8c72b
VB
9717 set src { int main() { return 0; } }
9718 return [gdb_simple_compile $me $src executable $flags]
9719}
9720
9721# Return 1 if linker supports --image-base, otherwise 0.
b50420fd 9722gdb_caching_proc linker_supports_image_base_flag {} {
2bb8c72b 9723 set me "linker_supports_image_base_flag"
21f507ef 9724 set flags ldflags="-Wl,--image-base=0x7000000"
2bb8c72b
VB
9725 set src { int main() { return 0; } }
9726 return [gdb_simple_compile $me $src executable $flags]
9727}
9728
9729
60108e47
TV
9730# Return 1 if compiler supports scalar_storage_order attribute, otherwise
9731# return 0.
b50420fd 9732gdb_caching_proc supports_scalar_storage_order_attribute {} {
60108e47
TV
9733 set me "supports_scalar_storage_order_attribute"
9734 set src {
9735 #include <string.h>
9736 struct sle {
9737 int v;
9738 } __attribute__((scalar_storage_order("little-endian")));
9739 struct sbe {
9740 int v;
9741 } __attribute__((scalar_storage_order("big-endian")));
9742 struct sle sle;
9743 struct sbe sbe;
9744 int main () {
9745 sle.v = sbe.v = 0x11223344;
9746 int same = memcmp (&sle, &sbe, sizeof (int)) == 0;
9747 int sso = !same;
9748 return sso;
9749 }
9750 }
9751 if { ![gdb_simple_compile $me $src executable ""] } {
9752 return 0
9753 }
9754
0eb0e082
TV
9755 set target_obj [gdb_remote_download target $obj]
9756 set result [remote_exec target $target_obj]
60108e47
TV
9757 set status [lindex $result 0]
9758 set output [lindex $result 1]
9759 if { $output != "" } {
9760 return 0
9761 }
9762
9763 return $status
9764}
9765
9766# Return 1 if compiler supports __GNUC__, otherwise return 0.
b50420fd 9767gdb_caching_proc supports_gnuc {} {
60108e47
TV
9768 set me "supports_gnuc"
9769 set src {
9770 #ifndef __GNUC__
9771 #error "No gnuc"
9772 #endif
9773 }
9774 return [gdb_simple_compile $me $src object ""]
9775}
9776
3f94e588 9777# Return 1 if target supports mpx, otherwise return 0.
b50420fd 9778gdb_caching_proc have_mpx {} {
3f94e588
TV
9779 global srcdir
9780
9781 set me "have_mpx"
9782 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
9783 verbose "$me: target does not support mpx, returning 0" 2
9784 return 0
9785 }
9786
9787 # Compile a test program.
9788 set src {
9789 #include "nat/x86-cpuid.h"
9790
9791 int main() {
9792 unsigned int eax, ebx, ecx, edx;
9793
9794 if (!__get_cpuid (1, &eax, &ebx, &ecx, &edx))
9795 return 0;
9796
9797 if ((ecx & bit_OSXSAVE) == bit_OSXSAVE)
9798 {
9799 if (__get_cpuid_max (0, (void *)0) < 7)
9800 return 0;
9801
9802 __cpuid_count (7, 0, eax, ebx, ecx, edx);
9803
9804 if ((ebx & bit_MPX) == bit_MPX)
9805 return 1;
9806
9807 }
9808 return 0;
9809 }
9810 }
9811 set compile_flags "incdir=${srcdir}/.."
9812 if {![gdb_simple_compile $me $src executable $compile_flags]} {
9813 return 0
9814 }
9815
0eb0e082
TV
9816 set target_obj [gdb_remote_download target $obj]
9817 set result [remote_exec target $target_obj]
3f94e588
TV
9818 set status [lindex $result 0]
9819 set output [lindex $result 1]
9820 if { $output != "" } {
9821 set status 0
9822 }
9823
9824 remote_file build delete $obj
75b2a443
TV
9825
9826 if { $status == 0 } {
9827 verbose "$me: returning $status" 2
9828 return $status
9829 }
9830
9831 # Compile program with -mmpx -fcheck-pointer-bounds, try to trigger
9832 # 'No MPX support', in other words, see if kernel supports mpx.
9833 set src { int main (void) { return 0; } }
9834 set comp_flags {}
9835 append comp_flags " additional_flags=-mmpx"
9836 append comp_flags " additional_flags=-fcheck-pointer-bounds"
9837 if {![gdb_simple_compile $me-2 $src executable $comp_flags]} {
9838 return 0
9839 }
9840
0eb0e082
TV
9841 set target_obj [gdb_remote_download target $obj]
9842 set result [remote_exec target $target_obj]
75b2a443
TV
9843 set status [lindex $result 0]
9844 set output [lindex $result 1]
9845 set status [expr ($status == 0) \
43792b0d 9846 && ![regexp "^No MPX support\r?\n" $output]]
75b2a443
TV
9847
9848 remote_file build delete $obj
3f94e588
TV
9849
9850 verbose "$me: returning $status" 2
9851 return $status
9852}
9853
10f3fbec 9854# Return 1 if target supports avx, otherwise return 0.
b50420fd 9855gdb_caching_proc have_avx {} {
10f3fbec
TV
9856 global srcdir
9857
9858 set me "have_avx"
9859 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
9860 verbose "$me: target does not support avx, returning 0" 2
9861 return 0
9862 }
9863
9864 # Compile a test program.
9865 set src {
9866 #include "nat/x86-cpuid.h"
9867
9868 int main() {
9869 unsigned int eax, ebx, ecx, edx;
9870
9871 if (!x86_cpuid (1, &eax, &ebx, &ecx, &edx))
9872 return 0;
9873
9874 if ((ecx & (bit_AVX | bit_OSXSAVE)) == (bit_AVX | bit_OSXSAVE))
9875 return 1;
9876 else
9877 return 0;
9878 }
9879 }
9880 set compile_flags "incdir=${srcdir}/.."
9881 if {![gdb_simple_compile $me $src executable $compile_flags]} {
9882 return 0
9883 }
9884
0eb0e082
TV
9885 set target_obj [gdb_remote_download target $obj]
9886 set result [remote_exec target $target_obj]
10f3fbec
TV
9887 set status [lindex $result 0]
9888 set output [lindex $result 1]
9889 if { $output != "" } {
9890 set status 0
9891 }
9892
9893 remote_file build delete $obj
9894
9895 verbose "$me: returning $status" 2
9896 return $status
9897}
9898
793862d2
TT
9899# Called as
9900# - require ARG...
9901#
9902# ARG can either be a name, or of the form !NAME.
9903#
7cd38c3c
SM
9904# Each name is a proc to evaluate in the caller's context. It can return a
9905# boolean or a two element list with a boolean and a reason string.
9906# A "!" means to invert the result. If this is true, all is well. If it is
9907# false, an "unsupported" is emitted and this proc causes the caller to return.
9908#
9909# The reason string is used to provide some context about a require failure,
9910# and is included in the "unsupported" message.
4f69f0a2 9911
793862d2
TT
9912proc require { args } {
9913 foreach arg $args {
9914 if {[string index $arg 0] == "!"} {
7cd38c3c 9915 set required_val 0
793862d2
TT
9916 set fn [string range $arg 1 end]
9917 } else {
7cd38c3c 9918 set required_val 1
793862d2 9919 set fn $arg
19abf6c5 9920 }
7cd38c3c
SM
9921
9922 set result [uplevel 1 $fn]
9923 set len [llength $result]
9924 if { $len == 2 } {
9925 set actual_val [lindex $result 0]
9926 set msg [lindex $result 1]
9927 } elseif { $len == 1 } {
9928 set actual_val $result
9929 set msg ""
9930 } else {
9931 error "proc $fn returned a list of unexpected length $len"
9932 }
9933
9934 if {$required_val != !!$actual_val} {
9935 if { [string length $msg] > 0 } {
9936 unsupported "require failed: $arg ($msg)"
9937 } else {
9938 unsupported "require failed: $arg"
9939 }
9940
793862d2 9941 return -code return 0
2786ef85 9942 }
4f69f0a2 9943 }
4f69f0a2
TV
9944}
9945
df5ad102
SM
9946# Wait up to ::TIMEOUT seconds for file PATH to exist on the target system.
9947# Return 1 if it does exist, 0 otherwise.
9948
9949proc target_file_exists_with_timeout { path } {
9950 for {set i 0} {$i < $::timeout} {incr i} {
9951 if { [remote_file target exists $path] } {
9952 return 1
9953 }
9954
9955 sleep 1
9956 }
9957
9958 return 0
9959}
9960
b50420fd 9961gdb_caching_proc has_hw_wp_support {} {
8d4e4d13
CL
9962 # Power 9, proc rev 2.2 does not support HW watchpoints due to HW bug.
9963 # Need to use a runtime test to determine if the Power processor has
9964 # support for HW watchpoints.
9965 global srcdir subdir gdb_prompt inferior_exited_re
9966
8d4e4d13
CL
9967 set me "has_hw_wp_support"
9968
4f04dba9
TV
9969 global gdb_spawn_id
9970 if { [info exists gdb_spawn_id] } {
9971 error "$me called with running gdb instance"
9972 }
9973
9974 set compile_flags {debug nowarnings quiet}
9975
8d4e4d13
CL
9976 # Compile a test program to test if HW watchpoints are supported
9977 set src {
9978 int main (void) {
9979 volatile int local;
9980 local = 1;
9981 if (local == 1)
9982 return 1;
9983 return 0;
9984 }
9985 }
9986
9987 if {![gdb_simple_compile $me $src executable $compile_flags]} {
9988 return 0
9989 }
9990
8d4e4d13
CL
9991 gdb_start
9992 gdb_reinitialize_dir $srcdir/$subdir
9993 gdb_load "$obj"
9994
9995 if ![runto_main] {
4f04dba9
TV
9996 gdb_exit
9997 remote_file build delete $obj
9998
8d4e4d13
CL
9999 set has_hw_wp_support 0
10000 return $has_hw_wp_support
10001 }
10002
10003 # The goal is to determine if HW watchpoints are available in general.
10004 # Use "watch" and then check if gdb responds with hardware watch point.
10005 set test "watch local"
10006
10007 gdb_test_multiple $test "Check for HW watchpoint support" {
10008 -re ".*Hardware watchpoint.*" {
10009 # HW watchpoint supported by platform
10010 verbose -log "\n$me: Hardware watchpoint detected"
10011 set has_hw_wp_support 1
10012 }
10013 -re ".*$gdb_prompt $" {
10014 set has_hw_wp_support 0
10015 verbose -log "\n$me: Default, hardware watchpoint not deteced"
10016 }
10017 }
10018
10019 gdb_exit
10020 remote_file build delete $obj
10021
10022 verbose "$me: returning $has_hw_wp_support" 2
10023 return $has_hw_wp_support
10024}
10025
feb5926e
TV
10026# Return a list of all the accepted values of the set command
10027# "SET_CMD SET_ARG".
10028# For example get_set_option_choices "set architecture" "i386".
01772c54 10029
feb5926e 10030proc get_set_option_choices { set_cmd {set_arg ""} } {
01772c54
PA
10031 set values {}
10032
feb5926e
TV
10033 if { $set_arg == "" } {
10034 # Add trailing space to signal that we need completion of the choices,
10035 # not of set_cmd itself.
10036 set cmd "complete $set_cmd "
10037 } else {
10038 set cmd "complete $set_cmd $set_arg"
10039 }
10040
10041 # Set test name without trailing space.
10042 set test [string trim $cmd]
8d45c3a8
TV
10043
10044 with_set max-completions unlimited {
10045 gdb_test_multiple $cmd $test {
7e213799
SM
10046 -re "^[string_to_regexp $cmd]\r\n" {
10047 exp_continue
10048 }
10049
10050 -re "^$set_cmd (\[^\r\n\]+)\r\n" {
8d45c3a8
TV
10051 lappend values $expect_out(1,string)
10052 exp_continue
10053 }
7e213799
SM
10054
10055 -re "^$::gdb_prompt $" {
8d45c3a8
TV
10056 pass $gdb_test_name
10057 }
01772c54
PA
10058 }
10059 }
8d45c3a8 10060
01772c54
PA
10061 return $values
10062}
10063
bc2220c8
PA
10064# Return the compiler that can generate 32-bit ARM executables. Used
10065# when testing biarch support on Aarch64. If ARM_CC_FOR_TARGET is
10066# set, use that. If not, try a few common compiler names, making sure
10067# that the executable they produce can run.
10068
b50420fd 10069gdb_caching_proc arm_cc_for_target {} {
8db775b2 10070 if {[info exists ::ARM_CC_FOR_TARGET]} {
bc2220c8
PA
10071 # If the user specified the compiler explicitly, then don't
10072 # check whether the resulting binary runs outside GDB. Assume
10073 # that it does, and if it turns out it doesn't, then the user
10074 # should get loud FAILs, instead of UNSUPPORTED.
8db775b2 10075 return $::ARM_CC_FOR_TARGET
bc2220c8
PA
10076 }
10077
10078 # Fallback to a few common compiler names. Also confirm the
10079 # produced binary actually runs on the system before declaring
10080 # we've found the right compiler.
10081
10082 if [istarget "*-linux*-*"] {
10083 set compilers {
10084 arm-linux-gnueabi-gcc
10085 arm-none-linux-gnueabi-gcc
10086 arm-linux-gnueabihf-gcc
10087 }
10088 } else {
10089 set compilers {}
10090 }
10091
10092 foreach compiler $compilers {
10093 if {![is_remote host] && [which $compiler] == 0} {
10094 # Avoid "default_target_compile: Can't find
10095 # $compiler." warning issued from gdb_compile.
10096 continue
10097 }
10098
10099 set src { int main() { return 0; } }
10100 if {[gdb_simple_compile aarch64-32bit \
10101 $src \
10102 executable [list compiler=$compiler]]} {
10103
0eb0e082
TV
10104 set target_obj [gdb_remote_download target $obj]
10105 set result [remote_exec target $target_obj]
bc2220c8
PA
10106 set status [lindex $result 0]
10107 set output [lindex $result 1]
10108
10109 file delete $obj
10110
10111 if { $output == "" && $status == 0} {
10112 return $compiler
10113 }
10114 }
10115 }
10116
10117 return ""
10118}
10119
9db78678
BL
10120# Step until the pattern REGEXP is found. Step at most
10121# MAX_STEPS times, but stop stepping once REGEXP is found.
334d405c 10122# CURRENT matches current location
9db78678
BL
10123# If REGEXP is found then a single pass is emitted, otherwise, after
10124# MAX_STEPS steps, a single fail is emitted.
10125#
10126# TEST_NAME is the name used in the pass/fail calls.
10127
334d405c
CL
10128proc gdb_step_until { regexp {test_name "stepping until regexp"} \
10129 {current "\}"} { max_steps 10 } } {
10130 repeat_cmd_until "step" $current $regexp $test_name "10"
10131}
10132
10133# Do repeated stepping COMMANDs in order to reach TARGET from CURRENT
10134#
10135# COMMAND is a stepping command
10136# CURRENT is a string matching the current location
10137# TARGET is a string matching the target location
10138# TEST_NAME is the test name
10139# MAX_STEPS is number of steps attempted before fail is emitted
10140#
10141# The function issues repeated COMMANDs as long as the location matches
10142# CURRENT up to a maximum of MAX_STEPS.
10143#
10144# TEST_NAME passes if the resulting location matches TARGET and fails
10145# otherwise.
10146
10147proc repeat_cmd_until { command current target \
10148 {test_name "stepping until regexp"} \
10149 {max_steps 100} } {
10150 global gdb_prompt
9db78678
BL
10151
10152 set count 0
334d405c 10153 gdb_test_multiple "$command" "$test_name" {
890891f1
GL
10154 -re "$target.*$gdb_prompt $" {
10155 pass "$test_name"
10156 }
334d405c
CL
10157 -re "$current.*$gdb_prompt $" {
10158 incr count
10159 if { $count < $max_steps } {
10160 send_gdb "$command\n"
9db78678
BL
10161 exp_continue
10162 } else {
334d405c 10163 fail "$test_name"
9db78678
BL
10164 }
10165 }
10166 }
10167}
10168
47171eeb
AB
10169# Return false if the current target is not operating in non-stop
10170# mode, otherwise, return true.
10171#
10172# The inferior will need to have started running in order to get the
10173# correct result.
10174
10175proc is_target_non_stop { {testname ""} } {
10176 # For historical reasons we assume non-stop mode is on. If the
10177 # maintenance command fails for any reason then we're going to
10178 # return true.
10179 set is_non_stop true
10180 gdb_test_multiple "maint show target-non-stop" $testname {
10181 -wrap -re "(is|currently) on.*" {
10182 set is_non_stop true
10183 }
10184 -wrap -re "(is|currently) off.*" {
10185 set is_non_stop false
10186 }
10187 }
10188 return $is_non_stop
10189}
10190
aff25014
AB
10191# Return the number of worker threads that GDB is currently using.
10192
10193proc gdb_get_worker_threads { {testname ""} } {
10194 set worker_threads "UNKNOWN"
10195 gdb_test_multiple "maintenance show worker-threads" $testname {
66e00622 10196 -wrap -re "^The number of worker threads GDB can use is the default \\(currently ($::decimal)\\)\\." {
aff25014
AB
10197 set worker_threads $expect_out(1,string)
10198 }
b489eb90 10199 -wrap -re "^The number of worker threads GDB can use is ($::decimal)\\." {
aff25014
AB
10200 set worker_threads $expect_out(1,string)
10201 }
10202 }
10203 return $worker_threads
10204}
10205
07bb02de
BL
10206# Check if the compiler emits epilogue information associated
10207# with the closing brace or with the last statement line.
10208#
10209# This proc restarts GDB
10210#
10211# Returns True if it is associated with the closing brace,
10212# False if it is the last statement
b50420fd 10213gdb_caching_proc have_epilogue_line_info {} {
07bb02de
BL
10214
10215 set main {
10216 int
10217 main ()
10218 {
10219 return 0;
10220 }
10221 }
10222 if {![gdb_simple_compile "simple_program" $main]} {
10223 return False
10224 }
10225
10226 clean_restart $obj
10227
10228 gdb_test_multiple "info line 6" "epilogue test" {
10229 -re -wrap ".*starts at address.*and ends at.*" {
10230 return True
10231 }
10232 -re -wrap ".*" {
10233 return False
10234 }
10235 }
10236}
10237
24eb586f
TV
10238# Decompress file BZ2, and return it.
10239
10240proc decompress_bz2 { bz2 } {
10241 set copy [standard_output_file [file tail $bz2]]
10242 set copy [remote_download build $bz2 $copy]
10243 if { $copy == "" } {
10244 return $copy
10245 }
10246
10247 set res [remote_exec build "bzip2" "-df $copy"]
10248 if { [lindex $res 0] == -1 } {
10249 return ""
10250 }
10251
10252 set copy [regsub {.bz2$} $copy ""]
10253 if { ![remote_file build exists $copy] } {
10254 return ""
10255 }
10256
10257 return $copy
10258}
10259
f1e19328
TV
10260# Return 1 if the output of "ldd FILE" contains regexp DEP, 0 if it doesn't,
10261# and -1 if there was a problem running the command.
10262
10263proc has_dependency { file dep } {
10264 set ldd [gdb_find_ldd]
10265 set command "$ldd $file"
10266 set result [remote_exec host $command]
10267 set status [lindex $result 0]
10268 set output [lindex $result 1]
10269 verbose -log "status of $command is $status"
10270 verbose -log "output of $command is $output"
10271 if { $status != 0 || $output == "" } {
10272 return -1
10273 }
10274 return [regexp $dep $output]
10275}
10276
37d75d45
TV
10277# Detect linux kernel version and return as list of 3 numbers: major, minor,
10278# and patchlevel. On failure, return an empty list.
10279
b50420fd 10280gdb_caching_proc linux_kernel_version {} {
37d75d45
TV
10281 if { ![istarget *-*-linux*] } {
10282 return {}
10283 }
10284
10285 set res [remote_exec target "uname -r"]
10286 set status [lindex $res 0]
10287 set output [lindex $res 1]
10288 if { $status != 0 } {
10289 return {}
10290 }
10291
10292 set re ^($::decimal)\\.($::decimal)\\.($::decimal)
10293 if { [regexp $re $output dummy v1 v2 v3] != 1 } {
10294 return {}
10295 }
10296
10297 return [list $v1 $v2 $v3]
10298}
10299
b3060b05
TV
10300# Return 1 if syscall NAME is supported.
10301
10302proc have_syscall { name } {
10303 set src \
10304 [list \
10305 "#include <sys/syscall.h>" \
10306 "int var = SYS_$name;"]
10307 set src [join $src "\n"]
10308 return [gdb_can_simple_compile have_syscall_$name $src object]
10309}
10310
491b4c18
TV
10311# Return 1 if compile flag FLAG is supported.
10312
71f1ab80 10313gdb_caching_proc have_compile_flag { flag } {
491b4c18
TV
10314 set src { void foo () {} }
10315 return [gdb_can_simple_compile have_compile_flag_$flag $src object \
10316 additional_flags=$flag]
10317}
10318
ac3c4894
TV
10319# Return 1 if we can create an executable using compile and link flag FLAG.
10320
10321gdb_caching_proc have_compile_and_link_flag { flag } {
10322 set src { int main () { return 0; } }
10323 return [gdb_can_simple_compile have_compile_and_link_flag_$flag $src executable \
10324 additional_flags=$flag]
10325}
10326
6af166ed
JB
10327# Return 1 if this GDB is configured with a "native" target.
10328
10329gdb_caching_proc have_native_target {} {
10330 gdb_test_multiple "help target native" "" {
10331 -re -wrap "Undefined target command.*" {
10332 return 0
10333 }
10334 -re -wrap "Native process.*" {
10335 return 1
10336 }
10337 }
10338 return 0
10339}
10340
722c4596
TV
10341# Handle include file $srcdir/$subdir/FILE.
10342
10343proc include_file { file } {
10344 set file [file join $::srcdir $::subdir $file]
10345 if { [is_remote host] } {
10346 set res [remote_download host $file]
10347 } else {
10348 set res $file
10349 }
10350
10351 return $res
10352}
4581f89b
TV
10353
10354# Handle include file FILE, and if necessary update compiler flags variable
10355# FLAGS.
10356
10357proc lappend_include_file { flags file } {
10358 upvar $flags up_flags
10359 if { [is_remote host] } {
10360 gdb_remote_download host $file
10361 } else {
10362 set dir [file dirname $file]
10363 if { $dir != [file join $::srcdir $::subdir] } {
10364 lappend up_flags "additional_flags=-I$dir"
10365 }
10366 }
10367}
10368
83aa2551
TV
10369# Return a list of supported host locales.
10370
10371gdb_caching_proc host_locales { } {
10372 set result [remote_exec host "locale -a"]
10373 set status [lindex $result 0]
10374 set output [lindex $result 1]
10375
10376 if { $status != 0 } {
10377 return {}
10378 }
10379
10380 # Split into list.
10381 set output [string trim $output]
10382 set l [split $output \n]
10383
10384 # Trim items.
10385 set l [lmap v $l { string trim $v }]
10386
10387 # Normalize items to lower-case.
10388 set l [lmap v $l { string tolower $v }]
ee12f46f
TV
10389 # Normalize items to without dash.
10390 set l [lmap v $l { string map { "-" "" } $v }]
83aa2551
TV
10391
10392 return $l
10393}
10394
10395# Return 1 if host locale LOCALE is supported.
10396
10397proc have_host_locale { locale } {
10398 # Normalize to lower-case.
10399 set locale [string tolower $locale]
10400 # Normalize to without dash.
10401 set locale [string map { "-" "" } $locale]
10402
10403 set idx [lsearch [host_locales] $locale]
10404 return [expr $idx != -1]
10405}
10406
130e33d8
TV
10407# Return 1 if we can use '#include <$file>' in source file.
10408
10409gdb_caching_proc have_system_header { file } {
10410 set src "#include <$file>"
10411 set name [string map { "/" "_sep_" } $file]
10412 return [gdb_can_simple_compile have_system_header_$name $src object]
10413}
10414
1bdabb9e
GL
10415# Return 1 if the test is being run as root, 0 otherwise.
10416
10417gdb_caching_proc root_user {} {
10418 # ID outputs to stdout, we have to use exec to capture it here.
10419 set res [remote_exec target id]
10420 set ret_val [lindex $res 0]
10421 set output [lindex $res 1]
10422
10423 # If ret_val is not 0, we couldn't run `id` on the target for some
10424 # reason. Return that we are not root, so problems are easier to
10425 # spot.
10426 if { $ret_val != 0 } {
10427 return 0
10428 }
10429
10430 regexp -all ".*uid=(\[0-9\]+).*" $output dummy uid
10431
10432 return [expr $uid == 0]
10433}
10434
42159ca5
TT
10435# Always load compatibility stuff.
10436load_lib future.exp