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.
23 # Tests would fail, logs on get_compiler_info() would be missing.
24 send_error "`site.exp' not found, run `make site.exp'!\n"
28 # Execute BODY, if COND wrapped in proc WRAP.
29 # Instead of writing the verbose and repetitive:
36 # cond_wrap $cond wrap $body
38 proc cond_wrap { cond wrap body } {
48 # Helper function for set_sanitizer/set_sanitizer_default.
50 proc set_sanitizer_1 { env_var var_id val default} {
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
60 if { $default && [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.
67 # Set var_id (env_var not empty case).
68 append env($env_var) : $var_id=$val
71 # Add VAR_ID=VAL to ENV_VAR.
73 proc set_sanitizer { env_var var_id val } {
74 set_sanitizer_1 $env_var $var_id $val 0
77 # Add VAR_ID=VAL to ENV_VAR, unless ENV_VAR already contains a VAR_ID setting.
79 proc set_sanitizer_default { env_var var_id val } {
80 set_sanitizer_1 $env_var $var_id $val 1
83 set_sanitizer_default TSAN_OPTIONS suppressions \
84 $srcdir/../tsan-suppressions.txt
86 # When using ThreadSanitizer we may run into the case that a race is detected,
87 # but we see the full stack trace only for one of the two accesses, and the
88 # other one is showing "failed to restore the stack".
89 # Try to prevent this by setting history_size to the maximum (7) by default.
90 # See also the ThreadSanitizer docs (
91 # https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags ).
92 set_sanitizer_default TSAN_OPTIONS history_size 7
94 # If GDB is built with ASAN (and because there are leaks), it will output a
95 # leak report when exiting as well as exit with a non-zero (failure) status.
96 # This can affect tests that are sensitive to what GDB prints on stderr or its
97 # exit status. Add `detect_leaks=0` to the ASAN_OPTIONS environment variable
98 # (which will affect any spawned sub-process) to avoid this.
99 set_sanitizer_default ASAN_OPTIONS detect_leaks 0
101 # List of procs to run in gdb_finish.
102 set gdb_finish_hooks [list]
104 # Variable in which we keep track of globals that are allowed to be live
106 array set gdb_persistent_globals {}
108 # Mark variable names in ARG as a persistent global, and declare them as
109 # global in the calling context. Can be used to rewrite "global var_a var_b"
110 # into "gdb_persistent_global var_a var_b".
111 proc gdb_persistent_global { args } {
112 global gdb_persistent_globals
113 foreach varname $args {
114 uplevel 1 global $varname
115 set gdb_persistent_globals($varname) 1
119 # Mark variable names in ARG as a persistent global.
120 proc gdb_persistent_global_no_decl { args } {
121 global gdb_persistent_globals
122 foreach varname $args {
123 set gdb_persistent_globals($varname) 1
127 # Override proc load_lib.
128 rename load_lib saved_load_lib
129 # Run the runtest version of load_lib, and mark all variables that were
130 # created by this call as persistent.
131 proc load_lib { file } {
132 array set known_global {}
133 foreach varname [info globals] {
134 set known_globals($varname) 1
137 set code [catch "saved_load_lib $file" result]
139 foreach varname [info globals] {
140 if { ![info exists known_globals($varname)] } {
141 gdb_persistent_global_no_decl $varname
146 global errorInfo errorCode
147 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
148 } elseif {$code > 1} {
149 return -code $code $result
155 load_lib libgloss.exp
157 load_lib gdb-utils.exp
159 load_lib check-test-names.exp
161 # The path to the GCORE script to test.
163 if {![info exists GCORE]} {
164 set GCORE [findfile $base_dir/../../gdb/gcore]
166 verbose "using GCORE = $GCORE" 2
168 # Return 0 if the gcore scipt is missing.
169 proc has_gcore_script {} {
178 # The path to the GDB binary to test.
181 # The data directory to use for testing. If this is the empty string,
182 # then we let GDB use its own configured data directory.
183 global GDB_DATA_DIRECTORY
185 # The spawn ID used for I/O interaction with the inferior. For native
186 # targets, or remote targets that can do I/O through GDB
187 # (semi-hosting) this will be the same as the host/GDB's spawn ID.
188 # Otherwise, the board may set this to some other spawn ID. E.g.,
189 # when debugging with GDBserver, this is set to GDBserver's spawn ID,
190 # so input/output is done on gdbserver's tty.
191 global inferior_spawn_id
193 if [info exists TOOL_EXECUTABLE] {
194 set GDB $TOOL_EXECUTABLE
196 if ![info exists GDB] {
197 if ![is_remote host] {
198 set GDB [findfile $base_dir/../../gdb/gdb "$base_dir/../../gdb/gdb" [transform gdb]]
200 set GDB [transform gdb]
203 # If the user specifies GDB on the command line, and doesn't
204 # specify GDB_DATA_DIRECTORY, then assume we're testing an
205 # installed GDB, and let it use its own configured data directory.
206 if ![info exists GDB_DATA_DIRECTORY] {
207 set GDB_DATA_DIRECTORY ""
210 verbose "using GDB = $GDB" 2
212 # The data directory the testing GDB will use. By default, assume
213 # we're testing a non-installed GDB in the build directory. Users may
214 # also explicitly override the -data-directory from the command line.
215 if ![info exists GDB_DATA_DIRECTORY] {
216 set GDB_DATA_DIRECTORY [file normalize "[pwd]/../data-directory"]
218 verbose "using GDB_DATA_DIRECTORY = $GDB_DATA_DIRECTORY" 2
220 # GDBFLAGS is available for the user to set on the command line.
221 # E.g. make check RUNTESTFLAGS=GDBFLAGS=mumble
222 # Testcases may use it to add additional flags, but they must:
223 # - append new flags, not overwrite
224 # - restore the original value when done
226 if ![info exists GDBFLAGS] {
229 verbose "using GDBFLAGS = $GDBFLAGS" 2
231 # Append the -data-directory option to pass to GDB to CMDLINE and
232 # return the resulting string. If GDB_DATA_DIRECTORY is empty,
233 # nothing is appended.
234 proc append_gdb_data_directory_option {cmdline} {
235 global GDB_DATA_DIRECTORY
237 if { $GDB_DATA_DIRECTORY != "" } {
238 return "$cmdline -data-directory $GDB_DATA_DIRECTORY"
244 # INTERNAL_GDBFLAGS contains flags that the testsuite requires.
245 # `-nw' disables any of the windowed interfaces.
246 # `-nx' disables ~/.gdbinit, so that it doesn't interfere with the tests.
247 # `-iex "set {height,width} 0"' disables pagination.
248 # `-data-directory' points to the data directory, usually in the build
250 global INTERNAL_GDBFLAGS
251 if ![info exists INTERNAL_GDBFLAGS] {
252 set INTERNAL_GDBFLAGS \
257 {-iex "set height 0"} \
258 {-iex "set width 0"}]]
260 # If DEBUGINFOD_URLS is set, gdb will try to download sources and
261 # debug info for f.i. system libraries. Prevent this.
262 if { [is_remote host] } {
263 # Setting environment variables on build has no effect on remote host,
264 # so handle this using "set debuginfod enabled off" instead.
265 set INTERNAL_GDBFLAGS \
266 "$INTERNAL_GDBFLAGS -iex \"set debuginfod enabled off\""
268 # See default_gdb_init.
271 set INTERNAL_GDBFLAGS [append_gdb_data_directory_option $INTERNAL_GDBFLAGS]
274 # The variable gdb_prompt is a regexp which matches the gdb prompt.
275 # Set it if it is not already set. This is also set by default_gdb_init
276 # but it's not clear what removing one of them will break.
277 # See with_gdb_prompt for more details on prompt handling.
279 if {![info exists gdb_prompt]} {
280 set gdb_prompt "\\(gdb\\)"
283 # A regexp that matches the pagination prompt.
284 set pagination_prompt \
285 "--Type <RET> for more, q to quit, c to continue without paging--"
287 # The variable fullname_syntax_POSIX is a regexp which matches a POSIX
288 # absolute path ie. /foo/
289 set fullname_syntax_POSIX {/[^\n]*/}
290 # The variable fullname_syntax_UNC is a regexp which matches a Windows
291 # UNC path ie. \\D\foo\
292 set fullname_syntax_UNC {\\\\[^\\]+\\[^\n]+\\}
293 # The variable fullname_syntax_DOS_CASE is a regexp which matches a
294 # particular DOS case that GDB most likely will output
295 # ie. \foo\, but don't match \\.*\
296 set fullname_syntax_DOS_CASE {\\[^\\][^\n]*\\}
297 # The variable fullname_syntax_DOS is a regexp which matches a DOS path
298 # ie. a:\foo\ && a:foo\
299 set fullname_syntax_DOS {[a-zA-Z]:[^\n]*\\}
300 # The variable fullname_syntax is a regexp which matches what GDB considers
301 # an absolute path. It is currently debatable if the Windows style paths
302 # d:foo and \abc should be considered valid as an absolute path.
303 # Also, the purpse of this regexp is not to recognize a well formed
304 # absolute path, but to say with certainty that a path is absolute.
305 set fullname_syntax "($fullname_syntax_POSIX|$fullname_syntax_UNC|$fullname_syntax_DOS_CASE|$fullname_syntax_DOS)"
307 # Needed for some tests under Cygwin.
311 if ![info exists env(EXEEXT)] {
314 set EXEEXT $env(EXEEXT)
319 set inferior_exited_re "(?:\\\[Inferior \[0-9\]+ \\(\[^\n\r\]*\\) exited)"
321 # A regular expression that matches the first word of a thread
322 # description after the thread number info 'info threads'
323 set tdlabel_re "(process|Thread|LWP)"
325 # A regular expression that matches a value history number.
327 set valnum_re "\\\$$decimal"
329 # A regular expression that matches a breakpoint hit with a breakpoint
330 # having several code locations.
331 set bkptno_num_re "$decimal\\.$decimal"
333 # A regular expression that matches a breakpoint hit
334 # with one or several code locations.
335 set bkptno_numopt_re "($decimal\\.$decimal|$decimal)"
337 ### Only procedures should come after this point.
340 # gdb_version -- extract and print the version number of GDB
342 proc default_gdb_version {} {
344 global INTERNAL_GDBFLAGS GDBFLAGS
348 if {[info exists inotify_pid]} {
349 eval exec kill $inotify_pid
352 set output [remote_exec host "$GDB $INTERNAL_GDBFLAGS --version"]
353 set tmp [lindex $output 1]
355 regexp " \[0-9\]\[^ \t\n\r\]+" "$tmp" version
356 if ![is_remote host] {
357 clone_output "[which $GDB] version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
359 clone_output "$GDB on remote host version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
363 proc gdb_version { } {
364 return [default_gdb_version]
367 # gdb_unload -- unload a file if one is loaded
369 # Returns the same as gdb_test_multiple.
371 proc gdb_unload { {msg "file"} } {
374 return [gdb_test_multiple "file" $msg {
375 -re "A program is being debugged already.\r\nAre you sure you want to change the file. .y or n. $" {
376 send_gdb "y\n" answer
380 -re "No executable file now\\.\r\n" {
384 -re "Discard symbol table from `.*'. .y or n. $" {
385 send_gdb "y\n" answer
389 -re -wrap "No symbol file now\\." {
395 # Many of the tests depend on setting breakpoints at various places and
396 # running until that breakpoint is reached. At times, we want to start
397 # with a clean-slate with respect to breakpoints, so this utility proc
398 # lets us do this without duplicating this code everywhere.
401 proc delete_breakpoints {} {
404 # we need a larger timeout value here or this thing just confuses
405 # itself. May need a better implementation if possible. - guo
409 set msg "delete all breakpoints, watchpoints, tracepoints, and catchpoints in delete_breakpoints"
411 gdb_test_multiple "delete breakpoints" "$msg" {
412 -re "Delete all breakpoints, watchpoints, tracepoints, and catchpoints.*y or n.*$" {
413 send_gdb "y\n" answer
416 -re "$gdb_prompt $" {
422 # Confirm with "info breakpoints".
424 set msg "info breakpoints"
425 gdb_test_multiple $msg $msg {
426 -re "No breakpoints, watchpoints, tracepoints, or catchpoints..*$gdb_prompt $" {
429 -re "$gdb_prompt $" {
435 perror "breakpoints not deleted"
439 # Returns true iff the target supports using the "run" command.
441 proc target_can_use_run_cmd { {target_description ""} } {
442 if { $target_description == "" } {
444 } elseif { $target_description == "core" } {
445 # We could try to figure this out by issuing an "info target" and
446 # checking for "Local core dump file:", but it would mean the proc
447 # would start requiring a current target. Also, uses while gdb
448 # produces non-standard output due to, say annotations would
449 # have to be moved around or eliminated, which would further limit
453 error "invalid argument: $target_description"
456 if [target_info exists use_gdb_stub] {
457 # In this case, when we connect, the inferior is already
462 if { $have_core && [target_info gdb_protocol] == "extended-remote" } {
463 # In this case, when we connect, the inferior is not running but
464 # cannot be made to run.
472 # Generic run command.
474 # Return 0 if we could start the program, -1 if we could not.
476 # The second pattern below matches up to the first newline *only*.
477 # Using ``.*$'' could swallow up output that we attempt to match
480 # INFERIOR_ARGS is passed as arguments to the start command, so may contain
481 # inferior arguments.
483 # N.B. This function does not wait for gdb to return to the prompt,
484 # that is the caller's responsibility.
486 proc gdb_run_cmd { {inferior_args {}} } {
487 global gdb_prompt use_gdb_stub
489 foreach command [gdb_init_commands] {
490 send_gdb "$command\n"
492 -re "$gdb_prompt $" { }
494 perror "gdb_init_command for target failed"
501 if [target_info exists gdb,do_reload_on_run] {
502 if { [gdb_reload $inferior_args] != 0 } {
505 send_gdb "continue\n"
507 -re "Continu\[^\r\n\]*\[\r\n\]" {}
513 if [target_info exists gdb,start_symbol] {
514 set start [target_info gdb,start_symbol]
518 send_gdb "jump *$start\n"
520 while { $start_attempt } {
521 # Cap (re)start attempts at three to ensure that this loop
522 # always eventually fails. Don't worry about trying to be
523 # clever and not send a command when it has failed.
524 if [expr $start_attempt > 3] {
525 perror "Jump to start() failed (retry count exceeded)"
528 set start_attempt [expr $start_attempt + 1]
530 -re "Continuing at \[^\r\n\]*\[\r\n\]" {
533 -re "No symbol \"_start\" in current.*$gdb_prompt $" {
534 perror "Can't find start symbol to run in gdb_run"
537 -re "No symbol \"start\" in current.*$gdb_prompt $" {
538 send_gdb "jump *_start\n"
540 -re "No symbol.*context.*$gdb_prompt $" {
543 -re "Line.* Jump anyway.*y or n. $" {
544 send_gdb "y\n" answer
546 -re "The program is not being run.*$gdb_prompt $" {
547 if { [gdb_reload $inferior_args] != 0 } {
550 send_gdb "jump *$start\n"
553 perror "Jump to start() failed (timeout)"
562 if [target_info exists gdb,do_reload_on_run] {
563 if { [gdb_reload $inferior_args] != 0 } {
567 send_gdb "run $inferior_args\n"
568 # This doesn't work quite right yet.
569 # Use -notransfer here so that test cases (like chng-sym.exp)
570 # may test for additional start-up messages.
572 -re "The program .* has been started already.*y or n. $" {
573 send_gdb "y\n" answer
576 -notransfer -re "Starting program: \[^\r\n\]*" {}
577 -notransfer -re "$gdb_prompt $" {
578 # There is no more input expected.
580 -notransfer -re "A problem internal to GDB has been detected" {
581 # Let caller handle this.
588 # Generic start command. Return 0 if we could start the program, -1
591 # INFERIOR_ARGS is passed as arguments to the start command, so may contain
592 # inferior arguments.
594 # N.B. This function does not wait for gdb to return to the prompt,
595 # that is the caller's responsibility.
597 proc gdb_start_cmd { {inferior_args {}} } {
598 global gdb_prompt use_gdb_stub
600 foreach command [gdb_init_commands] {
601 send_gdb "$command\n"
603 -re "$gdb_prompt $" { }
605 perror "gdb_init_command for target failed"
615 send_gdb "start $inferior_args\n"
616 # Use -notransfer here so that test cases (like chng-sym.exp)
617 # may test for additional start-up messages.
619 -re "The program .* has been started already.*y or n. $" {
620 send_gdb "y\n" answer
623 -notransfer -re "Starting program: \[^\r\n\]*" {
626 -re "$gdb_prompt $" { }
631 # Generic starti command. Return 0 if we could start the program, -1
634 # INFERIOR_ARGS is passed as arguments to the starti command, so may contain
635 # inferior arguments.
637 # N.B. This function does not wait for gdb to return to the prompt,
638 # that is the caller's responsibility.
640 proc gdb_starti_cmd { {inferior_args {}} } {
641 global gdb_prompt use_gdb_stub
643 foreach command [gdb_init_commands] {
644 send_gdb "$command\n"
646 -re "$gdb_prompt $" { }
648 perror "gdb_init_command for target failed"
658 send_gdb "starti $inferior_args\n"
660 -re "The program .* has been started already.*y or n. $" {
661 send_gdb "y\n" answer
664 -re "Starting program: \[^\r\n\]*" {
671 # Set a breakpoint using LINESPEC.
673 # If there is an additional argument it is a list of options; the supported
674 # options are allow-pending, temporary, message, no-message and qualified.
676 # The result is 1 for success, 0 for failure.
678 # Note: The handling of message vs no-message is messed up, but it's based
679 # on historical usage. By default this function does not print passes,
681 # no-message: turns off printing of fails (and passes, but they're already off)
682 # message: turns on printing of passes (and fails, but they're already on)
684 proc gdb_breakpoint { linespec args } {
688 set pending_response n
689 if {[lsearch -exact $args allow-pending] != -1} {
690 set pending_response y
693 set break_command "break"
694 set break_message "Breakpoint"
695 if {[lsearch -exact $args temporary] != -1} {
696 set break_command "tbreak"
697 set break_message "Temporary breakpoint"
700 if {[lsearch -exact $args qualified] != -1} {
701 append break_command " -qualified"
706 set no_message_loc [lsearch -exact $args no-message]
707 set message_loc [lsearch -exact $args message]
708 # The last one to appear in args wins.
709 if { $no_message_loc > $message_loc } {
711 } elseif { $message_loc > $no_message_loc } {
715 set test_name "gdb_breakpoint: set breakpoint at $linespec"
716 # The first two regexps are what we get with -g, the third is without -g.
717 gdb_test_multiple "$break_command $linespec" $test_name {
718 -re "$break_message \[0-9\]* at .*: file .*, line $decimal.\r\n$gdb_prompt $" {}
719 -re "$break_message \[0-9\]*: file .*, line $decimal.\r\n$gdb_prompt $" {}
720 -re "$break_message \[0-9\]* at .*$gdb_prompt $" {}
721 -re "$break_message \[0-9\]* \\(.*\\) pending.*$gdb_prompt $" {
722 if {$pending_response == "n"} {
729 -re "Make breakpoint pending.*y or \\\[n\\\]. $" {
730 send_gdb "$pending_response\n"
733 -re "$gdb_prompt $" {
746 # Set breakpoint at function and run gdb until it breaks there.
747 # Since this is the only breakpoint that will be set, if it stops
748 # at a breakpoint, we will assume it is the one we want. We can't
749 # just compare to "function" because it might be a fully qualified,
750 # single quoted C++ function specifier.
752 # If there are additional arguments, pass them to gdb_breakpoint.
753 # We recognize no-message/message ourselves as well as no-delete-brekpoints.
755 # no-message is messed up here, like gdb_breakpoint: to preserve
756 # historical usage fails are always printed by default.
757 # no-message: turns off printing of fails (and passes, but they're already off)
758 # message: turns on printing of passes (and fails, but they're already on)
760 # The 'no-delete-brekpoints' option stops this proc from deleting all
763 proc runto { linespec args } {
765 global bkptno_numopt_re
768 if {[lsearch -exact $args no-delete-breakpoints] == -1} {
774 set no_message_loc [lsearch -exact $args no-message]
775 set message_loc [lsearch -exact $args message]
776 # The last one to appear in args wins.
777 if { $no_message_loc > $message_loc } {
779 } elseif { $message_loc > $no_message_loc } {
783 set test_name "runto: run to $linespec"
785 if {![gdb_breakpoint $linespec {*}$args]} {
791 # the "at foo.c:36" output we get with -g.
792 # the "in func" output we get without -g.
794 -re "(?:Break|Temporary break).* at .*:.*$decimal.*$gdb_prompt $" {
800 -re "(?:Breakpoint|Temporary breakpoint) $bkptno_numopt_re, \[0-9xa-f\]* in .*$gdb_prompt $" {
806 -re "The target does not support running in non-stop mode.\r\n$gdb_prompt $" {
808 unsupported "non-stop mode not supported"
812 -re ".*A problem internal to GDB has been detected" {
813 # Always emit a FAIL if we encounter an internal error: internal
814 # errors are never expected.
815 fail "$test_name (GDB internal error)"
816 gdb_internal_error_resync
819 -re "$gdb_prompt $" {
827 fail "$test_name (eof)"
833 fail "$test_name (timeout)"
844 # Ask gdb to run until we hit a breakpoint at main.
846 # N.B. By default this function deletes all existing breakpoints. If
847 # you don't want that then pass the 'no-delete-breakpoints' argument.
849 proc runto_main { args } {
850 return [runto main qualified {*}$args]
853 ### Continue, and expect to hit a breakpoint.
854 ### Report a pass or fail, depending on whether it seems to have
855 ### worked. Use NAME as part of the test name; each call to
856 ### continue_to_breakpoint should use a NAME which is unique within
858 proc gdb_continue_to_breakpoint {name {location_pattern .*}} {
860 set full_name "continue to breakpoint: $name"
862 set kfail_pattern "Process record does not support instruction 0xfae64 at.*"
863 return [gdb_test_multiple "continue" $full_name {
864 -re "(?:Breakpoint|Temporary breakpoint) .* (at|in) $location_pattern\r\n$gdb_prompt $" {
867 -re "(?:$kfail_pattern)\r\n$gdb_prompt $" {
868 kfail "gdb/25038" $full_name
873 # Check whether GDB is stopped at the given instruction.
874 # INSTRUCTION should be just its mnemonic, without any arguments.
876 proc is_at_instruction { instruction } {
877 global gdb_prompt hex
879 set test "pc points to $instruction"
880 gdb_test_multiple {x/i $pc} $test {
881 -re -wrap "=> $hex \[^\r\n\]+:\t$instruction\t\[^\r\n\]+" {
884 -re "\r\n$gdb_prompt $" {
892 # Single-steps GDB until it arrives at the given instruction.
893 # INSTRUCTION should be just its mnemonic, without any arguments.
895 proc arrive_at_instruction { instruction } {
898 while { [is_at_instruction $instruction] != 1 } {
899 gdb_test -nopass "stepi" "\[^\r\n\]+" \
900 "stepi #$count to reach $instruction"
904 fail "didn't reach $instruction"
912 # gdb_internal_error_resync:
914 # Answer the questions GDB asks after it reports an internal error
915 # until we get back to a GDB prompt. Decline to quit the debugging
916 # session, and decline to create a core file. Return non-zero if the
919 # This procedure just answers whatever questions come up until it sees
920 # a GDB prompt; it doesn't require you to have matched the input up to
921 # any specific point. However, it only answers questions it sees in
922 # the output itself, so if you've matched a question, you had better
923 # answer it yourself before calling this.
925 # You can use this function thus:
929 # -re ".*A problem internal to GDB has been detected" {
930 # gdb_internal_error_resync
935 proc gdb_internal_error_resync {} {
938 verbose -log "Resyncing due to internal error."
941 while {$count < 10} {
943 -re "Recursive internal problem\\." {
944 perror "Could not resync from internal error (recursive internal problem)"
947 -re "Quit this debugging session\\? \\(y or n\\) $" {
948 send_gdb "n\n" answer
951 -re "Create a core file of GDB\\? \\(y or n\\) $" {
952 send_gdb "n\n" answer
955 -re "$gdb_prompt $" {
956 # We're resynchronized.
960 perror "Could not resync from internal error (timeout)"
964 perror "Could not resync from internal error (eof)"
969 perror "Could not resync from internal error (resync count exceeded)"
973 # Fill in the default prompt if PROMPT_REGEXP is empty.
975 # If WITH_ANCHOR is true and the default prompt is used, append a `$` at the end
976 # of the regexp, to anchor the match at the end of the buffer.
977 proc fill_in_default_prompt {prompt_regexp with_anchor} {
978 if { "$prompt_regexp" == "" } {
979 set prompt "$::gdb_prompt "
981 if { $with_anchor } {
987 return $prompt_regexp
990 # Generate message from COMMAND.
992 # This is not trivial in the case that the command contains parentheses.
993 # Trailing text between parentheses prefixed with a space is interpreted as
994 # extra information, and not as part of the test name [1]. Consequently,
995 # "PASS: print (1)" and "PASS: print (2)" count as duplicates.
997 # We fix this here by using "PASS: gdb-command<print (1)>" and
998 # "PASS: gdb-command<print (2)>".
1000 # A trivial way to fix this in a test-case is by using gdb_test "print(1)",
1001 # which produces the nicer-looking "PASS: print(1)".
1003 # [1] https://sourceware.org/gdb/wiki/GDBTestcaseCookbook#Do_not_use_.22tail_parentheses.22_on_test_messages
1005 proc command_to_message { command } {
1006 set message $command
1008 if { [regexp { \(([^()]*)\)$} $message] } {
1009 set message gdb-command<$message>
1015 # gdb_test_multiple COMMAND MESSAGE [ -prompt PROMPT_REGEXP] [ -lbl ]
1017 # Send a command to gdb; test the result.
1019 # COMMAND is the command to execute, send to GDB with send_gdb. If
1020 # this is the null string no command is sent.
1021 # MESSAGE is a message to be printed with the built-in failure patterns
1022 # if one of them matches. If MESSAGE is empty COMMAND will be used.
1023 # -prompt PROMPT_REGEXP specifies a regexp matching the expected prompt
1024 # after the command output. If empty, defaults to "$gdb_prompt $".
1025 # -no-prompt-anchor specifies that if the default prompt regexp is used, it
1026 # should not be anchored at the end of the buffer. This means that the
1027 # pattern can match even if there is stuff output after the prompt. Does not
1028 # have any effect if -prompt is specified.
1029 # -lbl specifies that line-by-line matching will be used.
1030 # EXPECT_ARGUMENTS will be fed to expect in addition to the standard
1031 # patterns. Pattern elements will be evaluated in the caller's
1032 # context; action elements will be executed in the caller's context.
1033 # Unlike patterns for gdb_test, these patterns should generally include
1034 # the final newline and prompt.
1037 # 1 if the test failed, according to a built-in failure pattern
1038 # 0 if only user-supplied patterns matched
1039 # -1 if there was an internal error.
1041 # You can use this function thus:
1043 # gdb_test_multiple "print foo" "test foo" {
1044 # -re "expected output 1" {
1047 # -re "expected output 2" {
1052 # Within action elements you can also make use of the variable
1053 # gdb_test_name. This variable is setup automatically by
1054 # gdb_test_multiple, and contains the value of MESSAGE. You can then
1055 # write this, which is equivalent to the above:
1057 # gdb_test_multiple "print foo" "test foo" {
1058 # -re "expected output 1" {
1059 # pass $gdb_test_name
1061 # -re "expected output 2" {
1062 # fail $gdb_test_name
1066 # Like with "expect", you can also specify the spawn id to match with
1067 # -i "$id". Interesting spawn ids are $inferior_spawn_id and
1068 # $gdb_spawn_id. The former matches inferior I/O, while the latter
1069 # matches GDB I/O. E.g.:
1071 # send_inferior "hello\n"
1072 # gdb_test_multiple "continue" "test echo" {
1073 # -i "$inferior_spawn_id" -re "^hello\r\nhello\r\n$" {
1076 # -i "$gdb_spawn_id" -re "Breakpoint.*$gdb_prompt $" {
1077 # fail "hit breakpoint"
1081 # The standard patterns, such as "Inferior exited..." and "A problem
1082 # ...", all being implicitly appended to that list. These are always
1083 # expected from $gdb_spawn_id. IOW, callers do not need to worry
1084 # about resetting "-i" back to $gdb_spawn_id explicitly.
1086 # In EXPECT_ARGUMENTS we can use a -wrap pattern flag, that wraps the regexp
1087 # pattern as gdb_test wraps its message argument.
1088 # This allows us to rewrite:
1089 # gdb_test <command> <pattern> <message>
1091 # gdb_test_multiple <command> <message> {
1092 # -re -wrap <pattern> {
1093 # pass $gdb_test_name
1096 # The special handling of '^' that is available in gdb_test is also
1097 # supported in gdb_test_multiple when -wrap is used.
1099 # In EXPECT_ARGUMENTS, a pattern flag -early can be used. It makes sure the
1100 # pattern is inserted before any implicit pattern added by gdb_test_multiple.
1101 # Using this pattern flag, we can f.i. setup a kfail for an assertion failure
1102 # <assert> during gdb_continue_to_breakpoint by the rewrite:
1103 # gdb_continue_to_breakpoint <msg> <pattern>
1105 # set breakpoint_pattern "(?:Breakpoint|Temporary breakpoint) .* (at|in)"
1106 # gdb_test_multiple "continue" "continue to breakpoint: <msg>" {
1107 # -early -re "internal-error: <assert>" {
1108 # setup_kfail gdb/nnnnn "*-*-*"
1111 # -re "$breakpoint_pattern <pattern>\r\n$gdb_prompt $" {
1112 # pass $gdb_test_name
1116 proc gdb_test_multiple { command message args } {
1117 global verbose use_gdb_stub
1118 global gdb_prompt pagination_prompt
1121 global inferior_exited_re
1122 upvar timeout timeout
1123 upvar expect_out expect_out
1127 set prompt_regexp ""
1129 for {set i 0} {$i < [llength $args]} {incr i} {
1130 set arg [lindex $args $i]
1131 if { $arg == "-prompt" } {
1133 set prompt_regexp [lindex $args $i]
1134 } elseif { $arg == "-lbl" } {
1136 } elseif { $arg == "-no-prompt-anchor" } {
1143 if { [expr $i + 1] < [llength $args] } {
1144 error "Too many arguments to gdb_test_multiple"
1145 } elseif { ![info exists user_code] } {
1146 error "Too few arguments to gdb_test_multiple"
1149 set prompt_regexp [fill_in_default_prompt $prompt_regexp $prompt_anchor]
1151 if { $message == "" } {
1152 set message [command_to_message $command]
1155 if [string match "*\[\r\n\]" $command] {
1156 error "Invalid trailing newline in \"$command\" command"
1159 if [string match "*\[\003\004\]" $command] {
1160 error "Invalid trailing control code in \"$command\" command"
1163 if [string match "*\[\r\n\]*" $message] {
1164 error "Invalid newline in \"$message\" test"
1168 && [regexp -nocase {^\s*(r|run|star|start|at|att|atta|attac|attach)\M} \
1170 error "gdbserver does not support $command without extended-remote"
1173 # TCL/EXPECT WART ALERT
1174 # Expect does something very strange when it receives a single braced
1175 # argument. It splits it along word separators and performs substitutions.
1176 # This means that { "[ab]" } is evaluated as "[ab]", but { "\[ab\]" } is
1177 # evaluated as "\[ab\]". But that's not how TCL normally works; inside a
1178 # double-quoted list item, "\[ab\]" is just a long way of representing
1179 # "[ab]", because the backslashes will be removed by lindex.
1181 # Unfortunately, there appears to be no easy way to duplicate the splitting
1182 # that expect will do from within TCL. And many places make use of the
1183 # "\[0-9\]" construct, so we need to support that; and some places make use
1184 # of the "[func]" construct, so we need to support that too. In order to
1185 # get this right we have to substitute quoted list elements differently
1186 # from braced list elements.
1188 # We do this roughly the same way that Expect does it. We have to use two
1189 # lists, because if we leave unquoted newlines in the argument to uplevel
1190 # they'll be treated as command separators, and if we escape newlines
1191 # we mangle newlines inside of command blocks. This assumes that the
1192 # input doesn't contain a pattern which contains actual embedded newlines
1195 regsub -all {\n} ${user_code} { } subst_code
1196 set subst_code [uplevel list $subst_code]
1198 set processed_code ""
1199 set early_processed_code ""
1200 # The variable current_list holds the name of the currently processed
1201 # list, either processed_code or early_processed_code.
1202 set current_list "processed_code"
1204 set expecting_action 0
1207 foreach item $user_code subst_item $subst_code {
1208 if { $item == "-n" || $item == "-notransfer" || $item == "-nocase" } {
1209 lappend $current_list $item
1212 if { $item == "-indices" || $item == "-re" || $item == "-ex" } {
1213 lappend $current_list $item
1216 if { $item == "-early" } {
1217 set current_list "early_processed_code"
1220 if { $item == "-timeout" || $item == "-i" } {
1222 lappend $current_list $item
1225 if { $item == "-wrap" } {
1229 if { $expecting_arg } {
1231 lappend $current_list $subst_item
1234 if { $expecting_action } {
1235 lappend $current_list "uplevel [list $item]"
1236 set expecting_action 0
1237 # Cosmetic, no effect on the list.
1238 append $current_list "\n"
1239 # End the effect of -early, it only applies to one action.
1240 set current_list "processed_code"
1243 set expecting_action 1
1244 if { $wrap_pattern } {
1245 # Wrap subst_item as is done for the gdb_test PATTERN argument.
1246 if {[string range $subst_item 0 0] eq "^"} {
1247 if {$command ne ""} {
1248 set command_regex [string_to_regexp $command]
1249 set subst_item [string range $subst_item 1 end]
1250 if {[string length "$subst_item"] > 0} {
1251 # We have an output pattern (other than the '^'),
1252 # add a newline at the start, this will eventually
1253 # sit between the command and the output pattern.
1254 set subst_item "\r\n${subst_item}"
1256 set subst_item "^${command_regex}${subst_item}"
1259 lappend $current_list \
1260 "(?:$subst_item)\r\n$prompt_regexp"
1263 lappend $current_list $subst_item
1265 if {$patterns != ""} {
1266 append patterns "; "
1268 append patterns "\"$subst_item\""
1271 # Also purely cosmetic.
1272 regsub -all {\r} $patterns {\\r} patterns
1273 regsub -all {\n} $patterns {\\n} patterns
1276 send_user "Sending \"$command\" to gdb\n"
1277 send_user "Looking to match \"$patterns\"\n"
1278 send_user "Message is \"$message\"\n"
1282 set string "${command}\n"
1283 if { $command != "" } {
1284 set multi_line_re "\[\r\n\] *>"
1285 while { "$string" != "" } {
1286 set foo [string first "\n" "$string"]
1287 set len [string length "$string"]
1288 if { $foo < [expr $len - 1] } {
1289 set str [string range "$string" 0 $foo]
1290 if { [send_gdb "$str"] != "" } {
1291 verbose -log "Couldn't send $command to GDB."
1295 # since we're checking if each line of the multi-line
1296 # command are 'accepted' by GDB here,
1297 # we need to set -notransfer expect option so that
1298 # command output is not lost for pattern matching
1301 -notransfer -re "$multi_line_re$" { verbose "partial: match" 3 }
1302 timeout { verbose "partial: timeout" 3 }
1304 set string [string range "$string" [expr $foo + 1] end]
1305 set multi_line_re "$multi_line_re.*\[\r\n\] *>"
1310 if { "$string" != "" } {
1311 if { [send_gdb "$string"] != "" } {
1312 verbose -log "Couldn't send $command to GDB."
1319 set code $early_processed_code
1321 -re ".*A problem internal to GDB has been detected" {
1322 fail "$message (GDB internal error)"
1323 gdb_internal_error_resync
1326 -re "\\*\\*\\* DOSEXIT code.*" {
1327 if { $message != "" } {
1332 -re "Corrupted shared library list.*$prompt_regexp" {
1333 fail "$message (shared library list corrupted)"
1336 -re "Invalid cast\.\r\nwarning: Probes-based dynamic linker interface failed.*$prompt_regexp" {
1337 fail "$message (probes interface failure)"
1341 append code $processed_code
1343 # Reset the spawn id, in case the processed code used -i.
1349 -re "Ending remote debugging.*$prompt_regexp" {
1351 warning "Can`t communicate to remote target."
1357 -re "Undefined\[a-z\]* command:.*$prompt_regexp" {
1358 perror "Undefined command \"$command\"."
1362 -re "Ambiguous command.*$prompt_regexp" {
1363 perror "\"$command\" is not a unique command name."
1367 -re "$inferior_exited_re with code \[0-9\]+.*$prompt_regexp" {
1368 if {![string match "" $message]} {
1369 set errmsg "$message (the program exited)"
1371 set errmsg "$command (the program exited)"
1376 -re "$inferior_exited_re normally.*$prompt_regexp" {
1377 if {![string match "" $message]} {
1378 set errmsg "$message (the program exited)"
1380 set errmsg "$command (the program exited)"
1385 -re "The program is not being run.*$prompt_regexp" {
1386 if {![string match "" $message]} {
1387 set errmsg "$message (the program is no longer running)"
1389 set errmsg "$command (the program is no longer running)"
1394 -re "\r\n$prompt_regexp" {
1395 if {![string match "" $message]} {
1400 -re "$pagination_prompt" {
1402 perror "Window too small."
1406 -re "\\((y or n|y or \\\[n\\\]|\\\[y\\\] or n)\\) " {
1407 send_gdb "n\n" answer
1408 gdb_expect -re "$prompt_regexp"
1409 fail "$message (got interactive prompt)"
1412 -re "\\\[0\\\] cancel\r\n\\\[1\\\] all.*\r\n> $" {
1414 gdb_expect -re "$prompt_regexp"
1415 fail "$message (got breakpoint menu)"
1421 perror "GDB process no longer exists"
1422 set wait_status [wait -i $gdb_spawn_id]
1423 verbose -log "GDB process exited with wait status $wait_status"
1424 if { $message != "" } {
1431 if {$line_by_line} {
1433 -re "\r\n\[^\r\n\]*(?=\r\n)" {
1439 # Now patterns that apply to any spawn id specified.
1443 perror "Process no longer exists"
1444 if { $message != "" } {
1450 perror "internal buffer is full."
1455 if {![string match "" $message]} {
1456 fail "$message (timeout)"
1462 # remote_expect calls the eof section if there is an error on the
1463 # expect call. We already have eof sections above, and we don't
1464 # want them to get called in that situation. Since the last eof
1465 # section becomes the error section, here we define another eof
1466 # section, but with an empty spawn_id list, so that it won't ever
1470 # This comment is here because the eof section must not be
1471 # the empty string, otherwise remote_expect won't realize
1476 # Create gdb_test_name in the parent scope. If this variable
1477 # already exists, which it might if we have nested calls to
1478 # gdb_test_multiple, then preserve the old value, otherwise,
1479 # create a new variable in the parent scope.
1480 upvar gdb_test_name gdb_test_name
1481 if { [info exists gdb_test_name] } {
1482 set gdb_test_name_old "$gdb_test_name"
1484 set gdb_test_name "$message"
1487 set code [catch {gdb_expect $code} string]
1489 # Clean up the gdb_test_name variable. If we had a
1490 # previous value then restore it, otherwise, delete the variable
1491 # from the parent scope.
1492 if { [info exists gdb_test_name_old] } {
1493 set gdb_test_name "$gdb_test_name_old"
1499 global errorInfo errorCode
1500 return -code error -errorinfo $errorInfo -errorcode $errorCode $string
1501 } elseif {$code > 1} {
1502 return -code $code $string
1507 # Usage: gdb_test_multiline NAME INPUT RESULT {INPUT RESULT} ...
1508 # Run a test named NAME, consisting of multiple lines of input.
1509 # After each input line INPUT, search for result line RESULT.
1510 # Succeed if all results are seen; fail otherwise.
1512 proc gdb_test_multiline { name args } {
1515 foreach {input result} $args {
1517 if {[gdb_test_multiple $input "$name: input $inputnr: $input" {
1518 -re "($result)\r\n($gdb_prompt | *>)$" {
1528 # gdb_test [-prompt PROMPT_REGEXP] [-lbl]
1529 # COMMAND [PATTERN] [MESSAGE] [QUESTION RESPONSE]
1530 # Send a command to gdb; test the result.
1532 # COMMAND is the command to execute, send to GDB with send_gdb. If
1533 # this is the null string no command is sent.
1534 # PATTERN is the pattern to match for a PASS, and must NOT include the
1535 # \r\n sequence immediately before the gdb prompt (see -nonl below).
1536 # This argument may be omitted to just match the prompt, ignoring
1537 # whatever output precedes it. If PATTERN starts with '^' then
1538 # PATTERN will be anchored such that it should match all output from
1540 # MESSAGE is an optional message to be printed. If this is
1541 # omitted, then the pass/fail messages use the command string as the
1542 # message. (If this is the empty string, then sometimes we don't
1543 # call pass or fail at all; I don't understand this at all.)
1544 # QUESTION is a question GDB should ask in response to COMMAND, like
1545 # "are you sure?" If this is specified, the test fails if GDB
1546 # doesn't print the question.
1547 # RESPONSE is the response to send when QUESTION appears.
1549 # -prompt PROMPT_REGEXP specifies a regexp matching the expected prompt
1550 # after the command output. If empty, defaults to "$gdb_prompt $".
1551 # -no-prompt-anchor specifies that if the default prompt regexp is used, it
1552 # should not be anchored at the end of the buffer. This means that the
1553 # pattern can match even if there is stuff output after the prompt. Does not
1554 # have any effect if -prompt is specified.
1555 # -lbl specifies that line-by-line matching will be used.
1556 # -nopass specifies that a PASS should not be issued.
1557 # -nonl specifies that no \r\n sequence is expected between PATTERN
1558 # and the gdb prompt.
1561 # 1 if the test failed,
1562 # 0 if the test passes,
1563 # -1 if there was an internal error.
1565 proc gdb_test { args } {
1567 upvar timeout timeout
1577 set args [lassign $args command pattern message question response]
1580 # Can't have a question without a response.
1581 if { $question != "" && $response == "" || [llength $args] > 5 } {
1582 error "Unexpected arguments: $args"
1585 if { $message == "" } {
1586 set message [command_to_message $command]
1589 set prompt [fill_in_default_prompt $prompt [expr !${no-prompt-anchor}]]
1590 set nl [expr ${nonl} ? {""} : {"\r\n"}]
1594 # If the pattern starts with a '^' then we want to match all the
1595 # output from COMMAND. To support this, here we inject an
1596 # additional pattern that matches the command immediately after
1598 if {[string range $pattern 0 0] eq "^"} {
1599 if {$command ne ""} {
1600 set command_regex [string_to_regexp $command]
1601 set pattern [string range $pattern 1 end]
1602 if {[string length "$pattern"] > 0} {
1603 # We have an output pattern (other than the '^'), add a
1604 # newline at the start, this will eventually sit between the
1605 # command and the output pattern.
1606 set pattern "\r\n$pattern"
1608 set pattern "^${command_regex}${pattern}"
1614 -re "(?:$pattern)$nl$prompt" {
1615 if { $question != "" & !$saw_question} {
1617 } elseif {!$nopass} {
1623 if { $question != "" } {
1627 send_gdb "$response\n"
1633 set user_code [join $user_code]
1636 lappend opts "-prompt" "$prompt"
1641 return [gdb_test_multiple $command $message {*}$opts $user_code]
1644 # Return 1 if python version used is at least MAJOR.MINOR
1645 proc python_version_at_least { major minor } {
1646 set python_script {print (sys.version_info\[0\], sys.version_info\[1\])}
1648 set res [remote_exec host $::GDB \
1649 "$::INTERNAL_GDBFLAGS -batch -ex \"python $python_script\""]
1650 if { [lindex $res 0] != 0 } {
1651 error "Couldn't get python version"
1654 set python_version [lindex $res 1]
1655 set python_version [string trim $python_version]
1657 regexp {^([0-9]+) ([0-9]+)$} $python_version \
1658 dummy python_version_major python_version_minor
1660 return [version_compare [list $major $minor] \
1661 <= [list $python_version_major $python_version_minor]]
1664 # Return 1 if tcl version used is at least MAJOR.MINOR.PATCHLEVEL.
1665 proc tcl_version_at_least { major minor {patchlevel 0} } {
1666 global tcl_patchLevel
1667 regexp {^([0-9]+)\.([0-9]+)\.([0-9]+)$} \
1668 $tcl_patchLevel dummy \
1669 tcl_version_major tcl_version_minor tcl_version_patchlevel
1678 $tcl_version_major \
1679 $tcl_version_minor \
1680 $tcl_version_patchlevel]]
1683 if { [tcl_version_at_least 8 5] == 0 } {
1684 # lrepeat was added in tcl 8.5. Only add if missing.
1685 proc lrepeat { n element } {
1686 if { [string is integer -strict $n] == 0 } {
1687 error "expected integer but got \"$n\""
1690 error "bad count \"$n\": must be integer >= 0"
1693 for {set i 0} {$i < $n} {incr i} {
1694 lappend res $element
1700 if { [tcl_version_at_least 8 6] == 0 } {
1701 # lmap was added in tcl 8.6. Only add if missing.
1703 # Note that we only implement the simple variant for now.
1704 proc lmap { varname list body } {
1707 uplevel 1 "set $varname $val"
1708 lappend res [uplevel 1 $body]
1714 # ::tcl_platform(pathSeparator) was added in 8.6.
1715 switch $::tcl_platform(platform) {
1717 set ::tcl_platform(pathSeparator) ;
1720 set ::tcl_platform(pathSeparator) :
1725 if { [tcl_version_at_least 8 6 2] == 0 } {
1726 # string cat was added in tcl 8.6.2. Only add if missing.
1728 rename string tcl_proc_string
1730 proc string { what args } {
1731 if { $what == "cat" } {
1732 return [join $args ""]
1734 return [tcl_proc_string $what {*}$args]
1738 # gdb_test_no_output [-prompt PROMPT_REGEXP] [-nopass] COMMAND [MESSAGE]
1739 # Send a command to GDB and verify that this command generated no output.
1741 # See gdb_test for a description of the -prompt, -no-prompt-anchor, -nopass,
1742 # COMMAND, and MESSAGE parameters.
1745 # 1 if the test failed,
1746 # 0 if the test passes,
1747 # -1 if there was an internal error.
1749 proc gdb_test_no_output { args } {
1758 set args [lassign $args command message]
1761 set prompt [fill_in_default_prompt $prompt [expr !${no-prompt-anchor}]]
1763 set command_regex [string_to_regexp $command]
1764 return [gdb_test_multiple $command $message -prompt $prompt {
1765 -re "^$command_regex\r\n$prompt" {
1773 # Send a command and then wait for a sequence of outputs.
1774 # This is useful when the sequence is long and contains ".*", a single
1775 # regexp to match the entire output can get a timeout much easier.
1777 # COMMAND is the command to execute, send to GDB with send_gdb. If
1778 # this is the null string no command is sent.
1779 # TEST_NAME is passed to pass/fail. COMMAND is used if TEST_NAME is "".
1780 # EXPECTED_OUTPUT_LIST is a list of regexps of expected output, which are
1781 # processed in order, and all must be present in the output.
1783 # The -prompt switch can be used to override the prompt expected at the end of
1784 # the output sequence.
1786 # It is unnecessary to specify ".*" at the beginning or end of any regexp,
1787 # there is an implicit ".*" between each element of EXPECTED_OUTPUT_LIST.
1788 # There is also an implicit ".*" between the last regexp and the gdb prompt.
1790 # Like gdb_test and gdb_test_multiple, the output is expected to end with the
1791 # gdb prompt, which must not be specified in EXPECTED_OUTPUT_LIST.
1794 # 1 if the test failed,
1795 # 0 if the test passes,
1796 # -1 if there was an internal error.
1798 proc gdb_test_sequence { args } {
1801 parse_some_args {{prompt ""}}
1803 if { $prompt == "" } {
1804 set prompt "$gdb_prompt $"
1807 if { [llength $args] != 3 } {
1808 error "Unexpected # of arguments, expecting: COMMAND TEST_NAME EXPECTED_OUTPUT_LIST"
1811 lassign $args command test_name expected_output_list
1813 if { $test_name == "" } {
1814 set test_name $command
1817 lappend expected_output_list ""; # implicit ".*" before gdb prompt
1819 if { $command != "" } {
1820 send_gdb "$command\n"
1823 return [gdb_expect_list $test_name $prompt $expected_output_list]
1827 # Issue COMMAND, and return corresponding output lines. Helper function for
1828 # gdb_get_lines_no_pass and gdb_get_lines.
1830 proc gdb_get_lines_1 { command message } {
1831 set no_pass [string equal $message ""]
1834 gdb_test_multiple $command $message {
1835 -re "\r\n(\[^\r\n\]*)(?=\r\n)" {
1836 set line $expect_out(1,string)
1837 if { $lines eq "" } {
1838 append lines "$line"
1840 append lines "\r\n$line"
1860 # Issue COMMAND, and return corresponding output lines. Don't generate a pass.
1862 proc gdb_get_lines_no_pass { command } {
1863 gdb_get_lines_1 $command ""
1866 # Issue COMMAND, and return corresponding output lines. Generate a pass.
1868 proc gdb_get_lines { command {message ""} } {
1869 if { $message == "" } {
1870 set message [command_to_message $command]
1873 gdb_get_lines_1 $command $message
1876 # Match output of COMMAND using RE. Read output line-by-line.
1877 # Report pass/fail with MESSAGE.
1878 # For a command foo with output:
1883 # the portion matched using RE is:
1888 # Optionally, additional -re-not <regexp> arguments can be specified, to
1889 # ensure that a regexp is not match by the COMMAND output.
1890 # Such an additional argument generates an additional PASS/FAIL of the form:
1891 # PASS: test-case.exp: $message: pattern not matched: <regexp>
1893 proc gdb_test_lines { command message re args } {
1896 for {set i 0} {$i < [llength $args]} {incr i} {
1897 set arg [lindex $args $i]
1898 if { $arg == "-re-not" } {
1900 if { [llength $args] == $i } {
1901 error "Missing argument for -re-not"
1904 set arg [lindex $args $i]
1907 error "Unhandled argument: $arg"
1911 if { $message == ""} {
1912 set message [command_to_message $command]
1915 set lines [gdb_get_lines_no_pass $command]
1916 gdb_assert { [regexp $re $lines] } $message
1918 foreach re $re_not {
1919 gdb_assert { ![regexp $re $lines] } "$message: pattern not matched: $re"
1923 # Test that a command gives an error. For pass or fail, return
1924 # a 1 to indicate that more tests can proceed. However a timeout
1925 # is a serious error, generates a special fail message, and causes
1926 # a 0 to be returned to indicate that more tests are likely to fail
1929 proc test_print_reject { args } {
1933 if {[llength $args] == 2} {
1934 set expectthis [lindex $args 1]
1936 set expectthis "should never match this bogus string"
1938 set sendthis [lindex $args 0]
1940 send_user "Sending \"$sendthis\" to gdb\n"
1941 send_user "Looking to match \"$expectthis\"\n"
1943 send_gdb "$sendthis\n"
1944 #FIXME: Should add timeout as parameter.
1946 -re "A .* in expression.*\\.*$gdb_prompt $" {
1947 pass "reject $sendthis"
1950 -re "Invalid syntax in expression.*$gdb_prompt $" {
1951 pass "reject $sendthis"
1954 -re "Junk after end of expression.*$gdb_prompt $" {
1955 pass "reject $sendthis"
1958 -re "Invalid number.*$gdb_prompt $" {
1959 pass "reject $sendthis"
1962 -re "Invalid character constant.*$gdb_prompt $" {
1963 pass "reject $sendthis"
1966 -re "No symbol table is loaded.*$gdb_prompt $" {
1967 pass "reject $sendthis"
1970 -re "No symbol .* in current context.*$gdb_prompt $" {
1971 pass "reject $sendthis"
1974 -re "Unmatched single quote.*$gdb_prompt $" {
1975 pass "reject $sendthis"
1978 -re "A character constant must contain at least one character.*$gdb_prompt $" {
1979 pass "reject $sendthis"
1982 -re "$expectthis.*$gdb_prompt $" {
1983 pass "reject $sendthis"
1986 -re ".*$gdb_prompt $" {
1987 fail "reject $sendthis"
1991 fail "reject $sendthis (eof or timeout)"
1998 # Same as gdb_test, but the second parameter is not a regexp,
1999 # but a string that must match exactly.
2001 proc gdb_test_exact { args } {
2002 upvar timeout timeout
2004 set command [lindex $args 0]
2006 # This applies a special meaning to a null string pattern. Without
2007 # this, "$pattern\r\n$gdb_prompt $" will match anything, including error
2008 # messages from commands that should have no output except a new
2009 # prompt. With this, only results of a null string will match a null
2012 set pattern [lindex $args 1]
2013 if [string match $pattern ""] {
2014 set pattern [string_to_regexp [lindex $args 0]]
2016 set pattern [string_to_regexp [lindex $args 1]]
2019 # It is most natural to write the pattern argument with only
2020 # embedded \n's, especially if you are trying to avoid Tcl quoting
2021 # problems. But gdb_expect really wants to see \r\n in patterns. So
2022 # transform the pattern here. First transform \r\n back to \n, in
2023 # case some users of gdb_test_exact already do the right thing.
2024 regsub -all "\r\n" $pattern "\n" pattern
2025 regsub -all "\n" $pattern "\r\n" pattern
2026 if {[llength $args] == 3} {
2027 set message [lindex $args 2]
2028 return [gdb_test $command $pattern $message]
2031 return [gdb_test $command $pattern]
2034 # Wrapper around gdb_test_multiple that looks for a list of expected
2035 # output elements, but which can appear in any order.
2036 # CMD is the gdb command.
2037 # NAME is the name of the test.
2038 # ELM_FIND_REGEXP specifies how to partition the output into elements to
2040 # ELM_EXTRACT_REGEXP specifies the part of ELM_FIND_REGEXP to compare.
2041 # RESULT_MATCH_LIST is a list of exact matches for each expected element.
2042 # All elements of RESULT_MATCH_LIST must appear for the test to pass.
2044 # A typical use of ELM_FIND_REGEXP/ELM_EXTRACT_REGEXP is to extract one line
2045 # of text per element and then strip trailing \r\n's.
2047 # gdb_test_list_exact "foo" "bar" \
2048 # "\[^\r\n\]+\[\r\n\]+" \
2051 # {expected result 1} \
2052 # {expected result 2} \
2055 proc gdb_test_list_exact { cmd name elm_find_regexp elm_extract_regexp result_match_list } {
2058 set matches [lsort $result_match_list]
2060 gdb_test_multiple $cmd $name {
2061 "$cmd\[\r\n\]" { exp_continue }
2062 -re $elm_find_regexp {
2063 set str $expect_out(0,string)
2064 verbose -log "seen: $str" 3
2065 regexp -- $elm_extract_regexp $str elm_seen
2066 verbose -log "extracted: $elm_seen" 3
2067 lappend seen $elm_seen
2070 -re "$gdb_prompt $" {
2072 foreach got [lsort $seen] have $matches {
2073 if {![string equal $got $have]} {
2078 if {[string length $failed] != 0} {
2079 fail "$name ($failed not found)"
2087 # gdb_test_stdio COMMAND INFERIOR_PATTERN GDB_PATTERN MESSAGE
2088 # Send a command to gdb; expect inferior and gdb output.
2090 # See gdb_test_multiple for a description of the COMMAND and MESSAGE
2093 # INFERIOR_PATTERN is the pattern to match against inferior output.
2095 # GDB_PATTERN is the pattern to match against gdb output, and must NOT
2096 # include the \r\n sequence immediately before the gdb prompt, nor the
2097 # prompt. The default is empty.
2099 # Both inferior and gdb patterns must match for a PASS.
2101 # If MESSAGE is omitted, then COMMAND will be used as the message.
2104 # 1 if the test failed,
2105 # 0 if the test passes,
2106 # -1 if there was an internal error.
2109 proc gdb_test_stdio {command inferior_pattern {gdb_pattern ""} {message ""}} {
2110 global inferior_spawn_id gdb_spawn_id
2113 if {$message == ""} {
2114 set message [command_to_message $command]
2117 set inferior_matched 0
2120 # Use an indirect spawn id list, and remove the inferior spawn id
2121 # from the expected output as soon as it matches, in case
2122 # $inferior_pattern happens to be a prefix of the resulting full
2123 # gdb pattern below (e.g., "\r\n").
2124 global gdb_test_stdio_spawn_id_list
2125 set gdb_test_stdio_spawn_id_list "$inferior_spawn_id"
2127 # Note that if $inferior_spawn_id and $gdb_spawn_id are different,
2128 # then we may see gdb's output arriving before the inferior's
2130 set res [gdb_test_multiple $command $message {
2131 -i gdb_test_stdio_spawn_id_list -re "$inferior_pattern" {
2132 set inferior_matched 1
2133 if {!$gdb_matched} {
2134 set gdb_test_stdio_spawn_id_list ""
2138 -i $gdb_spawn_id -re "$gdb_pattern\r\n$gdb_prompt $" {
2140 if {!$inferior_matched} {
2148 verbose -log "inferior_matched=$inferior_matched, gdb_matched=$gdb_matched"
2153 # Wrapper around gdb_test_multiple to be used when testing expression
2154 # evaluation while 'set debug expression 1' is in effect.
2155 # Looks for some patterns that indicates the expression was rejected.
2157 # CMD is the command to execute, which should include an expression
2158 # that GDB will need to parse.
2160 # OUTPUT is the expected output pattern.
2162 # TESTNAME is the name to be used for the test, defaults to CMD if not
2164 proc gdb_test_debug_expr { cmd output {testname "" }} {
2167 if { ${testname} == "" } {
2171 gdb_test_multiple $cmd $testname {
2172 -re ".*Invalid expression.*\r\n$gdb_prompt $" {
2175 -re ".*\[\r\n\]$output\r\n$gdb_prompt $" {
2181 # get_print_expr_at_depths EXP OUTPUTS
2183 # Used for testing 'set print max-depth'. Prints the expression EXP
2184 # with 'set print max-depth' set to various depths. OUTPUTS is a list
2185 # of `n` different patterns to match at each of the depths from 0 to
2188 # This proc does one final check with the max-depth set to 'unlimited'
2189 # which is tested against the last pattern in the OUTPUTS list. The
2190 # OUTPUTS list is therefore required to match every depth from 0 to a
2191 # depth where the whole of EXP is printed with no ellipsis.
2193 # This proc leaves the 'set print max-depth' set to 'unlimited'.
2194 proc gdb_print_expr_at_depths {exp outputs} {
2195 for { set depth 0 } { $depth <= [llength $outputs] } { incr depth } {
2196 if { $depth == [llength $outputs] } {
2197 set expected_result [lindex $outputs [expr [llength $outputs] - 1]]
2198 set depth_string "unlimited"
2200 set expected_result [lindex $outputs $depth]
2201 set depth_string $depth
2204 with_test_prefix "exp='$exp': depth=${depth_string}" {
2205 gdb_test_no_output "set print max-depth ${depth_string}"
2206 gdb_test "p $exp" "$expected_result"
2213 # Issue a PASS and return true if evaluating CONDITION in the caller's
2214 # frame returns true, and issue a FAIL and return false otherwise.
2215 # MESSAGE is the pass/fail message to be printed. If MESSAGE is
2216 # omitted or is empty, then the pass/fail messages use the condition
2217 # string as the message.
2219 proc gdb_assert { condition {message ""} } {
2220 if { $message == ""} {
2221 set message $condition
2224 set code [catch {uplevel 1 [list expr $condition]} res]
2226 # If code is 1 (TCL_ERROR), it means evaluation failed and res contains
2227 # an error message. Print the error message, and set res to 0 since we
2228 # want to return a boolean.
2229 warning "While evaluating expression in gdb_assert: $res"
2232 } elseif { !$res } {
2240 proc gdb_reinitialize_dir { subdir } {
2243 if [is_remote host] {
2248 -re "Reinitialize source path to empty.*y or n.(\\\s.answered Y; input not from terminal.)?" {
2249 if {![info exists expect_out(1,string)]} {
2250 send_gdb "y\n" answer
2253 -re "Source directories searched.*$gdb_prompt $" {
2254 send_gdb "dir $subdir\n"
2256 -re "Source directories searched.*$gdb_prompt $" {
2257 verbose "Dir set to $subdir"
2259 -re "$gdb_prompt $" {
2260 perror "Dir \"$subdir\" failed."
2264 -re "$gdb_prompt $" {
2265 perror "Dir \"$subdir\" failed."
2269 -re "$gdb_prompt $" {
2270 perror "Dir \"$subdir\" failed."
2276 # gdb_exit -- exit the GDB, killing the target program if necessary
2278 proc default_gdb_exit {} {
2280 global INTERNAL_GDBFLAGS GDBFLAGS
2281 global gdb_spawn_id inferior_spawn_id
2282 global inotify_log_file
2284 if ![info exists gdb_spawn_id] {
2288 verbose "Quitting $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
2290 if {[info exists inotify_log_file] && [file exists $inotify_log_file]} {
2291 set fd [open $inotify_log_file]
2292 set data [read -nonewline $fd]
2295 if {[string compare $data ""] != 0} {
2296 warning "parallel-unsafe file creations noticed"
2299 set fd [open $inotify_log_file w]
2304 if { [is_remote host] && [board_info host exists fileid] } {
2308 send_gdb "y\n" answer
2311 -re "DOSEXIT code" { }
2316 if ![is_remote host] {
2320 unset ::gdb_tty_name
2321 unset inferior_spawn_id
2324 # Load a file into the debugger.
2325 # The return value is 0 for success, -1 for failure.
2327 # ARG is the file name.
2328 # KILL_FLAG, if given, indicates whether a "kill" command should be used.
2330 # This procedure also set the global variable GDB_FILE_CMD_DEBUG_INFO
2331 # to one of these values:
2333 # debug file was loaded successfully and has debug information
2334 # nodebug file was loaded successfully and has no debug information
2335 # lzma file was loaded, .gnu_debugdata found, but no LZMA support
2337 # fail file was not loaded
2339 # This procedure also set the global variable GDB_FILE_CMD_MSG to the
2340 # output of the file command in case of success.
2342 # I tried returning this information as part of the return value,
2343 # but ran into a mess because of the many re-implementations of
2344 # gdb_load in config/*.exp.
2346 # TODO: gdb.base/sepdebug.exp and gdb.stabs/weird.exp might be able to use
2347 # this if they can get more information set.
2349 proc gdb_file_cmd { arg {kill_flag 1} } {
2352 global last_loaded_file
2354 # GCC for Windows target may create foo.exe given "-o foo".
2355 if { ![file exists $arg] && [file exists "$arg.exe"] } {
2359 # Save this for the benefit of gdbserver-support.exp.
2360 set last_loaded_file $arg
2362 # Set whether debug info was found.
2363 # Default to "fail".
2364 global gdb_file_cmd_debug_info gdb_file_cmd_msg
2365 set gdb_file_cmd_debug_info "fail"
2367 if [is_remote host] {
2368 set arg [remote_download host $arg]
2370 perror "download failed"
2375 # The file command used to kill the remote target. For the benefit
2376 # of the testsuite, preserve this behavior. Mark as optional so it doesn't
2377 # get written to the stdin log.
2379 send_gdb "kill\n" optional
2381 -re "Kill the program being debugged. .y or n. $" {
2382 send_gdb "y\n" answer
2383 verbose "\t\tKilling previous program being debugged"
2386 -re "$gdb_prompt $" {
2392 send_gdb "file $arg\n"
2393 set new_symbol_table 0
2394 set basename [file tail $arg]
2396 -re "(Reading symbols from.*LZMA support was disabled.*$gdb_prompt $)" {
2397 verbose "\t\tLoaded $arg into $GDB; .gnu_debugdata found but no LZMA available"
2398 set gdb_file_cmd_msg $expect_out(1,string)
2399 set gdb_file_cmd_debug_info "lzma"
2402 -re "(Reading symbols from.*No debugging symbols found.*$gdb_prompt $)" {
2403 verbose "\t\tLoaded $arg into $GDB with no debugging symbols"
2404 set gdb_file_cmd_msg $expect_out(1,string)
2405 set gdb_file_cmd_debug_info "nodebug"
2408 -re "(Reading symbols from.*$gdb_prompt $)" {
2409 verbose "\t\tLoaded $arg into $GDB"
2410 set gdb_file_cmd_msg $expect_out(1,string)
2411 set gdb_file_cmd_debug_info "debug"
2414 -re "Load new symbol table from \".*\".*y or n. $" {
2415 if { $new_symbol_table > 0 } {
2416 perror [join [list "Couldn't load $basename,"
2417 "interactive prompt loop detected."]]
2420 send_gdb "y\n" answer
2421 incr new_symbol_table
2422 set suffix "-- with new symbol table"
2423 set arg "$arg $suffix"
2424 set basename "$basename $suffix"
2427 -re "No such file or directory.*$gdb_prompt $" {
2428 perror "($basename) No such file or directory"
2431 -re "A problem internal to GDB has been detected" {
2432 perror "Couldn't load $basename into GDB (GDB internal error)."
2433 gdb_internal_error_resync
2436 -re "$gdb_prompt $" {
2437 perror "Couldn't load $basename into GDB."
2441 perror "Couldn't load $basename into GDB (timeout)."
2445 # This is an attempt to detect a core dump, but seems not to
2446 # work. Perhaps we need to match .* followed by eof, in which
2447 # gdb_expect does not seem to have a way to do that.
2448 perror "Couldn't load $basename into GDB (eof)."
2454 # The expect "spawn" function puts the tty name into the spawn_out
2455 # array; but dejagnu doesn't export this globally. So, we have to
2456 # wrap spawn with our own function and poke in the built-in spawn
2457 # so that we can capture this value.
2459 # If available, the TTY name is saved to the LAST_SPAWN_TTY_NAME global.
2460 # Otherwise, LAST_SPAWN_TTY_NAME is unset.
2462 proc spawn_capture_tty_name { args } {
2463 set result [uplevel builtin_spawn $args]
2464 upvar spawn_out spawn_out
2465 if { [info exists spawn_out(slave,name)] } {
2466 set ::last_spawn_tty_name $spawn_out(slave,name)
2468 # If a process is spawned as part of a pipe line (e.g. passing
2469 # -leaveopen to the spawn proc) then the spawned process is no
2470 # assigned a tty and spawn_out(slave,name) will not be set.
2471 # In that case we want to ensure that last_spawn_tty_name is
2474 # If the previous process spawned was also not assigned a tty
2475 # (e.g. multiple processed chained in a pipeline) then
2476 # last_spawn_tty_name will already be unset, so, if we don't
2477 # use -nocomplain here we would otherwise get an error.
2478 unset -nocomplain ::last_spawn_tty_name
2483 rename spawn builtin_spawn
2484 rename spawn_capture_tty_name spawn
2486 # Default gdb_spawn procedure.
2488 proc default_gdb_spawn { } {
2491 global INTERNAL_GDBFLAGS GDBFLAGS
2494 # Set the default value, it may be overriden later by specific testfile.
2496 # Use `set_board_info use_gdb_stub' for the board file to flag the inferior
2497 # is already started after connecting and run/attach are not supported.
2498 # This is used for the "remote" protocol. After GDB starts you should
2499 # check global $use_gdb_stub instead of the board as the testfile may force
2500 # a specific different target protocol itself.
2501 set use_gdb_stub [target_info exists use_gdb_stub]
2503 verbose "Spawning $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
2504 gdb_write_cmd_file "$GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
2506 if [info exists gdb_spawn_id] {
2510 if ![is_remote host] {
2511 if {[which $GDB] == 0} {
2512 perror "$GDB does not exist."
2517 # Put GDBFLAGS last so that tests can put "--args ..." in it.
2518 set res [remote_spawn host "$GDB $INTERNAL_GDBFLAGS [host_info gdb_opts] $GDBFLAGS"]
2519 if { $res < 0 || $res == "" } {
2520 perror "Spawning $GDB failed."
2524 set gdb_spawn_id $res
2525 set ::gdb_tty_name $::last_spawn_tty_name
2529 # Default gdb_start procedure.
2531 proc default_gdb_start { } {
2534 global inferior_spawn_id
2536 if [info exists gdb_spawn_id] {
2540 # Keep track of the number of times GDB has been launched.
2541 global gdb_instances
2551 # Default to assuming inferior I/O is done on GDB's terminal.
2552 if {![info exists inferior_spawn_id]} {
2553 set inferior_spawn_id $gdb_spawn_id
2556 # When running over NFS, particularly if running many simultaneous
2557 # tests on different hosts all using the same server, things can
2558 # get really slow. Give gdb at least 3 minutes to start up.
2560 -re "\[\r\n\]$gdb_prompt $" {
2561 verbose "GDB initialized."
2563 -re "\[\r\n\]\033\\\[.2004h$gdb_prompt $" {
2564 # This special case detects what happens when GDB is
2565 # started with bracketed paste mode enabled. This mode is
2566 # usually forced off (see setting of INPUTRC in
2567 # default_gdb_init), but for at least one test we turn
2568 # bracketed paste mode back on, and then start GDB. In
2569 # that case, this case is hit.
2570 verbose "GDB initialized."
2572 -re "^$gdb_prompt $" {
2574 verbose "GDB initialized."
2576 -re "^\033\\\[.2004h$gdb_prompt $" {
2577 # Output with -q, and bracketed paste mode enabled, see above.
2578 verbose "GDB initialized."
2580 -re "$gdb_prompt $" {
2581 perror "GDB never initialized."
2586 perror "(timeout) GDB never initialized after 10 seconds."
2592 perror "(eof) GDB never initialized."
2598 # force the height to "unlimited", so no pagers get used
2600 send_gdb "set height 0\n"
2602 -re "$gdb_prompt $" {
2603 verbose "Setting height to 0." 2
2606 warning "Couldn't set the height to 0"
2609 # force the width to "unlimited", so no wraparound occurs
2610 send_gdb "set width 0\n"
2612 -re "$gdb_prompt $" {
2613 verbose "Setting width to 0." 2
2616 warning "Couldn't set the width to 0."
2624 # Utility procedure to give user control of the gdb prompt in a script. It is
2625 # meant to be used for debugging test cases, and should not be left in the
2628 proc gdb_interact { } {
2630 set spawn_id $gdb_spawn_id
2632 send_user "+------------------------------------------+\n"
2633 send_user "| Script interrupted, you can now interact |\n"
2634 send_user "| with by gdb. Type >>> to continue. |\n"
2635 send_user "+------------------------------------------+\n"
2642 # Examine the output of compilation to determine whether compilation
2643 # failed or not. If it failed determine whether it is due to missing
2644 # compiler or due to compiler error. Report pass, fail or unsupported
2647 proc gdb_compile_test {src output} {
2648 set msg "compilation [file tail $src]"
2650 if { $output == "" } {
2655 if { [regexp {^[a-zA-Z_0-9]+: Can't find [^ ]+\.$} $output]
2656 || [regexp {.*: command not found[\r|\n]*$} $output]
2657 || [regexp {.*: [^\r\n]*compiler not installed[^\r\n]*[\r|\n]*$} $output] } {
2658 unsupported "$msg (missing compiler)"
2662 set gcc_re ".*: error: unrecognized command line option "
2663 set clang_re ".*: error: unsupported option "
2664 if { [regexp "(?:$gcc_re|$clang_re)(\[^ \t;\r\n\]*)" $output dummy option]
2665 && $option != "" } {
2666 unsupported "$msg (unsupported option $option)"
2670 # Unclassified compilation failure, be more verbose.
2671 verbose -log "compilation failed: $output" 2
2675 # Return a 1 for configurations for which we want to try to test C++.
2677 proc allow_cplus_tests {} {
2678 if { [istarget "h8300-*-*"] } {
2682 # The C++ IO streams are too large for HC11/HC12 and are thus not
2683 # available. The gdb C++ tests use them and don't compile.
2684 if { [istarget "m6811-*-*"] } {
2687 if { [istarget "m6812-*-*"] } {
2693 # Return a 0 for configurations which are missing either C++ or the STL.
2695 proc allow_stl_tests {} {
2696 return [allow_cplus_tests]
2699 # Return a 1 if I want to try to test FORTRAN.
2701 proc allow_fortran_tests {} {
2705 # Return a 1 if I want to try to test ada.
2707 proc allow_ada_tests {} {
2708 if { [is_remote host] } {
2709 # Currently gdb_ada_compile doesn't support remote host.
2715 # Return a 1 if I want to try to test GO.
2717 proc allow_go_tests {} {
2721 # Return a 1 if I even want to try to test D.
2723 proc allow_d_tests {} {
2727 # Return a 1 if we can compile source files in LANG.
2729 gdb_caching_proc can_compile { lang } {
2731 if { $lang == "d" } {
2732 set src { void main() {} }
2733 return [gdb_can_simple_compile can_compile_$lang $src executable {d}]
2736 if { $lang == "rust" } {
2737 if { ![isnative] } {
2741 if { [is_remote host] } {
2742 # Proc find_rustc returns "" for remote host.
2746 # The rust compiler does not support "-m32", skip.
2747 global board board_info
2748 set board [target_info name]
2749 if {[board_info $board exists multilib_flags]} {
2750 foreach flag [board_info $board multilib_flags] {
2751 if { $flag == "-m32" } {
2757 set src { fn main() {} }
2758 # Drop nowarnings in default_compile_flags, it translates to -w which
2759 # rustc doesn't support.
2760 return [gdb_can_simple_compile can_compile_$lang $src executable \
2761 {rust} {debug quiet}]
2764 error "can_compile doesn't support lang: $lang"
2767 # Return 1 to try Rust tests, 0 to skip them.
2768 proc allow_rust_tests {} {
2772 # Return a 1 for configurations that support Python scripting.
2774 gdb_caching_proc allow_python_tests {} {
2775 set output [remote_exec host $::GDB "$::INTERNAL_GDBFLAGS --configuration"]
2776 return [expr {[string first "--with-python" $output] != -1}]
2779 # Return a 1 for configurations that use system readline rather than the
2782 gdb_caching_proc with_system_readline {} {
2783 set output [remote_exec host $::GDB "$::INTERNAL_GDBFLAGS --configuration"]
2784 return [expr {[string first "--with-system-readline" $output] != -1}]
2787 gdb_caching_proc allow_dap_tests {} {
2788 if { ![allow_python_tests] } {
2792 # The dap code uses module typing, available starting python 3.5.
2793 if { ![python_version_at_least 3 5] } {
2797 # ton.tcl uses "string is entier", supported starting tcl 8.6.
2798 if { ![tcl_version_at_least 8 6] } {
2802 # With set auto-connect-native-target off, we run into:
2804 # Traceback (most recent call last):
2805 # File "startup.py", line <n>, in exec_and_log
2806 # output = gdb.execute(cmd, from_tty=True, to_string=True)
2807 # gdb.error: Don't know how to run. Try "help target".
2808 set gdb_flags [join $::GDBFLAGS $::INTERNAL_GDBFLAGS]
2809 return [expr {[string first "set auto-connect-native-target off" $gdb_flags] == -1}]
2812 # Return a 1 if we should run shared library tests.
2814 proc allow_shlib_tests {} {
2815 # Run the shared library tests on native systems.
2820 # An abbreviated list of remote targets where we should be able to
2821 # run shared library tests.
2822 if {([istarget *-*-linux*]
2823 || [istarget *-*-*bsd*]
2824 || [istarget *-*-solaris2*]
2825 || [istarget *-*-mingw*]
2826 || [istarget *-*-cygwin*]
2827 || [istarget *-*-pe*])} {
2834 # Return 1 if we should run dlmopen tests, 0 if we should not.
2836 gdb_caching_proc allow_dlmopen_tests {} {
2837 global srcdir subdir gdb_prompt inferior_exited_re
2839 # We need shared library support.
2840 if { ![allow_shlib_tests] } {
2844 set me "allow_dlmopen_tests"
2858 struct r_debug *r_debug;
2862 /* The version is kept at 1 until we create a new namespace. */
2863 handle = dlmopen (LM_ID_NEWLM, DSO_NAME, RTLD_LAZY | RTLD_LOCAL);
2865 printf ("dlmopen failed: %s.\n", dlerror ());
2870 /* Taken from /usr/include/link.h. */
2871 for (dyn = _DYNAMIC; dyn->d_tag != DT_NULL; ++dyn)
2872 if (dyn->d_tag == DT_DEBUG)
2873 r_debug = (struct r_debug *) dyn->d_un.d_ptr;
2876 printf ("r_debug not found.\n");
2879 if (r_debug->r_version < 2) {
2880 printf ("dlmopen debug not supported.\n");
2883 printf ("dlmopen debug supported.\n");
2888 set libsrc [standard_temp_file "libfoo.c"]
2889 set libout [standard_temp_file "libfoo.so"]
2890 gdb_produce_source $libsrc $lib
2892 if { [gdb_compile_shlib $libsrc $libout {debug}] != "" } {
2893 verbose -log "failed to build library"
2896 if { ![gdb_simple_compile $me $src executable \
2897 [list shlib_load debug \
2898 additional_flags=-DDSO_NAME=\"$libout\"]] } {
2899 verbose -log "failed to build executable"
2905 gdb_reinitialize_dir $srcdir/$subdir
2908 if { [gdb_run_cmd] != 0 } {
2909 verbose -log "failed to start skip test"
2913 -re "$inferior_exited_re normally.*${gdb_prompt} $" {
2914 set allow_dlmopen_tests 1
2916 -re "$inferior_exited_re with code.*${gdb_prompt} $" {
2917 set allow_dlmopen_tests 0
2920 warning "\n$me: default case taken"
2921 set allow_dlmopen_tests 0
2926 verbose "$me: returning $allow_dlmopen_tests" 2
2927 return $allow_dlmopen_tests
2930 # Return 1 if we should allow TUI-related tests.
2932 gdb_caching_proc allow_tui_tests {} {
2933 set output [remote_exec host $::GDB "$::INTERNAL_GDBFLAGS --configuration"]
2934 return [expr {[string first "--enable-tui" $output] != -1}]
2937 # Test files shall make sure all the test result lines in gdb.sum are
2938 # unique in a test run, so that comparing the gdb.sum files of two
2939 # test runs gives correct results. Test files that exercise
2940 # variations of the same tests more than once, shall prefix the
2941 # different test invocations with different identifying strings in
2942 # order to make them unique.
2944 # About test prefixes:
2946 # $pf_prefix is the string that dejagnu prints after the result (FAIL,
2947 # PASS, etc.), and before the test message/name in gdb.sum. E.g., the
2948 # underlined substring in
2950 # PASS: gdb.base/mytest.exp: some test
2951 # ^^^^^^^^^^^^^^^^^^^^
2955 # The easiest way to adjust the test prefix is to append a test
2956 # variation prefix to the $pf_prefix, using the with_test_prefix
2959 # proc do_tests {} {
2960 # gdb_test ... ... "test foo"
2961 # gdb_test ... ... "test bar"
2963 # with_test_prefix "subvariation a" {
2964 # gdb_test ... ... "test x"
2967 # with_test_prefix "subvariation b" {
2968 # gdb_test ... ... "test x"
2972 # with_test_prefix "variation1" {
2973 # ...do setup for variation 1...
2977 # with_test_prefix "variation2" {
2978 # ...do setup for variation 2...
2984 # PASS: gdb.base/mytest.exp: variation1: test foo
2985 # PASS: gdb.base/mytest.exp: variation1: test bar
2986 # PASS: gdb.base/mytest.exp: variation1: subvariation a: test x
2987 # PASS: gdb.base/mytest.exp: variation1: subvariation b: test x
2988 # PASS: gdb.base/mytest.exp: variation2: test foo
2989 # PASS: gdb.base/mytest.exp: variation2: test bar
2990 # PASS: gdb.base/mytest.exp: variation2: subvariation a: test x
2991 # PASS: gdb.base/mytest.exp: variation2: subvariation b: test x
2993 # If for some reason more flexibility is necessary, one can also
2994 # manipulate the pf_prefix global directly, treating it as a string.
2998 # set saved_pf_prefix
2999 # append pf_prefix "${foo}: bar"
3000 # ... actual tests ...
3001 # set pf_prefix $saved_pf_prefix
3004 # Run BODY in the context of the caller, with the current test prefix
3005 # (pf_prefix) appended with one space, then PREFIX, and then a colon.
3006 # Returns the result of BODY.
3008 proc with_test_prefix { prefix body } {
3011 set saved $pf_prefix
3012 append pf_prefix " " $prefix ":"
3013 set code [catch {uplevel 1 $body} result]
3014 set pf_prefix $saved
3017 global errorInfo errorCode
3018 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3020 return -code $code $result
3024 # Wrapper for foreach that calls with_test_prefix on each iteration,
3025 # including the iterator's name and current value in the prefix.
3027 proc foreach_with_prefix {var list body} {
3029 foreach myvar $list {
3030 with_test_prefix "$var=$myvar" {
3031 set code [catch {uplevel 1 $body} result]
3035 global errorInfo errorCode
3036 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3037 } elseif {$code == 3} {
3039 } elseif {$code == 2} {
3040 return -code $code $result
3045 # Like TCL's native proc, but defines a procedure that wraps its body
3046 # within 'with_test_prefix "$proc_name" { ... }'.
3047 proc proc_with_prefix {name arguments body} {
3048 # Define the advertised proc.
3049 proc $name $arguments [list with_test_prefix $name $body]
3052 # Return an id corresponding to the test prefix stored in $pf_prefix, which
3053 # is more suitable for use in a file name.
3054 # F.i., for a pf_prefix:
3055 # gdb.dwarf2/dw2-lines.exp: \
3056 # cv=5: cdw=64: lv=5: ldw=64: string_form=line_strp:
3058 # cv-5-cdw-32-lv-5-ldw-64-string_form-line_strp
3064 # Strip ".exp: " prefix.
3065 set id [regsub {.*\.exp: } $id {}]
3067 # Strip colon suffix.
3068 set id [regsub {:$} $id {}]
3071 set id [regsub -all { } $id {}]
3073 # Replace colons, equal signs.
3074 set id [regsub -all \[:=\] $id -]
3079 # Run BODY in the context of the caller. After BODY is run, the variables
3080 # listed in VARS will be reset to the values they had before BODY was run.
3082 # This is useful for providing a scope in which it is safe to temporarily
3083 # modify global variables, e.g.
3085 # global INTERNAL_GDBFLAGS
3088 # set foo GDBHISTSIZE
3090 # save_vars { INTERNAL_GDBFLAGS env($foo) env(HOME) } {
3091 # append INTERNAL_GDBFLAGS " -nx"
3092 # unset -nocomplain env(GDBHISTSIZE)
3097 # Here, although INTERNAL_GDBFLAGS, env(GDBHISTSIZE) and env(HOME) may be
3098 # modified inside BODY, this proc guarantees that the modifications will be
3099 # undone after BODY finishes executing.
3101 proc save_vars { vars body } {
3102 array set saved_scalars { }
3103 array set saved_arrays { }
3107 # First evaluate VAR in the context of the caller in case the variable
3108 # name may be a not-yet-interpolated string like env($foo)
3109 set var [uplevel 1 list $var]
3111 if [uplevel 1 [list info exists $var]] {
3112 if [uplevel 1 [list array exists $var]] {
3113 set saved_arrays($var) [uplevel 1 [list array get $var]]
3115 set saved_scalars($var) [uplevel 1 [list set $var]]
3118 lappend unset_vars $var
3122 set code [catch {uplevel 1 $body} result]
3124 foreach {var value} [array get saved_scalars] {
3125 uplevel 1 [list set $var $value]
3128 foreach {var value} [array get saved_arrays] {
3129 uplevel 1 [list unset $var]
3130 uplevel 1 [list array set $var $value]
3133 foreach var $unset_vars {
3134 uplevel 1 [list unset -nocomplain $var]
3138 global errorInfo errorCode
3139 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3141 return -code $code $result
3145 # As save_vars, but for variables stored in the board_info for the
3150 # save_target_board_info { multilib_flags } {
3152 # set board [target_info name]
3153 # unset_board_info multilib_flags
3154 # set_board_info multilib_flags "$multilib_flags"
3158 proc save_target_board_info { vars body } {
3159 global board board_info
3160 set board [target_info name]
3162 array set saved_target_board_info { }
3163 set unset_target_board_info { }
3166 if { [info exists board_info($board,$var)] } {
3167 set saved_target_board_info($var) [board_info $board $var]
3169 lappend unset_target_board_info $var
3173 set code [catch {uplevel 1 $body} result]
3175 foreach {var value} [array get saved_target_board_info] {
3176 unset_board_info $var
3177 set_board_info $var $value
3180 foreach var $unset_target_board_info {
3181 unset_board_info $var
3185 global errorInfo errorCode
3186 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3188 return -code $code $result
3192 # Run tests in BODY with the current working directory (CWD) set to
3193 # DIR. When BODY is finished, restore the original CWD. Return the
3196 # This procedure doesn't check if DIR is a valid directory, so you
3197 # have to make sure of that.
3199 proc with_cwd { dir body } {
3201 verbose -log "Switching to directory $dir (saved CWD: $saved_dir)."
3204 set code [catch {uplevel 1 $body} result]
3206 verbose -log "Switching back to $saved_dir."
3210 global errorInfo errorCode
3211 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3213 return -code $code $result
3217 # Use GDB's 'cd' command to switch to DIR. Return true if the switch
3218 # was successful, otherwise, call perror and return false.
3220 proc gdb_cd { dir } {
3222 gdb_test_multiple "cd $dir" "" {
3223 -re "^cd \[^\r\n\]+\r\n" {
3227 -re "^Working directory (\[^\r\n\]+)\\.\r\n" {
3228 set new_dir $expect_out(1,string)
3232 -re "^$::gdb_prompt $" {
3233 if { $new_dir == "" || $new_dir != $dir } {
3234 perror "failed to switch to $dir"
3243 # Use GDB's 'pwd' command to figure out the current working directory.
3244 # Return the directory as a string. If we can't figure out the
3245 # current working directory, then call perror, and return the empty
3250 gdb_test_multiple "pwd" "" {
3255 -re "^Working directory (\[^\r\n\]+)\\.\r\n" {
3256 set dir $expect_out(1,string)
3260 -re "^$::gdb_prompt $" {
3265 perror "failed to read GDB's current working directory"
3271 # Similar to the with_cwd proc, this proc runs BODY with the current
3272 # working directory changed to CWD.
3274 # Unlike with_cwd, the directory change here is done within GDB
3275 # itself, so GDB must be running before this proc is called.
3277 proc with_gdb_cwd { dir body } {
3278 set saved_dir [gdb_pwd]
3279 if { $saved_dir == "" } {
3283 verbose -log "Switching to directory $dir (saved CWD: $saved_dir)."
3288 set code [catch {uplevel 1 $body} result]
3290 verbose -log "Switching back to $saved_dir."
3291 if ![gdb_cd $saved_dir] {
3295 # Check that GDB is still alive. If GDB crashed in the above code
3296 # then any corefile will have been left in DIR, not the root
3297 # testsuite directory. As a result the corefile will not be
3298 # brought to the users attention. Instead, if GDB crashed, then
3299 # this check should cause a FAIL, which should be enough to alert
3301 set saw_result false
3302 gdb_test_multiple "p 123" "" {
3307 -re "^\\\$$::decimal = 123\r\n" {
3312 -re "^$::gdb_prompt $" {
3313 if { !$saw_result } {
3314 fail "check gdb is alive in with_gdb_cwd"
3320 global errorInfo errorCode
3321 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3323 return -code $code $result
3327 # Run tests in BODY with GDB prompt and variable $gdb_prompt set to
3328 # PROMPT. When BODY is finished, restore GDB prompt and variable
3330 # Returns the result of BODY.
3334 # 1) If you want to use, for example, "(foo)" as the prompt you must pass it
3335 # as "(foo)", and not the regexp form "\(foo\)" (expressed as "\\(foo\\)" in
3336 # TCL). PROMPT is internally converted to a suitable regexp for matching.
3337 # We do the conversion from "(foo)" to "\(foo\)" here for a few reasons:
3338 # a) It's more intuitive for callers to pass the plain text form.
3339 # b) We need two forms of the prompt:
3340 # - a regexp to use in output matching,
3341 # - a value to pass to the "set prompt" command.
3342 # c) It's easier to convert the plain text form to its regexp form.
3344 # 2) Don't add a trailing space, we do that here.
3346 proc with_gdb_prompt { prompt body } {
3349 # Convert "(foo)" to "\(foo\)".
3350 # We don't use string_to_regexp because while it works today it's not
3351 # clear it will work tomorrow: the value we need must work as both a
3352 # regexp *and* as the argument to the "set prompt" command, at least until
3353 # we start recording both forms separately instead of just $gdb_prompt.
3354 # The testsuite is pretty-much hardwired to interpret $gdb_prompt as the
3356 regsub -all {[]*+.|()^$\[\\]} $prompt {\\&} prompt
3358 set saved $gdb_prompt
3360 verbose -log "Setting gdb prompt to \"$prompt \"."
3361 set gdb_prompt $prompt
3362 gdb_test_no_output "set prompt $prompt " ""
3364 set code [catch {uplevel 1 $body} result]
3366 verbose -log "Restoring gdb prompt to \"$saved \"."
3367 set gdb_prompt $saved
3368 gdb_test_no_output "set prompt $saved " ""
3371 global errorInfo errorCode
3372 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3374 return -code $code $result
3378 # Run tests in BODY with target-charset setting to TARGET_CHARSET. When
3379 # BODY is finished, restore target-charset.
3381 proc with_target_charset { target_charset body } {
3385 gdb_test_multiple "show target-charset" "" {
3386 -re "The target character set is \".*; currently (.*)\"\..*$gdb_prompt " {
3387 set saved $expect_out(1,string)
3389 -re "The target character set is \"(.*)\".*$gdb_prompt " {
3390 set saved $expect_out(1,string)
3392 -re ".*$gdb_prompt " {
3393 fail "get target-charset"
3397 gdb_test_no_output -nopass "set target-charset $target_charset"
3399 set code [catch {uplevel 1 $body} result]
3401 gdb_test_no_output -nopass "set target-charset $saved"
3404 global errorInfo errorCode
3405 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3407 return -code $code $result
3411 # Run tests in BODY with max-value-size set to SIZE. When BODY is
3412 # finished restore max-value-size.
3414 proc with_max_value_size { size body } {
3418 gdb_test_multiple "show max-value-size" "" {
3419 -re -wrap "Maximum value size is ($::decimal) bytes\\." {
3420 set saved $expect_out(1,string)
3422 -re ".*$gdb_prompt " {
3423 fail "get max-value-size"
3427 gdb_test_no_output -nopass "set max-value-size $size"
3429 set code [catch {uplevel 1 $body} result]
3431 gdb_test_no_output -nopass "set max-value-size $saved"
3434 global errorInfo errorCode
3435 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3437 return -code $code $result
3441 # Switch the default spawn id to SPAWN_ID, so that gdb_test,
3442 # mi_gdb_test etc. default to using it.
3444 proc switch_gdb_spawn_id {spawn_id} {
3446 global board board_info
3448 set gdb_spawn_id $spawn_id
3449 set board [host_info name]
3450 set board_info($board,fileid) $spawn_id
3453 # Clear the default spawn id.
3455 proc clear_gdb_spawn_id {} {
3457 global board board_info
3459 unset -nocomplain gdb_spawn_id
3460 set board [host_info name]
3461 unset -nocomplain board_info($board,fileid)
3464 # Run BODY with SPAWN_ID as current spawn id.
3466 proc with_spawn_id { spawn_id body } {
3469 if [info exists gdb_spawn_id] {
3470 set saved_spawn_id $gdb_spawn_id
3473 switch_gdb_spawn_id $spawn_id
3475 set code [catch {uplevel 1 $body} result]
3477 if [info exists saved_spawn_id] {
3478 switch_gdb_spawn_id $saved_spawn_id
3484 global errorInfo errorCode
3485 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3487 return -code $code $result
3491 # DejaGNU records spawn ids in a global array and tries to wait for
3492 # them when exiting. Sometimes this caused problems if gdb's test
3493 # suite has already waited for the particular spawn id. And, dejagnu
3494 # only seems to allow a single spawn id per "machine". This proc can
3495 # be used to clean up after a spawn id has been closed.
3496 proc clean_up_spawn_id {host id} {
3498 set name [board_info $host name]
3499 if {[info exists board_info($name,fileid)]
3500 && $board_info($name,fileid) == $id} {
3501 unset -nocomplain board_info($name,fileid)
3505 # Select the largest timeout from all the timeouts:
3506 # - the local "timeout" variable of the scope two levels above,
3507 # - the global "timeout" variable,
3508 # - the board variable "gdb,timeout".
3510 proc get_largest_timeout {} {
3511 upvar #0 timeout gtimeout
3512 upvar 2 timeout timeout
3515 if [info exists timeout] {
3518 if { [info exists gtimeout] && $gtimeout > $tmt } {
3521 if { [target_info exists gdb,timeout]
3522 && [target_info gdb,timeout] > $tmt } {
3523 set tmt [target_info gdb,timeout]
3533 # Run tests in BODY with timeout increased by factor of FACTOR. When
3534 # BODY is finished, restore timeout.
3536 proc with_timeout_factor { factor body } {
3539 set savedtimeout $timeout
3541 set timeout [expr [get_largest_timeout] * $factor]
3542 set code [catch {uplevel 1 $body} result]
3544 set timeout $savedtimeout
3546 global errorInfo errorCode
3547 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3549 return -code $code $result
3553 # Run BODY with timeout factor FACTOR if check-read1 is used.
3555 proc with_read1_timeout_factor { factor body } {
3556 if { [info exists ::env(READ1)] == 1 && $::env(READ1) == 1 } {
3557 # Use timeout factor
3559 # Reset timeout factor
3562 return [uplevel [list with_timeout_factor $factor $body]]
3565 # Return 1 if _Complex types are supported, otherwise, return 0.
3567 gdb_caching_proc support_complex_tests {} {
3569 if { ![allow_float_test] } {
3570 # If floating point is not supported, _Complex is not
3575 # Compile a test program containing _Complex types.
3577 return [gdb_can_simple_compile complex {
3581 _Complex long double cld;
3587 # Return 1 if compiling go is supported.
3588 gdb_caching_proc support_go_compile {} {
3590 return [gdb_can_simple_compile go-hello {
3594 fmt.Println("hello world")
3599 # Return 1 if GDB can get a type for siginfo from the target, otherwise
3602 proc supports_get_siginfo_type {} {
3603 if { [istarget "*-*-linux*"] } {
3610 # Return 1 if memory tagging is supported at runtime, otherwise return 0.
3612 gdb_caching_proc supports_memtag {} {
3615 gdb_test_multiple "memory-tag check" "" {
3616 -re "Memory tagging not supported or disabled by the current architecture\..*$gdb_prompt $" {
3619 -re "Argument required \\(address or pointer\\).*$gdb_prompt $" {
3626 # Return 1 if catch syscall is supported, otherwise return 0.
3628 gdb_caching_proc supports_catch_syscall {} {
3629 set me "supports_catch_syscall"
3631 # Compile a test program.
3637 if {![gdb_simple_compile $me $src executable]} {
3638 verbose -log "$me: failed to compile"
3642 # No error message, compilation succeeded so now run it via gdb.
3646 gdb_reinitialize_dir $::srcdir/$::subdir
3648 if { ![runto_main] } {
3649 verbose -log "$me: failed to run to main"
3653 # To make sure we test both setting and inserting the catchpoint.
3654 gdb_test_no_output "set breakpoint always-inserted on"
3659 "Catchpoint 2 (any syscall)"]
3660 gdb_test_multiple "catch syscall" "" {
3661 -re -wrap ^$re_yes {
3669 remote_file build delete $obj
3671 verbose "$me: returning $res" 2
3675 # Return 1 if the target supports hardware single stepping.
3677 proc can_hardware_single_step {} {
3679 if { [istarget "arm*-*-*"] || [istarget "mips*-*-*"]
3680 || [istarget "tic6x-*-*"] || [istarget "sparc*-*-linux*"]
3681 || [istarget "riscv*-*-linux*"] } {
3688 # Return 1 if target hardware or OS supports single stepping to signal
3689 # handler, otherwise, return 0.
3691 proc can_single_step_to_signal_handler {} {
3692 # Targets don't have hardware single step. On these targets, when
3693 # a signal is delivered during software single step, gdb is unable
3694 # to determine the next instruction addresses, because start of signal
3695 # handler is one of them.
3696 return [can_hardware_single_step]
3699 # Return 1 if target supports process record, otherwise return 0.
3701 proc supports_process_record {} {
3703 if [target_info exists gdb,use_precord] {
3704 return [target_info gdb,use_precord]
3707 if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
3708 || [istarget "i\[34567\]86-*-linux*"]
3709 || [istarget "aarch64*-*-linux*"]
3710 || [istarget "loongarch*-*-linux*"]
3711 || [istarget "powerpc*-*-linux*"]
3712 || [istarget "s390*-*-linux*"] } {
3719 # Return 1 if target supports reverse debugging, otherwise return 0.
3721 proc supports_reverse {} {
3723 if [target_info exists gdb,can_reverse] {
3724 return [target_info gdb,can_reverse]
3727 if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
3728 || [istarget "i\[34567\]86-*-linux*"]
3729 || [istarget "aarch64*-*-linux*"]
3730 || [istarget "loongarch*-*-linux*"]
3731 || [istarget "powerpc*-*-linux*"]
3732 || [istarget "s390*-*-linux*"] } {
3739 # Return 1 if readline library is used.
3741 proc readline_is_used { } {
3744 gdb_test_multiple "show editing" "" {
3745 -re ".*Editing of command lines as they are typed is on\..*$gdb_prompt $" {
3748 -re ".*$gdb_prompt $" {
3754 # Return true if readline has support for the EOF flag.
3756 proc readline_supports_eof_flag { } {
3757 gdb_test_multiple "show configuration" "" {
3758 -re -wrap "\r\nGNU Readline library version: ($::decimal)\\.($::decimal)\\s+\\((internal|system)\\)" {
3759 set major $expect_out(1,string)
3760 set minor $expect_out(2,string)
3761 set type $expect_out(3,string)
3763 # The internal readline was patched with EOF support ahead
3764 # of this landing in upstream readline.
3765 if { $type eq "internal" } {
3769 # The EOF flag support was added in readline 8.2.
3770 if { $major > 8 || $major == 8 && $minor >= 2 } {
3776 -re ".*$::gdb_prompt $" {
3782 # Return 1 if target is ELF.
3783 gdb_caching_proc is_elf_target {} {
3784 set me "is_elf_target"
3786 set src { int foo () {return 0;} }
3787 if {![gdb_simple_compile elf_target $src]} {
3791 set fp_obj [open $obj "r"]
3792 fconfigure $fp_obj -translation binary
3793 set data [read $fp_obj]
3798 set ELFMAG "\u007FELF"
3800 if {[string compare -length 4 $data $ELFMAG] != 0} {
3801 verbose "$me: returning 0" 2
3805 verbose "$me: returning 1" 2
3809 # Return 1 if the memory at address zero is readable.
3811 gdb_caching_proc is_address_zero_readable {} {
3815 gdb_test_multiple "x 0" "" {
3816 -re "Cannot access memory at address 0x0.*$gdb_prompt $" {
3819 -re ".*$gdb_prompt $" {
3827 # Produce source file NAME and write SOURCES into it.
3829 proc gdb_produce_source { name sources } {
3831 set f [open $name "w"]
3837 # Return 1 if target is ILP32.
3838 # This cannot be decided simply from looking at the target string,
3839 # as it might depend on externally passed compiler options like -m64.
3840 gdb_caching_proc is_ilp32_target {} {
3841 return [gdb_can_simple_compile is_ilp32_target {
3842 int dummy[sizeof (int) == 4
3843 && sizeof (void *) == 4
3844 && sizeof (long) == 4 ? 1 : -1];
3848 # Return 1 if target is LP64.
3849 # This cannot be decided simply from looking at the target string,
3850 # as it might depend on externally passed compiler options like -m64.
3851 gdb_caching_proc is_lp64_target {} {
3852 return [gdb_can_simple_compile is_lp64_target {
3853 int dummy[sizeof (int) == 4
3854 && sizeof (void *) == 8
3855 && sizeof (long) == 8 ? 1 : -1];
3859 # Return 1 if target has 64 bit addresses.
3860 # This cannot be decided simply from looking at the target string,
3861 # as it might depend on externally passed compiler options like -m64.
3862 gdb_caching_proc is_64_target {} {
3863 return [gdb_can_simple_compile_nodebug is_64_target {
3864 int function(void) { return 3; }
3865 int dummy[sizeof (&function) == 8 ? 1 : -1];
3869 # Return 1 if target has x86_64 registers - either amd64 or x32.
3870 # x32 target identifies as x86_64-*-linux*, therefore it cannot be determined
3871 # just from the target string.
3872 gdb_caching_proc is_amd64_regs_target {} {
3873 if {![istarget "x86_64-*-*"] && ![istarget "i?86-*"]} {
3877 return [gdb_can_simple_compile is_amd64_regs_target {
3887 # Return 1 if this target is an x86 or x86-64 with -m32.
3888 proc is_x86_like_target {} {
3889 if {![istarget "x86_64-*-*"] && ![istarget i?86-*]} {
3892 return [expr [is_ilp32_target] && ![is_amd64_regs_target]]
3895 # Return 1 if this target is an x86_64 with -m64.
3896 proc is_x86_64_m64_target {} {
3897 return [expr [istarget x86_64-*-* ] && [is_lp64_target]]
3900 # Return 1 if this target is an arm or aarch32 on aarch64.
3902 gdb_caching_proc is_aarch32_target {} {
3903 if { [istarget "arm*-*-*"] } {
3907 if { ![istarget "aarch64*-*-*"] } {
3914 lappend list "\tmov $reg, $reg"
3917 return [gdb_can_simple_compile aarch32 [join $list \n]]
3920 # Return 1 if this target is an aarch64, either lp64 or ilp32.
3922 proc is_aarch64_target {} {
3923 if { ![istarget "aarch64*-*-*"] } {
3927 return [expr ![is_aarch32_target]]
3930 # Return 1 if displaced stepping is supported on target, otherwise, return 0.
3931 proc support_displaced_stepping {} {
3933 if { [istarget "x86_64-*-linux*"] || [istarget "i\[34567\]86-*-linux*"]
3934 || [istarget "arm*-*-linux*"] || [istarget "powerpc-*-linux*"]
3935 || [istarget "powerpc64-*-linux*"] || [istarget "s390*-*-*"]
3936 || [istarget "aarch64*-*-linux*"] || [istarget "loongarch*-*-linux*"] } {
3943 # Return 0 and a reason string if GDB can determine that libc doesn't have
3944 # debug info, and 1 otherwise. This procedure is meant to be called by the
3945 # require procedure.
3946 gdb_caching_proc libc_has_debug_info {} {
3947 global srcdir subdir gdb_prompt inferior_exited_re
3949 set me "libc_has_debug_info"
3951 # Compile a test program.
3956 printf ("Hello, world!\n");
3960 if {![gdb_simple_compile $me $src executable {debug}]} {
3961 return [list 0 "failed to compile test program"]
3964 # No error message, compilation succeeded so now run it via gdb.
3968 gdb_reinitialize_dir $srcdir/$subdir
3971 set libc_has_debug_info 1
3972 set message "unable to get information on libc.so"
3973 set test "info sharedlibrary"
3974 gdb_test_multiple $test $test {
3975 -re ".*\(\\*\)\[^\r\n\]*/libc\.so.*$gdb_prompt $" {
3976 # Matched the "(*)" in the "Syms Read" columns which means:
3977 # "(*): Shared library is missing debugging information."
3978 set libc_has_debug_info 0
3979 set message "libc doesn't have debug info"
3981 -re ".*$gdb_prompt $" {
3982 # The default pattern for the GDB prompt in gdb_test_multiple
3983 # causes a FAIL if it matches, but in our case we should just
3984 # assume that there is libc debug info.
3988 remote_file build delete $obj
3990 verbose "$me: returning $libc_has_debug_info" 2
3991 if { $libc_has_debug_info } {
3992 return $libc_has_debug_info
3994 return [list $libc_has_debug_info $message]
3998 # Run a test on the target to see if it supports vmx hardware. Return 1 if so,
3999 # 0 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
4001 gdb_caching_proc allow_altivec_tests {} {
4002 global srcdir subdir gdb_prompt inferior_exited_re
4004 set me "allow_altivec_tests"
4006 # Some simulators are known to not support VMX instructions.
4007 if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
4008 verbose "$me: target known to not support VMX, returning 0" 2
4012 if {![istarget powerpc*]} {
4013 verbose "$me: PPC target required, returning 0" 2
4017 # Make sure we have a compiler that understands altivec.
4018 if [test_compiler_info gcc*] {
4019 set compile_flags "additional_flags=-maltivec"
4020 } elseif [test_compiler_info xlc*] {
4021 set compile_flags "additional_flags=-qaltivec"
4023 verbose "Could not compile with altivec support, returning 0" 2
4027 # Compile a test program containing VMX instructions.
4031 asm volatile ("vor v0,v0,v0");
4033 asm volatile ("vor 0,0,0");
4038 if {![gdb_simple_compile $me $src executable $compile_flags]} {
4042 # Compilation succeeded so now run it via gdb.
4046 gdb_reinitialize_dir $srcdir/$subdir
4050 -re ".*Illegal instruction.*${gdb_prompt} $" {
4051 verbose -log "\n$me altivec hardware not detected"
4052 set allow_vmx_tests 0
4054 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
4055 verbose -log "\n$me: altivec hardware detected"
4056 set allow_vmx_tests 1
4059 warning "\n$me: default case taken"
4060 set allow_vmx_tests 0
4064 remote_file build delete $obj
4066 verbose "$me: returning $allow_vmx_tests" 2
4067 return $allow_vmx_tests
4070 # Run a test on the power target to see if it supports ISA 3.1 instructions
4071 gdb_caching_proc allow_power_isa_3_1_tests {} {
4072 global srcdir subdir gdb_prompt inferior_exited_re
4074 set me "allow_power_isa_3_1_tests"
4076 # Compile a test program containing ISA 3.1 instructions.
4079 asm volatile ("pnop"); // marker
4080 asm volatile ("nop");
4085 if {![gdb_simple_compile $me $src executable ]} {
4089 # No error message, compilation succeeded so now run it via gdb.
4093 gdb_reinitialize_dir $srcdir/$subdir
4097 -re ".*Illegal instruction.*${gdb_prompt} $" {
4098 verbose -log "\n$me Power ISA 3.1 hardware not detected"
4099 set allow_power_isa_3_1_tests 0
4101 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
4102 verbose -log "\n$me: Power ISA 3.1 hardware detected"
4103 set allow_power_isa_3_1_tests 1
4106 warning "\n$me: default case taken"
4107 set allow_power_isa_3_1_tests 0
4111 remote_file build delete $obj
4113 verbose "$me: returning $allow_power_isa_3_1_tests" 2
4114 return $allow_power_isa_3_1_tests
4117 # Run a test on the target to see if it supports vmx hardware. Return 1 if so,
4118 # 0 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
4120 gdb_caching_proc allow_vsx_tests {} {
4121 global srcdir subdir gdb_prompt inferior_exited_re
4123 set me "allow_vsx_tests"
4125 # Some simulators are known to not support Altivec instructions, so
4126 # they won't support VSX instructions as well.
4127 if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
4128 verbose "$me: target known to not support VSX, returning 0" 2
4132 # Make sure we have a compiler that understands altivec.
4133 if [test_compiler_info gcc*] {
4134 set compile_flags "additional_flags=-mvsx"
4135 } elseif [test_compiler_info xlc*] {
4136 set compile_flags "additional_flags=-qasm=gcc"
4138 verbose "Could not compile with vsx support, returning 0" 2
4142 # Compile a test program containing VSX instructions.
4145 double a[2] = { 1.0, 2.0 };
4147 asm volatile ("lxvd2x v0,v0,%[addr]" : : [addr] "r" (a));
4149 asm volatile ("lxvd2x 0,0,%[addr]" : : [addr] "r" (a));
4154 if {![gdb_simple_compile $me $src executable $compile_flags]} {
4158 # No error message, compilation succeeded so now run it via gdb.
4162 gdb_reinitialize_dir $srcdir/$subdir
4166 -re ".*Illegal instruction.*${gdb_prompt} $" {
4167 verbose -log "\n$me VSX hardware not detected"
4168 set allow_vsx_tests 0
4170 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
4171 verbose -log "\n$me: VSX hardware detected"
4172 set allow_vsx_tests 1
4175 warning "\n$me: default case taken"
4176 set allow_vsx_tests 0
4180 remote_file build delete $obj
4182 verbose "$me: returning $allow_vsx_tests" 2
4183 return $allow_vsx_tests
4186 # Run a test on the target to see if it supports TSX hardware. Return 1 if so,
4187 # 0 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
4189 gdb_caching_proc allow_tsx_tests {} {
4190 global srcdir subdir gdb_prompt inferior_exited_re
4192 set me "allow_tsx_tests"
4194 # Compile a test program.
4197 asm volatile ("xbegin .L0");
4198 asm volatile ("xend");
4199 asm volatile (".L0: nop");
4203 if {![gdb_simple_compile $me $src executable]} {
4207 # No error message, compilation succeeded so now run it via gdb.
4211 gdb_reinitialize_dir $srcdir/$subdir
4215 -re ".*Illegal instruction.*${gdb_prompt} $" {
4216 verbose -log "$me: TSX hardware not detected."
4217 set allow_tsx_tests 0
4219 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
4220 verbose -log "$me: TSX hardware detected."
4221 set allow_tsx_tests 1
4224 warning "\n$me: default case taken."
4225 set allow_tsx_tests 0
4229 remote_file build delete $obj
4231 verbose "$me: returning $allow_tsx_tests" 2
4232 return $allow_tsx_tests
4235 # Run a test on the target to see if it supports avx512bf16. Return 1 if so,
4236 # 0 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
4238 gdb_caching_proc allow_avx512bf16_tests {} {
4239 global srcdir subdir gdb_prompt inferior_exited_re
4241 set me "allow_avx512bf16_tests"
4242 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
4243 verbose "$me: target does not support avx512bf16, returning 0" 2
4247 # Compile a test program.
4250 asm volatile ("vcvtne2ps2bf16 %xmm0, %xmm1, %xmm0");
4254 if {![gdb_simple_compile $me $src executable]} {
4258 # No error message, compilation succeeded so now run it via gdb.
4262 gdb_reinitialize_dir $srcdir/$subdir
4266 -re ".*Illegal instruction.*${gdb_prompt} $" {
4267 verbose -log "$me: avx512bf16 hardware not detected."
4268 set allow_avx512bf16_tests 0
4270 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
4271 verbose -log "$me: avx512bf16 hardware detected."
4272 set allow_avx512bf16_tests 1
4275 warning "\n$me: default case taken."
4276 set allow_avx512bf16_tests 0
4280 remote_file build delete $obj
4282 verbose "$me: returning $allow_avx512bf16_tests" 2
4283 return $allow_avx512bf16_tests
4286 # Run a test on the target to see if it supports avx512fp16. Return 1 if so,
4287 # 0 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
4289 gdb_caching_proc allow_avx512fp16_tests {} {
4290 global srcdir subdir gdb_prompt inferior_exited_re
4292 set me "allow_avx512fp16_tests"
4293 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
4294 verbose "$me: target does not support avx512fp16, returning 0" 2
4298 # Compile a test program.
4301 asm volatile ("vcvtps2phx %xmm1, %xmm0");
4305 if {![gdb_simple_compile $me $src executable]} {
4309 # No error message, compilation succeeded so now run it via gdb.
4313 gdb_reinitialize_dir $srcdir/$subdir
4317 -re ".*Illegal instruction.*${gdb_prompt} $" {
4318 verbose -log "$me: avx512fp16 hardware not detected."
4319 set allow_avx512fp16_tests 0
4321 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
4322 verbose -log "$me: avx512fp16 hardware detected."
4323 set allow_avx512fp16_tests 1
4326 warning "\n$me: default case taken."
4327 set allow_avx512fp16_tests 0
4331 remote_file build delete $obj
4333 verbose "$me: returning $allow_avx512fp16_tests" 2
4334 return $allow_avx512fp16_tests
4337 # Run a test on the target to see if it supports LAM 57. Return 1 if so,
4338 # 0 if it does not. Based on the arch_prctl() handle ARCH_ENABLE_TAGGED_ADDR
4339 # to enable LAM which fails if the hardware or the OS does not support LAM.
4341 gdb_caching_proc allow_lam_tests {} {
4342 global gdb_prompt inferior_exited_re
4344 set me "allow_lam_tests"
4345 if { ![istarget "x86_64-*-*"] } {
4346 verbose "$me: target does not support LAM, returning 1" 2
4350 # Compile a test program.
4354 #include <sys/syscall.h>
4357 #include <asm/prctl.h>
4359 int configure_lam ()
4362 syscall (SYS_arch_prctl, ARCH_ENABLE_TAGGED_ADDR, 6);
4363 assert_perror (errno);
4368 main () { return configure_lam (); }
4371 if {![gdb_simple_compile $me $src executable ""]} {
4374 # No error message, compilation succeeded so now run it via gdb.
4376 set allow_lam_tests 0
4380 -re ".*$inferior_exited_re with code.*${gdb_prompt} $" {
4381 verbose -log "$me: LAM support not detected."
4383 -re ".*Program received signal SIGABRT, Aborted.*${gdb_prompt} $" {
4384 verbose -log "$me: LAM support not detected."
4386 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
4387 verbose -log "$me: LAM support detected."
4388 set allow_lam_tests 1
4391 warning "\n$me: default case taken."
4395 remote_file build delete $obj
4397 verbose "$me: returning $allow_lam_tests" 2
4398 return $allow_lam_tests
4401 # Run a test on the target to see if it supports btrace hardware. Return 1 if so,
4402 # 0 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
4404 gdb_caching_proc allow_btrace_tests {} {
4405 global srcdir subdir gdb_prompt inferior_exited_re
4407 set me "allow_btrace_tests"
4408 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
4409 verbose "$me: target does not support btrace, returning 0" 2
4413 # Compile a test program.
4414 set src { int main() { return 0; } }
4415 if {![gdb_simple_compile $me $src executable]} {
4419 # No error message, compilation succeeded so now run it via gdb.
4423 gdb_reinitialize_dir $srcdir/$subdir
4428 # In case of an unexpected output, we return 2 as a fail value.
4429 set allow_btrace_tests 2
4430 gdb_test_multiple "record btrace" "check btrace support" {
4431 -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
4432 set allow_btrace_tests 0
4434 -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
4435 set allow_btrace_tests 0
4437 -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
4438 set allow_btrace_tests 0
4440 -re "^record btrace\r\n$gdb_prompt $" {
4441 set allow_btrace_tests 1
4445 remote_file build delete $obj
4447 verbose "$me: returning $allow_btrace_tests" 2
4448 return $allow_btrace_tests
4451 # Run a test on the target to see if it supports btrace pt hardware.
4452 # Return 1 if so, 0 if it does not. Based on 'check_vmx_hw_available'
4453 # from the GCC testsuite.
4455 gdb_caching_proc allow_btrace_pt_tests {} {
4456 global srcdir subdir gdb_prompt inferior_exited_re
4458 set me "allow_btrace_pt_tests"
4459 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
4460 verbose "$me: target does not support btrace, returning 1" 2
4464 # Compile a test program.
4465 set src { int main() { return 0; } }
4466 if {![gdb_simple_compile $me $src executable]} {
4470 # No error message, compilation succeeded so now run it via gdb.
4474 gdb_reinitialize_dir $srcdir/$subdir
4479 # In case of an unexpected output, we return 2 as a fail value.
4480 set allow_btrace_pt_tests 2
4481 gdb_test_multiple "record btrace pt" "check btrace pt support" {
4482 -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
4483 set allow_btrace_pt_tests 0
4485 -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
4486 set allow_btrace_pt_tests 0
4488 -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
4489 set allow_btrace_pt_tests 0
4491 -re "support was disabled at compile time.*\r\n$gdb_prompt $" {
4492 set allow_btrace_pt_tests 0
4494 -re "^record btrace pt\r\n$gdb_prompt $" {
4495 set allow_btrace_pt_tests 1
4499 remote_file build delete $obj
4501 verbose "$me: returning $allow_btrace_pt_tests" 2
4502 return $allow_btrace_pt_tests
4505 # Run a test on the target to see if it supports ptwrite instructions and
4506 # if GDB can decode ptwrite events. Return 1 if so, 0 if it does not.
4508 gdb_caching_proc allow_btrace_ptw_tests {} {
4509 global srcdir subdir gdb_prompt inferior_exited_re decimal
4511 require allow_btrace_pt_tests
4512 set me "allow_btrace_ptw_tests"
4515 #include <immintrin.h>
4525 set compile_flags "additional_flags=-mptwrite"
4526 if {![gdb_simple_compile $me $src executable $compile_flags]} {
4532 gdb_reinitialize_dir $srcdir/$subdir
4538 gdb_test_no_output "record btrace pt" "$me: record btrace pt"
4540 set allow_btrace_ptw_tests 0
4541 gdb_test_multiple "next" "$me: next" {
4542 -re -wrap ".*Illegal instruction.*" {
4543 verbose -log "$me: ptwrite instruction support not detected."
4545 -re -wrap ".*$inferior_exited_re normally.*" {
4546 verbose -log "$me: ptwrite support not detected."
4548 -re -wrap "$decimal.*(at|in|return 0).*" {
4549 set allow_btrace_ptw_tests 1
4553 if { $allow_btrace_ptw_tests == 1 } {
4554 # Show the func-call-history to get the packet trace.
4555 gdb_test "record function-call-history" ".*"
4557 gdb_test_multiple "maintenance btrace packet-history 0,1000" \
4558 "$me: check decoding support" {
4560 verbose -log "$me: ptwrite decoding support detected."
4561 set allow_btrace_ptw_tests 1
4564 verbose -log "$me: ptwrite decoding support not detected."
4565 set allow_btrace_ptw_tests 0
4571 remote_file build delete $obj
4573 verbose "$me: returning $allow_btrace_ptw_tests" 2
4574 return $allow_btrace_ptw_tests
4578 # Run a test on the target to see if GDB supports event tracing on it.
4579 # Return 1 if so, 0 if it does not.
4581 gdb_caching_proc allow_btrace_pt_event_trace_tests {} {
4582 global srcdir subdir
4583 set me "allow_btrace_pt_event_trace_tests"
4584 require allow_btrace_pt_tests
4594 if {![gdb_simple_compile $me $src executable]} {
4600 gdb_reinitialize_dir $srcdir/$subdir
4606 set allow_event_trace_tests 0
4607 gdb_test_multiple "set record btrace pt event-tracing on" "$me: first check" {
4608 -re -wrap "Event-tracing is not supported by GDB." {
4611 set allow_event_trace_tests 1
4615 if { $allow_event_trace_tests == 1 } {
4616 gdb_test_multiple "record btrace pt" "$me: check OS support" {
4620 verbose -log "$me: Target doesn't support event tracing."
4621 set allow_event_trace_tests 0
4627 remote_file build delete $obj
4629 verbose "$me: returning $allow_event_trace_tests" 2
4630 return $allow_event_trace_tests
4634 # Run a test on the target to see if it supports Aarch64 SVE hardware.
4635 # Return 1 if so, 0 if it does not. Note this causes a restart of GDB.
4637 gdb_caching_proc allow_aarch64_sve_tests {} {
4638 global srcdir subdir gdb_prompt inferior_exited_re
4640 set me "allow_aarch64_sve_tests"
4642 if { ![is_aarch64_target]} {
4646 set compile_flags "{additional_flags=-march=armv8-a+sve}"
4648 # Compile a test program containing SVE instructions.
4651 asm volatile ("ptrue p0.b");
4655 if {![gdb_simple_compile $me $src executable $compile_flags]} {
4659 # Compilation succeeded so now run it via gdb.
4663 -re ".*Illegal instruction.*${gdb_prompt} $" {
4664 verbose -log "\n$me sve hardware not detected"
4665 set allow_sve_tests 0
4667 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
4668 verbose -log "\n$me: sve hardware detected"
4669 set allow_sve_tests 1
4672 warning "\n$me: default case taken"
4673 set allow_sve_tests 0
4677 remote_file build delete $obj
4679 # While testing for SVE support, also discover all the supported vector
4681 aarch64_initialize_sve_information
4683 verbose "$me: returning $allow_sve_tests" 2
4684 return $allow_sve_tests
4687 # Assuming SVE is supported by the target, run some checks to determine all
4688 # the supported vector length values and return an array containing all of those
4689 # values. Since this is a gdb_caching_proc, this proc will only be executed
4692 # To check if a particular SVE vector length is supported, the following code
4693 # can be used. For instance, for vl == 16:
4695 # if {[aarch64_supports_sve_vl 16]} {
4696 # verbose -log "SVE vector length 16 is supported."
4699 # This procedure should NEVER be called by hand, as it reinitializes the GDB
4700 # session and will derail a test. This should be called automatically as part
4701 # of the SVE support test routine allow_aarch64_sve_tests. Users should
4702 # restrict themselves to calling the helper proc aarch64_supports_sve_vl.
4704 gdb_caching_proc aarch64_initialize_sve_information { } {
4707 set src "${srcdir}/lib/aarch64-test-sve.c"
4708 set test_exec [standard_temp_file "aarch64-test-sve.x"]
4709 set compile_flags "{additional_flags=-march=armv8-a+sve}"
4710 array set supported_vl {}
4712 # Compile the SVE vector length test.
4713 set result [gdb_compile $src $test_exec executable [list debug ${compile_flags} nowarnings]]
4715 if {$result != ""} {
4716 verbose -log "Failed to compile SVE information gathering test."
4717 return [array get supported_vl]
4720 clean_restart $test_exec
4722 if {![runto_main]} {
4723 return [array get supported_vl]
4726 set stop_breakpoint "stop here"
4727 gdb_breakpoint [gdb_get_line_number $stop_breakpoint $src]
4728 gdb_continue_to_breakpoint $stop_breakpoint
4730 # Go through the data and extract the supported SVE vector lengths.
4731 set vl_count [get_valueof "" "supported_vl_count" "0" \
4732 "fetch value of supported_vl_count"]
4733 verbose -log "Found $vl_count supported SVE vector length values"
4735 for {set vl_index 0} {$vl_index < $vl_count} {incr vl_index} {
4736 set test_vl [get_valueof "" "supported_vl\[$vl_index\]" "0" \
4737 "fetch value of supported_vl\[$vl_index\]"]
4739 # Mark this vector length as supported.
4740 if {$test_vl != 0} {
4741 verbose -log "Found supported SVE vector length $test_vl"
4742 set supported_vl($test_vl) 1
4747 verbose -log "Cleaning up"
4748 remote_file build delete $test_exec
4750 verbose -log "Done gathering information about AArch64 SVE vector lengths."
4752 # Return the array containing all of the supported SVE vl values.
4753 return [array get supported_vl]
4757 # Return 1 if the target supports SVE vl LENGTH
4758 # Return 0 otherwise.
4761 proc aarch64_supports_sve_vl { length } {
4763 # Fetch the cached array of supported SVE vl values.
4764 array set supported_vl [aarch64_initialize_sve_information]
4766 # Do we have the global values cached?
4767 if {![info exists supported_vl($length)]} {
4768 verbose -log "Target does not support SVE vl $length"
4772 # The target supports SVE vl LENGTH.
4776 # Run a test on the target to see if it supports Aarch64 SME extensions.
4777 # Return 0 if so, 1 if it does not. Note this causes a restart of GDB.
4779 gdb_caching_proc allow_aarch64_sme_tests {} {
4780 global srcdir subdir gdb_prompt inferior_exited_re
4782 set me "allow_aarch64_sme_tests"
4784 if { ![is_aarch64_target]} {
4788 set compile_flags "{additional_flags=-march=armv8-a+sme}"
4790 # Compile a test program containing SME instructions.
4793 asm volatile ("smstart za");
4797 if {![gdb_simple_compile $me $src executable $compile_flags]} {
4798 # Try again, but with a raw hex instruction so we don't rely on
4799 # assembler support for SME.
4801 set compile_flags "{additional_flags=-march=armv8-a}"
4803 # Compile a test program containing SME instructions.
4806 asm volatile (".word 0xD503457F");
4811 if {![gdb_simple_compile $me $src executable $compile_flags]} {
4816 # Compilation succeeded so now run it via gdb.
4820 -re ".*Illegal instruction.*${gdb_prompt} $" {
4821 verbose -log "\n$me sme support not detected"
4822 set allow_sme_tests 0
4824 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
4825 verbose -log "\n$me: sme support detected"
4826 set allow_sme_tests 1
4829 warning "\n$me: default case taken"
4830 set allow_sme_tests 0
4834 remote_file build delete $obj
4836 # While testing for SME support, also discover all the supported vector
4838 aarch64_initialize_sme_information
4840 verbose "$me: returning $allow_sme_tests" 2
4841 return $allow_sme_tests
4844 # Assuming SME is supported by the target, run some checks to determine all
4845 # the supported streaming vector length values and return an array containing
4846 # all of those values. Since this is a gdb_caching_proc, this proc will only
4849 # To check if a particular SME streaming vector length is supported, the
4850 # following code can be used. For instance, for svl == 32:
4852 # if {[aarch64_supports_sme_svl 32]} {
4853 # verbose -log "SME streaming vector length 32 is supported."
4856 # This procedure should NEVER be called by hand, as it reinitializes the GDB
4857 # session and will derail a test. This should be called automatically as part
4858 # of the SME support test routine allow_aarch64_sme_tests. Users should
4859 # restrict themselves to calling the helper proc aarch64_supports_sme_svl.
4861 gdb_caching_proc aarch64_initialize_sme_information { } {
4864 set src "${srcdir}/lib/aarch64-test-sme.c"
4865 set test_exec [standard_temp_file "aarch64-test-sme.x"]
4866 set compile_flags "{additional_flags=-march=armv8-a+sme}"
4867 array set supported_svl {}
4869 # Compile the SME vector length test.
4870 set result [gdb_compile $src $test_exec executable [list debug ${compile_flags} nowarnings]]
4872 if {$result != ""} {
4873 verbose -log "Failed to compile SME information gathering test."
4874 return [array get supported_svl]
4877 clean_restart $test_exec
4879 if {![runto_main]} {
4880 return [array get supported_svl]
4883 set stop_breakpoint "stop here"
4884 gdb_breakpoint [gdb_get_line_number $stop_breakpoint $src]
4885 gdb_continue_to_breakpoint $stop_breakpoint
4887 # Go through the data and extract the supported SME vector lengths.
4888 set svl_count [get_valueof "" "supported_svl_count" "0" \
4889 "fetch value of supported_svl_count"]
4890 verbose -log "Found $svl_count supported SME vector length values"
4892 for {set svl_index 0} {$svl_index < $svl_count} {incr svl_index} {
4893 set test_svl [get_valueof "" "supported_svl\[$svl_index\]" "0" \
4894 "fetch value of supported_svl\[$svl_index\]"]
4896 # Mark this streaming vector length as supported.
4897 if {$test_svl != 0} {
4898 verbose -log "Found supported SME vector length $test_svl"
4899 set supported_svl($test_svl) 1
4904 verbose -log "Cleaning up"
4905 remote_file build delete $test_exec
4907 verbose -log "Done gathering information about AArch64 SME vector lengths."
4909 # Return the array containing all of the supported SME svl values.
4910 return [array get supported_svl]
4914 # Return 1 if the target supports SME svl LENGTH
4915 # Return 0 otherwise.
4918 proc aarch64_supports_sme_svl { length } {
4920 # Fetch the cached array of supported SME svl values.
4921 array set supported_svl [aarch64_initialize_sme_information]
4923 # Do we have the global values cached?
4924 if {![info exists supported_svl($length)]} {
4925 verbose -log "Target does not support SME svl $length"
4929 # The target supports SME svl LENGTH.
4933 # Run a test on the target to see if it supports AArch64 MOPS (Memory
4934 # Operations) extensions. Return 1 if so, 0 if it does not. Note this
4935 # causes a restart of GDB.
4937 gdb_caching_proc allow_aarch64_mops_tests {} {
4938 global srcdir subdir gdb_prompt inferior_exited_re
4940 set me "allow_aarch64_mops_tests"
4942 if { ![is_aarch64_target]} {
4946 # ARMv9.3-A contains the MOPS extension. The test program doesn't use it,
4947 # but take the opportunity to check whether the toolchain knows about MOPS.
4948 set compile_flags "{additional_flags=-march=armv9.3-a}"
4950 # Compile a program that tests the MOPS feature.
4952 #include <stdbool.h>
4953 #include <sys/auxv.h>
4956 #define HWCAP2_MOPS (1UL << 43)
4960 bool mops_supported = getauxval (AT_HWCAP2) & HWCAP2_MOPS;
4962 return !mops_supported;
4966 if {![gdb_simple_compile $me $src executable $compile_flags]} {
4970 # Compilation succeeded so now run it via gdb.
4974 -re ".*$inferior_exited_re with code 01.*${gdb_prompt} $" {
4975 verbose -log "\n$me mops support not detected"
4976 set allow_mops_tests 0
4978 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
4979 verbose -log "\n$me: mops support detected"
4980 set allow_mops_tests 1
4983 warning "\n$me: default case taken"
4984 set allow_mops_tests 0
4988 remote_file build delete $obj
4990 verbose "$me: returning $allow_mops_tests" 2
4991 return $allow_mops_tests
4994 # A helper that compiles a test case to see if __int128 is supported.
4995 proc gdb_int128_helper {lang} {
4996 return [gdb_can_simple_compile "i128-for-$lang" {
4998 int main() { return 0; }
5002 # Return true if the C compiler understands the __int128 type.
5003 gdb_caching_proc has_int128_c {} {
5004 return [gdb_int128_helper c]
5007 # Return true if the C++ compiler understands the __int128 type.
5008 gdb_caching_proc has_int128_cxx {} {
5009 return [gdb_int128_helper c++]
5012 # Return true if the IFUNC feature is supported.
5013 gdb_caching_proc allow_ifunc_tests {} {
5014 if [gdb_can_simple_compile ifunc {
5016 typedef void F (void);
5017 F* g (void) { return &f_; }
5018 void f () __attribute__ ((ifunc ("g")));
5026 # Return whether we should skip tests for showing inlined functions in
5027 # backtraces. Requires get_compiler_info and get_debug_format.
5029 proc skip_inline_frame_tests {} {
5030 # GDB only recognizes inlining information in DWARF.
5031 if { ! [test_debug_format "DWARF \[0-9\]"] } {
5035 # GCC before 4.1 does not emit DW_AT_call_file / DW_AT_call_line.
5036 if { ([test_compiler_info "gcc-2-*"]
5037 || [test_compiler_info "gcc-3-*"]
5038 || [test_compiler_info "gcc-4-0-*"]) } {
5045 # Return whether we should skip tests for showing variables from
5046 # inlined functions. Requires get_compiler_info and get_debug_format.
5048 proc skip_inline_var_tests {} {
5049 # GDB only recognizes inlining information in DWARF.
5050 if { ! [test_debug_format "DWARF \[0-9\]"] } {
5057 # Return a 1 if we should run tests that require hardware breakpoints
5059 proc allow_hw_breakpoint_tests {} {
5060 # Skip tests if requested by the board (note that no_hardware_watchpoints
5061 # disables both watchpoints and breakpoints)
5062 if { [target_info exists gdb,no_hardware_watchpoints]} {
5066 # These targets support hardware breakpoints natively
5067 if { [istarget "i?86-*-*"]
5068 || [istarget "x86_64-*-*"]
5069 || [istarget "ia64-*-*"]
5070 || [istarget "arm*-*-*"]
5071 || [istarget "aarch64*-*-*"]
5072 || [istarget "s390*-*-*"] } {
5079 # Return a 1 if we should run tests that require hardware watchpoints
5081 proc allow_hw_watchpoint_tests {} {
5082 # Skip tests if requested by the board
5083 if { [target_info exists gdb,no_hardware_watchpoints]} {
5087 # These targets support hardware watchpoints natively
5088 # Note, not all Power 9 processors support hardware watchpoints due to a HW
5089 # bug. Use has_hw_wp_support to check do a runtime check for hardware
5090 # watchpoint support on Powerpc.
5091 if { [istarget "i?86-*-*"]
5092 || [istarget "x86_64-*-*"]
5093 || [istarget "ia64-*-*"]
5094 || [istarget "arm*-*-*"]
5095 || [istarget "aarch64*-*-*"]
5096 || ([istarget "powerpc*-*-linux*"] && [has_hw_wp_support])
5097 || [istarget "s390*-*-*"] } {
5104 # Return a 1 if we should run tests that require *multiple* hardware
5105 # watchpoints to be active at the same time
5107 proc allow_hw_watchpoint_multi_tests {} {
5108 if { ![allow_hw_watchpoint_tests] } {
5112 # These targets support just a single hardware watchpoint
5113 if { [istarget "arm*-*-*"]
5114 || [istarget "powerpc*-*-linux*"] } {
5121 # Return a 1 if we should run tests that require read/access watchpoints
5123 proc allow_hw_watchpoint_access_tests {} {
5124 if { ![allow_hw_watchpoint_tests] } {
5128 # These targets support just write watchpoints
5129 if { [istarget "s390*-*-*"] } {
5136 # Return 1 if we should skip tests that require the runtime unwinder
5137 # hook. This must be invoked while gdb is running, after shared
5138 # libraries have been loaded. This is needed because otherwise a
5139 # shared libgcc won't be visible.
5141 proc skip_unwinder_tests {} {
5145 gdb_test_multiple "print _Unwind_DebugHook" "check for unwinder hook" {
5146 -re "= .*no debug info.*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
5148 -re "= .*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
5151 -re "No symbol .* in current context.\r\n$gdb_prompt $" {
5155 gdb_test_multiple "info probe" "check for stap probe in unwinder" {
5156 -re ".*libgcc.*unwind.*\r\n$gdb_prompt $" {
5159 -re "\r\n$gdb_prompt $" {
5166 # Return 1 if we should skip tests that require the libstdc++ stap
5167 # probes. This must be invoked while gdb is running, after shared
5168 # libraries have been loaded. PROMPT_REGEXP is the expected prompt.
5170 proc skip_libstdcxx_probe_tests_prompt { prompt_regexp } {
5172 gdb_test_multiple "info probes stap libstdcxx" \
5173 "check for stap probe in libstdc++" \
5174 -prompt "$prompt_regexp" {
5175 -re ".*libstdcxx.*catch.*\r\n$prompt_regexp" {
5178 -re "\r\n$prompt_regexp" {
5181 set skip [expr !$supported]
5185 # As skip_libstdcxx_probe_tests_prompt, with gdb_prompt.
5187 proc skip_libstdcxx_probe_tests {} {
5189 return [skip_libstdcxx_probe_tests_prompt "$gdb_prompt $"]
5192 # Return 1 if libc supports the longjmp probe. Note that we're not using
5193 # gdb_caching_proc because the probe may have been disabled.
5195 proc have_longjmp_probe {} {
5197 gdb_test_multiple "info probes stap libc ^longjmp$" "" {
5198 -re -wrap "No probes matched\\." {
5201 -re -wrap "\r\nstap\[ \t\]+libc\[ \t\]+longjmp\[ \t\]+.*" {
5205 if { $have_probe == -1 } {
5206 error "failed to get libc longjmp probe status"
5211 # Returns true if gdb_protocol is empty, indicating use of the native
5214 proc gdb_protocol_is_native { } {
5215 return [expr {[target_info gdb_protocol] == ""}]
5218 # Returns true if gdb_protocol is either "remote" or
5219 # "extended-remote".
5221 proc gdb_protocol_is_remote { } {
5222 return [expr {[target_info gdb_protocol] == "remote"
5223 || [target_info gdb_protocol] == "extended-remote"}]
5226 # Like istarget, but checks a list of targets.
5227 proc is_any_target {args} {
5228 foreach targ $args {
5229 if {[istarget $targ]} {
5236 # Return the effective value of use_gdb_stub.
5238 # If the use_gdb_stub global has been set (it is set when the gdb process is
5239 # spawned), return that. Otherwise, return the value of the use_gdb_stub
5240 # property from the board file.
5242 # This is the preferred way of checking use_gdb_stub, since it allows to check
5243 # the value before the gdb has been spawned and it will return the correct value
5244 # even when it was overriden by the test.
5246 # Note that stub targets are not able to spawn new inferiors. Use this
5247 # check for skipping respective tests.
5249 proc use_gdb_stub {} {
5252 if [info exists use_gdb_stub] {
5253 return $use_gdb_stub
5256 return [target_info exists use_gdb_stub]
5259 # Return 1 if the current remote target is an instance of our GDBserver, 0
5260 # otherwise. Return -1 if there was an error and we can't tell.
5262 gdb_caching_proc target_is_gdbserver {} {
5266 set test "probing for GDBserver"
5268 gdb_test_multiple "monitor help" $test {
5269 -re "The following monitor commands are supported.*Quit GDBserver.*$gdb_prompt $" {
5272 -re "$gdb_prompt $" {
5277 if { $is_gdbserver == -1 } {
5278 verbose -log "Unable to tell whether we are using GDBserver or not."
5281 return $is_gdbserver
5284 # N.B. compiler_info is intended to be local to this file.
5285 # Call test_compiler_info with no arguments to fetch its value.
5286 # Yes, this is counterintuitive when there's get_compiler_info,
5287 # but that's the current API.
5288 if [info exists compiler_info] {
5292 # Figure out what compiler I am using.
5293 # The result is cached so only the first invocation runs the compiler.
5295 # ARG can be empty or "C++". If empty, "C" is assumed.
5297 # There are several ways to do this, with various problems.
5299 # [ gdb_compile -E $ifile -o $binfile.ci ]
5300 # source $binfile.ci
5302 # Single Unix Spec v3 says that "-E -o ..." together are not
5303 # specified. And in fact, the native compiler on hp-ux 11 (among
5304 # others) does not work with "-E -o ...". Most targets used to do
5305 # this, and it mostly worked, because it works with gcc.
5307 # [ catch "exec $compiler -E $ifile > $binfile.ci" exec_output ]
5308 # source $binfile.ci
5310 # This avoids the problem with -E and -o together. This almost works
5311 # if the build machine is the same as the host machine, which is
5312 # usually true of the targets which are not gcc. But this code does
5313 # not figure which compiler to call, and it always ends up using the C
5314 # compiler. Not good for setting hp_aCC_compiler. Target
5315 # hppa*-*-hpux* used to do this.
5317 # [ gdb_compile -E $ifile > $binfile.ci ]
5318 # source $binfile.ci
5320 # dejagnu target_compile says that it supports output redirection,
5321 # but the code is completely different from the normal path and I
5322 # don't want to sweep the mines from that path. So I didn't even try
5325 # set cppout [ gdb_compile $ifile "" preprocess $args quiet ]
5328 # I actually do this for all targets now. gdb_compile runs the right
5329 # compiler, and TCL captures the output, and I eval the output.
5331 # Unfortunately, expect logs the output of the command as it goes by,
5332 # and dejagnu helpfully prints a second copy of it right afterwards.
5333 # So I turn off expect logging for a moment.
5335 # [ gdb_compile $ifile $ciexe_file executable $args ]
5336 # [ remote_exec $ciexe_file ]
5337 # [ source $ci_file.out ]
5339 # I could give up on -E and just do this.
5340 # I didn't get desperate enough to try this.
5342 # -- chastain 2004-01-06
5344 proc get_compiler_info {{language "c"}} {
5346 # For compiler.c, compiler.cc and compiler.F90.
5349 # I am going to play with the log to keep noise out.
5353 # These come from compiler.c, compiler.cc or compiler.F90.
5354 gdb_persistent_global compiler_info_cache
5356 if [info exists compiler_info_cache($language)] {
5361 # Choose which file to preprocess.
5362 if { $language == "c++" } {
5363 set ifile "${srcdir}/lib/compiler.cc"
5364 } elseif { $language == "f90" } {
5365 set ifile "${srcdir}/lib/compiler.F90"
5366 } elseif { $language == "c" } {
5367 set ifile "${srcdir}/lib/compiler.c"
5369 perror "Unable to fetch compiler version for language: $language"
5373 # Run $ifile through the right preprocessor.
5374 # Toggle gdb.log to keep the compiler output out of the log.
5375 set saved_log [log_file -info]
5377 if [is_remote host] {
5378 # We have to use -E and -o together, despite the comments
5379 # above, because of how DejaGnu handles remote host testing.
5380 set ppout [standard_temp_file compiler.i]
5381 gdb_compile "${ifile}" "$ppout" preprocess [list "$language" quiet getting_compiler_info]
5382 set file [open $ppout r]
5383 set cppout [read $file]
5386 # Copy $ifile to temp dir, to work around PR gcc/60447. This will leave the
5387 # superfluous .s file in the temp dir instead of in the source dir.
5388 set tofile [file tail $ifile]
5389 set tofile [standard_temp_file $tofile]
5390 file copy -force $ifile $tofile
5392 set cppout [ gdb_compile "${ifile}" "" preprocess [list "$language" quiet getting_compiler_info] ]
5394 eval log_file $saved_log
5398 foreach cppline [ split "$cppout" "\n" ] {
5399 if { [ regexp "^#" "$cppline" ] } {
5401 } elseif { [ regexp "^\[\n\r\t \]*$" "$cppline" ] } {
5403 } elseif { [ regexp "^\[\n\r\t \]*set\[\n\r\t \]" "$cppline" ] } {
5405 verbose "get_compiler_info: $cppline" 2
5407 } elseif { [ regexp {[fc]lang.*warning.*'-fdiagnostics-color=never'} "$cppline"] } {
5408 # Both flang preprocessors (llvm flang and classic flang) print a
5409 # warning for the unused -fdiagnostics-color=never, so we skip this
5411 # The armflang preprocessor has been observed to output the
5412 # warning prefixed with "clang", so the regex also accepts
5416 verbose -log "get_compiler_info: $cppline"
5421 # Set to unknown if for some reason compiler_info didn't get defined.
5422 if ![info exists compiler_info] {
5423 verbose -log "get_compiler_info: compiler_info not provided"
5424 set compiler_info "unknown"
5426 # Also set to unknown compiler if any diagnostics happened.
5428 verbose -log "get_compiler_info: got unexpected diagnostics"
5429 set compiler_info "unknown"
5432 set compiler_info_cache($language) $compiler_info
5434 # Log what happened.
5435 verbose -log "get_compiler_info: $compiler_info"
5440 # Return the compiler_info string if no arg is provided.
5441 # Otherwise the argument is a glob-style expression to match against
5444 proc test_compiler_info { {compiler ""} {language "c"} } {
5445 gdb_persistent_global compiler_info_cache
5447 if [get_compiler_info $language] {
5448 # An error will already have been printed in this case. Just
5449 # return a suitable result depending on how the user called
5451 if [string match "" $compiler] {
5458 # If no arg, return the compiler_info string.
5459 if [string match "" $compiler] {
5460 return $compiler_info_cache($language)
5463 return [string match $compiler $compiler_info_cache($language)]
5466 # Return true if the C compiler is GCC, otherwise, return false.
5468 proc is_c_compiler_gcc {} {
5469 set compiler_info [test_compiler_info]
5470 set gcc_compiled false
5471 regexp "^gcc-(\[0-9\]+)-" "$compiler_info" matchall gcc_compiled
5472 return $gcc_compiled
5475 # Return the gcc major version, or -1.
5476 # For gcc 4.8.5, the major version is 4.8.
5477 # For gcc 7.5.0, the major version 7.
5478 # The COMPILER and LANGUAGE arguments are as for test_compiler_info.
5480 proc gcc_major_version { {compiler "gcc-*"} {language "c"} } {
5482 if { ![test_compiler_info $compiler $language] } {
5485 # Strip "gcc-*" to "gcc".
5486 regsub -- {-.*} $compiler "" compiler
5487 set res [regexp $compiler-($decimal)-($decimal)- \
5488 [test_compiler_info "" $language] \
5489 dummy_var major minor]
5496 return $major.$minor
5499 proc current_target_name { } {
5501 if [info exists target_info(target,name)] {
5502 set answer $target_info(target,name)
5509 set gdb_wrapper_initialized 0
5510 set gdb_wrapper_target ""
5511 set gdb_wrapper_file ""
5512 set gdb_wrapper_flags ""
5514 proc gdb_wrapper_init { args } {
5515 global gdb_wrapper_initialized
5516 global gdb_wrapper_file
5517 global gdb_wrapper_flags
5518 global gdb_wrapper_target
5520 if { $gdb_wrapper_initialized == 1 } { return; }
5522 if {[target_info exists needs_status_wrapper] && \
5523 [target_info needs_status_wrapper] != "0"} {
5524 set result [build_wrapper "testglue.o"]
5525 if { $result != "" } {
5526 set gdb_wrapper_file [lindex $result 0]
5527 if ![is_remote host] {
5528 set gdb_wrapper_file [file join [pwd] $gdb_wrapper_file]
5530 set gdb_wrapper_flags [lindex $result 1]
5532 warning "Status wrapper failed to build."
5535 set gdb_wrapper_file ""
5536 set gdb_wrapper_flags ""
5538 verbose "set gdb_wrapper_file = $gdb_wrapper_file"
5539 set gdb_wrapper_initialized 1
5540 set gdb_wrapper_target [current_target_name]
5543 # Determine options that we always want to pass to the compiler.
5544 proc universal_compile_options {src obj} {
5547 # Try an option for disabling colored diagnostics. Some compilers
5548 # yield colored diagnostics by default (when run from a tty) unless
5549 # such an option is specified.
5550 set opt "additional_flags=-fdiagnostics-color=never"
5551 set lines [target_compile $src $obj object [list "quiet" $opt]]
5552 if {[string match "" $lines]} {
5553 # Seems to have worked; use the option.
5554 lappend options $opt
5560 # Determine options that we always want to pass to the C compiler.
5561 gdb_caching_proc universal_compile_options_c {} {
5562 set me "universal_compile_options_c"
5564 set src [standard_temp_file ccopts.c]
5565 set obj [standard_temp_file ccopts.o]
5567 gdb_produce_source $src {
5568 int foo(void) { return 0; }
5571 set options [universal_compile_options $src $obj]
5576 verbose "$me: returning $options" 2
5580 # Determine options that we always want to pass to the compiler for
5581 # assembly source files with the extension ".s".
5582 gdb_caching_proc universal_compile_options_assembly {} {
5583 set me "universal_compile_options_assembly"
5585 set src [standard_temp_file ccopts.s]
5586 set obj [standard_temp_file csymbol.o]
5588 gdb_produce_source $src {
5592 set options [universal_compile_options $src $obj]
5595 verbose "$me: returning $options" 2
5599 # Compile the code in $code to a file based on $name, using the flags
5600 # $compile_flag as well as debug, nowarning and quiet (unless otherwise
5601 # specified in default_compile_flags).
5602 # Return 1 if code can be compiled
5603 # Leave the file name of the resulting object in the upvar object.
5605 proc gdb_simple_compile {name code {type object} {compile_flags {}} {object obj} {default_compile_flags {}}} {
5608 switch -regexp -- $type {
5623 foreach flag $compile_flags {
5624 if { "$flag" == "go" } {
5628 if { "$flag" eq "hip" } {
5632 if { "$flag" eq "d" } {
5637 set src [standard_temp_file $name.$ext]
5638 set obj [standard_temp_file $name.$postfix]
5639 if { $default_compile_flags == "" } {
5640 set compile_flags [concat $compile_flags {debug nowarnings quiet}]
5642 set compile_flags [concat $compile_flags $default_compile_flags]
5645 gdb_produce_source $src $code
5647 verbose "$name: compiling testfile $src" 2
5648 set lines [gdb_compile $src $obj $type $compile_flags]
5652 if {![string match "" $lines]} {
5653 verbose "$name: compilation failed, returning 0" 2
5659 # Compile the code in $code to a file based on $name, using the flags
5660 # $compile_flag as well as debug, nowarning and quiet (unless otherwise
5661 # specified in default_compile_flags).
5662 # Return 1 if code can be compiled
5663 # Delete all created files and objects.
5665 proc gdb_can_simple_compile {name code {type object} {compile_flags ""} {default_compile_flags ""}} {
5666 set ret [gdb_simple_compile $name $code $type $compile_flags temp_obj \
5667 $default_compile_flags]
5668 file delete $temp_obj
5672 # As gdb_can_simple_compile, but defaults to using nodebug instead of debug.
5673 proc gdb_can_simple_compile_nodebug {name code {type object} {compile_flags ""}
5674 {default_compile_flags "nodebug nowarning quiet"}} {
5675 return [gdb_can_simple_compile $name $code $type $compile_flags \
5676 $default_compile_flags]
5679 # Some targets need to always link a special object in. Save its path here.
5680 global gdb_saved_set_unbuffered_mode_obj
5681 set gdb_saved_set_unbuffered_mode_obj ""
5683 # Escape STR sufficiently for use on host commandline.
5685 proc escape_for_host { str } {
5686 if { [is_remote host] } {
5696 return [string map $map $str]
5699 # Add double quotes around ARGS, sufficiently escaped for use on host
5702 proc quote_for_host { args } {
5703 set str [join $args]
5704 if { [is_remote host] } {
5705 set str [join [list {\"} $str {\"}] ""]
5707 set str [join [list {"} $str {"}] ""]
5712 # Compile source files specified by SOURCE into a binary of type TYPE at path
5713 # DEST. gdb_compile is implemented using DejaGnu's target_compile, so the type
5714 # parameter and most options are passed directly to it.
5716 # The type can be one of the following:
5718 # - object: Compile into an object file.
5719 # - executable: Compile and link into an executable.
5720 # - preprocess: Preprocess the source files.
5721 # - assembly: Generate assembly listing.
5723 # The following options are understood and processed by gdb_compile:
5725 # - shlib=so_path: Add SO_PATH to the sources, and enable some target-specific
5726 # quirks to be able to use shared libraries.
5727 # - shlib_load: Link with appropriate libraries to allow the test to
5728 # dynamically load libraries at runtime. For example, on Linux, this adds
5729 # -ldl so that the test can use dlopen.
5730 # - nowarnings: Inhibit all compiler warnings.
5731 # - pie: Force creation of PIE executables.
5732 # - nopie: Prevent creation of PIE executables.
5733 # - macros: Add the required compiler flag to include macro information in
5735 # - text_segment=addr: Tell the linker to place the text segment at ADDR.
5736 # - build-id: Ensure the final binary includes a build-id.
5737 # - no-build-id: Ensure the final binary does not include a build-id.
5738 # - column-info/no-column-info: Enable/Disable generation of column table
5740 # - dwarf5: Force compilation with dwarf-5 debug information.
5742 # And here are some of the not too obscure options understood by DejaGnu that
5743 # influence the compilation:
5745 # - additional_flags=flag: Add FLAG to the compiler flags.
5746 # - libs=library: Add LIBRARY to the libraries passed to the linker. The
5747 # argument can be a file, in which case it's added to the sources, or a
5749 # - ldflags=flag: Add FLAG to the linker flags.
5750 # - incdir=path: Add PATH to the searched include directories.
5751 # - libdir=path: Add PATH to the linker searched directories.
5752 # - ada, c++, f90, go, rust: Compile the file as Ada, C++,
5753 # Fortran 90, Go or Rust.
5754 # - debug: Build with debug information.
5755 # - optimize: Build with optimization.
5757 proc gdb_compile {source dest type options} {
5758 global GDB_TESTCASE_OPTIONS
5759 global gdb_wrapper_file
5760 global gdb_wrapper_flags
5763 global gdb_saved_set_unbuffered_mode_obj
5765 set outdir [file dirname $dest]
5767 # If this is set, calling test_compiler_info will cause recursion.
5768 if { [lsearch -exact $options getting_compiler_info] == -1 } {
5769 set getting_compiler_info false
5771 set getting_compiler_info true
5774 # Add platform-specific options if a shared library was specified using
5775 # "shlib=librarypath" in OPTIONS.
5777 if {[lsearch -exact $options rust] != -1} {
5778 # -fdiagnostics-color is not a rustcc option.
5780 # icx/clang compilers support the -fdiagnostics-color option for
5781 # ".S" files and only it is not supported for ".s" files.
5782 if {[string match *.s $source] != 0} {
5783 set new_options [universal_compile_options_assembly]
5785 set new_options [universal_compile_options_c]
5789 # C/C++ specific settings.
5790 if {!$getting_compiler_info
5791 && [lsearch -exact $options rust] == -1
5792 && [lsearch -exact $options ada] == -1
5793 && [lsearch -exact $options f90] == -1
5794 && [lsearch -exact $options go] == -1} {
5796 # Some C/C++ testcases unconditionally pass -Wno-foo as additional
5797 # options to disable some warning. That is OK with GCC, because
5798 # by design, GCC accepts any -Wno-foo option, even if it doesn't
5799 # support -Wfoo. Clang however warns about unknown -Wno-foo by
5800 # default, unless you pass -Wno-unknown-warning-option as well.
5801 # We do that here, so that individual testcases don't have to
5803 if {[test_compiler_info "clang-*"] || [test_compiler_info "icx-*"]} {
5804 lappend new_options "additional_flags=-Wno-unknown-warning-option"
5805 } elseif {[test_compiler_info "icc-*"]} {
5806 # This is the equivalent for the icc compiler.
5807 lappend new_options "additional_flags=-diag-disable=10148"
5810 # icpx/icx give the following warning if '-g' is used without '-O'.
5812 # icpx: remark: Note that use of '-g' without any
5813 # optimization-level option will turn off most compiler
5814 # optimizations similar to use of '-O0'
5816 # The warning makes dejagnu think that compilation has failed.
5818 # Furthermore, if no -O flag is passed, icx and icc optimize
5819 # the code by default. This breaks assumptions in many GDB
5820 # tests that the code is unoptimized by default.
5822 # To fix both problems, pass the -O0 flag explicitly, if no
5823 # optimization option is given.
5824 if {[test_compiler_info "icx-*"] || [test_compiler_info "icc-*"]} {
5825 if {[lsearch $options optimize=*] == -1
5826 && [lsearch $options additional_flags=-O*] == -1} {
5827 lappend new_options "optimize=-O0"
5831 # Starting with 2021.7.0 (recognized as icc-20-21-7 by GDB) icc and
5832 # icpc are marked as deprecated and both compilers emit the remark
5833 # #10441. To let GDB still compile successfully, we disable these
5835 if {([lsearch -exact $options c++] != -1
5836 && [test_compiler_info {icc-20-21-[7-9]} c++])
5837 || [test_compiler_info {icc-20-21-[7-9]}]} {
5838 lappend new_options "additional_flags=-diag-disable=10441"
5842 # If the 'build-id' option is used, then ensure that we generate a
5843 # build-id. It is possible that the compiler is configured to do
5844 # so automatically, but at least for GCC the configure option
5845 # --enable-linker-build-id is not enabled by default.
5846 # So to be sure, enable it explicitly.
5847 if {[lsearch -exact $options build-id] > 0} {
5848 lappend new_options "ldflags=-Wl,--build-id"
5851 # If the 'no-build-id' option is used then disable the build-id.
5852 if {[lsearch -exact $options no-build-id] > 0} {
5853 lappend new_options "ldflags=-Wl,--build-id=none"
5856 # Sanity check. If both 'build-id' and 'no-build-id' are used
5857 # then what is expected from us!
5858 if {[lsearch -exact $options build-id] > 0
5859 && [lsearch -exact $options no-build-id] > 0} {
5860 error "cannot use build-id and no-build-id options"
5863 # Treating .c input files as C++ is deprecated in Clang, so
5864 # explicitly force C++ language.
5865 if { !$getting_compiler_info
5866 && [lsearch -exact $options c++] != -1
5867 && [string match *.c $source] != 0 } {
5869 # gdb_compile cannot handle this combination of options, the
5870 # result is a command like "clang -x c++ foo.c bar.so -o baz"
5871 # which tells Clang to treat bar.so as C++. The solution is
5872 # to call gdb_compile twice--once to compile, once to link--
5873 # either directly, or via build_executable_from_specs.
5874 if { [lsearch $options shlib=*] != -1 } {
5875 error "incompatible gdb_compile options"
5878 if {[test_compiler_info "clang-*"]} {
5879 lappend new_options early_flags=-x\ c++
5883 # Place (and look for) Fortran `.mod` files in the output
5884 # directory for this specific test. For Intel compilers the -J
5885 # option is not supported so instead use the -module flag.
5886 # Additionally, Intel compilers need the -debug-parameters flag set to
5887 # emit debug info for all parameters in modules.
5889 # ifx gives the following warning if '-g' is used without '-O'.
5891 # ifx: remark #10440: Note that use of a debug option
5892 # without any optimization-level option will turnoff most
5893 # compiler optimizations similar to use of '-O0'
5895 # The warning makes dejagnu think that compilation has failed.
5897 # Furthermore, if no -O flag is passed, Intel compilers optimize
5898 # the code by default. This breaks assumptions in many GDB
5899 # tests that the code is unoptimized by default.
5901 # To fix both problems, pass the -O0 flag explicitly, if no
5902 # optimization option is given.
5903 if { !$getting_compiler_info && [lsearch -exact $options f90] != -1 } {
5905 set mod_path [standard_output_file ""]
5906 if { [test_compiler_info {gfortran-*} f90] } {
5907 lappend new_options "additional_flags=-J${mod_path}"
5908 } elseif { [test_compiler_info {ifort-*} f90]
5909 || [test_compiler_info {ifx-*} f90] } {
5910 lappend new_options "additional_flags=-module ${mod_path}"
5911 lappend new_options "additional_flags=-debug-parameters all"
5913 if {[lsearch $options optimize=*] == -1
5914 && [lsearch $options additional_flags=-O*] == -1} {
5915 lappend new_options "optimize=-O0"
5922 foreach opt $options {
5923 if {[regexp {^shlib=(.*)} $opt dummy_var shlib_name]
5924 && $type == "executable"} {
5925 if [test_compiler_info "xlc-*"] {
5926 # IBM xlc compiler doesn't accept shared library named other
5927 # than .so: use "-Wl," to bypass this
5928 lappend source "-Wl,$shlib_name"
5929 } elseif { ([istarget "*-*-mingw*"]
5930 || [istarget *-*-cygwin*]
5931 || [istarget *-*-pe*])} {
5932 lappend source "${shlib_name}.a"
5934 lappend source $shlib_name
5936 if { $shlib_found == 0 } {
5938 if { ([istarget "*-*-mingw*"]
5939 || [istarget *-*-cygwin*]) } {
5940 lappend new_options "ldflags=-Wl,--enable-auto-import"
5942 if { [test_compiler_info "gcc-*"] || [test_compiler_info "clang-*"] } {
5943 # Undo debian's change in the default.
5944 # Put it at the front to not override any user-provided
5945 # value, and to make sure it appears in front of all the
5947 lappend new_options "early_flags=-Wl,--no-as-needed"
5950 } elseif { $opt == "shlib_load" && $type == "executable" } {
5952 } elseif { $opt == "getting_compiler_info" } {
5953 # Ignore this setting here as it has been handled earlier in this
5954 # procedure. Do not append it to new_options as this will cause
5956 } elseif {[regexp "^text_segment=(.*)" $opt dummy_var addr]} {
5957 if { [linker_supports_Ttext_segment_flag] } {
5959 lappend new_options "ldflags=-Wl,-Ttext-segment=$addr"
5960 } elseif { [linker_supports_image_base_flag] } {
5962 lappend new_options "ldflags=-Wl,--image-base=$addr"
5963 } elseif { [linker_supports_Ttext_flag] } {
5964 # For old GNU gold versions.
5965 lappend new_options "ldflags=-Wl,-Ttext=$addr"
5967 error "Don't know how to handle text_segment option."
5969 } elseif { $opt == "column-info" } {
5970 # If GCC or clang does not support column-info, compilation
5971 # will fail and the usupported column-info option will be
5973 if {[test_compiler_info {gcc-*}]} {
5974 lappend new_options "additional_flags=-gcolumn-info"
5976 } elseif {[test_compiler_info {clang-*}]} {
5977 lappend new_options "additional_flags=-gcolumn-info"
5980 error "Option gcolumn-info not supported by compiler."
5983 } elseif { $opt == "no-column-info" } {
5984 if {[test_compiler_info {gcc-*}]} {
5985 if {[test_compiler_info {gcc-[1-6]-*}]} {
5986 # In this case, don't add the compile line option and
5987 # the result will be the same as using no-column-info
5988 # on a version that supports the option.
5989 warning "gdb_compile option no-column-info not supported, ignoring."
5991 lappend new_options "additional_flags=-gno-column-info"
5994 } elseif {[test_compiler_info {clang-*}]} {
5995 lappend new_options "additional_flags=-gno-column-info"
5998 error "Option gno-column-info not supported by compiler."
6001 } elseif { $opt == "dwarf5" } {
6002 if {[test_compiler_info {gcc-*}] \
6003 || [test_compiler_info {clang-*}]} {
6004 lappend new_options "additional_flags=-gdwarf-5"
6006 error "No idea how to force DWARF-5 in this compiler"
6009 lappend new_options $opt
6013 # Ensure stack protector is disabled for GCC, as this causes problems with
6014 # DWARF line numbering.
6015 # See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88432
6016 # This option defaults to on for Debian/Ubuntu.
6017 if { !$getting_compiler_info
6018 && [test_compiler_info {gcc-*-*}]
6019 && !([test_compiler_info {gcc-[0-3]-*}]
6020 || [test_compiler_info {gcc-4-0-*}])
6021 && [lsearch -exact $options rust] == -1} {
6022 # Put it at the front to not override any user-provided value.
6023 lappend new_options "early_flags=-fno-stack-protector"
6026 # hipcc defaults to -O2, so add -O0 to early flags for the hip language.
6027 # If "optimize" is also requested, another -O flag (e.g. -O2) will be added
6028 # to the flags, overriding this -O0.
6029 if {[lsearch -exact $options hip] != -1} {
6030 lappend new_options "early_flags=-O0"
6033 # Because we link with libraries using their basename, we may need
6034 # (depending on the platform) to set a special rpath value, to allow
6035 # the executable to find the libraries it depends on.
6036 if { $shlib_load || $shlib_found } {
6037 if { ([istarget "*-*-mingw*"]
6038 || [istarget *-*-cygwin*]
6039 || [istarget *-*-pe*]) } {
6040 # Do not need anything.
6041 } elseif { [istarget *-*-freebsd*] || [istarget *-*-openbsd*] } {
6042 lappend new_options "ldflags=-Wl,-rpath,${outdir}"
6044 if { $shlib_load } {
6045 lappend new_options "libs=-ldl"
6047 lappend new_options [escape_for_host {ldflags=-Wl,-rpath,$ORIGIN}]
6050 set options $new_options
6052 if [info exists GDB_TESTCASE_OPTIONS] {
6053 lappend options "additional_flags=$GDB_TESTCASE_OPTIONS"
6055 verbose "options are $options"
6056 verbose "source is $source $dest $type $options"
6060 if {[target_info exists needs_status_wrapper] && \
6061 [target_info needs_status_wrapper] != "0" && \
6062 $gdb_wrapper_file != "" } {
6063 lappend options "libs=${gdb_wrapper_file}"
6064 lappend options "ldflags=${gdb_wrapper_flags}"
6067 # Replace the "nowarnings" option with the appropriate additional_flags
6068 # to disable compiler warnings.
6069 set nowarnings [lsearch -exact $options nowarnings]
6070 if {$nowarnings != -1} {
6071 if [target_info exists gdb,nowarnings_flag] {
6072 set flag "additional_flags=[target_info gdb,nowarnings_flag]"
6074 set flag "additional_flags=-w"
6076 set options [lreplace $options $nowarnings $nowarnings $flag]
6079 # Replace the "pie" option with the appropriate compiler and linker flags
6080 # to enable PIE executables.
6081 set pie [lsearch -exact $options pie]
6083 if [target_info exists gdb,pie_flag] {
6084 set flag "additional_flags=[target_info gdb,pie_flag]"
6086 # For safety, use fPIE rather than fpie. On AArch64, m68k, PowerPC
6087 # and SPARC, fpie can cause compile errors due to the GOT exceeding
6088 # a maximum size. On other architectures the two flags are
6089 # identical (see the GCC manual). Note Debian9 and Ubuntu16.10
6090 # onwards default GCC to using fPIE. If you do require fpie, then
6091 # it can be set using the pie_flag.
6092 set flag "additional_flags=-fPIE"
6094 set options [lreplace $options $pie $pie $flag]
6096 if [target_info exists gdb,pie_ldflag] {
6097 set flag "ldflags=[target_info gdb,pie_ldflag]"
6099 set flag "ldflags=-pie"
6101 lappend options "$flag"
6104 # Replace the "nopie" option with the appropriate compiler and linker
6105 # flags to disable PIE executables.
6106 set nopie [lsearch -exact $options nopie]
6108 if [target_info exists gdb,nopie_flag] {
6109 set flag "additional_flags=[target_info gdb,nopie_flag]"
6111 set flag "additional_flags=-fno-pie"
6113 set options [lreplace $options $nopie $nopie $flag]
6115 if [target_info exists gdb,nopie_ldflag] {
6116 set flag "ldflags=[target_info gdb,nopie_ldflag]"
6118 set flag "ldflags=-no-pie"
6120 lappend options "$flag"
6123 set macros [lsearch -exact $options macros]
6124 if {$macros != -1} {
6125 if { [test_compiler_info "clang-*"] } {
6126 set flag "additional_flags=-fdebug-macro"
6128 set flag "additional_flags=-g3"
6131 set options [lreplace $options $macros $macros $flag]
6134 if { $type == "executable" } {
6135 if { ([istarget "*-*-mingw*"]
6136 || [istarget "*-*-*djgpp"]
6137 || [istarget "*-*-cygwin*"])} {
6138 # Force output to unbuffered mode, by linking in an object file
6139 # with a global contructor that calls setvbuf.
6141 # Compile the special object separately for two reasons:
6142 # 1) Insulate it from $options.
6143 # 2) Avoid compiling it for every gdb_compile invocation,
6144 # which is time consuming, especially if we're remote
6147 # Note the special care for GDB_PARALLEL. In that
6148 # scenario, multiple expect instances will potentially try
6149 # to compile the object file at the same time. The result
6150 # should be identical for every one of them, so we just
6151 # need to make sure that the final objfile is written to
6154 if { $gdb_saved_set_unbuffered_mode_obj == "" } {
6155 verbose "compiling gdb_saved_set_unbuffered_obj"
6156 set unbuf_src ${srcdir}/lib/set_unbuffered_mode.c
6157 # This gives us a per-expect-instance unique filename,
6158 # which is important for GDB_PARALLEL. See comments
6160 set unbuf_obj [standard_temp_file set_unbuffered_mode.o]
6162 set result [gdb_compile "${unbuf_src}" "${unbuf_obj}" object {nowarnings}]
6163 if { $result != "" } {
6166 if {[is_remote host]} {
6167 set gdb_saved_set_unbuffered_mode_obj set_unbuffered_mode_saved.o
6169 set gdb_saved_set_unbuffered_mode_obj ${objdir}/set_unbuffered_mode_saved.o
6171 # Link a copy of the output object, because the
6172 # original may be automatically deleted.
6173 if {[info exists ::GDB_PARALLEL]} {
6174 # Make sure to write the .o file atomically.
6175 # (Note GDB_PARALLEL mode does not support remote
6177 file rename -force -- $unbuf_obj $gdb_saved_set_unbuffered_mode_obj
6179 remote_download host $unbuf_obj $gdb_saved_set_unbuffered_mode_obj
6182 verbose "gdb_saved_set_unbuffered_obj already compiled"
6185 # Rely on the internal knowledge that the global ctors are ran in
6186 # reverse link order. In that case, we can use ldflags to
6187 # avoid copying the object file to the host multiple
6189 # This object can only be added if standard libraries are
6190 # used. Thus, we need to disable it if -nostdlib option is used
6191 if {[lsearch -regexp $options "-nostdlib"] < 0 } {
6192 lappend options "ldflags=$gdb_saved_set_unbuffered_mode_obj"
6197 cond_wrap [expr $pie != -1 || $nopie != -1] \
6198 with_PIE_multilib_flags_filtered {
6199 set result [target_compile $source $dest $type $options]
6202 # Prune uninteresting compiler (and linker) output.
6203 regsub "Creating library file: \[^\r\n\]*\[\r\n\]+" $result "" result
6205 # Starting with 2021.7.0 icc and icpc are marked as deprecated and both
6206 # compilers emit a remark #10441. To let GDB still compile successfully,
6207 # we disable these warnings. When $getting_compiler_info is true however,
6208 # we do not yet know the compiler (nor its version) and instead prune these
6209 # lines from the compiler output to let the get_compiler_info pass.
6210 if {$getting_compiler_info} {
6212 "(icc|icpc): remark #10441: The Intel\\(R\\) C\\+\\+ Compiler Classic \\(ICC\\) is deprecated\[^\r\n\]*" \
6216 regsub "\[\r\n\]*$" "$result" "" result
6217 regsub "^\[\r\n\]*" "$result" "" result
6219 if { $type == "executable" && $result == "" \
6220 && ($nopie != -1 || $pie != -1) } {
6221 set is_pie [exec_is_pie "$dest"]
6222 if { $nopie != -1 && $is_pie == 1 } {
6223 set result "nopie failed to prevent PIE executable"
6224 } elseif { $pie != -1 && $is_pie == 0 } {
6225 set result "pie failed to generate PIE executable"
6229 if {[lsearch $options quiet] < 0} {
6230 if { $result != "" } {
6231 clone_output "gdb compile failed, $result"
6238 # This is just like gdb_compile, above, except that it tries compiling
6239 # against several different thread libraries, to see which one this
6241 proc gdb_compile_pthreads {source dest type options} {
6242 if {$type != "executable"} {
6243 return [gdb_compile $source $dest $type $options]
6246 set why_msg "unrecognized error"
6247 foreach lib {-lpthreads -lpthread -lthread ""} {
6248 # This kind of wipes out whatever libs the caller may have
6249 # set. Or maybe theirs will override ours. How infelicitous.
6250 set options_with_lib [concat $options [list libs=$lib quiet]]
6251 set ccout [gdb_compile $source $dest $type $options_with_lib]
6252 switch -regexp -- $ccout {
6253 ".*no posix threads support.*" {
6254 set why_msg "missing threads include file"
6257 ".*cannot open -lpthread.*" {
6258 set why_msg "missing runtime threads library"
6260 ".*Can't find library for -lpthread.*" {
6261 set why_msg "missing runtime threads library"
6264 pass "successfully compiled posix threads test case"
6270 if {!$built_binfile} {
6271 unsupported "couldn't compile [file tail $source]: ${why_msg}"
6276 # Build a shared library from SOURCES.
6278 proc gdb_compile_shlib_1 {sources dest options} {
6279 set obj_options $options
6282 if { [lsearch -exact $options "ada"] >= 0 } {
6286 if { [lsearch -exact $options "c++"] >= 0 } {
6287 set info_options "c++"
6288 } elseif { [lsearch -exact $options "f90"] >= 0 } {
6289 set info_options "f90"
6291 set info_options "c"
6294 switch -glob [test_compiler_info "" ${info_options}] {
6296 lappend obj_options "additional_flags=-qpic"
6299 if { [istarget "*-*-cygwin*"]
6300 || [istarget "*-*-mingw*"] } {
6301 lappend obj_options "additional_flags=-fPIC"
6303 lappend obj_options "additional_flags=-fpic"
6307 if { [istarget "powerpc*-*-aix*"]
6308 || [istarget "rs6000*-*-aix*"]
6309 || [istarget "*-*-cygwin*"]
6310 || [istarget "*-*-mingw*"]
6311 || [istarget "*-*-pe*"] } {
6312 lappend obj_options "additional_flags=-fPIC"
6314 lappend obj_options "additional_flags=-fpic"
6318 lappend obj_options "additional_flags=-fpic"
6321 # don't know what the compiler is...
6322 lappend obj_options "additional_flags=-fPIC"
6326 set outdir [file dirname $dest]
6328 foreach source $sources {
6329 if {[file extension $source] == ".o"} {
6330 # Already a .o file.
6331 lappend objects $source
6335 set sourcebase [file tail $source]
6338 # Gnatmake doesn't like object name foo.adb.o, use foo.o.
6339 set sourcebase [file rootname $sourcebase]
6341 set object ${outdir}/${sourcebase}.o
6344 # Use gdb_compile_ada_1 instead of gdb_compile_ada to avoid the
6346 if {[gdb_compile_ada_1 $source $object object \
6347 $obj_options] != ""} {
6351 if {[gdb_compile $source $object object \
6352 $obj_options] != ""} {
6357 lappend objects $object
6360 set link_options $options
6362 # If we try to use gnatmake for the link, it will interpret the
6363 # object file as an .adb file. Remove ada from the options to
6365 set idx [lsearch $link_options "ada"]
6366 set link_options [lreplace $link_options $idx $idx]
6368 if [test_compiler_info "xlc-*"] {
6369 lappend link_options "additional_flags=-qmkshrobj"
6371 lappend link_options "additional_flags=-shared"
6373 if { ([istarget "*-*-mingw*"]
6374 || [istarget *-*-cygwin*]
6375 || [istarget *-*-pe*]) } {
6376 if { [is_remote host] } {
6377 set name [file tail ${dest}]
6381 lappend link_options "ldflags=-Wl,--out-implib,${name}.a"
6383 # Set the soname of the library. This causes the linker on ELF
6384 # systems to create the DT_NEEDED entry in the executable referring
6385 # to the soname of the library, and not its absolute path. This
6386 # (using the absolute path) would be problem when testing on a
6389 # In conjunction with setting the soname, we add the special
6390 # rpath=$ORIGIN value when building the executable, so that it's
6391 # able to find the library in its own directory.
6392 set destbase [file tail $dest]
6393 lappend link_options "ldflags=-Wl,-soname,$destbase"
6396 if {[gdb_compile "${objects}" "${dest}" executable $link_options] != ""} {
6399 if { [is_remote host]
6400 && ([istarget "*-*-mingw*"]
6401 || [istarget *-*-cygwin*]
6402 || [istarget *-*-pe*]) } {
6403 set dest_tail_name [file tail ${dest}]
6404 remote_upload host $dest_tail_name.a ${dest}.a
6405 remote_file host delete $dest_tail_name.a
6411 # Ignore FLAGS in target board multilib_flags while executing BODY.
6413 proc with_multilib_flags_filtered { flags body } {
6416 # Ignore flags in multilib_flags.
6417 set board [target_info name]
6418 set multilib_flags_orig [board_info $board multilib_flags]
6419 set multilib_flags ""
6420 foreach op $multilib_flags_orig {
6421 if { [lsearch -exact $flags $op] == -1 } {
6422 append multilib_flags " $op"
6426 save_target_board_info { multilib_flags } {
6427 unset_board_info multilib_flags
6428 set_board_info multilib_flags "$multilib_flags"
6429 set result [uplevel 1 $body]
6435 # Ignore PIE-related flags in target board multilib_flags while executing BODY.
6437 proc with_PIE_multilib_flags_filtered { body } {
6438 set pie_flags [list "-pie" "-no-pie" "-fPIE" "-fno-PIE"]
6439 return [uplevel 1 [list with_multilib_flags_filtered $pie_flags $body]]
6442 # Build a shared library from SOURCES. Ignore target boards PIE-related
6445 proc gdb_compile_shlib {sources dest options} {
6446 with_PIE_multilib_flags_filtered {
6447 set result [gdb_compile_shlib_1 $sources $dest $options]
6453 # This is just like gdb_compile_shlib, above, except that it tries compiling
6454 # against several different thread libraries, to see which one this
6456 proc gdb_compile_shlib_pthreads {sources dest options} {
6458 set why_msg "unrecognized error"
6459 foreach lib {-lpthreads -lpthread -lthread ""} {
6460 # This kind of wipes out whatever libs the caller may have
6461 # set. Or maybe theirs will override ours. How infelicitous.
6462 set options_with_lib [concat $options [list libs=$lib quiet]]
6463 set ccout [gdb_compile_shlib $sources $dest $options_with_lib]
6464 switch -regexp -- $ccout {
6465 ".*no posix threads support.*" {
6466 set why_msg "missing threads include file"
6469 ".*cannot open -lpthread.*" {
6470 set why_msg "missing runtime threads library"
6472 ".*Can't find library for -lpthread.*" {
6473 set why_msg "missing runtime threads library"
6476 pass "successfully compiled posix threads shlib test case"
6482 if {!$built_binfile} {
6483 unsupported "couldn't compile $sources: ${why_msg}"
6488 # This is just like gdb_compile_pthreads, above, except that we always add the
6489 # objc library for compiling Objective-C programs
6490 proc gdb_compile_objc {source dest type options} {
6492 set why_msg "unrecognized error"
6493 foreach lib {-lobjc -lpthreads -lpthread -lthread solaris} {
6494 # This kind of wipes out whatever libs the caller may have
6495 # set. Or maybe theirs will override ours. How infelicitous.
6496 if { $lib == "solaris" } {
6497 set lib "-lpthread -lposix4"
6499 if { $lib != "-lobjc" } {
6500 set lib "-lobjc $lib"
6502 set options_with_lib [concat $options [list libs=$lib quiet]]
6503 set ccout [gdb_compile $source $dest $type $options_with_lib]
6504 switch -regexp -- $ccout {
6505 ".*no posix threads support.*" {
6506 set why_msg "missing threads include file"
6509 ".*cannot open -lpthread.*" {
6510 set why_msg "missing runtime threads library"
6512 ".*Can't find library for -lpthread.*" {
6513 set why_msg "missing runtime threads library"
6516 pass "successfully compiled objc with posix threads test case"
6522 if {!$built_binfile} {
6523 unsupported "couldn't compile [file tail $source]: ${why_msg}"
6528 # Build an OpenMP program from SOURCE. See prefatory comment for
6529 # gdb_compile, above, for discussion of the parameters to this proc.
6531 proc gdb_compile_openmp {source dest type options} {
6532 lappend options "additional_flags=-fopenmp"
6533 return [gdb_compile $source $dest $type $options]
6536 # Send a command to GDB.
6537 # For options for TYPE see gdb_stdin_log_write
6539 proc send_gdb { string {type standard}} {
6540 gdb_stdin_log_write $string $type
6541 return [remote_send host "$string"]
6544 # Send STRING to the inferior's terminal.
6546 proc send_inferior { string } {
6547 global inferior_spawn_id
6549 if {[catch "send -i $inferior_spawn_id -- \$string" errorInfo]} {
6559 proc gdb_expect { args } {
6560 if { [llength $args] == 2 && [lindex $args 0] != "-re" } {
6561 set atimeout [lindex $args 0]
6562 set expcode [list [lindex $args 1]]
6567 # A timeout argument takes precedence, otherwise of all the timeouts
6568 # select the largest.
6569 if [info exists atimeout] {
6572 set tmt [get_largest_timeout]
6576 {uplevel remote_expect host $tmt $expcode} string]
6579 global errorInfo errorCode
6581 return -code error -errorinfo $errorInfo -errorcode $errorCode $string
6583 return -code $code $string
6587 # gdb_expect_list TEST SENTINEL LIST -- expect a sequence of outputs
6589 # Check for long sequence of output by parts.
6590 # TEST: is the test message to be printed with the test success/fail.
6591 # SENTINEL: Is the terminal pattern indicating that output has finished.
6592 # LIST: is the sequence of outputs to match.
6593 # If the sentinel is recognized early, it is considered an error.
6596 # 1 if the test failed,
6597 # 0 if the test passes,
6598 # -1 if there was an internal error.
6600 proc gdb_expect_list {test sentinel list} {
6605 while { ${index} < [llength ${list}] } {
6606 set pattern [lindex ${list} ${index}]
6607 set index [expr ${index} + 1]
6608 verbose -log "gdb_expect_list pattern: /$pattern/" 2
6609 if { ${index} == [llength ${list}] } {
6612 -re "${pattern}${sentinel}" {
6613 # pass "${test}, pattern ${index} + sentinel"
6616 fail "${test} (pattern ${index} + sentinel)"
6619 -re ".*A problem internal to GDB has been detected" {
6620 fail "${test} (GDB internal error)"
6622 gdb_internal_error_resync
6625 fail "${test} (pattern ${index} + sentinel) (timeout)"
6630 # unresolved "${test}, pattern ${index} + sentinel"
6636 # pass "${test}, pattern ${index}"
6639 fail "${test} (pattern ${index})"
6642 -re ".*A problem internal to GDB has been detected" {
6643 fail "${test} (GDB internal error)"
6645 gdb_internal_error_resync
6648 fail "${test} (pattern ${index}) (timeout)"
6653 # unresolved "${test}, pattern ${index}"
6665 # Spawn the gdb process.
6667 # This doesn't expect any output or do any other initialization,
6668 # leaving those to the caller.
6670 # Overridable function -- you can override this function in your
6673 proc gdb_spawn { } {
6677 # Spawn GDB with CMDLINE_FLAGS appended to the GDBFLAGS global.
6679 proc gdb_spawn_with_cmdline_opts { cmdline_flags } {
6682 save_vars { GDBFLAGS } {
6683 if {$GDBFLAGS != ""} {
6686 append GDBFLAGS $cmdline_flags
6694 # Start gdb running, wait for prompt, and disable the pagers.
6696 # Overridable function -- you can override this function in your
6699 proc gdb_start { } {
6704 catch default_gdb_exit
6707 # Return true if we can spawn a program on the target and attach to
6710 gdb_caching_proc can_spawn_for_attach {} {
6711 # We use exp_pid to get the inferior's pid, assuming that gives
6712 # back the pid of the program. On remote boards, that would give
6713 # us instead the PID of e.g., the ssh client, etc.
6714 if {[is_remote target]} {
6715 verbose -log "can't spawn for attach (target is remote)"
6719 # The "attach" command doesn't make sense when the target is
6720 # stub-like, where GDB finds the program already started on
6721 # initial connection.
6722 if {[target_info exists use_gdb_stub]} {
6723 verbose -log "can't spawn for attach (target is stub)"
6730 set me "can_spawn_for_attach"
6741 if {![gdb_simple_compile $me $src executable]} {
6745 set test_spawn_id [spawn_wait_for_attach_1 $obj]
6746 remote_file build delete $obj
6748 # In case GDB is already running.
6753 set test_pid [spawn_id_get_pid $test_spawn_id]
6754 set attaching_re "Attaching to process $test_pid"
6755 gdb_test_multiple "attach $test_pid" "can spawn for attach" {
6756 -re -wrap "$attaching_re\r\n.*ptrace: Operation not permitted\\." {
6761 # Don't know, keep assuming yes.
6767 kill_wait_spawned_process $test_spawn_id
6772 # Centralize the failure checking of "attach" command.
6773 # Return 0 if attach failed, otherwise return 1.
6775 proc gdb_attach { testpid args } {
6780 if { [llength $args] != 0 } {
6781 error "Unexpected arguments: $args"
6784 gdb_test_multiple "attach $testpid" "attach" {
6785 -re -wrap "Attaching to.*ptrace: Operation not permitted\\." {
6786 unsupported "$gdb_test_name (Operation not permitted)"
6789 -re -wrap "$pattern" {
6798 # Start gdb with "--pid $TESTPID" on the command line and wait for the prompt.
6799 # Return 1 if GDB managed to start and attach to the process, 0 otherwise.
6801 proc_with_prefix gdb_spawn_attach_cmdline { testpid } {
6802 if ![can_spawn_for_attach] {
6803 # The caller should have checked can_spawn_for_attach itself
6804 # before getting here.
6805 error "can't spawn for attach with this target/board"
6808 set test "start gdb with --pid"
6809 set res [gdb_spawn_with_cmdline_opts "-quiet --pid=$testpid"]
6815 gdb_test_multiple "" "$test" {
6816 -re -wrap "ptrace: Operation not permitted\\." {
6817 unsupported "$gdb_test_name (operation not permitted)"
6820 -re -wrap "ptrace: No such process\\." {
6821 fail "$gdb_test_name (no such process)"
6824 -re -wrap "Attaching to process $testpid\r\n.*" {
6829 # Check that we actually attached to a process, in case the
6830 # error message is not caught by the patterns above.
6831 gdb_test_multiple "info thread" "" {
6832 -re -wrap "No threads\\." {
6833 fail "$gdb_test_name (no thread)"
6844 # Kill a progress previously started with spawn_wait_for_attach, and
6845 # reap its wait status. PROC_SPAWN_ID is the spawn id associated with
6848 proc kill_wait_spawned_process { proc_spawn_id } {
6849 set pid [exp_pid -i $proc_spawn_id]
6851 verbose -log "killing ${pid}"
6852 remote_exec build "kill -9 ${pid}"
6854 verbose -log "closing ${proc_spawn_id}"
6855 catch "close -i $proc_spawn_id"
6856 verbose -log "waiting for ${proc_spawn_id}"
6858 # If somehow GDB ends up still attached to the process here, a
6859 # blocking wait hangs until gdb is killed (or until gdb / the
6860 # ptracer reaps the exit status too, but that won't happen because
6861 # something went wrong.) Passing -nowait makes expect tell Tcl to
6862 # wait for the PID in the background. That's fine because we
6863 # don't care about the exit status. */
6864 wait -nowait -i $proc_spawn_id
6865 clean_up_spawn_id target $proc_spawn_id
6868 # Returns the process id corresponding to the given spawn id.
6870 proc spawn_id_get_pid { spawn_id } {
6871 set testpid [exp_pid -i $spawn_id]
6873 if { [istarget "*-*-cygwin*"] } {
6874 # testpid is the Cygwin PID, GDB uses the Windows PID, which
6875 # might be different due to the way fork/exec works.
6876 set testpid [ exec ps -e | gawk "{ if (\$1 == $testpid) print \$4; }" ]
6882 # Helper function for spawn_wait_for_attach and can_spawn_for_attach_1. As
6883 # spawn_wait_for_attach, but doesn't check for can_spawn_for_attach.
6885 proc spawn_wait_for_attach_1 { executable_list } {
6886 set spawn_id_list {}
6888 foreach {executable} $executable_list {
6889 # Note we use Expect's spawn, not Tcl's exec, because with
6890 # spawn we control when to wait for/reap the process. That
6891 # allows killing the process by PID without being subject to
6893 lappend spawn_id_list [remote_spawn target $executable]
6898 return $spawn_id_list
6901 # Start a set of programs running and then wait for a bit, to be sure
6902 # that they can be attached to. Return a list of processes spawn IDs,
6903 # one element for each process spawned. It's a test error to call
6904 # this when [can_spawn_for_attach] is false.
6906 proc spawn_wait_for_attach { executable_list } {
6907 if ![can_spawn_for_attach] {
6908 # The caller should have checked can_spawn_for_attach itself
6909 # before getting here.
6910 error "can't spawn for attach with this target/board"
6913 return [spawn_wait_for_attach_1 $executable_list]
6917 # gdb_load_cmd -- load a file into the debugger.
6918 # ARGS - additional args to load command.
6919 # return a -1 if anything goes wrong.
6921 proc gdb_load_cmd { args } {
6924 if [target_info exists gdb_load_timeout] {
6925 set loadtimeout [target_info gdb_load_timeout]
6927 set loadtimeout 1600
6929 send_gdb "load $args\n"
6930 verbose "Timeout is now $loadtimeout seconds" 2
6931 gdb_expect $loadtimeout {
6932 -re "Loading section\[^\r\]*\r\n" {
6935 -re "Start address\[\r\]*\r\n" {
6938 -re "Transfer rate\[\r\]*\r\n" {
6941 -re "Memory access error\[^\r\]*\r\n" {
6942 perror "Failed to load program"
6945 -re "$gdb_prompt $" {
6948 -re "(.*)\r\n$gdb_prompt " {
6949 perror "Unexpected response from 'load' -- $expect_out(1,string)"
6953 perror "Timed out trying to load $args."
6960 # Invoke "gcore". CORE is the name of the core file to write. TEST
6961 # is the name of the test case. This will return 1 if the core file
6962 # was created, 0 otherwise. If this fails to make a core file because
6963 # this configuration of gdb does not support making core files, it
6964 # will call "unsupported", not "fail". However, if this fails to make
6965 # a core file for some other reason, then it will call "fail".
6967 proc gdb_gcore_cmd {core test} {
6972 set re_unsupported \
6973 "(?:Can't create a corefile|Target does not support core file generation\\.)"
6975 with_timeout_factor 3 {
6976 gdb_test_multiple "gcore $core" $test {
6977 -re -wrap "Saved corefile .*" {
6981 -re -wrap $re_unsupported {
6990 # Load core file CORE. TEST is the name of the test case.
6991 # This will record a pass/fail for loading the core file.
6993 # 1 - core file is successfully loaded
6994 # 0 - core file loaded but has a non fatal error
6995 # -1 - core file failed to load
6997 proc gdb_core_cmd { core test } {
7000 gdb_test_multiple "core $core" "$test" {
7001 -re "\\\[Thread debugging using \[^ \r\n\]* enabled\\\]\r\n" {
7004 -re " is not a core dump:.*\r\n$gdb_prompt $" {
7005 fail "$test (bad file format)"
7008 -re -wrap "[string_to_regexp $core]: No such file or directory.*" {
7009 fail "$test (file not found)"
7012 -re "Couldn't find .* registers in core file.*\r\n$gdb_prompt $" {
7013 fail "$test (incomplete note section)"
7016 -re "Core was generated by .*\r\n$gdb_prompt $" {
7020 -re ".*$gdb_prompt $" {
7025 fail "$test (timeout)"
7029 fail "unsupported output from 'core' command"
7033 # Return the filename to download to the target and load on the target
7034 # for this shared library. Normally just LIBNAME, unless shared libraries
7035 # for this target have separate link and load images.
7037 proc shlib_target_file { libname } {
7041 # Return the filename GDB will load symbols from when debugging this
7042 # shared library. Normally just LIBNAME, unless shared libraries for
7043 # this target have separate link and load images.
7045 proc shlib_symbol_file { libname } {
7049 # Return the filename to download to the target and load for this
7050 # executable. Normally just BINFILE unless it is renamed to something
7051 # else for this target.
7053 proc exec_target_file { binfile } {
7057 # Return the filename GDB will load symbols from when debugging this
7058 # executable. Normally just BINFILE unless executables for this target
7059 # have separate files for symbols.
7061 proc exec_symbol_file { binfile } {
7065 # Rename the executable file. Normally this is just BINFILE1 being renamed
7066 # to BINFILE2, but some targets require multiple binary files.
7067 proc gdb_rename_execfile { binfile1 binfile2 } {
7068 file rename -force [exec_target_file ${binfile1}] \
7069 [exec_target_file ${binfile2}]
7070 if { [exec_target_file ${binfile1}] != [exec_symbol_file ${binfile1}] } {
7071 file rename -force [exec_symbol_file ${binfile1}] \
7072 [exec_symbol_file ${binfile2}]
7076 # "Touch" the executable file to update the date. Normally this is just
7077 # BINFILE, but some targets require multiple files.
7078 proc gdb_touch_execfile { binfile } {
7079 set time [clock seconds]
7080 file mtime [exec_target_file ${binfile}] $time
7081 if { [exec_target_file ${binfile}] != [exec_symbol_file ${binfile}] } {
7082 file mtime [exec_symbol_file ${binfile}] $time
7086 # Override of dejagnu's remote_upload, which doesn't handle remotedir.
7088 rename remote_upload dejagnu_remote_upload
7089 proc remote_upload { dest srcfile args } {
7090 if { [is_remote $dest] && [board_info $dest exists remotedir] } {
7091 set remotedir [board_info $dest remotedir]
7092 if { ![string match "$remotedir*" $srcfile] } {
7093 # Use hardcoded '/' as separator, as in dejagnu's remote_download.
7094 set srcfile $remotedir/$srcfile
7098 return [dejagnu_remote_upload $dest $srcfile {*}$args]
7101 # Like remote_download but provides a gdb-specific behavior.
7103 # If the destination board is remote, the local file FROMFILE is transferred as
7104 # usual with remote_download to TOFILE on the remote board. The destination
7105 # filename is added to the CLEANFILES global, so it can be cleaned up at the
7108 # If the destination board is local, the destination path TOFILE is passed
7109 # through standard_output_file, and FROMFILE is copied there.
7111 # In both cases, if TOFILE is omitted, it defaults to the [file tail] of
7114 proc gdb_remote_download {dest fromfile {tofile {}}} {
7115 # If TOFILE is not given, default to the same filename as FROMFILE.
7116 if {[string length $tofile] == 0} {
7117 set tofile [file tail $fromfile]
7120 if {[is_remote $dest]} {
7121 # When the DEST is remote, we simply send the file to DEST.
7122 global cleanfiles_target cleanfiles_host
7124 set destname [remote_download $dest $fromfile $tofile]
7125 if { $dest == "target" } {
7126 lappend cleanfiles_target $destname
7127 } elseif { $dest == "host" } {
7128 lappend cleanfiles_host $destname
7133 # When the DEST is local, we copy the file to the test directory (where
7134 # the executable is).
7136 # Note that we pass TOFILE through standard_output_file, regardless of
7137 # whether it is absolute or relative, because we don't want the tests
7138 # to be able to write outside their standard output directory.
7140 set tofile [standard_output_file $tofile]
7142 file copy -force $fromfile $tofile
7148 # Copy shlib FILE to the target.
7150 proc gdb_download_shlib { file } {
7151 set target_file [shlib_target_file $file]
7152 if { [is_remote host] } {
7153 remote_download host $target_file
7155 return [gdb_remote_download target $target_file]
7158 # Set solib-search-path to allow gdb to locate shlib FILE.
7160 proc gdb_locate_shlib { file } {
7163 if ![info exists gdb_spawn_id] {
7164 perror "gdb_load_shlib: GDB is not running"
7167 if { [is_remote target] || [is_remote host] } {
7168 # If the target or host is remote, we need to tell gdb where to find
7174 # We could set this even when not testing remotely, but a user
7175 # generally won't set it unless necessary. In order to make the tests
7176 # more like the real-life scenarios, we don't set it for local testing.
7177 if { [is_remote host] } {
7178 set solib_search_path [board_info host remotedir]
7179 if { $solib_search_path == "" } {
7180 set solib_search_path .
7183 set solib_search_path [file dirname $file]
7186 gdb_test_no_output "set solib-search-path $solib_search_path" \
7187 "set solib-search-path for [file tail $file]"
7190 # Copy shlib FILE to the target and set solib-search-path to allow gdb to
7193 proc gdb_load_shlib { file } {
7194 set dest [gdb_download_shlib $file]
7195 gdb_locate_shlib $file
7200 # gdb_load -- load a file into the debugger. Specifying no file
7201 # defaults to the executable currently being debugged.
7202 # The return value is 0 for success, -1 for failure.
7203 # Many files in config/*.exp override this procedure.
7205 proc gdb_load { arg } {
7207 return [gdb_file_cmd $arg]
7213 # with_set -- Execute BODY and set VAR temporary to VAL for the
7216 proc with_set { var val body } {
7219 "is (\[^\r\n\]+)\\."
7220 gdb_test_multiple "show $var" "" {
7221 -re -wrap $show_re {
7222 set save $expect_out(1,string)
7226 # Handle 'set to "auto" (currently "i386")'.
7227 set save [regsub {^set to} $save ""]
7228 set save [regsub {\([^\r\n]+\)$} $save ""]
7229 set save [string trim $save]
7230 set save [regsub -all {^"|"$} $save ""]
7232 if { $save == "" } {
7233 perror "Did not manage to set $var"
7236 gdb_test_multiple "set $var $val" "" {
7239 -re -wrap " is set to \"?$val\"?\\." {
7244 set code [catch {uplevel 1 $body} result]
7246 # Restore saved setting.
7247 if { $save != "" } {
7248 gdb_test_multiple "set $var $save" "" {
7251 -re -wrap "is set to \"?$save\"?( \\(\[^)\]*\\))?\\." {
7257 global errorInfo errorCode
7258 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
7260 return -code $code $result
7265 # with_complaints -- Execute BODY and set complaints temporary to N for the
7268 proc with_complaints { n body } {
7269 return [uplevel [list with_set complaints $n $body]]
7273 # gdb_load_no_complaints -- As gdb_load, but in addition verifies that
7274 # loading caused no symbol reading complaints.
7276 proc gdb_load_no_complaints { arg } {
7277 global gdb_prompt gdb_file_cmd_msg decimal
7279 # Temporarily set complaint to a small non-zero number.
7284 # Verify that there were no complaints.
7287 "^(Reading symbols from \[^\r\n\]*" \
7288 ")+(Expanding full symbols from \[^\r\n\]*" \
7290 gdb_assert {[regexp $re $gdb_file_cmd_msg]} "No complaints"
7293 # gdb_reload -- load a file into the target. Called before "running",
7294 # either the first time or after already starting the program once,
7295 # for remote targets. Most files that override gdb_load should now
7296 # override this instead.
7298 # INFERIOR_ARGS contains the arguments to pass to the inferiors, as a
7299 # single string to get interpreted by a shell. If the target board
7300 # overriding gdb_reload is a "stub", then it should arrange things such
7301 # these arguments make their way to the inferior process.
7303 proc gdb_reload { {inferior_args {}} } {
7304 # For the benefit of existing configurations, default to gdb_load.
7305 # Specifying no file defaults to the executable currently being
7307 return [gdb_load ""]
7310 proc gdb_continue { function } {
7313 return [gdb_test "continue" ".*Breakpoint $decimal, $function .*" "continue to $function"]
7316 # Clean the directory containing the standard output files.
7318 proc clean_standard_output_dir {} {
7319 if { [info exists ::GDB_PERFTEST_MODE] && $::GDB_PERFTEST_MODE == "run" } {
7320 # Don't clean, use $GDB_PERFTEST_MODE == compile results.
7324 # Directory containing the standard output files.
7325 set standard_output_dir [file normalize [standard_output_file ""]]
7327 # Ensure that standard_output_dir is clean, or only contains
7328 # gdb.log / gdb.sum.
7329 set log_file_info [split [log_file -info]]
7330 set log_file [file normalize [lindex $log_file_info end]]
7331 if { $log_file == [file normalize [standard_output_file gdb.log]] } {
7332 # Dir already contains active gdb.log. Don't remove the dir, but
7333 # check that it's clean otherwise.
7334 set res [glob -directory $standard_output_dir -tails *]
7337 if { $f == "gdb.log" } {
7340 if { $f == "gdb.sum" } {
7346 error "standard output dir not clean"
7349 # Start with a clean dir.
7350 remote_exec build "rm -rf $standard_output_dir"
7355 # Default implementation of gdb_init.
7356 proc default_gdb_init { test_file_name } {
7357 global gdb_wrapper_initialized
7358 global gdb_wrapper_target
7359 global gdb_test_file_name
7360 global cleanfiles_target
7361 global cleanfiles_host
7364 # Reset the timeout value to the default. This way, any testcase
7365 # that changes the timeout value without resetting it cannot affect
7366 # the timeout used in subsequent testcases.
7367 global gdb_test_timeout
7369 set timeout $gdb_test_timeout
7371 if { [regexp ".*gdb\.reverse\/.*" $test_file_name]
7372 && [target_info exists gdb_reverse_timeout] } {
7373 set timeout [target_info gdb_reverse_timeout]
7376 # If GDB_INOTIFY is given, check for writes to '.'. This is a
7377 # debugging tool to help confirm that the test suite is
7378 # parallel-safe. You need "inotifywait" from the
7379 # inotify-tools package to use this.
7380 global GDB_INOTIFY inotify_pid
7381 if {[info exists GDB_INOTIFY] && ![info exists inotify_pid]} {
7382 global outdir tool inotify_log_file
7384 set exclusions {outputs temp gdb[.](log|sum) cache}
7385 set exclusion_re ([join $exclusions |])
7387 set inotify_log_file [standard_temp_file inotify.out]
7388 set inotify_pid [exec inotifywait -r -m -e move,create,delete . \
7389 --exclude $exclusion_re \
7390 |& tee -a $outdir/$tool.log $inotify_log_file &]
7392 # Wait for the watches; hopefully this is long enough.
7395 # Clear the log so that we don't emit a warning the first time
7397 set fd [open $inotify_log_file w]
7401 # Block writes to all banned variables, and invocation of all
7402 # banned procedures...
7403 global banned_variables
7404 global banned_procedures
7405 global banned_traced
7406 if (!$banned_traced) {
7407 foreach banned_var $banned_variables {
7408 global "$banned_var"
7409 trace add variable "$banned_var" write error
7411 foreach banned_proc $banned_procedures {
7412 global "$banned_proc"
7413 trace add execution "$banned_proc" enter error
7418 # We set LC_ALL, LC_CTYPE, and LANG to C so that we get the same
7419 # messages as expected.
7424 # Don't let a .inputrc file or an existing setting of INPUTRC mess
7425 # up the test results. Certain tests (style tests and TUI tests)
7426 # want to set the terminal to a non-"dumb" value, and for those we
7427 # want to disable bracketed paste mode. Versions of Readline
7428 # before 8.0 will not understand this and will issue a warning.
7429 # We tried using a $if to guard it, but Readline 8.1 had a bug in
7430 # its version-comparison code that prevented this for working.
7431 setenv INPUTRC [cached_file inputrc "set enable-bracketed-paste off"]
7433 # This disables style output, which would interfere with many
7435 setenv NO_COLOR sorry
7437 # This setting helps detect bugs in the Python code and doesn't
7438 # seem to have a significant downside for the tests.
7439 setenv PYTHONMALLOC malloc_debug
7441 # If DEBUGINFOD_URLS is set, gdb will try to download sources and
7442 # debug info for f.i. system libraries. Prevent this.
7443 if { [is_remote host] } {
7444 # See initialization of INTERNAL_GDBFLAGS.
7446 # Using "set debuginfod enabled off" in INTERNAL_GDBFLAGS interferes
7447 # with the gdb.debuginfod test-cases, so use the unsetenv method for
7449 unset -nocomplain ::env(DEBUGINFOD_URLS)
7452 # Ensure that GDBHISTFILE and GDBHISTSIZE are removed from the
7453 # environment, we don't want these modifications to the history
7455 unset -nocomplain ::env(GDBHISTFILE)
7456 unset -nocomplain ::env(GDBHISTSIZE)
7458 # Ensure that XDG_CONFIG_HOME is not set. Some tests setup a fake
7459 # home directory in order to test loading settings from gdbinit.
7460 # If XDG_CONFIG_HOME is set then GDB will load a gdbinit from
7461 # there (if one is present) rather than the home directory setup
7463 unset -nocomplain ::env(XDG_CONFIG_HOME)
7465 # Initialize GDB's pty with a fixed size, to make sure we avoid pagination
7466 # during startup. See "man expect" for details about stty_init.
7468 set stty_init "rows 25 cols 80"
7470 # Some tests (for example gdb.base/maint.exp) shell out from gdb to use
7471 # grep. Clear GREP_OPTIONS to make the behavior predictable,
7472 # especially having color output turned on can cause tests to fail.
7473 setenv GREP_OPTIONS ""
7475 # Clear $gdbserver_reconnect_p.
7476 global gdbserver_reconnect_p
7477 set gdbserver_reconnect_p 1
7478 unset gdbserver_reconnect_p
7480 # Clear $last_loaded_file
7481 global last_loaded_file
7482 unset -nocomplain last_loaded_file
7484 # Reset GDB number of instances
7485 global gdb_instances
7488 set cleanfiles_target {}
7489 set cleanfiles_host {}
7491 set gdb_test_file_name [file rootname [file tail $test_file_name]]
7493 clean_standard_output_dir
7495 # Make sure that the wrapper is rebuilt
7496 # with the appropriate multilib option.
7497 if { $gdb_wrapper_target != [current_target_name] } {
7498 set gdb_wrapper_initialized 0
7501 # Unlike most tests, we have a small number of tests that generate
7502 # a very large amount of output. We therefore increase the expect
7503 # buffer size to be able to contain the entire test output. This
7504 # is especially needed by gdb.base/info-macros.exp.
7506 # Also set this value for the currently running GDB.
7507 match_max [match_max -d]
7509 # We want to add the name of the TCL testcase to the PASS/FAIL messages.
7510 set pf_prefix "[file tail [file dirname $test_file_name]]/[file tail $test_file_name]:"
7513 if [target_info exists gdb_prompt] {
7514 set gdb_prompt [target_info gdb_prompt]
7516 set gdb_prompt "\\(gdb\\)"
7519 if [info exists use_gdb_stub] {
7523 gdb_setup_known_globals
7525 if { [info procs ::gdb_tcl_unknown] != "" } {
7526 # Dejagnu overrides proc unknown. The dejagnu version may trigger in a
7527 # test-case but abort the entire test run. To fix this, we install a
7528 # local version here, which reverts dejagnu's override, and restore
7529 # dejagnu's version in gdb_finish.
7530 rename ::unknown ::dejagnu_unknown
7531 proc unknown { args } {
7532 # Use tcl's unknown.
7533 set cmd [lindex $args 0]
7534 unresolved "testcase aborted due to invalid command name: $cmd"
7535 return [uplevel 1 ::gdb_tcl_unknown $args]
7539 # Dejagnu version 1.6.3 and later produce an unresolved at the end of a
7540 # testcase if an error triggered, resetting errcnt and warncnt to 0, in
7541 # order to avoid errors in one test-case influencing the following
7542 # test-case. Do this manually here, to support older versions.
7549 # Return a path using GDB_PARALLEL.
7550 # ARGS is a list of path elements to append to "$objdir/$GDB_PARALLEL".
7551 # GDB_PARALLEL must be defined, the caller must check.
7553 # The default value for GDB_PARALLEL is, canonically, ".".
7554 # The catch is that tests don't expect an additional "./" in file paths so
7555 # omit any directory for the default case.
7556 # GDB_PARALLEL is written as "yes" for the default case in Makefile.in to mark
7557 # its special handling.
7559 proc make_gdb_parallel_path { args } {
7560 global GDB_PARALLEL objdir
7561 set joiner [list "file" "join" $objdir]
7562 if { [info exists GDB_PARALLEL] && $GDB_PARALLEL != "yes" } {
7563 lappend joiner $GDB_PARALLEL
7565 set joiner [concat $joiner $args]
7566 return [eval $joiner]
7569 # Turn BASENAME into a full file name in the standard output
7570 # directory. It is ok if BASENAME is the empty string; in this case
7571 # the directory is returned.
7573 proc standard_output_file {basename} {
7574 global objdir subdir gdb_test_file_name
7576 set dir [make_gdb_parallel_path outputs $subdir $gdb_test_file_name]
7578 # If running on MinGW, replace /c/foo with c:/foo
7579 if { [ishost *-*-mingw*] } {
7580 set dir [exec sh -c "cd ${dir} && pwd -W"]
7582 return [file join $dir $basename]
7585 # Turn BASENAME into a file name on host.
7587 proc host_standard_output_file { basename } {
7588 if { [is_remote host] } {
7589 set remotedir [board_info host remotedir]
7590 if { $remotedir == "" } {
7591 if { $basename == "" } {
7596 return [join [list $remotedir $basename] "/"]
7599 return [standard_output_file $basename]
7603 # Turn BASENAME into a full file name in the standard output directory. If
7604 # GDB has been launched more than once then append the count, starting with
7607 proc standard_output_file_with_gdb_instance {basename} {
7608 global gdb_instances
7609 set count $gdb_instances
7612 return [standard_output_file $basename]
7614 return [standard_output_file ${basename}.${count}]
7617 # Return the name of a file in our standard temporary directory.
7619 proc standard_temp_file {basename} {
7620 # Since a particular runtest invocation is only executing a single test
7621 # file at any given time, we can use the runtest pid to build the
7622 # path of the temp directory.
7623 set dir [make_gdb_parallel_path temp [pid]]
7625 return [file join $dir $basename]
7628 # Rename file A to file B, if B does not already exists. Otherwise, leave B
7629 # as is and delete A. Return 1 if rename happened.
7631 proc tentative_rename { a b } {
7632 global errorInfo errorCode
7633 set code [catch {file rename -- $a $b} result]
7634 if { $code == 1 && [lindex $errorCode 0] == "POSIX" \
7635 && [lindex $errorCode 1] == "EEXIST" } {
7640 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
7641 } elseif {$code > 1} {
7642 return -code $code $result
7647 # Create a file with name FILENAME and contents TXT in the cache directory.
7648 # If EXECUTABLE, mark the new file for execution.
7650 proc cached_file { filename txt {executable 0}} {
7651 set filename [make_gdb_parallel_path cache $filename]
7653 if { [file exists $filename] } {
7657 set dir [file dirname $filename]
7660 set tmp_filename $filename.[pid]
7661 set fd [open $tmp_filename w]
7665 if { $executable } {
7666 exec chmod +x $tmp_filename
7668 tentative_rename $tmp_filename $filename
7673 # Return a wrapper around gdb that prevents generating a core file.
7675 proc gdb_no_core { } {
7679 [join [list exec $::GDB {"$@"}]]]
7680 set script [join $script "\n"]
7681 return [cached_file gdb-no-core.sh $script 1]
7684 # Set 'testfile', 'srcfile', and 'binfile'.
7686 # ARGS is a list of source file specifications.
7687 # Without any arguments, the .exp file's base name is used to
7688 # compute the source file name. The ".c" extension is added in this case.
7689 # If ARGS is not empty, each entry is a source file specification.
7690 # If the specification starts with a "." or "-", it is treated as a suffix
7691 # to append to the .exp file's base name.
7692 # If the specification is the empty string, it is treated as if it
7694 # Otherwise it is a file name.
7695 # The first file in the list is used to set the 'srcfile' global.
7696 # Each subsequent name is used to set 'srcfile2', 'srcfile3', etc.
7698 # Most tests should call this without arguments.
7700 # If a completely different binary file name is needed, then it
7701 # should be handled in the .exp file with a suitable comment.
7703 proc standard_testfile {args} {
7704 global gdb_test_file_name
7706 global gdb_test_file_last_vars
7709 global testfile binfile
7711 set testfile $gdb_test_file_name
7712 set binfile [standard_output_file ${testfile}]
7714 if {[llength $args] == 0} {
7718 # Unset our previous output variables.
7719 # This can help catch hidden bugs.
7720 if {[info exists gdb_test_file_last_vars]} {
7721 foreach varname $gdb_test_file_last_vars {
7723 catch {unset $varname}
7726 # 'executable' is often set by tests.
7727 set gdb_test_file_last_vars {executable}
7731 set varname srcfile$suffix
7734 # Handle an extension.
7738 set first [string range $arg 0 0]
7739 if { $first == "." || $first == "-" } {
7740 set arg $testfile$arg
7745 lappend gdb_test_file_last_vars $varname
7747 if {$suffix == ""} {
7755 # The default timeout used when testing GDB commands. We want to use
7756 # the same timeout as the default dejagnu timeout, unless the user has
7757 # already provided a specific value (probably through a site.exp file).
7758 global gdb_test_timeout
7759 if ![info exists gdb_test_timeout] {
7760 set gdb_test_timeout $timeout
7763 # A list of global variables that GDB testcases should not use.
7764 # We try to prevent their use by monitoring write accesses and raising
7765 # an error when that happens.
7766 set banned_variables { bug_id prms_id }
7768 # A list of procedures that GDB testcases should not use.
7769 # We try to prevent their use by monitoring invocations and raising
7770 # an error when that happens.
7771 set banned_procedures { strace }
7773 # gdb_init is called by runtest at start, but also by several
7774 # tests directly; gdb_finish is only called from within runtest after
7775 # each test source execution.
7776 # Placing several traces by repetitive calls to gdb_init leads
7777 # to problems, as only one trace is removed in gdb_finish.
7778 # To overcome this possible problem, we add a variable that records
7779 # if the banned variables and procedures are already traced.
7782 # Global array that holds the name of all global variables at the time
7783 # a test script is started. After the test script has completed any
7784 # global not in this list is deleted.
7785 array set gdb_known_globals {}
7787 # Setup the GDB_KNOWN_GLOBALS array with the names of all current
7789 proc gdb_setup_known_globals {} {
7790 global gdb_known_globals
7792 array set gdb_known_globals {}
7793 foreach varname [info globals] {
7794 set gdb_known_globals($varname) 1
7798 # Cleanup the global namespace. Any global not in the
7799 # GDB_KNOWN_GLOBALS array is unset, this ensures we don't "leak"
7800 # globals from one test script to another.
7801 proc gdb_cleanup_globals {} {
7802 global gdb_known_globals gdb_persistent_globals
7804 foreach varname [info globals] {
7805 if {![info exists gdb_known_globals($varname)]} {
7806 if { [info exists gdb_persistent_globals($varname)] } {
7809 uplevel #0 unset $varname
7814 # Create gdb_tcl_unknown, a copy tcl's ::unknown, provided it's present as a
7816 set temp [interp create]
7817 if { [interp eval $temp "info procs ::unknown"] != "" } {
7818 set old_args [interp eval $temp "info args ::unknown"]
7819 set old_body [interp eval $temp "info body ::unknown"]
7820 eval proc gdb_tcl_unknown {$old_args} {$old_body}
7825 # GDB implementation of ${tool}_init. Called right before executing the
7827 # Overridable function -- you can override this function in your
7829 proc gdb_init { args } {
7830 # A baseboard file overriding this proc and calling the default version
7831 # should behave the same as this proc. So, don't add code here, but to
7832 # the default version instead.
7833 return [default_gdb_init {*}$args]
7836 # GDB implementation of ${tool}_finish. Called right after executing the
7838 proc gdb_finish { } {
7839 global gdbserver_reconnect_p
7841 global cleanfiles_target
7842 global cleanfiles_host
7843 global known_globals
7845 if { [info procs ::gdb_tcl_unknown] != "" } {
7846 # Restore dejagnu's version of proc unknown.
7848 rename ::dejagnu_unknown ::unknown
7851 # Exit first, so that the files are no longer in use.
7854 if { [llength $cleanfiles_target] > 0 } {
7855 eval remote_file target delete $cleanfiles_target
7856 set cleanfiles_target {}
7858 if { [llength $cleanfiles_host] > 0 } {
7859 eval remote_file host delete $cleanfiles_host
7860 set cleanfiles_host {}
7863 # Unblock write access to the banned variables. Dejagnu typically
7864 # resets some of them between testcases.
7865 global banned_variables
7866 global banned_procedures
7867 global banned_traced
7868 if ($banned_traced) {
7869 foreach banned_var $banned_variables {
7870 global "$banned_var"
7871 trace remove variable "$banned_var" write error
7873 foreach banned_proc $banned_procedures {
7874 global "$banned_proc"
7875 trace remove execution "$banned_proc" enter error
7880 global gdb_finish_hooks
7881 foreach gdb_finish_hook $gdb_finish_hooks {
7884 set gdb_finish_hooks [list]
7890 set debug_format "unknown"
7892 # Run the gdb command "info source" and extract the debugging format
7893 # information from the output and save it in debug_format.
7895 proc get_debug_format { } {
7900 set debug_format "unknown"
7901 send_gdb "info source\n"
7903 -re "Compiled with (.*) debugging format.\r\n.*$gdb_prompt $" {
7904 set debug_format $expect_out(1,string)
7905 verbose "debug format is $debug_format"
7908 -re "No current source file.\r\n$gdb_prompt $" {
7909 perror "get_debug_format used when no current source file"
7912 -re "$gdb_prompt $" {
7913 warning "couldn't check debug format (no valid response)."
7917 warning "couldn't check debug format (timeout)."
7923 # Return true if FORMAT matches the debug format the current test was
7924 # compiled with. FORMAT is a shell-style globbing pattern; it can use
7925 # `*', `[...]', and so on.
7927 # This function depends on variables set by `get_debug_format', above.
7929 proc test_debug_format {format} {
7932 return [expr [string match $format $debug_format] != 0]
7935 # Like setup_xfail, but takes the name of a debug format (DWARF 1,
7936 # COFF, stabs, etc). If that format matches the format that the
7937 # current test was compiled with, then the next test is expected to
7938 # fail for any target. Returns 1 if the next test or set of tests is
7939 # expected to fail, 0 otherwise (or if it is unknown). Must have
7940 # previously called get_debug_format.
7941 proc setup_xfail_format { format } {
7942 set ret [test_debug_format $format]
7950 # gdb_get_line_number TEXT [FILE]
7952 # Search the source file FILE, and return the line number of the
7953 # first line containing TEXT. If no match is found, an error is thrown.
7955 # TEXT is a string literal, not a regular expression.
7957 # The default value of FILE is "$srcdir/$subdir/$srcfile". If FILE is
7958 # specified, and does not start with "/", then it is assumed to be in
7959 # "$srcdir/$subdir". This is awkward, and can be fixed in the future,
7960 # by changing the callers and the interface at the same time.
7961 # In particular: gdb.base/break.exp, gdb.base/condbreak.exp,
7962 # gdb.base/ena-dis-br.exp.
7964 # Use this function to keep your test scripts independent of the
7965 # exact line numbering of the source file. Don't write:
7967 # send_gdb "break 20"
7969 # This means that if anyone ever edits your test's source file,
7970 # your test could break. Instead, put a comment like this on the
7971 # source file line you want to break at:
7973 # /* breakpoint spot: frotz.exp: test name */
7975 # and then write, in your test script (which we assume is named
7978 # send_gdb "break [gdb_get_line_number "frotz.exp: test name"]\n"
7980 # (Yes, Tcl knows how to handle the nested quotes and brackets.
7983 # % puts "foo [lindex "bar baz" 1]"
7986 # Tcl is quite clever, for a little stringy language.)
7990 # The previous implementation of this procedure used the gdb search command.
7991 # This version is different:
7993 # . It works with MI, and it also works when gdb is not running.
7995 # . It operates on the build machine, not the host machine.
7997 # . For now, this implementation fakes a current directory of
7998 # $srcdir/$subdir to be compatible with the old implementation.
7999 # This will go away eventually and some callers will need to
8002 # . The TEXT argument is literal text and matches literally,
8003 # not a regular expression as it was before.
8005 # . State changes in gdb, such as changing the current file
8006 # and setting $_, no longer happen.
8008 # After a bit of time we can forget about the differences from the
8009 # old implementation.
8011 # --chastain 2004-08-05
8013 proc gdb_get_line_number { text { file "" } } {
8018 if {"$file" == ""} {
8021 if {![regexp "^/" "$file"]} {
8022 set file "$srcdir/$subdir/$file"
8025 if {[catch { set fd [open "$file"] } message]} {
8030 for { set line 1 } { 1 } { incr line } {
8031 if {[catch { set nchar [gets "$fd" body] } message]} {
8037 if {[string first "$text" "$body"] >= 0} {
8043 if {[catch { close "$fd" } message]} {
8048 error "undefined tag \"$text\""
8054 # Continue the program until it ends.
8056 # MSSG is the error message that gets printed. If not given, a
8058 # COMMAND is the command to invoke. If not given, "continue" is
8060 # ALLOW_EXTRA is a flag indicating whether the test should expect
8061 # extra output between the "Continuing." line and the program
8062 # exiting. By default it is zero; if nonzero, any extra output
8065 proc gdb_continue_to_end {{mssg ""} {command continue} {allow_extra 0}} {
8066 global inferior_exited_re use_gdb_stub
8069 set text "continue until exit"
8071 set text "continue until exit at $mssg"
8076 } elseif {[istarget *-*-cygwin*] || [istarget *-*-mingw*]} {
8077 # On Windows, even on supposedly single-threaded programs, we
8078 # may see thread exit output when running to end, for threads
8079 # spawned by the runtime. E.g.:
8083 # [Thread 14364.0x21d4 exited with code 0]
8084 # [Thread 14364.0x4374 exited with code 0]
8085 # [Thread 14364.0x3aec exited with code 0]
8086 # [Thread 14364.0x3368 exited with code 0]
8087 # [Inferior 1 (process 14364) exited normally]
8089 set extra "(\\\[Thread \[^\r\n\]+ exited with code $::decimal\\\]\r\n)*"
8094 # By default, we don't rely on exit() behavior of remote stubs --
8095 # it's common for exit() to be implemented as a simple infinite
8096 # loop, or a forced crash/reset. For native targets, by default, we
8097 # assume process exit is reported as such. If a non-reliable target
8098 # is used, we set a breakpoint at exit, and continue to that.
8099 if { [target_info exists exit_is_reliable] } {
8100 set exit_is_reliable [target_info exit_is_reliable]
8102 set exit_is_reliable [expr ! $use_gdb_stub]
8105 if { ! $exit_is_reliable } {
8106 if {![gdb_breakpoint "exit"]} {
8109 gdb_test $command "Continuing..*Breakpoint .*exit.*" \
8112 # Continue until we exit. Should not stop again.
8113 # Don't bother to check the output of the program, that may be
8114 # extremely tough for some remote systems.
8116 "Continuing.\[\r\n0-9\]+${extra}(... EXIT code 0\[\r\n\]+|$inferior_exited_re normally).*"\
8121 proc rerun_to_main {} {
8122 global gdb_prompt use_gdb_stub
8127 -re ".*Breakpoint .*main .*$gdb_prompt $"\
8128 {pass "rerun to main" ; return 0}
8129 -re "$gdb_prompt $"\
8130 {fail "rerun to main" ; return 0}
8131 timeout {fail "(timeout) rerun to main" ; return 0}
8136 -re "The program .* has been started already.*y or n. $" {
8137 send_gdb "y\n" answer
8140 -re "Starting program.*$gdb_prompt $"\
8141 {pass "rerun to main" ; return 0}
8142 -re "$gdb_prompt $"\
8143 {fail "rerun to main" ; return 0}
8144 timeout {fail "(timeout) rerun to main" ; return 0}
8149 # Return true if EXECUTABLE contains a .gdb_index or .debug_names index section.
8151 proc exec_has_index_section { executable } {
8152 set readelf_program [gdb_find_readelf]
8153 set res [catch {exec $readelf_program -S $executable \
8154 | grep -E "\.gdb_index|\.debug_names" }]
8161 # Return list with major and minor version of readelf, or an empty list.
8162 gdb_caching_proc readelf_version {} {
8163 set readelf_program [gdb_find_readelf]
8164 set res [catch {exec $readelf_program --version} output]
8168 set lines [split $output \n]
8169 set line [lindex $lines 0]
8170 set res [regexp {[ \t]+([0-9]+)[.]([0-9]+)[^ \t]*$} \
8171 $line dummy major minor]
8175 return [list $major $minor]
8178 # Return 1 if readelf prints the PIE flag, 0 if is doesn't, and -1 if unknown.
8179 proc readelf_prints_pie { } {
8180 set version [readelf_version]
8181 if { [llength $version] == 0 } {
8184 set major [lindex $version 0]
8185 set minor [lindex $version 1]
8186 # It would be better to construct a PIE executable and test if the PIE
8187 # flag is printed by readelf, but we cannot reliably construct a PIE
8188 # executable if the multilib_flags dictate otherwise
8189 # (--target_board=unix/-no-pie/-fno-PIE).
8190 return [version_compare {2 26} <= [list $major $minor]]
8193 # Return 1 if EXECUTABLE is a Position Independent Executable, 0 if it is not,
8194 # and -1 if unknown.
8196 proc exec_is_pie { executable } {
8197 set res [readelf_prints_pie]
8201 set readelf_program [gdb_find_readelf]
8202 # We're not testing readelf -d | grep "FLAGS_1.*Flags:.*PIE"
8203 # because the PIE flag is not set by all versions of gold, see PR
8205 set res [catch {exec $readelf_program -h $executable} output]
8209 set res [regexp -line {^[ \t]*Type:[ \t]*DYN \((Position-Independent Executable|Shared object) file\)$} \
8217 # Return false if a test should be skipped due to lack of floating
8218 # point support or GDB can't fetch the contents from floating point
8221 gdb_caching_proc allow_float_test {} {
8222 if [target_info exists gdb,skip_float_tests] {
8226 # There is an ARM kernel ptrace bug that hardware VFP registers
8227 # are not updated after GDB ptrace set VFP registers. The bug
8228 # was introduced by kernel commit 8130b9d7b9d858aa04ce67805e8951e3cb6e9b2f
8229 # in 2012 and is fixed in e2dfb4b880146bfd4b6aa8e138c0205407cebbaf
8230 # in May 2016. In other words, kernels older than 4.6.3, 4.4.14,
8231 # 4.1.27, 3.18.36, and 3.14.73 have this bug.
8232 # This kernel bug is detected by check how does GDB change the
8233 # program result by changing one VFP register.
8234 if { [istarget "arm*-*-linux*"] } {
8236 set compile_flags {debug nowarnings }
8238 # Set up, compile, and execute a test program having VFP
8240 set src [standard_temp_file arm_vfp.c]
8241 set exe [standard_temp_file arm_vfp.x]
8243 gdb_produce_source $src {
8248 asm ("vldr d0, [%0]" : : "r" (&d));
8249 asm ("vldr d1, [%0]" : : "r" (&d));
8250 asm (".global break_here\n"
8252 asm ("vcmp.f64 d0, d1\n"
8253 "vmrs APSR_nzcv, fpscr\n"
8254 "bne L_value_different\n"
8257 "L_value_different:\n"
8259 "L_end:\n" : "=r" (ret) :);
8261 /* Return $d0 != $d1. */
8266 verbose "compiling testfile $src" 2
8267 set lines [gdb_compile $src $exe executable $compile_flags]
8270 if {![string match "" $lines]} {
8271 verbose "testfile compilation failed, returning 1" 2
8275 # No error message, compilation succeeded so now run it via gdb.
8276 # Run the test up to 5 times to detect whether ptrace can
8277 # correctly update VFP registers or not.
8278 set allow_vfp_test 1
8279 for {set i 0} {$i < 5} {incr i} {
8280 global gdb_prompt srcdir subdir
8284 gdb_reinitialize_dir $srcdir/$subdir
8288 gdb_test "break *break_here"
8289 gdb_continue_to_breakpoint "break_here"
8291 # Modify $d0 to a different value, so the exit code should
8293 gdb_test "set \$d0 = 5.0"
8295 set test "continue to exit"
8296 gdb_test_multiple "continue" "$test" {
8297 -re "exited with code 01.*$gdb_prompt $" {
8299 -re "exited normally.*$gdb_prompt $" {
8300 # However, the exit code is 0. That means something
8301 # wrong in setting VFP registers.
8302 set allow_vfp_test 0
8309 remote_file build delete $exe
8311 return $allow_vfp_test
8316 # Print a message and return true if a test should be skipped
8317 # due to lack of stdio support.
8319 proc gdb_skip_stdio_test { msg } {
8320 if [target_info exists gdb,noinferiorio] {
8321 verbose "Skipping test '$msg': no inferior i/o."
8327 proc gdb_skip_bogus_test { msg } {
8331 # Return true if XML support is enabled in the host GDB.
8332 # NOTE: This must be called while gdb is *not* running.
8334 gdb_caching_proc allow_xml_test {} {
8339 if { [info exists gdb_spawn_id] } {
8340 error "GDB must not be running in allow_xml_tests."
8343 set xml_file [gdb_remote_download host "${srcdir}/gdb.xml/trivial.xml"]
8347 gdb_test_multiple "set tdesc filename $xml_file" "" {
8348 -re ".*XML support was disabled at compile time.*$gdb_prompt $" {
8351 -re ".*$gdb_prompt $" { }
8354 return [expr {!$xml_missing}]
8357 # Return true if argv[0] is available.
8359 gdb_caching_proc gdb_has_argv0 {} {
8362 # Compile and execute a test program to check whether argv[0] is available.
8363 gdb_simple_compile has_argv0 {
8364 int main (int argc, char **argv) {
8371 proc gdb_has_argv0_1 { exe } {
8372 global srcdir subdir
8373 global gdb_prompt hex
8377 gdb_reinitialize_dir $srcdir/$subdir
8380 # Set breakpoint on main.
8381 gdb_test_multiple "break -q main" "break -q main" {
8382 -re "Breakpoint.*${gdb_prompt} $" {
8384 -re "${gdb_prompt} $" {
8391 gdb_test_multiple "" "run to main" {
8392 -re "Breakpoint.*${gdb_prompt} $" {
8394 -re "${gdb_prompt} $" {
8399 set old_elements "200"
8400 set test "show print elements"
8401 gdb_test_multiple $test $test {
8402 -re "Limit on string chars or array elements to print is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
8403 set old_elements $expect_out(1,string)
8406 set old_repeats "200"
8407 set test "show print repeats"
8408 gdb_test_multiple $test $test {
8409 -re "Threshold for repeated print elements is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
8410 set old_repeats $expect_out(1,string)
8413 gdb_test_no_output "set print elements unlimited" ""
8414 gdb_test_no_output "set print repeats unlimited" ""
8417 # Check whether argc is 1.
8418 gdb_test_multiple "p argc" "p argc" {
8419 -re " = 1\r\n${gdb_prompt} $" {
8421 gdb_test_multiple "p argv\[0\]" "p argv\[0\]" {
8422 -re " = $hex \".*[file tail $exe]\"\r\n${gdb_prompt} $" {
8425 -re "${gdb_prompt} $" {
8429 -re "${gdb_prompt} $" {
8433 gdb_test_no_output "set print elements $old_elements" ""
8434 gdb_test_no_output "set print repeats $old_repeats" ""
8439 set result [gdb_has_argv0_1 $obj]
8445 && ([istarget *-*-linux*]
8446 || [istarget *-*-freebsd*] || [istarget *-*-kfreebsd*]
8447 || [istarget *-*-netbsd*] || [istarget *-*-knetbsd*]
8448 || [istarget *-*-openbsd*]
8449 || [istarget *-*-darwin*]
8450 || [istarget *-*-solaris*]
8451 || [istarget *-*-aix*]
8452 || [istarget *-*-gnu*]
8453 || [istarget *-*-cygwin*] || [istarget *-*-mingw32*]
8454 || [istarget *-*-*djgpp*] || [istarget *-*-go32*]
8455 || [istarget *-wince-pe] || [istarget *-*-mingw32ce*]
8456 || [istarget *-*-osf*]
8457 || [istarget *-*-dicos*]
8458 || [istarget *-*-*vms*]
8459 || [istarget *-*-lynx*178]) } {
8460 fail "argv\[0\] should be available on this target"
8466 # Note: the procedure gdb_gnu_strip_debug will produce an executable called
8467 # ${binfile}.dbglnk, which is just like the executable ($binfile) but without
8468 # the debuginfo. Instead $binfile has a .gnu_debuglink section which contains
8469 # the name of a debuginfo only file. This file will be stored in the same
8472 # Functions for separate debug info testing
8474 # starting with an executable:
8475 # foo --> original executable
8477 # at the end of the process we have:
8478 # foo.stripped --> foo w/o debug info
8479 # foo.debug --> foo's debug info
8480 # foo --> like foo, but with a new .gnu_debuglink section pointing to foo.debug.
8482 # Fetch the build id from the file.
8483 # Returns "" if there is none.
8485 proc get_build_id { filename } {
8486 if { ([istarget "*-*-mingw*"]
8487 || [istarget *-*-cygwin*]) } {
8488 set objdump_program [gdb_find_objdump]
8489 set result [catch {set data [exec $objdump_program -p $filename | grep signature | cut "-d " -f4]} output]
8490 verbose "result is $result"
8491 verbose "output is $output"
8497 set tmp [standard_output_file "${filename}-tmp"]
8498 set objcopy_program [gdb_find_objcopy]
8499 set result [catch "exec $objcopy_program -j .note.gnu.build-id -O binary $filename $tmp" output]
8500 verbose "result is $result"
8501 verbose "output is $output"
8506 fconfigure $fi -translation binary
8507 # Skip the NOTE header.
8512 if {![string compare $data ""]} {
8515 # Convert it to hex.
8516 binary scan $data H* data
8521 # Return the build-id hex string (usually 160 bits as 40 hex characters)
8522 # converted to the form: .build-id/ab/cdef1234...89.debug
8524 # The '.debug' suffix can be changed by passing the SUFFIX argument.
8526 # Return "" if no build-id found.
8527 proc build_id_debug_filename_get { filename {suffix ".debug"} } {
8528 set data [get_build_id $filename]
8529 if { $data == "" } {
8532 regsub {^..} $data {\0/} data
8533 return ".build-id/${data}${suffix}"
8536 # DEST should be a file compiled with debug information. This proc
8537 # creates DEST.debug which contains the debug information extracted
8538 # from DEST, and DEST is updated with the debug information removed.
8540 # By default a '.gnu_debuglink' section will be added to DEST that
8541 # points to DEST.debug.
8543 # If ARGS is passed, it is a list of optional flags. The currently
8544 # supported flags are:
8546 # - no-main : remove the symbol entry for main from the separate
8547 # debug file DEST.debug,
8548 # - no-debuglink : don't add the '.gnu_debuglink' section to
8551 # Function returns zero on success. Function will return non-zero failure code
8552 # on some targets not supporting separate debug info (such as i386-msdos).
8554 proc gdb_gnu_strip_debug { dest args } {
8556 # Use the first separate debug info file location searched by GDB so the
8557 # run cannot be broken by some stale file searched with higher precedence.
8558 set debug_file "${dest}.debug"
8560 set strip_to_file_program [transform strip]
8561 set objcopy_program [gdb_find_objcopy]
8563 set debug_link [file tail $debug_file]
8564 set stripped_file "${dest}.stripped"
8566 # Get rid of the debug info, and store result in stripped_file
8567 # something like gdb/testsuite/gdb.base/blah.stripped.
8568 set result [catch "exec $strip_to_file_program --strip-debug ${dest} -o ${stripped_file}" output]
8569 verbose "result is $result"
8570 verbose "output is $output"
8575 # Workaround PR binutils/10802:
8576 # Preserve the 'x' bit also for PIEs (Position Independent Executables).
8577 set perm [file attributes ${dest} -permissions]
8578 file attributes ${stripped_file} -permissions $perm
8580 # Get rid of everything but the debug info, and store result in debug_file
8581 # This will be in the .debug subdirectory, see above.
8582 set result [catch "exec $strip_to_file_program --only-keep-debug ${dest} -o ${debug_file}" output]
8583 verbose "result is $result"
8584 verbose "output is $output"
8589 # If no-main is passed, strip the symbol for main from the separate
8590 # file. This is to simulate the behavior of elfutils's eu-strip, which
8591 # leaves the symtab in the original file only. There's no way to get
8592 # objcopy or strip to remove the symbol table without also removing the
8593 # debugging sections, so this is as close as we can get.
8594 if {[lsearch -exact $args "no-main"] != -1} {
8595 set result [catch "exec $objcopy_program -N main ${debug_file} ${debug_file}-tmp" output]
8596 verbose "result is $result"
8597 verbose "output is $output"
8601 file delete "${debug_file}"
8602 file rename "${debug_file}-tmp" "${debug_file}"
8605 # Unless the "no-debuglink" flag is passed, then link the two
8606 # previous output files together, adding the .gnu_debuglink
8607 # section to the stripped_file, containing a pointer to the
8609 if {[lsearch -exact $args "no-debuglink"] == -1} {
8610 set result [catch "exec $objcopy_program --add-gnu-debuglink=${debug_file} ${stripped_file} ${stripped_file}-tmp" output]
8611 verbose "result is $result"
8612 verbose "output is $output"
8616 file delete "${stripped_file}"
8617 file rename "${stripped_file}-tmp" "${stripped_file}"
8620 # Workaround PR binutils/10802:
8621 # Preserve the 'x' bit also for PIEs (Position Independent Executables).
8622 set perm [file attributes ${dest} -permissions]
8623 file attributes ${stripped_file} -permissions $perm
8625 # Move the stripped_file back into dest.
8627 file rename ${stripped_file} ${dest}
8632 # Test the output of GDB_COMMAND matches the pattern obtained
8633 # by concatenating all elements of EXPECTED_LINES. This makes
8634 # it possible to split otherwise very long string into pieces.
8635 # If third argument TESTNAME is not empty, it's used as the name of the
8636 # test to be printed on pass/fail.
8637 proc help_test_raw { gdb_command expected_lines {testname {}} } {
8638 set expected_output [join $expected_lines ""]
8639 if {$testname != {}} {
8640 gdb_test "${gdb_command}" "${expected_output}" $testname
8644 gdb_test "${gdb_command}" "${expected_output}"
8647 # A regexp that matches the end of help CLASS|PREFIX_COMMAND
8648 set help_list_trailer {
8649 "Type \"apropos word\" to search for commands related to \"word\"\.[\r\n]+"
8650 "Type \"apropos -v word\" for full documentation of commands related to \"word\"\.[\r\n]+"
8651 "Command name abbreviations are allowed if unambiguous\."
8654 # Test the output of "help COMMAND_CLASS". EXPECTED_INITIAL_LINES
8655 # are regular expressions that should match the beginning of output,
8656 # before the list of commands in that class.
8657 # LIST_OF_COMMANDS are regular expressions that should match the
8658 # list of commands in that class. If empty, the command list will be
8659 # matched automatically. The presence of standard epilogue will be tested
8661 # If last argument TESTNAME is not empty, it's used as the name of the
8662 # test to be printed on pass/fail.
8663 # Notice that the '[' and ']' characters don't need to be escaped for strings
8664 # wrapped in {} braces.
8665 proc test_class_help { command_class expected_initial_lines {list_of_commands {}} {testname {}} } {
8666 global help_list_trailer
8667 if {[llength $list_of_commands]>0} {
8668 set l_list_of_commands {"List of commands:[\r\n]+[\r\n]+"}
8669 set l_list_of_commands [concat $l_list_of_commands $list_of_commands]
8670 set l_list_of_commands [concat $l_list_of_commands {"[\r\n]+[\r\n]+"}]
8672 set l_list_of_commands {"List of commands\:.*[\r\n]+"}
8675 "Type \"help\" followed by command name for full documentation\.[\r\n]+"
8677 set l_entire_body [concat $expected_initial_lines $l_list_of_commands \
8678 $l_stock_body $help_list_trailer]
8680 help_test_raw "help ${command_class}" $l_entire_body $testname
8683 # Like test_class_help but specialised to test "help user-defined".
8684 proc test_user_defined_class_help { {list_of_commands {}} {testname {}} } {
8685 test_class_help "user-defined" {
8686 "User-defined commands\.[\r\n]+"
8687 "The commands in this class are those defined by the user\.[\r\n]+"
8688 "Use the \"define\" command to define a command\.[\r\n]+"
8689 } $list_of_commands $testname
8693 # COMMAND_LIST should have either one element -- command to test, or
8694 # two elements -- abbreviated command to test, and full command the first
8695 # element is abbreviation of.
8696 # The command must be a prefix command. EXPECTED_INITIAL_LINES
8697 # are regular expressions that should match the beginning of output,
8698 # before the list of subcommands. The presence of
8699 # subcommand list and standard epilogue will be tested automatically.
8700 proc test_prefix_command_help { command_list expected_initial_lines args } {
8701 global help_list_trailer
8702 set command [lindex $command_list 0]
8703 if {[llength $command_list]>1} {
8704 set full_command [lindex $command_list 1]
8706 set full_command $command
8708 # Use 'list' and not just {} because we want variables to
8709 # be expanded in this list.
8710 set l_stock_body [list\
8711 "List of \"$full_command\" subcommands\:.*\[\r\n\]+"\
8712 "Type \"help $full_command\" followed by subcommand name for full documentation\.\[\r\n\]+"]
8713 set l_entire_body [concat $expected_initial_lines $l_stock_body $help_list_trailer]
8714 if {[llength $args]>0} {
8715 help_test_raw "help ${command}" $l_entire_body [lindex $args 0]
8717 help_test_raw "help ${command}" $l_entire_body
8721 # Build executable named EXECUTABLE from specifications that allow
8722 # different options to be passed to different sub-compilations.
8723 # TESTNAME is the name of the test; this is passed to 'untested' if
8725 # OPTIONS is passed to the final link, using gdb_compile. If OPTIONS
8726 # contains the option "pthreads", then gdb_compile_pthreads is used.
8727 # ARGS is a flat list of source specifications, of the form:
8728 # { SOURCE1 OPTIONS1 [ SOURCE2 OPTIONS2 ]... }
8729 # Each SOURCE is compiled to an object file using its OPTIONS,
8730 # using gdb_compile.
8731 # Returns 0 on success, -1 on failure.
8732 proc build_executable_from_specs {testname executable options args} {
8736 set binfile [standard_output_file $executable]
8738 set func gdb_compile
8739 set func_index [lsearch -regexp $options {^(pthreads|shlib|shlib_pthreads|openmp)$}]
8740 if {$func_index != -1} {
8741 set func "${func}_[lindex $options $func_index]"
8744 # gdb_compile_shlib and gdb_compile_shlib_pthreads do not use the 3rd
8745 # parameter. They also requires $sources while gdb_compile and
8746 # gdb_compile_pthreads require $objects. Moreover they ignore any options.
8747 if [string match gdb_compile_shlib* $func] {
8749 foreach {s local_options} $args {
8750 if {[regexp "^/" "$s"]} {
8751 lappend sources_path "$s"
8753 lappend sources_path "$srcdir/$subdir/$s"
8756 set ret [$func $sources_path "${binfile}" $options]
8757 } elseif {[lsearch -exact $options rust] != -1} {
8759 foreach {s local_options} $args {
8760 if {[regexp "^/" "$s"]} {
8761 lappend sources_path "$s"
8763 lappend sources_path "$srcdir/$subdir/$s"
8766 set ret [gdb_compile_rust $sources_path "${binfile}" $options]
8770 foreach {s local_options} $args {
8771 if {![regexp "^/" "$s"]} {
8772 set s "$srcdir/$subdir/$s"
8774 if { [$func "${s}" "${binfile}${i}.o" object $local_options] != "" } {
8778 lappend objects "${binfile}${i}.o"
8781 set ret [$func $objects "${binfile}" executable $options]
8791 # Build executable named EXECUTABLE, from SOURCES. If SOURCES are not
8792 # provided, uses $EXECUTABLE.c. The TESTNAME paramer is the name of test
8793 # to pass to untested, if something is wrong. OPTIONS are passed
8794 # to gdb_compile directly.
8795 proc build_executable { testname executable {sources ""} {options {debug}} } {
8796 if {[llength $sources]==0} {
8797 set sources ${executable}.c
8800 set arglist [list $testname $executable $options]
8801 foreach source $sources {
8802 lappend arglist $source $options
8805 return [eval build_executable_from_specs $arglist]
8808 # Starts fresh GDB binary and loads an optional executable into GDB.
8809 # Usage: clean_restart [EXECUTABLE]
8810 # EXECUTABLE is the basename of the binary.
8811 # Return -1 if starting gdb or loading the executable failed.
8813 proc clean_restart {{executable ""}} {
8821 # This is a clean restart, so reset error and warning count.
8826 # if { [gdb_start] == -1 } {
8829 # but gdb_start is a ${tool}_start proc, which doesn't have a defined
8830 # return value. So instead, we test for errcnt.
8832 if { $errcnt > 0 } {
8836 gdb_reinitialize_dir $srcdir/$subdir
8838 if {$executable != ""} {
8839 set binfile [standard_output_file ${executable}]
8840 return [gdb_load ${binfile}]
8846 # Prepares for testing by calling build_executable_full, then
8848 # TESTNAME is the name of the test.
8849 # Each element in ARGS is a list of the form
8850 # { EXECUTABLE OPTIONS SOURCE_SPEC... }
8851 # These are passed to build_executable_from_specs, which see.
8852 # The last EXECUTABLE is passed to clean_restart.
8853 # Returns 0 on success, non-zero on failure.
8854 proc prepare_for_testing_full {testname args} {
8855 foreach spec $args {
8856 if {[eval build_executable_from_specs [list $testname] $spec] == -1} {
8859 set executable [lindex $spec 0]
8861 clean_restart $executable
8865 # Prepares for testing, by calling build_executable, and then clean_restart.
8866 # Please refer to build_executable for parameter description.
8867 proc prepare_for_testing { testname executable {sources ""} {options {debug}}} {
8869 if {[build_executable $testname $executable $sources $options] == -1} {
8872 clean_restart $executable
8877 # Retrieve the value of EXP in the inferior, represented in format
8878 # specified in FMT (using "printFMT"). DEFAULT is used as fallback if
8879 # print fails. TEST is the test message to use. It can be omitted,
8880 # in which case a test message is built from EXP.
8882 proc get_valueof { fmt exp default {test ""} } {
8886 set test "get valueof \"${exp}\""
8890 gdb_test_multiple "print${fmt} ${exp}" "$test" {
8891 -re -wrap "^\\$\[0-9\]* = (\[^\r\n\]*)" {
8892 set val $expect_out(1,string)
8896 fail "$test (timeout)"
8902 # Retrieve the value of local var EXP in the inferior. DEFAULT is used as
8903 # fallback if print fails. TEST is the test message to use. It can be
8904 # omitted, in which case a test message is built from EXP.
8906 proc get_local_valueof { exp default {test ""} } {
8910 set test "get local valueof \"${exp}\""
8914 gdb_test_multiple "info locals ${exp}" "$test" {
8915 -re "$exp = (\[^\r\n\]*)\r\n$gdb_prompt $" {
8916 set val $expect_out(1,string)
8920 fail "$test (timeout)"
8926 # Retrieve the value of EXP in the inferior, as a signed decimal value
8927 # (using "print /d"). DEFAULT is used as fallback if print fails.
8928 # TEST is the test message to use. It can be omitted, in which case
8929 # a test message is built from EXP.
8931 proc get_integer_valueof { exp default {test ""} } {
8935 set test "get integer valueof \"${exp}\""
8939 gdb_test_multiple "print /d ${exp}" "$test" {
8940 -re -wrap "^\\$\[0-9\]* = (\[-\]*\[0-9\]*).*" {
8941 set val $expect_out(1,string)
8945 fail "$test (timeout)"
8951 # Retrieve the value of EXP in the inferior, as an hexadecimal value
8952 # (using "print /x"). DEFAULT is used as fallback if print fails.
8953 # TEST is the test message to use. It can be omitted, in which case
8954 # a test message is built from EXP.
8956 proc get_hexadecimal_valueof { exp default {test ""} } {
8960 set test "get hexadecimal valueof \"${exp}\""
8964 gdb_test_multiple "print /x ${exp}" $test {
8965 -re "\\$\[0-9\]* = (0x\[0-9a-zA-Z\]+).*$gdb_prompt $" {
8966 set val $expect_out(1,string)
8973 # Retrieve the size of TYPE in the inferior, as a decimal value. DEFAULT
8974 # is used as fallback if print fails. TEST is the test message to use.
8975 # It can be omitted, in which case a test message is 'sizeof (TYPE)'.
8977 proc get_sizeof { type default {test ""} } {
8978 return [get_integer_valueof "sizeof (${type})" $default $test]
8981 proc get_target_charset { } {
8984 gdb_test_multiple "show target-charset" "" {
8985 -re "The target character set is \"auto; currently (\[^\"\]*)\".*$gdb_prompt $" {
8986 return $expect_out(1,string)
8988 -re "The target character set is \"(\[^\"\]*)\".*$gdb_prompt $" {
8989 return $expect_out(1,string)
8993 # Pick a reasonable default.
8994 warning "Unable to read target-charset."
8998 # Get the address of VAR.
9000 proc get_var_address { var } {
9001 global gdb_prompt hex
9003 # Match output like:
9005 # $5 = (int (*)()) 0
9006 # $6 = (int (*)()) 0x24 <function_bar>
9008 gdb_test_multiple "print &${var}" "get address of ${var}" {
9009 -re "\\\$\[0-9\]+ = \\(.*\\) (0|$hex)( <${var}>)?\[\r\n\]+${gdb_prompt} $"
9011 pass "get address of ${var}"
9012 if { $expect_out(1,string) == "0" } {
9015 return $expect_out(1,string)
9022 # Return the frame number for the currently selected frame
9023 proc get_current_frame_number {{test_name ""}} {
9026 if { $test_name == "" } {
9027 set test_name "get current frame number"
9030 gdb_test_multiple "frame" $test_name {
9031 -re "#(\[0-9\]+) .*$gdb_prompt $" {
9032 set frame_num $expect_out(1,string)
9038 # Get the current value for remotetimeout and return it.
9039 proc get_remotetimeout { } {
9043 gdb_test_multiple "show remotetimeout" "" {
9044 -re "Timeout limit to wait for target to respond is ($decimal).*$gdb_prompt $" {
9045 return $expect_out(1,string)
9049 # Pick the default that gdb uses
9050 warning "Unable to read remotetimeout"
9054 # Set the remotetimeout to the specified timeout. Nothing is returned.
9055 proc set_remotetimeout { timeout } {
9058 gdb_test_multiple "set remotetimeout $timeout" "" {
9059 -re "$gdb_prompt $" {
9060 verbose "Set remotetimeout to $timeout\n"
9065 # Get the target's current endianness and return it.
9066 proc get_endianness { } {
9069 gdb_test_multiple "show endian" "determine endianness" {
9070 -re ".* (little|big) endian.*\r\n$gdb_prompt $" {
9072 return $expect_out(1,string)
9078 # Get the target's default endianness and return it.
9079 gdb_caching_proc target_endianness {} {
9082 set me "target_endianness"
9084 set src { int main() { return 0; } }
9085 if {![gdb_simple_compile $me $src executable]} {
9093 set res [get_endianness]
9096 remote_file build delete $obj
9101 # ROOT and FULL are file names. Returns the relative path from ROOT
9102 # to FULL. Note that FULL must be in a subdirectory of ROOT.
9103 # For example, given ROOT = /usr/bin and FULL = /usr/bin/ls, this
9106 proc relative_filename {root full} {
9107 set root_split [file split $root]
9108 set full_split [file split $full]
9110 set len [llength $root_split]
9112 if {[eval file join $root_split]
9113 != [eval file join [lrange $full_split 0 [expr {$len - 1}]]]} {
9114 error "$full not a subdir of $root"
9117 return [eval file join [lrange $full_split $len end]]
9120 # If GDB_PARALLEL exists, then set up the parallel-mode directories.
9121 if {[info exists GDB_PARALLEL]} {
9122 if {[is_remote host]} {
9126 [make_gdb_parallel_path outputs] \
9127 [make_gdb_parallel_path temp] \
9128 [make_gdb_parallel_path cache]
9132 # Set the inferior's cwd to the output directory, in order to have it
9133 # dump core there. This must be called before the inferior is
9136 proc set_inferior_cwd_to_output_dir {} {
9137 # Note this sets the inferior's cwd ("set cwd"), not GDB's ("cd").
9138 # If GDB crashes, we want its core dump in gdb/testsuite/, not in
9139 # the testcase's dir, so we can detect the unexpected core at the
9140 # end of the test run.
9141 if {![is_remote host]} {
9142 set output_dir [standard_output_file ""]
9143 gdb_test_no_output "set cwd $output_dir" \
9144 "set inferior cwd to test directory"
9148 # Get the inferior's PID.
9150 proc get_inferior_pid {} {
9152 gdb_test_multiple "inferior" "get inferior pid" {
9153 -re "process (\[0-9\]*).*$::gdb_prompt $" {
9154 set pid $expect_out(1,string)
9161 # Find the kernel-produced core file dumped for the current testfile
9162 # program. PID was the inferior's pid, saved before the inferior
9163 # exited with a signal, or -1 if not known. If not on a remote host,
9164 # this assumes the core was generated in the output directory.
9165 # Returns the name of the core dump, or empty string if not found.
9167 proc find_core_file {pid} {
9168 # For non-remote hosts, since cores are assumed to be in the
9169 # output dir, which we control, we use a laxer "core.*" glob. For
9170 # remote hosts, as we don't know whether the dir is being reused
9171 # for parallel runs, we use stricter names with no globs. It is
9172 # not clear whether this is really important, but it preserves
9175 if {![is_remote host]} {
9176 lappend files core.*
9177 } elseif {$pid != -1} {
9178 lappend files core.$pid
9180 lappend files ${::testfile}.core
9183 foreach file $files {
9184 if {![is_remote host]} {
9185 set names [glob -nocomplain [standard_output_file $file]]
9186 if {[llength $names] == 1} {
9187 return [lindex $names 0]
9190 if {[remote_file host exists $file]} {
9198 # Check for production of a core file and remove it. PID is the
9199 # inferior's pid or -1 if not known. TEST is the test's message.
9201 proc remove_core {pid {test ""}} {
9203 set test "cleanup core file"
9206 set file [find_core_file $pid]
9208 remote_file host delete $file
9209 pass "$test (removed)"
9211 pass "$test (not found)"
9215 proc core_find {binfile {deletefiles {}} {arg ""}} {
9216 global objdir subdir
9218 set destcore "$binfile.core"
9219 file delete $destcore
9221 # Create a core file named "$destcore" rather than just "core", to
9222 # avoid problems with sys admin types that like to regularly prune all
9223 # files named "core" from the system.
9225 # Arbitrarily try setting the core size limit to "unlimited" since
9226 # this does not hurt on systems where the command does not work and
9227 # allows us to generate a core on systems where it does.
9229 # Some systems append "core" to the name of the program; others append
9230 # the name of the program to "core"; still others (like Linux, as of
9231 # May 2003) create cores named "core.PID". In the latter case, we
9232 # could have many core files lying around, and it may be difficult to
9233 # tell which one is ours, so let's run the program in a subdirectory.
9235 set coredir [standard_output_file coredir.[getpid]]
9237 catch "system \"(cd ${coredir}; ulimit -c unlimited; ${binfile} ${arg}; true) >/dev/null 2>&1\""
9238 # remote_exec host "${binfile}"
9239 foreach i "${coredir}/core ${coredir}/core.coremaker.c ${binfile}.core" {
9240 if [remote_file build exists $i] {
9241 remote_exec build "mv $i $destcore"
9245 # Check for "core.PID", "core.EXEC.PID.HOST.TIME", etc. It's fine
9246 # to use a glob here as we're looking inside a directory we
9247 # created. Also, this procedure only works on non-remote hosts.
9248 if { $found == 0 } {
9249 set names [glob -nocomplain -directory $coredir core.*]
9250 if {[llength $names] == 1} {
9251 set corefile [file join $coredir [lindex $names 0]]
9252 remote_exec build "mv $corefile $destcore"
9256 if { $found == 0 } {
9257 # The braindamaged HPUX shell quits after the ulimit -c above
9258 # without executing ${binfile}. So we try again without the
9259 # ulimit here if we didn't find a core file above.
9260 # Oh, I should mention that any "braindamaged" non-Unix system has
9261 # the same problem. I like the cd bit too, it's really neat'n stuff.
9262 catch "system \"(cd ${objdir}/${subdir}; ${binfile}; true) >/dev/null 2>&1\""
9263 foreach i "${objdir}/${subdir}/core ${objdir}/${subdir}/core.coremaker.c ${binfile}.core" {
9264 if [remote_file build exists $i] {
9265 remote_exec build "mv $i $destcore"
9271 # Try to clean up after ourselves.
9272 foreach deletefile $deletefiles {
9273 remote_file build delete [file join $coredir $deletefile]
9275 remote_exec build "rmdir $coredir"
9277 if { $found == 0 } {
9278 warning "can't generate a core file - core tests suppressed - check ulimit -c"
9284 # gdb_target_symbol_prefix compiles a test program and then examines
9285 # the output from objdump to determine the prefix (such as underscore)
9286 # for linker symbol prefixes.
9288 gdb_caching_proc gdb_target_symbol_prefix {} {
9289 # Compile a simple test program...
9290 set src { int main() { return 0; } }
9291 if {![gdb_simple_compile target_symbol_prefix $src executable]} {
9297 set objdump_program [gdb_find_objdump]
9298 set result [catch "exec $objdump_program --syms $obj" output]
9301 && ![regexp -lineanchor \
9302 { ([^ a-zA-Z0-9]*)main$} $output dummy prefix] } {
9303 verbose "gdb_target_symbol_prefix: Could not find main in objdump output; returning null prefix" 2
9311 # Return 1 if target supports scheduler locking, otherwise return 0.
9313 gdb_caching_proc target_supports_scheduler_locking {} {
9316 set me "gdb_target_supports_scheduler_locking"
9318 set src { int main() { return 0; } }
9319 if {![gdb_simple_compile $me $src executable]} {
9328 set supports_schedule_locking -1
9329 set current_schedule_locking_mode ""
9331 set test "reading current scheduler-locking mode"
9332 gdb_test_multiple "show scheduler-locking" $test {
9333 -re "Mode for locking scheduler during execution is \"(\[\^\"\]*)\".*$gdb_prompt" {
9334 set current_schedule_locking_mode $expect_out(1,string)
9336 -re "$gdb_prompt $" {
9337 set supports_schedule_locking 0
9340 set supports_schedule_locking 0
9344 if { $supports_schedule_locking == -1 } {
9345 set test "checking for scheduler-locking support"
9346 gdb_test_multiple "set scheduler-locking $current_schedule_locking_mode" $test {
9347 -re "Target '\[^'\]+' cannot support this command\..*$gdb_prompt $" {
9348 set supports_schedule_locking 0
9350 -re "$gdb_prompt $" {
9351 set supports_schedule_locking 1
9354 set supports_schedule_locking 0
9359 if { $supports_schedule_locking == -1 } {
9360 set supports_schedule_locking 0
9364 remote_file build delete $obj
9365 verbose "$me: returning $supports_schedule_locking" 2
9366 return $supports_schedule_locking
9369 # Return 1 if compiler supports use of nested functions. Otherwise,
9372 gdb_caching_proc support_nested_function_tests {} {
9373 # Compile a test program containing a nested function
9374 return [gdb_can_simple_compile nested_func {
9384 # gdb_target_symbol returns the provided symbol with the correct prefix
9385 # prepended. (See gdb_target_symbol_prefix, above.)
9387 proc gdb_target_symbol { symbol } {
9388 set prefix [gdb_target_symbol_prefix]
9389 return "${prefix}${symbol}"
9392 # gdb_target_symbol_prefix_flags_asm returns a string that can be
9393 # added to gdb_compile options to define the C-preprocessor macro
9394 # SYMBOL_PREFIX with a value that can be prepended to symbols
9395 # for targets which require a prefix, such as underscore.
9397 # This version (_asm) defines the prefix without double quotes
9398 # surrounding the prefix. It is used to define the macro
9399 # SYMBOL_PREFIX for assembly language files. Another version, below,
9400 # is used for symbols in inline assembler in C/C++ files.
9402 # The lack of quotes in this version (_asm) makes it possible to
9403 # define supporting macros in the .S file. (The version which
9404 # uses quotes for the prefix won't work for such files since it's
9405 # impossible to define a quote-stripping macro in C.)
9407 # It's possible to use this version (_asm) for C/C++ source files too,
9408 # but a string is usually required in such files; providing a version
9409 # (no _asm) which encloses the prefix with double quotes makes it
9410 # somewhat easier to define the supporting macros in the test case.
9412 proc gdb_target_symbol_prefix_flags_asm {} {
9413 set prefix [gdb_target_symbol_prefix]
9414 if {$prefix ne ""} {
9415 return "additional_flags=-DSYMBOL_PREFIX=$prefix"
9421 # gdb_target_symbol_prefix_flags returns the same string as
9422 # gdb_target_symbol_prefix_flags_asm, above, but with the prefix
9423 # enclosed in double quotes if there is a prefix.
9425 # See the comment for gdb_target_symbol_prefix_flags_asm for an
9426 # extended discussion.
9428 proc gdb_target_symbol_prefix_flags {} {
9429 set prefix [gdb_target_symbol_prefix]
9430 if {$prefix ne ""} {
9431 return "additional_flags=-DSYMBOL_PREFIX=\"$prefix\""
9437 # A wrapper for 'remote_exec host' that passes or fails a test.
9438 # Returns 0 if all went well, nonzero on failure.
9439 # TEST is the name of the test, other arguments are as for remote_exec.
9441 proc run_on_host { test program args } {
9442 verbose -log "run_on_host: $program $args"
9443 # remote_exec doesn't work properly if the output is set but the
9444 # input is the empty string -- so replace an empty input with
9446 if {[llength $args] > 1 && [lindex $args 1] == ""} {
9447 set args [lreplace $args 1 1 "/dev/null"]
9449 set result [eval remote_exec host [list $program] $args]
9450 verbose "result is $result"
9451 set status [lindex $result 0]
9452 set output [lindex $result 1]
9457 verbose -log "run_on_host failed: $output"
9458 if { $output == "spawn failed" } {
9467 # Return non-zero if "board_info debug_flags" mentions Fission.
9468 # http://gcc.gnu.org/wiki/DebugFission
9469 # Fission doesn't support everything yet.
9470 # This supports working around bug 15954.
9472 proc using_fission { } {
9473 set debug_flags [board_info [target_info name] debug_flags]
9474 return [regexp -- "-gsplit-dwarf" $debug_flags]
9477 # Search LISTNAME in uplevel LEVEL caller and set variables according to the
9478 # list of valid options with prefix PREFIX described by ARGSET.
9480 # The first member of each one- or two-element list in ARGSET defines the
9481 # name of a variable that will be added to the caller's scope.
9483 # If only one element is given to describe an option, it the value is
9484 # 0 if the option is not present in (the caller's) ARGS or 1 if
9487 # If two elements are given, the second element is the default value of
9488 # the variable. This is then overwritten if the option exists in ARGS.
9489 # If EVAL, then subst is called on the value, which allows variables
9492 # Any parse_args elements in (the caller's) ARGS will be removed, leaving
9493 # any optional components.
9496 # proc myproc {foo args} {
9497 # parse_list 1 args {{bar} {baz "abc"} {qux}} "-" false
9500 # myproc ABC -bar -baz DEF peanut butter
9501 # will define the following variables in myproc:
9502 # foo (=ABC), bar (=1), baz (=DEF), and qux (=0)
9503 # args will be the list {peanut butter}
9505 proc parse_list { level listname argset prefix eval } {
9506 upvar $level $listname args
9508 foreach argument $argset {
9509 if {[llength $argument] == 1} {
9510 # Normalize argument, strip leading/trailing whitespace.
9511 # Allows us to treat {foo} and { foo } the same.
9512 set argument [string trim $argument]
9514 # No default specified, so we assume that we should set
9515 # the value to 1 if the arg is present and 0 if it's not.
9516 # It is assumed that no value is given with the argument.
9517 set pattern "$prefix$argument"
9518 set result [lsearch -exact $args $pattern]
9520 if {$result != -1} {
9522 set args [lreplace $args $result $result]
9526 uplevel $level [list set $argument $value]
9527 } elseif {[llength $argument] == 2} {
9528 # There are two items in the argument. The second is a
9529 # default value to use if the item is not present.
9530 # Otherwise, the variable is set to whatever is provided
9531 # after the item in the args.
9532 set arg [lindex $argument 0]
9533 set pattern "$prefix[lindex $arg 0]"
9534 set result [lsearch -exact $args $pattern]
9536 if {$result != -1} {
9537 set value [lindex $args [expr $result+1]]
9539 set value [uplevel [expr $level + 1] [list subst $value]]
9541 set args [lreplace $args $result [expr $result+1]]
9543 set value [lindex $argument 1]
9545 set value [uplevel $level [list subst $value]]
9548 uplevel $level [list set $arg $value]
9550 error "Badly formatted argument \"$argument\" in argument set"
9555 # Search the caller's args variable and set variables according to the list of
9556 # valid options described by ARGSET.
9558 proc parse_some_args { argset } {
9559 parse_list 2 args $argset "-" false
9561 # The remaining args should be checked to see that they match the
9562 # number of items expected to be passed into the procedure...
9565 # Check that the caller's args variable is empty.
9567 proc check_no_args_left {} {
9568 # Require no remaining args.
9570 if { [llength $args] != 0 } {
9571 error "Args left unparsed: $args"
9575 # As parse_some_args, but check that no args remain after parsing.
9577 proc parse_args { argset } {
9578 uplevel parse_some_args [list $argset]
9580 # Require no remaining args.
9581 uplevel check_no_args_left
9584 # Process the caller's options variable and set variables according
9585 # to the list of valid options described by OPTIONSET.
9587 proc parse_options { optionset } {
9588 parse_list 2 options $optionset "" true
9590 # Require no remaining options.
9591 upvar 1 options options
9592 if { [llength $options] != 0 } {
9593 error "Options left unparsed: $options"
9597 # Capture the output of COMMAND in a string ignoring PREFIX (a regexp);
9598 # return that string.
9600 proc capture_command_output { command prefix } {
9604 set test "capture_command_output for $command"
9606 set output_string ""
9607 gdb_test_multiple $command $test {
9608 -re "^(\[^\r\n\]+\r\n)" {
9609 if { ![string equal $output_string ""] } {
9610 set output_string [join [list $output_string $expect_out(1,string)] ""]
9612 set output_string $expect_out(1,string)
9617 -re "^$gdb_prompt $" {
9621 # Strip the command.
9622 set command_re [string_to_regexp ${command}]
9623 set output_string [regsub ^$command_re\r\n $output_string ""]
9626 if { $prefix != "" } {
9627 set output_string [regsub ^$prefix $output_string ""]
9630 # Strip a trailing newline.
9631 set output_string [regsub "\r\n$" $output_string ""]
9633 return $output_string
9636 # A convenience function that joins all the arguments together, with a
9637 # regexp that matches exactly one end of line in between each argument.
9638 # This function is ideal to write the expected output of a GDB command
9639 # that generates more than a couple of lines, as this allows us to write
9640 # each line as a separate string, which is easier to read by a human
9643 proc multi_line { args } {
9644 if { [llength $args] == 1 } {
9645 set hint "forgot {*} before list argument?"
9646 error "multi_line called with one argument ($hint)"
9648 return [join $args "\r\n"]
9651 # Similar to the above, but while multi_line is meant to be used to
9652 # match GDB output, this one is meant to be used to build strings to
9653 # send as GDB input.
9655 proc multi_line_input { args } {
9656 return [join $args "\n"]
9659 # Return how many newlines there are in the given string.
9661 proc count_newlines { string } {
9662 return [regexp -all "\n" $string]
9665 # Return the version of the DejaGnu framework.
9667 # The return value is a list containing the major, minor and patch version
9668 # numbers. If the version does not contain a minor or patch number, they will
9669 # be set to 0. For example:
9675 proc dejagnu_version { } {
9676 # The frame_version variable is defined by DejaGnu, in runtest.exp.
9677 global frame_version
9679 verbose -log "DejaGnu version: $frame_version"
9680 verbose -log "Expect version: [exp_version]"
9681 verbose -log "Tcl version: [info tclversion]"
9683 set dg_ver [split $frame_version .]
9685 while { [llength $dg_ver] < 3 } {
9692 # Define user-defined command COMMAND using the COMMAND_LIST as the
9693 # command's definition. The terminating "end" is added automatically.
9695 proc gdb_define_cmd {command command_list} {
9698 set input [multi_line_input {*}$command_list "end"]
9699 set test "define $command"
9701 gdb_test_multiple "define $command" $test {
9702 -re "End with \[^\r\n\]*\r\n *>$" {
9703 gdb_test_multiple $input $test {
9704 -re "\r\n$gdb_prompt " {
9711 # Override the 'cd' builtin with a version that ensures that the
9712 # log file keeps pointing at the same file. We need this because
9713 # unfortunately the path to the log file is recorded using an
9714 # relative path name, and, we sometimes need to close/reopen the log
9715 # after changing the current directory. See get_compiler_info.
9717 rename cd builtin_cd
9721 # Get the existing log file flags.
9722 set log_file_info [log_file -info]
9724 # Split the flags into args and file name.
9725 set log_file_flags ""
9726 set log_file_file ""
9727 foreach arg [ split "$log_file_info" " "] {
9728 if [string match "-*" $arg] {
9729 lappend log_file_flags $arg
9731 lappend log_file_file $arg
9735 # If there was an existing file, ensure it is an absolute path, and then
9737 if { $log_file_file != "" } {
9738 set log_file_file [file normalize $log_file_file]
9740 log_file $log_file_flags "$log_file_file"
9743 # Call the builtin version of cd.
9747 # Return a list of all languages supported by GDB, suitable for use in
9748 # 'set language NAME'. This doesn't include the languages auto,
9749 # local, or unknown.
9750 gdb_caching_proc gdb_supported_languages {} {
9751 # The extra space after 'complete set language ' in the command below is
9752 # critical. Only with that space will GDB complete the next level of
9753 # the command, i.e. fill in the actual language names.
9754 set output [remote_exec host $::GDB "$::INTERNAL_GDBFLAGS -batch -ex \"complete set language \""]
9756 if {[lindex $output 0] != 0} {
9757 error "failed to get list of supported languages"
9761 foreach line [split [lindex $output 1] \n] {
9762 if {[regexp "set language (\[^\r\]+)" $line full_match lang]} {
9763 # If LANG is not one of the languages that we ignore, then
9764 # add it to our list of languages.
9765 if {[lsearch -exact {auto local unknown} $lang] == -1} {
9773 # Check if debugging is enabled for gdb.
9775 proc gdb_debug_enabled { } {
9778 # If not already read, get the debug setting from environment or board setting.
9779 if {![info exists gdbdebug]} {
9781 if [info exists env(GDB_DEBUG)] {
9782 set gdbdebug $env(GDB_DEBUG)
9783 } elseif [target_info exists gdb,debug] {
9784 set gdbdebug [target_info gdb,debug]
9790 # Ensure it not empty.
9791 return [expr { $gdbdebug != "" }]
9794 # Turn on debugging if enabled, or reset if already on.
9796 proc gdb_debug_init { } {
9800 if ![gdb_debug_enabled] {
9804 # First ensure logging is off.
9805 send_gdb "set logging enabled off\n"
9807 set debugfile [standard_output_file gdb.debug]
9808 send_gdb "set logging file $debugfile\n"
9810 send_gdb "set logging debugredirect\n"
9813 foreach entry [split $gdbdebug ,] {
9814 send_gdb "set debug $entry 1\n"
9817 # Now that everything is set, enable logging.
9818 send_gdb "set logging enabled on\n"
9820 -re "Copying output to $debugfile.*Redirecting debug output to $debugfile.*$gdb_prompt $" {}
9821 timeout { warning "Couldn't set logging file" }
9825 # Check if debugging is enabled for gdbserver.
9827 proc gdbserver_debug_enabled { } {
9828 # Always disabled for GDB only setups.
9832 # Open the file for logging gdb input
9834 proc gdb_stdin_log_init { } {
9835 gdb_persistent_global in_file
9837 if {[info exists in_file]} {
9838 # Close existing file.
9839 catch "close $in_file"
9842 set logfile [standard_output_file_with_gdb_instance gdb.in]
9843 set in_file [open $logfile w]
9846 # Write to the file for logging gdb input.
9847 # TYPE can be one of the following:
9848 # "standard" : Default. Standard message written to the log
9849 # "answer" : Answer to a question (eg "Y"). Not written the log.
9850 # "optional" : Optional message. Not written to the log.
9852 proc gdb_stdin_log_write { message {type standard} } {
9855 if {![info exists in_file]} {
9859 # Check message types.
9860 switch -regexp -- $type {
9869 # Write to the log and make sure the output is there, even in case
9871 puts -nonewline $in_file "$message"
9875 # Write the command line used to invocate gdb to the cmd file.
9877 proc gdb_write_cmd_file { cmdline } {
9878 set logfile [standard_output_file_with_gdb_instance gdb.cmd]
9879 set cmd_file [open $logfile w]
9880 puts $cmd_file $cmdline
9881 catch "close $cmd_file"
9884 # Compare contents of FILE to string STR. Pass with MSG if equal, otherwise
9887 proc cmp_file_string { file str msg } {
9888 if { ![file exists $file]} {
9893 set caught_error [catch {
9894 set fp [open "$file" r]
9895 set file_contents [read $fp]
9898 if {$caught_error} {
9899 error "$error_message"
9904 if { $file_contents == $str } {
9911 # Compare FILE1 and FILE2 as binary files. Return 0 if the files are
9912 # equal, otherwise, return non-zero.
9914 proc cmp_binary_files { file1 file2 } {
9915 set fd1 [open $file1]
9916 fconfigure $fd1 -translation binary
9917 set fd2 [open $file2]
9918 fconfigure $fd2 -translation binary
9922 set blk1 [read $fd1 $blk_size]
9923 set blk2 [read $fd2 $blk_size]
9924 set diff [string compare $blk1 $blk2]
9925 if {$diff != 0 || [eof $fd1] || [eof $fd2]} {
9933 # Does the compiler support CTF debug output using '-gctf' compiler
9934 # flag? If not then we should skip these tests. We should also
9935 # skip them if libctf was explicitly disabled.
9937 gdb_caching_proc allow_ctf_tests {} {
9938 global enable_libctf
9940 if {$enable_libctf eq "no"} {
9944 set can_ctf [gdb_can_simple_compile ctfdebug {
9948 } executable "additional_flags=-gctf"]
9953 # Return 1 if compiler supports -gstatement-frontiers. Otherwise,
9956 gdb_caching_proc supports_statement_frontiers {} {
9957 return [gdb_can_simple_compile supports_statement_frontiers {
9961 } executable "additional_flags=-gstatement-frontiers"]
9964 # Return 1 if compiler supports -fcf-protection=. Otherwise,
9967 gdb_caching_proc supports_fcf_protection {} {
9968 return [gdb_can_simple_compile supports_fcf_protection {
9972 } executable "additional_flags=-fcf-protection=full"]
9975 # Return true if symbols were read in using -readnow. Otherwise,
9979 return [expr {[lsearch -exact $::GDBFLAGS -readnow] != -1
9980 || [lsearch -exact $::GDBFLAGS --readnow] != -1}]
9983 # Return 'gdb_index' if the symbols from OBJFILE were read using a
9984 # .gdb_index index. Return 'debug_names' if the symbols were read
9985 # using a DWARF-5 style .debug_names index. Otherwise, return an
9988 proc have_index { objfile } {
9990 # This proc is mostly used with $binfile, but that gives problems with
9991 # remote host, while using $testfile would work.
9992 # Fix this by reducing $binfile to $testfile.
9993 set objfile [file tail $objfile]
9995 set index_type [get_index_type $objfile]
9997 if { $index_type eq "gdb" } {
9999 } elseif { $index_type eq "dwarf5" } {
10000 return "debug_names"
10006 # Return 1 if partial symbols are available. Otherwise, return 0.
10008 proc psymtabs_p { } {
10011 set cmd "maint info psymtab"
10012 gdb_test_multiple $cmd "" {
10013 -re "$cmd\r\n$gdb_prompt $" {
10024 # Verify that partial symtab expansion for $filename has state $readin.
10026 proc verify_psymtab_expanded { filename readin } {
10029 set cmd "maint info psymtab"
10030 set test "$cmd: $filename: $readin"
10031 set re [multi_line \
10032 " \{ psymtab \[^\r\n\]*$filename\[^\r\n\]*" \
10033 " readin $readin" \
10036 gdb_test_multiple $cmd $test {
10037 -re "$cmd\r\n$gdb_prompt $" {
10038 unsupported $gdb_test_name
10041 pass $gdb_test_name
10046 # Add a .gdb_index section to PROGRAM.
10047 # PROGRAM is assumed to be the output of standard_output_file.
10048 # Returns the 0 if there is a failure, otherwise 1.
10050 # STYLE controls which style of index to add, if needed. The empty
10051 # string (the default) means .gdb_index; "-dwarf-5" means .debug_names.
10053 proc add_gdb_index { program {style ""} } {
10054 global srcdir GDB env
10055 set contrib_dir "$srcdir/../contrib"
10056 set env(GDB) [append_gdb_data_directory_option $GDB]
10057 set result [catch "exec $contrib_dir/gdb-add-index.sh $style $program" output]
10058 if { $result != 0 } {
10059 verbose -log "result is $result"
10060 verbose -log "output is $output"
10067 # Use 'maint print objfiles OBJFILE' to determine what (if any) type
10068 # of index is present in OBJFILE. Return a string indicating the
10071 # 'gdb' - Contains a .gdb_index style index,
10073 # 'dwarf5' - Contain DWARF5 style index sections,
10075 # 'readnow' - A fake .gdb_index as a result of readnow being used,
10077 # 'cooked' - The cooked index created when reading non-indexed debug
10080 # 'none' - There's no index, and no debug information to create a
10081 # cooked index from.
10083 # If something goes wrong then this proc will emit a FAIL and return
10086 # TESTNAME is used as part of any pass/fail emitted from this proc.
10087 proc get_index_type { objfile { testname "" } } {
10088 if { $testname eq "" } {
10089 set testname "find index type"
10092 set index_type "unknown"
10093 gdb_test_multiple "maint print objfiles ${objfile}" $testname -lbl {
10094 -re "\r\n\\.gdb_index: version ${::decimal}(?=\r\n)" {
10095 set index_type "gdb"
10096 gdb_test_lines "" $gdb_test_name ".*"
10098 -re "\r\n\\.debug_names: exists(?=\r\n)" {
10099 set index_type "dwarf5"
10100 gdb_test_lines "" $gdb_test_name ".*"
10102 -re "\r\n(Cooked index in use:|Psymtabs)(?=\r\n)" {
10103 set index_type "cooked"
10104 gdb_test_lines "" $gdb_test_name ".*"
10106 -re ".gdb_index: faked for \"readnow\"" {
10107 set index_type "readnow"
10108 gdb_test_lines "" $gdb_test_name ".*"
10111 set index_type "none"
10115 gdb_assert { $index_type ne "unknown" } \
10116 "$testname, check type is valid"
10118 if { $index_type eq "unknown" } {
10125 # Add a .gdb_index section to PROGRAM, unless it alread has an index
10126 # (.gdb_index/.debug_names). Gdb doesn't support building an index from a
10127 # program already using one. Return 1 if a .gdb_index was added, return 0
10128 # if it already contained an index, and -1 if an error occurred.
10130 # STYLE controls which style of index to add, if needed. The empty
10131 # string (the default) means .gdb_index; "-dwarf-5" means .debug_names.
10133 proc ensure_gdb_index { binfile {style ""} } {
10134 set testfile [file tail $binfile]
10136 set test "check if index present"
10137 set index_type [get_index_type $testfile $test]
10139 if { $index_type eq "gdb" || $index_type eq "dwarf5" } {
10143 if { $index_type eq "readnow" } {
10147 if { [add_gdb_index $binfile $style] == "1" } {
10154 # Return 1 if executable contains .debug_types section. Otherwise, return 0.
10156 proc debug_types { } {
10159 set cmd "maint info sections"
10160 gdb_test_multiple $cmd "" {
10161 -re -wrap "at $hex: .debug_types.*" {
10172 # Return the addresses in the line table for FILE for which is_stmt is true.
10174 proc is_stmt_addresses { file } {
10180 gdb_test_multiple "maint info line-table $file" "" {
10181 -re "\r\n$decimal\[ \t\]+$decimal\[ \t\]+($hex)\[ \t\]+$hex\[ \t\]+Y\[^\r\n\]*" {
10182 lappend is_stmt $expect_out(1,string)
10192 # Return 1 if hex number VAL is an element of HEXLIST.
10194 proc hex_in_list { val hexlist } {
10195 # Normalize val by removing 0x prefix, and leading zeros.
10196 set val [regsub ^0x $val ""]
10197 set val [regsub ^0+ $val "0"]
10200 set index [lsearch -regexp $hexlist $re]
10201 return [expr $index != -1]
10204 # As info args, but also add the default values.
10206 proc info_args_with_defaults { name } {
10209 foreach arg [info args $name] {
10210 if { [info default $name $arg default_value] } {
10211 lappend args [list $arg $default_value]
10220 # Override proc NAME to proc OVERRIDE for the duration of the execution of
10223 proc with_override { name override body } {
10224 # Implementation note: It's possible to implement the override using
10225 # rename, like this:
10226 # rename $name save_$name
10227 # rename $override $name
10228 # set code [catch {uplevel 1 $body} result]
10229 # rename $name $override
10230 # rename save_$name $name
10231 # but there are two issues here:
10232 # - the save_$name might clash with an existing proc
10233 # - the override is no longer available under its original name during
10235 # So, we use this more elaborate but cleaner mechanism.
10237 # Save the old proc, if it exists.
10238 if { [info procs $name] != "" } {
10239 set old_args [info_args_with_defaults $name]
10240 set old_body [info body $name]
10246 # Install the override.
10247 set new_args [info_args_with_defaults $override]
10248 set new_body [info body $override]
10249 eval proc $name {$new_args} {$new_body}
10252 set code [catch {uplevel 1 $body} result]
10254 # Restore old proc if it existed on entry, else delete it.
10256 eval proc $name {$old_args} {$old_body}
10261 # Return as appropriate.
10262 if { $code == 1 } {
10263 global errorInfo errorCode
10264 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
10265 } elseif { $code > 1 } {
10266 return -code $code $result
10272 # Run BODY after setting the TERM environment variable to 'ansi', and
10273 # unsetting the NO_COLOR environment variable.
10274 proc with_ansi_styling_terminal { body } {
10275 save_vars { ::env(TERM) ::env(NO_COLOR) ::env(COLORTERM) } {
10276 # Set environment variables to allow styling.
10278 unset -nocomplain ::env(NO_COLOR)
10279 unset -nocomplain ::env(COLORTERM)
10281 set code [catch {uplevel 1 $body} result]
10285 global errorInfo errorCode
10286 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
10288 return -code $code $result
10292 # Setup tuiterm.exp environment. To be used in test-cases instead of
10293 # "load_lib tuiterm.exp". Calls initialization function and schedules
10294 # finalization function.
10295 proc tuiterm_env { } {
10296 load_lib tuiterm.exp
10299 # Dejagnu has a version of note, but usage is not allowed outside of dejagnu.
10300 # Define a local version.
10301 proc gdb_note { message } {
10302 verbose -- "NOTE: $message" 0
10305 # Return 1 if compiler supports -fuse-ld=gold, otherwise return 0.
10306 gdb_caching_proc have_fuse_ld_gold {} {
10307 set me "have_fuse_ld_gold"
10308 set flags "additional_flags=-fuse-ld=gold"
10309 set src { int main() { return 0; } }
10310 return [gdb_simple_compile $me $src executable $flags]
10313 # Return 1 if compiler supports fvar-tracking, otherwise return 0.
10314 gdb_caching_proc have_fvar_tracking {} {
10315 set me "have_fvar_tracking"
10316 set flags "additional_flags=-fvar-tracking"
10317 set src { int main() { return 0; } }
10318 return [gdb_simple_compile $me $src executable $flags]
10321 # Return 1 if linker supports -Ttext-segment, otherwise return 0.
10322 gdb_caching_proc linker_supports_Ttext_segment_flag {} {
10323 set me "linker_supports_Ttext_segment_flag"
10324 set flags ldflags="-Wl,-Ttext-segment=0x7000000"
10325 set src { int main() { return 0; } }
10326 return [gdb_simple_compile $me $src executable $flags]
10329 # Return 1 if linker supports -Ttext, otherwise return 0.
10330 gdb_caching_proc linker_supports_Ttext_flag {} {
10331 set me "linker_supports_Ttext_flag"
10332 set flags ldflags="-Wl,-Ttext=0x7000000"
10333 set src { int main() { return 0; } }
10334 return [gdb_simple_compile $me $src executable $flags]
10337 # Return 1 if linker supports --image-base, otherwise 0.
10338 gdb_caching_proc linker_supports_image_base_flag {} {
10339 set me "linker_supports_image_base_flag"
10340 set flags ldflags="-Wl,--image-base=0x7000000"
10341 set src { int main() { return 0; } }
10342 return [gdb_simple_compile $me $src executable $flags]
10346 # Return 1 if compiler supports scalar_storage_order attribute, otherwise
10348 gdb_caching_proc supports_scalar_storage_order_attribute {} {
10349 set me "supports_scalar_storage_order_attribute"
10351 #include <string.h>
10354 } __attribute__((scalar_storage_order("little-endian")));
10357 } __attribute__((scalar_storage_order("big-endian")));
10361 sle.v = sbe.v = 0x11223344;
10362 int same = memcmp (&sle, &sbe, sizeof (int)) == 0;
10367 if { ![gdb_simple_compile $me $src executable ""] } {
10371 set target_obj [gdb_remote_download target $obj]
10372 set result [remote_exec target $target_obj]
10373 set status [lindex $result 0]
10374 set output [lindex $result 1]
10375 if { $output != "" } {
10382 # Return 1 if compiler supports __GNUC__, otherwise return 0.
10383 gdb_caching_proc supports_gnuc {} {
10384 set me "supports_gnuc"
10390 return [gdb_simple_compile $me $src object ""]
10393 # Return 1 if target supports avx, otherwise return 0.
10394 gdb_caching_proc have_avx {} {
10398 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
10399 verbose "$me: target does not support avx, returning 0" 2
10403 # Compile a test program.
10405 #include "nat/x86-cpuid.h"
10408 unsigned int eax, ebx, ecx, edx;
10410 if (!x86_cpuid (1, &eax, &ebx, &ecx, &edx))
10413 if ((ecx & (bit_AVX | bit_OSXSAVE)) == (bit_AVX | bit_OSXSAVE))
10419 set compile_flags "incdir=${srcdir}/.."
10420 if {![gdb_simple_compile $me $src executable $compile_flags]} {
10424 set target_obj [gdb_remote_download target $obj]
10425 set result [remote_exec target $target_obj]
10426 set status [lindex $result 0]
10427 set output [lindex $result 1]
10428 if { $output != "" } {
10432 remote_file build delete $obj
10434 verbose "$me: returning $status" 2
10438 # Return 1 if target supports avx2, otherwise return 0.
10439 gdb_caching_proc have_avx2 {} {
10443 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
10444 verbose "$me: target does not support avx2, returning 0" 2
10448 # Compile a test program.
10450 #include "nat/x86-cpuid.h"
10453 unsigned int eax, ebx, ecx, edx;
10455 if (!x86_cpuid_count (7, 0, &eax, &ebx, &ecx, &edx))
10458 if ((ebx & bit_AVX2) == bit_AVX2)
10464 set compile_flags "incdir=${srcdir}/.."
10465 if {![gdb_simple_compile $me $src executable $compile_flags]} {
10469 set target_obj [gdb_remote_download target $obj]
10470 set result [remote_exec target $target_obj]
10471 set status [lindex $result 0]
10472 set output [lindex $result 1]
10473 if { $output != "" } {
10477 remote_file build delete $obj
10479 verbose "$me: returning $status" 2
10486 # ARG can either be a name, or of the form !NAME.
10488 # Each name is a proc to evaluate in the caller's context. It can return a
10489 # boolean or a two element list with a boolean and a reason string.
10490 # A "!" means to invert the result. If this is true, all is well. If it is
10491 # false, an "unsupported" is emitted and this proc causes the caller to return.
10493 # The reason string is used to provide some context about a require failure,
10494 # and is included in the "unsupported" message.
10496 proc require { args } {
10497 foreach arg $args {
10498 if {[string index $arg 0] == "!"} {
10500 set fn [string range $arg 1 end]
10506 set result [uplevel 1 $fn]
10507 set len [llength $result]
10509 set actual_val [lindex $result 0]
10510 set msg [lindex $result 1]
10511 } elseif { $len == 1 } {
10512 set actual_val $result
10515 error "proc $fn returned a list of unexpected length $len"
10518 if {$required_val != !!$actual_val} {
10519 if { [string length $msg] > 0 } {
10520 unsupported "require failed: $arg ($msg)"
10522 unsupported "require failed: $arg"
10525 return -code return 0
10530 # Wait up to ::TIMEOUT seconds for file PATH to exist on the target system.
10531 # Return 1 if it does exist, 0 otherwise.
10533 proc target_file_exists_with_timeout { path } {
10534 for {set i 0} {$i < $::timeout} {incr i} {
10535 if { [remote_file target exists $path] } {
10545 gdb_caching_proc has_hw_wp_support {} {
10546 # Power 9, proc rev 2.2 does not support HW watchpoints due to HW bug.
10547 # Need to use a runtime test to determine if the Power processor has
10548 # support for HW watchpoints.
10549 global srcdir subdir gdb_prompt inferior_exited_re
10551 set me "has_hw_wp_support"
10553 global gdb_spawn_id
10554 if { [info exists gdb_spawn_id] } {
10555 error "$me called with running gdb instance"
10558 set compile_flags {debug nowarnings quiet}
10560 # Compile a test program to test if HW watchpoints are supported
10563 volatile int local;
10571 if {![gdb_simple_compile $me $src executable $compile_flags]} {
10576 gdb_reinitialize_dir $srcdir/$subdir
10581 remote_file build delete $obj
10583 set has_hw_wp_support 0
10584 return $has_hw_wp_support
10587 # The goal is to determine if HW watchpoints are available in general.
10588 # Use "watch" and then check if gdb responds with hardware watch point.
10589 set test "watch local"
10591 gdb_test_multiple $test "Check for HW watchpoint support" {
10592 -re ".*Hardware watchpoint.*" {
10593 # HW watchpoint supported by platform
10594 verbose -log "\n$me: Hardware watchpoint detected"
10595 set has_hw_wp_support 1
10597 -re ".*$gdb_prompt $" {
10598 set has_hw_wp_support 0
10599 verbose -log "\n$me: Default, hardware watchpoint not deteced"
10604 remote_file build delete $obj
10606 verbose "$me: returning $has_hw_wp_support" 2
10607 return $has_hw_wp_support
10610 # Return a list of all the accepted values of the set command
10611 # "SET_CMD SET_ARG".
10612 # For example get_set_option_choices "set architecture" "i386".
10614 proc get_set_option_choices { set_cmd {set_arg ""} } {
10617 if { $set_arg == "" } {
10618 # Add trailing space to signal that we need completion of the choices,
10619 # not of set_cmd itself.
10620 set cmd "complete $set_cmd "
10622 set cmd "complete $set_cmd $set_arg"
10625 # Set test name without trailing space.
10626 set test [string trim $cmd]
10628 with_set max-completions unlimited {
10629 gdb_test_multiple $cmd $test {
10630 -re "^[string_to_regexp $cmd]\r\n" {
10634 -re "^$set_cmd (\[^\r\n\]+)\r\n" {
10635 lappend values $expect_out(1,string)
10639 -re "^$::gdb_prompt $" {
10640 pass $gdb_test_name
10648 # Return the compiler that can generate 32-bit ARM executables. Used
10649 # when testing biarch support on Aarch64. If ARM_CC_FOR_TARGET is
10650 # set, use that. If not, try a few common compiler names, making sure
10651 # that the executable they produce can run.
10653 gdb_caching_proc arm_cc_for_target {} {
10654 if {[info exists ::ARM_CC_FOR_TARGET]} {
10655 # If the user specified the compiler explicitly, then don't
10656 # check whether the resulting binary runs outside GDB. Assume
10657 # that it does, and if it turns out it doesn't, then the user
10658 # should get loud FAILs, instead of UNSUPPORTED.
10659 return $::ARM_CC_FOR_TARGET
10662 # Fallback to a few common compiler names. Also confirm the
10663 # produced binary actually runs on the system before declaring
10664 # we've found the right compiler.
10666 if [istarget "*-linux*-*"] {
10668 arm-linux-gnueabi-gcc
10669 arm-none-linux-gnueabi-gcc
10670 arm-linux-gnueabihf-gcc
10676 foreach compiler $compilers {
10677 if {![is_remote host] && [which $compiler] == 0} {
10678 # Avoid "default_target_compile: Can't find
10679 # $compiler." warning issued from gdb_compile.
10683 set src { int main() { return 0; } }
10684 if {[gdb_simple_compile aarch64-32bit \
10686 executable [list compiler=$compiler]]} {
10688 set target_obj [gdb_remote_download target $obj]
10689 set result [remote_exec target $target_obj]
10690 set status [lindex $result 0]
10691 set output [lindex $result 1]
10695 if { $output == "" && $status == 0} {
10704 # Step until the pattern REGEXP is found. Step at most
10705 # MAX_STEPS times, but stop stepping once REGEXP is found.
10706 # CURRENT matches current location
10707 # If REGEXP is found then a single pass is emitted, otherwise, after
10708 # MAX_STEPS steps, a single fail is emitted.
10710 # TEST_NAME is the name used in the pass/fail calls.
10712 proc gdb_step_until { regexp {test_name "stepping until regexp"} \
10713 {current "\}"} { max_steps 10 } } {
10714 repeat_cmd_until "step" $current $regexp $test_name "10"
10717 # Do repeated stepping COMMANDs in order to reach TARGET from CURRENT
10719 # COMMAND is a stepping command
10720 # CURRENT is a string matching the current location
10721 # TARGET is a string matching the target location
10722 # TEST_NAME is the test name
10723 # MAX_STEPS is number of steps attempted before fail is emitted
10725 # The function issues repeated COMMANDs as long as the location matches
10726 # CURRENT up to a maximum of MAX_STEPS.
10728 # TEST_NAME passes if the resulting location matches TARGET and fails
10731 proc repeat_cmd_until { command current target \
10732 {test_name "stepping until regexp"} \
10733 {max_steps 100} } {
10737 gdb_test_multiple "$command" "$test_name" {
10738 -re "$target.*$gdb_prompt $" {
10741 -re "$current.*$gdb_prompt $" {
10743 if { $count < $max_steps } {
10744 send_gdb "$command\n"
10753 # Return false if the current target is not operating in non-stop
10754 # mode, otherwise, return true.
10756 # The inferior will need to have started running in order to get the
10759 proc is_target_non_stop { {testname ""} } {
10760 # For historical reasons we assume non-stop mode is on. If the
10761 # maintenance command fails for any reason then we're going to
10763 set is_non_stop true
10764 gdb_test_multiple "maint show target-non-stop" $testname {
10765 -wrap -re "(is|currently) on.*" {
10766 set is_non_stop true
10768 -wrap -re "(is|currently) off.*" {
10769 set is_non_stop false
10772 return $is_non_stop
10775 # Return the number of worker threads that GDB is currently using.
10777 proc gdb_get_worker_threads { {testname ""} } {
10778 set worker_threads "UNKNOWN"
10779 gdb_test_multiple "maintenance show worker-threads" $testname {
10780 -wrap -re "^The number of worker threads GDB can use is the default \\(currently ($::decimal)\\)\\." {
10781 set worker_threads $expect_out(1,string)
10783 -wrap -re "^The number of worker threads GDB can use is ($::decimal)\\." {
10784 set worker_threads $expect_out(1,string)
10787 return $worker_threads
10790 # Check if the compiler emits epilogue information associated
10791 # with the closing brace or with the last statement line.
10793 # This proc restarts GDB
10795 # Returns True if it is associated with the closing brace,
10796 # False if it is the last statement
10797 gdb_caching_proc have_epilogue_line_info {} {
10806 if {![gdb_simple_compile "simple_program" $main]} {
10812 gdb_test_multiple "info line 6" "epilogue test" {
10813 -re -wrap ".*starts at address.*and ends at.*" {
10822 # Decompress file BZ2, and return it.
10824 proc decompress_bz2 { bz2 } {
10825 set copy [standard_output_file [file tail $bz2]]
10826 set copy [remote_download build $bz2 $copy]
10827 if { $copy == "" } {
10831 set res [remote_exec build "bzip2" "-df $copy"]
10832 if { [lindex $res 0] == -1 } {
10836 set copy [regsub {.bz2$} $copy ""]
10837 if { ![remote_file build exists $copy] } {
10844 # Return 1 if the output of "ldd FILE" contains regexp DEP, 0 if it doesn't,
10845 # and -1 if there was a problem running the command.
10847 proc has_dependency { file dep } {
10848 set ldd [gdb_find_ldd]
10849 set command "$ldd $file"
10850 set result [remote_exec host $command]
10851 set status [lindex $result 0]
10852 set output [lindex $result 1]
10853 verbose -log "status of $command is $status"
10854 verbose -log "output of $command is $output"
10855 if { $status != 0 || $output == "" } {
10858 return [regexp $dep $output]
10861 # Detect linux kernel version and return as list of 3 numbers: major, minor,
10862 # and patchlevel. On failure, return an empty list.
10864 gdb_caching_proc linux_kernel_version {} {
10865 if { ![istarget *-*-linux*] } {
10869 set res [remote_exec target "uname -r"]
10870 set status [lindex $res 0]
10871 set output [lindex $res 1]
10872 if { $status != 0 } {
10876 set re ^($::decimal)\\.($::decimal)\\.($::decimal)
10877 if { [regexp $re $output dummy v1 v2 v3] != 1 } {
10881 return [list $v1 $v2 $v3]
10884 # Return 1 if syscall NAME is supported.
10886 proc have_syscall { name } {
10889 "#include <sys/syscall.h>" \
10890 "int var = SYS_$name;"]
10891 set src [join $src "\n"]
10892 return [gdb_can_simple_compile have_syscall_$name $src object]
10895 # Return 1 if compile flag FLAG is supported.
10897 gdb_caching_proc have_compile_flag { flag } {
10898 set src { void foo () {} }
10899 return [gdb_can_simple_compile have_compile_flag_$flag $src object \
10900 additional_flags=$flag]
10903 # Return 1 if we can create an executable using compile and link flag FLAG.
10905 gdb_caching_proc have_compile_and_link_flag { flag } {
10906 set src { int main () { return 0; } }
10907 return [gdb_can_simple_compile have_compile_and_link_flag_$flag $src executable \
10908 additional_flags=$flag]
10911 # Return 1 if this GDB is configured with a "native" target.
10913 gdb_caching_proc have_native_target {} {
10914 gdb_test_multiple "help target native" "" {
10915 -re -wrap "Undefined target command.*" {
10918 -re -wrap "Native process.*" {
10925 # Handle include file $srcdir/$subdir/FILE.
10927 proc include_file { file } {
10928 set file [file join $::srcdir $::subdir $file]
10929 if { [is_remote host] } {
10930 set res [remote_download host $file]
10938 # Handle include file FILE, and if necessary update compiler flags variable
10941 proc lappend_include_file { flags file } {
10942 upvar $flags up_flags
10943 if { [is_remote host] } {
10944 gdb_remote_download host $file
10946 set dir [file dirname $file]
10947 if { $dir != [file join $::srcdir $::subdir] } {
10948 lappend up_flags "additional_flags=-I$dir"
10953 # Return a list of supported host locales.
10955 gdb_caching_proc host_locales { } {
10956 set result [remote_exec host "locale -a"]
10957 set status [lindex $result 0]
10958 set output [lindex $result 1]
10960 if { $status != 0 } {
10965 set output [string trim $output]
10966 set l [split $output \n]
10969 set l [lmap v $l { string trim $v }]
10971 # Normalize items to lower-case.
10972 set l [lmap v $l { string tolower $v }]
10973 # Normalize items to without dash.
10974 set l [lmap v $l { string map { "-" "" } $v }]
10979 # Return 1 if host locale LOCALE is supported.
10981 proc have_host_locale { locale } {
10982 # Normalize to lower-case.
10983 set locale [string tolower $locale]
10984 # Normalize to without dash.
10985 set locale [string map { "-" "" } $locale]
10987 set idx [lsearch [host_locales] $locale]
10988 return [expr $idx != -1]
10991 # Return 1 if we can use '#include <$file>' in source file.
10993 gdb_caching_proc have_system_header { file } {
10994 set src "#include <$file>"
10995 set name [string map { "/" "_sep_" } $file]
10996 return [gdb_can_simple_compile have_system_header_$name $src object]
10999 # Return 1 if the test is being run as root, 0 otherwise.
11001 gdb_caching_proc root_user {} {
11002 # ID outputs to stdout, we have to use exec to capture it here.
11003 set res [remote_exec target id]
11004 set ret_val [lindex $res 0]
11005 set output [lindex $res 1]
11007 # If ret_val is not 0, we couldn't run `id` on the target for some
11008 # reason. Return that we are not root, so problems are easier to
11010 if { $ret_val != 0 } {
11014 regexp -all ".*uid=(\[0-9\]+).*" $output dummy uid
11016 return [expr $uid == 0]
11019 # Always load compatibility stuff.
11020 load_lib future.exp