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