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