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