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