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