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