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