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