[gdb/testsuite] Add PR gdb/26967 KFAIL in two more test-cases
[binutils-gdb.git] / gdb / testsuite / lib / gdb.exp
bloba0c4855ffc5589db91a1a8831e787faea3aa1722
1 # Copyright 1992-2024 Free Software Foundation, Inc.
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
5 # the Free Software Foundation; either version 3 of the License, or
6 # (at your option) any later version.
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.
13 # You should have received a copy of the GNU General Public License
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 # This file was written by Fred Fish. (fnf@cygnus.com)
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.
22 if {$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
28 # Execute BODY, if COND wrapped in proc WRAP.
29 # Instead of writing the verbose and repetitive:
30 # if { $cond } {
31 # wrap $body
32 # } else {
33 # $body
34 # }
35 # we can use instead:
36 # cond_wrap $cond wrap $body
38 proc cond_wrap { cond wrap body } {
39 if { $cond } {
40 $wrap {
41 uplevel 1 $body
43 } else {
44 uplevel 1 $body
48 # Add VAR_ID=VAL to ENV_VAR, unless ENV_VAR already contains a VAR_ID setting.
50 proc set_sanitizer_default { env_var var_id val } {
51 global env
53 if { ![info exists env($env_var) ]
54 || $env($env_var) == "" } {
55 # Set var_id (env_var non-existing / empty case).
56 append env($env_var) $var_id=$val
57 return
60 if { [regexp $var_id= $env($env_var)] } {
61 # Don't set var_id. It's already set by the user, leave as is.
62 # Note that we could probably get the same result by unconditionally
63 # prepending it, but this way is less likely to cause confusion.
64 return
67 # Set var_id (env_var not empty case).
68 append env($env_var) : $var_id=$val
71 set_sanitizer_default TSAN_OPTIONS suppressions \
72 $srcdir/../tsan-suppressions.txt
74 # When using ThreadSanitizer we may run into the case that a race is detected,
75 # but we see the full stack trace only for one of the two accesses, and the
76 # other one is showing "failed to restore the stack".
77 # Try to prevent this by setting history_size to the maximum (7) by default.
78 # See also the ThreadSanitizer docs (
79 # https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags ).
80 set_sanitizer_default TSAN_OPTIONS history_size 7
82 # If GDB is built with ASAN (and because there are leaks), it will output a
83 # leak report when exiting as well as exit with a non-zero (failure) status.
84 # This can affect tests that are sensitive to what GDB prints on stderr or its
85 # exit status. Add `detect_leaks=0` to the ASAN_OPTIONS environment variable
86 # (which will affect any spawned sub-process) to avoid this.
87 set_sanitizer_default ASAN_OPTIONS detect_leaks 0
89 # List of procs to run in gdb_finish.
90 set gdb_finish_hooks [list]
92 # Variable in which we keep track of globals that are allowed to be live
93 # across test-cases.
94 array set gdb_persistent_globals {}
96 # Mark variable names in ARG as a persistent global, and declare them as
97 # global in the calling context. Can be used to rewrite "global var_a var_b"
98 # into "gdb_persistent_global var_a var_b".
99 proc gdb_persistent_global { args } {
100 global gdb_persistent_globals
101 foreach varname $args {
102 uplevel 1 global $varname
103 set gdb_persistent_globals($varname) 1
107 # Mark variable names in ARG as a persistent global.
108 proc gdb_persistent_global_no_decl { args } {
109 global gdb_persistent_globals
110 foreach varname $args {
111 set gdb_persistent_globals($varname) 1
115 # Override proc load_lib.
116 rename load_lib saved_load_lib
117 # Run the runtest version of load_lib, and mark all variables that were
118 # created by this call as persistent.
119 proc load_lib { file } {
120 array set known_global {}
121 foreach varname [info globals] {
122 set known_globals($varname) 1
125 set code [catch "saved_load_lib $file" result]
127 foreach varname [info globals] {
128 if { ![info exists known_globals($varname)] } {
129 gdb_persistent_global_no_decl $varname
133 if {$code == 1} {
134 global errorInfo errorCode
135 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
136 } elseif {$code > 1} {
137 return -code $code $result
140 return $result
143 load_lib libgloss.exp
144 load_lib cache.exp
145 load_lib gdb-utils.exp
146 load_lib memory.exp
147 load_lib check-test-names.exp
149 # The path to the GDB binary to test.
150 global GDB
152 # The data directory to use for testing. If this is the empty string,
153 # then we let GDB use its own configured data directory.
154 global GDB_DATA_DIRECTORY
156 # The spawn ID used for I/O interaction with the inferior. For native
157 # targets, or remote targets that can do I/O through GDB
158 # (semi-hosting) this will be the same as the host/GDB's spawn ID.
159 # Otherwise, the board may set this to some other spawn ID. E.g.,
160 # when debugging with GDBserver, this is set to GDBserver's spawn ID,
161 # so input/output is done on gdbserver's tty.
162 global inferior_spawn_id
164 if [info exists TOOL_EXECUTABLE] {
165 set GDB $TOOL_EXECUTABLE
167 if ![info exists GDB] {
168 if ![is_remote host] {
169 set GDB [findfile $base_dir/../../gdb/gdb "$base_dir/../../gdb/gdb" [transform gdb]]
170 } else {
171 set GDB [transform gdb]
173 } else {
174 # If the user specifies GDB on the command line, and doesn't
175 # specify GDB_DATA_DIRECTORY, then assume we're testing an
176 # installed GDB, and let it use its own configured data directory.
177 if ![info exists GDB_DATA_DIRECTORY] {
178 set GDB_DATA_DIRECTORY ""
181 verbose "using GDB = $GDB" 2
183 # The data directory the testing GDB will use. By default, assume
184 # we're testing a non-installed GDB in the build directory. Users may
185 # also explicitly override the -data-directory from the command line.
186 if ![info exists GDB_DATA_DIRECTORY] {
187 set GDB_DATA_DIRECTORY [file normalize "[pwd]/../data-directory"]
189 verbose "using GDB_DATA_DIRECTORY = $GDB_DATA_DIRECTORY" 2
191 # GDBFLAGS is available for the user to set on the command line.
192 # E.g. make check RUNTESTFLAGS=GDBFLAGS=mumble
193 # Testcases may use it to add additional flags, but they must:
194 # - append new flags, not overwrite
195 # - restore the original value when done
196 global GDBFLAGS
197 if ![info exists GDBFLAGS] {
198 set GDBFLAGS ""
200 verbose "using GDBFLAGS = $GDBFLAGS" 2
202 # Append the -data-directory option to pass to GDB to CMDLINE and
203 # return the resulting string. If GDB_DATA_DIRECTORY is empty,
204 # nothing is appended.
205 proc append_gdb_data_directory_option {cmdline} {
206 global GDB_DATA_DIRECTORY
208 if { $GDB_DATA_DIRECTORY != "" } {
209 return "$cmdline -data-directory $GDB_DATA_DIRECTORY"
210 } else {
211 return $cmdline
215 # INTERNAL_GDBFLAGS contains flags that the testsuite requires.
216 # `-nw' disables any of the windowed interfaces.
217 # `-nx' disables ~/.gdbinit, so that it doesn't interfere with the tests.
218 # `-iex "set {height,width} 0"' disables pagination.
219 # `-data-directory' points to the data directory, usually in the build
220 # directory.
221 global INTERNAL_GDBFLAGS
222 if ![info exists INTERNAL_GDBFLAGS] {
223 set INTERNAL_GDBFLAGS \
224 [join [list \
225 "-nw" \
226 "-nx" \
227 "-q" \
228 {-iex "set height 0"} \
229 {-iex "set width 0"}]]
231 # If DEBUGINFOD_URLS is set, gdb will try to download sources and
232 # debug info for f.i. system libraries. Prevent this.
233 if { [is_remote host] } {
234 # Setting environment variables on build has no effect on remote host,
235 # so handle this using "set debuginfod enabled off" instead.
236 set INTERNAL_GDBFLAGS \
237 "$INTERNAL_GDBFLAGS -iex \"set debuginfod enabled off\""
238 } else {
239 # See default_gdb_init.
242 set INTERNAL_GDBFLAGS [append_gdb_data_directory_option $INTERNAL_GDBFLAGS]
245 # The variable gdb_prompt is a regexp which matches the gdb prompt.
246 # Set it if it is not already set. This is also set by default_gdb_init
247 # but it's not clear what removing one of them will break.
248 # See with_gdb_prompt for more details on prompt handling.
249 global gdb_prompt
250 if {![info exists gdb_prompt]} {
251 set gdb_prompt "\\(gdb\\)"
254 # A regexp that matches the pagination prompt.
255 set pagination_prompt \
256 "--Type <RET> for more, q to quit, c to continue without paging--"
258 # The variable fullname_syntax_POSIX is a regexp which matches a POSIX
259 # absolute path ie. /foo/
260 set fullname_syntax_POSIX {/[^\n]*/}
261 # The variable fullname_syntax_UNC is a regexp which matches a Windows
262 # UNC path ie. \\D\foo\
263 set fullname_syntax_UNC {\\\\[^\\]+\\[^\n]+\\}
264 # The variable fullname_syntax_DOS_CASE is a regexp which matches a
265 # particular DOS case that GDB most likely will output
266 # ie. \foo\, but don't match \\.*\
267 set fullname_syntax_DOS_CASE {\\[^\\][^\n]*\\}
268 # The variable fullname_syntax_DOS is a regexp which matches a DOS path
269 # ie. a:\foo\ && a:foo\
270 set fullname_syntax_DOS {[a-zA-Z]:[^\n]*\\}
271 # The variable fullname_syntax is a regexp which matches what GDB considers
272 # an absolute path. It is currently debatable if the Windows style paths
273 # d:foo and \abc should be considered valid as an absolute path.
274 # Also, the purpse of this regexp is not to recognize a well formed
275 # absolute path, but to say with certainty that a path is absolute.
276 set fullname_syntax "($fullname_syntax_POSIX|$fullname_syntax_UNC|$fullname_syntax_DOS_CASE|$fullname_syntax_DOS)"
278 # Needed for some tests under Cygwin.
279 global EXEEXT
280 global env
282 if ![info exists env(EXEEXT)] {
283 set EXEEXT ""
284 } else {
285 set EXEEXT $env(EXEEXT)
288 set octal "\[0-7\]+"
290 set inferior_exited_re "(?:\\\[Inferior \[0-9\]+ \\(\[^\n\r\]*\\) exited)"
292 # A regular expression that matches a value history number.
293 # E.g., $1, $2, etc.
294 set valnum_re "\\\$$decimal"
296 # A regular expression that matches a breakpoint hit with a breakpoint
297 # having several code locations.
298 set bkptno_num_re "$decimal\\.$decimal"
300 # A regular expression that matches a breakpoint hit
301 # with one or several code locations.
302 set bkptno_numopt_re "($decimal\\.$decimal|$decimal)"
304 ### Only procedures should come after this point.
307 # gdb_version -- extract and print the version number of GDB
309 proc default_gdb_version {} {
310 global GDB
311 global INTERNAL_GDBFLAGS GDBFLAGS
312 global gdb_prompt
313 global inotify_pid
315 if {[info exists inotify_pid]} {
316 eval exec kill $inotify_pid
319 set output [remote_exec host "$GDB $INTERNAL_GDBFLAGS --version"]
320 set tmp [lindex $output 1]
321 set version ""
322 regexp " \[0-9\]\[^ \t\n\r\]+" "$tmp" version
323 if ![is_remote host] {
324 clone_output "[which $GDB] version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
325 } else {
326 clone_output "$GDB on remote host version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
330 proc gdb_version { } {
331 return [default_gdb_version]
334 # gdb_unload -- unload a file if one is loaded
336 # Returns the same as gdb_test_multiple.
338 proc gdb_unload { {msg "file"} } {
339 global GDB
340 global gdb_prompt
341 return [gdb_test_multiple "file" $msg {
342 -re "A program is being debugged already.\r\nAre you sure you want to change the file. .y or n. $" {
343 send_gdb "y\n" answer
344 exp_continue
347 -re "No executable file now\\.\r\n" {
348 exp_continue
351 -re "Discard symbol table from `.*'. .y or n. $" {
352 send_gdb "y\n" answer
353 exp_continue
356 -re -wrap "No symbol file now\\." {
357 pass $gdb_test_name
362 # Many of the tests depend on setting breakpoints at various places and
363 # running until that breakpoint is reached. At times, we want to start
364 # with a clean-slate with respect to breakpoints, so this utility proc
365 # lets us do this without duplicating this code everywhere.
368 proc delete_breakpoints {} {
369 global gdb_prompt
371 # we need a larger timeout value here or this thing just confuses
372 # itself. May need a better implementation if possible. - guo
374 set timeout 100
376 set msg "delete all breakpoints, watchpoints, tracepoints, and catchpoints in delete_breakpoints"
377 set deleted 0
378 gdb_test_multiple "delete breakpoints" "$msg" {
379 -re "Delete all breakpoints, watchpoints, tracepoints, and catchpoints.*y or n.*$" {
380 send_gdb "y\n" answer
381 exp_continue
383 -re "$gdb_prompt $" {
384 set deleted 1
388 if {$deleted} {
389 # Confirm with "info breakpoints".
390 set deleted 0
391 set msg "info breakpoints"
392 gdb_test_multiple $msg $msg {
393 -re "No breakpoints, watchpoints, tracepoints, or catchpoints..*$gdb_prompt $" {
394 set deleted 1
396 -re "$gdb_prompt $" {
401 if {!$deleted} {
402 perror "breakpoints not deleted"
406 # Returns true iff the target supports using the "run" command.
408 proc target_can_use_run_cmd { {target_description ""} } {
409 if { $target_description == "" } {
410 set have_core 0
411 } elseif { $target_description == "core" } {
412 # We could try to figure this out by issuing an "info target" and
413 # checking for "Local core dump file:", but it would mean the proc
414 # would start requiring a current target. Also, uses while gdb
415 # produces non-standard output due to, say annotations would
416 # have to be moved around or eliminated, which would further limit
417 # usability.
418 set have_core 1
419 } else {
420 error "invalid argument: $target_description"
423 if [target_info exists use_gdb_stub] {
424 # In this case, when we connect, the inferior is already
425 # running.
426 return 0
429 if { $have_core && [target_info gdb_protocol] == "extended-remote" } {
430 # In this case, when we connect, the inferior is not running but
431 # cannot be made to run.
432 return 0
435 # Assume yes.
436 return 1
439 # Generic run command.
441 # Return 0 if we could start the program, -1 if we could not.
443 # The second pattern below matches up to the first newline *only*.
444 # Using ``.*$'' could swallow up output that we attempt to match
445 # elsewhere.
447 # INFERIOR_ARGS is passed as arguments to the start command, so may contain
448 # inferior arguments.
450 # N.B. This function does not wait for gdb to return to the prompt,
451 # that is the caller's responsibility.
453 proc gdb_run_cmd { {inferior_args {}} } {
454 global gdb_prompt use_gdb_stub
456 foreach command [gdb_init_commands] {
457 send_gdb "$command\n"
458 gdb_expect 30 {
459 -re "$gdb_prompt $" { }
460 default {
461 perror "gdb_init_command for target failed"
462 return
467 if $use_gdb_stub {
468 if [target_info exists gdb,do_reload_on_run] {
469 if { [gdb_reload $inferior_args] != 0 } {
470 return -1
472 send_gdb "continue\n"
473 gdb_expect 60 {
474 -re "Continu\[^\r\n\]*\[\r\n\]" {}
475 default {}
477 return 0
480 if [target_info exists gdb,start_symbol] {
481 set start [target_info gdb,start_symbol]
482 } else {
483 set start "start"
485 send_gdb "jump *$start\n"
486 set start_attempt 1
487 while { $start_attempt } {
488 # Cap (re)start attempts at three to ensure that this loop
489 # always eventually fails. Don't worry about trying to be
490 # clever and not send a command when it has failed.
491 if [expr $start_attempt > 3] {
492 perror "Jump to start() failed (retry count exceeded)"
493 return -1
495 set start_attempt [expr $start_attempt + 1]
496 gdb_expect 30 {
497 -re "Continuing at \[^\r\n\]*\[\r\n\]" {
498 set start_attempt 0
500 -re "No symbol \"_start\" in current.*$gdb_prompt $" {
501 perror "Can't find start symbol to run in gdb_run"
502 return -1
504 -re "No symbol \"start\" in current.*$gdb_prompt $" {
505 send_gdb "jump *_start\n"
507 -re "No symbol.*context.*$gdb_prompt $" {
508 set start_attempt 0
510 -re "Line.* Jump anyway.*y or n. $" {
511 send_gdb "y\n" answer
513 -re "The program is not being run.*$gdb_prompt $" {
514 if { [gdb_reload $inferior_args] != 0 } {
515 return -1
517 send_gdb "jump *$start\n"
519 timeout {
520 perror "Jump to start() failed (timeout)"
521 return -1
526 return 0
529 if [target_info exists gdb,do_reload_on_run] {
530 if { [gdb_reload $inferior_args] != 0 } {
531 return -1
534 send_gdb "run $inferior_args\n"
535 # This doesn't work quite right yet.
536 # Use -notransfer here so that test cases (like chng-sym.exp)
537 # may test for additional start-up messages.
538 gdb_expect 60 {
539 -re "The program .* has been started already.*y or n. $" {
540 send_gdb "y\n" answer
541 exp_continue
543 -notransfer -re "Starting program: \[^\r\n\]*" {}
544 -notransfer -re "$gdb_prompt $" {
545 # There is no more input expected.
547 -notransfer -re "A problem internal to GDB has been detected" {
548 # Let caller handle this.
552 return 0
555 # Generic start command. Return 0 if we could start the program, -1
556 # if we could not.
558 # INFERIOR_ARGS is passed as arguments to the start command, so may contain
559 # inferior arguments.
561 # N.B. This function does not wait for gdb to return to the prompt,
562 # that is the caller's responsibility.
564 proc gdb_start_cmd { {inferior_args {}} } {
565 global gdb_prompt use_gdb_stub
567 foreach command [gdb_init_commands] {
568 send_gdb "$command\n"
569 gdb_expect 30 {
570 -re "$gdb_prompt $" { }
571 default {
572 perror "gdb_init_command for target failed"
573 return -1
578 if $use_gdb_stub {
579 return -1
582 send_gdb "start $inferior_args\n"
583 # Use -notransfer here so that test cases (like chng-sym.exp)
584 # may test for additional start-up messages.
585 gdb_expect 60 {
586 -re "The program .* has been started already.*y or n. $" {
587 send_gdb "y\n" answer
588 exp_continue
590 -notransfer -re "Starting program: \[^\r\n\]*" {
591 return 0
593 -re "$gdb_prompt $" { }
595 return -1
598 # Generic starti command. Return 0 if we could start the program, -1
599 # if we could not.
601 # INFERIOR_ARGS is passed as arguments to the starti command, so may contain
602 # inferior arguments.
604 # N.B. This function does not wait for gdb to return to the prompt,
605 # that is the caller's responsibility.
607 proc gdb_starti_cmd { {inferior_args {}} } {
608 global gdb_prompt use_gdb_stub
610 foreach command [gdb_init_commands] {
611 send_gdb "$command\n"
612 gdb_expect 30 {
613 -re "$gdb_prompt $" { }
614 default {
615 perror "gdb_init_command for target failed"
616 return -1
621 if $use_gdb_stub {
622 return -1
625 send_gdb "starti $inferior_args\n"
626 gdb_expect 60 {
627 -re "The program .* has been started already.*y or n. $" {
628 send_gdb "y\n" answer
629 exp_continue
631 -re "Starting program: \[^\r\n\]*" {
632 return 0
635 return -1
638 # Set a breakpoint using LINESPEC.
640 # If there is an additional argument it is a list of options; the supported
641 # options are allow-pending, temporary, message, no-message and qualified.
643 # The result is 1 for success, 0 for failure.
645 # Note: The handling of message vs no-message is messed up, but it's based
646 # on historical usage. By default this function does not print passes,
647 # only fails.
648 # no-message: turns off printing of fails (and passes, but they're already off)
649 # message: turns on printing of passes (and fails, but they're already on)
651 proc gdb_breakpoint { linespec args } {
652 global gdb_prompt
653 global decimal
655 set pending_response n
656 if {[lsearch -exact $args allow-pending] != -1} {
657 set pending_response y
660 set break_command "break"
661 set break_message "Breakpoint"
662 if {[lsearch -exact $args temporary] != -1} {
663 set break_command "tbreak"
664 set break_message "Temporary breakpoint"
667 if {[lsearch -exact $args qualified] != -1} {
668 append break_command " -qualified"
671 set print_pass 0
672 set print_fail 1
673 set no_message_loc [lsearch -exact $args no-message]
674 set message_loc [lsearch -exact $args message]
675 # The last one to appear in args wins.
676 if { $no_message_loc > $message_loc } {
677 set print_fail 0
678 } elseif { $message_loc > $no_message_loc } {
679 set print_pass 1
682 set test_name "gdb_breakpoint: set breakpoint at $linespec"
683 # The first two regexps are what we get with -g, the third is without -g.
684 gdb_test_multiple "$break_command $linespec" $test_name {
685 -re "$break_message \[0-9\]* at .*: file .*, line $decimal.\r\n$gdb_prompt $" {}
686 -re "$break_message \[0-9\]*: file .*, line $decimal.\r\n$gdb_prompt $" {}
687 -re "$break_message \[0-9\]* at .*$gdb_prompt $" {}
688 -re "$break_message \[0-9\]* \\(.*\\) pending.*$gdb_prompt $" {
689 if {$pending_response == "n"} {
690 if { $print_fail } {
691 fail $gdb_test_name
693 return 0
696 -re "Make breakpoint pending.*y or \\\[n\\\]. $" {
697 send_gdb "$pending_response\n"
698 exp_continue
700 -re "$gdb_prompt $" {
701 if { $print_fail } {
702 fail $test_name
704 return 0
707 if { $print_pass } {
708 pass $test_name
710 return 1
713 # Set breakpoint at function and run gdb until it breaks there.
714 # Since this is the only breakpoint that will be set, if it stops
715 # at a breakpoint, we will assume it is the one we want. We can't
716 # just compare to "function" because it might be a fully qualified,
717 # single quoted C++ function specifier.
719 # If there are additional arguments, pass them to gdb_breakpoint.
720 # We recognize no-message/message ourselves.
722 # no-message is messed up here, like gdb_breakpoint: to preserve
723 # historical usage fails are always printed by default.
724 # no-message: turns off printing of fails (and passes, but they're already off)
725 # message: turns on printing of passes (and fails, but they're already on)
727 proc runto { linespec args } {
728 global gdb_prompt
729 global bkptno_numopt_re
730 global decimal
732 delete_breakpoints
734 set print_pass 0
735 set print_fail 1
736 set no_message_loc [lsearch -exact $args no-message]
737 set message_loc [lsearch -exact $args message]
738 # The last one to appear in args wins.
739 if { $no_message_loc > $message_loc } {
740 set print_fail 0
741 } elseif { $message_loc > $no_message_loc } {
742 set print_pass 1
745 set test_name "runto: run to $linespec"
747 if {![gdb_breakpoint $linespec {*}$args]} {
748 return 0
751 gdb_run_cmd
753 # the "at foo.c:36" output we get with -g.
754 # the "in func" output we get without -g.
755 gdb_expect 30 {
756 -re "(?:Break|Temporary break).* at .*:$decimal.*$gdb_prompt $" {
757 if { $print_pass } {
758 pass $test_name
760 return 1
762 -re "(?:Breakpoint|Temporary breakpoint) $bkptno_numopt_re, \[0-9xa-f\]* in .*$gdb_prompt $" {
763 if { $print_pass } {
764 pass $test_name
766 return 1
768 -re "The target does not support running in non-stop mode.\r\n$gdb_prompt $" {
769 if { $print_fail } {
770 unsupported "non-stop mode not supported"
772 return 0
774 -re ".*A problem internal to GDB has been detected" {
775 # Always emit a FAIL if we encounter an internal error: internal
776 # errors are never expected.
777 fail "$test_name (GDB internal error)"
778 gdb_internal_error_resync
779 return 0
781 -re "$gdb_prompt $" {
782 if { $print_fail } {
783 fail $test_name
785 return 0
787 eof {
788 if { $print_fail } {
789 fail "$test_name (eof)"
791 return 0
793 timeout {
794 if { $print_fail } {
795 fail "$test_name (timeout)"
797 return 0
800 if { $print_pass } {
801 pass $test_name
803 return 1
806 # Ask gdb to run until we hit a breakpoint at main.
808 # N.B. This function deletes all existing breakpoints.
809 # If you don't want that, use gdb_start_cmd.
811 proc runto_main { } {
812 return [runto main qualified]
815 ### Continue, and expect to hit a breakpoint.
816 ### Report a pass or fail, depending on whether it seems to have
817 ### worked. Use NAME as part of the test name; each call to
818 ### continue_to_breakpoint should use a NAME which is unique within
819 ### that test file.
820 proc gdb_continue_to_breakpoint {name {location_pattern .*}} {
821 global gdb_prompt
822 set full_name "continue to breakpoint: $name"
824 set kfail_pattern "Process record does not support instruction 0xfae64 at.*"
825 return [gdb_test_multiple "continue" $full_name {
826 -re "(?:Breakpoint|Temporary breakpoint) .* (at|in) $location_pattern\r\n$gdb_prompt $" {
827 pass $full_name
829 -re "(?:$kfail_pattern)\r\n$gdb_prompt $" {
830 kfail "gdb/25038" $full_name
836 # gdb_internal_error_resync:
838 # Answer the questions GDB asks after it reports an internal error
839 # until we get back to a GDB prompt. Decline to quit the debugging
840 # session, and decline to create a core file. Return non-zero if the
841 # resync succeeds.
843 # This procedure just answers whatever questions come up until it sees
844 # a GDB prompt; it doesn't require you to have matched the input up to
845 # any specific point. However, it only answers questions it sees in
846 # the output itself, so if you've matched a question, you had better
847 # answer it yourself before calling this.
849 # You can use this function thus:
851 # gdb_expect {
852 # ...
853 # -re ".*A problem internal to GDB has been detected" {
854 # gdb_internal_error_resync
856 # ...
859 proc gdb_internal_error_resync {} {
860 global gdb_prompt
862 verbose -log "Resyncing due to internal error."
864 set count 0
865 while {$count < 10} {
866 gdb_expect {
867 -re "Recursive internal problem\\." {
868 perror "Could not resync from internal error (recursive internal problem)"
869 return 0
871 -re "Quit this debugging session\\? \\(y or n\\) $" {
872 send_gdb "n\n" answer
873 incr count
875 -re "Create a core file of GDB\\? \\(y or n\\) $" {
876 send_gdb "n\n" answer
877 incr count
879 -re "$gdb_prompt $" {
880 # We're resynchronized.
881 return 1
883 timeout {
884 perror "Could not resync from internal error (timeout)"
885 return 0
887 eof {
888 perror "Could not resync from internal error (eof)"
889 return 0
893 perror "Could not resync from internal error (resync count exceeded)"
894 return 0
897 # Fill in the default prompt if PROMPT_REGEXP is empty.
899 # If WITH_ANCHOR is true and the default prompt is used, append a `$` at the end
900 # of the regexp, to anchor the match at the end of the buffer.
901 proc fill_in_default_prompt {prompt_regexp with_anchor} {
902 if { "$prompt_regexp" == "" } {
903 set prompt "$::gdb_prompt "
905 if { $with_anchor } {
906 append prompt "$"
909 return $prompt
911 return $prompt_regexp
914 # gdb_test_multiple COMMAND MESSAGE [ -prompt PROMPT_REGEXP] [ -lbl ]
915 # EXPECT_ARGUMENTS
916 # Send a command to gdb; test the result.
918 # COMMAND is the command to execute, send to GDB with send_gdb. If
919 # this is the null string no command is sent.
920 # MESSAGE is a message to be printed with the built-in failure patterns
921 # if one of them matches. If MESSAGE is empty COMMAND will be used.
922 # -prompt PROMPT_REGEXP specifies a regexp matching the expected prompt
923 # after the command output. If empty, defaults to "$gdb_prompt $".
924 # -lbl specifies that line-by-line matching will be used.
925 # EXPECT_ARGUMENTS will be fed to expect in addition to the standard
926 # patterns. Pattern elements will be evaluated in the caller's
927 # context; action elements will be executed in the caller's context.
928 # Unlike patterns for gdb_test, these patterns should generally include
929 # the final newline and prompt.
931 # Returns:
932 # 1 if the test failed, according to a built-in failure pattern
933 # 0 if only user-supplied patterns matched
934 # -1 if there was an internal error.
936 # You can use this function thus:
938 # gdb_test_multiple "print foo" "test foo" {
939 # -re "expected output 1" {
940 # pass "test foo"
942 # -re "expected output 2" {
943 # fail "test foo"
947 # Within action elements you can also make use of the variable
948 # gdb_test_name. This variable is setup automatically by
949 # gdb_test_multiple, and contains the value of MESSAGE. You can then
950 # write this, which is equivalent to the above:
952 # gdb_test_multiple "print foo" "test foo" {
953 # -re "expected output 1" {
954 # pass $gdb_test_name
956 # -re "expected output 2" {
957 # fail $gdb_test_name
961 # Like with "expect", you can also specify the spawn id to match with
962 # -i "$id". Interesting spawn ids are $inferior_spawn_id and
963 # $gdb_spawn_id. The former matches inferior I/O, while the latter
964 # matches GDB I/O. E.g.:
966 # send_inferior "hello\n"
967 # gdb_test_multiple "continue" "test echo" {
968 # -i "$inferior_spawn_id" -re "^hello\r\nhello\r\n$" {
969 # pass "got echo"
971 # -i "$gdb_spawn_id" -re "Breakpoint.*$gdb_prompt $" {
972 # fail "hit breakpoint"
976 # The standard patterns, such as "Inferior exited..." and "A problem
977 # ...", all being implicitly appended to that list. These are always
978 # expected from $gdb_spawn_id. IOW, callers do not need to worry
979 # about resetting "-i" back to $gdb_spawn_id explicitly.
981 # In EXPECT_ARGUMENTS we can use a -wrap pattern flag, that wraps the regexp
982 # pattern as gdb_test wraps its message argument.
983 # This allows us to rewrite:
984 # gdb_test <command> <pattern> <message>
985 # into:
986 # gdb_test_multiple <command> <message> {
987 # -re -wrap <pattern> {
988 # pass $gdb_test_name
991 # The special handling of '^' that is available in gdb_test is also
992 # supported in gdb_test_multiple when -wrap is used.
994 # In EXPECT_ARGUMENTS, a pattern flag -early can be used. It makes sure the
995 # pattern is inserted before any implicit pattern added by gdb_test_multiple.
996 # Using this pattern flag, we can f.i. setup a kfail for an assertion failure
997 # <assert> during gdb_continue_to_breakpoint by the rewrite:
998 # gdb_continue_to_breakpoint <msg> <pattern>
999 # into:
1000 # set breakpoint_pattern "(?:Breakpoint|Temporary breakpoint) .* (at|in)"
1001 # gdb_test_multiple "continue" "continue to breakpoint: <msg>" {
1002 # -early -re "internal-error: <assert>" {
1003 # setup_kfail gdb/nnnnn "*-*-*"
1004 # exp_continue
1006 # -re "$breakpoint_pattern <pattern>\r\n$gdb_prompt $" {
1007 # pass $gdb_test_name
1011 proc gdb_test_multiple { command message args } {
1012 global verbose use_gdb_stub
1013 global gdb_prompt pagination_prompt
1014 global GDB
1015 global gdb_spawn_id
1016 global inferior_exited_re
1017 upvar timeout timeout
1018 upvar expect_out expect_out
1019 global any_spawn_id
1021 set line_by_line 0
1022 set prompt_regexp ""
1023 for {set i 0} {$i < [llength $args]} {incr i} {
1024 set arg [lindex $args $i]
1025 if { $arg == "-prompt" } {
1026 incr i
1027 set prompt_regexp [lindex $args $i]
1028 } elseif { $arg == "-lbl" } {
1029 set line_by_line 1
1030 } else {
1031 set user_code $arg
1032 break
1035 if { [expr $i + 1] < [llength $args] } {
1036 error "Too many arguments to gdb_test_multiple"
1037 } elseif { ![info exists user_code] } {
1038 error "Too few arguments to gdb_test_multiple"
1041 set prompt_regexp [fill_in_default_prompt $prompt_regexp true]
1043 if { $message == "" } {
1044 set message $command
1047 if [string match "*\[\r\n\]" $command] {
1048 error "Invalid trailing newline in \"$command\" command"
1051 if [string match "*\[\003\004\]" $command] {
1052 error "Invalid trailing control code in \"$command\" command"
1055 if [string match "*\[\r\n\]*" $message] {
1056 error "Invalid newline in \"$message\" test"
1059 if {$use_gdb_stub
1060 && [regexp -nocase {^\s*(r|run|star|start|at|att|atta|attac|attach)\M} \
1061 $command]} {
1062 error "gdbserver does not support $command without extended-remote"
1065 # TCL/EXPECT WART ALERT
1066 # Expect does something very strange when it receives a single braced
1067 # argument. It splits it along word separators and performs substitutions.
1068 # This means that { "[ab]" } is evaluated as "[ab]", but { "\[ab\]" } is
1069 # evaluated as "\[ab\]". But that's not how TCL normally works; inside a
1070 # double-quoted list item, "\[ab\]" is just a long way of representing
1071 # "[ab]", because the backslashes will be removed by lindex.
1073 # Unfortunately, there appears to be no easy way to duplicate the splitting
1074 # that expect will do from within TCL. And many places make use of the
1075 # "\[0-9\]" construct, so we need to support that; and some places make use
1076 # of the "[func]" construct, so we need to support that too. In order to
1077 # get this right we have to substitute quoted list elements differently
1078 # from braced list elements.
1080 # We do this roughly the same way that Expect does it. We have to use two
1081 # lists, because if we leave unquoted newlines in the argument to uplevel
1082 # they'll be treated as command separators, and if we escape newlines
1083 # we mangle newlines inside of command blocks. This assumes that the
1084 # input doesn't contain a pattern which contains actual embedded newlines
1085 # at this point!
1087 regsub -all {\n} ${user_code} { } subst_code
1088 set subst_code [uplevel list $subst_code]
1090 set processed_code ""
1091 set early_processed_code ""
1092 # The variable current_list holds the name of the currently processed
1093 # list, either processed_code or early_processed_code.
1094 set current_list "processed_code"
1095 set patterns ""
1096 set expecting_action 0
1097 set expecting_arg 0
1098 set wrap_pattern 0
1099 foreach item $user_code subst_item $subst_code {
1100 if { $item == "-n" || $item == "-notransfer" || $item == "-nocase" } {
1101 lappend $current_list $item
1102 continue
1104 if { $item == "-indices" || $item == "-re" || $item == "-ex" } {
1105 lappend $current_list $item
1106 continue
1108 if { $item == "-early" } {
1109 set current_list "early_processed_code"
1110 continue
1112 if { $item == "-timeout" || $item == "-i" } {
1113 set expecting_arg 1
1114 lappend $current_list $item
1115 continue
1117 if { $item == "-wrap" } {
1118 set wrap_pattern 1
1119 continue
1121 if { $expecting_arg } {
1122 set expecting_arg 0
1123 lappend $current_list $subst_item
1124 continue
1126 if { $expecting_action } {
1127 lappend $current_list "uplevel [list $item]"
1128 set expecting_action 0
1129 # Cosmetic, no effect on the list.
1130 append $current_list "\n"
1131 # End the effect of -early, it only applies to one action.
1132 set current_list "processed_code"
1133 continue
1135 set expecting_action 1
1136 if { $wrap_pattern } {
1137 # Wrap subst_item as is done for the gdb_test PATTERN argument.
1138 if {[string range $subst_item 0 0] eq "^"} {
1139 if {$command ne ""} {
1140 set command_regex [string_to_regexp $command]
1141 set subst_item [string range $subst_item 1 end]
1142 if {[string length "$subst_item"] > 0} {
1143 # We have an output pattern (other than the '^'),
1144 # add a newline at the start, this will eventually
1145 # sit between the command and the output pattern.
1146 set subst_item "\r\n${subst_item}"
1148 set subst_item "^${command_regex}${subst_item}"
1151 lappend $current_list \
1152 "(?:$subst_item)\r\n$prompt_regexp"
1153 set wrap_pattern 0
1154 } else {
1155 lappend $current_list $subst_item
1157 if {$patterns != ""} {
1158 append patterns "; "
1160 append patterns "\"$subst_item\""
1163 # Also purely cosmetic.
1164 regsub -all {\r} $patterns {\\r} patterns
1165 regsub -all {\n} $patterns {\\n} patterns
1167 if {$verbose > 2} {
1168 send_user "Sending \"$command\" to gdb\n"
1169 send_user "Looking to match \"$patterns\"\n"
1170 send_user "Message is \"$message\"\n"
1173 set result -1
1174 set string "${command}\n"
1175 if { $command != "" } {
1176 set multi_line_re "\[\r\n\] *>"
1177 while { "$string" != "" } {
1178 set foo [string first "\n" "$string"]
1179 set len [string length "$string"]
1180 if { $foo < [expr $len - 1] } {
1181 set str [string range "$string" 0 $foo]
1182 if { [send_gdb "$str"] != "" } {
1183 verbose -log "Couldn't send $command to GDB."
1184 unresolved $message
1185 return -1
1187 # since we're checking if each line of the multi-line
1188 # command are 'accepted' by GDB here,
1189 # we need to set -notransfer expect option so that
1190 # command output is not lost for pattern matching
1191 # - guo
1192 gdb_expect 2 {
1193 -notransfer -re "$multi_line_re$" { verbose "partial: match" 3 }
1194 timeout { verbose "partial: timeout" 3 }
1196 set string [string range "$string" [expr $foo + 1] end]
1197 set multi_line_re "$multi_line_re.*\[\r\n\] *>"
1198 } else {
1199 break
1202 if { "$string" != "" } {
1203 if { [send_gdb "$string"] != "" } {
1204 verbose -log "Couldn't send $command to GDB."
1205 unresolved $message
1206 return -1
1211 set code $early_processed_code
1212 append code {
1213 -re ".*A problem internal to GDB has been detected" {
1214 fail "$message (GDB internal error)"
1215 gdb_internal_error_resync
1216 set result -1
1218 -re "\\*\\*\\* DOSEXIT code.*" {
1219 if { $message != "" } {
1220 fail "$message"
1222 set result -1
1224 -re "Corrupted shared library list.*$prompt_regexp" {
1225 fail "$message (shared library list corrupted)"
1226 set result -1
1228 -re "Invalid cast\.\r\nwarning: Probes-based dynamic linker interface failed.*$prompt_regexp" {
1229 fail "$message (probes interface failure)"
1230 set result -1
1233 append code $processed_code
1235 # Reset the spawn id, in case the processed code used -i.
1236 append code {
1237 -i "$gdb_spawn_id"
1240 append code {
1241 -re "Ending remote debugging.*$prompt_regexp" {
1242 if {![isnative]} {
1243 warning "Can`t communicate to remote target."
1245 gdb_exit
1246 gdb_start
1247 set result -1
1249 -re "Undefined\[a-z\]* command:.*$prompt_regexp" {
1250 perror "Undefined command \"$command\"."
1251 fail "$message"
1252 set result 1
1254 -re "Ambiguous command.*$prompt_regexp" {
1255 perror "\"$command\" is not a unique command name."
1256 fail "$message"
1257 set result 1
1259 -re "$inferior_exited_re with code \[0-9\]+.*$prompt_regexp" {
1260 if {![string match "" $message]} {
1261 set errmsg "$message (the program exited)"
1262 } else {
1263 set errmsg "$command (the program exited)"
1265 fail "$errmsg"
1266 set result -1
1268 -re "$inferior_exited_re normally.*$prompt_regexp" {
1269 if {![string match "" $message]} {
1270 set errmsg "$message (the program exited)"
1271 } else {
1272 set errmsg "$command (the program exited)"
1274 fail "$errmsg"
1275 set result -1
1277 -re "The program is not being run.*$prompt_regexp" {
1278 if {![string match "" $message]} {
1279 set errmsg "$message (the program is no longer running)"
1280 } else {
1281 set errmsg "$command (the program is no longer running)"
1283 fail "$errmsg"
1284 set result -1
1286 -re "\r\n$prompt_regexp" {
1287 if {![string match "" $message]} {
1288 fail "$message"
1290 set result 1
1292 -re "$pagination_prompt" {
1293 send_gdb "\n"
1294 perror "Window too small."
1295 fail "$message"
1296 set result -1
1298 -re "\\((y or n|y or \\\[n\\\]|\\\[y\\\] or n)\\) " {
1299 send_gdb "n\n" answer
1300 gdb_expect -re "$prompt_regexp"
1301 fail "$message (got interactive prompt)"
1302 set result -1
1304 -re "\\\[0\\\] cancel\r\n\\\[1\\\] all.*\r\n> $" {
1305 send_gdb "0\n"
1306 gdb_expect -re "$prompt_regexp"
1307 fail "$message (got breakpoint menu)"
1308 set result -1
1311 -i $gdb_spawn_id
1312 eof {
1313 perror "GDB process no longer exists"
1314 set wait_status [wait -i $gdb_spawn_id]
1315 verbose -log "GDB process exited with wait status $wait_status"
1316 if { $message != "" } {
1317 fail "$message"
1319 return -1
1323 if {$line_by_line} {
1324 append code {
1325 -re "\r\n\[^\r\n\]*(?=\r\n)" {
1326 exp_continue
1331 # Now patterns that apply to any spawn id specified.
1332 append code {
1333 -i $any_spawn_id
1334 eof {
1335 perror "Process no longer exists"
1336 if { $message != "" } {
1337 fail "$message"
1339 return -1
1341 full_buffer {
1342 perror "internal buffer is full."
1343 fail "$message"
1344 set result -1
1346 timeout {
1347 if {![string match "" $message]} {
1348 fail "$message (timeout)"
1350 set result 1
1354 # remote_expect calls the eof section if there is an error on the
1355 # expect call. We already have eof sections above, and we don't
1356 # want them to get called in that situation. Since the last eof
1357 # section becomes the error section, here we define another eof
1358 # section, but with an empty spawn_id list, so that it won't ever
1359 # match.
1360 append code {
1361 -i "" eof {
1362 # This comment is here because the eof section must not be
1363 # the empty string, otherwise remote_expect won't realize
1364 # it exists.
1368 # Create gdb_test_name in the parent scope. If this variable
1369 # already exists, which it might if we have nested calls to
1370 # gdb_test_multiple, then preserve the old value, otherwise,
1371 # create a new variable in the parent scope.
1372 upvar gdb_test_name gdb_test_name
1373 if { [info exists gdb_test_name] } {
1374 set gdb_test_name_old "$gdb_test_name"
1376 set gdb_test_name "$message"
1378 set result 0
1379 set code [catch {gdb_expect $code} string]
1381 # Clean up the gdb_test_name variable. If we had a
1382 # previous value then restore it, otherwise, delete the variable
1383 # from the parent scope.
1384 if { [info exists gdb_test_name_old] } {
1385 set gdb_test_name "$gdb_test_name_old"
1386 } else {
1387 unset gdb_test_name
1390 if {$code == 1} {
1391 global errorInfo errorCode
1392 return -code error -errorinfo $errorInfo -errorcode $errorCode $string
1393 } elseif {$code > 1} {
1394 return -code $code $string
1396 return $result
1399 # Usage: gdb_test_multiline NAME INPUT RESULT {INPUT RESULT} ...
1400 # Run a test named NAME, consisting of multiple lines of input.
1401 # After each input line INPUT, search for result line RESULT.
1402 # Succeed if all results are seen; fail otherwise.
1404 proc gdb_test_multiline { name args } {
1405 global gdb_prompt
1406 set inputnr 0
1407 foreach {input result} $args {
1408 incr inputnr
1409 if {[gdb_test_multiple $input "$name: input $inputnr: $input" {
1410 -re "($result)\r\n($gdb_prompt | *>)$" {
1411 pass $gdb_test_name
1413 }]} {
1414 return 1
1417 return 0
1421 # gdb_test [-prompt PROMPT_REGEXP] [-lbl]
1422 # COMMAND [PATTERN] [MESSAGE] [QUESTION RESPONSE]
1423 # Send a command to gdb; test the result.
1425 # COMMAND is the command to execute, send to GDB with send_gdb. If
1426 # this is the null string no command is sent.
1427 # PATTERN is the pattern to match for a PASS, and must NOT include the
1428 # \r\n sequence immediately before the gdb prompt (see -nonl below).
1429 # This argument may be omitted to just match the prompt, ignoring
1430 # whatever output precedes it. If PATTERN starts with '^' then
1431 # PATTERN will be anchored such that it should match all output from
1432 # COMMAND.
1433 # MESSAGE is an optional message to be printed. If this is
1434 # omitted, then the pass/fail messages use the command string as the
1435 # message. (If this is the empty string, then sometimes we don't
1436 # call pass or fail at all; I don't understand this at all.)
1437 # QUESTION is a question GDB should ask in response to COMMAND, like
1438 # "are you sure?" If this is specified, the test fails if GDB
1439 # doesn't print the question.
1440 # RESPONSE is the response to send when QUESTION appears.
1442 # -prompt PROMPT_REGEXP specifies a regexp matching the expected prompt
1443 # after the command output. If empty, defaults to "$gdb_prompt $".
1444 # -no-prompt-anchor specifies that if the default prompt regexp is used, it
1445 # should not be anchored at the end of the buffer. This means that the
1446 # pattern can match even if there is stuff output after the prompt. Does not
1447 # have any effect if -prompt is specified.
1448 # -lbl specifies that line-by-line matching will be used.
1449 # -nopass specifies that a PASS should not be issued.
1450 # -nonl specifies that no \r\n sequence is expected between PATTERN
1451 # and the gdb prompt.
1453 # Returns:
1454 # 1 if the test failed,
1455 # 0 if the test passes,
1456 # -1 if there was an internal error.
1458 proc gdb_test { args } {
1459 global gdb_prompt
1460 upvar timeout timeout
1462 parse_args {
1463 {prompt ""}
1464 {no-prompt-anchor}
1465 {lbl}
1466 {nopass}
1467 {nonl}
1470 lassign $args command pattern message question response
1472 # Can't have a question without a response.
1473 if { $question != "" && $response == "" || [llength $args] > 5 } {
1474 error "Unexpected arguments: $args"
1477 if { $message == "" } {
1478 set message $command
1481 set prompt [fill_in_default_prompt $prompt [expr !${no-prompt-anchor}]]
1482 set nl [expr ${nonl} ? {""} : {"\r\n"}]
1484 set saw_question 0
1486 # If the pattern starts with a '^' then we want to match all the
1487 # output from COMMAND. To support this, here we inject an
1488 # additional pattern that matches the command immediately after
1489 # the '^'.
1490 if {[string range $pattern 0 0] eq "^"} {
1491 if {$command ne ""} {
1492 set command_regex [string_to_regexp $command]
1493 set pattern [string range $pattern 1 end]
1494 if {[string length "$pattern"] > 0} {
1495 # We have an output pattern (other than the '^'), add a
1496 # newline at the start, this will eventually sit between the
1497 # command and the output pattern.
1498 set pattern "\r\n$pattern"
1500 set pattern "^${command_regex}${pattern}"
1504 set user_code {}
1505 lappend user_code {
1506 -re "(?:$pattern)$nl$prompt" {
1507 if { $question != "" & !$saw_question} {
1508 fail $message
1509 } elseif {!$nopass} {
1510 pass $message
1515 if { $question != "" } {
1516 lappend user_code {
1517 -re "$question$" {
1518 set saw_question 1
1519 send_gdb "$response\n"
1520 exp_continue
1525 set user_code [join $user_code]
1527 set opts {}
1528 lappend opts "-prompt" "$prompt"
1529 if {$lbl} {
1530 lappend opts "-lbl"
1533 return [gdb_test_multiple $command $message {*}$opts $user_code]
1536 # Return 1 if python version used is at least MAJOR.MINOR
1537 proc python_version_at_least { major minor } {
1538 set python_script {print (sys.version_info\[0\], sys.version_info\[1\])}
1540 set res [remote_exec host $::GDB \
1541 "$::INTERNAL_GDBFLAGS -batch -ex \"python $python_script\""]
1542 if { [lindex $res 0] != 0 } {
1543 error "Couldn't get python version"
1546 set python_version [lindex $res 1]
1547 set python_version [string trim $python_version]
1549 regexp {^([0-9]+) ([0-9]+)$} $python_version \
1550 dummy python_version_major python_version_minor
1552 return [version_compare [list $major $minor] \
1553 <= [list $python_version_major $python_version_minor]]
1556 # Return 1 if tcl version used is at least MAJOR.MINOR
1557 proc tcl_version_at_least { major minor } {
1558 global tcl_version
1559 regexp {^([0-9]+)\.([0-9]+)$} $tcl_version \
1560 dummy tcl_version_major tcl_version_minor
1561 return [version_compare [list $major $minor] \
1562 <= [list $tcl_version_major $tcl_version_minor]]
1565 if { [tcl_version_at_least 8 5] == 0 } {
1566 # lrepeat was added in tcl 8.5. Only add if missing.
1567 proc lrepeat { n element } {
1568 if { [string is integer -strict $n] == 0 } {
1569 error "expected integer but got \"$n\""
1571 if { $n < 0 } {
1572 error "bad count \"$n\": must be integer >= 0"
1574 set res [list]
1575 for {set i 0} {$i < $n} {incr i} {
1576 lappend res $element
1578 return $res
1582 if { [tcl_version_at_least 8 6] == 0 } {
1583 # lmap was added in tcl 8.6. Only add if missing.
1585 # Note that we only implement the simple variant for now.
1586 proc lmap { varname list body } {
1587 set res {}
1588 foreach val $list {
1589 uplevel 1 "set $varname $val"
1590 lappend res [uplevel 1 $body]
1593 return $res
1597 # gdb_test_no_output [-prompt PROMPT_REGEXP] [-nopass] COMMAND [MESSAGE]
1598 # Send a command to GDB and verify that this command generated no output.
1600 # See gdb_test for a description of the -prompt, -no-prompt-anchor, -nopass,
1601 # COMMAND, and MESSAGE parameters.
1603 # Returns:
1604 # 1 if the test failed,
1605 # 0 if the test passes,
1606 # -1 if there was an internal error.
1608 proc gdb_test_no_output { args } {
1609 global gdb_prompt
1611 parse_args {
1612 {prompt ""}
1613 {no-prompt-anchor}
1614 {nopass}
1617 lassign $args command message
1619 set prompt [fill_in_default_prompt $prompt [expr !${no-prompt-anchor}]]
1621 set command_regex [string_to_regexp $command]
1622 return [gdb_test_multiple $command $message -prompt $prompt {
1623 -re "^$command_regex\r\n$prompt" {
1624 if {!$nopass} {
1625 pass $gdb_test_name
1631 # Send a command and then wait for a sequence of outputs.
1632 # This is useful when the sequence is long and contains ".*", a single
1633 # regexp to match the entire output can get a timeout much easier.
1635 # COMMAND is the command to execute, send to GDB with send_gdb. If
1636 # this is the null string no command is sent.
1637 # TEST_NAME is passed to pass/fail. COMMAND is used if TEST_NAME is "".
1638 # EXPECTED_OUTPUT_LIST is a list of regexps of expected output, which are
1639 # processed in order, and all must be present in the output.
1641 # The -prompt switch can be used to override the prompt expected at the end of
1642 # the output sequence.
1644 # It is unnecessary to specify ".*" at the beginning or end of any regexp,
1645 # there is an implicit ".*" between each element of EXPECTED_OUTPUT_LIST.
1646 # There is also an implicit ".*" between the last regexp and the gdb prompt.
1648 # Like gdb_test and gdb_test_multiple, the output is expected to end with the
1649 # gdb prompt, which must not be specified in EXPECTED_OUTPUT_LIST.
1651 # Returns:
1652 # 1 if the test failed,
1653 # 0 if the test passes,
1654 # -1 if there was an internal error.
1656 proc gdb_test_sequence { args } {
1657 global gdb_prompt
1659 parse_args {{prompt ""}}
1661 if { $prompt == "" } {
1662 set prompt "$gdb_prompt $"
1665 if { [llength $args] != 3 } {
1666 error "Unexpected # of arguments, expecting: COMMAND TEST_NAME EXPECTED_OUTPUT_LIST"
1669 lassign $args command test_name expected_output_list
1671 if { $test_name == "" } {
1672 set test_name $command
1675 lappend expected_output_list ""; # implicit ".*" before gdb prompt
1677 if { $command != "" } {
1678 send_gdb "$command\n"
1681 return [gdb_expect_list $test_name $prompt $expected_output_list]
1685 # Match output of COMMAND using RE. Read output line-by-line.
1686 # Report pass/fail with MESSAGE.
1687 # For a command foo with output:
1688 # (gdb) foo^M
1689 # <line1>^M
1690 # <line2>^M
1691 # (gdb)
1692 # the portion matched using RE is:
1693 # '<line1>^M
1694 # <line2>^M
1697 # Optionally, additional -re-not <regexp> arguments can be specified, to
1698 # ensure that a regexp is not match by the COMMAND output.
1699 # Such an additional argument generates an additional PASS/FAIL of the form:
1700 # PASS: test-case.exp: $message: pattern not matched: <regexp>
1702 proc gdb_test_lines { command message re args } {
1703 set re_not [list]
1705 for {set i 0} {$i < [llength $args]} {incr i} {
1706 set arg [lindex $args $i]
1707 if { $arg == "-re-not" } {
1708 incr i
1709 if { [llength $args] == $i } {
1710 error "Missing argument for -re-not"
1711 break
1713 set arg [lindex $args $i]
1714 lappend re_not $arg
1715 } else {
1716 error "Unhandled argument: $arg"
1720 if { $message == ""} {
1721 set message $command
1724 set lines ""
1725 gdb_test_multiple $command $message {
1726 -re "\r\n(\[^\r\n\]*)(?=\r\n)" {
1727 set line $expect_out(1,string)
1728 if { $lines eq "" } {
1729 append lines "$line"
1730 } else {
1731 append lines "\r\n$line"
1733 exp_continue
1735 -re -wrap "" {
1736 append lines "\r\n"
1740 gdb_assert { [regexp $re $lines] } $message
1742 foreach re $re_not {
1743 gdb_assert { ![regexp $re $lines] } "$message: pattern not matched: $re"
1747 # Test that a command gives an error. For pass or fail, return
1748 # a 1 to indicate that more tests can proceed. However a timeout
1749 # is a serious error, generates a special fail message, and causes
1750 # a 0 to be returned to indicate that more tests are likely to fail
1751 # as well.
1753 proc test_print_reject { args } {
1754 global gdb_prompt
1755 global verbose
1757 if {[llength $args] == 2} {
1758 set expectthis [lindex $args 1]
1759 } else {
1760 set expectthis "should never match this bogus string"
1762 set sendthis [lindex $args 0]
1763 if {$verbose > 2} {
1764 send_user "Sending \"$sendthis\" to gdb\n"
1765 send_user "Looking to match \"$expectthis\"\n"
1767 send_gdb "$sendthis\n"
1768 #FIXME: Should add timeout as parameter.
1769 gdb_expect {
1770 -re "A .* in expression.*\\.*$gdb_prompt $" {
1771 pass "reject $sendthis"
1772 return 1
1774 -re "Invalid syntax in expression.*$gdb_prompt $" {
1775 pass "reject $sendthis"
1776 return 1
1778 -re "Junk after end of expression.*$gdb_prompt $" {
1779 pass "reject $sendthis"
1780 return 1
1782 -re "Invalid number.*$gdb_prompt $" {
1783 pass "reject $sendthis"
1784 return 1
1786 -re "Invalid character constant.*$gdb_prompt $" {
1787 pass "reject $sendthis"
1788 return 1
1790 -re "No symbol table is loaded.*$gdb_prompt $" {
1791 pass "reject $sendthis"
1792 return 1
1794 -re "No symbol .* in current context.*$gdb_prompt $" {
1795 pass "reject $sendthis"
1796 return 1
1798 -re "Unmatched single quote.*$gdb_prompt $" {
1799 pass "reject $sendthis"
1800 return 1
1802 -re "A character constant must contain at least one character.*$gdb_prompt $" {
1803 pass "reject $sendthis"
1804 return 1
1806 -re "$expectthis.*$gdb_prompt $" {
1807 pass "reject $sendthis"
1808 return 1
1810 -re ".*$gdb_prompt $" {
1811 fail "reject $sendthis"
1812 return 1
1814 default {
1815 fail "reject $sendthis (eof or timeout)"
1816 return 0
1822 # Same as gdb_test, but the second parameter is not a regexp,
1823 # but a string that must match exactly.
1825 proc gdb_test_exact { args } {
1826 upvar timeout timeout
1828 set command [lindex $args 0]
1830 # This applies a special meaning to a null string pattern. Without
1831 # this, "$pattern\r\n$gdb_prompt $" will match anything, including error
1832 # messages from commands that should have no output except a new
1833 # prompt. With this, only results of a null string will match a null
1834 # string pattern.
1836 set pattern [lindex $args 1]
1837 if [string match $pattern ""] {
1838 set pattern [string_to_regexp [lindex $args 0]]
1839 } else {
1840 set pattern [string_to_regexp [lindex $args 1]]
1843 # It is most natural to write the pattern argument with only
1844 # embedded \n's, especially if you are trying to avoid Tcl quoting
1845 # problems. But gdb_expect really wants to see \r\n in patterns. So
1846 # transform the pattern here. First transform \r\n back to \n, in
1847 # case some users of gdb_test_exact already do the right thing.
1848 regsub -all "\r\n" $pattern "\n" pattern
1849 regsub -all "\n" $pattern "\r\n" pattern
1850 if {[llength $args] == 3} {
1851 set message [lindex $args 2]
1852 return [gdb_test $command $pattern $message]
1855 return [gdb_test $command $pattern]
1858 # Wrapper around gdb_test_multiple that looks for a list of expected
1859 # output elements, but which can appear in any order.
1860 # CMD is the gdb command.
1861 # NAME is the name of the test.
1862 # ELM_FIND_REGEXP specifies how to partition the output into elements to
1863 # compare.
1864 # ELM_EXTRACT_REGEXP specifies the part of ELM_FIND_REGEXP to compare.
1865 # RESULT_MATCH_LIST is a list of exact matches for each expected element.
1866 # All elements of RESULT_MATCH_LIST must appear for the test to pass.
1868 # A typical use of ELM_FIND_REGEXP/ELM_EXTRACT_REGEXP is to extract one line
1869 # of text per element and then strip trailing \r\n's.
1870 # Example:
1871 # gdb_test_list_exact "foo" "bar" \
1872 # "\[^\r\n\]+\[\r\n\]+" \
1873 # "\[^\r\n\]+" \
1874 # { \
1875 # {expected result 1} \
1876 # {expected result 2} \
1879 proc gdb_test_list_exact { cmd name elm_find_regexp elm_extract_regexp result_match_list } {
1880 global gdb_prompt
1882 set matches [lsort $result_match_list]
1883 set seen {}
1884 gdb_test_multiple $cmd $name {
1885 "$cmd\[\r\n\]" { exp_continue }
1886 -re $elm_find_regexp {
1887 set str $expect_out(0,string)
1888 verbose -log "seen: $str" 3
1889 regexp -- $elm_extract_regexp $str elm_seen
1890 verbose -log "extracted: $elm_seen" 3
1891 lappend seen $elm_seen
1892 exp_continue
1894 -re "$gdb_prompt $" {
1895 set failed ""
1896 foreach got [lsort $seen] have $matches {
1897 if {![string equal $got $have]} {
1898 set failed $have
1899 break
1902 if {[string length $failed] != 0} {
1903 fail "$name ($failed not found)"
1904 } else {
1905 pass $name
1911 # gdb_test_stdio COMMAND INFERIOR_PATTERN GDB_PATTERN MESSAGE
1912 # Send a command to gdb; expect inferior and gdb output.
1914 # See gdb_test_multiple for a description of the COMMAND and MESSAGE
1915 # parameters.
1917 # INFERIOR_PATTERN is the pattern to match against inferior output.
1919 # GDB_PATTERN is the pattern to match against gdb output, and must NOT
1920 # include the \r\n sequence immediately before the gdb prompt, nor the
1921 # prompt. The default is empty.
1923 # Both inferior and gdb patterns must match for a PASS.
1925 # If MESSAGE is omitted, then COMMAND will be used as the message.
1927 # Returns:
1928 # 1 if the test failed,
1929 # 0 if the test passes,
1930 # -1 if there was an internal error.
1933 proc gdb_test_stdio {command inferior_pattern {gdb_pattern ""} {message ""}} {
1934 global inferior_spawn_id gdb_spawn_id
1935 global gdb_prompt
1937 if {$message == ""} {
1938 set message $command
1941 set inferior_matched 0
1942 set gdb_matched 0
1944 # Use an indirect spawn id list, and remove the inferior spawn id
1945 # from the expected output as soon as it matches, in case
1946 # $inferior_pattern happens to be a prefix of the resulting full
1947 # gdb pattern below (e.g., "\r\n").
1948 global gdb_test_stdio_spawn_id_list
1949 set gdb_test_stdio_spawn_id_list "$inferior_spawn_id"
1951 # Note that if $inferior_spawn_id and $gdb_spawn_id are different,
1952 # then we may see gdb's output arriving before the inferior's
1953 # output.
1954 set res [gdb_test_multiple $command $message {
1955 -i gdb_test_stdio_spawn_id_list -re "$inferior_pattern" {
1956 set inferior_matched 1
1957 if {!$gdb_matched} {
1958 set gdb_test_stdio_spawn_id_list ""
1959 exp_continue
1962 -i $gdb_spawn_id -re "$gdb_pattern\r\n$gdb_prompt $" {
1963 set gdb_matched 1
1964 if {!$inferior_matched} {
1965 exp_continue
1969 if {$res == 0} {
1970 pass $message
1971 } else {
1972 verbose -log "inferior_matched=$inferior_matched, gdb_matched=$gdb_matched"
1974 return $res
1977 # Wrapper around gdb_test_multiple to be used when testing expression
1978 # evaluation while 'set debug expression 1' is in effect.
1979 # Looks for some patterns that indicates the expression was rejected.
1981 # CMD is the command to execute, which should include an expression
1982 # that GDB will need to parse.
1984 # OUTPUT is the expected output pattern.
1986 # TESTNAME is the name to be used for the test, defaults to CMD if not
1987 # given.
1988 proc gdb_test_debug_expr { cmd output {testname "" }} {
1989 global gdb_prompt
1991 if { ${testname} == "" } {
1992 set testname $cmd
1995 gdb_test_multiple $cmd $testname {
1996 -re ".*Invalid expression.*\r\n$gdb_prompt $" {
1997 fail $gdb_test_name
1999 -re ".*\[\r\n\]$output\r\n$gdb_prompt $" {
2000 pass $gdb_test_name
2005 # get_print_expr_at_depths EXP OUTPUTS
2007 # Used for testing 'set print max-depth'. Prints the expression EXP
2008 # with 'set print max-depth' set to various depths. OUTPUTS is a list
2009 # of `n` different patterns to match at each of the depths from 0 to
2010 # (`n` - 1).
2012 # This proc does one final check with the max-depth set to 'unlimited'
2013 # which is tested against the last pattern in the OUTPUTS list. The
2014 # OUTPUTS list is therefore required to match every depth from 0 to a
2015 # depth where the whole of EXP is printed with no ellipsis.
2017 # This proc leaves the 'set print max-depth' set to 'unlimited'.
2018 proc gdb_print_expr_at_depths {exp outputs} {
2019 for { set depth 0 } { $depth <= [llength $outputs] } { incr depth } {
2020 if { $depth == [llength $outputs] } {
2021 set expected_result [lindex $outputs [expr [llength $outputs] - 1]]
2022 set depth_string "unlimited"
2023 } else {
2024 set expected_result [lindex $outputs $depth]
2025 set depth_string $depth
2028 with_test_prefix "exp='$exp': depth=${depth_string}" {
2029 gdb_test_no_output "set print max-depth ${depth_string}"
2030 gdb_test "p $exp" "$expected_result"
2037 # Issue a PASS and return true if evaluating CONDITION in the caller's
2038 # frame returns true, and issue a FAIL and return false otherwise.
2039 # MESSAGE is the pass/fail message to be printed. If MESSAGE is
2040 # omitted or is empty, then the pass/fail messages use the condition
2041 # string as the message.
2043 proc gdb_assert { condition {message ""} } {
2044 if { $message == ""} {
2045 set message $condition
2048 set code [catch {uplevel 1 [list expr $condition]} res]
2049 if {$code == 1} {
2050 # If code is 1 (TCL_ERROR), it means evaluation failed and res contains
2051 # an error message. Print the error message, and set res to 0 since we
2052 # want to return a boolean.
2053 warning "While evaluating expression in gdb_assert: $res"
2054 unresolved $message
2055 set res 0
2056 } elseif { !$res } {
2057 fail $message
2058 } else {
2059 pass $message
2061 return $res
2064 proc gdb_reinitialize_dir { subdir } {
2065 global gdb_prompt
2067 if [is_remote host] {
2068 return ""
2070 send_gdb "dir\n"
2071 gdb_expect 60 {
2072 -re "Reinitialize source path to empty.*y or n. " {
2073 send_gdb "y\n" answer
2074 gdb_expect 60 {
2075 -re "Source directories searched.*$gdb_prompt $" {
2076 send_gdb "dir $subdir\n"
2077 gdb_expect 60 {
2078 -re "Source directories searched.*$gdb_prompt $" {
2079 verbose "Dir set to $subdir"
2081 -re "$gdb_prompt $" {
2082 perror "Dir \"$subdir\" failed."
2086 -re "$gdb_prompt $" {
2087 perror "Dir \"$subdir\" failed."
2091 -re "$gdb_prompt $" {
2092 perror "Dir \"$subdir\" failed."
2098 # gdb_exit -- exit the GDB, killing the target program if necessary
2100 proc default_gdb_exit {} {
2101 global GDB
2102 global INTERNAL_GDBFLAGS GDBFLAGS
2103 global gdb_spawn_id inferior_spawn_id
2104 global inotify_log_file
2106 if ![info exists gdb_spawn_id] {
2107 return
2110 verbose "Quitting $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
2112 if {[info exists inotify_log_file] && [file exists $inotify_log_file]} {
2113 set fd [open $inotify_log_file]
2114 set data [read -nonewline $fd]
2115 close $fd
2117 if {[string compare $data ""] != 0} {
2118 warning "parallel-unsafe file creations noticed"
2120 # Clear the log.
2121 set fd [open $inotify_log_file w]
2122 close $fd
2126 if { [is_remote host] && [board_info host exists fileid] } {
2127 send_gdb "quit\n"
2128 gdb_expect 10 {
2129 -re "y or n" {
2130 send_gdb "y\n" answer
2131 exp_continue
2133 -re "DOSEXIT code" { }
2134 default { }
2138 if ![is_remote host] {
2139 remote_close host
2141 unset gdb_spawn_id
2142 unset ::gdb_tty_name
2143 unset inferior_spawn_id
2146 # Load a file into the debugger.
2147 # The return value is 0 for success, -1 for failure.
2149 # ARG is the file name.
2150 # KILL_FLAG, if given, indicates whether a "kill" command should be used.
2152 # This procedure also set the global variable GDB_FILE_CMD_DEBUG_INFO
2153 # to one of these values:
2155 # debug file was loaded successfully and has debug information
2156 # nodebug file was loaded successfully and has no debug information
2157 # lzma file was loaded, .gnu_debugdata found, but no LZMA support
2158 # compiled in
2159 # fail file was not loaded
2161 # This procedure also set the global variable GDB_FILE_CMD_MSG to the
2162 # output of the file command in case of success.
2164 # I tried returning this information as part of the return value,
2165 # but ran into a mess because of the many re-implementations of
2166 # gdb_load in config/*.exp.
2168 # TODO: gdb.base/sepdebug.exp and gdb.stabs/weird.exp might be able to use
2169 # this if they can get more information set.
2171 proc gdb_file_cmd { arg {kill_flag 1} } {
2172 global gdb_prompt
2173 global GDB
2174 global last_loaded_file
2176 # GCC for Windows target may create foo.exe given "-o foo".
2177 if { ![file exists $arg] && [file exists "$arg.exe"] } {
2178 set arg "$arg.exe"
2181 # Save this for the benefit of gdbserver-support.exp.
2182 set last_loaded_file $arg
2184 # Set whether debug info was found.
2185 # Default to "fail".
2186 global gdb_file_cmd_debug_info gdb_file_cmd_msg
2187 set gdb_file_cmd_debug_info "fail"
2189 if [is_remote host] {
2190 set arg [remote_download host $arg]
2191 if { $arg == "" } {
2192 perror "download failed"
2193 return -1
2197 # The file command used to kill the remote target. For the benefit
2198 # of the testsuite, preserve this behavior. Mark as optional so it doesn't
2199 # get written to the stdin log.
2200 if {$kill_flag} {
2201 send_gdb "kill\n" optional
2202 gdb_expect 120 {
2203 -re "Kill the program being debugged. .y or n. $" {
2204 send_gdb "y\n" answer
2205 verbose "\t\tKilling previous program being debugged"
2206 exp_continue
2208 -re "$gdb_prompt $" {
2209 # OK.
2214 send_gdb "file $arg\n"
2215 set new_symbol_table 0
2216 set basename [file tail $arg]
2217 gdb_expect 120 {
2218 -re "(Reading symbols from.*LZMA support was disabled.*$gdb_prompt $)" {
2219 verbose "\t\tLoaded $arg into $GDB; .gnu_debugdata found but no LZMA available"
2220 set gdb_file_cmd_msg $expect_out(1,string)
2221 set gdb_file_cmd_debug_info "lzma"
2222 return 0
2224 -re "(Reading symbols from.*No debugging symbols found.*$gdb_prompt $)" {
2225 verbose "\t\tLoaded $arg into $GDB with no debugging symbols"
2226 set gdb_file_cmd_msg $expect_out(1,string)
2227 set gdb_file_cmd_debug_info "nodebug"
2228 return 0
2230 -re "(Reading symbols from.*$gdb_prompt $)" {
2231 verbose "\t\tLoaded $arg into $GDB"
2232 set gdb_file_cmd_msg $expect_out(1,string)
2233 set gdb_file_cmd_debug_info "debug"
2234 return 0
2236 -re "Load new symbol table from \".*\".*y or n. $" {
2237 if { $new_symbol_table > 0 } {
2238 perror [join [list "Couldn't load $basename,"
2239 "interactive prompt loop detected."]]
2240 return -1
2242 send_gdb "y\n" answer
2243 incr new_symbol_table
2244 set suffix "-- with new symbol table"
2245 set arg "$arg $suffix"
2246 set basename "$basename $suffix"
2247 exp_continue
2249 -re "No such file or directory.*$gdb_prompt $" {
2250 perror "($basename) No such file or directory"
2251 return -1
2253 -re "A problem internal to GDB has been detected" {
2254 perror "Couldn't load $basename into GDB (GDB internal error)."
2255 gdb_internal_error_resync
2256 return -1
2258 -re "$gdb_prompt $" {
2259 perror "Couldn't load $basename into GDB."
2260 return -1
2262 timeout {
2263 perror "Couldn't load $basename into GDB (timeout)."
2264 return -1
2266 eof {
2267 # This is an attempt to detect a core dump, but seems not to
2268 # work. Perhaps we need to match .* followed by eof, in which
2269 # gdb_expect does not seem to have a way to do that.
2270 perror "Couldn't load $basename into GDB (eof)."
2271 return -1
2276 # The expect "spawn" function puts the tty name into the spawn_out
2277 # array; but dejagnu doesn't export this globally. So, we have to
2278 # wrap spawn with our own function and poke in the built-in spawn
2279 # so that we can capture this value.
2281 # If available, the TTY name is saved to the LAST_SPAWN_TTY_NAME global.
2282 # Otherwise, LAST_SPAWN_TTY_NAME is unset.
2284 proc spawn_capture_tty_name { args } {
2285 set result [uplevel builtin_spawn $args]
2286 upvar spawn_out spawn_out
2287 if { [info exists spawn_out(slave,name)] } {
2288 set ::last_spawn_tty_name $spawn_out(slave,name)
2289 } else {
2290 # If a process is spawned as part of a pipe line (e.g. passing
2291 # -leaveopen to the spawn proc) then the spawned process is no
2292 # assigned a tty and spawn_out(slave,name) will not be set.
2293 # In that case we want to ensure that last_spawn_tty_name is
2294 # not set.
2296 # If the previous process spawned was also not assigned a tty
2297 # (e.g. multiple processed chained in a pipeline) then
2298 # last_spawn_tty_name will already be unset, so, if we don't
2299 # use -nocomplain here we would otherwise get an error.
2300 unset -nocomplain ::last_spawn_tty_name
2302 return $result
2305 rename spawn builtin_spawn
2306 rename spawn_capture_tty_name spawn
2308 # Default gdb_spawn procedure.
2310 proc default_gdb_spawn { } {
2311 global use_gdb_stub
2312 global GDB
2313 global INTERNAL_GDBFLAGS GDBFLAGS
2314 global gdb_spawn_id
2316 # Set the default value, it may be overriden later by specific testfile.
2318 # Use `set_board_info use_gdb_stub' for the board file to flag the inferior
2319 # is already started after connecting and run/attach are not supported.
2320 # This is used for the "remote" protocol. After GDB starts you should
2321 # check global $use_gdb_stub instead of the board as the testfile may force
2322 # a specific different target protocol itself.
2323 set use_gdb_stub [target_info exists use_gdb_stub]
2325 verbose "Spawning $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
2326 gdb_write_cmd_file "$GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
2328 if [info exists gdb_spawn_id] {
2329 return 0
2332 if ![is_remote host] {
2333 if {[which $GDB] == 0} {
2334 perror "$GDB does not exist."
2335 exit 1
2339 # Put GDBFLAGS last so that tests can put "--args ..." in it.
2340 set res [remote_spawn host "$GDB $INTERNAL_GDBFLAGS [host_info gdb_opts] $GDBFLAGS"]
2341 if { $res < 0 || $res == "" } {
2342 perror "Spawning $GDB failed."
2343 return 1
2346 set gdb_spawn_id $res
2347 set ::gdb_tty_name $::last_spawn_tty_name
2348 return 0
2351 # Default gdb_start procedure.
2353 proc default_gdb_start { } {
2354 global gdb_prompt
2355 global gdb_spawn_id
2356 global inferior_spawn_id
2358 if [info exists gdb_spawn_id] {
2359 return 0
2362 # Keep track of the number of times GDB has been launched.
2363 global gdb_instances
2364 incr gdb_instances
2366 gdb_stdin_log_init
2368 set res [gdb_spawn]
2369 if { $res != 0} {
2370 return $res
2373 # Default to assuming inferior I/O is done on GDB's terminal.
2374 if {![info exists inferior_spawn_id]} {
2375 set inferior_spawn_id $gdb_spawn_id
2378 # When running over NFS, particularly if running many simultaneous
2379 # tests on different hosts all using the same server, things can
2380 # get really slow. Give gdb at least 3 minutes to start up.
2381 gdb_expect 360 {
2382 -re "\[\r\n\]$gdb_prompt $" {
2383 verbose "GDB initialized."
2385 -re "\[\r\n\]\033\\\[.2004h$gdb_prompt $" {
2386 # This special case detects what happens when GDB is
2387 # started with bracketed paste mode enabled. This mode is
2388 # usually forced off (see setting of INPUTRC in
2389 # default_gdb_init), but for at least one test we turn
2390 # bracketed paste mode back on, and then start GDB. In
2391 # that case, this case is hit.
2392 verbose "GDB initialized."
2394 -re "^$gdb_prompt $" {
2395 # Output with -q.
2396 verbose "GDB initialized."
2398 -re "^\033\\\[.2004h$gdb_prompt $" {
2399 # Output with -q, and bracketed paste mode enabled, see above.
2400 verbose "GDB initialized."
2402 -re "$gdb_prompt $" {
2403 perror "GDB never initialized."
2404 unset gdb_spawn_id
2405 return -1
2407 timeout {
2408 perror "(timeout) GDB never initialized after 10 seconds."
2409 remote_close host
2410 unset gdb_spawn_id
2411 return -1
2413 eof {
2414 perror "(eof) GDB never initialized."
2415 unset gdb_spawn_id
2416 return -1
2420 # force the height to "unlimited", so no pagers get used
2422 send_gdb "set height 0\n"
2423 gdb_expect 10 {
2424 -re "$gdb_prompt $" {
2425 verbose "Setting height to 0." 2
2427 timeout {
2428 warning "Couldn't set the height to 0"
2431 # force the width to "unlimited", so no wraparound occurs
2432 send_gdb "set width 0\n"
2433 gdb_expect 10 {
2434 -re "$gdb_prompt $" {
2435 verbose "Setting width to 0." 2
2437 timeout {
2438 warning "Couldn't set the width to 0."
2442 gdb_debug_init
2443 return 0
2446 # Utility procedure to give user control of the gdb prompt in a script. It is
2447 # meant to be used for debugging test cases, and should not be left in the
2448 # test cases code.
2450 proc gdb_interact { } {
2451 global gdb_spawn_id
2452 set spawn_id $gdb_spawn_id
2454 send_user "+------------------------------------------+\n"
2455 send_user "| Script interrupted, you can now interact |\n"
2456 send_user "| with by gdb. Type >>> to continue. |\n"
2457 send_user "+------------------------------------------+\n"
2459 interact {
2460 ">>>" return
2464 # Examine the output of compilation to determine whether compilation
2465 # failed or not. If it failed determine whether it is due to missing
2466 # compiler or due to compiler error. Report pass, fail or unsupported
2467 # as appropriate.
2469 proc gdb_compile_test {src output} {
2470 set msg "compilation [file tail $src]"
2472 if { $output == "" } {
2473 pass $msg
2474 return
2477 if { [regexp {^[a-zA-Z_0-9]+: Can't find [^ ]+\.$} $output]
2478 || [regexp {.*: command not found[\r|\n]*$} $output]
2479 || [regexp {.*: [^\r\n]*compiler not installed[^\r\n]*[\r|\n]*$} $output] } {
2480 unsupported "$msg (missing compiler)"
2481 return
2484 set gcc_re ".*: error: unrecognized command line option "
2485 set clang_re ".*: error: unsupported option "
2486 if { [regexp "(?:$gcc_re|$clang_re)(\[^ \t;\r\n\]*)" $output dummy option]
2487 && $option != "" } {
2488 unsupported "$msg (unsupported option $option)"
2489 return
2492 # Unclassified compilation failure, be more verbose.
2493 verbose -log "compilation failed: $output" 2
2494 fail "$msg"
2497 # Return a 1 for configurations for which we want to try to test C++.
2499 proc allow_cplus_tests {} {
2500 if { [istarget "h8300-*-*"] } {
2501 return 0
2504 # The C++ IO streams are too large for HC11/HC12 and are thus not
2505 # available. The gdb C++ tests use them and don't compile.
2506 if { [istarget "m6811-*-*"] } {
2507 return 0
2509 if { [istarget "m6812-*-*"] } {
2510 return 0
2512 return 1
2515 # Return a 0 for configurations which are missing either C++ or the STL.
2517 proc allow_stl_tests {} {
2518 return [allow_cplus_tests]
2521 # Return a 1 if I want to try to test FORTRAN.
2523 proc allow_fortran_tests {} {
2524 return 1
2527 # Return a 1 if I want to try to test ada.
2529 proc allow_ada_tests {} {
2530 if { [is_remote host] } {
2531 # Currently gdb_ada_compile doesn't support remote host.
2532 return 0
2534 return 1
2537 # Return a 1 if I want to try to test GO.
2539 proc allow_go_tests {} {
2540 return 1
2543 # Return a 1 if I even want to try to test D.
2545 proc allow_d_tests {} {
2546 return 1
2549 # Return a 1 if we can compile source files in LANG.
2551 gdb_caching_proc can_compile { lang } {
2553 if { $lang == "d" } {
2554 set src { void main() {} }
2555 return [gdb_can_simple_compile can_compile_$lang $src executable {d}]
2558 if { $lang == "rust" } {
2559 if { ![isnative] } {
2560 return 0
2563 if { [is_remote host] } {
2564 # Proc find_rustc returns "" for remote host.
2565 return 0
2568 # The rust compiler does not support "-m32", skip.
2569 global board board_info
2570 set board [target_info name]
2571 if {[board_info $board exists multilib_flags]} {
2572 foreach flag [board_info $board multilib_flags] {
2573 if { $flag == "-m32" } {
2574 return 0
2579 set src { fn main() {} }
2580 # Drop nowarnings in default_compile_flags, it translates to -w which
2581 # rustc doesn't support.
2582 return [gdb_can_simple_compile can_compile_$lang $src executable \
2583 {rust} {debug quiet}]
2586 error "can_compile doesn't support lang: $lang"
2589 # Return 1 to try Rust tests, 0 to skip them.
2590 proc allow_rust_tests {} {
2591 return 1
2594 # Return a 1 for configurations that support Python scripting.
2596 gdb_caching_proc allow_python_tests {} {
2597 set output [remote_exec host $::GDB "$::INTERNAL_GDBFLAGS --configuration"]
2598 return [expr {[string first "--with-python" $output] != -1}]
2601 # Return a 1 for configurations that use system readline rather than the
2602 # in-repo copy.
2604 gdb_caching_proc with_system_readline {} {
2605 set output [remote_exec host $::GDB "$::INTERNAL_GDBFLAGS --configuration"]
2606 return [expr {[string first "--with-system-readline" $output] != -1}]
2609 gdb_caching_proc allow_dap_tests {} {
2610 if { ![allow_python_tests] } {
2611 return 0
2614 # The dap code uses module typing, available starting python 3.5.
2615 if { ![python_version_at_least 3 5] } {
2616 return 0
2619 # ton.tcl uses "string is entier", supported starting tcl 8.6.
2620 if { ![tcl_version_at_least 8 6] } {
2621 return 0
2624 # With set auto-connect-native-target off, we run into:
2625 # +++ run
2626 # Traceback (most recent call last):
2627 # File "startup.py", line <n>, in exec_and_log
2628 # output = gdb.execute(cmd, from_tty=True, to_string=True)
2629 # gdb.error: Don't know how to run. Try "help target".
2630 set gdb_flags [join $::GDBFLAGS $::INTERNAL_GDBFLAGS]
2631 return [expr {[string first "set auto-connect-native-target off" $gdb_flags] == -1}]
2634 # Return a 1 if we should run shared library tests.
2636 proc allow_shlib_tests {} {
2637 # Run the shared library tests on native systems.
2638 if {[isnative]} {
2639 return 1
2642 # An abbreviated list of remote targets where we should be able to
2643 # run shared library tests.
2644 if {([istarget *-*-linux*]
2645 || [istarget *-*-*bsd*]
2646 || [istarget *-*-solaris2*]
2647 || [istarget *-*-mingw*]
2648 || [istarget *-*-cygwin*]
2649 || [istarget *-*-pe*])} {
2650 return 1
2653 return 0
2656 # Return 1 if we should run dlmopen tests, 0 if we should not.
2658 gdb_caching_proc allow_dlmopen_tests {} {
2659 global srcdir subdir gdb_prompt inferior_exited_re
2661 # We need shared library support.
2662 if { ![allow_shlib_tests] } {
2663 return 0
2666 set me "allow_dlmopen_tests"
2667 set lib {
2668 int foo (void) {
2669 return 42;
2672 set src {
2673 #define _GNU_SOURCE
2674 #include <dlfcn.h>
2675 #include <link.h>
2676 #include <stdio.h>
2677 #include <errno.h>
2679 int main (void) {
2680 struct r_debug *r_debug;
2681 ElfW(Dyn) *dyn;
2682 void *handle;
2684 /* The version is kept at 1 until we create a new namespace. */
2685 handle = dlmopen (LM_ID_NEWLM, DSO_NAME, RTLD_LAZY | RTLD_LOCAL);
2686 if (!handle) {
2687 printf ("dlmopen failed: %s.\n", dlerror ());
2688 return 1;
2691 r_debug = 0;
2692 /* Taken from /usr/include/link.h. */
2693 for (dyn = _DYNAMIC; dyn->d_tag != DT_NULL; ++dyn)
2694 if (dyn->d_tag == DT_DEBUG)
2695 r_debug = (struct r_debug *) dyn->d_un.d_ptr;
2697 if (!r_debug) {
2698 printf ("r_debug not found.\n");
2699 return 1;
2701 if (r_debug->r_version < 2) {
2702 printf ("dlmopen debug not supported.\n");
2703 return 1;
2705 printf ("dlmopen debug supported.\n");
2706 return 0;
2710 set libsrc [standard_temp_file "libfoo.c"]
2711 set libout [standard_temp_file "libfoo.so"]
2712 gdb_produce_source $libsrc $lib
2714 if { [gdb_compile_shlib $libsrc $libout {debug}] != "" } {
2715 verbose -log "failed to build library"
2716 return 0
2718 if { ![gdb_simple_compile $me $src executable \
2719 [list shlib_load debug \
2720 additional_flags=-DDSO_NAME=\"$libout\"]] } {
2721 verbose -log "failed to build executable"
2722 return 0
2725 gdb_exit
2726 gdb_start
2727 gdb_reinitialize_dir $srcdir/$subdir
2728 gdb_load $obj
2730 if { [gdb_run_cmd] != 0 } {
2731 verbose -log "failed to start skip test"
2732 return 0
2734 gdb_expect {
2735 -re "$inferior_exited_re normally.*${gdb_prompt} $" {
2736 set allow_dlmopen_tests 1
2738 -re "$inferior_exited_re with code.*${gdb_prompt} $" {
2739 set allow_dlmopen_tests 0
2741 default {
2742 warning "\n$me: default case taken"
2743 set allow_dlmopen_tests 0
2746 gdb_exit
2748 verbose "$me: returning $allow_dlmopen_tests" 2
2749 return $allow_dlmopen_tests
2752 # Return 1 if we should allow TUI-related tests.
2754 gdb_caching_proc allow_tui_tests {} {
2755 set output [remote_exec host $::GDB "$::INTERNAL_GDBFLAGS --configuration"]
2756 return [expr {[string first "--enable-tui" $output] != -1}]
2759 # Test files shall make sure all the test result lines in gdb.sum are
2760 # unique in a test run, so that comparing the gdb.sum files of two
2761 # test runs gives correct results. Test files that exercise
2762 # variations of the same tests more than once, shall prefix the
2763 # different test invocations with different identifying strings in
2764 # order to make them unique.
2766 # About test prefixes:
2768 # $pf_prefix is the string that dejagnu prints after the result (FAIL,
2769 # PASS, etc.), and before the test message/name in gdb.sum. E.g., the
2770 # underlined substring in
2772 # PASS: gdb.base/mytest.exp: some test
2773 # ^^^^^^^^^^^^^^^^^^^^
2775 # is $pf_prefix.
2777 # The easiest way to adjust the test prefix is to append a test
2778 # variation prefix to the $pf_prefix, using the with_test_prefix
2779 # procedure. E.g.,
2781 # proc do_tests {} {
2782 # gdb_test ... ... "test foo"
2783 # gdb_test ... ... "test bar"
2785 # with_test_prefix "subvariation a" {
2786 # gdb_test ... ... "test x"
2789 # with_test_prefix "subvariation b" {
2790 # gdb_test ... ... "test x"
2794 # with_test_prefix "variation1" {
2795 # ...do setup for variation 1...
2796 # do_tests
2799 # with_test_prefix "variation2" {
2800 # ...do setup for variation 2...
2801 # do_tests
2804 # Results in:
2806 # PASS: gdb.base/mytest.exp: variation1: test foo
2807 # PASS: gdb.base/mytest.exp: variation1: test bar
2808 # PASS: gdb.base/mytest.exp: variation1: subvariation a: test x
2809 # PASS: gdb.base/mytest.exp: variation1: subvariation b: test x
2810 # PASS: gdb.base/mytest.exp: variation2: test foo
2811 # PASS: gdb.base/mytest.exp: variation2: test bar
2812 # PASS: gdb.base/mytest.exp: variation2: subvariation a: test x
2813 # PASS: gdb.base/mytest.exp: variation2: subvariation b: test x
2815 # If for some reason more flexibility is necessary, one can also
2816 # manipulate the pf_prefix global directly, treating it as a string.
2817 # E.g.,
2819 # global pf_prefix
2820 # set saved_pf_prefix
2821 # append pf_prefix "${foo}: bar"
2822 # ... actual tests ...
2823 # set pf_prefix $saved_pf_prefix
2826 # Run BODY in the context of the caller, with the current test prefix
2827 # (pf_prefix) appended with one space, then PREFIX, and then a colon.
2828 # Returns the result of BODY.
2830 proc with_test_prefix { prefix body } {
2831 global pf_prefix
2833 set saved $pf_prefix
2834 append pf_prefix " " $prefix ":"
2835 set code [catch {uplevel 1 $body} result]
2836 set pf_prefix $saved
2838 if {$code == 1} {
2839 global errorInfo errorCode
2840 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2841 } else {
2842 return -code $code $result
2846 # Wrapper for foreach that calls with_test_prefix on each iteration,
2847 # including the iterator's name and current value in the prefix.
2849 proc foreach_with_prefix {var list body} {
2850 upvar 1 $var myvar
2851 foreach myvar $list {
2852 with_test_prefix "$var=$myvar" {
2853 set code [catch {uplevel 1 $body} result]
2856 if {$code == 1} {
2857 global errorInfo errorCode
2858 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2859 } elseif {$code == 3} {
2860 break
2861 } elseif {$code == 2} {
2862 return -code $code $result
2867 # Like TCL's native proc, but defines a procedure that wraps its body
2868 # within 'with_test_prefix "$proc_name" { ... }'.
2869 proc proc_with_prefix {name arguments body} {
2870 # Define the advertised proc.
2871 proc $name $arguments [list with_test_prefix $name $body]
2874 # Return an id corresponding to the test prefix stored in $pf_prefix, which
2875 # is more suitable for use in a file name.
2876 # F.i., for a pf_prefix:
2877 # gdb.dwarf2/dw2-lines.exp: \
2878 # cv=5: cdw=64: lv=5: ldw=64: string_form=line_strp:
2879 # return an id:
2880 # cv-5-cdw-32-lv-5-ldw-64-string_form-line_strp
2882 proc prefix_id {} {
2883 global pf_prefix
2884 set id $pf_prefix
2886 # Strip ".exp: " prefix.
2887 set id [regsub {.*\.exp: } $id {}]
2889 # Strip colon suffix.
2890 set id [regsub {:$} $id {}]
2892 # Strip spaces.
2893 set id [regsub -all { } $id {}]
2895 # Replace colons, equal signs.
2896 set id [regsub -all \[:=\] $id -]
2898 return $id
2901 # Run BODY in the context of the caller. After BODY is run, the variables
2902 # listed in VARS will be reset to the values they had before BODY was run.
2904 # This is useful for providing a scope in which it is safe to temporarily
2905 # modify global variables, e.g.
2907 # global INTERNAL_GDBFLAGS
2908 # global env
2910 # set foo GDBHISTSIZE
2912 # save_vars { INTERNAL_GDBFLAGS env($foo) env(HOME) } {
2913 # append INTERNAL_GDBFLAGS " -nx"
2914 # unset -nocomplain env(GDBHISTSIZE)
2915 # gdb_start
2916 # gdb_test ...
2919 # Here, although INTERNAL_GDBFLAGS, env(GDBHISTSIZE) and env(HOME) may be
2920 # modified inside BODY, this proc guarantees that the modifications will be
2921 # undone after BODY finishes executing.
2923 proc save_vars { vars body } {
2924 array set saved_scalars { }
2925 array set saved_arrays { }
2926 set unset_vars { }
2928 foreach var $vars {
2929 # First evaluate VAR in the context of the caller in case the variable
2930 # name may be a not-yet-interpolated string like env($foo)
2931 set var [uplevel 1 list $var]
2933 if [uplevel 1 [list info exists $var]] {
2934 if [uplevel 1 [list array exists $var]] {
2935 set saved_arrays($var) [uplevel 1 [list array get $var]]
2936 } else {
2937 set saved_scalars($var) [uplevel 1 [list set $var]]
2939 } else {
2940 lappend unset_vars $var
2944 set code [catch {uplevel 1 $body} result]
2946 foreach {var value} [array get saved_scalars] {
2947 uplevel 1 [list set $var $value]
2950 foreach {var value} [array get saved_arrays] {
2951 uplevel 1 [list unset $var]
2952 uplevel 1 [list array set $var $value]
2955 foreach var $unset_vars {
2956 uplevel 1 [list unset -nocomplain $var]
2959 if {$code == 1} {
2960 global errorInfo errorCode
2961 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2962 } else {
2963 return -code $code $result
2967 # As save_vars, but for variables stored in the board_info for the
2968 # target board.
2970 # Usage example:
2972 # save_target_board_info { multilib_flags } {
2973 # global board
2974 # set board [target_info name]
2975 # unset_board_info multilib_flags
2976 # set_board_info multilib_flags "$multilib_flags"
2977 # ...
2980 proc save_target_board_info { vars body } {
2981 global board board_info
2982 set board [target_info name]
2984 array set saved_target_board_info { }
2985 set unset_target_board_info { }
2987 foreach var $vars {
2988 if { [info exists board_info($board,$var)] } {
2989 set saved_target_board_info($var) [board_info $board $var]
2990 } else {
2991 lappend unset_target_board_info $var
2995 set code [catch {uplevel 1 $body} result]
2997 foreach {var value} [array get saved_target_board_info] {
2998 unset_board_info $var
2999 set_board_info $var $value
3002 foreach var $unset_target_board_info {
3003 unset_board_info $var
3006 if {$code == 1} {
3007 global errorInfo errorCode
3008 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3009 } else {
3010 return -code $code $result
3014 # Run tests in BODY with the current working directory (CWD) set to
3015 # DIR. When BODY is finished, restore the original CWD. Return the
3016 # result of BODY.
3018 # This procedure doesn't check if DIR is a valid directory, so you
3019 # have to make sure of that.
3021 proc with_cwd { dir body } {
3022 set saved_dir [pwd]
3023 verbose -log "Switching to directory $dir (saved CWD: $saved_dir)."
3024 cd $dir
3026 set code [catch {uplevel 1 $body} result]
3028 verbose -log "Switching back to $saved_dir."
3029 cd $saved_dir
3031 if {$code == 1} {
3032 global errorInfo errorCode
3033 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3034 } else {
3035 return -code $code $result
3039 # Use GDB's 'cd' command to switch to DIR. Return true if the switch
3040 # was successful, otherwise, call perror and return false.
3042 proc gdb_cd { dir } {
3043 set new_dir ""
3044 gdb_test_multiple "cd $dir" "" {
3045 -re "^cd \[^\r\n\]+\r\n" {
3046 exp_continue
3049 -re "^Working directory (\[^\r\n\]+)\\.\r\n" {
3050 set new_dir $expect_out(1,string)
3051 exp_continue
3054 -re "^$::gdb_prompt $" {
3055 if { $new_dir == "" || $new_dir != $dir } {
3056 perror "failed to switch to $dir"
3057 return false
3062 return true
3065 # Use GDB's 'pwd' command to figure out the current working directory.
3066 # Return the directory as a string. If we can't figure out the
3067 # current working directory, then call perror, and return the empty
3068 # string.
3070 proc gdb_pwd { } {
3071 set dir ""
3072 gdb_test_multiple "pwd" "" {
3073 -re "^pwd\r\n" {
3074 exp_continue
3077 -re "^Working directory (\[^\r\n\]+)\\.\r\n" {
3078 set dir $expect_out(1,string)
3079 exp_continue
3082 -re "^$::gdb_prompt $" {
3086 if { $dir == "" } {
3087 perror "failed to read GDB's current working directory"
3090 return $dir
3093 # Similar to the with_cwd proc, this proc runs BODY with the current
3094 # working directory changed to CWD.
3096 # Unlike with_cwd, the directory change here is done within GDB
3097 # itself, so GDB must be running before this proc is called.
3099 proc with_gdb_cwd { dir body } {
3100 set saved_dir [gdb_pwd]
3101 if { $saved_dir == "" } {
3102 return
3105 verbose -log "Switching to directory $dir (saved CWD: $saved_dir)."
3106 if ![gdb_cd $dir] {
3107 return
3110 set code [catch {uplevel 1 $body} result]
3112 verbose -log "Switching back to $saved_dir."
3113 if ![gdb_cd $saved_dir] {
3114 return
3117 # Check that GDB is still alive. If GDB crashed in the above code
3118 # then any corefile will have been left in DIR, not the root
3119 # testsuite directory. As a result the corefile will not be
3120 # brought to the users attention. Instead, if GDB crashed, then
3121 # this check should cause a FAIL, which should be enough to alert
3122 # the user.
3123 set saw_result false
3124 gdb_test_multiple "p 123" "" {
3125 -re "p 123\r\n" {
3126 exp_continue
3129 -re "^\\\$$::decimal = 123\r\n" {
3130 set saw_result true
3131 exp_continue
3134 -re "^$::gdb_prompt $" {
3135 if { !$saw_result } {
3136 fail "check gdb is alive in with_gdb_cwd"
3141 if {$code == 1} {
3142 global errorInfo errorCode
3143 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3144 } else {
3145 return -code $code $result
3149 # Run tests in BODY with GDB prompt and variable $gdb_prompt set to
3150 # PROMPT. When BODY is finished, restore GDB prompt and variable
3151 # $gdb_prompt.
3152 # Returns the result of BODY.
3154 # Notes:
3156 # 1) If you want to use, for example, "(foo)" as the prompt you must pass it
3157 # as "(foo)", and not the regexp form "\(foo\)" (expressed as "\\(foo\\)" in
3158 # TCL). PROMPT is internally converted to a suitable regexp for matching.
3159 # We do the conversion from "(foo)" to "\(foo\)" here for a few reasons:
3160 # a) It's more intuitive for callers to pass the plain text form.
3161 # b) We need two forms of the prompt:
3162 # - a regexp to use in output matching,
3163 # - a value to pass to the "set prompt" command.
3164 # c) It's easier to convert the plain text form to its regexp form.
3166 # 2) Don't add a trailing space, we do that here.
3168 proc with_gdb_prompt { prompt body } {
3169 global gdb_prompt
3171 # Convert "(foo)" to "\(foo\)".
3172 # We don't use string_to_regexp because while it works today it's not
3173 # clear it will work tomorrow: the value we need must work as both a
3174 # regexp *and* as the argument to the "set prompt" command, at least until
3175 # we start recording both forms separately instead of just $gdb_prompt.
3176 # The testsuite is pretty-much hardwired to interpret $gdb_prompt as the
3177 # regexp form.
3178 regsub -all {[]*+.|()^$\[\\]} $prompt {\\&} prompt
3180 set saved $gdb_prompt
3182 verbose -log "Setting gdb prompt to \"$prompt \"."
3183 set gdb_prompt $prompt
3184 gdb_test_no_output "set prompt $prompt " ""
3186 set code [catch {uplevel 1 $body} result]
3188 verbose -log "Restoring gdb prompt to \"$saved \"."
3189 set gdb_prompt $saved
3190 gdb_test_no_output "set prompt $saved " ""
3192 if {$code == 1} {
3193 global errorInfo errorCode
3194 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3195 } else {
3196 return -code $code $result
3200 # Run tests in BODY with target-charset setting to TARGET_CHARSET. When
3201 # BODY is finished, restore target-charset.
3203 proc with_target_charset { target_charset body } {
3204 global gdb_prompt
3206 set saved ""
3207 gdb_test_multiple "show target-charset" "" {
3208 -re "The target character set is \".*; currently (.*)\"\..*$gdb_prompt " {
3209 set saved $expect_out(1,string)
3211 -re "The target character set is \"(.*)\".*$gdb_prompt " {
3212 set saved $expect_out(1,string)
3214 -re ".*$gdb_prompt " {
3215 fail "get target-charset"
3219 gdb_test_no_output -nopass "set target-charset $target_charset"
3221 set code [catch {uplevel 1 $body} result]
3223 gdb_test_no_output -nopass "set target-charset $saved"
3225 if {$code == 1} {
3226 global errorInfo errorCode
3227 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3228 } else {
3229 return -code $code $result
3233 # Run tests in BODY with max-value-size set to SIZE. When BODY is
3234 # finished restore max-value-size.
3236 proc with_max_value_size { size body } {
3237 global gdb_prompt
3239 set saved ""
3240 gdb_test_multiple "show max-value-size" "" {
3241 -re -wrap "Maximum value size is ($::decimal) bytes\\." {
3242 set saved $expect_out(1,string)
3244 -re ".*$gdb_prompt " {
3245 fail "get max-value-size"
3249 gdb_test_no_output -nopass "set max-value-size $size"
3251 set code [catch {uplevel 1 $body} result]
3253 gdb_test_no_output -nopass "set max-value-size $saved"
3255 if {$code == 1} {
3256 global errorInfo errorCode
3257 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3258 } else {
3259 return -code $code $result
3263 # Switch the default spawn id to SPAWN_ID, so that gdb_test,
3264 # mi_gdb_test etc. default to using it.
3266 proc switch_gdb_spawn_id {spawn_id} {
3267 global gdb_spawn_id
3268 global board board_info
3270 set gdb_spawn_id $spawn_id
3271 set board [host_info name]
3272 set board_info($board,fileid) $spawn_id
3275 # Clear the default spawn id.
3277 proc clear_gdb_spawn_id {} {
3278 global gdb_spawn_id
3279 global board board_info
3281 unset -nocomplain gdb_spawn_id
3282 set board [host_info name]
3283 unset -nocomplain board_info($board,fileid)
3286 # Run BODY with SPAWN_ID as current spawn id.
3288 proc with_spawn_id { spawn_id body } {
3289 global gdb_spawn_id
3291 if [info exists gdb_spawn_id] {
3292 set saved_spawn_id $gdb_spawn_id
3295 switch_gdb_spawn_id $spawn_id
3297 set code [catch {uplevel 1 $body} result]
3299 if [info exists saved_spawn_id] {
3300 switch_gdb_spawn_id $saved_spawn_id
3301 } else {
3302 clear_gdb_spawn_id
3305 if {$code == 1} {
3306 global errorInfo errorCode
3307 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3308 } else {
3309 return -code $code $result
3313 # DejaGNU records spawn ids in a global array and tries to wait for
3314 # them when exiting. Sometimes this caused problems if gdb's test
3315 # suite has already waited for the particular spawn id. And, dejagnu
3316 # only seems to allow a single spawn id per "machine". This proc can
3317 # be used to clean up after a spawn id has been closed.
3318 proc clean_up_spawn_id {host id} {
3319 global board_info
3320 set name [board_info $host name]
3321 if {[info exists board_info($name,fileid)]
3322 && $board_info($name,fileid) == $id} {
3323 unset -nocomplain board_info($name,fileid)
3327 # Select the largest timeout from all the timeouts:
3328 # - the local "timeout" variable of the scope two levels above,
3329 # - the global "timeout" variable,
3330 # - the board variable "gdb,timeout".
3332 proc get_largest_timeout {} {
3333 upvar #0 timeout gtimeout
3334 upvar 2 timeout timeout
3336 set tmt 0
3337 if [info exists timeout] {
3338 set tmt $timeout
3340 if { [info exists gtimeout] && $gtimeout > $tmt } {
3341 set tmt $gtimeout
3343 if { [target_info exists gdb,timeout]
3344 && [target_info gdb,timeout] > $tmt } {
3345 set tmt [target_info gdb,timeout]
3347 if { $tmt == 0 } {
3348 # Eeeeew.
3349 set tmt 60
3352 return $tmt
3355 # Run tests in BODY with timeout increased by factor of FACTOR. When
3356 # BODY is finished, restore timeout.
3358 proc with_timeout_factor { factor body } {
3359 global timeout
3361 set savedtimeout $timeout
3363 set timeout [expr [get_largest_timeout] * $factor]
3364 set code [catch {uplevel 1 $body} result]
3366 set timeout $savedtimeout
3367 if {$code == 1} {
3368 global errorInfo errorCode
3369 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3370 } else {
3371 return -code $code $result
3375 # Run BODY with timeout factor FACTOR if check-read1 is used.
3377 proc with_read1_timeout_factor { factor body } {
3378 if { [info exists ::env(READ1)] == 1 && $::env(READ1) == 1 } {
3379 # Use timeout factor
3380 } else {
3381 # Reset timeout factor
3382 set factor 1
3384 return [uplevel [list with_timeout_factor $factor $body]]
3387 # Return 1 if _Complex types are supported, otherwise, return 0.
3389 gdb_caching_proc support_complex_tests {} {
3391 if { ![allow_float_test] } {
3392 # If floating point is not supported, _Complex is not
3393 # supported.
3394 return 0
3397 # Compile a test program containing _Complex types.
3399 return [gdb_can_simple_compile complex {
3400 int main() {
3401 _Complex float cf;
3402 _Complex double cd;
3403 _Complex long double cld;
3404 return 0;
3406 } executable]
3409 # Return 1 if compiling go is supported.
3410 gdb_caching_proc support_go_compile {} {
3412 return [gdb_can_simple_compile go-hello {
3413 package main
3414 import "fmt"
3415 func main() {
3416 fmt.Println("hello world")
3418 } executable go]
3421 # Return 1 if GDB can get a type for siginfo from the target, otherwise
3422 # return 0.
3424 proc supports_get_siginfo_type {} {
3425 if { [istarget "*-*-linux*"] } {
3426 return 1
3427 } else {
3428 return 0
3432 # Return 1 if memory tagging is supported at runtime, otherwise return 0.
3434 gdb_caching_proc supports_memtag {} {
3435 global gdb_prompt
3437 gdb_test_multiple "memory-tag check" "" {
3438 -re "Memory tagging not supported or disabled by the current architecture\..*$gdb_prompt $" {
3439 return 0
3441 -re "Argument required \\(address or pointer\\).*$gdb_prompt $" {
3442 return 1
3445 return 0
3448 # Return 1 if the target supports hardware single stepping.
3450 proc can_hardware_single_step {} {
3452 if { [istarget "arm*-*-*"] || [istarget "mips*-*-*"]
3453 || [istarget "tic6x-*-*"] || [istarget "sparc*-*-linux*"]
3454 || [istarget "nios2-*-*"] || [istarget "riscv*-*-linux*"] } {
3455 return 0
3458 return 1
3461 # Return 1 if target hardware or OS supports single stepping to signal
3462 # handler, otherwise, return 0.
3464 proc can_single_step_to_signal_handler {} {
3465 # Targets don't have hardware single step. On these targets, when
3466 # a signal is delivered during software single step, gdb is unable
3467 # to determine the next instruction addresses, because start of signal
3468 # handler is one of them.
3469 return [can_hardware_single_step]
3472 # Return 1 if target supports process record, otherwise return 0.
3474 proc supports_process_record {} {
3476 if [target_info exists gdb,use_precord] {
3477 return [target_info gdb,use_precord]
3480 if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
3481 || [istarget "i\[34567\]86-*-linux*"]
3482 || [istarget "aarch64*-*-linux*"]
3483 || [istarget "powerpc*-*-linux*"]
3484 || [istarget "s390*-*-linux*"] } {
3485 return 1
3488 return 0
3491 # Return 1 if target supports reverse debugging, otherwise return 0.
3493 proc supports_reverse {} {
3495 if [target_info exists gdb,can_reverse] {
3496 return [target_info gdb,can_reverse]
3499 if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
3500 || [istarget "i\[34567\]86-*-linux*"]
3501 || [istarget "aarch64*-*-linux*"]
3502 || [istarget "powerpc*-*-linux*"]
3503 || [istarget "s390*-*-linux*"] } {
3504 return 1
3507 return 0
3510 # Return 1 if readline library is used.
3512 proc readline_is_used { } {
3513 global gdb_prompt
3515 gdb_test_multiple "show editing" "" {
3516 -re ".*Editing of command lines as they are typed is on\..*$gdb_prompt $" {
3517 return 1
3519 -re ".*$gdb_prompt $" {
3520 return 0
3525 # Return 1 if target is ELF.
3526 gdb_caching_proc is_elf_target {} {
3527 set me "is_elf_target"
3529 set src { int foo () {return 0;} }
3530 if {![gdb_simple_compile elf_target $src]} {
3531 return 0
3534 set fp_obj [open $obj "r"]
3535 fconfigure $fp_obj -translation binary
3536 set data [read $fp_obj]
3537 close $fp_obj
3539 file delete $obj
3541 set ELFMAG "\u007FELF"
3543 if {[string compare -length 4 $data $ELFMAG] != 0} {
3544 verbose "$me: returning 0" 2
3545 return 0
3548 verbose "$me: returning 1" 2
3549 return 1
3552 # Return 1 if the memory at address zero is readable.
3554 gdb_caching_proc is_address_zero_readable {} {
3555 global gdb_prompt
3557 set ret 0
3558 gdb_test_multiple "x 0" "" {
3559 -re "Cannot access memory at address 0x0.*$gdb_prompt $" {
3560 set ret 0
3562 -re ".*$gdb_prompt $" {
3563 set ret 1
3567 return $ret
3570 # Produce source file NAME and write SOURCES into it.
3572 proc gdb_produce_source { name sources } {
3573 set index 0
3574 set f [open $name "w"]
3576 puts $f $sources
3577 close $f
3580 # Return 1 if target is ILP32.
3581 # This cannot be decided simply from looking at the target string,
3582 # as it might depend on externally passed compiler options like -m64.
3583 gdb_caching_proc is_ilp32_target {} {
3584 return [gdb_can_simple_compile is_ilp32_target {
3585 int dummy[sizeof (int) == 4
3586 && sizeof (void *) == 4
3587 && sizeof (long) == 4 ? 1 : -1];
3591 # Return 1 if target is LP64.
3592 # This cannot be decided simply from looking at the target string,
3593 # as it might depend on externally passed compiler options like -m64.
3594 gdb_caching_proc is_lp64_target {} {
3595 return [gdb_can_simple_compile is_lp64_target {
3596 int dummy[sizeof (int) == 4
3597 && sizeof (void *) == 8
3598 && sizeof (long) == 8 ? 1 : -1];
3602 # Return 1 if target has 64 bit addresses.
3603 # This cannot be decided simply from looking at the target string,
3604 # as it might depend on externally passed compiler options like -m64.
3605 gdb_caching_proc is_64_target {} {
3606 return [gdb_can_simple_compile_nodebug is_64_target {
3607 int function(void) { return 3; }
3608 int dummy[sizeof (&function) == 8 ? 1 : -1];
3612 # Return 1 if target has x86_64 registers - either amd64 or x32.
3613 # x32 target identifies as x86_64-*-linux*, therefore it cannot be determined
3614 # just from the target string.
3615 gdb_caching_proc is_amd64_regs_target {} {
3616 if {![istarget "x86_64-*-*"] && ![istarget "i?86-*"]} {
3617 return 0
3620 return [gdb_can_simple_compile is_amd64_regs_target {
3621 int main (void) {
3622 asm ("incq %rax");
3623 asm ("incq %r15");
3625 return 0;
3630 # Return 1 if this target is an x86 or x86-64 with -m32.
3631 proc is_x86_like_target {} {
3632 if {![istarget "x86_64-*-*"] && ![istarget i?86-*]} {
3633 return 0
3635 return [expr [is_ilp32_target] && ![is_amd64_regs_target]]
3638 # Return 1 if this target is an x86_64 with -m64.
3639 proc is_x86_64_m64_target {} {
3640 return [expr [istarget x86_64-*-* ] && [is_lp64_target]]
3643 # Return 1 if this target is an arm or aarch32 on aarch64.
3645 gdb_caching_proc is_aarch32_target {} {
3646 if { [istarget "arm*-*-*"] } {
3647 return 1
3650 if { ![istarget "aarch64*-*-*"] } {
3651 return 0
3654 set list {}
3655 foreach reg \
3656 {r0 r1 r2 r3} {
3657 lappend list "\tmov $reg, $reg"
3660 return [gdb_can_simple_compile aarch32 [join $list \n]]
3663 # Return 1 if this target is an aarch64, either lp64 or ilp32.
3665 proc is_aarch64_target {} {
3666 if { ![istarget "aarch64*-*-*"] } {
3667 return 0
3670 return [expr ![is_aarch32_target]]
3673 # Return 1 if displaced stepping is supported on target, otherwise, return 0.
3674 proc support_displaced_stepping {} {
3676 if { [istarget "x86_64-*-linux*"] || [istarget "i\[34567\]86-*-linux*"]
3677 || [istarget "arm*-*-linux*"] || [istarget "powerpc-*-linux*"]
3678 || [istarget "powerpc64-*-linux*"] || [istarget "s390*-*-*"]
3679 || [istarget "aarch64*-*-linux*"] || [istarget "loongarch*-*-linux*"] } {
3680 return 1
3683 return 0
3686 # Run a test on the target to see if it supports vmx hardware. Return 1 if so,
3687 # 0 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3689 gdb_caching_proc allow_altivec_tests {} {
3690 global srcdir subdir gdb_prompt inferior_exited_re
3692 set me "allow_altivec_tests"
3694 # Some simulators are known to not support VMX instructions.
3695 if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
3696 verbose "$me: target known to not support VMX, returning 0" 2
3697 return 0
3700 if {![istarget powerpc*]} {
3701 verbose "$me: PPC target required, returning 0" 2
3702 return 0
3705 # Make sure we have a compiler that understands altivec.
3706 if [test_compiler_info gcc*] {
3707 set compile_flags "additional_flags=-maltivec"
3708 } elseif [test_compiler_info xlc*] {
3709 set compile_flags "additional_flags=-qaltivec"
3710 } else {
3711 verbose "Could not compile with altivec support, returning 0" 2
3712 return 0
3715 # Compile a test program containing VMX instructions.
3716 set src {
3717 int main() {
3718 #ifdef __MACH__
3719 asm volatile ("vor v0,v0,v0");
3720 #else
3721 asm volatile ("vor 0,0,0");
3722 #endif
3723 return 0;
3726 if {![gdb_simple_compile $me $src executable $compile_flags]} {
3727 return 0
3730 # Compilation succeeded so now run it via gdb.
3732 gdb_exit
3733 gdb_start
3734 gdb_reinitialize_dir $srcdir/$subdir
3735 gdb_load "$obj"
3736 gdb_run_cmd
3737 gdb_expect {
3738 -re ".*Illegal instruction.*${gdb_prompt} $" {
3739 verbose -log "\n$me altivec hardware not detected"
3740 set allow_vmx_tests 0
3742 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3743 verbose -log "\n$me: altivec hardware detected"
3744 set allow_vmx_tests 1
3746 default {
3747 warning "\n$me: default case taken"
3748 set allow_vmx_tests 0
3751 gdb_exit
3752 remote_file build delete $obj
3754 verbose "$me: returning $allow_vmx_tests" 2
3755 return $allow_vmx_tests
3758 # Run a test on the power target to see if it supports ISA 3.1 instructions
3759 gdb_caching_proc allow_power_isa_3_1_tests {} {
3760 global srcdir subdir gdb_prompt inferior_exited_re
3762 set me "allow_power_isa_3_1_tests"
3764 # Compile a test program containing ISA 3.1 instructions.
3765 set src {
3766 int main() {
3767 asm volatile ("pnop"); // marker
3768 asm volatile ("nop");
3769 return 0;
3773 if {![gdb_simple_compile $me $src executable ]} {
3774 return 0
3777 # No error message, compilation succeeded so now run it via gdb.
3779 gdb_exit
3780 gdb_start
3781 gdb_reinitialize_dir $srcdir/$subdir
3782 gdb_load "$obj"
3783 gdb_run_cmd
3784 gdb_expect {
3785 -re ".*Illegal instruction.*${gdb_prompt} $" {
3786 verbose -log "\n$me Power ISA 3.1 hardware not detected"
3787 set allow_power_isa_3_1_tests 0
3789 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3790 verbose -log "\n$me: Power ISA 3.1 hardware detected"
3791 set allow_power_isa_3_1_tests 1
3793 default {
3794 warning "\n$me: default case taken"
3795 set allow_power_isa_3_1_tests 0
3798 gdb_exit
3799 remote_file build delete $obj
3801 verbose "$me: returning $allow_power_isa_3_1_tests" 2
3802 return $allow_power_isa_3_1_tests
3805 # Run a test on the target to see if it supports vmx hardware. Return 1 if so,
3806 # 0 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3808 gdb_caching_proc allow_vsx_tests {} {
3809 global srcdir subdir gdb_prompt inferior_exited_re
3811 set me "allow_vsx_tests"
3813 # Some simulators are known to not support Altivec instructions, so
3814 # they won't support VSX instructions as well.
3815 if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
3816 verbose "$me: target known to not support VSX, returning 0" 2
3817 return 0
3820 # Make sure we have a compiler that understands altivec.
3821 if [test_compiler_info gcc*] {
3822 set compile_flags "additional_flags=-mvsx"
3823 } elseif [test_compiler_info xlc*] {
3824 set compile_flags "additional_flags=-qasm=gcc"
3825 } else {
3826 verbose "Could not compile with vsx support, returning 0" 2
3827 return 0
3830 # Compile a test program containing VSX instructions.
3831 set src {
3832 int main() {
3833 double a[2] = { 1.0, 2.0 };
3834 #ifdef __MACH__
3835 asm volatile ("lxvd2x v0,v0,%[addr]" : : [addr] "r" (a));
3836 #else
3837 asm volatile ("lxvd2x 0,0,%[addr]" : : [addr] "r" (a));
3838 #endif
3839 return 0;
3842 if {![gdb_simple_compile $me $src executable $compile_flags]} {
3843 return 0
3846 # No error message, compilation succeeded so now run it via gdb.
3848 gdb_exit
3849 gdb_start
3850 gdb_reinitialize_dir $srcdir/$subdir
3851 gdb_load "$obj"
3852 gdb_run_cmd
3853 gdb_expect {
3854 -re ".*Illegal instruction.*${gdb_prompt} $" {
3855 verbose -log "\n$me VSX hardware not detected"
3856 set allow_vsx_tests 0
3858 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3859 verbose -log "\n$me: VSX hardware detected"
3860 set allow_vsx_tests 1
3862 default {
3863 warning "\n$me: default case taken"
3864 set allow_vsx_tests 0
3867 gdb_exit
3868 remote_file build delete $obj
3870 verbose "$me: returning $allow_vsx_tests" 2
3871 return $allow_vsx_tests
3874 # Run a test on the target to see if it supports TSX hardware. Return 1 if so,
3875 # 0 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3877 gdb_caching_proc allow_tsx_tests {} {
3878 global srcdir subdir gdb_prompt inferior_exited_re
3880 set me "allow_tsx_tests"
3882 # Compile a test program.
3883 set src {
3884 int main() {
3885 asm volatile ("xbegin .L0");
3886 asm volatile ("xend");
3887 asm volatile (".L0: nop");
3888 return 0;
3891 if {![gdb_simple_compile $me $src executable]} {
3892 return 0
3895 # No error message, compilation succeeded so now run it via gdb.
3897 gdb_exit
3898 gdb_start
3899 gdb_reinitialize_dir $srcdir/$subdir
3900 gdb_load "$obj"
3901 gdb_run_cmd
3902 gdb_expect {
3903 -re ".*Illegal instruction.*${gdb_prompt} $" {
3904 verbose -log "$me: TSX hardware not detected."
3905 set allow_tsx_tests 0
3907 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3908 verbose -log "$me: TSX hardware detected."
3909 set allow_tsx_tests 1
3911 default {
3912 warning "\n$me: default case taken."
3913 set allow_tsx_tests 0
3916 gdb_exit
3917 remote_file build delete $obj
3919 verbose "$me: returning $allow_tsx_tests" 2
3920 return $allow_tsx_tests
3923 # Run a test on the target to see if it supports avx512bf16. Return 1 if so,
3924 # 0 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3926 gdb_caching_proc allow_avx512bf16_tests {} {
3927 global srcdir subdir gdb_prompt inferior_exited_re
3929 set me "allow_avx512bf16_tests"
3930 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
3931 verbose "$me: target does not support avx512bf16, returning 0" 2
3932 return 0
3935 # Compile a test program.
3936 set src {
3937 int main() {
3938 asm volatile ("vcvtne2ps2bf16 %xmm0, %xmm1, %xmm0");
3939 return 0;
3942 if {![gdb_simple_compile $me $src executable]} {
3943 return 0
3946 # No error message, compilation succeeded so now run it via gdb.
3948 gdb_exit
3949 gdb_start
3950 gdb_reinitialize_dir $srcdir/$subdir
3951 gdb_load "$obj"
3952 gdb_run_cmd
3953 gdb_expect {
3954 -re ".*Illegal instruction.*${gdb_prompt} $" {
3955 verbose -log "$me: avx512bf16 hardware not detected."
3956 set allow_avx512bf16_tests 0
3958 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3959 verbose -log "$me: avx512bf16 hardware detected."
3960 set allow_avx512bf16_tests 1
3962 default {
3963 warning "\n$me: default case taken."
3964 set allow_avx512bf16_tests 0
3967 gdb_exit
3968 remote_file build delete $obj
3970 verbose "$me: returning $allow_avx512bf16_tests" 2
3971 return $allow_avx512bf16_tests
3974 # Run a test on the target to see if it supports avx512fp16. Return 1 if so,
3975 # 0 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3977 gdb_caching_proc allow_avx512fp16_tests {} {
3978 global srcdir subdir gdb_prompt inferior_exited_re
3980 set me "allow_avx512fp16_tests"
3981 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
3982 verbose "$me: target does not support avx512fp16, returning 0" 2
3983 return 0
3986 # Compile a test program.
3987 set src {
3988 int main() {
3989 asm volatile ("vcvtps2phx %xmm1, %xmm0");
3990 return 0;
3993 if {![gdb_simple_compile $me $src executable]} {
3994 return 0
3997 # No error message, compilation succeeded so now run it via gdb.
3999 gdb_exit
4000 gdb_start
4001 gdb_reinitialize_dir $srcdir/$subdir
4002 gdb_load "$obj"
4003 gdb_run_cmd
4004 gdb_expect {
4005 -re ".*Illegal instruction.*${gdb_prompt} $" {
4006 verbose -log "$me: avx512fp16 hardware not detected."
4007 set allow_avx512fp16_tests 0
4009 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
4010 verbose -log "$me: avx512fp16 hardware detected."
4011 set allow_avx512fp16_tests 1
4013 default {
4014 warning "\n$me: default case taken."
4015 set allow_avx512fp16_tests 0
4018 gdb_exit
4019 remote_file build delete $obj
4021 verbose "$me: returning $allow_avx512fp16_tests" 2
4022 return $allow_avx512fp16_tests
4025 # Run a test on the target to see if it supports btrace hardware. Return 1 if so,
4026 # 0 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
4028 gdb_caching_proc allow_btrace_tests {} {
4029 global srcdir subdir gdb_prompt inferior_exited_re
4031 set me "allow_btrace_tests"
4032 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
4033 verbose "$me: target does not support btrace, returning 0" 2
4034 return 0
4037 # Compile a test program.
4038 set src { int main() { return 0; } }
4039 if {![gdb_simple_compile $me $src executable]} {
4040 return 0
4043 # No error message, compilation succeeded so now run it via gdb.
4045 gdb_exit
4046 gdb_start
4047 gdb_reinitialize_dir $srcdir/$subdir
4048 gdb_load $obj
4049 if ![runto_main] {
4050 return 0
4052 # In case of an unexpected output, we return 2 as a fail value.
4053 set allow_btrace_tests 2
4054 gdb_test_multiple "record btrace" "check btrace support" {
4055 -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
4056 set allow_btrace_tests 0
4058 -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
4059 set allow_btrace_tests 0
4061 -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
4062 set allow_btrace_tests 0
4064 -re "^record btrace\r\n$gdb_prompt $" {
4065 set allow_btrace_tests 1
4068 gdb_exit
4069 remote_file build delete $obj
4071 verbose "$me: returning $allow_btrace_tests" 2
4072 return $allow_btrace_tests
4075 # Run a test on the target to see if it supports btrace pt hardware.
4076 # Return 1 if so, 0 if it does not. Based on 'check_vmx_hw_available'
4077 # from the GCC testsuite.
4079 gdb_caching_proc allow_btrace_pt_tests {} {
4080 global srcdir subdir gdb_prompt inferior_exited_re
4082 set me "allow_btrace_pt_tests"
4083 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
4084 verbose "$me: target does not support btrace, returning 1" 2
4085 return 0
4088 # Compile a test program.
4089 set src { int main() { return 0; } }
4090 if {![gdb_simple_compile $me $src executable]} {
4091 return 0
4094 # No error message, compilation succeeded so now run it via gdb.
4096 gdb_exit
4097 gdb_start
4098 gdb_reinitialize_dir $srcdir/$subdir
4099 gdb_load $obj
4100 if ![runto_main] {
4101 return 0
4103 # In case of an unexpected output, we return 2 as a fail value.
4104 set allow_btrace_pt_tests 2
4105 gdb_test_multiple "record btrace pt" "check btrace pt support" {
4106 -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
4107 set allow_btrace_pt_tests 0
4109 -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
4110 set allow_btrace_pt_tests 0
4112 -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
4113 set allow_btrace_pt_tests 0
4115 -re "support was disabled at compile time.*\r\n$gdb_prompt $" {
4116 set allow_btrace_pt_tests 0
4118 -re "^record btrace pt\r\n$gdb_prompt $" {
4119 set allow_btrace_pt_tests 1
4122 gdb_exit
4123 remote_file build delete $obj
4125 verbose "$me: returning $allow_btrace_pt_tests" 2
4126 return $allow_btrace_pt_tests
4129 # Run a test on the target to see if it supports Aarch64 SVE hardware.
4130 # Return 1 if so, 0 if it does not. Note this causes a restart of GDB.
4132 gdb_caching_proc allow_aarch64_sve_tests {} {
4133 global srcdir subdir gdb_prompt inferior_exited_re
4135 set me "allow_aarch64_sve_tests"
4137 if { ![is_aarch64_target]} {
4138 return 0
4141 set compile_flags "{additional_flags=-march=armv8-a+sve}"
4143 # Compile a test program containing SVE instructions.
4144 set src {
4145 int main() {
4146 asm volatile ("ptrue p0.b");
4147 return 0;
4150 if {![gdb_simple_compile $me $src executable $compile_flags]} {
4151 return 0
4154 # Compilation succeeded so now run it via gdb.
4155 clean_restart $obj
4156 gdb_run_cmd
4157 gdb_expect {
4158 -re ".*Illegal instruction.*${gdb_prompt} $" {
4159 verbose -log "\n$me sve hardware not detected"
4160 set allow_sve_tests 0
4162 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
4163 verbose -log "\n$me: sve hardware detected"
4164 set allow_sve_tests 1
4166 default {
4167 warning "\n$me: default case taken"
4168 set allow_sve_tests 0
4171 gdb_exit
4172 remote_file build delete $obj
4174 # While testing for SVE support, also discover all the supported vector
4175 # length values.
4176 aarch64_initialize_sve_information
4178 verbose "$me: returning $allow_sve_tests" 2
4179 return $allow_sve_tests
4182 # Assuming SVE is supported by the target, run some checks to determine all
4183 # the supported vector length values and return an array containing all of those
4184 # values. Since this is a gdb_caching_proc, this proc will only be executed
4185 # once.
4187 # To check if a particular SVE vector length is supported, the following code
4188 # can be used. For instance, for vl == 16:
4190 # if {[aarch64_supports_sve_vl 16]} {
4191 # verbose -log "SVE vector length 16 is supported."
4194 # This procedure should NEVER be called by hand, as it reinitializes the GDB
4195 # session and will derail a test. This should be called automatically as part
4196 # of the SVE support test routine allow_aarch64_sve_tests. Users should
4197 # restrict themselves to calling the helper proc aarch64_supports_sve_vl.
4199 gdb_caching_proc aarch64_initialize_sve_information { } {
4200 global srcdir
4202 set src "${srcdir}/lib/aarch64-test-sve.c"
4203 set test_exec [standard_temp_file "aarch64-test-sve.x"]
4204 set compile_flags "{additional_flags=-march=armv8-a+sve}"
4205 array set supported_vl {}
4207 # Compile the SVE vector length test.
4208 set result [gdb_compile $src $test_exec executable [list debug ${compile_flags} nowarnings]]
4210 if {$result != ""} {
4211 verbose -log "Failed to compile SVE information gathering test."
4212 return [array get supported_vl]
4215 clean_restart $test_exec
4217 if {![runto_main]} {
4218 return [array get supported_vl]
4221 set stop_breakpoint "stop here"
4222 gdb_breakpoint [gdb_get_line_number $stop_breakpoint $src]
4223 gdb_continue_to_breakpoint $stop_breakpoint
4225 # Go through the data and extract the supported SVE vector lengths.
4226 set vl_count [get_valueof "" "supported_vl_count" "0" \
4227 "fetch value of supported_vl_count"]
4228 verbose -log "Found $vl_count supported SVE vector length values"
4230 for {set vl_index 0} {$vl_index < $vl_count} {incr vl_index} {
4231 set test_vl [get_valueof "" "supported_vl\[$vl_index\]" "0" \
4232 "fetch value of supported_vl\[$vl_index\]"]
4234 # Mark this vector length as supported.
4235 if {$test_vl != 0} {
4236 verbose -log "Found supported SVE vector length $test_vl"
4237 set supported_vl($test_vl) 1
4241 gdb_exit
4242 verbose -log "Cleaning up"
4243 remote_file build delete $test_exec
4245 verbose -log "Done gathering information about AArch64 SVE vector lengths."
4247 # Return the array containing all of the supported SVE vl values.
4248 return [array get supported_vl]
4252 # Return 1 if the target supports SVE vl LENGTH
4253 # Return 0 otherwise.
4256 proc aarch64_supports_sve_vl { length } {
4258 # Fetch the cached array of supported SVE vl values.
4259 array set supported_vl [aarch64_initialize_sve_information]
4261 # Do we have the global values cached?
4262 if {![info exists supported_vl($length)]} {
4263 verbose -log "Target does not support SVE vl $length"
4264 return 0
4267 # The target supports SVE vl LENGTH.
4268 return 1
4271 # Run a test on the target to see if it supports Aarch64 SME extensions.
4272 # Return 0 if so, 1 if it does not. Note this causes a restart of GDB.
4274 gdb_caching_proc allow_aarch64_sme_tests {} {
4275 global srcdir subdir gdb_prompt inferior_exited_re
4277 set me "allow_aarch64_sme_tests"
4279 if { ![is_aarch64_target]} {
4280 return 0
4283 set compile_flags "{additional_flags=-march=armv8-a+sme}"
4285 # Compile a test program containing SME instructions.
4286 set src {
4287 int main() {
4288 asm volatile ("smstart za");
4289 return 0;
4292 if {![gdb_simple_compile $me $src executable $compile_flags]} {
4293 # Try again, but with a raw hex instruction so we don't rely on
4294 # assembler support for SME.
4296 set compile_flags "{additional_flags=-march=armv8-a}"
4298 # Compile a test program containing SME instructions.
4299 set src {
4300 int main() {
4301 asm volatile (".word 0xD503457F");
4302 return 0;
4306 if {![gdb_simple_compile $me $src executable $compile_flags]} {
4307 return 0
4311 # Compilation succeeded so now run it via gdb.
4312 clean_restart $obj
4313 gdb_run_cmd
4314 gdb_expect {
4315 -re ".*Illegal instruction.*${gdb_prompt} $" {
4316 verbose -log "\n$me sme support not detected"
4317 set allow_sme_tests 0
4319 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
4320 verbose -log "\n$me: sme support detected"
4321 set allow_sme_tests 1
4323 default {
4324 warning "\n$me: default case taken"
4325 set allow_sme_tests 0
4328 gdb_exit
4329 remote_file build delete $obj
4331 # While testing for SME support, also discover all the supported vector
4332 # length values.
4333 aarch64_initialize_sme_information
4335 verbose "$me: returning $allow_sme_tests" 2
4336 return $allow_sme_tests
4339 # Assuming SME is supported by the target, run some checks to determine all
4340 # the supported streaming vector length values and return an array containing
4341 # all of those values. Since this is a gdb_caching_proc, this proc will only
4342 # be executed once.
4344 # To check if a particular SME streaming vector length is supported, the
4345 # following code can be used. For instance, for svl == 32:
4347 # if {[aarch64_supports_sme_svl 32]} {
4348 # verbose -log "SME streaming vector length 32 is supported."
4351 # This procedure should NEVER be called by hand, as it reinitializes the GDB
4352 # session and will derail a test. This should be called automatically as part
4353 # of the SME support test routine allow_aarch64_sme_tests. Users should
4354 # restrict themselves to calling the helper proc aarch64_supports_sme_svl.
4356 gdb_caching_proc aarch64_initialize_sme_information { } {
4357 global srcdir
4359 set src "${srcdir}/lib/aarch64-test-sme.c"
4360 set test_exec [standard_temp_file "aarch64-test-sme.x"]
4361 set compile_flags "{additional_flags=-march=armv8-a+sme}"
4362 array set supported_svl {}
4364 # Compile the SME vector length test.
4365 set result [gdb_compile $src $test_exec executable [list debug ${compile_flags} nowarnings]]
4367 if {$result != ""} {
4368 verbose -log "Failed to compile SME information gathering test."
4369 return [array get supported_svl]
4372 clean_restart $test_exec
4374 if {![runto_main]} {
4375 return [array get supported_svl]
4378 set stop_breakpoint "stop here"
4379 gdb_breakpoint [gdb_get_line_number $stop_breakpoint $src]
4380 gdb_continue_to_breakpoint $stop_breakpoint
4382 # Go through the data and extract the supported SME vector lengths.
4383 set svl_count [get_valueof "" "supported_svl_count" "0" \
4384 "fetch value of supported_svl_count"]
4385 verbose -log "Found $svl_count supported SME vector length values"
4387 for {set svl_index 0} {$svl_index < $svl_count} {incr svl_index} {
4388 set test_svl [get_valueof "" "supported_svl\[$svl_index\]" "0" \
4389 "fetch value of supported_svl\[$svl_index\]"]
4391 # Mark this streaming vector length as supported.
4392 if {$test_svl != 0} {
4393 verbose -log "Found supported SME vector length $test_svl"
4394 set supported_svl($test_svl) 1
4398 gdb_exit
4399 verbose -log "Cleaning up"
4400 remote_file build delete $test_exec
4402 verbose -log "Done gathering information about AArch64 SME vector lengths."
4404 # Return the array containing all of the supported SME svl values.
4405 return [array get supported_svl]
4409 # Return 1 if the target supports SME svl LENGTH
4410 # Return 0 otherwise.
4413 proc aarch64_supports_sme_svl { length } {
4415 # Fetch the cached array of supported SME svl values.
4416 array set supported_svl [aarch64_initialize_sme_information]
4418 # Do we have the global values cached?
4419 if {![info exists supported_svl($length)]} {
4420 verbose -log "Target does not support SME svl $length"
4421 return 0
4424 # The target supports SME svl LENGTH.
4425 return 1
4428 # A helper that compiles a test case to see if __int128 is supported.
4429 proc gdb_int128_helper {lang} {
4430 return [gdb_can_simple_compile "i128-for-$lang" {
4431 __int128 x;
4432 int main() { return 0; }
4433 } executable $lang]
4436 # Return true if the C compiler understands the __int128 type.
4437 gdb_caching_proc has_int128_c {} {
4438 return [gdb_int128_helper c]
4441 # Return true if the C++ compiler understands the __int128 type.
4442 gdb_caching_proc has_int128_cxx {} {
4443 return [gdb_int128_helper c++]
4446 # Return true if the IFUNC feature is supported.
4447 gdb_caching_proc allow_ifunc_tests {} {
4448 if [gdb_can_simple_compile ifunc {
4449 extern void f_ ();
4450 typedef void F (void);
4451 F* g (void) { return &f_; }
4452 void f () __attribute__ ((ifunc ("g")));
4453 } object] {
4454 return 1
4455 } else {
4456 return 0
4460 # Return whether we should skip tests for showing inlined functions in
4461 # backtraces. Requires get_compiler_info and get_debug_format.
4463 proc skip_inline_frame_tests {} {
4464 # GDB only recognizes inlining information in DWARF.
4465 if { ! [test_debug_format "DWARF \[0-9\]"] } {
4466 return 1
4469 # GCC before 4.1 does not emit DW_AT_call_file / DW_AT_call_line.
4470 if { ([test_compiler_info "gcc-2-*"]
4471 || [test_compiler_info "gcc-3-*"]
4472 || [test_compiler_info "gcc-4-0-*"]) } {
4473 return 1
4476 return 0
4479 # Return whether we should skip tests for showing variables from
4480 # inlined functions. Requires get_compiler_info and get_debug_format.
4482 proc skip_inline_var_tests {} {
4483 # GDB only recognizes inlining information in DWARF.
4484 if { ! [test_debug_format "DWARF \[0-9\]"] } {
4485 return 1
4488 return 0
4491 # Return a 1 if we should run tests that require hardware breakpoints
4493 proc allow_hw_breakpoint_tests {} {
4494 # Skip tests if requested by the board (note that no_hardware_watchpoints
4495 # disables both watchpoints and breakpoints)
4496 if { [target_info exists gdb,no_hardware_watchpoints]} {
4497 return 0
4500 # These targets support hardware breakpoints natively
4501 if { [istarget "i?86-*-*"]
4502 || [istarget "x86_64-*-*"]
4503 || [istarget "ia64-*-*"]
4504 || [istarget "arm*-*-*"]
4505 || [istarget "aarch64*-*-*"]
4506 || [istarget "s390*-*-*"] } {
4507 return 1
4510 return 0
4513 # Return a 1 if we should run tests that require hardware watchpoints
4515 proc allow_hw_watchpoint_tests {} {
4516 # Skip tests if requested by the board
4517 if { [target_info exists gdb,no_hardware_watchpoints]} {
4518 return 0
4521 # These targets support hardware watchpoints natively
4522 # Note, not all Power 9 processors support hardware watchpoints due to a HW
4523 # bug. Use has_hw_wp_support to check do a runtime check for hardware
4524 # watchpoint support on Powerpc.
4525 if { [istarget "i?86-*-*"]
4526 || [istarget "x86_64-*-*"]
4527 || [istarget "ia64-*-*"]
4528 || [istarget "arm*-*-*"]
4529 || [istarget "aarch64*-*-*"]
4530 || ([istarget "powerpc*-*-linux*"] && [has_hw_wp_support])
4531 || [istarget "s390*-*-*"] } {
4532 return 1
4535 return 0
4538 # Return a 1 if we should run tests that require *multiple* hardware
4539 # watchpoints to be active at the same time
4541 proc allow_hw_watchpoint_multi_tests {} {
4542 if { ![allow_hw_watchpoint_tests] } {
4543 return 0
4546 # These targets support just a single hardware watchpoint
4547 if { [istarget "arm*-*-*"]
4548 || [istarget "powerpc*-*-linux*"] } {
4549 return 0
4552 return 1
4555 # Return a 1 if we should run tests that require read/access watchpoints
4557 proc allow_hw_watchpoint_access_tests {} {
4558 if { ![allow_hw_watchpoint_tests] } {
4559 return 0
4562 # These targets support just write watchpoints
4563 if { [istarget "s390*-*-*"] } {
4564 return 0
4567 return 1
4570 # Return 1 if we should skip tests that require the runtime unwinder
4571 # hook. This must be invoked while gdb is running, after shared
4572 # libraries have been loaded. This is needed because otherwise a
4573 # shared libgcc won't be visible.
4575 proc skip_unwinder_tests {} {
4576 global gdb_prompt
4578 set ok 0
4579 gdb_test_multiple "print _Unwind_DebugHook" "check for unwinder hook" {
4580 -re "= .*no debug info.*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
4582 -re "= .*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
4583 set ok 1
4585 -re "No symbol .* in current context.\r\n$gdb_prompt $" {
4588 if {!$ok} {
4589 gdb_test_multiple "info probe" "check for stap probe in unwinder" {
4590 -re ".*libgcc.*unwind.*\r\n$gdb_prompt $" {
4591 set ok 1
4593 -re "\r\n$gdb_prompt $" {
4597 return $ok
4600 # Return 1 if we should skip tests that require the libstdc++ stap
4601 # probes. This must be invoked while gdb is running, after shared
4602 # libraries have been loaded. PROMPT_REGEXP is the expected prompt.
4604 proc skip_libstdcxx_probe_tests_prompt { prompt_regexp } {
4605 set supported 0
4606 gdb_test_multiple "info probe" "check for stap probe in libstdc++" \
4607 -prompt "$prompt_regexp" {
4608 -re ".*libstdcxx.*catch.*\r\n$prompt_regexp" {
4609 set supported 1
4611 -re "\r\n$prompt_regexp" {
4614 set skip [expr !$supported]
4615 return $skip
4618 # As skip_libstdcxx_probe_tests_prompt, with gdb_prompt.
4620 proc skip_libstdcxx_probe_tests {} {
4621 global gdb_prompt
4622 return [skip_libstdcxx_probe_tests_prompt "$gdb_prompt $"]
4625 # Return 1 if libc supports the longjmp probe. Note that we're not using
4626 # gdb_caching_proc because the probe may have been disabled.
4628 proc have_longjmp_probe {} {
4629 set have_probe -1
4630 gdb_test_multiple "info probes stap libc ^longjmp$" "" {
4631 -re -wrap "No probes matched\\." {
4632 set have_probe 0
4634 -re -wrap "\r\nstap\[ \t\]+libc\[ \t\]+longjmp\[ \t\]+.*" {
4635 set have_probe 1
4638 if { $have_probe == -1 } {
4639 error "failed to get libc longjmp probe status"
4641 return $have_probe
4644 # Helper for gdb_is_target_* procs. TARGET_NAME is the name of the target
4645 # we're looking for (used to build the test name). TARGET_STACK_REGEXP
4646 # is a regexp that will match the output of "maint print target-stack" if
4647 # the target in question is currently pushed. PROMPT_REGEXP is a regexp
4648 # matching the expected prompt after the command output.
4650 # NOTE: GDB must be running BEFORE this procedure is called!
4652 proc gdb_is_target_1 { target_name target_stack_regexp prompt_regexp } {
4653 global gdb_spawn_id
4655 # Throw a Tcl error if gdb isn't already started.
4656 if {![info exists gdb_spawn_id]} {
4657 error "gdb_is_target_1 called with no running gdb instance"
4660 set test "probe for target ${target_name}"
4661 gdb_test_multiple "maint print target-stack" $test \
4662 -prompt "$prompt_regexp" {
4663 -re "${target_stack_regexp}${prompt_regexp}" {
4664 pass $test
4665 return 1
4667 -re "$prompt_regexp" {
4668 pass $test
4671 return 0
4674 # Helper for gdb_is_target_remote where the expected prompt is variable.
4676 # NOTE: GDB must be running BEFORE this procedure is called!
4678 proc gdb_is_target_remote_prompt { prompt_regexp } {
4679 return [gdb_is_target_1 "remote" ".*emote target using gdb-specific protocol.*" $prompt_regexp]
4682 # Check whether we're testing with the remote or extended-remote
4683 # targets.
4685 # NOTE: GDB must be running BEFORE this procedure is called!
4687 proc gdb_is_target_remote { } {
4688 global gdb_prompt
4690 return [gdb_is_target_remote_prompt "$gdb_prompt $"]
4693 # Check whether we're testing with the native target.
4695 # NOTE: GDB must be running BEFORE this procedure is called!
4697 proc gdb_is_target_native { } {
4698 global gdb_prompt
4700 return [gdb_is_target_1 "native" ".*native \\(Native process\\).*" "$gdb_prompt $"]
4703 # Like istarget, but checks a list of targets.
4704 proc is_any_target {args} {
4705 foreach targ $args {
4706 if {[istarget $targ]} {
4707 return 1
4710 return 0
4713 # Return the effective value of use_gdb_stub.
4715 # If the use_gdb_stub global has been set (it is set when the gdb process is
4716 # spawned), return that. Otherwise, return the value of the use_gdb_stub
4717 # property from the board file.
4719 # This is the preferred way of checking use_gdb_stub, since it allows to check
4720 # the value before the gdb has been spawned and it will return the correct value
4721 # even when it was overriden by the test.
4723 # Note that stub targets are not able to spawn new inferiors. Use this
4724 # check for skipping respective tests.
4726 proc use_gdb_stub {} {
4727 global use_gdb_stub
4729 if [info exists use_gdb_stub] {
4730 return $use_gdb_stub
4733 return [target_info exists use_gdb_stub]
4736 # Return 1 if the current remote target is an instance of our GDBserver, 0
4737 # otherwise. Return -1 if there was an error and we can't tell.
4739 gdb_caching_proc target_is_gdbserver {} {
4740 global gdb_prompt
4742 set is_gdbserver -1
4743 set test "probing for GDBserver"
4745 gdb_test_multiple "monitor help" $test {
4746 -re "The following monitor commands are supported.*Quit GDBserver.*$gdb_prompt $" {
4747 set is_gdbserver 1
4749 -re "$gdb_prompt $" {
4750 set is_gdbserver 0
4754 if { $is_gdbserver == -1 } {
4755 verbose -log "Unable to tell whether we are using GDBserver or not."
4758 return $is_gdbserver
4761 # N.B. compiler_info is intended to be local to this file.
4762 # Call test_compiler_info with no arguments to fetch its value.
4763 # Yes, this is counterintuitive when there's get_compiler_info,
4764 # but that's the current API.
4765 if [info exists compiler_info] {
4766 unset compiler_info
4769 # Figure out what compiler I am using.
4770 # The result is cached so only the first invocation runs the compiler.
4772 # ARG can be empty or "C++". If empty, "C" is assumed.
4774 # There are several ways to do this, with various problems.
4776 # [ gdb_compile -E $ifile -o $binfile.ci ]
4777 # source $binfile.ci
4779 # Single Unix Spec v3 says that "-E -o ..." together are not
4780 # specified. And in fact, the native compiler on hp-ux 11 (among
4781 # others) does not work with "-E -o ...". Most targets used to do
4782 # this, and it mostly worked, because it works with gcc.
4784 # [ catch "exec $compiler -E $ifile > $binfile.ci" exec_output ]
4785 # source $binfile.ci
4787 # This avoids the problem with -E and -o together. This almost works
4788 # if the build machine is the same as the host machine, which is
4789 # usually true of the targets which are not gcc. But this code does
4790 # not figure which compiler to call, and it always ends up using the C
4791 # compiler. Not good for setting hp_aCC_compiler. Target
4792 # hppa*-*-hpux* used to do this.
4794 # [ gdb_compile -E $ifile > $binfile.ci ]
4795 # source $binfile.ci
4797 # dejagnu target_compile says that it supports output redirection,
4798 # but the code is completely different from the normal path and I
4799 # don't want to sweep the mines from that path. So I didn't even try
4800 # this.
4802 # set cppout [ gdb_compile $ifile "" preprocess $args quiet ]
4803 # eval $cppout
4805 # I actually do this for all targets now. gdb_compile runs the right
4806 # compiler, and TCL captures the output, and I eval the output.
4808 # Unfortunately, expect logs the output of the command as it goes by,
4809 # and dejagnu helpfully prints a second copy of it right afterwards.
4810 # So I turn off expect logging for a moment.
4812 # [ gdb_compile $ifile $ciexe_file executable $args ]
4813 # [ remote_exec $ciexe_file ]
4814 # [ source $ci_file.out ]
4816 # I could give up on -E and just do this.
4817 # I didn't get desperate enough to try this.
4819 # -- chastain 2004-01-06
4821 proc get_compiler_info {{language "c"}} {
4823 # For compiler.c, compiler.cc and compiler.F90.
4824 global srcdir
4826 # I am going to play with the log to keep noise out.
4827 global outdir
4828 global tool
4830 # These come from compiler.c, compiler.cc or compiler.F90.
4831 gdb_persistent_global compiler_info_cache
4833 if [info exists compiler_info_cache($language)] {
4834 # Already computed.
4835 return 0
4838 # Choose which file to preprocess.
4839 if { $language == "c++" } {
4840 set ifile "${srcdir}/lib/compiler.cc"
4841 } elseif { $language == "f90" } {
4842 set ifile "${srcdir}/lib/compiler.F90"
4843 } elseif { $language == "c" } {
4844 set ifile "${srcdir}/lib/compiler.c"
4845 } else {
4846 perror "Unable to fetch compiler version for language: $language"
4847 return -1
4850 # Run $ifile through the right preprocessor.
4851 # Toggle gdb.log to keep the compiler output out of the log.
4852 set saved_log [log_file -info]
4853 log_file
4854 if [is_remote host] {
4855 # We have to use -E and -o together, despite the comments
4856 # above, because of how DejaGnu handles remote host testing.
4857 set ppout "$outdir/compiler.i"
4858 gdb_compile "${ifile}" "$ppout" preprocess [list "$language" quiet getting_compiler_info]
4859 set file [open $ppout r]
4860 set cppout [read $file]
4861 close $file
4862 } else {
4863 # Copy $ifile to temp dir, to work around PR gcc/60447. This will leave the
4864 # superfluous .s file in the temp dir instead of in the source dir.
4865 set tofile [file tail $ifile]
4866 set tofile [standard_temp_file $tofile]
4867 file copy -force $ifile $tofile
4868 set ifile $tofile
4869 set cppout [ gdb_compile "${ifile}" "" preprocess [list "$language" quiet getting_compiler_info] ]
4871 eval log_file $saved_log
4873 # Eval the output.
4874 set unknown 0
4875 foreach cppline [ split "$cppout" "\n" ] {
4876 if { [ regexp "^#" "$cppline" ] } {
4877 # line marker
4878 } elseif { [ regexp "^\[\n\r\t \]*$" "$cppline" ] } {
4879 # blank line
4880 } elseif { [ regexp "^\[\n\r\t \]*set\[\n\r\t \]" "$cppline" ] } {
4881 # eval this line
4882 verbose "get_compiler_info: $cppline" 2
4883 eval "$cppline"
4884 } elseif { [ regexp {[fc]lang.*warning.*'-fdiagnostics-color=never'} "$cppline"] } {
4885 # Both flang preprocessors (llvm flang and classic flang) print a
4886 # warning for the unused -fdiagnostics-color=never, so we skip this
4887 # output line here.
4888 # The armflang preprocessor has been observed to output the
4889 # warning prefixed with "clang", so the regex also accepts
4890 # this.
4891 } else {
4892 # unknown line
4893 verbose -log "get_compiler_info: $cppline"
4894 set unknown 1
4898 # Set to unknown if for some reason compiler_info didn't get defined.
4899 if ![info exists compiler_info] {
4900 verbose -log "get_compiler_info: compiler_info not provided"
4901 set compiler_info "unknown"
4903 # Also set to unknown compiler if any diagnostics happened.
4904 if { $unknown } {
4905 verbose -log "get_compiler_info: got unexpected diagnostics"
4906 set compiler_info "unknown"
4909 set compiler_info_cache($language) $compiler_info
4911 # Log what happened.
4912 verbose -log "get_compiler_info: $compiler_info"
4914 return 0
4917 # Return the compiler_info string if no arg is provided.
4918 # Otherwise the argument is a glob-style expression to match against
4919 # compiler_info.
4921 proc test_compiler_info { {compiler ""} {language "c"} } {
4922 gdb_persistent_global compiler_info_cache
4924 if [get_compiler_info $language] {
4925 # An error will already have been printed in this case. Just
4926 # return a suitable result depending on how the user called
4927 # this function.
4928 if [string match "" $compiler] {
4929 return ""
4930 } else {
4931 return false
4935 # If no arg, return the compiler_info string.
4936 if [string match "" $compiler] {
4937 return $compiler_info_cache($language)
4940 return [string match $compiler $compiler_info_cache($language)]
4943 # Return true if the C compiler is GCC, otherwise, return false.
4945 proc is_c_compiler_gcc {} {
4946 set compiler_info [test_compiler_info]
4947 set gcc_compiled false
4948 regexp "^gcc-(\[0-9\]+)-" "$compiler_info" matchall gcc_compiled
4949 return $gcc_compiled
4952 # Return the gcc major version, or -1.
4953 # For gcc 4.8.5, the major version is 4.8.
4954 # For gcc 7.5.0, the major version 7.
4955 # The COMPILER and LANGUAGE arguments are as for test_compiler_info.
4957 proc gcc_major_version { {compiler "gcc-*"} {language "c"} } {
4958 global decimal
4959 if { ![test_compiler_info $compiler $language] } {
4960 return -1
4962 # Strip "gcc-*" to "gcc".
4963 regsub -- {-.*} $compiler "" compiler
4964 set res [regexp $compiler-($decimal)-($decimal)- \
4965 [test_compiler_info "" $language] \
4966 dummy_var major minor]
4967 if { $res != 1 } {
4968 return -1
4970 if { $major >= 5} {
4971 return $major
4973 return $major.$minor
4976 proc current_target_name { } {
4977 global target_info
4978 if [info exists target_info(target,name)] {
4979 set answer $target_info(target,name)
4980 } else {
4981 set answer ""
4983 return $answer
4986 set gdb_wrapper_initialized 0
4987 set gdb_wrapper_target ""
4988 set gdb_wrapper_file ""
4989 set gdb_wrapper_flags ""
4991 proc gdb_wrapper_init { args } {
4992 global gdb_wrapper_initialized
4993 global gdb_wrapper_file
4994 global gdb_wrapper_flags
4995 global gdb_wrapper_target
4997 if { $gdb_wrapper_initialized == 1 } { return; }
4999 if {[target_info exists needs_status_wrapper] && \
5000 [target_info needs_status_wrapper] != "0"} {
5001 set result [build_wrapper "testglue.o"]
5002 if { $result != "" } {
5003 set gdb_wrapper_file [lindex $result 0]
5004 if ![is_remote host] {
5005 set gdb_wrapper_file [file join [pwd] $gdb_wrapper_file]
5007 set gdb_wrapper_flags [lindex $result 1]
5008 } else {
5009 warning "Status wrapper failed to build."
5011 } else {
5012 set gdb_wrapper_file ""
5013 set gdb_wrapper_flags ""
5015 verbose "set gdb_wrapper_file = $gdb_wrapper_file"
5016 set gdb_wrapper_initialized 1
5017 set gdb_wrapper_target [current_target_name]
5020 # Determine options that we always want to pass to the compiler.
5021 gdb_caching_proc universal_compile_options {} {
5022 set me "universal_compile_options"
5023 set options {}
5025 set src [standard_temp_file ccopts.c]
5026 set obj [standard_temp_file ccopts.o]
5028 gdb_produce_source $src {
5029 int foo(void) { return 0; }
5032 # Try an option for disabling colored diagnostics. Some compilers
5033 # yield colored diagnostics by default (when run from a tty) unless
5034 # such an option is specified.
5035 set opt "additional_flags=-fdiagnostics-color=never"
5036 set lines [target_compile $src $obj object [list "quiet" $opt]]
5037 if {[string match "" $lines]} {
5038 # Seems to have worked; use the option.
5039 lappend options $opt
5041 file delete $src
5042 file delete $obj
5044 verbose "$me: returning $options" 2
5045 return $options
5048 # Compile the code in $code to a file based on $name, using the flags
5049 # $compile_flag as well as debug, nowarning and quiet (unless otherwise
5050 # specified in default_compile_flags).
5051 # Return 1 if code can be compiled
5052 # Leave the file name of the resulting object in the upvar object.
5054 proc gdb_simple_compile {name code {type object} {compile_flags {}} {object obj} {default_compile_flags {}}} {
5055 upvar $object obj
5057 switch -regexp -- $type {
5058 "executable" {
5059 set postfix "x"
5061 "object" {
5062 set postfix "o"
5064 "preprocess" {
5065 set postfix "i"
5067 "assembly" {
5068 set postfix "s"
5071 set ext "c"
5072 foreach flag $compile_flags {
5073 if { "$flag" == "go" } {
5074 set ext "go"
5075 break
5077 if { "$flag" eq "hip" } {
5078 set ext "cpp"
5079 break
5081 if { "$flag" eq "d" } {
5082 set ext "d"
5083 break
5086 set src [standard_temp_file $name.$ext]
5087 set obj [standard_temp_file $name.$postfix]
5088 if { $default_compile_flags == "" } {
5089 set compile_flags [concat $compile_flags {debug nowarnings quiet}]
5090 } else {
5091 set compile_flags [concat $compile_flags $default_compile_flags]
5094 gdb_produce_source $src $code
5096 verbose "$name: compiling testfile $src" 2
5097 set lines [gdb_compile $src $obj $type $compile_flags]
5099 file delete $src
5101 if {![string match "" $lines]} {
5102 verbose "$name: compilation failed, returning 0" 2
5103 return 0
5105 return 1
5108 # Compile the code in $code to a file based on $name, using the flags
5109 # $compile_flag as well as debug, nowarning and quiet (unless otherwise
5110 # specified in default_compile_flags).
5111 # Return 1 if code can be compiled
5112 # Delete all created files and objects.
5114 proc gdb_can_simple_compile {name code {type object} {compile_flags ""} {default_compile_flags ""}} {
5115 set ret [gdb_simple_compile $name $code $type $compile_flags temp_obj \
5116 $default_compile_flags]
5117 file delete $temp_obj
5118 return $ret
5121 # As gdb_can_simple_compile, but defaults to using nodebug instead of debug.
5122 proc gdb_can_simple_compile_nodebug {name code {type object} {compile_flags ""}
5123 {default_compile_flags "nodebug nowarning quiet"}} {
5124 return [gdb_can_simple_compile $name $code $type $compile_flags \
5125 $default_compile_flags]
5128 # Some targets need to always link a special object in. Save its path here.
5129 global gdb_saved_set_unbuffered_mode_obj
5130 set gdb_saved_set_unbuffered_mode_obj ""
5132 # Escape STR sufficiently for use on host commandline.
5134 proc escape_for_host { str } {
5135 if { [is_remote host] } {
5136 set map {
5137 {$} {\\$}
5139 } else {
5140 set map {
5141 {$} {\$}
5145 return [string map $map $str]
5148 # Add double quotes around ARGS, sufficiently escaped for use on host
5149 # commandline.
5151 proc quote_for_host { args } {
5152 set str [join $args]
5153 if { [is_remote host] } {
5154 set str [join [list {\"} $str {\"}] ""]
5155 } else {
5156 set str [join [list {"} $str {"}] ""]
5158 return $str
5161 # Compile source files specified by SOURCE into a binary of type TYPE at path
5162 # DEST. gdb_compile is implemented using DejaGnu's target_compile, so the type
5163 # parameter and most options are passed directly to it.
5165 # The type can be one of the following:
5167 # - object: Compile into an object file.
5168 # - executable: Compile and link into an executable.
5169 # - preprocess: Preprocess the source files.
5170 # - assembly: Generate assembly listing.
5172 # The following options are understood and processed by gdb_compile:
5174 # - shlib=so_path: Add SO_PATH to the sources, and enable some target-specific
5175 # quirks to be able to use shared libraries.
5176 # - shlib_load: Link with appropriate libraries to allow the test to
5177 # dynamically load libraries at runtime. For example, on Linux, this adds
5178 # -ldl so that the test can use dlopen.
5179 # - nowarnings: Inhibit all compiler warnings.
5180 # - pie: Force creation of PIE executables.
5181 # - nopie: Prevent creation of PIE executables.
5182 # - macros: Add the required compiler flag to include macro information in
5183 # debug information
5184 # - text_segment=addr: Tell the linker to place the text segment at ADDR.
5185 # - build-id: Ensure the final binary includes a build-id.
5186 # - column-info/no-column-info: Enable/Disable generation of column table
5187 # information.
5189 # And here are some of the not too obscure options understood by DejaGnu that
5190 # influence the compilation:
5192 # - additional_flags=flag: Add FLAG to the compiler flags.
5193 # - libs=library: Add LIBRARY to the libraries passed to the linker. The
5194 # argument can be a file, in which case it's added to the sources, or a
5195 # linker flag.
5196 # - ldflags=flag: Add FLAG to the linker flags.
5197 # - incdir=path: Add PATH to the searched include directories.
5198 # - libdir=path: Add PATH to the linker searched directories.
5199 # - ada, c++, f90, go, rust: Compile the file as Ada, C++,
5200 # Fortran 90, Go or Rust.
5201 # - debug: Build with debug information.
5202 # - optimize: Build with optimization.
5204 proc gdb_compile {source dest type options} {
5205 global GDB_TESTCASE_OPTIONS
5206 global gdb_wrapper_file
5207 global gdb_wrapper_flags
5208 global srcdir
5209 global objdir
5210 global gdb_saved_set_unbuffered_mode_obj
5212 set outdir [file dirname $dest]
5214 # If this is set, calling test_compiler_info will cause recursion.
5215 if { [lsearch -exact $options getting_compiler_info] == -1 } {
5216 set getting_compiler_info false
5217 } else {
5218 set getting_compiler_info true
5221 # Add platform-specific options if a shared library was specified using
5222 # "shlib=librarypath" in OPTIONS.
5223 set new_options {}
5224 if {[lsearch -exact $options rust] != -1} {
5225 # -fdiagnostics-color is not a rustcc option.
5226 } else {
5227 set new_options [universal_compile_options]
5230 # C/C++ specific settings.
5231 if {!$getting_compiler_info
5232 && [lsearch -exact $options rust] == -1
5233 && [lsearch -exact $options ada] == -1
5234 && [lsearch -exact $options f90] == -1
5235 && [lsearch -exact $options go] == -1} {
5237 # Some C/C++ testcases unconditionally pass -Wno-foo as additional
5238 # options to disable some warning. That is OK with GCC, because
5239 # by design, GCC accepts any -Wno-foo option, even if it doesn't
5240 # support -Wfoo. Clang however warns about unknown -Wno-foo by
5241 # default, unless you pass -Wno-unknown-warning-option as well.
5242 # We do that here, so that individual testcases don't have to
5243 # worry about it.
5244 if {[test_compiler_info "clang-*"] || [test_compiler_info "icx-*"]} {
5245 lappend new_options "additional_flags=-Wno-unknown-warning-option"
5246 } elseif {[test_compiler_info "icc-*"]} {
5247 # This is the equivalent for the icc compiler.
5248 lappend new_options "additional_flags=-diag-disable=10148"
5251 # icpx/icx give the following warning if '-g' is used without '-O'.
5253 # icpx: remark: Note that use of '-g' without any
5254 # optimization-level option will turn off most compiler
5255 # optimizations similar to use of '-O0'
5257 # The warning makes dejagnu think that compilation has failed.
5259 # Furthermore, if no -O flag is passed, icx and icc optimize
5260 # the code by default. This breaks assumptions in many GDB
5261 # tests that the code is unoptimized by default.
5263 # To fix both problems, pass the -O0 flag explicitly, if no
5264 # optimization option is given.
5265 if {[test_compiler_info "icx-*"] || [test_compiler_info "icc-*"]} {
5266 if {[lsearch $options optimize=*] == -1
5267 && [lsearch $options additional_flags=-O*] == -1} {
5268 lappend new_options "optimize=-O0"
5272 # Starting with 2021.7.0 (recognized as icc-20-21-7 by GDB) icc and
5273 # icpc are marked as deprecated and both compilers emit the remark
5274 # #10441. To let GDB still compile successfully, we disable these
5275 # warnings here.
5276 if {([lsearch -exact $options c++] != -1
5277 && [test_compiler_info {icc-20-21-[7-9]} c++])
5278 || [test_compiler_info {icc-20-21-[7-9]}]} {
5279 lappend new_options "additional_flags=-diag-disable=10441"
5283 # If the 'build-id' option is used, then ensure that we generate a
5284 # build-id. GCC does this by default, but Clang does not, so
5285 # enable it now.
5286 if {[lsearch -exact $options build-id] > 0
5287 && [test_compiler_info "clang-*"]} {
5288 lappend new_options "additional_flags=-Wl,--build-id"
5291 # Treating .c input files as C++ is deprecated in Clang, so
5292 # explicitly force C++ language.
5293 if { !$getting_compiler_info
5294 && [lsearch -exact $options c++] != -1
5295 && [string match *.c $source] != 0 } {
5297 # gdb_compile cannot handle this combination of options, the
5298 # result is a command like "clang -x c++ foo.c bar.so -o baz"
5299 # which tells Clang to treat bar.so as C++. The solution is
5300 # to call gdb_compile twice--once to compile, once to link--
5301 # either directly, or via build_executable_from_specs.
5302 if { [lsearch $options shlib=*] != -1 } {
5303 error "incompatible gdb_compile options"
5306 if {[test_compiler_info "clang-*"]} {
5307 lappend new_options early_flags=-x\ c++
5311 # Place (and look for) Fortran `.mod` files in the output
5312 # directory for this specific test. For Intel compilers the -J
5313 # option is not supported so instead use the -module flag.
5314 # Additionally, Intel compilers need the -debug-parameters flag set to
5315 # emit debug info for all parameters in modules.
5317 # ifx gives the following warning if '-g' is used without '-O'.
5319 # ifx: remark #10440: Note that use of a debug option
5320 # without any optimization-level option will turnoff most
5321 # compiler optimizations similar to use of '-O0'
5323 # The warning makes dejagnu think that compilation has failed.
5325 # Furthermore, if no -O flag is passed, Intel compilers optimize
5326 # the code by default. This breaks assumptions in many GDB
5327 # tests that the code is unoptimized by default.
5329 # To fix both problems, pass the -O0 flag explicitly, if no
5330 # optimization option is given.
5331 if { !$getting_compiler_info && [lsearch -exact $options f90] != -1 } {
5332 # Fortran compile.
5333 set mod_path [standard_output_file ""]
5334 if { [test_compiler_info {gfortran-*} f90] } {
5335 lappend new_options "additional_flags=-J${mod_path}"
5336 } elseif { [test_compiler_info {ifort-*} f90]
5337 || [test_compiler_info {ifx-*} f90] } {
5338 lappend new_options "additional_flags=-module ${mod_path}"
5339 lappend new_options "additional_flags=-debug-parameters all"
5341 if {[lsearch $options optimize=*] == -1
5342 && [lsearch $options additional_flags=-O*] == -1} {
5343 lappend new_options "optimize=-O0"
5348 set shlib_found 0
5349 set shlib_load 0
5350 foreach opt $options {
5351 if {[regexp {^shlib=(.*)} $opt dummy_var shlib_name]
5352 && $type == "executable"} {
5353 if [test_compiler_info "xlc-*"] {
5354 # IBM xlc compiler doesn't accept shared library named other
5355 # than .so: use "-Wl," to bypass this
5356 lappend source "-Wl,$shlib_name"
5357 } elseif { ([istarget "*-*-mingw*"]
5358 || [istarget *-*-cygwin*]
5359 || [istarget *-*-pe*])} {
5360 lappend source "${shlib_name}.a"
5361 } else {
5362 lappend source $shlib_name
5364 if { $shlib_found == 0 } {
5365 set shlib_found 1
5366 if { ([istarget "*-*-mingw*"]
5367 || [istarget *-*-cygwin*]) } {
5368 lappend new_options "ldflags=-Wl,--enable-auto-import"
5370 if { [test_compiler_info "gcc-*"] || [test_compiler_info "clang-*"] } {
5371 # Undo debian's change in the default.
5372 # Put it at the front to not override any user-provided
5373 # value, and to make sure it appears in front of all the
5374 # shlibs!
5375 lappend new_options "early_flags=-Wl,--no-as-needed"
5378 } elseif { $opt == "shlib_load" && $type == "executable" } {
5379 set shlib_load 1
5380 } elseif { $opt == "getting_compiler_info" } {
5381 # Ignore this setting here as it has been handled earlier in this
5382 # procedure. Do not append it to new_options as this will cause
5383 # recursion.
5384 } elseif {[regexp "^text_segment=(.*)" $opt dummy_var addr]} {
5385 if { [linker_supports_Ttext_segment_flag] } {
5386 # For GNU ld.
5387 lappend new_options "ldflags=-Wl,-Ttext-segment=$addr"
5388 } elseif { [linker_supports_image_base_flag] } {
5389 # For LLVM's lld.
5390 lappend new_options "ldflags=-Wl,--image-base=$addr"
5391 } elseif { [linker_supports_Ttext_flag] } {
5392 # For old GNU gold versions.
5393 lappend new_options "ldflags=-Wl,-Ttext=$addr"
5394 } else {
5395 error "Don't know how to handle text_segment option."
5397 } elseif { $opt == "column-info" } {
5398 # If GCC or clang does not support column-info, compilation
5399 # will fail and the usupported column-info option will be
5400 # reported as such.
5401 if {[test_compiler_info {gcc-*}]} {
5402 lappend new_options "additional_flags=-gcolumn-info"
5404 } elseif {[test_compiler_info {clang-*}]} {
5405 lappend new_options "additional_flags=-gcolumn-info"
5407 } else {
5408 error "Option gcolumn-info not supported by compiler."
5411 } elseif { $opt == "no-column-info" } {
5412 if {[test_compiler_info {gcc-*}]} {
5413 if {[test_compiler_info {gcc-[1-6]-*}]} {
5414 # In this case, don't add the compile line option and
5415 # the result will be the same as using no-column-info
5416 # on a version that supports the option.
5417 warning "gdb_compile option no-column-info not supported, ignoring."
5418 } else {
5419 lappend new_options "additional_flags=-gno-column-info"
5422 } elseif {[test_compiler_info {clang-*}]} {
5423 lappend new_options "additional_flags=-gno-column-info"
5425 } else {
5426 error "Option gno-column-info not supported by compiler."
5429 } else {
5430 lappend new_options $opt
5434 # Ensure stack protector is disabled for GCC, as this causes problems with
5435 # DWARF line numbering.
5436 # See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88432
5437 # This option defaults to on for Debian/Ubuntu.
5438 if { !$getting_compiler_info
5439 && [test_compiler_info {gcc-*-*}]
5440 && !([test_compiler_info {gcc-[0-3]-*}]
5441 || [test_compiler_info {gcc-4-0-*}])
5442 && [lsearch -exact $options rust] == -1} {
5443 # Put it at the front to not override any user-provided value.
5444 lappend new_options "early_flags=-fno-stack-protector"
5447 # hipcc defaults to -O2, so add -O0 to early flags for the hip language.
5448 # If "optimize" is also requested, another -O flag (e.g. -O2) will be added
5449 # to the flags, overriding this -O0.
5450 if {[lsearch -exact $options hip] != -1} {
5451 lappend new_options "early_flags=-O0"
5454 # Because we link with libraries using their basename, we may need
5455 # (depending on the platform) to set a special rpath value, to allow
5456 # the executable to find the libraries it depends on.
5457 if { $shlib_load || $shlib_found } {
5458 if { ([istarget "*-*-mingw*"]
5459 || [istarget *-*-cygwin*]
5460 || [istarget *-*-pe*]) } {
5461 # Do not need anything.
5462 } elseif { [istarget *-*-freebsd*] || [istarget *-*-openbsd*] } {
5463 lappend new_options "ldflags=-Wl,-rpath,${outdir}"
5464 } else {
5465 if { $shlib_load } {
5466 lappend new_options "libs=-ldl"
5468 lappend new_options [escape_for_host {ldflags=-Wl,-rpath,$ORIGIN}]
5471 set options $new_options
5473 if [info exists GDB_TESTCASE_OPTIONS] {
5474 lappend options "additional_flags=$GDB_TESTCASE_OPTIONS"
5476 verbose "options are $options"
5477 verbose "source is $source $dest $type $options"
5479 gdb_wrapper_init
5481 if {[target_info exists needs_status_wrapper] && \
5482 [target_info needs_status_wrapper] != "0" && \
5483 $gdb_wrapper_file != "" } {
5484 lappend options "libs=${gdb_wrapper_file}"
5485 lappend options "ldflags=${gdb_wrapper_flags}"
5488 # Replace the "nowarnings" option with the appropriate additional_flags
5489 # to disable compiler warnings.
5490 set nowarnings [lsearch -exact $options nowarnings]
5491 if {$nowarnings != -1} {
5492 if [target_info exists gdb,nowarnings_flag] {
5493 set flag "additional_flags=[target_info gdb,nowarnings_flag]"
5494 } else {
5495 set flag "additional_flags=-w"
5497 set options [lreplace $options $nowarnings $nowarnings $flag]
5500 # Replace the "pie" option with the appropriate compiler and linker flags
5501 # to enable PIE executables.
5502 set pie [lsearch -exact $options pie]
5503 if {$pie != -1} {
5504 if [target_info exists gdb,pie_flag] {
5505 set flag "additional_flags=[target_info gdb,pie_flag]"
5506 } else {
5507 # For safety, use fPIE rather than fpie. On AArch64, m68k, PowerPC
5508 # and SPARC, fpie can cause compile errors due to the GOT exceeding
5509 # a maximum size. On other architectures the two flags are
5510 # identical (see the GCC manual). Note Debian9 and Ubuntu16.10
5511 # onwards default GCC to using fPIE. If you do require fpie, then
5512 # it can be set using the pie_flag.
5513 set flag "additional_flags=-fPIE"
5515 set options [lreplace $options $pie $pie $flag]
5517 if [target_info exists gdb,pie_ldflag] {
5518 set flag "ldflags=[target_info gdb,pie_ldflag]"
5519 } else {
5520 set flag "ldflags=-pie"
5522 lappend options "$flag"
5525 # Replace the "nopie" option with the appropriate compiler and linker
5526 # flags to disable PIE executables.
5527 set nopie [lsearch -exact $options nopie]
5528 if {$nopie != -1} {
5529 if [target_info exists gdb,nopie_flag] {
5530 set flag "additional_flags=[target_info gdb,nopie_flag]"
5531 } else {
5532 set flag "additional_flags=-fno-pie"
5534 set options [lreplace $options $nopie $nopie $flag]
5536 if [target_info exists gdb,nopie_ldflag] {
5537 set flag "ldflags=[target_info gdb,nopie_ldflag]"
5538 } else {
5539 set flag "ldflags=-no-pie"
5541 lappend options "$flag"
5544 set macros [lsearch -exact $options macros]
5545 if {$macros != -1} {
5546 if { [test_compiler_info "clang-*"] } {
5547 set flag "additional_flags=-fdebug-macro"
5548 } else {
5549 set flag "additional_flags=-g3"
5552 set options [lreplace $options $macros $macros $flag]
5555 if { $type == "executable" } {
5556 if { ([istarget "*-*-mingw*"]
5557 || [istarget "*-*-*djgpp"]
5558 || [istarget "*-*-cygwin*"])} {
5559 # Force output to unbuffered mode, by linking in an object file
5560 # with a global contructor that calls setvbuf.
5562 # Compile the special object separately for two reasons:
5563 # 1) Insulate it from $options.
5564 # 2) Avoid compiling it for every gdb_compile invocation,
5565 # which is time consuming, especially if we're remote
5566 # host testing.
5568 if { $gdb_saved_set_unbuffered_mode_obj == "" } {
5569 verbose "compiling gdb_saved_set_unbuffered_obj"
5570 set unbuf_src ${srcdir}/lib/set_unbuffered_mode.c
5571 set unbuf_obj ${objdir}/set_unbuffered_mode.o
5573 set result [gdb_compile "${unbuf_src}" "${unbuf_obj}" object {nowarnings}]
5574 if { $result != "" } {
5575 return $result
5577 if {[is_remote host]} {
5578 set gdb_saved_set_unbuffered_mode_obj set_unbuffered_mode_saved.o
5579 } else {
5580 set gdb_saved_set_unbuffered_mode_obj ${objdir}/set_unbuffered_mode_saved.o
5582 # Link a copy of the output object, because the
5583 # original may be automatically deleted.
5584 remote_download host $unbuf_obj $gdb_saved_set_unbuffered_mode_obj
5585 } else {
5586 verbose "gdb_saved_set_unbuffered_obj already compiled"
5589 # Rely on the internal knowledge that the global ctors are ran in
5590 # reverse link order. In that case, we can use ldflags to
5591 # avoid copying the object file to the host multiple
5592 # times.
5593 # This object can only be added if standard libraries are
5594 # used. Thus, we need to disable it if -nostdlib option is used
5595 if {[lsearch -regexp $options "-nostdlib"] < 0 } {
5596 lappend options "ldflags=$gdb_saved_set_unbuffered_mode_obj"
5601 cond_wrap [expr $pie != -1 || $nopie != -1] \
5602 with_PIE_multilib_flags_filtered {
5603 set result [target_compile $source $dest $type $options]
5606 # Prune uninteresting compiler (and linker) output.
5607 regsub "Creating library file: \[^\r\n\]*\[\r\n\]+" $result "" result
5609 # Starting with 2021.7.0 icc and icpc are marked as deprecated and both
5610 # compilers emit a remark #10441. To let GDB still compile successfully,
5611 # we disable these warnings. When $getting_compiler_info is true however,
5612 # we do not yet know the compiler (nor its version) and instead prune these
5613 # lines from the compiler output to let the get_compiler_info pass.
5614 if {$getting_compiler_info} {
5615 regsub \
5616 "(icc|icpc): remark #10441: The Intel\\(R\\) C\\+\\+ Compiler Classic \\(ICC\\) is deprecated\[^\r\n\]*" \
5617 "$result" "" result
5620 regsub "\[\r\n\]*$" "$result" "" result
5621 regsub "^\[\r\n\]*" "$result" "" result
5623 if { $type == "executable" && $result == "" \
5624 && ($nopie != -1 || $pie != -1) } {
5625 set is_pie [exec_is_pie "$dest"]
5626 if { $nopie != -1 && $is_pie == 1 } {
5627 set result "nopie failed to prevent PIE executable"
5628 } elseif { $pie != -1 && $is_pie == 0 } {
5629 set result "pie failed to generate PIE executable"
5633 if {[lsearch $options quiet] < 0} {
5634 if { $result != "" } {
5635 clone_output "gdb compile failed, $result"
5638 return $result
5642 # This is just like gdb_compile, above, except that it tries compiling
5643 # against several different thread libraries, to see which one this
5644 # system has.
5645 proc gdb_compile_pthreads {source dest type options} {
5646 if {$type != "executable"} {
5647 return [gdb_compile $source $dest $type $options]
5649 set built_binfile 0
5650 set why_msg "unrecognized error"
5651 foreach lib {-lpthreads -lpthread -lthread ""} {
5652 # This kind of wipes out whatever libs the caller may have
5653 # set. Or maybe theirs will override ours. How infelicitous.
5654 set options_with_lib [concat $options [list libs=$lib quiet]]
5655 set ccout [gdb_compile $source $dest $type $options_with_lib]
5656 switch -regexp -- $ccout {
5657 ".*no posix threads support.*" {
5658 set why_msg "missing threads include file"
5659 break
5661 ".*cannot open -lpthread.*" {
5662 set why_msg "missing runtime threads library"
5664 ".*Can't find library for -lpthread.*" {
5665 set why_msg "missing runtime threads library"
5667 {^$} {
5668 pass "successfully compiled posix threads test case"
5669 set built_binfile 1
5670 break
5674 if {!$built_binfile} {
5675 unsupported "couldn't compile [file tail $source]: ${why_msg}"
5676 return -1
5680 # Build a shared library from SOURCES.
5682 proc gdb_compile_shlib_1 {sources dest options} {
5683 set obj_options $options
5685 set ada 0
5686 if { [lsearch -exact $options "ada"] >= 0 } {
5687 set ada 1
5690 if { [lsearch -exact $options "c++"] >= 0 } {
5691 set info_options "c++"
5692 } elseif { [lsearch -exact $options "f90"] >= 0 } {
5693 set info_options "f90"
5694 } else {
5695 set info_options "c"
5698 switch -glob [test_compiler_info "" ${info_options}] {
5699 "xlc-*" {
5700 lappend obj_options "additional_flags=-qpic"
5702 "clang-*" {
5703 if { [istarget "*-*-cygwin*"]
5704 || [istarget "*-*-mingw*"] } {
5705 lappend obj_options "additional_flags=-fPIC"
5706 } else {
5707 lappend obj_options "additional_flags=-fpic"
5710 "gcc-*" {
5711 if { [istarget "powerpc*-*-aix*"]
5712 || [istarget "rs6000*-*-aix*"]
5713 || [istarget "*-*-cygwin*"]
5714 || [istarget "*-*-mingw*"]
5715 || [istarget "*-*-pe*"] } {
5716 lappend obj_options "additional_flags=-fPIC"
5717 } else {
5718 lappend obj_options "additional_flags=-fpic"
5721 "icc-*" {
5722 lappend obj_options "additional_flags=-fpic"
5724 default {
5725 # don't know what the compiler is...
5726 lappend obj_options "additional_flags=-fPIC"
5730 set outdir [file dirname $dest]
5731 set objects ""
5732 foreach source $sources {
5733 if {[file extension $source] == ".o"} {
5734 # Already a .o file.
5735 lappend objects $source
5736 continue
5739 set sourcebase [file tail $source]
5741 if { $ada } {
5742 # Gnatmake doesn't like object name foo.adb.o, use foo.o.
5743 set sourcebase [file rootname $sourcebase]
5745 set object ${outdir}/${sourcebase}.o
5747 if { $ada } {
5748 # Use gdb_compile_ada_1 instead of gdb_compile_ada to avoid the
5749 # PASS message.
5750 if {[gdb_compile_ada_1 $source $object object \
5751 $obj_options] != ""} {
5752 return -1
5754 } else {
5755 if {[gdb_compile $source $object object \
5756 $obj_options] != ""} {
5757 return -1
5761 lappend objects $object
5764 set link_options $options
5765 if { $ada } {
5766 # If we try to use gnatmake for the link, it will interpret the
5767 # object file as an .adb file. Remove ada from the options to
5768 # avoid it.
5769 set idx [lsearch $link_options "ada"]
5770 set link_options [lreplace $link_options $idx $idx]
5772 if [test_compiler_info "xlc-*"] {
5773 lappend link_options "additional_flags=-qmkshrobj"
5774 } else {
5775 lappend link_options "additional_flags=-shared"
5777 if { ([istarget "*-*-mingw*"]
5778 || [istarget *-*-cygwin*]
5779 || [istarget *-*-pe*]) } {
5780 if { [is_remote host] } {
5781 set name [file tail ${dest}]
5782 } else {
5783 set name ${dest}
5785 lappend link_options "ldflags=-Wl,--out-implib,${name}.a"
5786 } else {
5787 # Set the soname of the library. This causes the linker on ELF
5788 # systems to create the DT_NEEDED entry in the executable referring
5789 # to the soname of the library, and not its absolute path. This
5790 # (using the absolute path) would be problem when testing on a
5791 # remote target.
5793 # In conjunction with setting the soname, we add the special
5794 # rpath=$ORIGIN value when building the executable, so that it's
5795 # able to find the library in its own directory.
5796 set destbase [file tail $dest]
5797 lappend link_options "ldflags=-Wl,-soname,$destbase"
5800 if {[gdb_compile "${objects}" "${dest}" executable $link_options] != ""} {
5801 return -1
5803 if { [is_remote host]
5804 && ([istarget "*-*-mingw*"]
5805 || [istarget *-*-cygwin*]
5806 || [istarget *-*-pe*]) } {
5807 set dest_tail_name [file tail ${dest}]
5808 remote_upload host $dest_tail_name.a ${dest}.a
5809 remote_file host delete $dest_tail_name.a
5812 return ""
5815 # Ignore FLAGS in target board multilib_flags while executing BODY.
5817 proc with_multilib_flags_filtered { flags body } {
5818 global board
5820 # Ignore flags in multilib_flags.
5821 set board [target_info name]
5822 set multilib_flags_orig [board_info $board multilib_flags]
5823 set multilib_flags ""
5824 foreach op $multilib_flags_orig {
5825 if { [lsearch -exact $flags $op] == -1 } {
5826 append multilib_flags " $op"
5830 save_target_board_info { multilib_flags } {
5831 unset_board_info multilib_flags
5832 set_board_info multilib_flags "$multilib_flags"
5833 set result [uplevel 1 $body]
5836 return $result
5839 # Ignore PIE-related flags in target board multilib_flags while executing BODY.
5841 proc with_PIE_multilib_flags_filtered { body } {
5842 set pie_flags [list "-pie" "-no-pie" "-fPIE" "-fno-PIE"]
5843 return [uplevel 1 [list with_multilib_flags_filtered $pie_flags $body]]
5846 # Build a shared library from SOURCES. Ignore target boards PIE-related
5847 # multilib_flags.
5849 proc gdb_compile_shlib {sources dest options} {
5850 with_PIE_multilib_flags_filtered {
5851 set result [gdb_compile_shlib_1 $sources $dest $options]
5854 return $result
5857 # This is just like gdb_compile_shlib, above, except that it tries compiling
5858 # against several different thread libraries, to see which one this
5859 # system has.
5860 proc gdb_compile_shlib_pthreads {sources dest options} {
5861 set built_binfile 0
5862 set why_msg "unrecognized error"
5863 foreach lib {-lpthreads -lpthread -lthread ""} {
5864 # This kind of wipes out whatever libs the caller may have
5865 # set. Or maybe theirs will override ours. How infelicitous.
5866 set options_with_lib [concat $options [list libs=$lib quiet]]
5867 set ccout [gdb_compile_shlib $sources $dest $options_with_lib]
5868 switch -regexp -- $ccout {
5869 ".*no posix threads support.*" {
5870 set why_msg "missing threads include file"
5871 break
5873 ".*cannot open -lpthread.*" {
5874 set why_msg "missing runtime threads library"
5876 ".*Can't find library for -lpthread.*" {
5877 set why_msg "missing runtime threads library"
5879 {^$} {
5880 pass "successfully compiled posix threads shlib test case"
5881 set built_binfile 1
5882 break
5886 if {!$built_binfile} {
5887 unsupported "couldn't compile $sources: ${why_msg}"
5888 return -1
5892 # This is just like gdb_compile_pthreads, above, except that we always add the
5893 # objc library for compiling Objective-C programs
5894 proc gdb_compile_objc {source dest type options} {
5895 set built_binfile 0
5896 set why_msg "unrecognized error"
5897 foreach lib {-lobjc -lpthreads -lpthread -lthread solaris} {
5898 # This kind of wipes out whatever libs the caller may have
5899 # set. Or maybe theirs will override ours. How infelicitous.
5900 if { $lib == "solaris" } {
5901 set lib "-lpthread -lposix4"
5903 if { $lib != "-lobjc" } {
5904 set lib "-lobjc $lib"
5906 set options_with_lib [concat $options [list libs=$lib quiet]]
5907 set ccout [gdb_compile $source $dest $type $options_with_lib]
5908 switch -regexp -- $ccout {
5909 ".*no posix threads support.*" {
5910 set why_msg "missing threads include file"
5911 break
5913 ".*cannot open -lpthread.*" {
5914 set why_msg "missing runtime threads library"
5916 ".*Can't find library for -lpthread.*" {
5917 set why_msg "missing runtime threads library"
5919 {^$} {
5920 pass "successfully compiled objc with posix threads test case"
5921 set built_binfile 1
5922 break
5926 if {!$built_binfile} {
5927 unsupported "couldn't compile [file tail $source]: ${why_msg}"
5928 return -1
5932 # Build an OpenMP program from SOURCE. See prefatory comment for
5933 # gdb_compile, above, for discussion of the parameters to this proc.
5935 proc gdb_compile_openmp {source dest type options} {
5936 lappend options "additional_flags=-fopenmp"
5937 return [gdb_compile $source $dest $type $options]
5940 # Send a command to GDB.
5941 # For options for TYPE see gdb_stdin_log_write
5943 proc send_gdb { string {type standard}} {
5944 gdb_stdin_log_write $string $type
5945 return [remote_send host "$string"]
5948 # Send STRING to the inferior's terminal.
5950 proc send_inferior { string } {
5951 global inferior_spawn_id
5953 if {[catch "send -i $inferior_spawn_id -- \$string" errorInfo]} {
5954 return "$errorInfo"
5955 } else {
5956 return ""
5963 proc gdb_expect { args } {
5964 if { [llength $args] == 2 && [lindex $args 0] != "-re" } {
5965 set atimeout [lindex $args 0]
5966 set expcode [list [lindex $args 1]]
5967 } else {
5968 set expcode $args
5971 # A timeout argument takes precedence, otherwise of all the timeouts
5972 # select the largest.
5973 if [info exists atimeout] {
5974 set tmt $atimeout
5975 } else {
5976 set tmt [get_largest_timeout]
5979 set code [catch \
5980 {uplevel remote_expect host $tmt $expcode} string]
5982 if {$code == 1} {
5983 global errorInfo errorCode
5985 return -code error -errorinfo $errorInfo -errorcode $errorCode $string
5986 } else {
5987 return -code $code $string
5991 # gdb_expect_list TEST SENTINEL LIST -- expect a sequence of outputs
5993 # Check for long sequence of output by parts.
5994 # TEST: is the test message to be printed with the test success/fail.
5995 # SENTINEL: Is the terminal pattern indicating that output has finished.
5996 # LIST: is the sequence of outputs to match.
5997 # If the sentinel is recognized early, it is considered an error.
5999 # Returns:
6000 # 1 if the test failed,
6001 # 0 if the test passes,
6002 # -1 if there was an internal error.
6004 proc gdb_expect_list {test sentinel list} {
6005 global gdb_prompt
6006 set index 0
6007 set ok 1
6009 while { ${index} < [llength ${list}] } {
6010 set pattern [lindex ${list} ${index}]
6011 set index [expr ${index} + 1]
6012 verbose -log "gdb_expect_list pattern: /$pattern/" 2
6013 if { ${index} == [llength ${list}] } {
6014 if { ${ok} } {
6015 gdb_expect {
6016 -re "${pattern}${sentinel}" {
6017 # pass "${test}, pattern ${index} + sentinel"
6019 -re "${sentinel}" {
6020 fail "${test} (pattern ${index} + sentinel)"
6021 set ok 0
6023 -re ".*A problem internal to GDB has been detected" {
6024 fail "${test} (GDB internal error)"
6025 set ok 0
6026 gdb_internal_error_resync
6028 timeout {
6029 fail "${test} (pattern ${index} + sentinel) (timeout)"
6030 set ok 0
6033 } else {
6034 # unresolved "${test}, pattern ${index} + sentinel"
6036 } else {
6037 if { ${ok} } {
6038 gdb_expect {
6039 -re "${pattern}" {
6040 # pass "${test}, pattern ${index}"
6042 -re "${sentinel}" {
6043 fail "${test} (pattern ${index})"
6044 set ok 0
6046 -re ".*A problem internal to GDB has been detected" {
6047 fail "${test} (GDB internal error)"
6048 set ok 0
6049 gdb_internal_error_resync
6051 timeout {
6052 fail "${test} (pattern ${index}) (timeout)"
6053 set ok 0
6056 } else {
6057 # unresolved "${test}, pattern ${index}"
6061 if { ${ok} } {
6062 pass "${test}"
6063 return 0
6064 } else {
6065 return 1
6069 # Spawn the gdb process.
6071 # This doesn't expect any output or do any other initialization,
6072 # leaving those to the caller.
6074 # Overridable function -- you can override this function in your
6075 # baseboard file.
6077 proc gdb_spawn { } {
6078 default_gdb_spawn
6081 # Spawn GDB with CMDLINE_FLAGS appended to the GDBFLAGS global.
6083 proc gdb_spawn_with_cmdline_opts { cmdline_flags } {
6084 global GDBFLAGS
6086 set saved_gdbflags $GDBFLAGS
6088 if {$GDBFLAGS != ""} {
6089 append GDBFLAGS " "
6091 append GDBFLAGS $cmdline_flags
6093 set res [gdb_spawn]
6095 set GDBFLAGS $saved_gdbflags
6097 return $res
6100 # Start gdb running, wait for prompt, and disable the pagers.
6102 # Overridable function -- you can override this function in your
6103 # baseboard file.
6105 proc gdb_start { } {
6106 default_gdb_start
6109 proc gdb_exit { } {
6110 catch default_gdb_exit
6113 # Return true if we can spawn a program on the target and attach to
6114 # it.
6116 proc can_spawn_for_attach { } {
6117 # We use exp_pid to get the inferior's pid, assuming that gives
6118 # back the pid of the program. On remote boards, that would give
6119 # us instead the PID of e.g., the ssh client, etc.
6120 if {[is_remote target]} {
6121 verbose -log "can't spawn for attach (target is remote)"
6122 return 0
6125 # The "attach" command doesn't make sense when the target is
6126 # stub-like, where GDB finds the program already started on
6127 # initial connection.
6128 if {[target_info exists use_gdb_stub]} {
6129 verbose -log "can't spawn for attach (target is stub)"
6130 return 0
6133 # Assume yes.
6134 return 1
6137 # Centralize the failure checking of "attach" command.
6138 # Return 0 if attach failed, otherwise return 1.
6140 proc gdb_attach { testpid args } {
6141 parse_args {
6142 {pattern ""}
6145 if { [llength $args] != 0 } {
6146 error "Unexpected arguments: $args"
6149 gdb_test_multiple "attach $testpid" "attach" {
6150 -re -wrap "Attaching to.*ptrace: Operation not permitted\\." {
6151 unsupported "$gdb_test_name (Operation not permitted)"
6152 return 0
6154 -re -wrap "$pattern" {
6155 pass $gdb_test_name
6156 return 1
6160 return 0
6163 # Start gdb with "--pid $TESTPID" on the command line and wait for the prompt.
6164 # Return 1 if GDB managed to start and attach to the process, 0 otherwise.
6166 proc_with_prefix gdb_spawn_attach_cmdline { testpid } {
6167 if ![can_spawn_for_attach] {
6168 # The caller should have checked can_spawn_for_attach itself
6169 # before getting here.
6170 error "can't spawn for attach with this target/board"
6173 set test "start gdb with --pid"
6174 set res [gdb_spawn_with_cmdline_opts "-quiet --pid=$testpid"]
6175 if { $res != 0 } {
6176 fail $test
6177 return 0
6180 gdb_test_multiple "" "$test" {
6181 -re -wrap "ptrace: Operation not permitted\\." {
6182 unsupported "$gdb_test_name (operation not permitted)"
6183 return 0
6185 -re -wrap "ptrace: No such process\\." {
6186 fail "$gdb_test_name (no such process)"
6187 return 0
6189 -re -wrap "Attaching to process $testpid\r\n.*" {
6190 pass $gdb_test_name
6194 # Check that we actually attached to a process, in case the
6195 # error message is not caught by the patterns above.
6196 gdb_test_multiple "info thread" "" {
6197 -re -wrap "No threads\\." {
6198 fail "$gdb_test_name (no thread)"
6200 -re -wrap "Id.*" {
6201 pass $gdb_test_name
6202 return 1
6206 return 0
6209 # Kill a progress previously started with spawn_wait_for_attach, and
6210 # reap its wait status. PROC_SPAWN_ID is the spawn id associated with
6211 # the process.
6213 proc kill_wait_spawned_process { proc_spawn_id } {
6214 set pid [exp_pid -i $proc_spawn_id]
6216 verbose -log "killing ${pid}"
6217 remote_exec build "kill -9 ${pid}"
6219 verbose -log "closing ${proc_spawn_id}"
6220 catch "close -i $proc_spawn_id"
6221 verbose -log "waiting for ${proc_spawn_id}"
6223 # If somehow GDB ends up still attached to the process here, a
6224 # blocking wait hangs until gdb is killed (or until gdb / the
6225 # ptracer reaps the exit status too, but that won't happen because
6226 # something went wrong.) Passing -nowait makes expect tell Tcl to
6227 # wait for the PID in the background. That's fine because we
6228 # don't care about the exit status. */
6229 wait -nowait -i $proc_spawn_id
6230 clean_up_spawn_id target $proc_spawn_id
6233 # Returns the process id corresponding to the given spawn id.
6235 proc spawn_id_get_pid { spawn_id } {
6236 set testpid [exp_pid -i $spawn_id]
6238 if { [istarget "*-*-cygwin*"] } {
6239 # testpid is the Cygwin PID, GDB uses the Windows PID, which
6240 # might be different due to the way fork/exec works.
6241 set testpid [ exec ps -e | gawk "{ if (\$1 == $testpid) print \$4; }" ]
6244 return $testpid
6247 # Start a set of programs running and then wait for a bit, to be sure
6248 # that they can be attached to. Return a list of processes spawn IDs,
6249 # one element for each process spawned. It's a test error to call
6250 # this when [can_spawn_for_attach] is false.
6252 proc spawn_wait_for_attach { executable_list } {
6253 set spawn_id_list {}
6255 if ![can_spawn_for_attach] {
6256 # The caller should have checked can_spawn_for_attach itself
6257 # before getting here.
6258 error "can't spawn for attach with this target/board"
6261 foreach {executable} $executable_list {
6262 # Note we use Expect's spawn, not Tcl's exec, because with
6263 # spawn we control when to wait for/reap the process. That
6264 # allows killing the process by PID without being subject to
6265 # pid-reuse races.
6266 lappend spawn_id_list [remote_spawn target $executable]
6269 sleep 2
6271 return $spawn_id_list
6275 # gdb_load_cmd -- load a file into the debugger.
6276 # ARGS - additional args to load command.
6277 # return a -1 if anything goes wrong.
6279 proc gdb_load_cmd { args } {
6280 global gdb_prompt
6282 if [target_info exists gdb_load_timeout] {
6283 set loadtimeout [target_info gdb_load_timeout]
6284 } else {
6285 set loadtimeout 1600
6287 send_gdb "load $args\n"
6288 verbose "Timeout is now $loadtimeout seconds" 2
6289 gdb_expect $loadtimeout {
6290 -re "Loading section\[^\r\]*\r\n" {
6291 exp_continue
6293 -re "Start address\[\r\]*\r\n" {
6294 exp_continue
6296 -re "Transfer rate\[\r\]*\r\n" {
6297 exp_continue
6299 -re "Memory access error\[^\r\]*\r\n" {
6300 perror "Failed to load program"
6301 return -1
6303 -re "$gdb_prompt $" {
6304 return 0
6306 -re "(.*)\r\n$gdb_prompt " {
6307 perror "Unexpected response from 'load' -- $expect_out(1,string)"
6308 return -1
6310 timeout {
6311 perror "Timed out trying to load $args."
6312 return -1
6315 return -1
6318 # Invoke "gcore". CORE is the name of the core file to write. TEST
6319 # is the name of the test case. This will return 1 if the core file
6320 # was created, 0 otherwise. If this fails to make a core file because
6321 # this configuration of gdb does not support making core files, it
6322 # will call "unsupported", not "fail". However, if this fails to make
6323 # a core file for some other reason, then it will call "fail".
6325 proc gdb_gcore_cmd {core test} {
6326 global gdb_prompt
6328 set result 0
6330 set re_unsupported \
6331 "(?:Can't create a corefile|Target does not support core file generation\\.)"
6333 with_timeout_factor 3 {
6334 gdb_test_multiple "gcore $core" $test {
6335 -re -wrap "Saved corefile .*" {
6336 pass $test
6337 set result 1
6339 -re -wrap $re_unsupported {
6340 unsupported $test
6345 return $result
6348 # Load core file CORE. TEST is the name of the test case.
6349 # This will record a pass/fail for loading the core file.
6350 # Returns:
6351 # 1 - core file is successfully loaded
6352 # 0 - core file loaded but has a non fatal error
6353 # -1 - core file failed to load
6355 proc gdb_core_cmd { core test } {
6356 global gdb_prompt
6358 gdb_test_multiple "core $core" "$test" {
6359 -re "\\\[Thread debugging using \[^ \r\n\]* enabled\\\]\r\n" {
6360 exp_continue
6362 -re " is not a core dump:.*\r\n$gdb_prompt $" {
6363 fail "$test (bad file format)"
6364 return -1
6366 -re -wrap "[string_to_regexp $core]: No such file or directory.*" {
6367 fail "$test (file not found)"
6368 return -1
6370 -re "Couldn't find .* registers in core file.*\r\n$gdb_prompt $" {
6371 fail "$test (incomplete note section)"
6372 return 0
6374 -re "Core was generated by .*\r\n$gdb_prompt $" {
6375 pass "$test"
6376 return 1
6378 -re ".*$gdb_prompt $" {
6379 fail "$test"
6380 return -1
6382 timeout {
6383 fail "$test (timeout)"
6384 return -1
6387 fail "unsupported output from 'core' command"
6388 return -1
6391 # Return the filename to download to the target and load on the target
6392 # for this shared library. Normally just LIBNAME, unless shared libraries
6393 # for this target have separate link and load images.
6395 proc shlib_target_file { libname } {
6396 return $libname
6399 # Return the filename GDB will load symbols from when debugging this
6400 # shared library. Normally just LIBNAME, unless shared libraries for
6401 # this target have separate link and load images.
6403 proc shlib_symbol_file { libname } {
6404 return $libname
6407 # Return the filename to download to the target and load for this
6408 # executable. Normally just BINFILE unless it is renamed to something
6409 # else for this target.
6411 proc exec_target_file { binfile } {
6412 return $binfile
6415 # Return the filename GDB will load symbols from when debugging this
6416 # executable. Normally just BINFILE unless executables for this target
6417 # have separate files for symbols.
6419 proc exec_symbol_file { binfile } {
6420 return $binfile
6423 # Rename the executable file. Normally this is just BINFILE1 being renamed
6424 # to BINFILE2, but some targets require multiple binary files.
6425 proc gdb_rename_execfile { binfile1 binfile2 } {
6426 file rename -force [exec_target_file ${binfile1}] \
6427 [exec_target_file ${binfile2}]
6428 if { [exec_target_file ${binfile1}] != [exec_symbol_file ${binfile1}] } {
6429 file rename -force [exec_symbol_file ${binfile1}] \
6430 [exec_symbol_file ${binfile2}]
6434 # "Touch" the executable file to update the date. Normally this is just
6435 # BINFILE, but some targets require multiple files.
6436 proc gdb_touch_execfile { binfile } {
6437 set time [clock seconds]
6438 file mtime [exec_target_file ${binfile}] $time
6439 if { [exec_target_file ${binfile}] != [exec_symbol_file ${binfile}] } {
6440 file mtime [exec_symbol_file ${binfile}] $time
6444 # Override of dejagnu's remote_upload, which doesn't handle remotedir.
6446 rename remote_upload dejagnu_remote_upload
6447 proc remote_upload { dest srcfile args } {
6448 if { [is_remote $dest] && [board_info $dest exists remotedir] } {
6449 set remotedir [board_info $dest remotedir]
6450 if { ![string match "$remotedir*" $srcfile] } {
6451 # Use hardcoded '/' as separator, as in dejagnu's remote_download.
6452 set srcfile $remotedir/$srcfile
6456 return [dejagnu_remote_upload $dest $srcfile {*}$args]
6459 # Like remote_download but provides a gdb-specific behavior.
6461 # If the destination board is remote, the local file FROMFILE is transferred as
6462 # usual with remote_download to TOFILE on the remote board. The destination
6463 # filename is added to the CLEANFILES global, so it can be cleaned up at the
6464 # end of the test.
6466 # If the destination board is local, the destination path TOFILE is passed
6467 # through standard_output_file, and FROMFILE is copied there.
6469 # In both cases, if TOFILE is omitted, it defaults to the [file tail] of
6470 # FROMFILE.
6472 proc gdb_remote_download {dest fromfile {tofile {}}} {
6473 # If TOFILE is not given, default to the same filename as FROMFILE.
6474 if {[string length $tofile] == 0} {
6475 set tofile [file tail $fromfile]
6478 if {[is_remote $dest]} {
6479 # When the DEST is remote, we simply send the file to DEST.
6480 global cleanfiles_target cleanfiles_host
6482 set destname [remote_download $dest $fromfile $tofile]
6483 if { $dest == "target" } {
6484 lappend cleanfiles_target $destname
6485 } elseif { $dest == "host" } {
6486 lappend cleanfiles_host $destname
6489 return $destname
6490 } else {
6491 # When the DEST is local, we copy the file to the test directory (where
6492 # the executable is).
6494 # Note that we pass TOFILE through standard_output_file, regardless of
6495 # whether it is absolute or relative, because we don't want the tests
6496 # to be able to write outside their standard output directory.
6498 set tofile [standard_output_file $tofile]
6500 file copy -force $fromfile $tofile
6502 return $tofile
6506 # Copy shlib FILE to the target.
6508 proc gdb_download_shlib { file } {
6509 set target_file [shlib_target_file $file]
6510 if { [is_remote host] } {
6511 remote_download host $target_file
6513 return [gdb_remote_download target $target_file]
6516 # Set solib-search-path to allow gdb to locate shlib FILE.
6518 proc gdb_locate_shlib { file } {
6519 global gdb_spawn_id
6521 if ![info exists gdb_spawn_id] {
6522 perror "gdb_load_shlib: GDB is not running"
6525 if { [is_remote target] || [is_remote host] } {
6526 # If the target or host is remote, we need to tell gdb where to find
6527 # the libraries.
6528 } else {
6529 return
6532 # We could set this even when not testing remotely, but a user
6533 # generally won't set it unless necessary. In order to make the tests
6534 # more like the real-life scenarios, we don't set it for local testing.
6535 if { [is_remote host] } {
6536 set solib_search_path [board_info host remotedir]
6537 if { $solib_search_path == "" } {
6538 set solib_search_path .
6540 } else {
6541 set solib_search_path [file dirname $file]
6544 gdb_test_no_output "set solib-search-path $solib_search_path" \
6545 "set solib-search-path for [file tail $file]"
6548 # Copy shlib FILE to the target and set solib-search-path to allow gdb to
6549 # locate it.
6551 proc gdb_load_shlib { file } {
6552 set dest [gdb_download_shlib $file]
6553 gdb_locate_shlib $file
6554 return $dest
6558 # gdb_load -- load a file into the debugger. Specifying no file
6559 # defaults to the executable currently being debugged.
6560 # The return value is 0 for success, -1 for failure.
6561 # Many files in config/*.exp override this procedure.
6563 proc gdb_load { arg } {
6564 if { $arg != "" } {
6565 return [gdb_file_cmd $arg]
6567 return 0
6571 # with_set -- Execute BODY and set VAR temporary to VAL for the
6572 # duration.
6574 proc with_set { var val body } {
6575 set save ""
6576 set show_re \
6577 "is (\[^\r\n\]+)\\."
6578 gdb_test_multiple "show $var" "" {
6579 -re -wrap $show_re {
6580 set save $expect_out(1,string)
6584 # Handle 'set to "auto" (currently "i386")'.
6585 set save [regsub {^set to} $save ""]
6586 set save [regsub {\([^\r\n]+\)$} $save ""]
6587 set save [string trim $save]
6588 set save [regsub -all {^"|"$} $save ""]
6590 if { $save == "" } {
6591 perror "Did not manage to set $var"
6592 } else {
6593 # Set var.
6594 gdb_test_multiple "set $var $val" "" {
6595 -re -wrap "^" {
6597 -re -wrap " is set to \"?$val\"?\\." {
6602 set code [catch {uplevel 1 $body} result]
6604 # Restore saved setting.
6605 if { $save != "" } {
6606 gdb_test_multiple "set $var $save" "" {
6607 -re -wrap "^" {
6609 -re -wrap "is set to \"?$save\"?( \\(\[^)\]*\\))?\\." {
6614 if {$code == 1} {
6615 global errorInfo errorCode
6616 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
6617 } else {
6618 return -code $code $result
6623 # with_complaints -- Execute BODY and set complaints temporary to N for the
6624 # duration.
6626 proc with_complaints { n body } {
6627 return [uplevel [list with_set complaints $n $body]]
6631 # gdb_load_no_complaints -- As gdb_load, but in addition verifies that
6632 # loading caused no symbol reading complaints.
6634 proc gdb_load_no_complaints { arg } {
6635 global gdb_prompt gdb_file_cmd_msg decimal
6637 # Temporarily set complaint to a small non-zero number.
6638 with_complaints 5 {
6639 gdb_load $arg
6642 # Verify that there were no complaints.
6643 set re \
6644 [multi_line \
6645 "^(Reading symbols from \[^\r\n\]*" \
6646 ")+(Expanding full symbols from \[^\r\n\]*" \
6647 ")?$gdb_prompt $"]
6648 gdb_assert {[regexp $re $gdb_file_cmd_msg]} "No complaints"
6651 # gdb_reload -- load a file into the target. Called before "running",
6652 # either the first time or after already starting the program once,
6653 # for remote targets. Most files that override gdb_load should now
6654 # override this instead.
6656 # INFERIOR_ARGS contains the arguments to pass to the inferiors, as a
6657 # single string to get interpreted by a shell. If the target board
6658 # overriding gdb_reload is a "stub", then it should arrange things such
6659 # these arguments make their way to the inferior process.
6661 proc gdb_reload { {inferior_args {}} } {
6662 # For the benefit of existing configurations, default to gdb_load.
6663 # Specifying no file defaults to the executable currently being
6664 # debugged.
6665 return [gdb_load ""]
6668 proc gdb_continue { function } {
6669 global decimal
6671 return [gdb_test "continue" ".*Breakpoint $decimal, $function .*" "continue to $function"]
6674 # Clean the directory containing the standard output files.
6676 proc clean_standard_output_dir {} {
6677 if { [info exists ::GDB_PERFTEST_MODE] && $::GDB_PERFTEST_MODE == "run" } {
6678 # Don't clean, use $GDB_PERFTEST_MODE == compile results.
6679 return
6682 # Directory containing the standard output files.
6683 set standard_output_dir [file normalize [standard_output_file ""]]
6685 # Ensure that standard_output_dir is clean, or only contains
6686 # gdb.log / gdb.sum.
6687 set log_file_info [split [log_file -info]]
6688 set log_file [file normalize [lindex $log_file_info end]]
6689 if { $log_file == [file normalize [standard_output_file gdb.log]] } {
6690 # Dir already contains active gdb.log. Don't remove the dir, but
6691 # check that it's clean otherwise.
6692 set res [glob -directory $standard_output_dir -tails *]
6693 set ok 1
6694 foreach f $res {
6695 if { $f == "gdb.log" } {
6696 continue
6698 if { $f == "gdb.sum" } {
6699 continue
6701 set ok 0
6703 if { !$ok } {
6704 error "standard output dir not clean"
6706 } else {
6707 # Start with a clean dir.
6708 remote_exec build "rm -rf $standard_output_dir"
6713 # Default implementation of gdb_init.
6714 proc default_gdb_init { test_file_name } {
6715 global gdb_wrapper_initialized
6716 global gdb_wrapper_target
6717 global gdb_test_file_name
6718 global cleanfiles_target
6719 global cleanfiles_host
6720 global pf_prefix
6722 # Reset the timeout value to the default. This way, any testcase
6723 # that changes the timeout value without resetting it cannot affect
6724 # the timeout used in subsequent testcases.
6725 global gdb_test_timeout
6726 global timeout
6727 set timeout $gdb_test_timeout
6729 if { [regexp ".*gdb\.reverse\/.*" $test_file_name]
6730 && [target_info exists gdb_reverse_timeout] } {
6731 set timeout [target_info gdb_reverse_timeout]
6734 # If GDB_INOTIFY is given, check for writes to '.'. This is a
6735 # debugging tool to help confirm that the test suite is
6736 # parallel-safe. You need "inotifywait" from the
6737 # inotify-tools package to use this.
6738 global GDB_INOTIFY inotify_pid
6739 if {[info exists GDB_INOTIFY] && ![info exists inotify_pid]} {
6740 global outdir tool inotify_log_file
6742 set exclusions {outputs temp gdb[.](log|sum) cache}
6743 set exclusion_re ([join $exclusions |])
6745 set inotify_log_file [standard_temp_file inotify.out]
6746 set inotify_pid [exec inotifywait -r -m -e move,create,delete . \
6747 --exclude $exclusion_re \
6748 |& tee -a $outdir/$tool.log $inotify_log_file &]
6750 # Wait for the watches; hopefully this is long enough.
6751 sleep 2
6753 # Clear the log so that we don't emit a warning the first time
6754 # we check it.
6755 set fd [open $inotify_log_file w]
6756 close $fd
6759 # Block writes to all banned variables, and invocation of all
6760 # banned procedures...
6761 global banned_variables
6762 global banned_procedures
6763 global banned_traced
6764 if (!$banned_traced) {
6765 foreach banned_var $banned_variables {
6766 global "$banned_var"
6767 trace add variable "$banned_var" write error
6769 foreach banned_proc $banned_procedures {
6770 global "$banned_proc"
6771 trace add execution "$banned_proc" enter error
6773 set banned_traced 1
6776 # We set LC_ALL, LC_CTYPE, and LANG to C so that we get the same
6777 # messages as expected.
6778 setenv LC_ALL C
6779 setenv LC_CTYPE C
6780 setenv LANG C
6782 # Don't let a .inputrc file or an existing setting of INPUTRC mess
6783 # up the test results. Certain tests (style tests and TUI tests)
6784 # want to set the terminal to a non-"dumb" value, and for those we
6785 # want to disable bracketed paste mode. Versions of Readline
6786 # before 8.0 will not understand this and will issue a warning.
6787 # We tried using a $if to guard it, but Readline 8.1 had a bug in
6788 # its version-comparison code that prevented this for working.
6789 setenv INPUTRC [cached_file inputrc "set enable-bracketed-paste off"]
6791 # This disables style output, which would interfere with many
6792 # tests.
6793 setenv NO_COLOR sorry
6795 # This setting helps detect bugs in the Python code and doesn't
6796 # seem to have a significant downside for the tests.
6797 setenv PYTHONMALLOC malloc_debug
6799 # If DEBUGINFOD_URLS is set, gdb will try to download sources and
6800 # debug info for f.i. system libraries. Prevent this.
6801 if { [is_remote host] } {
6802 # See initialization of INTERNAL_GDBFLAGS.
6803 } else {
6804 # Using "set debuginfod enabled off" in INTERNAL_GDBFLAGS interferes
6805 # with the gdb.debuginfod test-cases, so use the unsetenv method for
6806 # non-remote host.
6807 unset -nocomplain ::env(DEBUGINFOD_URLS)
6810 # Ensure that GDBHISTFILE and GDBHISTSIZE are removed from the
6811 # environment, we don't want these modifications to the history
6812 # settings.
6813 unset -nocomplain ::env(GDBHISTFILE)
6814 unset -nocomplain ::env(GDBHISTSIZE)
6816 # Ensure that XDG_CONFIG_HOME is not set. Some tests setup a fake
6817 # home directory in order to test loading settings from gdbinit.
6818 # If XDG_CONFIG_HOME is set then GDB will load a gdbinit from
6819 # there (if one is present) rather than the home directory setup
6820 # in the test.
6821 unset -nocomplain ::env(XDG_CONFIG_HOME)
6823 # Initialize GDB's pty with a fixed size, to make sure we avoid pagination
6824 # during startup. See "man expect" for details about stty_init.
6825 global stty_init
6826 set stty_init "rows 25 cols 80"
6828 # Some tests (for example gdb.base/maint.exp) shell out from gdb to use
6829 # grep. Clear GREP_OPTIONS to make the behavior predictable,
6830 # especially having color output turned on can cause tests to fail.
6831 setenv GREP_OPTIONS ""
6833 # Clear $gdbserver_reconnect_p.
6834 global gdbserver_reconnect_p
6835 set gdbserver_reconnect_p 1
6836 unset gdbserver_reconnect_p
6838 # Clear $last_loaded_file
6839 global last_loaded_file
6840 unset -nocomplain last_loaded_file
6842 # Reset GDB number of instances
6843 global gdb_instances
6844 set gdb_instances 0
6846 set cleanfiles_target {}
6847 set cleanfiles_host {}
6849 set gdb_test_file_name [file rootname [file tail $test_file_name]]
6851 clean_standard_output_dir
6853 # Make sure that the wrapper is rebuilt
6854 # with the appropriate multilib option.
6855 if { $gdb_wrapper_target != [current_target_name] } {
6856 set gdb_wrapper_initialized 0
6859 # Unlike most tests, we have a small number of tests that generate
6860 # a very large amount of output. We therefore increase the expect
6861 # buffer size to be able to contain the entire test output. This
6862 # is especially needed by gdb.base/info-macros.exp.
6863 match_max -d 65536
6864 # Also set this value for the currently running GDB.
6865 match_max [match_max -d]
6867 # We want to add the name of the TCL testcase to the PASS/FAIL messages.
6868 set pf_prefix "[file tail [file dirname $test_file_name]]/[file tail $test_file_name]:"
6870 global gdb_prompt
6871 if [target_info exists gdb_prompt] {
6872 set gdb_prompt [target_info gdb_prompt]
6873 } else {
6874 set gdb_prompt "\\(gdb\\)"
6876 global use_gdb_stub
6877 if [info exists use_gdb_stub] {
6878 unset use_gdb_stub
6881 gdb_setup_known_globals
6883 if { [info procs ::gdb_tcl_unknown] != "" } {
6884 # Dejagnu overrides proc unknown. The dejagnu version may trigger in a
6885 # test-case but abort the entire test run. To fix this, we install a
6886 # local version here, which reverts dejagnu's override, and restore
6887 # dejagnu's version in gdb_finish.
6888 rename ::unknown ::dejagnu_unknown
6889 proc unknown { args } {
6890 # Use tcl's unknown.
6891 set cmd [lindex $args 0]
6892 unresolved "testcase aborted due to invalid command name: $cmd"
6893 return [uplevel 1 ::gdb_tcl_unknown $args]
6897 # Dejagnu version 1.6.3 and later produce an unresolved at the end of a
6898 # testcase if an error triggered, resetting errcnt and warncnt to 0, in
6899 # order to avoid errors in one test-case influencing the following
6900 # test-case. Do this manually here, to support older versions.
6901 global errcnt
6902 global warncnt
6903 set errcnt 0
6904 set warncnt 0
6907 # Return a path using GDB_PARALLEL.
6908 # ARGS is a list of path elements to append to "$objdir/$GDB_PARALLEL".
6909 # GDB_PARALLEL must be defined, the caller must check.
6911 # The default value for GDB_PARALLEL is, canonically, ".".
6912 # The catch is that tests don't expect an additional "./" in file paths so
6913 # omit any directory for the default case.
6914 # GDB_PARALLEL is written as "yes" for the default case in Makefile.in to mark
6915 # its special handling.
6917 proc make_gdb_parallel_path { args } {
6918 global GDB_PARALLEL objdir
6919 set joiner [list "file" "join" $objdir]
6920 if { [info exists GDB_PARALLEL] && $GDB_PARALLEL != "yes" } {
6921 lappend joiner $GDB_PARALLEL
6923 set joiner [concat $joiner $args]
6924 return [eval $joiner]
6927 # Turn BASENAME into a full file name in the standard output
6928 # directory. It is ok if BASENAME is the empty string; in this case
6929 # the directory is returned.
6931 proc standard_output_file {basename} {
6932 global objdir subdir gdb_test_file_name
6934 set dir [make_gdb_parallel_path outputs $subdir $gdb_test_file_name]
6935 file mkdir $dir
6936 # If running on MinGW, replace /c/foo with c:/foo
6937 if { [ishost *-*-mingw*] } {
6938 set dir [exec sh -c "cd ${dir} && pwd -W"]
6940 return [file join $dir $basename]
6943 # Turn BASENAME into a file name on host.
6945 proc host_standard_output_file { basename } {
6946 if { [is_remote host] } {
6947 set remotedir [board_info host remotedir]
6948 if { $remotedir == "" } {
6949 if { $basename == "" } {
6950 return "."
6952 return $basename
6953 } else {
6954 return [join [list $remotedir $basename] "/"]
6956 } else {
6957 return [standard_output_file $basename]
6961 # Turn BASENAME into a full file name in the standard output directory. If
6962 # GDB has been launched more than once then append the count, starting with
6963 # a ".1" postfix.
6965 proc standard_output_file_with_gdb_instance {basename} {
6966 global gdb_instances
6967 set count $gdb_instances
6969 if {$count == 0} {
6970 return [standard_output_file $basename]
6972 return [standard_output_file ${basename}.${count}]
6975 # Return the name of a file in our standard temporary directory.
6977 proc standard_temp_file {basename} {
6978 # Since a particular runtest invocation is only executing a single test
6979 # file at any given time, we can use the runtest pid to build the
6980 # path of the temp directory.
6981 set dir [make_gdb_parallel_path temp [pid]]
6982 file mkdir $dir
6983 return [file join $dir $basename]
6986 # Rename file A to file B, if B does not already exists. Otherwise, leave B
6987 # as is and delete A. Return 1 if rename happened.
6989 proc tentative_rename { a b } {
6990 global errorInfo errorCode
6991 set code [catch {file rename -- $a $b} result]
6992 if { $code == 1 && [lindex $errorCode 0] == "POSIX" \
6993 && [lindex $errorCode 1] == "EEXIST" } {
6994 file delete $a
6995 return 0
6997 if {$code == 1} {
6998 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
6999 } elseif {$code > 1} {
7000 return -code $code $result
7002 return 1
7005 # Create a file with name FILENAME and contents TXT in the cache directory.
7006 # If EXECUTABLE, mark the new file for execution.
7008 proc cached_file { filename txt {executable 0}} {
7009 set filename [make_gdb_parallel_path cache $filename]
7011 if { [file exists $filename] } {
7012 return $filename
7015 set dir [file dirname $filename]
7016 file mkdir $dir
7018 set tmp_filename $filename.[pid]
7019 set fd [open $tmp_filename w]
7020 puts $fd $txt
7021 close $fd
7023 if { $executable } {
7024 exec chmod +x $tmp_filename
7026 tentative_rename $tmp_filename $filename
7028 return $filename
7031 # Return a wrapper around gdb that prevents generating a core file.
7033 proc gdb_no_core { } {
7034 set script \
7035 [list \
7036 "ulimit -c 0" \
7037 [join [list exec $::GDB {"$@"}]]]
7038 set script [join $script "\n"]
7039 return [cached_file gdb-no-core.sh $script 1]
7042 # Set 'testfile', 'srcfile', and 'binfile'.
7044 # ARGS is a list of source file specifications.
7045 # Without any arguments, the .exp file's base name is used to
7046 # compute the source file name. The ".c" extension is added in this case.
7047 # If ARGS is not empty, each entry is a source file specification.
7048 # If the specification starts with a "." or "-", it is treated as a suffix
7049 # to append to the .exp file's base name.
7050 # If the specification is the empty string, it is treated as if it
7051 # were ".c".
7052 # Otherwise it is a file name.
7053 # The first file in the list is used to set the 'srcfile' global.
7054 # Each subsequent name is used to set 'srcfile2', 'srcfile3', etc.
7056 # Most tests should call this without arguments.
7058 # If a completely different binary file name is needed, then it
7059 # should be handled in the .exp file with a suitable comment.
7061 proc standard_testfile {args} {
7062 global gdb_test_file_name
7063 global subdir
7064 global gdb_test_file_last_vars
7066 # Outputs.
7067 global testfile binfile
7069 set testfile $gdb_test_file_name
7070 set binfile [standard_output_file ${testfile}]
7072 if {[llength $args] == 0} {
7073 set args .c
7076 # Unset our previous output variables.
7077 # This can help catch hidden bugs.
7078 if {[info exists gdb_test_file_last_vars]} {
7079 foreach varname $gdb_test_file_last_vars {
7080 global $varname
7081 catch {unset $varname}
7084 # 'executable' is often set by tests.
7085 set gdb_test_file_last_vars {executable}
7087 set suffix ""
7088 foreach arg $args {
7089 set varname srcfile$suffix
7090 global $varname
7092 # Handle an extension.
7093 if {$arg == ""} {
7094 set arg $testfile.c
7095 } else {
7096 set first [string range $arg 0 0]
7097 if { $first == "." || $first == "-" } {
7098 set arg $testfile$arg
7102 set $varname $arg
7103 lappend gdb_test_file_last_vars $varname
7105 if {$suffix == ""} {
7106 set suffix 2
7107 } else {
7108 incr suffix
7113 # The default timeout used when testing GDB commands. We want to use
7114 # the same timeout as the default dejagnu timeout, unless the user has
7115 # already provided a specific value (probably through a site.exp file).
7116 global gdb_test_timeout
7117 if ![info exists gdb_test_timeout] {
7118 set gdb_test_timeout $timeout
7121 # A list of global variables that GDB testcases should not use.
7122 # We try to prevent their use by monitoring write accesses and raising
7123 # an error when that happens.
7124 set banned_variables { bug_id prms_id }
7126 # A list of procedures that GDB testcases should not use.
7127 # We try to prevent their use by monitoring invocations and raising
7128 # an error when that happens.
7129 set banned_procedures { strace }
7131 # gdb_init is called by runtest at start, but also by several
7132 # tests directly; gdb_finish is only called from within runtest after
7133 # each test source execution.
7134 # Placing several traces by repetitive calls to gdb_init leads
7135 # to problems, as only one trace is removed in gdb_finish.
7136 # To overcome this possible problem, we add a variable that records
7137 # if the banned variables and procedures are already traced.
7138 set banned_traced 0
7140 # Global array that holds the name of all global variables at the time
7141 # a test script is started. After the test script has completed any
7142 # global not in this list is deleted.
7143 array set gdb_known_globals {}
7145 # Setup the GDB_KNOWN_GLOBALS array with the names of all current
7146 # global variables.
7147 proc gdb_setup_known_globals {} {
7148 global gdb_known_globals
7150 array set gdb_known_globals {}
7151 foreach varname [info globals] {
7152 set gdb_known_globals($varname) 1
7156 # Cleanup the global namespace. Any global not in the
7157 # GDB_KNOWN_GLOBALS array is unset, this ensures we don't "leak"
7158 # globals from one test script to another.
7159 proc gdb_cleanup_globals {} {
7160 global gdb_known_globals gdb_persistent_globals
7162 foreach varname [info globals] {
7163 if {![info exists gdb_known_globals($varname)]} {
7164 if { [info exists gdb_persistent_globals($varname)] } {
7165 continue
7167 uplevel #0 unset $varname
7172 # Create gdb_tcl_unknown, a copy tcl's ::unknown, provided it's present as a
7173 # proc.
7174 set temp [interp create]
7175 if { [interp eval $temp "info procs ::unknown"] != "" } {
7176 set old_args [interp eval $temp "info args ::unknown"]
7177 set old_body [interp eval $temp "info body ::unknown"]
7178 eval proc gdb_tcl_unknown {$old_args} {$old_body}
7180 interp delete $temp
7181 unset temp
7183 # GDB implementation of ${tool}_init. Called right before executing the
7184 # test-case.
7185 # Overridable function -- you can override this function in your
7186 # baseboard file.
7187 proc gdb_init { args } {
7188 # A baseboard file overriding this proc and calling the default version
7189 # should behave the same as this proc. So, don't add code here, but to
7190 # the default version instead.
7191 return [default_gdb_init {*}$args]
7194 # GDB implementation of ${tool}_finish. Called right after executing the
7195 # test-case.
7196 proc gdb_finish { } {
7197 global gdbserver_reconnect_p
7198 global gdb_prompt
7199 global cleanfiles_target
7200 global cleanfiles_host
7201 global known_globals
7203 if { [info procs ::gdb_tcl_unknown] != "" } {
7204 # Restore dejagnu's version of proc unknown.
7205 rename ::unknown ""
7206 rename ::dejagnu_unknown ::unknown
7209 # Exit first, so that the files are no longer in use.
7210 gdb_exit
7212 if { [llength $cleanfiles_target] > 0 } {
7213 eval remote_file target delete $cleanfiles_target
7214 set cleanfiles_target {}
7216 if { [llength $cleanfiles_host] > 0 } {
7217 eval remote_file host delete $cleanfiles_host
7218 set cleanfiles_host {}
7221 # Unblock write access to the banned variables. Dejagnu typically
7222 # resets some of them between testcases.
7223 global banned_variables
7224 global banned_procedures
7225 global banned_traced
7226 if ($banned_traced) {
7227 foreach banned_var $banned_variables {
7228 global "$banned_var"
7229 trace remove variable "$banned_var" write error
7231 foreach banned_proc $banned_procedures {
7232 global "$banned_proc"
7233 trace remove execution "$banned_proc" enter error
7235 set banned_traced 0
7238 global gdb_finish_hooks
7239 foreach gdb_finish_hook $gdb_finish_hooks {
7240 $gdb_finish_hook
7242 set gdb_finish_hooks [list]
7244 gdb_cleanup_globals
7247 global debug_format
7248 set debug_format "unknown"
7250 # Run the gdb command "info source" and extract the debugging format
7251 # information from the output and save it in debug_format.
7253 proc get_debug_format { } {
7254 global gdb_prompt
7255 global expect_out
7256 global debug_format
7258 set debug_format "unknown"
7259 send_gdb "info source\n"
7260 gdb_expect 10 {
7261 -re "Compiled with (.*) debugging format.\r\n.*$gdb_prompt $" {
7262 set debug_format $expect_out(1,string)
7263 verbose "debug format is $debug_format"
7264 return 1
7266 -re "No current source file.\r\n$gdb_prompt $" {
7267 perror "get_debug_format used when no current source file"
7268 return 0
7270 -re "$gdb_prompt $" {
7271 warning "couldn't check debug format (no valid response)."
7272 return 1
7274 timeout {
7275 warning "couldn't check debug format (timeout)."
7276 return 1
7281 # Return true if FORMAT matches the debug format the current test was
7282 # compiled with. FORMAT is a shell-style globbing pattern; it can use
7283 # `*', `[...]', and so on.
7285 # This function depends on variables set by `get_debug_format', above.
7287 proc test_debug_format {format} {
7288 global debug_format
7290 return [expr [string match $format $debug_format] != 0]
7293 # Like setup_xfail, but takes the name of a debug format (DWARF 1,
7294 # COFF, stabs, etc). If that format matches the format that the
7295 # current test was compiled with, then the next test is expected to
7296 # fail for any target. Returns 1 if the next test or set of tests is
7297 # expected to fail, 0 otherwise (or if it is unknown). Must have
7298 # previously called get_debug_format.
7299 proc setup_xfail_format { format } {
7300 set ret [test_debug_format $format]
7302 if {$ret} {
7303 setup_xfail "*-*-*"
7305 return $ret
7308 # gdb_get_line_number TEXT [FILE]
7310 # Search the source file FILE, and return the line number of the
7311 # first line containing TEXT. If no match is found, an error is thrown.
7313 # TEXT is a string literal, not a regular expression.
7315 # The default value of FILE is "$srcdir/$subdir/$srcfile". If FILE is
7316 # specified, and does not start with "/", then it is assumed to be in
7317 # "$srcdir/$subdir". This is awkward, and can be fixed in the future,
7318 # by changing the callers and the interface at the same time.
7319 # In particular: gdb.base/break.exp, gdb.base/condbreak.exp,
7320 # gdb.base/ena-dis-br.exp.
7322 # Use this function to keep your test scripts independent of the
7323 # exact line numbering of the source file. Don't write:
7325 # send_gdb "break 20"
7327 # This means that if anyone ever edits your test's source file,
7328 # your test could break. Instead, put a comment like this on the
7329 # source file line you want to break at:
7331 # /* breakpoint spot: frotz.exp: test name */
7333 # and then write, in your test script (which we assume is named
7334 # frotz.exp):
7336 # send_gdb "break [gdb_get_line_number "frotz.exp: test name"]\n"
7338 # (Yes, Tcl knows how to handle the nested quotes and brackets.
7339 # Try this:
7340 # $ tclsh
7341 # % puts "foo [lindex "bar baz" 1]"
7342 # foo baz
7343 # %
7344 # Tcl is quite clever, for a little stringy language.)
7346 # ===
7348 # The previous implementation of this procedure used the gdb search command.
7349 # This version is different:
7351 # . It works with MI, and it also works when gdb is not running.
7353 # . It operates on the build machine, not the host machine.
7355 # . For now, this implementation fakes a current directory of
7356 # $srcdir/$subdir to be compatible with the old implementation.
7357 # This will go away eventually and some callers will need to
7358 # be changed.
7360 # . The TEXT argument is literal text and matches literally,
7361 # not a regular expression as it was before.
7363 # . State changes in gdb, such as changing the current file
7364 # and setting $_, no longer happen.
7366 # After a bit of time we can forget about the differences from the
7367 # old implementation.
7369 # --chastain 2004-08-05
7371 proc gdb_get_line_number { text { file "" } } {
7372 global srcdir
7373 global subdir
7374 global srcfile
7376 if {"$file" == ""} {
7377 set file "$srcfile"
7379 if {![regexp "^/" "$file"]} {
7380 set file "$srcdir/$subdir/$file"
7383 if {[catch { set fd [open "$file"] } message]} {
7384 error "$message"
7387 set found -1
7388 for { set line 1 } { 1 } { incr line } {
7389 if {[catch { set nchar [gets "$fd" body] } message]} {
7390 error "$message"
7392 if {$nchar < 0} {
7393 break
7395 if {[string first "$text" "$body"] >= 0} {
7396 set found $line
7397 break
7401 if {[catch { close "$fd" } message]} {
7402 error "$message"
7405 if {$found == -1} {
7406 error "undefined tag \"$text\""
7409 return $found
7412 # Continue the program until it ends.
7414 # MSSG is the error message that gets printed. If not given, a
7415 # default is used.
7416 # COMMAND is the command to invoke. If not given, "continue" is
7417 # used.
7418 # ALLOW_EXTRA is a flag indicating whether the test should expect
7419 # extra output between the "Continuing." line and the program
7420 # exiting. By default it is zero; if nonzero, any extra output
7421 # is accepted.
7423 proc gdb_continue_to_end {{mssg ""} {command continue} {allow_extra 0}} {
7424 global inferior_exited_re use_gdb_stub
7426 if {$mssg == ""} {
7427 set text "continue until exit"
7428 } else {
7429 set text "continue until exit at $mssg"
7431 if {$allow_extra} {
7432 set extra ".*"
7433 } else {
7434 set extra ""
7437 # By default, we don't rely on exit() behavior of remote stubs --
7438 # it's common for exit() to be implemented as a simple infinite
7439 # loop, or a forced crash/reset. For native targets, by default, we
7440 # assume process exit is reported as such. If a non-reliable target
7441 # is used, we set a breakpoint at exit, and continue to that.
7442 if { [target_info exists exit_is_reliable] } {
7443 set exit_is_reliable [target_info exit_is_reliable]
7444 } else {
7445 set exit_is_reliable [expr ! $use_gdb_stub]
7448 if { ! $exit_is_reliable } {
7449 if {![gdb_breakpoint "exit"]} {
7450 return 0
7452 gdb_test $command "Continuing..*Breakpoint .*exit.*" \
7453 $text
7454 } else {
7455 # Continue until we exit. Should not stop again.
7456 # Don't bother to check the output of the program, that may be
7457 # extremely tough for some remote systems.
7458 gdb_test $command \
7459 "Continuing.\[\r\n0-9\]+${extra}(... EXIT code 0\[\r\n\]+|$inferior_exited_re normally).*"\
7460 $text
7464 proc rerun_to_main {} {
7465 global gdb_prompt use_gdb_stub
7467 if $use_gdb_stub {
7468 gdb_run_cmd
7469 gdb_expect {
7470 -re ".*Breakpoint .*main .*$gdb_prompt $"\
7471 {pass "rerun to main" ; return 0}
7472 -re "$gdb_prompt $"\
7473 {fail "rerun to main" ; return 0}
7474 timeout {fail "(timeout) rerun to main" ; return 0}
7476 } else {
7477 send_gdb "run\n"
7478 gdb_expect {
7479 -re "The program .* has been started already.*y or n. $" {
7480 send_gdb "y\n" answer
7481 exp_continue
7483 -re "Starting program.*$gdb_prompt $"\
7484 {pass "rerun to main" ; return 0}
7485 -re "$gdb_prompt $"\
7486 {fail "rerun to main" ; return 0}
7487 timeout {fail "(timeout) rerun to main" ; return 0}
7492 # Return true if EXECUTABLE contains a .gdb_index or .debug_names index section.
7494 proc exec_has_index_section { executable } {
7495 set readelf_program [gdb_find_readelf]
7496 set res [catch {exec $readelf_program -S $executable \
7497 | grep -E "\.gdb_index|\.debug_names" }]
7498 if { $res == 0 } {
7499 return 1
7501 return 0
7504 # Return list with major and minor version of readelf, or an empty list.
7505 gdb_caching_proc readelf_version {} {
7506 set readelf_program [gdb_find_readelf]
7507 set res [catch {exec $readelf_program --version} output]
7508 if { $res != 0 } {
7509 return [list]
7511 set lines [split $output \n]
7512 set line [lindex $lines 0]
7513 set res [regexp {[ \t]+([0-9]+)[.]([0-9]+)[^ \t]*$} \
7514 $line dummy major minor]
7515 if { $res != 1 } {
7516 return [list]
7518 return [list $major $minor]
7521 # Return 1 if readelf prints the PIE flag, 0 if is doesn't, and -1 if unknown.
7522 proc readelf_prints_pie { } {
7523 set version [readelf_version]
7524 if { [llength $version] == 0 } {
7525 return -1
7527 set major [lindex $version 0]
7528 set minor [lindex $version 1]
7529 # It would be better to construct a PIE executable and test if the PIE
7530 # flag is printed by readelf, but we cannot reliably construct a PIE
7531 # executable if the multilib_flags dictate otherwise
7532 # (--target_board=unix/-no-pie/-fno-PIE).
7533 return [version_compare {2 26} <= [list $major $minor]]
7536 # Return 1 if EXECUTABLE is a Position Independent Executable, 0 if it is not,
7537 # and -1 if unknown.
7539 proc exec_is_pie { executable } {
7540 set res [readelf_prints_pie]
7541 if { $res != 1 } {
7542 return -1
7544 set readelf_program [gdb_find_readelf]
7545 # We're not testing readelf -d | grep "FLAGS_1.*Flags:.*PIE"
7546 # because the PIE flag is not set by all versions of gold, see PR
7547 # binutils/26039.
7548 set res [catch {exec $readelf_program -h $executable} output]
7549 if { $res != 0 } {
7550 return -1
7552 set res [regexp -line {^[ \t]*Type:[ \t]*DYN \((Position-Independent Executable|Shared object) file\)$} \
7553 $output]
7554 if { $res == 1 } {
7555 return 1
7557 return 0
7560 # Return false if a test should be skipped due to lack of floating
7561 # point support or GDB can't fetch the contents from floating point
7562 # registers.
7564 gdb_caching_proc allow_float_test {} {
7565 if [target_info exists gdb,skip_float_tests] {
7566 return 0
7569 # There is an ARM kernel ptrace bug that hardware VFP registers
7570 # are not updated after GDB ptrace set VFP registers. The bug
7571 # was introduced by kernel commit 8130b9d7b9d858aa04ce67805e8951e3cb6e9b2f
7572 # in 2012 and is fixed in e2dfb4b880146bfd4b6aa8e138c0205407cebbaf
7573 # in May 2016. In other words, kernels older than 4.6.3, 4.4.14,
7574 # 4.1.27, 3.18.36, and 3.14.73 have this bug.
7575 # This kernel bug is detected by check how does GDB change the
7576 # program result by changing one VFP register.
7577 if { [istarget "arm*-*-linux*"] } {
7579 set compile_flags {debug nowarnings }
7581 # Set up, compile, and execute a test program having VFP
7582 # operations.
7583 set src [standard_temp_file arm_vfp.c]
7584 set exe [standard_temp_file arm_vfp.x]
7586 gdb_produce_source $src {
7587 int main() {
7588 double d = 4.0;
7589 int ret;
7591 asm ("vldr d0, [%0]" : : "r" (&d));
7592 asm ("vldr d1, [%0]" : : "r" (&d));
7593 asm (".global break_here\n"
7594 "break_here:");
7595 asm ("vcmp.f64 d0, d1\n"
7596 "vmrs APSR_nzcv, fpscr\n"
7597 "bne L_value_different\n"
7598 "movs %0, #0\n"
7599 "b L_end\n"
7600 "L_value_different:\n"
7601 "movs %0, #1\n"
7602 "L_end:\n" : "=r" (ret) :);
7604 /* Return $d0 != $d1. */
7605 return ret;
7609 verbose "compiling testfile $src" 2
7610 set lines [gdb_compile $src $exe executable $compile_flags]
7611 file delete $src
7613 if {![string match "" $lines]} {
7614 verbose "testfile compilation failed, returning 1" 2
7615 return 1
7618 # No error message, compilation succeeded so now run it via gdb.
7619 # Run the test up to 5 times to detect whether ptrace can
7620 # correctly update VFP registers or not.
7621 set allow_vfp_test 1
7622 for {set i 0} {$i < 5} {incr i} {
7623 global gdb_prompt srcdir subdir
7625 gdb_exit
7626 gdb_start
7627 gdb_reinitialize_dir $srcdir/$subdir
7628 gdb_load "$exe"
7630 runto_main
7631 gdb_test "break *break_here"
7632 gdb_continue_to_breakpoint "break_here"
7634 # Modify $d0 to a different value, so the exit code should
7635 # be 1.
7636 gdb_test "set \$d0 = 5.0"
7638 set test "continue to exit"
7639 gdb_test_multiple "continue" "$test" {
7640 -re "exited with code 01.*$gdb_prompt $" {
7642 -re "exited normally.*$gdb_prompt $" {
7643 # However, the exit code is 0. That means something
7644 # wrong in setting VFP registers.
7645 set allow_vfp_test 0
7646 break
7651 gdb_exit
7652 remote_file build delete $exe
7654 return $allow_vfp_test
7656 return 1
7659 # Print a message and return true if a test should be skipped
7660 # due to lack of stdio support.
7662 proc gdb_skip_stdio_test { msg } {
7663 if [target_info exists gdb,noinferiorio] {
7664 verbose "Skipping test '$msg': no inferior i/o."
7665 return 1
7667 return 0
7670 proc gdb_skip_bogus_test { msg } {
7671 return 0
7674 # Return true if XML support is enabled in the host GDB.
7675 # NOTE: This must be called while gdb is *not* running.
7677 gdb_caching_proc allow_xml_test {} {
7678 global gdb_spawn_id
7679 global gdb_prompt
7680 global srcdir
7682 if { [info exists gdb_spawn_id] } {
7683 error "GDB must not be running in allow_xml_tests."
7686 set xml_file [gdb_remote_download host "${srcdir}/gdb.xml/trivial.xml"]
7688 gdb_start
7689 set xml_missing 0
7690 gdb_test_multiple "set tdesc filename $xml_file" "" {
7691 -re ".*XML support was disabled at compile time.*$gdb_prompt $" {
7692 set xml_missing 1
7694 -re ".*$gdb_prompt $" { }
7696 gdb_exit
7697 return [expr {!$xml_missing}]
7700 # Return true if argv[0] is available.
7702 gdb_caching_proc gdb_has_argv0 {} {
7703 set result 0
7705 # Compile and execute a test program to check whether argv[0] is available.
7706 gdb_simple_compile has_argv0 {
7707 int main (int argc, char **argv) {
7708 return 0;
7710 } executable
7713 # Helper proc.
7714 proc gdb_has_argv0_1 { exe } {
7715 global srcdir subdir
7716 global gdb_prompt hex
7718 gdb_exit
7719 gdb_start
7720 gdb_reinitialize_dir $srcdir/$subdir
7721 gdb_load "$exe"
7723 # Set breakpoint on main.
7724 gdb_test_multiple "break -q main" "break -q main" {
7725 -re "Breakpoint.*${gdb_prompt} $" {
7727 -re "${gdb_prompt} $" {
7728 return 0
7732 # Run to main.
7733 gdb_run_cmd
7734 gdb_test_multiple "" "run to main" {
7735 -re "Breakpoint.*${gdb_prompt} $" {
7737 -re "${gdb_prompt} $" {
7738 return 0
7742 set old_elements "200"
7743 set test "show print elements"
7744 gdb_test_multiple $test $test {
7745 -re "Limit on string chars or array elements to print is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
7746 set old_elements $expect_out(1,string)
7749 set old_repeats "200"
7750 set test "show print repeats"
7751 gdb_test_multiple $test $test {
7752 -re "Threshold for repeated print elements is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
7753 set old_repeats $expect_out(1,string)
7756 gdb_test_no_output "set print elements unlimited" ""
7757 gdb_test_no_output "set print repeats unlimited" ""
7759 set retval 0
7760 # Check whether argc is 1.
7761 gdb_test_multiple "p argc" "p argc" {
7762 -re " = 1\r\n${gdb_prompt} $" {
7764 gdb_test_multiple "p argv\[0\]" "p argv\[0\]" {
7765 -re " = $hex \".*[file tail $exe]\"\r\n${gdb_prompt} $" {
7766 set retval 1
7768 -re "${gdb_prompt} $" {
7772 -re "${gdb_prompt} $" {
7776 gdb_test_no_output "set print elements $old_elements" ""
7777 gdb_test_no_output "set print repeats $old_repeats" ""
7779 return $retval
7782 set result [gdb_has_argv0_1 $obj]
7784 gdb_exit
7785 file delete $obj
7787 if { !$result
7788 && ([istarget *-*-linux*]
7789 || [istarget *-*-freebsd*] || [istarget *-*-kfreebsd*]
7790 || [istarget *-*-netbsd*] || [istarget *-*-knetbsd*]
7791 || [istarget *-*-openbsd*]
7792 || [istarget *-*-darwin*]
7793 || [istarget *-*-solaris*]
7794 || [istarget *-*-aix*]
7795 || [istarget *-*-gnu*]
7796 || [istarget *-*-cygwin*] || [istarget *-*-mingw32*]
7797 || [istarget *-*-*djgpp*] || [istarget *-*-go32*]
7798 || [istarget *-wince-pe] || [istarget *-*-mingw32ce*]
7799 || [istarget *-*-osf*]
7800 || [istarget *-*-dicos*]
7801 || [istarget *-*-nto*]
7802 || [istarget *-*-*vms*]
7803 || [istarget *-*-lynx*178]) } {
7804 fail "argv\[0\] should be available on this target"
7807 return $result
7810 # Note: the procedure gdb_gnu_strip_debug will produce an executable called
7811 # ${binfile}.dbglnk, which is just like the executable ($binfile) but without
7812 # the debuginfo. Instead $binfile has a .gnu_debuglink section which contains
7813 # the name of a debuginfo only file. This file will be stored in the same
7814 # subdirectory.
7816 # Functions for separate debug info testing
7818 # starting with an executable:
7819 # foo --> original executable
7821 # at the end of the process we have:
7822 # foo.stripped --> foo w/o debug info
7823 # foo.debug --> foo's debug info
7824 # foo --> like foo, but with a new .gnu_debuglink section pointing to foo.debug.
7826 # Fetch the build id from the file.
7827 # Returns "" if there is none.
7829 proc get_build_id { filename } {
7830 if { ([istarget "*-*-mingw*"]
7831 || [istarget *-*-cygwin*]) } {
7832 set objdump_program [gdb_find_objdump]
7833 set result [catch {set data [exec $objdump_program -p $filename | grep signature | cut "-d " -f4]} output]
7834 verbose "result is $result"
7835 verbose "output is $output"
7836 if {$result == 1} {
7837 return ""
7839 return $data
7840 } else {
7841 set tmp [standard_output_file "${filename}-tmp"]
7842 set objcopy_program [gdb_find_objcopy]
7843 set result [catch "exec $objcopy_program -j .note.gnu.build-id -O binary $filename $tmp" output]
7844 verbose "result is $result"
7845 verbose "output is $output"
7846 if {$result == 1} {
7847 return ""
7849 set fi [open $tmp]
7850 fconfigure $fi -translation binary
7851 # Skip the NOTE header.
7852 read $fi 16
7853 set data [read $fi]
7854 close $fi
7855 file delete $tmp
7856 if {![string compare $data ""]} {
7857 return ""
7859 # Convert it to hex.
7860 binary scan $data H* data
7861 return $data
7865 # Return the build-id hex string (usually 160 bits as 40 hex characters)
7866 # converted to the form: .build-id/ab/cdef1234...89.debug
7867 # Return "" if no build-id found.
7868 proc build_id_debug_filename_get { filename } {
7869 set data [get_build_id $filename]
7870 if { $data == "" } {
7871 return ""
7873 regsub {^..} $data {\0/} data
7874 return ".build-id/${data}.debug"
7877 # DEST should be a file compiled with debug information. This proc
7878 # creates two new files DEST.debug which contains the debug
7879 # information extracted from DEST, and DEST.stripped, which is a copy
7880 # of DEST with the debug information removed. A '.gnu_debuglink'
7881 # section will be added to DEST.stripped that points to DEST.debug.
7883 # If ARGS is passed, it is a list of optional flags. The currently
7884 # supported flags are:
7886 # - no-main : remove the symbol entry for main from the separate
7887 # debug file DEST.debug,
7888 # - no-debuglink : don't add the '.gnu_debuglink' section to
7889 # DEST.stripped.
7891 # Function returns zero on success. Function will return non-zero failure code
7892 # on some targets not supporting separate debug info (such as i386-msdos).
7894 proc gdb_gnu_strip_debug { dest args } {
7896 # Use the first separate debug info file location searched by GDB so the
7897 # run cannot be broken by some stale file searched with higher precedence.
7898 set debug_file "${dest}.debug"
7900 set strip_to_file_program [transform strip]
7901 set objcopy_program [gdb_find_objcopy]
7903 set debug_link [file tail $debug_file]
7904 set stripped_file "${dest}.stripped"
7906 # Get rid of the debug info, and store result in stripped_file
7907 # something like gdb/testsuite/gdb.base/blah.stripped.
7908 set result [catch "exec $strip_to_file_program --strip-debug ${dest} -o ${stripped_file}" output]
7909 verbose "result is $result"
7910 verbose "output is $output"
7911 if {$result == 1} {
7912 return 1
7915 # Workaround PR binutils/10802:
7916 # Preserve the 'x' bit also for PIEs (Position Independent Executables).
7917 set perm [file attributes ${dest} -permissions]
7918 file attributes ${stripped_file} -permissions $perm
7920 # Get rid of everything but the debug info, and store result in debug_file
7921 # This will be in the .debug subdirectory, see above.
7922 set result [catch "exec $strip_to_file_program --only-keep-debug ${dest} -o ${debug_file}" output]
7923 verbose "result is $result"
7924 verbose "output is $output"
7925 if {$result == 1} {
7926 return 1
7929 # If no-main is passed, strip the symbol for main from the separate
7930 # file. This is to simulate the behavior of elfutils's eu-strip, which
7931 # leaves the symtab in the original file only. There's no way to get
7932 # objcopy or strip to remove the symbol table without also removing the
7933 # debugging sections, so this is as close as we can get.
7934 if {[lsearch -exact $args "no-main"] != -1} {
7935 set result [catch "exec $objcopy_program -N main ${debug_file} ${debug_file}-tmp" output]
7936 verbose "result is $result"
7937 verbose "output is $output"
7938 if {$result == 1} {
7939 return 1
7941 file delete "${debug_file}"
7942 file rename "${debug_file}-tmp" "${debug_file}"
7945 # Unless the "no-debuglink" flag is passed, then link the two
7946 # previous output files together, adding the .gnu_debuglink
7947 # section to the stripped_file, containing a pointer to the
7948 # debug_file, save the new file in dest.
7949 if {[lsearch -exact $args "no-debuglink"] == -1} {
7950 set result [catch "exec $objcopy_program --add-gnu-debuglink=${debug_file} ${stripped_file} ${dest}" output]
7951 verbose "result is $result"
7952 verbose "output is $output"
7953 if {$result == 1} {
7954 return 1
7958 # Workaround PR binutils/10802:
7959 # Preserve the 'x' bit also for PIEs (Position Independent Executables).
7960 set perm [file attributes ${stripped_file} -permissions]
7961 file attributes ${dest} -permissions $perm
7963 return 0
7966 # Test the output of GDB_COMMAND matches the pattern obtained
7967 # by concatenating all elements of EXPECTED_LINES. This makes
7968 # it possible to split otherwise very long string into pieces.
7969 # If third argument TESTNAME is not empty, it's used as the name of the
7970 # test to be printed on pass/fail.
7971 proc help_test_raw { gdb_command expected_lines {testname {}} } {
7972 set expected_output [join $expected_lines ""]
7973 if {$testname != {}} {
7974 gdb_test "${gdb_command}" "${expected_output}" $testname
7975 return
7978 gdb_test "${gdb_command}" "${expected_output}"
7981 # A regexp that matches the end of help CLASS|PREFIX_COMMAND
7982 set help_list_trailer {
7983 "Type \"apropos word\" to search for commands related to \"word\"\.[\r\n]+"
7984 "Type \"apropos -v word\" for full documentation of commands related to \"word\"\.[\r\n]+"
7985 "Command name abbreviations are allowed if unambiguous\."
7988 # Test the output of "help COMMAND_CLASS". EXPECTED_INITIAL_LINES
7989 # are regular expressions that should match the beginning of output,
7990 # before the list of commands in that class.
7991 # LIST_OF_COMMANDS are regular expressions that should match the
7992 # list of commands in that class. If empty, the command list will be
7993 # matched automatically. The presence of standard epilogue will be tested
7994 # automatically.
7995 # If last argument TESTNAME is not empty, it's used as the name of the
7996 # test to be printed on pass/fail.
7997 # Notice that the '[' and ']' characters don't need to be escaped for strings
7998 # wrapped in {} braces.
7999 proc test_class_help { command_class expected_initial_lines {list_of_commands {}} {testname {}} } {
8000 global help_list_trailer
8001 if {[llength $list_of_commands]>0} {
8002 set l_list_of_commands {"List of commands:[\r\n]+[\r\n]+"}
8003 set l_list_of_commands [concat $l_list_of_commands $list_of_commands]
8004 set l_list_of_commands [concat $l_list_of_commands {"[\r\n]+[\r\n]+"}]
8005 } else {
8006 set l_list_of_commands {"List of commands\:.*[\r\n]+"}
8008 set l_stock_body {
8009 "Type \"help\" followed by command name for full documentation\.[\r\n]+"
8011 set l_entire_body [concat $expected_initial_lines $l_list_of_commands \
8012 $l_stock_body $help_list_trailer]
8014 help_test_raw "help ${command_class}" $l_entire_body $testname
8017 # Like test_class_help but specialised to test "help user-defined".
8018 proc test_user_defined_class_help { {list_of_commands {}} {testname {}} } {
8019 test_class_help "user-defined" {
8020 "User-defined commands\.[\r\n]+"
8021 "The commands in this class are those defined by the user\.[\r\n]+"
8022 "Use the \"define\" command to define a command\.[\r\n]+"
8023 } $list_of_commands $testname
8027 # COMMAND_LIST should have either one element -- command to test, or
8028 # two elements -- abbreviated command to test, and full command the first
8029 # element is abbreviation of.
8030 # The command must be a prefix command. EXPECTED_INITIAL_LINES
8031 # are regular expressions that should match the beginning of output,
8032 # before the list of subcommands. The presence of
8033 # subcommand list and standard epilogue will be tested automatically.
8034 proc test_prefix_command_help { command_list expected_initial_lines args } {
8035 global help_list_trailer
8036 set command [lindex $command_list 0]
8037 if {[llength $command_list]>1} {
8038 set full_command [lindex $command_list 1]
8039 } else {
8040 set full_command $command
8042 # Use 'list' and not just {} because we want variables to
8043 # be expanded in this list.
8044 set l_stock_body [list\
8045 "List of $full_command subcommands\:.*\[\r\n\]+"\
8046 "Type \"help $full_command\" followed by $full_command subcommand name for full documentation\.\[\r\n\]+"]
8047 set l_entire_body [concat $expected_initial_lines $l_stock_body $help_list_trailer]
8048 if {[llength $args]>0} {
8049 help_test_raw "help ${command}" $l_entire_body [lindex $args 0]
8050 } else {
8051 help_test_raw "help ${command}" $l_entire_body
8055 # Build executable named EXECUTABLE from specifications that allow
8056 # different options to be passed to different sub-compilations.
8057 # TESTNAME is the name of the test; this is passed to 'untested' if
8058 # something fails.
8059 # OPTIONS is passed to the final link, using gdb_compile. If OPTIONS
8060 # contains the option "pthreads", then gdb_compile_pthreads is used.
8061 # ARGS is a flat list of source specifications, of the form:
8062 # { SOURCE1 OPTIONS1 [ SOURCE2 OPTIONS2 ]... }
8063 # Each SOURCE is compiled to an object file using its OPTIONS,
8064 # using gdb_compile.
8065 # Returns 0 on success, -1 on failure.
8066 proc build_executable_from_specs {testname executable options args} {
8067 global subdir
8068 global srcdir
8070 set binfile [standard_output_file $executable]
8072 set func gdb_compile
8073 set func_index [lsearch -regexp $options {^(pthreads|shlib|shlib_pthreads|openmp)$}]
8074 if {$func_index != -1} {
8075 set func "${func}_[lindex $options $func_index]"
8078 # gdb_compile_shlib and gdb_compile_shlib_pthreads do not use the 3rd
8079 # parameter. They also requires $sources while gdb_compile and
8080 # gdb_compile_pthreads require $objects. Moreover they ignore any options.
8081 if [string match gdb_compile_shlib* $func] {
8082 set sources_path {}
8083 foreach {s local_options} $args {
8084 if {[regexp "^/" "$s"]} {
8085 lappend sources_path "$s"
8086 } else {
8087 lappend sources_path "$srcdir/$subdir/$s"
8090 set ret [$func $sources_path "${binfile}" $options]
8091 } elseif {[lsearch -exact $options rust] != -1} {
8092 set sources_path {}
8093 foreach {s local_options} $args {
8094 if {[regexp "^/" "$s"]} {
8095 lappend sources_path "$s"
8096 } else {
8097 lappend sources_path "$srcdir/$subdir/$s"
8100 set ret [gdb_compile_rust $sources_path "${binfile}" $options]
8101 } else {
8102 set objects {}
8103 set i 0
8104 foreach {s local_options} $args {
8105 if {![regexp "^/" "$s"]} {
8106 set s "$srcdir/$subdir/$s"
8108 if { [$func "${s}" "${binfile}${i}.o" object $local_options] != "" } {
8109 untested $testname
8110 return -1
8112 lappend objects "${binfile}${i}.o"
8113 incr i
8115 set ret [$func $objects "${binfile}" executable $options]
8117 if { $ret != "" } {
8118 untested $testname
8119 return -1
8122 return 0
8125 # Build executable named EXECUTABLE, from SOURCES. If SOURCES are not
8126 # provided, uses $EXECUTABLE.c. The TESTNAME paramer is the name of test
8127 # to pass to untested, if something is wrong. OPTIONS are passed
8128 # to gdb_compile directly.
8129 proc build_executable { testname executable {sources ""} {options {debug}} } {
8130 if {[llength $sources]==0} {
8131 set sources ${executable}.c
8134 set arglist [list $testname $executable $options]
8135 foreach source $sources {
8136 lappend arglist $source $options
8139 return [eval build_executable_from_specs $arglist]
8142 # Starts fresh GDB binary and loads an optional executable into GDB.
8143 # Usage: clean_restart [EXECUTABLE]
8144 # EXECUTABLE is the basename of the binary.
8145 # Return -1 if starting gdb or loading the executable failed.
8147 proc clean_restart {{executable ""}} {
8148 global srcdir
8149 global subdir
8150 global errcnt
8151 global warncnt
8153 gdb_exit
8155 # This is a clean restart, so reset error and warning count.
8156 set errcnt 0
8157 set warncnt 0
8159 # We'd like to do:
8160 # if { [gdb_start] == -1 } {
8161 # return -1
8163 # but gdb_start is a ${tool}_start proc, which doesn't have a defined
8164 # return value. So instead, we test for errcnt.
8165 gdb_start
8166 if { $errcnt > 0 } {
8167 return -1
8170 gdb_reinitialize_dir $srcdir/$subdir
8172 if {$executable != ""} {
8173 set binfile [standard_output_file ${executable}]
8174 return [gdb_load ${binfile}]
8177 return 0
8180 # Prepares for testing by calling build_executable_full, then
8181 # clean_restart.
8182 # TESTNAME is the name of the test.
8183 # Each element in ARGS is a list of the form
8184 # { EXECUTABLE OPTIONS SOURCE_SPEC... }
8185 # These are passed to build_executable_from_specs, which see.
8186 # The last EXECUTABLE is passed to clean_restart.
8187 # Returns 0 on success, non-zero on failure.
8188 proc prepare_for_testing_full {testname args} {
8189 foreach spec $args {
8190 if {[eval build_executable_from_specs [list $testname] $spec] == -1} {
8191 return -1
8193 set executable [lindex $spec 0]
8195 clean_restart $executable
8196 return 0
8199 # Prepares for testing, by calling build_executable, and then clean_restart.
8200 # Please refer to build_executable for parameter description.
8201 proc prepare_for_testing { testname executable {sources ""} {options {debug}}} {
8203 if {[build_executable $testname $executable $sources $options] == -1} {
8204 return -1
8206 clean_restart $executable
8208 return 0
8211 # Retrieve the value of EXP in the inferior, represented in format
8212 # specified in FMT (using "printFMT"). DEFAULT is used as fallback if
8213 # print fails. TEST is the test message to use. It can be omitted,
8214 # in which case a test message is built from EXP.
8216 proc get_valueof { fmt exp default {test ""} } {
8217 global gdb_prompt
8219 if {$test == "" } {
8220 set test "get valueof \"${exp}\""
8223 set val ${default}
8224 gdb_test_multiple "print${fmt} ${exp}" "$test" {
8225 -re -wrap "^\\$\[0-9\]* = (\[^\r\n\]*)" {
8226 set val $expect_out(1,string)
8227 pass "$test"
8229 timeout {
8230 fail "$test (timeout)"
8233 return ${val}
8236 # Retrieve the value of local var EXP in the inferior. DEFAULT is used as
8237 # fallback if print fails. TEST is the test message to use. It can be
8238 # omitted, in which case a test message is built from EXP.
8240 proc get_local_valueof { exp default {test ""} } {
8241 global gdb_prompt
8243 if {$test == "" } {
8244 set test "get local valueof \"${exp}\""
8247 set val ${default}
8248 gdb_test_multiple "info locals ${exp}" "$test" {
8249 -re "$exp = (\[^\r\n\]*)\r\n$gdb_prompt $" {
8250 set val $expect_out(1,string)
8251 pass "$test"
8253 timeout {
8254 fail "$test (timeout)"
8257 return ${val}
8260 # Retrieve the value of EXP in the inferior, as a signed decimal value
8261 # (using "print /d"). DEFAULT is used as fallback if print fails.
8262 # TEST is the test message to use. It can be omitted, in which case
8263 # a test message is built from EXP.
8265 proc get_integer_valueof { exp default {test ""} } {
8266 global gdb_prompt
8268 if {$test == ""} {
8269 set test "get integer valueof \"${exp}\""
8272 set val ${default}
8273 gdb_test_multiple "print /d ${exp}" "$test" {
8274 -re -wrap "^\\$\[0-9\]* = (\[-\]*\[0-9\]*).*" {
8275 set val $expect_out(1,string)
8276 pass "$test"
8278 timeout {
8279 fail "$test (timeout)"
8282 return ${val}
8285 # Retrieve the value of EXP in the inferior, as an hexadecimal value
8286 # (using "print /x"). DEFAULT is used as fallback if print fails.
8287 # TEST is the test message to use. It can be omitted, in which case
8288 # a test message is built from EXP.
8290 proc get_hexadecimal_valueof { exp default {test ""} } {
8291 global gdb_prompt
8293 if {$test == ""} {
8294 set test "get hexadecimal valueof \"${exp}\""
8297 set val ${default}
8298 gdb_test_multiple "print /x ${exp}" $test {
8299 -re "\\$\[0-9\]* = (0x\[0-9a-zA-Z\]+).*$gdb_prompt $" {
8300 set val $expect_out(1,string)
8301 pass "$test"
8304 return ${val}
8307 # Retrieve the size of TYPE in the inferior, as a decimal value. DEFAULT
8308 # is used as fallback if print fails. TEST is the test message to use.
8309 # It can be omitted, in which case a test message is 'sizeof (TYPE)'.
8311 proc get_sizeof { type default {test ""} } {
8312 return [get_integer_valueof "sizeof (${type})" $default $test]
8315 proc get_target_charset { } {
8316 global gdb_prompt
8318 gdb_test_multiple "show target-charset" "" {
8319 -re "The target character set is \"auto; currently (\[^\"\]*)\".*$gdb_prompt $" {
8320 return $expect_out(1,string)
8322 -re "The target character set is \"(\[^\"\]*)\".*$gdb_prompt $" {
8323 return $expect_out(1,string)
8327 # Pick a reasonable default.
8328 warning "Unable to read target-charset."
8329 return "UTF-8"
8332 # Get the address of VAR.
8334 proc get_var_address { var } {
8335 global gdb_prompt hex
8337 # Match output like:
8338 # $1 = (int *) 0x0
8339 # $5 = (int (*)()) 0
8340 # $6 = (int (*)()) 0x24 <function_bar>
8342 gdb_test_multiple "print &${var}" "get address of ${var}" {
8343 -re "\\\$\[0-9\]+ = \\(.*\\) (0|$hex)( <${var}>)?\[\r\n\]+${gdb_prompt} $"
8345 pass "get address of ${var}"
8346 if { $expect_out(1,string) == "0" } {
8347 return "0x0"
8348 } else {
8349 return $expect_out(1,string)
8353 return ""
8356 # Return the frame number for the currently selected frame
8357 proc get_current_frame_number {{test_name ""}} {
8358 global gdb_prompt
8360 if { $test_name == "" } {
8361 set test_name "get current frame number"
8363 set frame_num -1
8364 gdb_test_multiple "frame" $test_name {
8365 -re "#(\[0-9\]+) .*$gdb_prompt $" {
8366 set frame_num $expect_out(1,string)
8369 return $frame_num
8372 # Get the current value for remotetimeout and return it.
8373 proc get_remotetimeout { } {
8374 global gdb_prompt
8375 global decimal
8377 gdb_test_multiple "show remotetimeout" "" {
8378 -re "Timeout limit to wait for target to respond is ($decimal).*$gdb_prompt $" {
8379 return $expect_out(1,string)
8383 # Pick the default that gdb uses
8384 warning "Unable to read remotetimeout"
8385 return 300
8388 # Set the remotetimeout to the specified timeout. Nothing is returned.
8389 proc set_remotetimeout { timeout } {
8390 global gdb_prompt
8392 gdb_test_multiple "set remotetimeout $timeout" "" {
8393 -re "$gdb_prompt $" {
8394 verbose "Set remotetimeout to $timeout\n"
8399 # Get the target's current endianness and return it.
8400 proc get_endianness { } {
8401 global gdb_prompt
8403 gdb_test_multiple "show endian" "determine endianness" {
8404 -re ".* (little|big) endian.*\r\n$gdb_prompt $" {
8405 # Pass silently.
8406 return $expect_out(1,string)
8409 return "little"
8412 # Get the target's default endianness and return it.
8413 gdb_caching_proc target_endianness {} {
8414 global gdb_prompt
8416 set me "target_endianness"
8418 set src { int main() { return 0; } }
8419 if {![gdb_simple_compile $me $src executable]} {
8420 return 0
8423 clean_restart $obj
8424 if ![runto_main] {
8425 return 0
8427 set res [get_endianness]
8429 gdb_exit
8430 remote_file build delete $obj
8432 return $res
8435 # ROOT and FULL are file names. Returns the relative path from ROOT
8436 # to FULL. Note that FULL must be in a subdirectory of ROOT.
8437 # For example, given ROOT = /usr/bin and FULL = /usr/bin/ls, this
8438 # will return "ls".
8440 proc relative_filename {root full} {
8441 set root_split [file split $root]
8442 set full_split [file split $full]
8444 set len [llength $root_split]
8446 if {[eval file join $root_split]
8447 != [eval file join [lrange $full_split 0 [expr {$len - 1}]]]} {
8448 error "$full not a subdir of $root"
8451 return [eval file join [lrange $full_split $len end]]
8454 # If GDB_PARALLEL exists, then set up the parallel-mode directories.
8455 if {[info exists GDB_PARALLEL]} {
8456 if {[is_remote host]} {
8457 unset GDB_PARALLEL
8458 } else {
8459 file mkdir \
8460 [make_gdb_parallel_path outputs] \
8461 [make_gdb_parallel_path temp] \
8462 [make_gdb_parallel_path cache]
8466 # Set the inferior's cwd to the output directory, in order to have it
8467 # dump core there. This must be called before the inferior is
8468 # started.
8470 proc set_inferior_cwd_to_output_dir {} {
8471 # Note this sets the inferior's cwd ("set cwd"), not GDB's ("cd").
8472 # If GDB crashes, we want its core dump in gdb/testsuite/, not in
8473 # the testcase's dir, so we can detect the unexpected core at the
8474 # end of the test run.
8475 if {![is_remote host]} {
8476 set output_dir [standard_output_file ""]
8477 gdb_test_no_output "set cwd $output_dir" \
8478 "set inferior cwd to test directory"
8482 # Get the inferior's PID.
8484 proc get_inferior_pid {} {
8485 set pid -1
8486 gdb_test_multiple "inferior" "get inferior pid" {
8487 -re "process (\[0-9\]*).*$::gdb_prompt $" {
8488 set pid $expect_out(1,string)
8489 pass $gdb_test_name
8492 return $pid
8495 # Find the kernel-produced core file dumped for the current testfile
8496 # program. PID was the inferior's pid, saved before the inferior
8497 # exited with a signal, or -1 if not known. If not on a remote host,
8498 # this assumes the core was generated in the output directory.
8499 # Returns the name of the core dump, or empty string if not found.
8501 proc find_core_file {pid} {
8502 # For non-remote hosts, since cores are assumed to be in the
8503 # output dir, which we control, we use a laxer "core.*" glob. For
8504 # remote hosts, as we don't know whether the dir is being reused
8505 # for parallel runs, we use stricter names with no globs. It is
8506 # not clear whether this is really important, but it preserves
8507 # status quo ante.
8508 set files {}
8509 if {![is_remote host]} {
8510 lappend files core.*
8511 } elseif {$pid != -1} {
8512 lappend files core.$pid
8514 lappend files ${::testfile}.core
8515 lappend files core
8517 foreach file $files {
8518 if {![is_remote host]} {
8519 set names [glob -nocomplain [standard_output_file $file]]
8520 if {[llength $names] == 1} {
8521 return [lindex $names 0]
8523 } else {
8524 if {[remote_file host exists $file]} {
8525 return $file
8529 return ""
8532 # Check for production of a core file and remove it. PID is the
8533 # inferior's pid or -1 if not known. TEST is the test's message.
8535 proc remove_core {pid {test ""}} {
8536 if {$test == ""} {
8537 set test "cleanup core file"
8540 set file [find_core_file $pid]
8541 if {$file != ""} {
8542 remote_file host delete $file
8543 pass "$test (removed)"
8544 } else {
8545 pass "$test (not found)"
8549 proc core_find {binfile {deletefiles {}} {arg ""}} {
8550 global objdir subdir
8552 set destcore "$binfile.core"
8553 file delete $destcore
8555 # Create a core file named "$destcore" rather than just "core", to
8556 # avoid problems with sys admin types that like to regularly prune all
8557 # files named "core" from the system.
8559 # Arbitrarily try setting the core size limit to "unlimited" since
8560 # this does not hurt on systems where the command does not work and
8561 # allows us to generate a core on systems where it does.
8563 # Some systems append "core" to the name of the program; others append
8564 # the name of the program to "core"; still others (like Linux, as of
8565 # May 2003) create cores named "core.PID". In the latter case, we
8566 # could have many core files lying around, and it may be difficult to
8567 # tell which one is ours, so let's run the program in a subdirectory.
8568 set found 0
8569 set coredir [standard_output_file coredir.[getpid]]
8570 file mkdir $coredir
8571 catch "system \"(cd ${coredir}; ulimit -c unlimited; ${binfile} ${arg}; true) >/dev/null 2>&1\""
8572 # remote_exec host "${binfile}"
8573 foreach i "${coredir}/core ${coredir}/core.coremaker.c ${binfile}.core" {
8574 if [remote_file build exists $i] {
8575 remote_exec build "mv $i $destcore"
8576 set found 1
8579 # Check for "core.PID", "core.EXEC.PID.HOST.TIME", etc. It's fine
8580 # to use a glob here as we're looking inside a directory we
8581 # created. Also, this procedure only works on non-remote hosts.
8582 if { $found == 0 } {
8583 set names [glob -nocomplain -directory $coredir core.*]
8584 if {[llength $names] == 1} {
8585 set corefile [file join $coredir [lindex $names 0]]
8586 remote_exec build "mv $corefile $destcore"
8587 set found 1
8590 if { $found == 0 } {
8591 # The braindamaged HPUX shell quits after the ulimit -c above
8592 # without executing ${binfile}. So we try again without the
8593 # ulimit here if we didn't find a core file above.
8594 # Oh, I should mention that any "braindamaged" non-Unix system has
8595 # the same problem. I like the cd bit too, it's really neat'n stuff.
8596 catch "system \"(cd ${objdir}/${subdir}; ${binfile}; true) >/dev/null 2>&1\""
8597 foreach i "${objdir}/${subdir}/core ${objdir}/${subdir}/core.coremaker.c ${binfile}.core" {
8598 if [remote_file build exists $i] {
8599 remote_exec build "mv $i $destcore"
8600 set found 1
8605 # Try to clean up after ourselves.
8606 foreach deletefile $deletefiles {
8607 remote_file build delete [file join $coredir $deletefile]
8609 remote_exec build "rmdir $coredir"
8611 if { $found == 0 } {
8612 warning "can't generate a core file - core tests suppressed - check ulimit -c"
8613 return ""
8615 return $destcore
8618 # gdb_target_symbol_prefix compiles a test program and then examines
8619 # the output from objdump to determine the prefix (such as underscore)
8620 # for linker symbol prefixes.
8622 gdb_caching_proc gdb_target_symbol_prefix {} {
8623 # Compile a simple test program...
8624 set src { int main() { return 0; } }
8625 if {![gdb_simple_compile target_symbol_prefix $src executable]} {
8626 return 0
8629 set prefix ""
8631 set objdump_program [gdb_find_objdump]
8632 set result [catch "exec $objdump_program --syms $obj" output]
8634 if { $result == 0 \
8635 && ![regexp -lineanchor \
8636 { ([^ a-zA-Z0-9]*)main$} $output dummy prefix] } {
8637 verbose "gdb_target_symbol_prefix: Could not find main in objdump output; returning null prefix" 2
8640 file delete $obj
8642 return $prefix
8645 # Return 1 if target supports scheduler locking, otherwise return 0.
8647 gdb_caching_proc target_supports_scheduler_locking {} {
8648 global gdb_prompt
8650 set me "gdb_target_supports_scheduler_locking"
8652 set src { int main() { return 0; } }
8653 if {![gdb_simple_compile $me $src executable]} {
8654 return 0
8657 clean_restart $obj
8658 if ![runto_main] {
8659 return 0
8662 set supports_schedule_locking -1
8663 set current_schedule_locking_mode ""
8665 set test "reading current scheduler-locking mode"
8666 gdb_test_multiple "show scheduler-locking" $test {
8667 -re "Mode for locking scheduler during execution is \"(\[\^\"\]*)\".*$gdb_prompt" {
8668 set current_schedule_locking_mode $expect_out(1,string)
8670 -re "$gdb_prompt $" {
8671 set supports_schedule_locking 0
8673 timeout {
8674 set supports_schedule_locking 0
8678 if { $supports_schedule_locking == -1 } {
8679 set test "checking for scheduler-locking support"
8680 gdb_test_multiple "set scheduler-locking $current_schedule_locking_mode" $test {
8681 -re "Target '\[^'\]+' cannot support this command\..*$gdb_prompt $" {
8682 set supports_schedule_locking 0
8684 -re "$gdb_prompt $" {
8685 set supports_schedule_locking 1
8687 timeout {
8688 set supports_schedule_locking 0
8693 if { $supports_schedule_locking == -1 } {
8694 set supports_schedule_locking 0
8697 gdb_exit
8698 remote_file build delete $obj
8699 verbose "$me: returning $supports_schedule_locking" 2
8700 return $supports_schedule_locking
8703 # Return 1 if compiler supports use of nested functions. Otherwise,
8704 # return 0.
8706 gdb_caching_proc support_nested_function_tests {} {
8707 # Compile a test program containing a nested function
8708 return [gdb_can_simple_compile nested_func {
8709 int main () {
8710 int foo () {
8711 return 0;
8713 return foo ();
8715 } executable]
8718 # gdb_target_symbol returns the provided symbol with the correct prefix
8719 # prepended. (See gdb_target_symbol_prefix, above.)
8721 proc gdb_target_symbol { symbol } {
8722 set prefix [gdb_target_symbol_prefix]
8723 return "${prefix}${symbol}"
8726 # gdb_target_symbol_prefix_flags_asm returns a string that can be
8727 # added to gdb_compile options to define the C-preprocessor macro
8728 # SYMBOL_PREFIX with a value that can be prepended to symbols
8729 # for targets which require a prefix, such as underscore.
8731 # This version (_asm) defines the prefix without double quotes
8732 # surrounding the prefix. It is used to define the macro
8733 # SYMBOL_PREFIX for assembly language files. Another version, below,
8734 # is used for symbols in inline assembler in C/C++ files.
8736 # The lack of quotes in this version (_asm) makes it possible to
8737 # define supporting macros in the .S file. (The version which
8738 # uses quotes for the prefix won't work for such files since it's
8739 # impossible to define a quote-stripping macro in C.)
8741 # It's possible to use this version (_asm) for C/C++ source files too,
8742 # but a string is usually required in such files; providing a version
8743 # (no _asm) which encloses the prefix with double quotes makes it
8744 # somewhat easier to define the supporting macros in the test case.
8746 proc gdb_target_symbol_prefix_flags_asm {} {
8747 set prefix [gdb_target_symbol_prefix]
8748 if {$prefix ne ""} {
8749 return "additional_flags=-DSYMBOL_PREFIX=$prefix"
8750 } else {
8751 return "";
8755 # gdb_target_symbol_prefix_flags returns the same string as
8756 # gdb_target_symbol_prefix_flags_asm, above, but with the prefix
8757 # enclosed in double quotes if there is a prefix.
8759 # See the comment for gdb_target_symbol_prefix_flags_asm for an
8760 # extended discussion.
8762 proc gdb_target_symbol_prefix_flags {} {
8763 set prefix [gdb_target_symbol_prefix]
8764 if {$prefix ne ""} {
8765 return "additional_flags=-DSYMBOL_PREFIX=\"$prefix\""
8766 } else {
8767 return "";
8771 # A wrapper for 'remote_exec host' that passes or fails a test.
8772 # Returns 0 if all went well, nonzero on failure.
8773 # TEST is the name of the test, other arguments are as for remote_exec.
8775 proc run_on_host { test program args } {
8776 verbose -log "run_on_host: $program $args"
8777 # remote_exec doesn't work properly if the output is set but the
8778 # input is the empty string -- so replace an empty input with
8779 # /dev/null.
8780 if {[llength $args] > 1 && [lindex $args 1] == ""} {
8781 set args [lreplace $args 1 1 "/dev/null"]
8783 set result [eval remote_exec host [list $program] $args]
8784 verbose "result is $result"
8785 set status [lindex $result 0]
8786 set output [lindex $result 1]
8787 if {$status == 0} {
8788 pass $test
8789 return 0
8790 } else {
8791 verbose -log "run_on_host failed: $output"
8792 if { $output == "spawn failed" } {
8793 unsupported $test
8794 } else {
8795 fail $test
8797 return -1
8801 # Return non-zero if "board_info debug_flags" mentions Fission.
8802 # http://gcc.gnu.org/wiki/DebugFission
8803 # Fission doesn't support everything yet.
8804 # This supports working around bug 15954.
8806 proc using_fission { } {
8807 set debug_flags [board_info [target_info name] debug_flags]
8808 return [regexp -- "-gsplit-dwarf" $debug_flags]
8811 # Search LISTNAME in uplevel LEVEL caller and set variables according to the
8812 # list of valid options with prefix PREFIX described by ARGSET.
8814 # The first member of each one- or two-element list in ARGSET defines the
8815 # name of a variable that will be added to the caller's scope.
8817 # If only one element is given to describe an option, it the value is
8818 # 0 if the option is not present in (the caller's) ARGS or 1 if
8819 # it is.
8821 # If two elements are given, the second element is the default value of
8822 # the variable. This is then overwritten if the option exists in ARGS.
8823 # If EVAL, then subst is called on the value, which allows variables
8824 # to be used.
8826 # Any parse_args elements in (the caller's) ARGS will be removed, leaving
8827 # any optional components.
8829 # Example:
8830 # proc myproc {foo args} {
8831 # parse_list args 1 {{bar} {baz "abc"} {qux}} "-" false
8832 # # ...
8834 # myproc ABC -bar -baz DEF peanut butter
8835 # will define the following variables in myproc:
8836 # foo (=ABC), bar (=1), baz (=DEF), and qux (=0)
8837 # args will be the list {peanut butter}
8839 proc parse_list { level listname argset prefix eval } {
8840 upvar $level $listname args
8842 foreach argument $argset {
8843 if {[llength $argument] == 1} {
8844 # Normalize argument, strip leading/trailing whitespace.
8845 # Allows us to treat {foo} and { foo } the same.
8846 set argument [string trim $argument]
8848 # No default specified, so we assume that we should set
8849 # the value to 1 if the arg is present and 0 if it's not.
8850 # It is assumed that no value is given with the argument.
8851 set pattern "$prefix$argument"
8852 set result [lsearch -exact $args $pattern]
8854 if {$result != -1} {
8855 set value 1
8856 set args [lreplace $args $result $result]
8857 } else {
8858 set value 0
8860 uplevel $level [list set $argument $value]
8861 } elseif {[llength $argument] == 2} {
8862 # There are two items in the argument. The second is a
8863 # default value to use if the item is not present.
8864 # Otherwise, the variable is set to whatever is provided
8865 # after the item in the args.
8866 set arg [lindex $argument 0]
8867 set pattern "$prefix[lindex $arg 0]"
8868 set result [lsearch -exact $args $pattern]
8870 if {$result != -1} {
8871 set value [lindex $args [expr $result+1]]
8872 if { $eval } {
8873 set value [uplevel [expr $level + 1] [list subst $value]]
8875 set args [lreplace $args $result [expr $result+1]]
8876 } else {
8877 set value [lindex $argument 1]
8878 if { $eval } {
8879 set value [uplevel $level [list subst $value]]
8882 uplevel $level [list set $arg $value]
8883 } else {
8884 error "Badly formatted argument \"$argument\" in argument set"
8889 # Search the caller's args variable and set variables according to the list of
8890 # valid options described by ARGSET.
8892 proc parse_args { argset } {
8893 parse_list 2 args $argset "-" false
8895 # The remaining args should be checked to see that they match the
8896 # number of items expected to be passed into the procedure...
8899 # Process the caller's options variable and set variables according
8900 # to the list of valid options described by OPTIONSET.
8902 proc parse_options { optionset } {
8903 parse_list 2 options $optionset "" true
8905 # Require no remaining options.
8906 upvar 1 options options
8907 if { [llength $options] != 0 } {
8908 error "Options left unparsed: $options"
8912 # Capture the output of COMMAND in a string ignoring PREFIX (a regexp);
8913 # return that string.
8915 proc capture_command_output { command prefix } {
8916 global gdb_prompt
8917 global expect_out
8919 set test "capture_command_output for $command"
8921 set output_string ""
8922 gdb_test_multiple $command $test {
8923 -re "^(\[^\r\n\]+\r\n)" {
8924 if { ![string equal $output_string ""] } {
8925 set output_string [join [list $output_string $expect_out(1,string)] ""]
8926 } else {
8927 set output_string $expect_out(1,string)
8929 exp_continue
8932 -re "^$gdb_prompt $" {
8936 # Strip the command.
8937 set command_re [string_to_regexp ${command}]
8938 set output_string [regsub ^$command_re\r\n $output_string ""]
8940 # Strip the prefix.
8941 if { $prefix != "" } {
8942 set output_string [regsub ^$prefix $output_string ""]
8945 # Strip a trailing newline.
8946 set output_string [regsub "\r\n$" $output_string ""]
8948 return $output_string
8951 # A convenience function that joins all the arguments together, with a
8952 # regexp that matches exactly one end of line in between each argument.
8953 # This function is ideal to write the expected output of a GDB command
8954 # that generates more than a couple of lines, as this allows us to write
8955 # each line as a separate string, which is easier to read by a human
8956 # being.
8958 proc multi_line { args } {
8959 if { [llength $args] == 1 } {
8960 set hint "forgot {*} before list argument?"
8961 error "multi_line called with one argument ($hint)"
8963 return [join $args "\r\n"]
8966 # Similar to the above, but while multi_line is meant to be used to
8967 # match GDB output, this one is meant to be used to build strings to
8968 # send as GDB input.
8970 proc multi_line_input { args } {
8971 return [join $args "\n"]
8974 # Return how many newlines there are in the given string.
8976 proc count_newlines { string } {
8977 return [regexp -all "\n" $string]
8980 # Return the version of the DejaGnu framework.
8982 # The return value is a list containing the major, minor and patch version
8983 # numbers. If the version does not contain a minor or patch number, they will
8984 # be set to 0. For example:
8986 # 1.6 -> {1 6 0}
8987 # 1.6.1 -> {1 6 1}
8988 # 2 -> {2 0 0}
8990 proc dejagnu_version { } {
8991 # The frame_version variable is defined by DejaGnu, in runtest.exp.
8992 global frame_version
8994 verbose -log "DejaGnu version: $frame_version"
8995 verbose -log "Expect version: [exp_version]"
8996 verbose -log "Tcl version: [info tclversion]"
8998 set dg_ver [split $frame_version .]
9000 while { [llength $dg_ver] < 3 } {
9001 lappend dg_ver 0
9004 return $dg_ver
9007 # Define user-defined command COMMAND using the COMMAND_LIST as the
9008 # command's definition. The terminating "end" is added automatically.
9010 proc gdb_define_cmd {command command_list} {
9011 global gdb_prompt
9013 set input [multi_line_input {*}$command_list "end"]
9014 set test "define $command"
9016 gdb_test_multiple "define $command" $test {
9017 -re "End with \[^\r\n\]*\r\n *>$" {
9018 gdb_test_multiple $input $test {
9019 -re "\r\n$gdb_prompt " {
9026 # Override the 'cd' builtin with a version that ensures that the
9027 # log file keeps pointing at the same file. We need this because
9028 # unfortunately the path to the log file is recorded using an
9029 # relative path name, and, we sometimes need to close/reopen the log
9030 # after changing the current directory. See get_compiler_info.
9032 rename cd builtin_cd
9034 proc cd { dir } {
9036 # Get the existing log file flags.
9037 set log_file_info [log_file -info]
9039 # Split the flags into args and file name.
9040 set log_file_flags ""
9041 set log_file_file ""
9042 foreach arg [ split "$log_file_info" " "] {
9043 if [string match "-*" $arg] {
9044 lappend log_file_flags $arg
9045 } else {
9046 lappend log_file_file $arg
9050 # If there was an existing file, ensure it is an absolute path, and then
9051 # reset logging.
9052 if { $log_file_file != "" } {
9053 set log_file_file [file normalize $log_file_file]
9054 log_file
9055 log_file $log_file_flags "$log_file_file"
9058 # Call the builtin version of cd.
9059 builtin_cd $dir
9062 # Return a list of all languages supported by GDB, suitable for use in
9063 # 'set language NAME'. This doesn't include the languages auto,
9064 # local, or unknown.
9065 gdb_caching_proc gdb_supported_languages {} {
9066 # The extra space after 'complete set language ' in the command below is
9067 # critical. Only with that space will GDB complete the next level of
9068 # the command, i.e. fill in the actual language names.
9069 set output [remote_exec host $::GDB "$::INTERNAL_GDBFLAGS -batch -ex \"complete set language \""]
9071 if {[lindex $output 0] != 0} {
9072 error "failed to get list of supported languages"
9075 set langs {}
9076 foreach line [split [lindex $output 1] \n] {
9077 if {[regexp "set language (\[^\r\]+)" $line full_match lang]} {
9078 # If LANG is not one of the languages that we ignore, then
9079 # add it to our list of languages.
9080 if {[lsearch -exact {auto local unknown} $lang] == -1} {
9081 lappend langs $lang
9085 return $langs
9088 # Check if debugging is enabled for gdb.
9090 proc gdb_debug_enabled { } {
9091 global gdbdebug
9093 # If not already read, get the debug setting from environment or board setting.
9094 if {![info exists gdbdebug]} {
9095 global env
9096 if [info exists env(GDB_DEBUG)] {
9097 set gdbdebug $env(GDB_DEBUG)
9098 } elseif [target_info exists gdb,debug] {
9099 set gdbdebug [target_info gdb,debug]
9100 } else {
9101 return 0
9105 # Ensure it not empty.
9106 return [expr { $gdbdebug != "" }]
9109 # Turn on debugging if enabled, or reset if already on.
9111 proc gdb_debug_init { } {
9113 global gdb_prompt
9115 if ![gdb_debug_enabled] {
9116 return;
9119 # First ensure logging is off.
9120 send_gdb "set logging enabled off\n"
9122 set debugfile [standard_output_file gdb.debug]
9123 send_gdb "set logging file $debugfile\n"
9125 send_gdb "set logging debugredirect\n"
9127 global gdbdebug
9128 foreach entry [split $gdbdebug ,] {
9129 send_gdb "set debug $entry 1\n"
9132 # Now that everything is set, enable logging.
9133 send_gdb "set logging enabled on\n"
9134 gdb_expect 10 {
9135 -re "Copying output to $debugfile.*Redirecting debug output to $debugfile.*$gdb_prompt $" {}
9136 timeout { warning "Couldn't set logging file" }
9140 # Check if debugging is enabled for gdbserver.
9142 proc gdbserver_debug_enabled { } {
9143 # Always disabled for GDB only setups.
9144 return 0
9147 # Open the file for logging gdb input
9149 proc gdb_stdin_log_init { } {
9150 gdb_persistent_global in_file
9152 if {[info exists in_file]} {
9153 # Close existing file.
9154 catch "close $in_file"
9157 set logfile [standard_output_file_with_gdb_instance gdb.in]
9158 set in_file [open $logfile w]
9161 # Write to the file for logging gdb input.
9162 # TYPE can be one of the following:
9163 # "standard" : Default. Standard message written to the log
9164 # "answer" : Answer to a question (eg "Y"). Not written the log.
9165 # "optional" : Optional message. Not written to the log.
9167 proc gdb_stdin_log_write { message {type standard} } {
9169 global in_file
9170 if {![info exists in_file]} {
9171 return
9174 # Check message types.
9175 switch -regexp -- $type {
9176 "answer" {
9177 return
9179 "optional" {
9180 return
9184 # Write to the log and make sure the output is there, even in case
9185 # of crash.
9186 puts -nonewline $in_file "$message"
9187 flush $in_file
9190 # Write the command line used to invocate gdb to the cmd file.
9192 proc gdb_write_cmd_file { cmdline } {
9193 set logfile [standard_output_file_with_gdb_instance gdb.cmd]
9194 set cmd_file [open $logfile w]
9195 puts $cmd_file $cmdline
9196 catch "close $cmd_file"
9199 # Compare contents of FILE to string STR. Pass with MSG if equal, otherwise
9200 # fail with MSG.
9202 proc cmp_file_string { file str msg } {
9203 if { ![file exists $file]} {
9204 fail "$msg"
9205 return
9208 set caught_error [catch {
9209 set fp [open "$file" r]
9210 set file_contents [read $fp]
9211 close $fp
9212 } error_message]
9213 if {$caught_error} {
9214 error "$error_message"
9215 fail "$msg"
9216 return
9219 if { $file_contents == $str } {
9220 pass "$msg"
9221 } else {
9222 fail "$msg"
9226 # Compare FILE1 and FILE2 as binary files. Return 0 if the files are
9227 # equal, otherwise, return non-zero.
9229 proc cmp_binary_files { file1 file2 } {
9230 set fd1 [open $file1]
9231 fconfigure $fd1 -translation binary
9232 set fd2 [open $file2]
9233 fconfigure $fd2 -translation binary
9235 set blk_size 1024
9236 while {true} {
9237 set blk1 [read $fd1 $blk_size]
9238 set blk2 [read $fd2 $blk_size]
9239 set diff [string compare $blk1 $blk2]
9240 if {$diff != 0 || [eof $fd1] || [eof $fd2]} {
9241 close $fd1
9242 close $fd2
9243 return $diff
9248 # Does the compiler support CTF debug output using '-gctf' compiler
9249 # flag? If not then we should skip these tests. We should also
9250 # skip them if libctf was explicitly disabled.
9252 gdb_caching_proc allow_ctf_tests {} {
9253 global enable_libctf
9255 if {$enable_libctf eq "no"} {
9256 return 0
9259 set can_ctf [gdb_can_simple_compile ctfdebug {
9260 int main () {
9261 return 0;
9263 } executable "additional_flags=-gctf"]
9265 return $can_ctf
9268 # Return 1 if compiler supports -gstatement-frontiers. Otherwise,
9269 # return 0.
9271 gdb_caching_proc supports_statement_frontiers {} {
9272 return [gdb_can_simple_compile supports_statement_frontiers {
9273 int main () {
9274 return 0;
9276 } executable "additional_flags=-gstatement-frontiers"]
9279 # Return 1 if compiler supports -mmpx -fcheck-pointer-bounds. Otherwise,
9280 # return 0.
9282 gdb_caching_proc supports_mpx_check_pointer_bounds {} {
9283 set flags "additional_flags=-mmpx additional_flags=-fcheck-pointer-bounds"
9284 return [gdb_can_simple_compile supports_mpx_check_pointer_bounds {
9285 int main () {
9286 return 0;
9288 } executable $flags]
9291 # Return 1 if compiler supports -fcf-protection=. Otherwise,
9292 # return 0.
9294 gdb_caching_proc supports_fcf_protection {} {
9295 return [gdb_can_simple_compile supports_fcf_protection {
9296 int main () {
9297 return 0;
9299 } executable "additional_flags=-fcf-protection=full"]
9302 # Return true if symbols were read in using -readnow. Otherwise,
9303 # return false.
9305 proc readnow { } {
9306 return [expr {[lsearch -exact $::GDBFLAGS -readnow] != -1
9307 || [lsearch -exact $::GDBFLAGS --readnow] != -1}]
9310 # Return 'gdb_index' if the symbols from OBJFILE were read using a
9311 # .gdb_index index. Return 'debug_names' if the symbols were read
9312 # using a DWARF-5 style .debug_names index. Otherwise, return an
9313 # empty string.
9315 proc have_index { objfile } {
9317 # This proc is mostly used with $binfile, but that gives problems with
9318 # remote host, while using $testfile would work.
9319 # Fix this by reducing $binfile to $testfile.
9320 set objfile [file tail $objfile]
9322 set index_type [get_index_type $objfile]
9324 if { $index_type eq "gdb" } {
9325 return "gdb_index"
9326 } elseif { $index_type eq "dwarf5" } {
9327 return "debug_names"
9328 } else {
9329 return ""
9333 # Return 1 if partial symbols are available. Otherwise, return 0.
9335 proc psymtabs_p { } {
9336 global gdb_prompt
9338 set cmd "maint info psymtab"
9339 gdb_test_multiple $cmd "" {
9340 -re "$cmd\r\n$gdb_prompt $" {
9341 return 0
9343 -re -wrap "" {
9344 return 1
9348 return 0
9351 # Verify that partial symtab expansion for $filename has state $readin.
9353 proc verify_psymtab_expanded { filename readin } {
9354 global gdb_prompt
9356 set cmd "maint info psymtab"
9357 set test "$cmd: $filename: $readin"
9358 set re [multi_line \
9359 " \{ psymtab \[^\r\n\]*$filename\[^\r\n\]*" \
9360 " readin $readin" \
9361 ".*"]
9363 gdb_test_multiple $cmd $test {
9364 -re "$cmd\r\n$gdb_prompt $" {
9365 unsupported $gdb_test_name
9367 -re -wrap $re {
9368 pass $gdb_test_name
9373 # Add a .gdb_index section to PROGRAM.
9374 # PROGRAM is assumed to be the output of standard_output_file.
9375 # Returns the 0 if there is a failure, otherwise 1.
9377 # STYLE controls which style of index to add, if needed. The empty
9378 # string (the default) means .gdb_index; "-dwarf-5" means .debug_names.
9380 proc add_gdb_index { program {style ""} } {
9381 global srcdir GDB env
9382 set contrib_dir "$srcdir/../contrib"
9383 set env(GDB) [append_gdb_data_directory_option $GDB]
9384 set result [catch "exec $contrib_dir/gdb-add-index.sh $style $program" output]
9385 if { $result != 0 } {
9386 verbose -log "result is $result"
9387 verbose -log "output is $output"
9388 return 0
9391 return 1
9394 # Use 'maint print objfiles OBJFILE' to determine what (if any) type
9395 # of index is present in OBJFILE. Return a string indicating the
9396 # index type:
9398 # 'gdb' - Contains a .gdb_index style index,
9400 # 'dwarf5' - Contain DWARF5 style index sections,
9402 # 'readnow' - A fake .gdb_index as a result of readnow being used,
9404 # 'cooked' - The cooked index created when reading non-indexed debug
9405 # information,
9407 # 'none' - There's no index, and no debug information to create a
9408 # cooked index from.
9410 # If something goes wrong then this proc will emit a FAIL and return
9411 # an empty string.
9413 # TESTNAME is used as part of any pass/fail emitted from this proc.
9414 proc get_index_type { objfile { testname "" } } {
9415 if { $testname eq "" } {
9416 set testname "find index type"
9419 set index_type "unknown"
9420 gdb_test_multiple "maint print objfiles ${objfile}" $testname -lbl {
9421 -re "\r\n\\.gdb_index: version ${::decimal}(?=\r\n)" {
9422 set index_type "gdb"
9423 gdb_test_lines "" $gdb_test_name ".*"
9425 -re "\r\n\\.debug_names: exists(?=\r\n)" {
9426 set index_type "dwarf5"
9427 gdb_test_lines "" $gdb_test_name ".*"
9429 -re "\r\n(Cooked index in use:|Psymtabs)(?=\r\n)" {
9430 set index_type "cooked"
9431 gdb_test_lines "" $gdb_test_name ".*"
9433 -re ".gdb_index: faked for \"readnow\"" {
9434 set index_type "readnow"
9435 gdb_test_lines "" $gdb_test_name ".*"
9437 -re -wrap "" {
9438 set index_type "none"
9442 gdb_assert { $index_type ne "unknown" } \
9443 "$testname, check type is valid"
9445 if { $index_type eq "unknown" } {
9446 set index_type ""
9449 return $index_type
9452 # Add a .gdb_index section to PROGRAM, unless it alread has an index
9453 # (.gdb_index/.debug_names). Gdb doesn't support building an index from a
9454 # program already using one. Return 1 if a .gdb_index was added, return 0
9455 # if it already contained an index, and -1 if an error occurred.
9457 # STYLE controls which style of index to add, if needed. The empty
9458 # string (the default) means .gdb_index; "-dwarf-5" means .debug_names.
9460 proc ensure_gdb_index { binfile {style ""} } {
9461 set testfile [file tail $binfile]
9463 set test "check if index present"
9464 set index_type [get_index_type $testfile $test]
9466 if { $index_type eq "gdb" || $index_type eq "dwarf5" } {
9467 return 0
9470 if { $index_type eq "readnow" } {
9471 return -1
9474 if { [add_gdb_index $binfile $style] == "1" } {
9475 return 1
9478 return -1
9481 # Return 1 if executable contains .debug_types section. Otherwise, return 0.
9483 proc debug_types { } {
9484 global hex
9486 set cmd "maint info sections"
9487 gdb_test_multiple $cmd "" {
9488 -re -wrap "at $hex: .debug_types.*" {
9489 return 1
9491 -re -wrap "" {
9492 return 0
9496 return 0
9499 # Return the addresses in the line table for FILE for which is_stmt is true.
9501 proc is_stmt_addresses { file } {
9502 global decimal
9503 global hex
9505 set is_stmt [list]
9507 gdb_test_multiple "maint info line-table $file" "" {
9508 -re "\r\n$decimal\[ \t\]+$decimal\[ \t\]+($hex)\[ \t\]+$hex\[ \t\]+Y\[^\r\n\]*" {
9509 lappend is_stmt $expect_out(1,string)
9510 exp_continue
9512 -re -wrap "" {
9516 return $is_stmt
9519 # Return 1 if hex number VAL is an element of HEXLIST.
9521 proc hex_in_list { val hexlist } {
9522 # Normalize val by removing 0x prefix, and leading zeros.
9523 set val [regsub ^0x $val ""]
9524 set val [regsub ^0+ $val "0"]
9526 set re 0x0*$val
9527 set index [lsearch -regexp $hexlist $re]
9528 return [expr $index != -1]
9531 # As info args, but also add the default values.
9533 proc info_args_with_defaults { name } {
9534 set args {}
9536 foreach arg [info args $name] {
9537 if { [info default $name $arg default_value] } {
9538 lappend args [list $arg $default_value]
9539 } else {
9540 lappend args $arg
9544 return $args
9547 # Override proc NAME to proc OVERRIDE for the duration of the execution of
9548 # BODY.
9550 proc with_override { name override body } {
9551 # Implementation note: It's possible to implement the override using
9552 # rename, like this:
9553 # rename $name save_$name
9554 # rename $override $name
9555 # set code [catch {uplevel 1 $body} result]
9556 # rename $name $override
9557 # rename save_$name $name
9558 # but there are two issues here:
9559 # - the save_$name might clash with an existing proc
9560 # - the override is no longer available under its original name during
9561 # the override
9562 # So, we use this more elaborate but cleaner mechanism.
9564 # Save the old proc, if it exists.
9565 if { [info procs $name] != "" } {
9566 set old_args [info_args_with_defaults $name]
9567 set old_body [info body $name]
9568 set existed true
9569 } else {
9570 set existed false
9573 # Install the override.
9574 set new_args [info_args_with_defaults $override]
9575 set new_body [info body $override]
9576 eval proc $name {$new_args} {$new_body}
9578 # Execute body.
9579 set code [catch {uplevel 1 $body} result]
9581 # Restore old proc if it existed on entry, else delete it.
9582 if { $existed } {
9583 eval proc $name {$old_args} {$old_body}
9584 } else {
9585 rename $name ""
9588 # Return as appropriate.
9589 if { $code == 1 } {
9590 global errorInfo errorCode
9591 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
9592 } elseif { $code > 1 } {
9593 return -code $code $result
9596 return $result
9599 # Run BODY after setting the TERM environment variable to 'ansi', and
9600 # unsetting the NO_COLOR environment variable.
9601 proc with_ansi_styling_terminal { body } {
9602 save_vars { ::env(TERM) ::env(NO_COLOR) } {
9603 # Set environment variables to allow styling.
9604 setenv TERM ansi
9605 unset -nocomplain ::env(NO_COLOR)
9607 set code [catch {uplevel 1 $body} result]
9610 if {$code == 1} {
9611 global errorInfo errorCode
9612 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
9613 } else {
9614 return -code $code $result
9618 # Setup tuiterm.exp environment. To be used in test-cases instead of
9619 # "load_lib tuiterm.exp". Calls initialization function and schedules
9620 # finalization function.
9621 proc tuiterm_env { } {
9622 load_lib tuiterm.exp
9625 # Dejagnu has a version of note, but usage is not allowed outside of dejagnu.
9626 # Define a local version.
9627 proc gdb_note { message } {
9628 verbose -- "NOTE: $message" 0
9631 # Return 1 if compiler supports -fuse-ld=gold, otherwise return 0.
9632 gdb_caching_proc have_fuse_ld_gold {} {
9633 set me "have_fuse_ld_gold"
9634 set flags "additional_flags=-fuse-ld=gold"
9635 set src { int main() { return 0; } }
9636 return [gdb_simple_compile $me $src executable $flags]
9639 # Return 1 if compiler supports fvar-tracking, otherwise return 0.
9640 gdb_caching_proc have_fvar_tracking {} {
9641 set me "have_fvar_tracking"
9642 set flags "additional_flags=-fvar-tracking"
9643 set src { int main() { return 0; } }
9644 return [gdb_simple_compile $me $src executable $flags]
9647 # Return 1 if linker supports -Ttext-segment, otherwise return 0.
9648 gdb_caching_proc linker_supports_Ttext_segment_flag {} {
9649 set me "linker_supports_Ttext_segment_flag"
9650 set flags ldflags="-Wl,-Ttext-segment=0x7000000"
9651 set src { int main() { return 0; } }
9652 return [gdb_simple_compile $me $src executable $flags]
9655 # Return 1 if linker supports -Ttext, otherwise return 0.
9656 gdb_caching_proc linker_supports_Ttext_flag {} {
9657 set me "linker_supports_Ttext_flag"
9658 set flags ldflags="-Wl,-Ttext=0x7000000"
9659 set src { int main() { return 0; } }
9660 return [gdb_simple_compile $me $src executable $flags]
9663 # Return 1 if linker supports --image-base, otherwise 0.
9664 gdb_caching_proc linker_supports_image_base_flag {} {
9665 set me "linker_supports_image_base_flag"
9666 set flags ldflags="-Wl,--image-base=0x7000000"
9667 set src { int main() { return 0; } }
9668 return [gdb_simple_compile $me $src executable $flags]
9672 # Return 1 if compiler supports scalar_storage_order attribute, otherwise
9673 # return 0.
9674 gdb_caching_proc supports_scalar_storage_order_attribute {} {
9675 set me "supports_scalar_storage_order_attribute"
9676 set src {
9677 #include <string.h>
9678 struct sle {
9679 int v;
9680 } __attribute__((scalar_storage_order("little-endian")));
9681 struct sbe {
9682 int v;
9683 } __attribute__((scalar_storage_order("big-endian")));
9684 struct sle sle;
9685 struct sbe sbe;
9686 int main () {
9687 sle.v = sbe.v = 0x11223344;
9688 int same = memcmp (&sle, &sbe, sizeof (int)) == 0;
9689 int sso = !same;
9690 return sso;
9693 if { ![gdb_simple_compile $me $src executable ""] } {
9694 return 0
9697 set target_obj [gdb_remote_download target $obj]
9698 set result [remote_exec target $target_obj]
9699 set status [lindex $result 0]
9700 set output [lindex $result 1]
9701 if { $output != "" } {
9702 return 0
9705 return $status
9708 # Return 1 if compiler supports __GNUC__, otherwise return 0.
9709 gdb_caching_proc supports_gnuc {} {
9710 set me "supports_gnuc"
9711 set src {
9712 #ifndef __GNUC__
9713 #error "No gnuc"
9714 #endif
9716 return [gdb_simple_compile $me $src object ""]
9719 # Return 1 if target supports mpx, otherwise return 0.
9720 gdb_caching_proc have_mpx {} {
9721 global srcdir
9723 set me "have_mpx"
9724 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
9725 verbose "$me: target does not support mpx, returning 0" 2
9726 return 0
9729 # Compile a test program.
9730 set src {
9731 #include "nat/x86-cpuid.h"
9733 int main() {
9734 unsigned int eax, ebx, ecx, edx;
9736 if (!__get_cpuid (1, &eax, &ebx, &ecx, &edx))
9737 return 0;
9739 if ((ecx & bit_OSXSAVE) == bit_OSXSAVE)
9741 if (__get_cpuid_max (0, (void *)0) < 7)
9742 return 0;
9744 __cpuid_count (7, 0, eax, ebx, ecx, edx);
9746 if ((ebx & bit_MPX) == bit_MPX)
9747 return 1;
9750 return 0;
9753 set compile_flags "incdir=${srcdir}/.."
9754 if {![gdb_simple_compile $me $src executable $compile_flags]} {
9755 return 0
9758 set target_obj [gdb_remote_download target $obj]
9759 set result [remote_exec target $target_obj]
9760 set status [lindex $result 0]
9761 set output [lindex $result 1]
9762 if { $output != "" } {
9763 set status 0
9766 remote_file build delete $obj
9768 if { $status == 0 } {
9769 verbose "$me: returning $status" 2
9770 return $status
9773 # Compile program with -mmpx -fcheck-pointer-bounds, try to trigger
9774 # 'No MPX support', in other words, see if kernel supports mpx.
9775 set src { int main (void) { return 0; } }
9776 set comp_flags {}
9777 append comp_flags " additional_flags=-mmpx"
9778 append comp_flags " additional_flags=-fcheck-pointer-bounds"
9779 if {![gdb_simple_compile $me-2 $src executable $comp_flags]} {
9780 return 0
9783 set target_obj [gdb_remote_download target $obj]
9784 set result [remote_exec target $target_obj]
9785 set status [lindex $result 0]
9786 set output [lindex $result 1]
9787 set status [expr ($status == 0) \
9788 && ![regexp "^No MPX support\r?\n" $output]]
9790 remote_file build delete $obj
9792 verbose "$me: returning $status" 2
9793 return $status
9796 # Return 1 if target supports avx, otherwise return 0.
9797 gdb_caching_proc have_avx {} {
9798 global srcdir
9800 set me "have_avx"
9801 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
9802 verbose "$me: target does not support avx, returning 0" 2
9803 return 0
9806 # Compile a test program.
9807 set src {
9808 #include "nat/x86-cpuid.h"
9810 int main() {
9811 unsigned int eax, ebx, ecx, edx;
9813 if (!x86_cpuid (1, &eax, &ebx, &ecx, &edx))
9814 return 0;
9816 if ((ecx & (bit_AVX | bit_OSXSAVE)) == (bit_AVX | bit_OSXSAVE))
9817 return 1;
9818 else
9819 return 0;
9822 set compile_flags "incdir=${srcdir}/.."
9823 if {![gdb_simple_compile $me $src executable $compile_flags]} {
9824 return 0
9827 set target_obj [gdb_remote_download target $obj]
9828 set result [remote_exec target $target_obj]
9829 set status [lindex $result 0]
9830 set output [lindex $result 1]
9831 if { $output != "" } {
9832 set status 0
9835 remote_file build delete $obj
9837 verbose "$me: returning $status" 2
9838 return $status
9841 # Called as
9842 # - require ARG...
9844 # ARG can either be a name, or of the form !NAME.
9846 # Each name is a proc to evaluate in the caller's context. It can return a
9847 # boolean or a two element list with a boolean and a reason string.
9848 # A "!" means to invert the result. If this is true, all is well. If it is
9849 # false, an "unsupported" is emitted and this proc causes the caller to return.
9851 # The reason string is used to provide some context about a require failure,
9852 # and is included in the "unsupported" message.
9854 proc require { args } {
9855 foreach arg $args {
9856 if {[string index $arg 0] == "!"} {
9857 set required_val 0
9858 set fn [string range $arg 1 end]
9859 } else {
9860 set required_val 1
9861 set fn $arg
9864 set result [uplevel 1 $fn]
9865 set len [llength $result]
9866 if { $len == 2 } {
9867 set actual_val [lindex $result 0]
9868 set msg [lindex $result 1]
9869 } elseif { $len == 1 } {
9870 set actual_val $result
9871 set msg ""
9872 } else {
9873 error "proc $fn returned a list of unexpected length $len"
9876 if {$required_val != !!$actual_val} {
9877 if { [string length $msg] > 0 } {
9878 unsupported "require failed: $arg ($msg)"
9879 } else {
9880 unsupported "require failed: $arg"
9883 return -code return 0
9888 # Wait up to ::TIMEOUT seconds for file PATH to exist on the target system.
9889 # Return 1 if it does exist, 0 otherwise.
9891 proc target_file_exists_with_timeout { path } {
9892 for {set i 0} {$i < $::timeout} {incr i} {
9893 if { [remote_file target exists $path] } {
9894 return 1
9897 sleep 1
9900 return 0
9903 gdb_caching_proc has_hw_wp_support {} {
9904 # Power 9, proc rev 2.2 does not support HW watchpoints due to HW bug.
9905 # Need to use a runtime test to determine if the Power processor has
9906 # support for HW watchpoints.
9907 global srcdir subdir gdb_prompt inferior_exited_re
9909 set me "has_hw_wp_support"
9911 global gdb_spawn_id
9912 if { [info exists gdb_spawn_id] } {
9913 error "$me called with running gdb instance"
9916 set compile_flags {debug nowarnings quiet}
9918 # Compile a test program to test if HW watchpoints are supported
9919 set src {
9920 int main (void) {
9921 volatile int local;
9922 local = 1;
9923 if (local == 1)
9924 return 1;
9925 return 0;
9929 if {![gdb_simple_compile $me $src executable $compile_flags]} {
9930 return 0
9933 gdb_start
9934 gdb_reinitialize_dir $srcdir/$subdir
9935 gdb_load "$obj"
9937 if ![runto_main] {
9938 gdb_exit
9939 remote_file build delete $obj
9941 set has_hw_wp_support 0
9942 return $has_hw_wp_support
9945 # The goal is to determine if HW watchpoints are available in general.
9946 # Use "watch" and then check if gdb responds with hardware watch point.
9947 set test "watch local"
9949 gdb_test_multiple $test "Check for HW watchpoint support" {
9950 -re ".*Hardware watchpoint.*" {
9951 # HW watchpoint supported by platform
9952 verbose -log "\n$me: Hardware watchpoint detected"
9953 set has_hw_wp_support 1
9955 -re ".*$gdb_prompt $" {
9956 set has_hw_wp_support 0
9957 verbose -log "\n$me: Default, hardware watchpoint not deteced"
9961 gdb_exit
9962 remote_file build delete $obj
9964 verbose "$me: returning $has_hw_wp_support" 2
9965 return $has_hw_wp_support
9968 # Return a list of all the accepted values of the set command
9969 # "SET_CMD SET_ARG".
9970 # For example get_set_option_choices "set architecture" "i386".
9972 proc get_set_option_choices { set_cmd {set_arg ""} } {
9973 set values {}
9975 if { $set_arg == "" } {
9976 # Add trailing space to signal that we need completion of the choices,
9977 # not of set_cmd itself.
9978 set cmd "complete $set_cmd "
9979 } else {
9980 set cmd "complete $set_cmd $set_arg"
9983 # Set test name without trailing space.
9984 set test [string trim $cmd]
9986 with_set max-completions unlimited {
9987 gdb_test_multiple $cmd $test {
9988 -re "^[string_to_regexp $cmd]\r\n" {
9989 exp_continue
9992 -re "^$set_cmd (\[^\r\n\]+)\r\n" {
9993 lappend values $expect_out(1,string)
9994 exp_continue
9997 -re "^$::gdb_prompt $" {
9998 pass $gdb_test_name
10003 return $values
10006 # Return the compiler that can generate 32-bit ARM executables. Used
10007 # when testing biarch support on Aarch64. If ARM_CC_FOR_TARGET is
10008 # set, use that. If not, try a few common compiler names, making sure
10009 # that the executable they produce can run.
10011 gdb_caching_proc arm_cc_for_target {} {
10012 if {[info exists ::ARM_CC_FOR_TARGET]} {
10013 # If the user specified the compiler explicitly, then don't
10014 # check whether the resulting binary runs outside GDB. Assume
10015 # that it does, and if it turns out it doesn't, then the user
10016 # should get loud FAILs, instead of UNSUPPORTED.
10017 return $::ARM_CC_FOR_TARGET
10020 # Fallback to a few common compiler names. Also confirm the
10021 # produced binary actually runs on the system before declaring
10022 # we've found the right compiler.
10024 if [istarget "*-linux*-*"] {
10025 set compilers {
10026 arm-linux-gnueabi-gcc
10027 arm-none-linux-gnueabi-gcc
10028 arm-linux-gnueabihf-gcc
10030 } else {
10031 set compilers {}
10034 foreach compiler $compilers {
10035 if {![is_remote host] && [which $compiler] == 0} {
10036 # Avoid "default_target_compile: Can't find
10037 # $compiler." warning issued from gdb_compile.
10038 continue
10041 set src { int main() { return 0; } }
10042 if {[gdb_simple_compile aarch64-32bit \
10043 $src \
10044 executable [list compiler=$compiler]]} {
10046 set target_obj [gdb_remote_download target $obj]
10047 set result [remote_exec target $target_obj]
10048 set status [lindex $result 0]
10049 set output [lindex $result 1]
10051 file delete $obj
10053 if { $output == "" && $status == 0} {
10054 return $compiler
10059 return ""
10062 # Step until the pattern REGEXP is found. Step at most
10063 # MAX_STEPS times, but stop stepping once REGEXP is found.
10064 # CURRENT matches current location
10065 # If REGEXP is found then a single pass is emitted, otherwise, after
10066 # MAX_STEPS steps, a single fail is emitted.
10068 # TEST_NAME is the name used in the pass/fail calls.
10070 proc gdb_step_until { regexp {test_name "stepping until regexp"} \
10071 {current "\}"} { max_steps 10 } } {
10072 repeat_cmd_until "step" $current $regexp $test_name "10"
10075 # Do repeated stepping COMMANDs in order to reach TARGET from CURRENT
10077 # COMMAND is a stepping command
10078 # CURRENT is a string matching the current location
10079 # TARGET is a string matching the target location
10080 # TEST_NAME is the test name
10081 # MAX_STEPS is number of steps attempted before fail is emitted
10083 # The function issues repeated COMMANDs as long as the location matches
10084 # CURRENT up to a maximum of MAX_STEPS.
10086 # TEST_NAME passes if the resulting location matches TARGET and fails
10087 # otherwise.
10089 proc repeat_cmd_until { command current target \
10090 {test_name "stepping until regexp"} \
10091 {max_steps 100} } {
10092 global gdb_prompt
10094 set count 0
10095 gdb_test_multiple "$command" "$test_name" {
10096 -re "$target.*$gdb_prompt $" {
10097 pass "$test_name"
10099 -re "$current.*$gdb_prompt $" {
10100 incr count
10101 if { $count < $max_steps } {
10102 send_gdb "$command\n"
10103 exp_continue
10104 } else {
10105 fail "$test_name"
10111 # Return false if the current target is not operating in non-stop
10112 # mode, otherwise, return true.
10114 # The inferior will need to have started running in order to get the
10115 # correct result.
10117 proc is_target_non_stop { {testname ""} } {
10118 # For historical reasons we assume non-stop mode is on. If the
10119 # maintenance command fails for any reason then we're going to
10120 # return true.
10121 set is_non_stop true
10122 gdb_test_multiple "maint show target-non-stop" $testname {
10123 -wrap -re "(is|currently) on.*" {
10124 set is_non_stop true
10126 -wrap -re "(is|currently) off.*" {
10127 set is_non_stop false
10130 return $is_non_stop
10133 # Return the number of worker threads that GDB is currently using.
10135 proc gdb_get_worker_threads { {testname ""} } {
10136 set worker_threads "UNKNOWN"
10137 gdb_test_multiple "maintenance show worker-threads" $testname {
10138 -wrap -re "^The number of worker threads GDB can use is the default \\(currently ($::decimal)\\)\\." {
10139 set worker_threads $expect_out(1,string)
10141 -wrap -re "^The number of worker threads GDB can use is ($::decimal)\\." {
10142 set worker_threads $expect_out(1,string)
10145 return $worker_threads
10148 # Check if the compiler emits epilogue information associated
10149 # with the closing brace or with the last statement line.
10151 # This proc restarts GDB
10153 # Returns True if it is associated with the closing brace,
10154 # False if it is the last statement
10155 gdb_caching_proc have_epilogue_line_info {} {
10157 set main {
10159 main ()
10161 return 0;
10164 if {![gdb_simple_compile "simple_program" $main]} {
10165 return False
10168 clean_restart $obj
10170 gdb_test_multiple "info line 6" "epilogue test" {
10171 -re -wrap ".*starts at address.*and ends at.*" {
10172 return True
10174 -re -wrap ".*" {
10175 return False
10180 # Decompress file BZ2, and return it.
10182 proc decompress_bz2 { bz2 } {
10183 set copy [standard_output_file [file tail $bz2]]
10184 set copy [remote_download build $bz2 $copy]
10185 if { $copy == "" } {
10186 return $copy
10189 set res [remote_exec build "bzip2" "-df $copy"]
10190 if { [lindex $res 0] == -1 } {
10191 return ""
10194 set copy [regsub {.bz2$} $copy ""]
10195 if { ![remote_file build exists $copy] } {
10196 return ""
10199 return $copy
10202 # Return 1 if the output of "ldd FILE" contains regexp DEP, 0 if it doesn't,
10203 # and -1 if there was a problem running the command.
10205 proc has_dependency { file dep } {
10206 set ldd [gdb_find_ldd]
10207 set command "$ldd $file"
10208 set result [remote_exec host $command]
10209 set status [lindex $result 0]
10210 set output [lindex $result 1]
10211 verbose -log "status of $command is $status"
10212 verbose -log "output of $command is $output"
10213 if { $status != 0 || $output == "" } {
10214 return -1
10216 return [regexp $dep $output]
10219 # Detect linux kernel version and return as list of 3 numbers: major, minor,
10220 # and patchlevel. On failure, return an empty list.
10222 gdb_caching_proc linux_kernel_version {} {
10223 if { ![istarget *-*-linux*] } {
10224 return {}
10227 set res [remote_exec target "uname -r"]
10228 set status [lindex $res 0]
10229 set output [lindex $res 1]
10230 if { $status != 0 } {
10231 return {}
10234 set re ^($::decimal)\\.($::decimal)\\.($::decimal)
10235 if { [regexp $re $output dummy v1 v2 v3] != 1 } {
10236 return {}
10239 return [list $v1 $v2 $v3]
10242 # Return 1 if syscall NAME is supported.
10244 proc have_syscall { name } {
10245 set src \
10246 [list \
10247 "#include <sys/syscall.h>" \
10248 "int var = SYS_$name;"]
10249 set src [join $src "\n"]
10250 return [gdb_can_simple_compile have_syscall_$name $src object]
10253 # Return 1 if compile flag FLAG is supported.
10255 gdb_caching_proc have_compile_flag { flag } {
10256 set src { void foo () {} }
10257 return [gdb_can_simple_compile have_compile_flag_$flag $src object \
10258 additional_flags=$flag]
10261 # Return 1 if we can create an executable using compile and link flag FLAG.
10263 gdb_caching_proc have_compile_and_link_flag { flag } {
10264 set src { int main () { return 0; } }
10265 return [gdb_can_simple_compile have_compile_and_link_flag_$flag $src executable \
10266 additional_flags=$flag]
10269 # Return 1 if this GDB is configured with a "native" target.
10271 gdb_caching_proc have_native_target {} {
10272 gdb_test_multiple "help target native" "" {
10273 -re -wrap "Undefined target command.*" {
10274 return 0
10276 -re -wrap "Native process.*" {
10277 return 1
10280 return 0
10283 # Handle include file $srcdir/$subdir/FILE.
10285 proc include_file { file } {
10286 set file [file join $::srcdir $::subdir $file]
10287 if { [is_remote host] } {
10288 set res [remote_download host $file]
10289 } else {
10290 set res $file
10293 return $res
10296 # Handle include file FILE, and if necessary update compiler flags variable
10297 # FLAGS.
10299 proc lappend_include_file { flags file } {
10300 upvar $flags up_flags
10301 if { [is_remote host] } {
10302 gdb_remote_download host $file
10303 } else {
10304 set dir [file dirname $file]
10305 if { $dir != [file join $::srcdir $::subdir] } {
10306 lappend up_flags "additional_flags=-I$dir"
10311 # Return a list of supported host locales.
10313 gdb_caching_proc host_locales { } {
10314 set result [remote_exec host "locale -a"]
10315 set status [lindex $result 0]
10316 set output [lindex $result 1]
10318 if { $status != 0 } {
10319 return {}
10322 # Split into list.
10323 set output [string trim $output]
10324 set l [split $output \n]
10326 # Trim items.
10327 set l [lmap v $l { string trim $v }]
10329 # Normalize items to lower-case.
10330 set l [lmap v $l { string tolower $v }]
10331 # Normalize items to without dash.
10332 set l [lmap v $l { string map { "-" "" } $v }]
10334 return $l
10337 # Return 1 if host locale LOCALE is supported.
10339 proc have_host_locale { locale } {
10340 # Normalize to lower-case.
10341 set locale [string tolower $locale]
10342 # Normalize to without dash.
10343 set locale [string map { "-" "" } $locale]
10345 set idx [lsearch [host_locales] $locale]
10346 return [expr $idx != -1]
10349 # Return 1 if we can use '#include <$file>' in source file.
10351 gdb_caching_proc have_system_header { file } {
10352 set src "#include <$file>"
10353 set name [string map { "/" "_sep_" } $file]
10354 return [gdb_can_simple_compile have_system_header_$name $src object]
10357 # Return 1 if the test is being run as root, 0 otherwise.
10359 gdb_caching_proc root_user {} {
10360 # ID outputs to stdout, we have to use exec to capture it here.
10361 set res [remote_exec target id]
10362 set ret_val [lindex $res 0]
10363 set output [lindex $res 1]
10365 # If ret_val is not 0, we couldn't run `id` on the target for some
10366 # reason. Return that we are not root, so problems are easier to
10367 # spot.
10368 if { $ret_val != 0 } {
10369 return 0
10372 regexp -all ".*uid=(\[0-9\]+).*" $output dummy uid
10374 return [expr $uid == 0]
10377 # Always load compatibility stuff.
10378 load_lib future.exp