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