1 # Copyright 1992-2021 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 # List of procs to run in gdb_finish.
29 set gdb_finish_hooks [list]
31 # Variable in which we keep track of globals that are allowed to be live
33 array set gdb_persistent_globals {}
35 # Mark variable names in ARG as a persistent global, and declare them as
36 # global in the calling context. Can be used to rewrite "global var_a var_b"
37 # into "gdb_persistent_global var_a var_b".
38 proc gdb_persistent_global { args } {
39 global gdb_persistent_globals
40 foreach varname $args {
41 uplevel 1 global $varname
42 set gdb_persistent_globals($varname) 1
46 # Mark variable names in ARG as a persistent global.
47 proc gdb_persistent_global_no_decl { args } {
48 global gdb_persistent_globals
49 foreach varname $args {
50 set gdb_persistent_globals($varname) 1
54 # Override proc load_lib.
55 rename load_lib saved_load_lib
56 # Run the runtest version of load_lib, and mark all variables that were
57 # created by this call as persistent.
58 proc load_lib { file } {
59 array set known_global {}
60 foreach varname [info globals] {
61 set known_globals($varname) 1
64 set code [catch "saved_load_lib $file" result]
66 foreach varname [info globals] {
67 if { ![info exists known_globals($varname)] } {
68 gdb_persistent_global_no_decl $varname
73 global errorInfo errorCode
74 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
75 } elseif {$code > 1} {
76 return -code $code $result
84 load_lib gdb-utils.exp
86 load_lib check-test-names.exp
90 # The spawn ID used for I/O interaction with the inferior. For native
91 # targets, or remote targets that can do I/O through GDB
92 # (semi-hosting) this will be the same as the host/GDB's spawn ID.
93 # Otherwise, the board may set this to some other spawn ID. E.g.,
94 # when debugging with GDBserver, this is set to GDBserver's spawn ID,
95 # so input/output is done on gdbserver's tty.
96 global inferior_spawn_id
98 if [info exists TOOL_EXECUTABLE] {
99 set GDB $TOOL_EXECUTABLE
101 if ![info exists GDB] {
102 if ![is_remote host] {
103 set GDB [findfile $base_dir/../../gdb/gdb "$base_dir/../../gdb/gdb" [transform gdb]]
105 set GDB [transform gdb]
108 verbose "using GDB = $GDB" 2
110 # GDBFLAGS is available for the user to set on the command line.
111 # E.g. make check RUNTESTFLAGS=GDBFLAGS=mumble
112 # Testcases may use it to add additional flags, but they must:
113 # - append new flags, not overwrite
114 # - restore the original value when done
116 if ![info exists GDBFLAGS] {
119 verbose "using GDBFLAGS = $GDBFLAGS" 2
121 # Make the build data directory available to tests.
122 set BUILD_DATA_DIRECTORY "[pwd]/../data-directory"
124 # INTERNAL_GDBFLAGS contains flags that the testsuite requires.
125 global INTERNAL_GDBFLAGS
126 if ![info exists INTERNAL_GDBFLAGS] {
127 set INTERNAL_GDBFLAGS \
131 "-data-directory $BUILD_DATA_DIRECTORY" \
132 {-iex "set height 0"} \
133 {-iex "set width 0"}]]
136 # The variable gdb_prompt is a regexp which matches the gdb prompt.
137 # Set it if it is not already set. This is also set by default_gdb_init
138 # but it's not clear what removing one of them will break.
139 # See with_gdb_prompt for more details on prompt handling.
141 if ![info exists gdb_prompt] then {
142 set gdb_prompt "\\(gdb\\)"
145 # A regexp that matches the pagination prompt.
146 set pagination_prompt \
147 "--Type <RET> for more, q to quit, c to continue without paging--"
149 # The variable fullname_syntax_POSIX is a regexp which matches a POSIX
150 # absolute path ie. /foo/
151 set fullname_syntax_POSIX {/[^\n]*/}
152 # The variable fullname_syntax_UNC is a regexp which matches a Windows
153 # UNC path ie. \\D\foo\
154 set fullname_syntax_UNC {\\\\[^\\]+\\[^\n]+\\}
155 # The variable fullname_syntax_DOS_CASE is a regexp which matches a
156 # particular DOS case that GDB most likely will output
157 # ie. \foo\, but don't match \\.*\
158 set fullname_syntax_DOS_CASE {\\[^\\][^\n]*\\}
159 # The variable fullname_syntax_DOS is a regexp which matches a DOS path
160 # ie. a:\foo\ && a:foo\
161 set fullname_syntax_DOS {[a-zA-Z]:[^\n]*\\}
162 # The variable fullname_syntax is a regexp which matches what GDB considers
163 # an absolute path. It is currently debatable if the Windows style paths
164 # d:foo and \abc should be considered valid as an absolute path.
165 # Also, the purpse of this regexp is not to recognize a well formed
166 # absolute path, but to say with certainty that a path is absolute.
167 set fullname_syntax "($fullname_syntax_POSIX|$fullname_syntax_UNC|$fullname_syntax_DOS_CASE|$fullname_syntax_DOS)"
169 # Needed for some tests under Cygwin.
173 if ![info exists env(EXEEXT)] {
176 set EXEEXT $env(EXEEXT)
181 set inferior_exited_re "(?:\\\[Inferior \[0-9\]+ \\(\[^\n\r\]*\\) exited)"
183 # A regular expression that matches a value history number.
185 set valnum_re "\\\$$decimal"
187 ### Only procedures should come after this point.
190 # gdb_version -- extract and print the version number of GDB
192 proc default_gdb_version {} {
194 global INTERNAL_GDBFLAGS GDBFLAGS
198 if {[info exists inotify_pid]} {
199 eval exec kill $inotify_pid
202 set output [remote_exec host "$GDB $INTERNAL_GDBFLAGS --version"]
203 set tmp [lindex $output 1]
205 regexp " \[0-9\]\[^ \t\n\r\]+" "$tmp" version
206 if ![is_remote host] {
207 clone_output "[which $GDB] version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
209 clone_output "$GDB on remote host version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
213 proc gdb_version { } {
214 return [default_gdb_version]
218 # gdb_unload -- unload a file if one is loaded
219 # Return 0 on success, -1 on error.
227 -re "No executable file now\[^\r\n\]*\[\r\n\]" { exp_continue }
228 -re "No symbol file now\[^\r\n\]*\[\r\n\]" { exp_continue }
229 -re "A program is being debugged already.*Are you sure you want to change the file.*y or n. $" {
230 send_gdb "y\n" answer
233 -re "Discard symbol table from .*y or n.*$" {
234 send_gdb "y\n" answer
237 -re "$gdb_prompt $" {}
239 perror "couldn't unload file in $GDB (timeout)."
246 # Many of the tests depend on setting breakpoints at various places and
247 # running until that breakpoint is reached. At times, we want to start
248 # with a clean-slate with respect to breakpoints, so this utility proc
249 # lets us do this without duplicating this code everywhere.
252 proc delete_breakpoints {} {
255 # we need a larger timeout value here or this thing just confuses
256 # itself. May need a better implementation if possible. - guo
260 set msg "delete all breakpoints in delete_breakpoints"
262 gdb_test_multiple "delete breakpoints" "$msg" {
263 -re "Delete all breakpoints.*y or n.*$" {
264 send_gdb "y\n" answer
267 -re "$gdb_prompt $" {
273 # Confirm with "info breakpoints".
275 set msg "info breakpoints"
276 gdb_test_multiple $msg $msg {
277 -re "No breakpoints or watchpoints..*$gdb_prompt $" {
280 -re "$gdb_prompt $" {
286 perror "breakpoints not deleted"
290 # Returns true iff the target supports using the "run" command.
292 proc target_can_use_run_cmd {} {
293 if [target_info exists use_gdb_stub] {
294 # In this case, when we connect, the inferior is already
303 # Generic run command.
305 # Return 0 if we could start the program, -1 if we could not.
307 # The second pattern below matches up to the first newline *only*.
308 # Using ``.*$'' could swallow up output that we attempt to match
311 # INFERIOR_ARGS is passed as arguments to the start command, so may contain
312 # inferior arguments.
314 # N.B. This function does not wait for gdb to return to the prompt,
315 # that is the caller's responsibility.
317 proc gdb_run_cmd { {inferior_args {}} } {
318 global gdb_prompt use_gdb_stub
320 foreach command [gdb_init_commands] {
321 send_gdb "$command\n"
323 -re "$gdb_prompt $" { }
325 perror "gdb_init_command for target failed"
332 if [target_info exists gdb,do_reload_on_run] {
333 if { [gdb_reload $inferior_args] != 0 } {
336 send_gdb "continue\n"
338 -re "Continu\[^\r\n\]*\[\r\n\]" {}
344 if [target_info exists gdb,start_symbol] {
345 set start [target_info gdb,start_symbol]
349 send_gdb "jump *$start\n"
351 while { $start_attempt } {
352 # Cap (re)start attempts at three to ensure that this loop
353 # always eventually fails. Don't worry about trying to be
354 # clever and not send a command when it has failed.
355 if [expr $start_attempt > 3] {
356 perror "Jump to start() failed (retry count exceeded)"
359 set start_attempt [expr $start_attempt + 1]
361 -re "Continuing at \[^\r\n\]*\[\r\n\]" {
364 -re "No symbol \"_start\" in current.*$gdb_prompt $" {
365 perror "Can't find start symbol to run in gdb_run"
368 -re "No symbol \"start\" in current.*$gdb_prompt $" {
369 send_gdb "jump *_start\n"
371 -re "No symbol.*context.*$gdb_prompt $" {
374 -re "Line.* Jump anyway.*y or n. $" {
375 send_gdb "y\n" answer
377 -re "The program is not being run.*$gdb_prompt $" {
378 if { [gdb_reload $inferior_args] != 0 } {
381 send_gdb "jump *$start\n"
384 perror "Jump to start() failed (timeout)"
393 if [target_info exists gdb,do_reload_on_run] {
394 if { [gdb_reload $inferior_args] != 0 } {
398 send_gdb "run $inferior_args\n"
399 # This doesn't work quite right yet.
400 # Use -notransfer here so that test cases (like chng-sym.exp)
401 # may test for additional start-up messages.
403 -re "The program .* has been started already.*y or n. $" {
404 send_gdb "y\n" answer
407 -notransfer -re "Starting program: \[^\r\n\]*" {}
408 -notransfer -re "$gdb_prompt $" {
409 # There is no more input expected.
416 # Generic start command. Return 0 if we could start the program, -1
419 # INFERIOR_ARGS is passed as arguments to the start command, so may contain
420 # inferior arguments.
422 # N.B. This function does not wait for gdb to return to the prompt,
423 # that is the caller's responsibility.
425 proc gdb_start_cmd { {inferior_args {}} } {
426 global gdb_prompt use_gdb_stub
428 foreach command [gdb_init_commands] {
429 send_gdb "$command\n"
431 -re "$gdb_prompt $" { }
433 perror "gdb_init_command for target failed"
443 send_gdb "start $inferior_args\n"
444 # Use -notransfer here so that test cases (like chng-sym.exp)
445 # may test for additional start-up messages.
447 -re "The program .* has been started already.*y or n. $" {
448 send_gdb "y\n" answer
451 -notransfer -re "Starting program: \[^\r\n\]*" {
458 # Generic starti command. Return 0 if we could start the program, -1
461 # INFERIOR_ARGS is passed as arguments to the starti command, so may contain
462 # inferior arguments.
464 # N.B. This function does not wait for gdb to return to the prompt,
465 # that is the caller's responsibility.
467 proc gdb_starti_cmd { {inferior_args {}} } {
468 global gdb_prompt use_gdb_stub
470 foreach command [gdb_init_commands] {
471 send_gdb "$command\n"
473 -re "$gdb_prompt $" { }
475 perror "gdb_init_command for target failed"
485 send_gdb "starti $inferior_args\n"
487 -re "The program .* has been started already.*y or n. $" {
488 send_gdb "y\n" answer
491 -re "Starting program: \[^\r\n\]*" {
498 # Set a breakpoint at FUNCTION. If there is an additional argument it is
499 # a list of options; the supported options are allow-pending, temporary,
500 # message, no-message and qualified.
501 # The result is 1 for success, 0 for failure.
503 # Note: The handling of message vs no-message is messed up, but it's based
504 # on historical usage. By default this function does not print passes,
506 # no-message: turns off printing of fails (and passes, but they're already off)
507 # message: turns on printing of passes (and fails, but they're already on)
509 proc gdb_breakpoint { function args } {
513 set pending_response n
514 if {[lsearch -exact $args allow-pending] != -1} {
515 set pending_response y
518 set break_command "break"
519 set break_message "Breakpoint"
520 if {[lsearch -exact $args temporary] != -1} {
521 set break_command "tbreak"
522 set break_message "Temporary breakpoint"
525 if {[lsearch -exact $args qualified] != -1} {
526 append break_command " -qualified"
531 set no_message_loc [lsearch -exact $args no-message]
532 set message_loc [lsearch -exact $args message]
533 # The last one to appear in args wins.
534 if { $no_message_loc > $message_loc } {
536 } elseif { $message_loc > $no_message_loc } {
540 set test_name "setting breakpoint at $function"
542 send_gdb "$break_command $function\n"
543 # The first two regexps are what we get with -g, the third is without -g.
545 -re "$break_message \[0-9\]* at .*: file .*, line $decimal.\r\n$gdb_prompt $" {}
546 -re "$break_message \[0-9\]*: file .*, line $decimal.\r\n$gdb_prompt $" {}
547 -re "$break_message \[0-9\]* at .*$gdb_prompt $" {}
548 -re "$break_message \[0-9\]* \\(.*\\) pending.*$gdb_prompt $" {
549 if {$pending_response == "n"} {
556 -re "Make breakpoint pending.*y or \\\[n\\\]. $" {
557 send_gdb "$pending_response\n"
560 -re "A problem internal to GDB has been detected" {
562 fail "$test_name (GDB internal error)"
564 gdb_internal_error_resync
567 -re "$gdb_prompt $" {
574 perror "GDB process no longer exists"
576 set wait_status [wait -i $gdb_spawn_id]
577 verbose -log "GDB process exited with wait status $wait_status"
579 fail "$test_name (eof)"
585 fail "$test_name (timeout)"
596 # Set breakpoint at function and run gdb until it breaks there.
597 # Since this is the only breakpoint that will be set, if it stops
598 # at a breakpoint, we will assume it is the one we want. We can't
599 # just compare to "function" because it might be a fully qualified,
600 # single quoted C++ function specifier.
602 # If there are additional arguments, pass them to gdb_breakpoint.
603 # We recognize no-message/message ourselves.
604 # The default is no-message.
605 # no-message is messed up here, like gdb_breakpoint: to preserve
606 # historical usage fails are always printed by default.
607 # no-message: turns off printing of fails (and passes, but they're already off)
608 # message: turns on printing of passes (and fails, but they're already on)
610 proc runto { function args } {
616 # Default to "no-message".
617 set args "no-message $args"
621 set no_message_loc [lsearch -exact $args no-message]
622 set message_loc [lsearch -exact $args message]
623 # The last one to appear in args wins.
624 if { $no_message_loc > $message_loc } {
626 } elseif { $message_loc > $no_message_loc } {
630 set test_name "running to $function in runto"
632 # We need to use eval here to pass our varargs args to gdb_breakpoint
633 # which is also a varargs function.
634 # But we also have to be careful because $function may have multiple
635 # elements, and we don't want Tcl to move the remaining elements after
636 # the first to $args. That is why $function is wrapped in {}.
637 if ![eval gdb_breakpoint {$function} $args] {
643 # the "at foo.c:36" output we get with -g.
644 # the "in func" output we get without -g.
646 -re "Break.* at .*:$decimal.*$gdb_prompt $" {
652 -re "Breakpoint \[0-9\]*, \[0-9xa-f\]* in .*$gdb_prompt $" {
658 -re "The target does not support running in non-stop mode.\r\n$gdb_prompt $" {
660 unsupported "non-stop mode not supported"
664 -re ".*A problem internal to GDB has been detected" {
665 # Always emit a FAIL if we encounter an internal error: internal
666 # errors are never expected.
667 fail "$test_name (GDB internal error)"
668 gdb_internal_error_resync
671 -re "$gdb_prompt $" {
679 fail "$test_name (eof)"
685 fail "$test_name (timeout)"
696 # Ask gdb to run until we hit a breakpoint at main.
698 # N.B. This function deletes all existing breakpoints.
699 # If you don't want that, use gdb_start_cmd.
701 proc runto_main { } {
702 return [runto main no-message qualified]
705 ### Continue, and expect to hit a breakpoint.
706 ### Report a pass or fail, depending on whether it seems to have
707 ### worked. Use NAME as part of the test name; each call to
708 ### continue_to_breakpoint should use a NAME which is unique within
710 proc gdb_continue_to_breakpoint {name {location_pattern .*}} {
712 set full_name "continue to breakpoint: $name"
714 set kfail_pattern "Process record does not support instruction 0xfae64 at.*"
715 gdb_test_multiple "continue" $full_name {
716 -re "(?:Breakpoint|Temporary breakpoint) .* (at|in) $location_pattern\r\n$gdb_prompt $" {
719 -re "\[\r\n\]*(?:$kfail_pattern)\[\r\n\]+$gdb_prompt $" {
720 kfail "gdb/25038" $full_name
726 # gdb_internal_error_resync:
728 # Answer the questions GDB asks after it reports an internal error
729 # until we get back to a GDB prompt. Decline to quit the debugging
730 # session, and decline to create a core file. Return non-zero if the
733 # This procedure just answers whatever questions come up until it sees
734 # a GDB prompt; it doesn't require you to have matched the input up to
735 # any specific point. However, it only answers questions it sees in
736 # the output itself, so if you've matched a question, you had better
737 # answer it yourself before calling this.
739 # You can use this function thus:
743 # -re ".*A problem internal to GDB has been detected" {
744 # gdb_internal_error_resync
749 proc gdb_internal_error_resync {} {
752 verbose -log "Resyncing due to internal error."
755 while {$count < 10} {
757 -re "Quit this debugging session\\? \\(y or n\\) $" {
758 send_gdb "n\n" answer
761 -re "Create a core file of GDB\\? \\(y or n\\) $" {
762 send_gdb "n\n" answer
765 -re "$gdb_prompt $" {
766 # We're resynchronized.
770 perror "Could not resync from internal error (timeout)"
775 perror "Could not resync from internal error (resync count exceeded)"
780 # gdb_test_multiple COMMAND MESSAGE [ -prompt PROMPT_REGEXP] [ -lbl ]
782 # Send a command to gdb; test the result.
784 # COMMAND is the command to execute, send to GDB with send_gdb. If
785 # this is the null string no command is sent.
786 # MESSAGE is a message to be printed with the built-in failure patterns
787 # if one of them matches. If MESSAGE is empty COMMAND will be used.
788 # -prompt PROMPT_REGEXP specifies a regexp matching the expected prompt
789 # after the command output. If empty, defaults to "$gdb_prompt $".
790 # -lbl specifies that line-by-line matching will be used.
791 # EXPECT_ARGUMENTS will be fed to expect in addition to the standard
792 # patterns. Pattern elements will be evaluated in the caller's
793 # context; action elements will be executed in the caller's context.
794 # Unlike patterns for gdb_test, these patterns should generally include
795 # the final newline and prompt.
798 # 1 if the test failed, according to a built-in failure pattern
799 # 0 if only user-supplied patterns matched
800 # -1 if there was an internal error.
802 # You can use this function thus:
804 # gdb_test_multiple "print foo" "test foo" {
805 # -re "expected output 1" {
808 # -re "expected output 2" {
813 # Within action elements you can also make use of the variable
814 # gdb_test_name. This variable is setup automatically by
815 # gdb_test_multiple, and contains the value of MESSAGE. You can then
816 # write this, which is equivalent to the above:
818 # gdb_test_multiple "print foo" "test foo" {
819 # -re "expected output 1" {
820 # pass $gdb_test_name
822 # -re "expected output 2" {
823 # fail $gdb_test_name
827 # Like with "expect", you can also specify the spawn id to match with
828 # -i "$id". Interesting spawn ids are $inferior_spawn_id and
829 # $gdb_spawn_id. The former matches inferior I/O, while the latter
830 # matches GDB I/O. E.g.:
832 # send_inferior "hello\n"
833 # gdb_test_multiple "continue" "test echo" {
834 # -i "$inferior_spawn_id" -re "^hello\r\nhello\r\n$" {
837 # -i "$gdb_spawn_id" -re "Breakpoint.*$gdb_prompt $" {
838 # fail "hit breakpoint"
842 # The standard patterns, such as "Inferior exited..." and "A problem
843 # ...", all being implicitly appended to that list. These are always
844 # expected from $gdb_spawn_id. IOW, callers do not need to worry
845 # about resetting "-i" back to $gdb_spawn_id explicitly.
847 # In EXPECT_ARGUMENTS we can use a -wrap pattern flag, that wraps the regexp
848 # pattern as gdb_test wraps its message argument.
849 # This allows us to rewrite:
850 # gdb_test <command> <pattern> <message>
852 # gdb_test_multiple <command> <message> {
853 # -re -wrap <pattern> {
854 # pass $gdb_test_name
858 # In EXPECT_ARGUMENTS, a pattern flag -early can be used. It makes sure the
859 # pattern is inserted before any implicit pattern added by gdb_test_multiple.
860 # Using this pattern flag, we can f.i. setup a kfail for an assertion failure
861 # <assert> during gdb_continue_to_breakpoint by the rewrite:
862 # gdb_continue_to_breakpoint <msg> <pattern>
864 # set breakpoint_pattern "(?:Breakpoint|Temporary breakpoint) .* (at|in)"
865 # gdb_test_multiple "continue" "continue to breakpoint: <msg>" {
866 # -early -re "internal-error: <assert>" {
867 # setup_kfail gdb/nnnnn "*-*-*"
870 # -re "$breakpoint_pattern <pattern>\r\n$gdb_prompt $" {
871 # pass $gdb_test_name
875 proc gdb_test_multiple { command message args } {
876 global verbose use_gdb_stub
877 global gdb_prompt pagination_prompt
880 global inferior_exited_re
881 upvar timeout timeout
882 upvar expect_out expect_out
887 for {set i 0} {$i < [llength $args]} {incr i} {
888 set arg [lindex $args $i]
889 if { $arg == "-prompt" } {
891 set prompt_regexp [lindex $args $i]
892 } elseif { $arg == "-lbl" } {
899 if { [expr $i + 1] < [llength $args] } {
900 error "Too many arguments to gdb_test_multiple"
901 } elseif { ![info exists user_code] } {
902 error "Too few arguments to gdb_test_multiple"
905 if { "$prompt_regexp" == "" } {
906 set prompt_regexp "$gdb_prompt $"
909 if { $message == "" } {
913 if [string match "*\[\r\n\]" $command] {
914 error "Invalid trailing newline in \"$message\" test"
917 if [string match "*\[\r\n\]*" $message] {
918 error "Invalid newline in \"$message\" test"
922 && [regexp -nocase {^\s*(r|run|star|start|at|att|atta|attac|attach)\M} \
924 error "gdbserver does not support $command without extended-remote"
927 # TCL/EXPECT WART ALERT
928 # Expect does something very strange when it receives a single braced
929 # argument. It splits it along word separators and performs substitutions.
930 # This means that { "[ab]" } is evaluated as "[ab]", but { "\[ab\]" } is
931 # evaluated as "\[ab\]". But that's not how TCL normally works; inside a
932 # double-quoted list item, "\[ab\]" is just a long way of representing
933 # "[ab]", because the backslashes will be removed by lindex.
935 # Unfortunately, there appears to be no easy way to duplicate the splitting
936 # that expect will do from within TCL. And many places make use of the
937 # "\[0-9\]" construct, so we need to support that; and some places make use
938 # of the "[func]" construct, so we need to support that too. In order to
939 # get this right we have to substitute quoted list elements differently
940 # from braced list elements.
942 # We do this roughly the same way that Expect does it. We have to use two
943 # lists, because if we leave unquoted newlines in the argument to uplevel
944 # they'll be treated as command separators, and if we escape newlines
945 # we mangle newlines inside of command blocks. This assumes that the
946 # input doesn't contain a pattern which contains actual embedded newlines
949 regsub -all {\n} ${user_code} { } subst_code
950 set subst_code [uplevel list $subst_code]
952 set processed_code ""
953 set early_processed_code ""
954 # The variable current_list holds the name of the currently processed
955 # list, either processed_code or early_processed_code.
956 set current_list "processed_code"
958 set expecting_action 0
961 foreach item $user_code subst_item $subst_code {
962 if { $item == "-n" || $item == "-notransfer" || $item == "-nocase" } {
963 lappend $current_list $item
966 if { $item == "-indices" || $item == "-re" || $item == "-ex" } {
967 lappend $current_list $item
970 if { $item == "-early" } {
971 set current_list "early_processed_code"
974 if { $item == "-timeout" || $item == "-i" } {
976 lappend $current_list $item
979 if { $item == "-wrap" } {
983 if { $expecting_arg } {
985 lappend $current_list $subst_item
988 if { $expecting_action } {
989 lappend $current_list "uplevel [list $item]"
990 set expecting_action 0
991 # Cosmetic, no effect on the list.
992 append $current_list "\n"
993 # End the effect of -early, it only applies to one action.
994 set current_list "processed_code"
997 set expecting_action 1
998 if { $wrap_pattern } {
999 # Wrap subst_item as is done for the gdb_test PATTERN argument.
1000 lappend $current_list \
1001 "\[\r\n\]*(?:$subst_item)\[\r\n\]+$gdb_prompt $"
1004 lappend $current_list $subst_item
1006 if {$patterns != ""} {
1007 append patterns "; "
1009 append patterns "\"$subst_item\""
1012 # Also purely cosmetic.
1013 regsub -all {\r} $patterns {\\r} patterns
1014 regsub -all {\n} $patterns {\\n} patterns
1016 if $verbose>2 then {
1017 send_user "Sending \"$command\" to gdb\n"
1018 send_user "Looking to match \"$patterns\"\n"
1019 send_user "Message is \"$message\"\n"
1023 set string "${command}\n"
1024 if { $command != "" } {
1025 set multi_line_re "\[\r\n\] *>"
1026 while { "$string" != "" } {
1027 set foo [string first "\n" "$string"]
1028 set len [string length "$string"]
1029 if { $foo < [expr $len - 1] } {
1030 set str [string range "$string" 0 $foo]
1031 if { [send_gdb "$str"] != "" } {
1032 perror "Couldn't send $command to GDB."
1034 # since we're checking if each line of the multi-line
1035 # command are 'accepted' by GDB here,
1036 # we need to set -notransfer expect option so that
1037 # command output is not lost for pattern matching
1040 -notransfer -re "$multi_line_re$" { verbose "partial: match" 3 }
1041 timeout { verbose "partial: timeout" 3 }
1043 set string [string range "$string" [expr $foo + 1] end]
1044 set multi_line_re "$multi_line_re.*\[\r\n\] *>"
1049 if { "$string" != "" } {
1050 if { [send_gdb "$string"] != "" } {
1051 perror "Couldn't send $command to GDB."
1056 set code $early_processed_code
1058 -re ".*A problem internal to GDB has been detected" {
1059 fail "$message (GDB internal error)"
1060 gdb_internal_error_resync
1063 -re "\\*\\*\\* DOSEXIT code.*" {
1064 if { $message != "" } {
1070 append code $processed_code
1072 # Reset the spawn id, in case the processed code used -i.
1078 -re "Ending remote debugging.*$prompt_regexp" {
1079 if ![isnative] then {
1080 warning "Can`t communicate to remote target."
1086 -re "Undefined\[a-z\]* command:.*$prompt_regexp" {
1087 perror "Undefined command \"$command\"."
1091 -re "Ambiguous command.*$prompt_regexp" {
1092 perror "\"$command\" is not a unique command name."
1096 -re "$inferior_exited_re with code \[0-9\]+.*$prompt_regexp" {
1097 if ![string match "" $message] then {
1098 set errmsg "$message (the program exited)"
1100 set errmsg "$command (the program exited)"
1105 -re "$inferior_exited_re normally.*$prompt_regexp" {
1106 if ![string match "" $message] then {
1107 set errmsg "$message (the program exited)"
1109 set errmsg "$command (the program exited)"
1114 -re "The program is not being run.*$prompt_regexp" {
1115 if ![string match "" $message] then {
1116 set errmsg "$message (the program is no longer running)"
1118 set errmsg "$command (the program is no longer running)"
1123 -re "\r\n$prompt_regexp" {
1124 if ![string match "" $message] then {
1129 -re "$pagination_prompt" {
1131 perror "Window too small."
1135 -re "\\((y or n|y or \\\[n\\\]|\\\[y\\\] or n)\\) " {
1136 send_gdb "n\n" answer
1137 gdb_expect -re "$prompt_regexp"
1138 fail "$message (got interactive prompt)"
1141 -re "\\\[0\\\] cancel\r\n\\\[1\\\] all.*\r\n> $" {
1143 gdb_expect -re "$prompt_regexp"
1144 fail "$message (got breakpoint menu)"
1150 perror "GDB process no longer exists"
1151 set wait_status [wait -i $gdb_spawn_id]
1152 verbose -log "GDB process exited with wait status $wait_status"
1153 if { $message != "" } {
1160 if {$line_by_line} {
1162 -re "\r\n\[^\r\n\]*(?=\r\n)" {
1168 # Now patterns that apply to any spawn id specified.
1172 perror "Process no longer exists"
1173 if { $message != "" } {
1179 perror "internal buffer is full."
1184 if ![string match "" $message] then {
1185 fail "$message (timeout)"
1191 # remote_expect calls the eof section if there is an error on the
1192 # expect call. We already have eof sections above, and we don't
1193 # want them to get called in that situation. Since the last eof
1194 # section becomes the error section, here we define another eof
1195 # section, but with an empty spawn_id list, so that it won't ever
1199 # This comment is here because the eof section must not be
1200 # the empty string, otherwise remote_expect won't realize
1205 # Create gdb_test_name in the parent scope. If this variable
1206 # already exists, which it might if we have nested calls to
1207 # gdb_test_multiple, then preserve the old value, otherwise,
1208 # create a new variable in the parent scope.
1209 upvar gdb_test_name gdb_test_name
1210 if { [info exists gdb_test_name] } {
1211 set gdb_test_name_old "$gdb_test_name"
1213 set gdb_test_name "$message"
1216 set code [catch {gdb_expect $code} string]
1218 # Clean up the gdb_test_name variable. If we had a
1219 # previous value then restore it, otherwise, delete the variable
1220 # from the parent scope.
1221 if { [info exists gdb_test_name_old] } {
1222 set gdb_test_name "$gdb_test_name_old"
1228 global errorInfo errorCode
1229 return -code error -errorinfo $errorInfo -errorcode $errorCode $string
1230 } elseif {$code > 1} {
1231 return -code $code $string
1236 # Usage: gdb_test_multiline NAME INPUT RESULT {INPUT RESULT} ...
1237 # Run a test named NAME, consisting of multiple lines of input.
1238 # After each input line INPUT, search for result line RESULT.
1239 # Succeed if all results are seen; fail otherwise.
1241 proc gdb_test_multiline { name args } {
1244 foreach {input result} $args {
1246 if {[gdb_test_multiple $input "$name: input $inputnr: $input" {
1247 -re "\[\r\n\]*($result)\[\r\n\]+($gdb_prompt | *>)$" {
1258 # gdb_test COMMAND PATTERN MESSAGE QUESTION RESPONSE
1259 # Send a command to gdb; test the result.
1261 # COMMAND is the command to execute, send to GDB with send_gdb. If
1262 # this is the null string no command is sent.
1263 # PATTERN is the pattern to match for a PASS, and must NOT include
1264 # the \r\n sequence immediately before the gdb prompt. This argument
1265 # may be omitted to just match the prompt, ignoring whatever output
1267 # MESSAGE is an optional message to be printed. If this is
1268 # omitted, then the pass/fail messages use the command string as the
1269 # message. (If this is the empty string, then sometimes we don't
1270 # call pass or fail at all; I don't understand this at all.)
1271 # QUESTION is a question GDB may ask in response to COMMAND, like
1273 # RESPONSE is the response to send if QUESTION appears.
1276 # 1 if the test failed,
1277 # 0 if the test passes,
1278 # -1 if there was an internal error.
1280 proc gdb_test { args } {
1282 upvar timeout timeout
1284 if [llength $args]>2 then {
1285 set message [lindex $args 2]
1287 set message [lindex $args 0]
1289 set command [lindex $args 0]
1290 set pattern [lindex $args 1]
1294 -re "\[\r\n\]*(?:$pattern)\[\r\n\]+$gdb_prompt $" {
1295 if ![string match "" $message] then {
1301 if { [llength $args] == 5 } {
1302 set question_string [lindex $args 3]
1303 set response_string [lindex $args 4]
1305 -re "(${question_string})$" {
1306 send_gdb "$response_string\n"
1312 set user_code [join $user_code]
1313 return [gdb_test_multiple $command $message $user_code]
1316 # Return 1 if version MAJOR.MINOR is at least AT_LEAST_MAJOR.AT_LEAST_MINOR.
1317 proc version_at_least { major minor at_least_major at_least_minor} {
1318 if { $major > $at_least_major } {
1320 } elseif { $major == $at_least_major \
1321 && $minor >= $at_least_minor } {
1328 # Return 1 if tcl version used is at least MAJOR.MINOR
1329 proc tcl_version_at_least { major minor } {
1331 regexp {^([0-9]+)\.([0-9]+)$} $tcl_version \
1332 dummy tcl_version_major tcl_version_minor
1333 return [version_at_least $tcl_version_major $tcl_version_minor \
1337 if { [tcl_version_at_least 8 5] == 0 } {
1338 # lrepeat was added in tcl 8.5. Only add if missing.
1339 proc lrepeat { n element } {
1340 if { [string is integer -strict $n] == 0 } {
1341 error "expected integer but got \"$n\""
1344 error "bad count \"$n\": must be integer >= 0"
1347 for {set i 0} {$i < $n} {incr i} {
1348 lappend res $element
1354 # gdb_test_no_output COMMAND MESSAGE
1355 # Send a command to GDB and verify that this command generated no output.
1357 # See gdb_test_multiple for a description of the COMMAND and MESSAGE
1358 # parameters. If MESSAGE is ommitted, then COMMAND will be used as
1359 # the message. (If MESSAGE is the empty string, then sometimes we do not
1360 # call pass or fail at all; I don't understand this at all.)
1362 proc gdb_test_no_output { args } {
1364 set command [lindex $args 0]
1365 if [llength $args]>1 then {
1366 set message [lindex $args 1]
1368 set message $command
1371 set command_regex [string_to_regexp $command]
1372 gdb_test_multiple $command $message {
1373 -re "^$command_regex\r\n$gdb_prompt $" {
1374 if ![string match "" $message] then {
1381 # Send a command and then wait for a sequence of outputs.
1382 # This is useful when the sequence is long and contains ".*", a single
1383 # regexp to match the entire output can get a timeout much easier.
1385 # COMMAND is the command to execute, send to GDB with send_gdb. If
1386 # this is the null string no command is sent.
1387 # TEST_NAME is passed to pass/fail. COMMAND is used if TEST_NAME is "".
1388 # EXPECTED_OUTPUT_LIST is a list of regexps of expected output, which are
1389 # processed in order, and all must be present in the output.
1391 # The -prompt switch can be used to override the prompt expected at the end of
1392 # the output sequence.
1394 # It is unnecessary to specify ".*" at the beginning or end of any regexp,
1395 # there is an implicit ".*" between each element of EXPECTED_OUTPUT_LIST.
1396 # There is also an implicit ".*" between the last regexp and the gdb prompt.
1398 # Like gdb_test and gdb_test_multiple, the output is expected to end with the
1399 # gdb prompt, which must not be specified in EXPECTED_OUTPUT_LIST.
1402 # 1 if the test failed,
1403 # 0 if the test passes,
1404 # -1 if there was an internal error.
1406 proc gdb_test_sequence { args } {
1409 parse_args {{prompt ""}}
1411 if { $prompt == "" } {
1412 set prompt "$gdb_prompt $"
1415 if { [llength $args] != 3 } {
1416 error "Unexpected # of arguments, expecting: COMMAND TEST_NAME EXPECTED_OUTPUT_LIST"
1419 lassign $args command test_name expected_output_list
1421 if { $test_name == "" } {
1422 set test_name $command
1425 lappend expected_output_list ""; # implicit ".*" before gdb prompt
1427 if { $command != "" } {
1428 send_gdb "$command\n"
1431 return [gdb_expect_list $test_name $prompt $expected_output_list]
1435 # Test that a command gives an error. For pass or fail, return
1436 # a 1 to indicate that more tests can proceed. However a timeout
1437 # is a serious error, generates a special fail message, and causes
1438 # a 0 to be returned to indicate that more tests are likely to fail
1441 proc test_print_reject { args } {
1445 if [llength $args]==2 then {
1446 set expectthis [lindex $args 1]
1448 set expectthis "should never match this bogus string"
1450 set sendthis [lindex $args 0]
1451 if $verbose>2 then {
1452 send_user "Sending \"$sendthis\" to gdb\n"
1453 send_user "Looking to match \"$expectthis\"\n"
1455 send_gdb "$sendthis\n"
1456 #FIXME: Should add timeout as parameter.
1458 -re "A .* in expression.*\\.*$gdb_prompt $" {
1459 pass "reject $sendthis"
1462 -re "Invalid syntax in expression.*$gdb_prompt $" {
1463 pass "reject $sendthis"
1466 -re "Junk after end of expression.*$gdb_prompt $" {
1467 pass "reject $sendthis"
1470 -re "Invalid number.*$gdb_prompt $" {
1471 pass "reject $sendthis"
1474 -re "Invalid character constant.*$gdb_prompt $" {
1475 pass "reject $sendthis"
1478 -re "No symbol table is loaded.*$gdb_prompt $" {
1479 pass "reject $sendthis"
1482 -re "No symbol .* in current context.*$gdb_prompt $" {
1483 pass "reject $sendthis"
1486 -re "Unmatched single quote.*$gdb_prompt $" {
1487 pass "reject $sendthis"
1490 -re "A character constant must contain at least one character.*$gdb_prompt $" {
1491 pass "reject $sendthis"
1494 -re "$expectthis.*$gdb_prompt $" {
1495 pass "reject $sendthis"
1498 -re ".*$gdb_prompt $" {
1499 fail "reject $sendthis"
1503 fail "reject $sendthis (eof or timeout)"
1510 # Same as gdb_test, but the second parameter is not a regexp,
1511 # but a string that must match exactly.
1513 proc gdb_test_exact { args } {
1514 upvar timeout timeout
1516 set command [lindex $args 0]
1518 # This applies a special meaning to a null string pattern. Without
1519 # this, "$pattern\r\n$gdb_prompt $" will match anything, including error
1520 # messages from commands that should have no output except a new
1521 # prompt. With this, only results of a null string will match a null
1524 set pattern [lindex $args 1]
1525 if [string match $pattern ""] {
1526 set pattern [string_to_regexp [lindex $args 0]]
1528 set pattern [string_to_regexp [lindex $args 1]]
1531 # It is most natural to write the pattern argument with only
1532 # embedded \n's, especially if you are trying to avoid Tcl quoting
1533 # problems. But gdb_expect really wants to see \r\n in patterns. So
1534 # transform the pattern here. First transform \r\n back to \n, in
1535 # case some users of gdb_test_exact already do the right thing.
1536 regsub -all "\r\n" $pattern "\n" pattern
1537 regsub -all "\n" $pattern "\r\n" pattern
1538 if [llength $args]==3 then {
1539 set message [lindex $args 2]
1540 return [gdb_test $command $pattern $message]
1543 return [gdb_test $command $pattern]
1546 # Wrapper around gdb_test_multiple that looks for a list of expected
1547 # output elements, but which can appear in any order.
1548 # CMD is the gdb command.
1549 # NAME is the name of the test.
1550 # ELM_FIND_REGEXP specifies how to partition the output into elements to
1552 # ELM_EXTRACT_REGEXP specifies the part of ELM_FIND_REGEXP to compare.
1553 # RESULT_MATCH_LIST is a list of exact matches for each expected element.
1554 # All elements of RESULT_MATCH_LIST must appear for the test to pass.
1556 # A typical use of ELM_FIND_REGEXP/ELM_EXTRACT_REGEXP is to extract one line
1557 # of text per element and then strip trailing \r\n's.
1559 # gdb_test_list_exact "foo" "bar" \
1560 # "\[^\r\n\]+\[\r\n\]+" \
1563 # {expected result 1} \
1564 # {expected result 2} \
1567 proc gdb_test_list_exact { cmd name elm_find_regexp elm_extract_regexp result_match_list } {
1570 set matches [lsort $result_match_list]
1572 gdb_test_multiple $cmd $name {
1573 "$cmd\[\r\n\]" { exp_continue }
1574 -re $elm_find_regexp {
1575 set str $expect_out(0,string)
1576 verbose -log "seen: $str" 3
1577 regexp -- $elm_extract_regexp $str elm_seen
1578 verbose -log "extracted: $elm_seen" 3
1579 lappend seen $elm_seen
1582 -re "$gdb_prompt $" {
1584 foreach got [lsort $seen] have $matches {
1585 if {![string equal $got $have]} {
1590 if {[string length $failed] != 0} {
1591 fail "$name ($failed not found)"
1599 # gdb_test_stdio COMMAND INFERIOR_PATTERN GDB_PATTERN MESSAGE
1600 # Send a command to gdb; expect inferior and gdb output.
1602 # See gdb_test_multiple for a description of the COMMAND and MESSAGE
1605 # INFERIOR_PATTERN is the pattern to match against inferior output.
1607 # GDB_PATTERN is the pattern to match against gdb output, and must NOT
1608 # include the \r\n sequence immediately before the gdb prompt, nor the
1609 # prompt. The default is empty.
1611 # Both inferior and gdb patterns must match for a PASS.
1613 # If MESSAGE is ommitted, then COMMAND will be used as the message.
1616 # 1 if the test failed,
1617 # 0 if the test passes,
1618 # -1 if there was an internal error.
1621 proc gdb_test_stdio {command inferior_pattern {gdb_pattern ""} {message ""}} {
1622 global inferior_spawn_id gdb_spawn_id
1625 if {$message == ""} {
1626 set message $command
1629 set inferior_matched 0
1632 # Use an indirect spawn id list, and remove the inferior spawn id
1633 # from the expected output as soon as it matches, in case
1634 # $inferior_pattern happens to be a prefix of the resulting full
1635 # gdb pattern below (e.g., "\r\n").
1636 global gdb_test_stdio_spawn_id_list
1637 set gdb_test_stdio_spawn_id_list "$inferior_spawn_id"
1639 # Note that if $inferior_spawn_id and $gdb_spawn_id are different,
1640 # then we may see gdb's output arriving before the inferior's
1642 set res [gdb_test_multiple $command $message {
1643 -i gdb_test_stdio_spawn_id_list -re "$inferior_pattern" {
1644 set inferior_matched 1
1645 if {!$gdb_matched} {
1646 set gdb_test_stdio_spawn_id_list ""
1650 -i $gdb_spawn_id -re "$gdb_pattern\r\n$gdb_prompt $" {
1652 if {!$inferior_matched} {
1660 verbose -log "inferior_matched=$inferior_matched, gdb_matched=$gdb_matched"
1665 # Wrapper around gdb_test_multiple to be used when testing expression
1666 # evaluation while 'set debug expression 1' is in effect.
1667 # Looks for some patterns that indicates the expression was rejected.
1669 # CMD is the command to execute, which should include an expression
1670 # that GDB will need to parse.
1672 # OUTPUT is the expected output pattern.
1674 # TESTNAME is the name to be used for the test, defaults to CMD if not
1676 proc gdb_test_debug_expr { cmd output {testname "" }} {
1679 if { ${testname} == "" } {
1683 gdb_test_multiple $cmd $testname {
1684 -re ".*Invalid expression.*\r\n$gdb_prompt $" {
1687 -re ".*\[\r\n\]$output\r\n$gdb_prompt $" {
1693 # get_print_expr_at_depths EXP OUTPUTS
1695 # Used for testing 'set print max-depth'. Prints the expression EXP
1696 # with 'set print max-depth' set to various depths. OUTPUTS is a list
1697 # of `n` different patterns to match at each of the depths from 0 to
1700 # This proc does one final check with the max-depth set to 'unlimited'
1701 # which is tested against the last pattern in the OUTPUTS list. The
1702 # OUTPUTS list is therefore required to match every depth from 0 to a
1703 # depth where the whole of EXP is printed with no ellipsis.
1705 # This proc leaves the 'set print max-depth' set to 'unlimited'.
1706 proc gdb_print_expr_at_depths {exp outputs} {
1707 for { set depth 0 } { $depth <= [llength $outputs] } { incr depth } {
1708 if { $depth == [llength $outputs] } {
1709 set expected_result [lindex $outputs [expr [llength $outputs] - 1]]
1710 set depth_string "unlimited"
1712 set expected_result [lindex $outputs $depth]
1713 set depth_string $depth
1716 with_test_prefix "exp='$exp': depth=${depth_string}" {
1717 gdb_test_no_output "set print max-depth ${depth_string}"
1718 gdb_test "p $exp" "$expected_result"
1725 # Issue a PASS and return true if evaluating CONDITION in the caller's
1726 # frame returns true, and issue a FAIL and return false otherwise.
1727 # MESSAGE is the pass/fail message to be printed. If MESSAGE is
1728 # omitted or is empty, then the pass/fail messages use the condition
1729 # string as the message.
1731 proc gdb_assert { condition {message ""} } {
1732 if { $message == ""} {
1733 set message $condition
1736 set code [catch {uplevel 1 expr $condition} res]
1738 # If code is 1 (TCL_ERROR), it means evaluation failed and res contains
1739 # an error message. Print the error message, and set res to 0 since we
1740 # want to return a boolean.
1741 warning "While evaluating expression in gdb_assert: $res"
1744 } elseif { !$res } {
1752 proc gdb_reinitialize_dir { subdir } {
1755 if [is_remote host] {
1760 -re "Reinitialize source path to empty.*y or n. " {
1761 send_gdb "y\n" answer
1763 -re "Source directories searched.*$gdb_prompt $" {
1764 send_gdb "dir $subdir\n"
1766 -re "Source directories searched.*$gdb_prompt $" {
1767 verbose "Dir set to $subdir"
1769 -re "$gdb_prompt $" {
1770 perror "Dir \"$subdir\" failed."
1774 -re "$gdb_prompt $" {
1775 perror "Dir \"$subdir\" failed."
1779 -re "$gdb_prompt $" {
1780 perror "Dir \"$subdir\" failed."
1786 # gdb_exit -- exit the GDB, killing the target program if necessary
1788 proc default_gdb_exit {} {
1790 global INTERNAL_GDBFLAGS GDBFLAGS
1791 global gdb_spawn_id inferior_spawn_id
1792 global inotify_log_file
1794 if ![info exists gdb_spawn_id] {
1798 verbose "Quitting $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
1800 if {[info exists inotify_log_file] && [file exists $inotify_log_file]} {
1801 set fd [open $inotify_log_file]
1802 set data [read -nonewline $fd]
1805 if {[string compare $data ""] != 0} {
1806 warning "parallel-unsafe file creations noticed"
1809 set fd [open $inotify_log_file w]
1814 if { [is_remote host] && [board_info host exists fileid] } {
1818 send_gdb "y\n" answer
1821 -re "DOSEXIT code" { }
1826 if ![is_remote host] {
1830 unset inferior_spawn_id
1833 # Load a file into the debugger.
1834 # The return value is 0 for success, -1 for failure.
1836 # This procedure also set the global variable GDB_FILE_CMD_DEBUG_INFO
1837 # to one of these values:
1839 # debug file was loaded successfully and has debug information
1840 # nodebug file was loaded successfully and has no debug information
1841 # lzma file was loaded, .gnu_debugdata found, but no LZMA support
1843 # fail file was not loaded
1845 # This procedure also set the global variable GDB_FILE_CMD_MSG to the
1846 # output of the file command in case of success.
1848 # I tried returning this information as part of the return value,
1849 # but ran into a mess because of the many re-implementations of
1850 # gdb_load in config/*.exp.
1852 # TODO: gdb.base/sepdebug.exp and gdb.stabs/weird.exp might be able to use
1853 # this if they can get more information set.
1855 proc gdb_file_cmd { arg } {
1858 global last_loaded_file
1860 # GCC for Windows target may create foo.exe given "-o foo".
1861 if { ![file exists $arg] && [file exists "$arg.exe"] } {
1865 # Save this for the benefit of gdbserver-support.exp.
1866 set last_loaded_file $arg
1868 # Set whether debug info was found.
1869 # Default to "fail".
1870 global gdb_file_cmd_debug_info gdb_file_cmd_msg
1871 set gdb_file_cmd_debug_info "fail"
1873 if [is_remote host] {
1874 set arg [remote_download host $arg]
1876 perror "download failed"
1881 # The file command used to kill the remote target. For the benefit
1882 # of the testsuite, preserve this behavior. Mark as optional so it doesn't
1883 # get written to the stdin log.
1884 send_gdb "kill\n" optional
1886 -re "Kill the program being debugged. .y or n. $" {
1887 send_gdb "y\n" answer
1888 verbose "\t\tKilling previous program being debugged"
1891 -re "$gdb_prompt $" {
1896 send_gdb "file $arg\n"
1897 set new_symbol_table 0
1898 set basename [file tail $arg]
1900 -re "(Reading symbols from.*LZMA support was disabled.*$gdb_prompt $)" {
1901 verbose "\t\tLoaded $arg into $GDB; .gnu_debugdata found but no LZMA available"
1902 set gdb_file_cmd_msg $expect_out(1,string)
1903 set gdb_file_cmd_debug_info "lzma"
1906 -re "(Reading symbols from.*no debugging symbols found.*$gdb_prompt $)" {
1907 verbose "\t\tLoaded $arg into $GDB with no debugging symbols"
1908 set gdb_file_cmd_msg $expect_out(1,string)
1909 set gdb_file_cmd_debug_info "nodebug"
1912 -re "(Reading symbols from.*$gdb_prompt $)" {
1913 verbose "\t\tLoaded $arg into $GDB"
1914 set gdb_file_cmd_msg $expect_out(1,string)
1915 set gdb_file_cmd_debug_info "debug"
1918 -re "Load new symbol table from \".*\".*y or n. $" {
1919 if { $new_symbol_table > 0 } {
1920 perror [join [list "Couldn't load $basename,"
1921 "interactive prompt loop detected."]]
1924 send_gdb "y\n" answer
1925 incr new_symbol_table
1926 set suffix "-- with new symbol table"
1927 set arg "$arg $suffix"
1928 set basename "$basename $suffix"
1931 -re "No such file or directory.*$gdb_prompt $" {
1932 perror "($basename) No such file or directory"
1935 -re "A problem internal to GDB has been detected" {
1936 perror "Couldn't load $basename into GDB (GDB internal error)."
1937 gdb_internal_error_resync
1940 -re "$gdb_prompt $" {
1941 perror "Couldn't load $basename into GDB."
1945 perror "Couldn't load $basename into GDB (timeout)."
1949 # This is an attempt to detect a core dump, but seems not to
1950 # work. Perhaps we need to match .* followed by eof, in which
1951 # gdb_expect does not seem to have a way to do that.
1952 perror "Couldn't load $basename into GDB (eof)."
1958 # Default gdb_spawn procedure.
1960 proc default_gdb_spawn { } {
1963 global INTERNAL_GDBFLAGS GDBFLAGS
1966 # Set the default value, it may be overriden later by specific testfile.
1968 # Use `set_board_info use_gdb_stub' for the board file to flag the inferior
1969 # is already started after connecting and run/attach are not supported.
1970 # This is used for the "remote" protocol. After GDB starts you should
1971 # check global $use_gdb_stub instead of the board as the testfile may force
1972 # a specific different target protocol itself.
1973 set use_gdb_stub [target_info exists use_gdb_stub]
1975 verbose "Spawning $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
1976 gdb_write_cmd_file "$GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
1978 if [info exists gdb_spawn_id] {
1982 if ![is_remote host] {
1983 if { [which $GDB] == 0 } then {
1984 perror "$GDB does not exist."
1988 set res [remote_spawn host "$GDB $INTERNAL_GDBFLAGS $GDBFLAGS [host_info gdb_opts]"]
1989 if { $res < 0 || $res == "" } {
1990 perror "Spawning $GDB failed."
1994 set gdb_spawn_id $res
1998 # Default gdb_start procedure.
2000 proc default_gdb_start { } {
2003 global inferior_spawn_id
2005 if [info exists gdb_spawn_id] {
2009 # Keep track of the number of times GDB has been launched.
2010 global gdb_instances
2020 # Default to assuming inferior I/O is done on GDB's terminal.
2021 if {![info exists inferior_spawn_id]} {
2022 set inferior_spawn_id $gdb_spawn_id
2025 # When running over NFS, particularly if running many simultaneous
2026 # tests on different hosts all using the same server, things can
2027 # get really slow. Give gdb at least 3 minutes to start up.
2029 -re "\[\r\n\]$gdb_prompt $" {
2030 verbose "GDB initialized."
2032 -re "$gdb_prompt $" {
2033 perror "GDB never initialized."
2038 perror "(timeout) GDB never initialized after 10 seconds."
2044 perror "(eof) GDB never initialized."
2050 # force the height to "unlimited", so no pagers get used
2052 send_gdb "set height 0\n"
2054 -re "$gdb_prompt $" {
2055 verbose "Setting height to 0." 2
2058 warning "Couldn't set the height to 0"
2061 # force the width to "unlimited", so no wraparound occurs
2062 send_gdb "set width 0\n"
2064 -re "$gdb_prompt $" {
2065 verbose "Setting width to 0." 2
2068 warning "Couldn't set the width to 0."
2076 # Utility procedure to give user control of the gdb prompt in a script. It is
2077 # meant to be used for debugging test cases, and should not be left in the
2080 proc gdb_interact { } {
2082 set spawn_id $gdb_spawn_id
2084 send_user "+------------------------------------------+\n"
2085 send_user "| Script interrupted, you can now interact |\n"
2086 send_user "| with by gdb. Type >>> to continue. |\n"
2087 send_user "+------------------------------------------+\n"
2094 # Examine the output of compilation to determine whether compilation
2095 # failed or not. If it failed determine whether it is due to missing
2096 # compiler or due to compiler error. Report pass, fail or unsupported
2099 proc gdb_compile_test {src output} {
2100 if { $output == "" } {
2101 pass "compilation [file tail $src]"
2102 } elseif { [regexp {^[a-zA-Z_0-9]+: Can't find [^ ]+\.$} $output] } {
2103 unsupported "compilation [file tail $src]"
2104 } elseif { [regexp {.*: command not found[\r|\n]*$} $output] } {
2105 unsupported "compilation [file tail $src]"
2106 } elseif { [regexp {.*: [^\r\n]*compiler not installed[^\r\n]*[\r|\n]*$} $output] } {
2107 unsupported "compilation [file tail $src]"
2109 verbose -log "compilation failed: $output" 2
2110 fail "compilation [file tail $src]"
2114 # Return a 1 for configurations for which we don't even want to try to
2117 proc skip_cplus_tests {} {
2118 if { [istarget "h8300-*-*"] } {
2122 # The C++ IO streams are too large for HC11/HC12 and are thus not
2123 # available. The gdb C++ tests use them and don't compile.
2124 if { [istarget "m6811-*-*"] } {
2127 if { [istarget "m6812-*-*"] } {
2133 # Return a 1 for configurations for which don't have both C++ and the STL.
2135 proc skip_stl_tests {} {
2136 return [skip_cplus_tests]
2139 # Return a 1 if I don't even want to try to test FORTRAN.
2141 proc skip_fortran_tests {} {
2145 # Return a 1 if I don't even want to try to test ada.
2147 proc skip_ada_tests {} {
2151 # Return a 1 if I don't even want to try to test GO.
2153 proc skip_go_tests {} {
2157 # Return a 1 if I don't even want to try to test D.
2159 proc skip_d_tests {} {
2163 # Return 1 to skip Rust tests, 0 to try them.
2164 proc skip_rust_tests {} {
2165 if { ![isnative] } {
2169 # The rust compiler does not support "-m32", skip.
2170 global board board_info
2171 set board [target_info name]
2172 if {[board_info $board exists multilib_flags]} {
2173 foreach flag [board_info $board multilib_flags] {
2174 if { $flag == "-m32" } {
2183 # Return a 1 for configurations that do not support Python scripting.
2184 # PROMPT_REGEXP is the expected prompt.
2186 proc skip_python_tests_prompt { prompt_regexp } {
2187 global gdb_py_is_py3k
2189 gdb_test_multiple "python print ('test')" "verify python support" \
2190 -prompt "$prompt_regexp" {
2191 -re "not supported.*$prompt_regexp" {
2192 unsupported "Python support is disabled."
2195 -re "$prompt_regexp" {}
2198 gdb_test_multiple "python print (sys.version_info\[0\])" "check if python 3" \
2199 -prompt "$prompt_regexp" {
2200 -re "3.*$prompt_regexp" {
2201 set gdb_py_is_py3k 1
2203 -re ".*$prompt_regexp" {
2204 set gdb_py_is_py3k 0
2211 # Return a 1 for configurations that do not support Python scripting.
2212 # Note: This also sets various globals that specify which version of Python
2213 # is in use. See skip_python_tests_prompt.
2215 proc skip_python_tests {} {
2217 return [skip_python_tests_prompt "$gdb_prompt $"]
2220 # Return a 1 if we should skip shared library tests.
2222 proc skip_shlib_tests {} {
2223 # Run the shared library tests on native systems.
2228 # An abbreviated list of remote targets where we should be able to
2229 # run shared library tests.
2230 if {([istarget *-*-linux*]
2231 || [istarget *-*-*bsd*]
2232 || [istarget *-*-solaris2*]
2233 || [istarget *-*-mingw*]
2234 || [istarget *-*-cygwin*]
2235 || [istarget *-*-pe*])} {
2242 # Return 1 if we should skip tui related tests.
2244 proc skip_tui_tests {} {
2247 gdb_test_multiple "help layout" "verify tui support" {
2248 -re "Undefined command: \"layout\".*$gdb_prompt $" {
2251 -re "$gdb_prompt $" {
2258 # Test files shall make sure all the test result lines in gdb.sum are
2259 # unique in a test run, so that comparing the gdb.sum files of two
2260 # test runs gives correct results. Test files that exercise
2261 # variations of the same tests more than once, shall prefix the
2262 # different test invocations with different identifying strings in
2263 # order to make them unique.
2265 # About test prefixes:
2267 # $pf_prefix is the string that dejagnu prints after the result (FAIL,
2268 # PASS, etc.), and before the test message/name in gdb.sum. E.g., the
2269 # underlined substring in
2271 # PASS: gdb.base/mytest.exp: some test
2272 # ^^^^^^^^^^^^^^^^^^^^
2276 # The easiest way to adjust the test prefix is to append a test
2277 # variation prefix to the $pf_prefix, using the with_test_prefix
2280 # proc do_tests {} {
2281 # gdb_test ... ... "test foo"
2282 # gdb_test ... ... "test bar"
2284 # with_test_prefix "subvariation a" {
2285 # gdb_test ... ... "test x"
2288 # with_test_prefix "subvariation b" {
2289 # gdb_test ... ... "test x"
2293 # with_test_prefix "variation1" {
2294 # ...do setup for variation 1...
2298 # with_test_prefix "variation2" {
2299 # ...do setup for variation 2...
2305 # PASS: gdb.base/mytest.exp: variation1: test foo
2306 # PASS: gdb.base/mytest.exp: variation1: test bar
2307 # PASS: gdb.base/mytest.exp: variation1: subvariation a: test x
2308 # PASS: gdb.base/mytest.exp: variation1: subvariation b: test x
2309 # PASS: gdb.base/mytest.exp: variation2: test foo
2310 # PASS: gdb.base/mytest.exp: variation2: test bar
2311 # PASS: gdb.base/mytest.exp: variation2: subvariation a: test x
2312 # PASS: gdb.base/mytest.exp: variation2: subvariation b: test x
2314 # If for some reason more flexibility is necessary, one can also
2315 # manipulate the pf_prefix global directly, treating it as a string.
2319 # set saved_pf_prefix
2320 # append pf_prefix "${foo}: bar"
2321 # ... actual tests ...
2322 # set pf_prefix $saved_pf_prefix
2325 # Run BODY in the context of the caller, with the current test prefix
2326 # (pf_prefix) appended with one space, then PREFIX, and then a colon.
2327 # Returns the result of BODY.
2329 proc with_test_prefix { prefix body } {
2332 set saved $pf_prefix
2333 append pf_prefix " " $prefix ":"
2334 set code [catch {uplevel 1 $body} result]
2335 set pf_prefix $saved
2338 global errorInfo errorCode
2339 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2341 return -code $code $result
2345 # Wrapper for foreach that calls with_test_prefix on each iteration,
2346 # including the iterator's name and current value in the prefix.
2348 proc foreach_with_prefix {var list body} {
2350 foreach myvar $list {
2351 with_test_prefix "$var=$myvar" {
2352 set code [catch {uplevel 1 $body} result]
2356 global errorInfo errorCode
2357 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2358 } elseif {$code == 3} {
2360 } elseif {$code == 2} {
2361 return -code $code $result
2366 # Like TCL's native proc, but defines a procedure that wraps its body
2367 # within 'with_test_prefix "$proc_name" { ... }'.
2368 proc proc_with_prefix {name arguments body} {
2369 # Define the advertised proc.
2370 proc $name $arguments [list with_test_prefix $name $body]
2374 # Run BODY in the context of the caller. After BODY is run, the variables
2375 # listed in VARS will be reset to the values they had before BODY was run.
2377 # This is useful for providing a scope in which it is safe to temporarily
2378 # modify global variables, e.g.
2380 # global INTERNAL_GDBFLAGS
2383 # set foo GDBHISTSIZE
2385 # save_vars { INTERNAL_GDBFLAGS env($foo) env(HOME) } {
2386 # append INTERNAL_GDBFLAGS " -nx"
2387 # unset -nocomplain env(GDBHISTSIZE)
2392 # Here, although INTERNAL_GDBFLAGS, env(GDBHISTSIZE) and env(HOME) may be
2393 # modified inside BODY, this proc guarantees that the modifications will be
2394 # undone after BODY finishes executing.
2396 proc save_vars { vars body } {
2397 array set saved_scalars { }
2398 array set saved_arrays { }
2402 # First evaluate VAR in the context of the caller in case the variable
2403 # name may be a not-yet-interpolated string like env($foo)
2404 set var [uplevel 1 list $var]
2406 if [uplevel 1 [list info exists $var]] {
2407 if [uplevel 1 [list array exists $var]] {
2408 set saved_arrays($var) [uplevel 1 [list array get $var]]
2410 set saved_scalars($var) [uplevel 1 [list set $var]]
2413 lappend unset_vars $var
2417 set code [catch {uplevel 1 $body} result]
2419 foreach {var value} [array get saved_scalars] {
2420 uplevel 1 [list set $var $value]
2423 foreach {var value} [array get saved_arrays] {
2424 uplevel 1 [list unset $var]
2425 uplevel 1 [list array set $var $value]
2428 foreach var $unset_vars {
2429 uplevel 1 [list unset -nocomplain $var]
2433 global errorInfo errorCode
2434 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2436 return -code $code $result
2440 # As save_vars, but for variables stored in the board_info for the
2445 # save_target_board_info { multilib_flags } {
2447 # set board [target_info name]
2448 # unset_board_info multilib_flags
2449 # set_board_info multilib_flags "$multilib_flags"
2453 proc save_target_board_info { vars body } {
2454 global board board_info
2455 set board [target_info name]
2457 array set saved_target_board_info { }
2458 set unset_target_board_info { }
2461 if { [info exists board_info($board,$var)] } {
2462 set saved_target_board_info($var) [board_info $board $var]
2464 lappend unset_target_board_info $var
2468 set code [catch {uplevel 1 $body} result]
2470 foreach {var value} [array get saved_target_board_info] {
2471 unset_board_info $var
2472 set_board_info $var $value
2475 foreach var $unset_target_board_info {
2476 unset_board_info $var
2480 global errorInfo errorCode
2481 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2483 return -code $code $result
2487 # Run tests in BODY with the current working directory (CWD) set to
2488 # DIR. When BODY is finished, restore the original CWD. Return the
2491 # This procedure doesn't check if DIR is a valid directory, so you
2492 # have to make sure of that.
2494 proc with_cwd { dir body } {
2496 verbose -log "Switching to directory $dir (saved CWD: $saved_dir)."
2499 set code [catch {uplevel 1 $body} result]
2501 verbose -log "Switching back to $saved_dir."
2505 global errorInfo errorCode
2506 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2508 return -code $code $result
2512 # Run tests in BODY with GDB prompt and variable $gdb_prompt set to
2513 # PROMPT. When BODY is finished, restore GDB prompt and variable
2515 # Returns the result of BODY.
2519 # 1) If you want to use, for example, "(foo)" as the prompt you must pass it
2520 # as "(foo)", and not the regexp form "\(foo\)" (expressed as "\\(foo\\)" in
2521 # TCL). PROMPT is internally converted to a suitable regexp for matching.
2522 # We do the conversion from "(foo)" to "\(foo\)" here for a few reasons:
2523 # a) It's more intuitive for callers to pass the plain text form.
2524 # b) We need two forms of the prompt:
2525 # - a regexp to use in output matching,
2526 # - a value to pass to the "set prompt" command.
2527 # c) It's easier to convert the plain text form to its regexp form.
2529 # 2) Don't add a trailing space, we do that here.
2531 proc with_gdb_prompt { prompt body } {
2534 # Convert "(foo)" to "\(foo\)".
2535 # We don't use string_to_regexp because while it works today it's not
2536 # clear it will work tomorrow: the value we need must work as both a
2537 # regexp *and* as the argument to the "set prompt" command, at least until
2538 # we start recording both forms separately instead of just $gdb_prompt.
2539 # The testsuite is pretty-much hardwired to interpret $gdb_prompt as the
2541 regsub -all {[]*+.|()^$\[\\]} $prompt {\\&} prompt
2543 set saved $gdb_prompt
2545 verbose -log "Setting gdb prompt to \"$prompt \"."
2546 set gdb_prompt $prompt
2547 gdb_test_no_output "set prompt $prompt " ""
2549 set code [catch {uplevel 1 $body} result]
2551 verbose -log "Restoring gdb prompt to \"$saved \"."
2552 set gdb_prompt $saved
2553 gdb_test_no_output "set prompt $saved " ""
2556 global errorInfo errorCode
2557 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2559 return -code $code $result
2563 # Run tests in BODY with target-charset setting to TARGET_CHARSET. When
2564 # BODY is finished, restore target-charset.
2566 proc with_target_charset { target_charset body } {
2570 gdb_test_multiple "show target-charset" "" {
2571 -re "The target character set is \".*; currently (.*)\"\..*$gdb_prompt " {
2572 set saved $expect_out(1,string)
2574 -re "The target character set is \"(.*)\".*$gdb_prompt " {
2575 set saved $expect_out(1,string)
2577 -re ".*$gdb_prompt " {
2578 fail "get target-charset"
2582 gdb_test_no_output "set target-charset $target_charset" ""
2584 set code [catch {uplevel 1 $body} result]
2586 gdb_test_no_output "set target-charset $saved" ""
2589 global errorInfo errorCode
2590 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2592 return -code $code $result
2596 # Switch the default spawn id to SPAWN_ID, so that gdb_test,
2597 # mi_gdb_test etc. default to using it.
2599 proc switch_gdb_spawn_id {spawn_id} {
2601 global board board_info
2603 set gdb_spawn_id $spawn_id
2604 set board [host_info name]
2605 set board_info($board,fileid) $spawn_id
2608 # Clear the default spawn id.
2610 proc clear_gdb_spawn_id {} {
2612 global board board_info
2614 unset -nocomplain gdb_spawn_id
2615 set board [host_info name]
2616 unset -nocomplain board_info($board,fileid)
2619 # Run BODY with SPAWN_ID as current spawn id.
2621 proc with_spawn_id { spawn_id body } {
2624 if [info exists gdb_spawn_id] {
2625 set saved_spawn_id $gdb_spawn_id
2628 switch_gdb_spawn_id $spawn_id
2630 set code [catch {uplevel 1 $body} result]
2632 if [info exists saved_spawn_id] {
2633 switch_gdb_spawn_id $saved_spawn_id
2639 global errorInfo errorCode
2640 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2642 return -code $code $result
2646 # Select the largest timeout from all the timeouts:
2647 # - the local "timeout" variable of the scope two levels above,
2648 # - the global "timeout" variable,
2649 # - the board variable "gdb,timeout".
2651 proc get_largest_timeout {} {
2652 upvar #0 timeout gtimeout
2653 upvar 2 timeout timeout
2656 if [info exists timeout] {
2659 if { [info exists gtimeout] && $gtimeout > $tmt } {
2662 if { [target_info exists gdb,timeout]
2663 && [target_info gdb,timeout] > $tmt } {
2664 set tmt [target_info gdb,timeout]
2674 # Run tests in BODY with timeout increased by factor of FACTOR. When
2675 # BODY is finished, restore timeout.
2677 proc with_timeout_factor { factor body } {
2680 set savedtimeout $timeout
2682 set timeout [expr [get_largest_timeout] * $factor]
2683 set code [catch {uplevel 1 $body} result]
2685 set timeout $savedtimeout
2687 global errorInfo errorCode
2688 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2690 return -code $code $result
2694 # Run BODY with timeout factor FACTOR if check-read1 is used.
2696 proc with_read1_timeout_factor { factor body } {
2697 if { [info exists ::env(READ1)] == 1 && $::env(READ1) == 1 } {
2698 # Use timeout factor
2700 # Reset timeout factor
2703 return [uplevel [list with_timeout_factor $factor $body]]
2706 # Return 1 if _Complex types are supported, otherwise, return 0.
2708 gdb_caching_proc support_complex_tests {
2710 if { [gdb_skip_float_test] } {
2711 # If floating point is not supported, _Complex is not
2716 # Compile a test program containing _Complex types.
2718 return [gdb_can_simple_compile complex {
2722 _Complex long double cld;
2728 # Return 1 if compiling go is supported.
2729 gdb_caching_proc support_go_compile {
2731 return [gdb_can_simple_compile go-hello {
2735 fmt.Println("hello world")
2740 # Return 1 if GDB can get a type for siginfo from the target, otherwise
2743 proc supports_get_siginfo_type {} {
2744 if { [istarget "*-*-linux*"] } {
2751 # Return 1 if the target supports hardware single stepping.
2753 proc can_hardware_single_step {} {
2755 if { [istarget "arm*-*-*"] || [istarget "mips*-*-*"]
2756 || [istarget "tic6x-*-*"] || [istarget "sparc*-*-linux*"]
2757 || [istarget "nios2-*-*"] } {
2764 # Return 1 if target hardware or OS supports single stepping to signal
2765 # handler, otherwise, return 0.
2767 proc can_single_step_to_signal_handler {} {
2768 # Targets don't have hardware single step. On these targets, when
2769 # a signal is delivered during software single step, gdb is unable
2770 # to determine the next instruction addresses, because start of signal
2771 # handler is one of them.
2772 return [can_hardware_single_step]
2775 # Return 1 if target supports process record, otherwise return 0.
2777 proc supports_process_record {} {
2779 if [target_info exists gdb,use_precord] {
2780 return [target_info gdb,use_precord]
2783 if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
2784 || [istarget "i\[34567\]86-*-linux*"]
2785 || [istarget "aarch64*-*-linux*"]
2786 || [istarget "powerpc*-*-linux*"]
2787 || [istarget "s390*-*-linux*"] } {
2794 # Return 1 if target supports reverse debugging, otherwise return 0.
2796 proc supports_reverse {} {
2798 if [target_info exists gdb,can_reverse] {
2799 return [target_info gdb,can_reverse]
2802 if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
2803 || [istarget "i\[34567\]86-*-linux*"]
2804 || [istarget "aarch64*-*-linux*"]
2805 || [istarget "powerpc*-*-linux*"]
2806 || [istarget "s390*-*-linux*"] } {
2813 # Return 1 if readline library is used.
2815 proc readline_is_used { } {
2818 gdb_test_multiple "show editing" "" {
2819 -re ".*Editing of command lines as they are typed is on\..*$gdb_prompt $" {
2822 -re ".*$gdb_prompt $" {
2828 # Return 1 if target is ELF.
2829 gdb_caching_proc is_elf_target {
2830 set me "is_elf_target"
2832 set src { int foo () {return 0;} }
2833 if {![gdb_simple_compile elf_target $src]} {
2837 set fp_obj [open $obj "r"]
2838 fconfigure $fp_obj -translation binary
2839 set data [read $fp_obj]
2844 set ELFMAG "\u007FELF"
2846 if {[string compare -length 4 $data $ELFMAG] != 0} {
2847 verbose "$me: returning 0" 2
2851 verbose "$me: returning 1" 2
2855 # Return 1 if the memory at address zero is readable.
2857 gdb_caching_proc is_address_zero_readable {
2861 gdb_test_multiple "x 0" "" {
2862 -re "Cannot access memory at address 0x0.*$gdb_prompt $" {
2865 -re ".*$gdb_prompt $" {
2873 # Produce source file NAME and write SOURCES into it.
2875 proc gdb_produce_source { name sources } {
2877 set f [open $name "w"]
2883 # Return 1 if target is ILP32.
2884 # This cannot be decided simply from looking at the target string,
2885 # as it might depend on externally passed compiler options like -m64.
2886 gdb_caching_proc is_ilp32_target {
2887 return [gdb_can_simple_compile is_ilp32_target {
2888 int dummy[sizeof (int) == 4
2889 && sizeof (void *) == 4
2890 && sizeof (long) == 4 ? 1 : -1];
2894 # Return 1 if target is LP64.
2895 # This cannot be decided simply from looking at the target string,
2896 # as it might depend on externally passed compiler options like -m64.
2897 gdb_caching_proc is_lp64_target {
2898 return [gdb_can_simple_compile is_lp64_target {
2899 int dummy[sizeof (int) == 4
2900 && sizeof (void *) == 8
2901 && sizeof (long) == 8 ? 1 : -1];
2905 # Return 1 if target has 64 bit addresses.
2906 # This cannot be decided simply from looking at the target string,
2907 # as it might depend on externally passed compiler options like -m64.
2908 gdb_caching_proc is_64_target {
2909 return [gdb_can_simple_compile is_64_target {
2910 int function(void) { return 3; }
2911 int dummy[sizeof (&function) == 8 ? 1 : -1];
2915 # Return 1 if target has x86_64 registers - either amd64 or x32.
2916 # x32 target identifies as x86_64-*-linux*, therefore it cannot be determined
2917 # just from the target string.
2918 gdb_caching_proc is_amd64_regs_target {
2919 if {![istarget "x86_64-*-*"] && ![istarget "i?86-*"]} {
2923 return [gdb_can_simple_compile is_amd64_regs_target {
2933 # Return 1 if this target is an x86 or x86-64 with -m32.
2934 proc is_x86_like_target {} {
2935 if {![istarget "x86_64-*-*"] && ![istarget i?86-*]} {
2938 return [expr [is_ilp32_target] && ![is_amd64_regs_target]]
2941 # Return 1 if this target is an arm or aarch32 on aarch64.
2943 gdb_caching_proc is_aarch32_target {
2944 if { [istarget "arm*-*-*"] } {
2948 if { ![istarget "aarch64*-*-*"] } {
2955 lappend list "\tmov $reg, $reg"
2958 return [gdb_can_simple_compile aarch32 [join $list \n]]
2961 # Return 1 if this target is an aarch64, either lp64 or ilp32.
2963 proc is_aarch64_target {} {
2964 if { ![istarget "aarch64*-*-*"] } {
2968 return [expr ![is_aarch32_target]]
2971 # Return 1 if displaced stepping is supported on target, otherwise, return 0.
2972 proc support_displaced_stepping {} {
2974 if { [istarget "x86_64-*-linux*"] || [istarget "i\[34567\]86-*-linux*"]
2975 || [istarget "arm*-*-linux*"] || [istarget "powerpc-*-linux*"]
2976 || [istarget "powerpc64-*-linux*"] || [istarget "s390*-*-*"]
2977 || [istarget "aarch64*-*-linux*"] } {
2984 # Run a test on the target to see if it supports vmx hardware. Return 0 if so,
2985 # 1 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
2987 gdb_caching_proc skip_altivec_tests {
2988 global srcdir subdir gdb_prompt inferior_exited_re
2990 set me "skip_altivec_tests"
2992 # Some simulators are known to not support VMX instructions.
2993 if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
2994 verbose "$me: target known to not support VMX, returning 1" 2
2998 # Make sure we have a compiler that understands altivec.
2999 if [get_compiler_info] {
3000 warning "Could not get compiler info"
3003 if [test_compiler_info gcc*] {
3004 set compile_flags "additional_flags=-maltivec"
3005 } elseif [test_compiler_info xlc*] {
3006 set compile_flags "additional_flags=-qaltivec"
3008 verbose "Could not compile with altivec support, returning 1" 2
3012 # Compile a test program containing VMX instructions.
3016 asm volatile ("vor v0,v0,v0");
3018 asm volatile ("vor 0,0,0");
3023 if {![gdb_simple_compile $me $src executable $compile_flags]} {
3027 # Compilation succeeded so now run it via gdb.
3031 gdb_reinitialize_dir $srcdir/$subdir
3035 -re ".*Illegal instruction.*${gdb_prompt} $" {
3036 verbose -log "\n$me altivec hardware not detected"
3037 set skip_vmx_tests 1
3039 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3040 verbose -log "\n$me: altivec hardware detected"
3041 set skip_vmx_tests 0
3044 warning "\n$me: default case taken"
3045 set skip_vmx_tests 1
3049 remote_file build delete $obj
3051 verbose "$me: returning $skip_vmx_tests" 2
3052 return $skip_vmx_tests
3055 # Run a test on the target to see if it supports vmx hardware. Return 0 if so,
3056 # 1 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3058 gdb_caching_proc skip_vsx_tests {
3059 global srcdir subdir gdb_prompt inferior_exited_re
3061 set me "skip_vsx_tests"
3063 # Some simulators are known to not support Altivec instructions, so
3064 # they won't support VSX instructions as well.
3065 if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
3066 verbose "$me: target known to not support VSX, returning 1" 2
3070 # Make sure we have a compiler that understands altivec.
3071 if [get_compiler_info] {
3072 warning "Could not get compiler info"
3075 if [test_compiler_info gcc*] {
3076 set compile_flags "additional_flags=-mvsx"
3077 } elseif [test_compiler_info xlc*] {
3078 set compile_flags "additional_flags=-qasm=gcc"
3080 verbose "Could not compile with vsx support, returning 1" 2
3084 # Compile a test program containing VSX instructions.
3087 double a[2] = { 1.0, 2.0 };
3089 asm volatile ("lxvd2x v0,v0,%[addr]" : : [addr] "r" (a));
3091 asm volatile ("lxvd2x 0,0,%[addr]" : : [addr] "r" (a));
3096 if {![gdb_simple_compile $me $src executable $compile_flags]} {
3100 # No error message, compilation succeeded so now run it via gdb.
3104 gdb_reinitialize_dir $srcdir/$subdir
3108 -re ".*Illegal instruction.*${gdb_prompt} $" {
3109 verbose -log "\n$me VSX hardware not detected"
3110 set skip_vsx_tests 1
3112 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3113 verbose -log "\n$me: VSX hardware detected"
3114 set skip_vsx_tests 0
3117 warning "\n$me: default case taken"
3118 set skip_vsx_tests 1
3122 remote_file build delete $obj
3124 verbose "$me: returning $skip_vsx_tests" 2
3125 return $skip_vsx_tests
3128 # Run a test on the target to see if it supports TSX hardware. Return 0 if so,
3129 # 1 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3131 gdb_caching_proc skip_tsx_tests {
3132 global srcdir subdir gdb_prompt inferior_exited_re
3134 set me "skip_tsx_tests"
3136 # Compile a test program.
3139 asm volatile ("xbegin .L0");
3140 asm volatile ("xend");
3141 asm volatile (".L0: nop");
3145 if {![gdb_simple_compile $me $src executable]} {
3149 # No error message, compilation succeeded so now run it via gdb.
3153 gdb_reinitialize_dir $srcdir/$subdir
3157 -re ".*Illegal instruction.*${gdb_prompt} $" {
3158 verbose -log "$me: TSX hardware not detected."
3159 set skip_tsx_tests 1
3161 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3162 verbose -log "$me: TSX hardware detected."
3163 set skip_tsx_tests 0
3166 warning "\n$me: default case taken."
3167 set skip_tsx_tests 1
3171 remote_file build delete $obj
3173 verbose "$me: returning $skip_tsx_tests" 2
3174 return $skip_tsx_tests
3177 # Run a test on the target to see if it supports avx512bf16. Return 0 if so,
3178 # 1 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3180 gdb_caching_proc skip_avx512bf16_tests {
3181 global srcdir subdir gdb_prompt inferior_exited_re
3183 set me "skip_avx512bf16_tests"
3184 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
3185 verbose "$me: target does not support avx512bf16, returning 1" 2
3189 # Compile a test program.
3192 asm volatile ("vcvtne2ps2bf16 %xmm0, %xmm1, %xmm0");
3196 if {![gdb_simple_compile $me $src executable]} {
3200 # No error message, compilation succeeded so now run it via gdb.
3204 gdb_reinitialize_dir $srcdir/$subdir
3208 -re ".*Illegal instruction.*${gdb_prompt} $" {
3209 verbose -log "$me: avx512bf16 hardware not detected."
3210 set skip_avx512bf16_tests 1
3212 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3213 verbose -log "$me: avx512bf16 hardware detected."
3214 set skip_avx512bf16_tests 0
3217 warning "\n$me: default case taken."
3218 set skip_avx512bf16_tests 1
3222 remote_file build delete $obj
3224 verbose "$me: returning $skip_avx512bf16_tests" 2
3225 return $skip_avx512bf16_tests
3228 # Run a test on the target to see if it supports btrace hardware. Return 0 if so,
3229 # 1 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3231 gdb_caching_proc skip_btrace_tests {
3232 global srcdir subdir gdb_prompt inferior_exited_re
3234 set me "skip_btrace_tests"
3235 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
3236 verbose "$me: target does not support btrace, returning 1" 2
3240 # Compile a test program.
3241 set src { int main() { return 0; } }
3242 if {![gdb_simple_compile $me $src executable]} {
3246 # No error message, compilation succeeded so now run it via gdb.
3250 gdb_reinitialize_dir $srcdir/$subdir
3255 # In case of an unexpected output, we return 2 as a fail value.
3256 set skip_btrace_tests 2
3257 gdb_test_multiple "record btrace" "check btrace support" {
3258 -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
3259 set skip_btrace_tests 1
3261 -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
3262 set skip_btrace_tests 1
3264 -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
3265 set skip_btrace_tests 1
3267 -re "^record btrace\r\n$gdb_prompt $" {
3268 set skip_btrace_tests 0
3272 remote_file build delete $obj
3274 verbose "$me: returning $skip_btrace_tests" 2
3275 return $skip_btrace_tests
3278 # Run a test on the target to see if it supports btrace pt hardware.
3279 # Return 0 if so, 1 if it does not. Based on 'check_vmx_hw_available'
3280 # from the GCC testsuite.
3282 gdb_caching_proc skip_btrace_pt_tests {
3283 global srcdir subdir gdb_prompt inferior_exited_re
3285 set me "skip_btrace_tests"
3286 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
3287 verbose "$me: target does not support btrace, returning 1" 2
3291 # Compile a test program.
3292 set src { int main() { return 0; } }
3293 if {![gdb_simple_compile $me $src executable]} {
3297 # No error message, compilation succeeded so now run it via gdb.
3301 gdb_reinitialize_dir $srcdir/$subdir
3306 # In case of an unexpected output, we return 2 as a fail value.
3307 set skip_btrace_tests 2
3308 gdb_test_multiple "record btrace pt" "check btrace pt support" {
3309 -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
3310 set skip_btrace_tests 1
3312 -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
3313 set skip_btrace_tests 1
3315 -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
3316 set skip_btrace_tests 1
3318 -re "support was disabled at compile time.*\r\n$gdb_prompt $" {
3319 set skip_btrace_tests 1
3321 -re "^record btrace pt\r\n$gdb_prompt $" {
3322 set skip_btrace_tests 0
3326 remote_file build delete $obj
3328 verbose "$me: returning $skip_btrace_tests" 2
3329 return $skip_btrace_tests
3332 # Run a test on the target to see if it supports Aarch64 SVE hardware.
3333 # Return 0 if so, 1 if it does not. Note this causes a restart of GDB.
3335 gdb_caching_proc skip_aarch64_sve_tests {
3336 global srcdir subdir gdb_prompt inferior_exited_re
3338 set me "skip_aarch64_sve_tests"
3340 if { ![is_aarch64_target]} {
3344 set compile_flags "{additional_flags=-march=armv8-a+sve}"
3346 # Compile a test program containing SVE instructions.
3349 asm volatile ("ptrue p0.b");
3353 if {![gdb_simple_compile $me $src executable $compile_flags]} {
3357 # Compilation succeeded so now run it via gdb.
3361 -re ".*Illegal instruction.*${gdb_prompt} $" {
3362 verbose -log "\n$me sve hardware not detected"
3363 set skip_sve_tests 1
3365 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3366 verbose -log "\n$me: sve hardware detected"
3367 set skip_sve_tests 0
3370 warning "\n$me: default case taken"
3371 set skip_sve_tests 1
3375 remote_file build delete $obj
3377 verbose "$me: returning $skip_sve_tests" 2
3378 return $skip_sve_tests
3382 # A helper that compiles a test case to see if __int128 is supported.
3383 proc gdb_int128_helper {lang} {
3384 return [gdb_can_simple_compile "i128-for-$lang" {
3386 int main() { return 0; }
3390 # Return true if the C compiler understands the __int128 type.
3391 gdb_caching_proc has_int128_c {
3392 return [gdb_int128_helper c]
3395 # Return true if the C++ compiler understands the __int128 type.
3396 gdb_caching_proc has_int128_cxx {
3397 return [gdb_int128_helper c++]
3400 # Return true if the IFUNC feature is unsupported.
3401 gdb_caching_proc skip_ifunc_tests {
3402 if [gdb_can_simple_compile ifunc {
3404 typedef void F (void);
3405 F* g (void) { return &f_; }
3406 void f () __attribute__ ((ifunc ("g")));
3414 # Return whether we should skip tests for showing inlined functions in
3415 # backtraces. Requires get_compiler_info and get_debug_format.
3417 proc skip_inline_frame_tests {} {
3418 # GDB only recognizes inlining information in DWARF 2 (DWARF 3).
3419 if { ! [test_debug_format "DWARF 2"] } {
3423 # GCC before 4.1 does not emit DW_AT_call_file / DW_AT_call_line.
3424 if { ([test_compiler_info "gcc-2-*"]
3425 || [test_compiler_info "gcc-3-*"]
3426 || [test_compiler_info "gcc-4-0-*"]) } {
3433 # Return whether we should skip tests for showing variables from
3434 # inlined functions. Requires get_compiler_info and get_debug_format.
3436 proc skip_inline_var_tests {} {
3437 # GDB only recognizes inlining information in DWARF 2 (DWARF 3).
3438 if { ! [test_debug_format "DWARF 2"] } {
3445 # Return a 1 if we should skip tests that require hardware breakpoints
3447 proc skip_hw_breakpoint_tests {} {
3448 # Skip tests if requested by the board (note that no_hardware_watchpoints
3449 # disables both watchpoints and breakpoints)
3450 if { [target_info exists gdb,no_hardware_watchpoints]} {
3454 # These targets support hardware breakpoints natively
3455 if { [istarget "i?86-*-*"]
3456 || [istarget "x86_64-*-*"]
3457 || [istarget "ia64-*-*"]
3458 || [istarget "arm*-*-*"]
3459 || [istarget "aarch64*-*-*"]
3460 || [istarget "s390*-*-*"] } {
3467 # Return a 1 if we should skip tests that require hardware watchpoints
3469 proc skip_hw_watchpoint_tests {} {
3470 # Skip tests if requested by the board
3471 if { [target_info exists gdb,no_hardware_watchpoints]} {
3475 # These targets support hardware watchpoints natively
3476 if { [istarget "i?86-*-*"]
3477 || [istarget "x86_64-*-*"]
3478 || [istarget "ia64-*-*"]
3479 || [istarget "arm*-*-*"]
3480 || [istarget "aarch64*-*-*"]
3481 || [istarget "powerpc*-*-linux*"]
3482 || [istarget "s390*-*-*"] } {
3489 # Return a 1 if we should skip tests that require *multiple* hardware
3490 # watchpoints to be active at the same time
3492 proc skip_hw_watchpoint_multi_tests {} {
3493 if { [skip_hw_watchpoint_tests] } {
3497 # These targets support just a single hardware watchpoint
3498 if { [istarget "arm*-*-*"]
3499 || [istarget "powerpc*-*-linux*"] } {
3506 # Return a 1 if we should skip tests that require read/access watchpoints
3508 proc skip_hw_watchpoint_access_tests {} {
3509 if { [skip_hw_watchpoint_tests] } {
3513 # These targets support just write watchpoints
3514 if { [istarget "s390*-*-*"] } {
3521 # Return 1 if we should skip tests that require the runtime unwinder
3522 # hook. This must be invoked while gdb is running, after shared
3523 # libraries have been loaded. This is needed because otherwise a
3524 # shared libgcc won't be visible.
3526 proc skip_unwinder_tests {} {
3530 gdb_test_multiple "print _Unwind_DebugHook" "check for unwinder hook" {
3531 -re "= .*no debug info.*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
3533 -re "= .*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
3536 -re "No symbol .* in current context.\r\n$gdb_prompt $" {
3540 gdb_test_multiple "info probe" "check for stap probe in unwinder" {
3541 -re ".*libgcc.*unwind.*\r\n$gdb_prompt $" {
3544 -re "\r\n$gdb_prompt $" {
3551 # Return 1 if we should skip tests that require the libstdc++ stap
3552 # probes. This must be invoked while gdb is running, after shared
3553 # libraries have been loaded. PROMPT_REGEXP is the expected prompt.
3555 proc skip_libstdcxx_probe_tests_prompt { prompt_regexp } {
3557 gdb_test_multiple "info probe" "check for stap probe in libstdc++" \
3558 -prompt "$prompt_regexp" {
3559 -re ".*libstdcxx.*catch.*\r\n$prompt_regexp" {
3562 -re "\r\n$prompt_regexp" {
3565 set skip [expr !$supported]
3569 # As skip_libstdcxx_probe_tests_prompt, with gdb_prompt.
3571 proc skip_libstdcxx_probe_tests {} {
3573 return [skip_libstdcxx_probe_tests_prompt "$gdb_prompt $"]
3576 # Return 1 if we should skip tests of the "compile" feature.
3577 # This must be invoked after the inferior has been started.
3579 proc skip_compile_feature_tests {} {
3583 gdb_test_multiple "compile code -- ;" "check for working compile command" {
3584 "Could not load libcc1.*\r\n$gdb_prompt $" {
3587 -re "Command not supported on this host\\..*\r\n$gdb_prompt $" {
3590 -re "\r\n$gdb_prompt $" {
3596 # Helper for gdb_is_target_* procs. TARGET_NAME is the name of the target
3597 # we're looking for (used to build the test name). TARGET_STACK_REGEXP
3598 # is a regexp that will match the output of "maint print target-stack" if
3599 # the target in question is currently pushed. PROMPT_REGEXP is a regexp
3600 # matching the expected prompt after the command output.
3602 proc gdb_is_target_1 { target_name target_stack_regexp prompt_regexp } {
3603 set test "probe for target ${target_name}"
3604 gdb_test_multiple "maint print target-stack" $test \
3605 -prompt "$prompt_regexp" {
3606 -re "${target_stack_regexp}${prompt_regexp}" {
3610 -re "$prompt_regexp" {
3617 # Helper for gdb_is_target_remote where the expected prompt is variable.
3619 proc gdb_is_target_remote_prompt { prompt_regexp } {
3620 return [gdb_is_target_1 "remote" ".*emote serial target in gdb-specific protocol.*" $prompt_regexp]
3623 # Check whether we're testing with the remote or extended-remote
3626 proc gdb_is_target_remote { } {
3629 return [gdb_is_target_remote_prompt "$gdb_prompt $"]
3632 # Check whether we're testing with the native target.
3634 proc gdb_is_target_native { } {
3637 return [gdb_is_target_1 "native" ".*native \\(Native process\\).*" "$gdb_prompt $"]
3640 # Return the effective value of use_gdb_stub.
3642 # If the use_gdb_stub global has been set (it is set when the gdb process is
3643 # spawned), return that. Otherwise, return the value of the use_gdb_stub
3644 # property from the board file.
3646 # This is the preferred way of checking use_gdb_stub, since it allows to check
3647 # the value before the gdb has been spawned and it will return the correct value
3648 # even when it was overriden by the test.
3650 # Note that stub targets are not able to spawn new inferiors. Use this
3651 # check for skipping respective tests.
3653 proc use_gdb_stub {} {
3656 if [info exists use_gdb_stub] {
3657 return $use_gdb_stub
3660 return [target_info exists use_gdb_stub]
3663 # Return 1 if the current remote target is an instance of our GDBserver, 0
3664 # otherwise. Return -1 if there was an error and we can't tell.
3666 gdb_caching_proc target_is_gdbserver {
3670 set test "probing for GDBserver"
3672 gdb_test_multiple "monitor help" $test {
3673 -re "The following monitor commands are supported.*Quit GDBserver.*$gdb_prompt $" {
3676 -re "$gdb_prompt $" {
3681 if { $is_gdbserver == -1 } {
3682 verbose -log "Unable to tell whether we are using GDBserver or not."
3685 return $is_gdbserver
3688 # N.B. compiler_info is intended to be local to this file.
3689 # Call test_compiler_info with no arguments to fetch its value.
3690 # Yes, this is counterintuitive when there's get_compiler_info,
3691 # but that's the current API.
3692 if [info exists compiler_info] {
3698 # Figure out what compiler I am using.
3699 # The result is cached so only the first invocation runs the compiler.
3701 # ARG can be empty or "C++". If empty, "C" is assumed.
3703 # There are several ways to do this, with various problems.
3705 # [ gdb_compile -E $ifile -o $binfile.ci ]
3706 # source $binfile.ci
3708 # Single Unix Spec v3 says that "-E -o ..." together are not
3709 # specified. And in fact, the native compiler on hp-ux 11 (among
3710 # others) does not work with "-E -o ...". Most targets used to do
3711 # this, and it mostly worked, because it works with gcc.
3713 # [ catch "exec $compiler -E $ifile > $binfile.ci" exec_output ]
3714 # source $binfile.ci
3716 # This avoids the problem with -E and -o together. This almost works
3717 # if the build machine is the same as the host machine, which is
3718 # usually true of the targets which are not gcc. But this code does
3719 # not figure which compiler to call, and it always ends up using the C
3720 # compiler. Not good for setting hp_aCC_compiler. Target
3721 # hppa*-*-hpux* used to do this.
3723 # [ gdb_compile -E $ifile > $binfile.ci ]
3724 # source $binfile.ci
3726 # dejagnu target_compile says that it supports output redirection,
3727 # but the code is completely different from the normal path and I
3728 # don't want to sweep the mines from that path. So I didn't even try
3731 # set cppout [ gdb_compile $ifile "" preprocess $args quiet ]
3734 # I actually do this for all targets now. gdb_compile runs the right
3735 # compiler, and TCL captures the output, and I eval the output.
3737 # Unfortunately, expect logs the output of the command as it goes by,
3738 # and dejagnu helpfully prints a second copy of it right afterwards.
3739 # So I turn off expect logging for a moment.
3741 # [ gdb_compile $ifile $ciexe_file executable $args ]
3742 # [ remote_exec $ciexe_file ]
3743 # [ source $ci_file.out ]
3745 # I could give up on -E and just do this.
3746 # I didn't get desperate enough to try this.
3748 # -- chastain 2004-01-06
3750 proc get_compiler_info {{arg ""}} {
3751 # For compiler.c and compiler.cc
3754 # I am going to play with the log to keep noise out.
3758 # These come from compiler.c or compiler.cc
3759 global compiler_info
3761 # Legacy global data symbols.
3764 if [info exists compiler_info] {
3769 # Choose which file to preprocess.
3770 set ifile "${srcdir}/lib/compiler.c"
3771 if { $arg == "c++" } {
3772 set ifile "${srcdir}/lib/compiler.cc"
3775 # Run $ifile through the right preprocessor.
3776 # Toggle gdb.log to keep the compiler output out of the log.
3777 set saved_log [log_file -info]
3779 if [is_remote host] {
3780 # We have to use -E and -o together, despite the comments
3781 # above, because of how DejaGnu handles remote host testing.
3782 set ppout "$outdir/compiler.i"
3783 gdb_compile "${ifile}" "$ppout" preprocess [list "$arg" quiet getting_compiler_info]
3784 set file [open $ppout r]
3785 set cppout [read $file]
3788 set cppout [ gdb_compile "${ifile}" "" preprocess [list "$arg" quiet getting_compiler_info] ]
3790 eval log_file $saved_log
3794 foreach cppline [ split "$cppout" "\n" ] {
3795 if { [ regexp "^#" "$cppline" ] } {
3797 } elseif { [ regexp "^\[\n\r\t \]*$" "$cppline" ] } {
3799 } elseif { [ regexp "^\[\n\r\t \]*set\[\n\r\t \]" "$cppline" ] } {
3801 verbose "get_compiler_info: $cppline" 2
3805 verbose -log "get_compiler_info: $cppline"
3810 # Set to unknown if for some reason compiler_info didn't get defined.
3811 if ![info exists compiler_info] {
3812 verbose -log "get_compiler_info: compiler_info not provided"
3813 set compiler_info "unknown"
3815 # Also set to unknown compiler if any diagnostics happened.
3817 verbose -log "get_compiler_info: got unexpected diagnostics"
3818 set compiler_info "unknown"
3821 # Set the legacy symbols.
3823 regexp "^gcc-(\[0-9\]+)-" "$compiler_info" matchall gcc_compiled
3825 # Log what happened.
3826 verbose -log "get_compiler_info: $compiler_info"
3828 # Most compilers will evaluate comparisons and other boolean
3829 # operations to 0 or 1.
3830 uplevel \#0 { set true 1 }
3831 uplevel \#0 { set false 0 }
3836 # Return the compiler_info string if no arg is provided.
3837 # Otherwise the argument is a glob-style expression to match against
3840 proc test_compiler_info { {compiler ""} } {
3841 global compiler_info
3844 # If no arg, return the compiler_info string.
3845 if [string match "" $compiler] {
3846 return $compiler_info
3849 return [string match $compiler $compiler_info]
3852 proc current_target_name { } {
3854 if [info exists target_info(target,name)] {
3855 set answer $target_info(target,name)
3862 set gdb_wrapper_initialized 0
3863 set gdb_wrapper_target ""
3864 set gdb_wrapper_file ""
3865 set gdb_wrapper_flags ""
3867 proc gdb_wrapper_init { args } {
3868 global gdb_wrapper_initialized
3869 global gdb_wrapper_file
3870 global gdb_wrapper_flags
3871 global gdb_wrapper_target
3873 if { $gdb_wrapper_initialized == 1 } { return; }
3875 if {[target_info exists needs_status_wrapper] && \
3876 [target_info needs_status_wrapper] != "0"} {
3877 set result [build_wrapper "testglue.o"]
3878 if { $result != "" } {
3879 set gdb_wrapper_file [lindex $result 0]
3880 if ![is_remote host] {
3881 set gdb_wrapper_file [file join [pwd] $gdb_wrapper_file]
3883 set gdb_wrapper_flags [lindex $result 1]
3885 warning "Status wrapper failed to build."
3888 set gdb_wrapper_file ""
3889 set gdb_wrapper_flags ""
3891 verbose "set gdb_wrapper_file = $gdb_wrapper_file"
3892 set gdb_wrapper_initialized 1
3893 set gdb_wrapper_target [current_target_name]
3896 # Determine options that we always want to pass to the compiler.
3897 gdb_caching_proc universal_compile_options {
3898 set me "universal_compile_options"
3901 set src [standard_temp_file ccopts[pid].c]
3902 set obj [standard_temp_file ccopts[pid].o]
3904 gdb_produce_source $src {
3905 int foo(void) { return 0; }
3908 # Try an option for disabling colored diagnostics. Some compilers
3909 # yield colored diagnostics by default (when run from a tty) unless
3910 # such an option is specified.
3911 set opt "additional_flags=-fdiagnostics-color=never"
3912 set lines [target_compile $src $obj object [list "quiet" $opt]]
3913 if [string match "" $lines] then {
3914 # Seems to have worked; use the option.
3915 lappend options $opt
3920 verbose "$me: returning $options" 2
3924 # Compile the code in $code to a file based on $name, using the flags
3925 # $compile_flag as well as debug, nowarning and quiet.
3926 # Return 1 if code can be compiled
3927 # Leave the file name of the resulting object in the upvar object.
3929 proc gdb_simple_compile {name code {type object} {compile_flags {}} {object obj}} {
3932 switch -regexp -- $type {
3947 foreach flag $compile_flags {
3948 if { "$flag" == "go" } {
3953 set src [standard_temp_file $name-[pid].$ext]
3954 set obj [standard_temp_file $name-[pid].$postfix]
3955 set compile_flags [concat $compile_flags {debug nowarnings quiet}]
3957 gdb_produce_source $src $code
3959 verbose "$name: compiling testfile $src" 2
3960 set lines [gdb_compile $src $obj $type $compile_flags]
3964 if ![string match "" $lines] then {
3965 verbose "$name: compilation failed, returning 0" 2
3971 # Compile the code in $code to a file based on $name, using the flags
3972 # $compile_flag as well as debug, nowarning and quiet.
3973 # Return 1 if code can be compiled
3974 # Delete all created files and objects.
3976 proc gdb_can_simple_compile {name code {type object} {compile_flags ""}} {
3977 set ret [gdb_simple_compile $name $code $type $compile_flags temp_obj]
3978 file delete $temp_obj
3982 # Some targets need to always link a special object in. Save its path here.
3983 global gdb_saved_set_unbuffered_mode_obj
3984 set gdb_saved_set_unbuffered_mode_obj ""
3986 # Compile source files specified by SOURCE into a binary of type TYPE at path
3987 # DEST. gdb_compile is implemented using DejaGnu's target_compile, so the type
3988 # parameter and most options are passed directly to it.
3990 # The type can be one of the following:
3992 # - object: Compile into an object file.
3993 # - executable: Compile and link into an executable.
3994 # - preprocess: Preprocess the source files.
3995 # - assembly: Generate assembly listing.
3997 # The following options are understood and processed by gdb_compile:
3999 # - shlib=so_path: Add SO_PATH to the sources, and enable some target-specific
4000 # quirks to be able to use shared libraries.
4001 # - shlib_load: Link with appropriate libraries to allow the test to
4002 # dynamically load libraries at runtime. For example, on Linux, this adds
4003 # -ldl so that the test can use dlopen.
4004 # - nowarnings: Inhibit all compiler warnings.
4005 # - pie: Force creation of PIE executables.
4006 # - nopie: Prevent creation of PIE executables.
4008 # And here are some of the not too obscure options understood by DejaGnu that
4009 # influence the compilation:
4011 # - additional_flags=flag: Add FLAG to the compiler flags.
4012 # - libs=library: Add LIBRARY to the libraries passed to the linker. The
4013 # argument can be a file, in which case it's added to the sources, or a
4015 # - ldflags=flag: Add FLAG to the linker flags.
4016 # - incdir=path: Add PATH to the searched include directories.
4017 # - libdir=path: Add PATH to the linker searched directories.
4018 # - ada, c++, f77, f90, go, rust: Compile the file as Ada, C++,
4019 # Fortran 77, Fortran 90, Go or Rust.
4020 # - debug: Build with debug information.
4021 # - optimize: Build with optimization.
4023 proc gdb_compile {source dest type options} {
4024 global GDB_TESTCASE_OPTIONS
4025 global gdb_wrapper_file
4026 global gdb_wrapper_flags
4029 global gdb_saved_set_unbuffered_mode_obj
4031 set outdir [file dirname $dest]
4033 # Add platform-specific options if a shared library was specified using
4034 # "shlib=librarypath" in OPTIONS.
4036 if {[lsearch -exact $options rust] != -1} {
4037 # -fdiagnostics-color is not a rustcc option.
4039 set new_options [universal_compile_options]
4042 # Some C/C++ testcases unconditionally pass -Wno-foo as additional
4043 # options to disable some warning. That is OK with GCC, because
4044 # by design, GCC accepts any -Wno-foo option, even if it doesn't
4045 # support -Wfoo. Clang however warns about unknown -Wno-foo by
4046 # default, unless you pass -Wno-unknown-warning-option as well.
4047 # We do that here, so that individual testcases don't have to
4049 if {[lsearch -exact $options getting_compiler_info] == -1
4050 && [lsearch -exact $options rust] == -1
4051 && [lsearch -exact $options ada] == -1
4052 && [lsearch -exact $options f77] == -1
4053 && [lsearch -exact $options f90] == -1
4054 && [lsearch -exact $options go] == -1
4055 && [test_compiler_info "clang-*"]} {
4056 lappend new_options "additional_flags=-Wno-unknown-warning-option"
4059 # Treating .c input files as C++ is deprecated in Clang, so
4060 # explicitly force C++ language.
4061 if { [lsearch -exact $options getting_compiler_info] == -1
4062 && [lsearch -exact $options c++] != -1
4063 && [string match *.c $source] != 0 } {
4065 # gdb_compile cannot handle this combination of options, the
4066 # result is a command like "clang -x c++ foo.c bar.so -o baz"
4067 # which tells Clang to treat bar.so as C++. The solution is
4068 # to call gdb_compile twice--once to compile, once to link--
4069 # either directly, or via build_executable_from_specs.
4070 if { [lsearch $options shlib=*] != -1 } {
4071 error "incompatible gdb_compile options"
4074 if {[test_compiler_info "clang-*"]} {
4075 lappend new_options early_flags=-x\ c++
4079 # Place (and look for) Fortran `.mod` files in the output
4080 # directory for this specific test.
4081 if {[lsearch -exact $options f77] != -1 \
4082 || [lsearch -exact $options f90] != -1 } {
4084 set mod_path [standard_output_file ""]
4085 lappend new_options "additional_flags=-J${mod_path}"
4090 set getting_compiler_info 0
4091 foreach opt $options {
4092 if {[regexp {^shlib=(.*)} $opt dummy_var shlib_name]
4093 && $type == "executable"} {
4094 if [test_compiler_info "xlc-*"] {
4095 # IBM xlc compiler doesn't accept shared library named other
4096 # than .so: use "-Wl," to bypass this
4097 lappend source "-Wl,$shlib_name"
4098 } elseif { ([istarget "*-*-mingw*"]
4099 || [istarget *-*-cygwin*]
4100 || [istarget *-*-pe*])} {
4101 lappend source "${shlib_name}.a"
4103 lappend source $shlib_name
4105 if { $shlib_found == 0 } {
4107 if { ([istarget "*-*-mingw*"]
4108 || [istarget *-*-cygwin*]) } {
4109 lappend new_options "additional_flags=-Wl,--enable-auto-import"
4111 if { [test_compiler_info "gcc-*"] || [test_compiler_info "clang-*"] } {
4112 # Undo debian's change in the default.
4113 # Put it at the front to not override any user-provided
4114 # value, and to make sure it appears in front of all the
4116 lappend new_options "early_flags=-Wl,--no-as-needed"
4119 } elseif { $opt == "shlib_load" && $type == "executable" } {
4121 } elseif { $opt == "getting_compiler_info" } {
4122 # If this is set, calling test_compiler_info will cause recursion.
4123 set getting_compiler_info 1
4125 lappend new_options $opt
4129 # Ensure stack protector is disabled for GCC, as this causes problems with
4130 # DWARF line numbering.
4131 # See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88432
4132 # This option defaults to on for Debian/Ubuntu.
4133 if { $getting_compiler_info == 0
4134 && [test_compiler_info {gcc-*-*}]
4135 && !([test_compiler_info {gcc-[0-3]-*}]
4136 || [test_compiler_info {gcc-4-0-*}])
4137 && [lsearch -exact $options rust] == -1} {
4138 # Put it at the front to not override any user-provided value.
4139 lappend new_options "early_flags=-fno-stack-protector"
4142 # Because we link with libraries using their basename, we may need
4143 # (depending on the platform) to set a special rpath value, to allow
4144 # the executable to find the libraries it depends on.
4145 if { $shlib_load || $shlib_found } {
4146 if { ([istarget "*-*-mingw*"]
4147 || [istarget *-*-cygwin*]
4148 || [istarget *-*-pe*]) } {
4149 # Do not need anything.
4150 } elseif { [istarget *-*-freebsd*] || [istarget *-*-openbsd*] } {
4151 lappend new_options "ldflags=-Wl,-rpath,${outdir}"
4153 if { $shlib_load } {
4154 lappend new_options "libs=-ldl"
4156 lappend new_options "ldflags=-Wl,-rpath,\\\$ORIGIN"
4159 set options $new_options
4161 if [info exists GDB_TESTCASE_OPTIONS] {
4162 lappend options "additional_flags=$GDB_TESTCASE_OPTIONS"
4164 verbose "options are $options"
4165 verbose "source is $source $dest $type $options"
4169 if {[target_info exists needs_status_wrapper] && \
4170 [target_info needs_status_wrapper] != "0" && \
4171 $gdb_wrapper_file != "" } {
4172 lappend options "libs=${gdb_wrapper_file}"
4173 lappend options "ldflags=${gdb_wrapper_flags}"
4176 # Replace the "nowarnings" option with the appropriate additional_flags
4177 # to disable compiler warnings.
4178 set nowarnings [lsearch -exact $options nowarnings]
4179 if {$nowarnings != -1} {
4180 if [target_info exists gdb,nowarnings_flag] {
4181 set flag "additional_flags=[target_info gdb,nowarnings_flag]"
4183 set flag "additional_flags=-w"
4185 set options [lreplace $options $nowarnings $nowarnings $flag]
4188 # Replace the "pie" option with the appropriate compiler and linker flags
4189 # to enable PIE executables.
4190 set pie [lsearch -exact $options pie]
4192 if [target_info exists gdb,pie_flag] {
4193 set flag "additional_flags=[target_info gdb,pie_flag]"
4195 # For safety, use fPIE rather than fpie. On AArch64, m68k, PowerPC
4196 # and SPARC, fpie can cause compile errors due to the GOT exceeding
4197 # a maximum size. On other architectures the two flags are
4198 # identical (see the GCC manual). Note Debian9 and Ubuntu16.10
4199 # onwards default GCC to using fPIE. If you do require fpie, then
4200 # it can be set using the pie_flag.
4201 set flag "additional_flags=-fPIE"
4203 set options [lreplace $options $pie $pie $flag]
4205 if [target_info exists gdb,pie_ldflag] {
4206 set flag "ldflags=[target_info gdb,pie_ldflag]"
4208 set flag "ldflags=-pie"
4210 lappend options "$flag"
4213 # Replace the "nopie" option with the appropriate compiler and linker
4214 # flags to disable PIE executables.
4215 set nopie [lsearch -exact $options nopie]
4217 if [target_info exists gdb,nopie_flag] {
4218 set flag "additional_flags=[target_info gdb,nopie_flag]"
4220 set flag "additional_flags=-fno-pie"
4222 set options [lreplace $options $nopie $nopie $flag]
4224 if [target_info exists gdb,nopie_ldflag] {
4225 set flag "ldflags=[target_info gdb,nopie_ldflag]"
4227 set flag "ldflags=-no-pie"
4229 lappend options "$flag"
4232 if { $type == "executable" } {
4233 if { ([istarget "*-*-mingw*"]
4234 || [istarget "*-*-*djgpp"]
4235 || [istarget "*-*-cygwin*"])} {
4236 # Force output to unbuffered mode, by linking in an object file
4237 # with a global contructor that calls setvbuf.
4239 # Compile the special object separately for two reasons:
4240 # 1) Insulate it from $options.
4241 # 2) Avoid compiling it for every gdb_compile invocation,
4242 # which is time consuming, especially if we're remote
4245 if { $gdb_saved_set_unbuffered_mode_obj == "" } {
4246 verbose "compiling gdb_saved_set_unbuffered_obj"
4247 set unbuf_src ${srcdir}/lib/set_unbuffered_mode.c
4248 set unbuf_obj ${objdir}/set_unbuffered_mode.o
4250 set result [gdb_compile "${unbuf_src}" "${unbuf_obj}" object {nowarnings}]
4251 if { $result != "" } {
4254 if {[is_remote host]} {
4255 set gdb_saved_set_unbuffered_mode_obj set_unbuffered_mode_saved.o
4257 set gdb_saved_set_unbuffered_mode_obj ${objdir}/set_unbuffered_mode_saved.o
4259 # Link a copy of the output object, because the
4260 # original may be automatically deleted.
4261 remote_download host $unbuf_obj $gdb_saved_set_unbuffered_mode_obj
4263 verbose "gdb_saved_set_unbuffered_obj already compiled"
4266 # Rely on the internal knowledge that the global ctors are ran in
4267 # reverse link order. In that case, we can use ldflags to
4268 # avoid copying the object file to the host multiple
4270 # This object can only be added if standard libraries are
4271 # used. Thus, we need to disable it if -nostdlib option is used
4272 if {[lsearch -regexp $options "-nostdlib"] < 0 } {
4273 lappend options "ldflags=$gdb_saved_set_unbuffered_mode_obj"
4278 set result [target_compile $source $dest $type $options]
4280 # Prune uninteresting compiler (and linker) output.
4281 regsub "Creating library file: \[^\r\n\]*\[\r\n\]+" $result "" result
4283 regsub "\[\r\n\]*$" "$result" "" result
4284 regsub "^\[\r\n\]*" "$result" "" result
4286 if { $type == "executable" && $result == "" \
4287 && ($nopie != -1 || $pie != -1) } {
4288 set is_pie [exec_is_pie "$dest"]
4289 if { $nopie != -1 && $is_pie == 1 } {
4290 set result "nopie failed to prevent PIE executable"
4291 } elseif { $pie != -1 && $is_pie == 0 } {
4292 set result "pie failed to generate PIE executable"
4296 if {[lsearch $options quiet] < 0} {
4297 # We shall update this on a per language basis, to avoid
4298 # changing the entire testsuite in one go.
4299 if {[lsearch $options f77] >= 0} {
4300 gdb_compile_test $source $result
4301 } elseif { $result != "" } {
4302 clone_output "gdb compile failed, $result"
4309 # This is just like gdb_compile, above, except that it tries compiling
4310 # against several different thread libraries, to see which one this
4312 proc gdb_compile_pthreads {source dest type options} {
4313 if {$type != "executable"} {
4314 return [gdb_compile $source $dest $type $options]
4317 set why_msg "unrecognized error"
4318 foreach lib {-lpthreads -lpthread -lthread ""} {
4319 # This kind of wipes out whatever libs the caller may have
4320 # set. Or maybe theirs will override ours. How infelicitous.
4321 set options_with_lib [concat $options [list libs=$lib quiet]]
4322 set ccout [gdb_compile $source $dest $type $options_with_lib]
4323 switch -regexp -- $ccout {
4324 ".*no posix threads support.*" {
4325 set why_msg "missing threads include file"
4328 ".*cannot open -lpthread.*" {
4329 set why_msg "missing runtime threads library"
4331 ".*Can't find library for -lpthread.*" {
4332 set why_msg "missing runtime threads library"
4335 pass "successfully compiled posix threads test case"
4341 if {!$built_binfile} {
4342 unsupported "couldn't compile [file tail $source]: ${why_msg}"
4347 # Build a shared library from SOURCES.
4349 proc gdb_compile_shlib_1 {sources dest options} {
4350 set obj_options $options
4353 if { [lsearch -exact $options "ada"] >= 0 } {
4358 if { [lsearch -exact $options "c++"] >= 0 } {
4359 set info_options "c++"
4361 if [get_compiler_info ${info_options}] {
4365 switch -glob [test_compiler_info] {
4367 lappend obj_options "additional_flags=-qpic"
4370 if { [istarget "*-*-cygwin*"]
4371 || [istarget "*-*-mingw*"] } {
4372 lappend obj_options "additional_flags=-fPIC"
4374 lappend obj_options "additional_flags=-fpic"
4378 if { [istarget "powerpc*-*-aix*"]
4379 || [istarget "rs6000*-*-aix*"]
4380 || [istarget "*-*-cygwin*"]
4381 || [istarget "*-*-mingw*"]
4382 || [istarget "*-*-pe*"] } {
4383 lappend obj_options "additional_flags=-fPIC"
4385 lappend obj_options "additional_flags=-fpic"
4389 lappend obj_options "additional_flags=-fpic"
4392 # don't know what the compiler is...
4393 lappend obj_options "additional_flags=-fPIC"
4397 set outdir [file dirname $dest]
4399 foreach source $sources {
4400 if {[file extension $source] == ".o"} {
4401 # Already a .o file.
4402 lappend objects $source
4406 set sourcebase [file tail $source]
4409 # Gnatmake doesn't like object name foo.adb.o, use foo.o.
4410 set sourcebase [file rootname $sourcebase]
4412 set object ${outdir}/${sourcebase}.o
4415 # Use gdb_compile_ada_1 instead of gdb_compile_ada to avoid the
4417 if {[gdb_compile_ada_1 $source $object object \
4418 $obj_options] != ""} {
4422 if {[gdb_compile $source $object object \
4423 $obj_options] != ""} {
4428 lappend objects $object
4431 set link_options $options
4433 # If we try to use gnatmake for the link, it will interpret the
4434 # object file as an .adb file. Remove ada from the options to
4436 set idx [lsearch $link_options "ada"]
4437 set link_options [lreplace $link_options $idx $idx]
4439 if [test_compiler_info "xlc-*"] {
4440 lappend link_options "additional_flags=-qmkshrobj"
4442 lappend link_options "additional_flags=-shared"
4444 if { ([istarget "*-*-mingw*"]
4445 || [istarget *-*-cygwin*]
4446 || [istarget *-*-pe*]) } {
4447 if { [is_remote host] } {
4448 set name [file tail ${dest}]
4452 lappend link_options "additional_flags=-Wl,--out-implib,${name}.a"
4454 # Set the soname of the library. This causes the linker on ELF
4455 # systems to create the DT_NEEDED entry in the executable referring
4456 # to the soname of the library, and not its absolute path. This
4457 # (using the absolute path) would be problem when testing on a
4460 # In conjunction with setting the soname, we add the special
4461 # rpath=$ORIGIN value when building the executable, so that it's
4462 # able to find the library in its own directory.
4463 set destbase [file tail $dest]
4464 lappend link_options "additional_flags=-Wl,-soname,$destbase"
4467 if {[gdb_compile "${objects}" "${dest}" executable $link_options] != ""} {
4470 if { [is_remote host]
4471 && ([istarget "*-*-mingw*"]
4472 || [istarget *-*-cygwin*]
4473 || [istarget *-*-pe*]) } {
4474 set dest_tail_name [file tail ${dest}]
4475 remote_upload host $dest_tail_name.a ${dest}.a
4476 remote_file host delete $dest_tail_name.a
4482 # Build a shared library from SOURCES. Ignore target boards PIE-related
4485 proc gdb_compile_shlib {sources dest options} {
4488 # Ignore PIE-related setting in multilib_flags.
4489 set board [target_info name]
4490 set multilib_flags_orig [board_info $board multilib_flags]
4491 set multilib_flags ""
4492 foreach op $multilib_flags_orig {
4493 if { $op == "-pie" || $op == "-no-pie" \
4494 || $op == "-fPIE" || $op == "-fno-PIE"} {
4496 append multilib_flags " $op"
4500 save_target_board_info { multilib_flags } {
4501 unset_board_info multilib_flags
4502 set_board_info multilib_flags "$multilib_flags"
4503 set result [gdb_compile_shlib_1 $sources $dest $options]
4509 # This is just like gdb_compile_shlib, above, except that it tries compiling
4510 # against several different thread libraries, to see which one this
4512 proc gdb_compile_shlib_pthreads {sources dest options} {
4514 set why_msg "unrecognized error"
4515 foreach lib {-lpthreads -lpthread -lthread ""} {
4516 # This kind of wipes out whatever libs the caller may have
4517 # set. Or maybe theirs will override ours. How infelicitous.
4518 set options_with_lib [concat $options [list libs=$lib quiet]]
4519 set ccout [gdb_compile_shlib $sources $dest $options_with_lib]
4520 switch -regexp -- $ccout {
4521 ".*no posix threads support.*" {
4522 set why_msg "missing threads include file"
4525 ".*cannot open -lpthread.*" {
4526 set why_msg "missing runtime threads library"
4528 ".*Can't find library for -lpthread.*" {
4529 set why_msg "missing runtime threads library"
4532 pass "successfully compiled posix threads test case"
4538 if {!$built_binfile} {
4539 unsupported "couldn't compile $sources: ${why_msg}"
4544 # This is just like gdb_compile_pthreads, above, except that we always add the
4545 # objc library for compiling Objective-C programs
4546 proc gdb_compile_objc {source dest type options} {
4548 set why_msg "unrecognized error"
4549 foreach lib {-lobjc -lpthreads -lpthread -lthread solaris} {
4550 # This kind of wipes out whatever libs the caller may have
4551 # set. Or maybe theirs will override ours. How infelicitous.
4552 if { $lib == "solaris" } {
4553 set lib "-lpthread -lposix4"
4555 if { $lib != "-lobjc" } {
4556 set lib "-lobjc $lib"
4558 set options_with_lib [concat $options [list libs=$lib quiet]]
4559 set ccout [gdb_compile $source $dest $type $options_with_lib]
4560 switch -regexp -- $ccout {
4561 ".*no posix threads support.*" {
4562 set why_msg "missing threads include file"
4565 ".*cannot open -lpthread.*" {
4566 set why_msg "missing runtime threads library"
4568 ".*Can't find library for -lpthread.*" {
4569 set why_msg "missing runtime threads library"
4572 pass "successfully compiled objc with posix threads test case"
4578 if {!$built_binfile} {
4579 unsupported "couldn't compile [file tail $source]: ${why_msg}"
4584 # Build an OpenMP program from SOURCE. See prefatory comment for
4585 # gdb_compile, above, for discussion of the parameters to this proc.
4587 proc gdb_compile_openmp {source dest type options} {
4588 lappend options "additional_flags=-fopenmp"
4589 return [gdb_compile $source $dest $type $options]
4592 # Send a command to GDB.
4593 # For options for TYPE see gdb_stdin_log_write
4595 proc send_gdb { string {type standard}} {
4596 gdb_stdin_log_write $string $type
4597 return [remote_send host "$string"]
4600 # Send STRING to the inferior's terminal.
4602 proc send_inferior { string } {
4603 global inferior_spawn_id
4605 if {[catch "send -i $inferior_spawn_id -- \$string" errorInfo]} {
4615 proc gdb_expect { args } {
4616 if { [llength $args] == 2 && [lindex $args 0] != "-re" } {
4617 set atimeout [lindex $args 0]
4618 set expcode [list [lindex $args 1]]
4623 # A timeout argument takes precedence, otherwise of all the timeouts
4624 # select the largest.
4625 if [info exists atimeout] {
4628 set tmt [get_largest_timeout]
4632 {uplevel remote_expect host $tmt $expcode} string]
4635 global errorInfo errorCode
4637 return -code error -errorinfo $errorInfo -errorcode $errorCode $string
4639 return -code $code $string
4643 # gdb_expect_list TEST SENTINEL LIST -- expect a sequence of outputs
4645 # Check for long sequence of output by parts.
4646 # TEST: is the test message to be printed with the test success/fail.
4647 # SENTINEL: Is the terminal pattern indicating that output has finished.
4648 # LIST: is the sequence of outputs to match.
4649 # If the sentinel is recognized early, it is considered an error.
4652 # 1 if the test failed,
4653 # 0 if the test passes,
4654 # -1 if there was an internal error.
4656 proc gdb_expect_list {test sentinel list} {
4661 while { ${index} < [llength ${list}] } {
4662 set pattern [lindex ${list} ${index}]
4663 set index [expr ${index} + 1]
4664 verbose -log "gdb_expect_list pattern: /$pattern/" 2
4665 if { ${index} == [llength ${list}] } {
4668 -re "${pattern}${sentinel}" {
4669 # pass "${test}, pattern ${index} + sentinel"
4672 fail "${test} (pattern ${index} + sentinel)"
4675 -re ".*A problem internal to GDB has been detected" {
4676 fail "${test} (GDB internal error)"
4678 gdb_internal_error_resync
4681 fail "${test} (pattern ${index} + sentinel) (timeout)"
4686 # unresolved "${test}, pattern ${index} + sentinel"
4692 # pass "${test}, pattern ${index}"
4695 fail "${test} (pattern ${index})"
4698 -re ".*A problem internal to GDB has been detected" {
4699 fail "${test} (GDB internal error)"
4701 gdb_internal_error_resync
4704 fail "${test} (pattern ${index}) (timeout)"
4709 # unresolved "${test}, pattern ${index}"
4721 # Spawn the gdb process.
4723 # This doesn't expect any output or do any other initialization,
4724 # leaving those to the caller.
4726 # Overridable function -- you can override this function in your
4729 proc gdb_spawn { } {
4733 # Spawn GDB with CMDLINE_FLAGS appended to the GDBFLAGS global.
4735 proc gdb_spawn_with_cmdline_opts { cmdline_flags } {
4738 set saved_gdbflags $GDBFLAGS
4740 if {$GDBFLAGS != ""} {
4743 append GDBFLAGS $cmdline_flags
4747 set GDBFLAGS $saved_gdbflags
4752 # Start gdb running, wait for prompt, and disable the pagers.
4754 # Overridable function -- you can override this function in your
4757 proc gdb_start { } {
4762 catch default_gdb_exit
4765 # Return true if we can spawn a program on the target and attach to
4768 proc can_spawn_for_attach { } {
4769 # We use exp_pid to get the inferior's pid, assuming that gives
4770 # back the pid of the program. On remote boards, that would give
4771 # us instead the PID of e.g., the ssh client, etc.
4772 if [is_remote target] then {
4776 # The "attach" command doesn't make sense when the target is
4777 # stub-like, where GDB finds the program already started on
4778 # initial connection.
4779 if {[target_info exists use_gdb_stub]} {
4787 # Kill a progress previously started with spawn_wait_for_attach, and
4788 # reap its wait status. PROC_SPAWN_ID is the spawn id associated with
4791 proc kill_wait_spawned_process { proc_spawn_id } {
4792 set pid [exp_pid -i $proc_spawn_id]
4794 verbose -log "killing ${pid}"
4795 remote_exec build "kill -9 ${pid}"
4797 verbose -log "closing ${proc_spawn_id}"
4798 catch "close -i $proc_spawn_id"
4799 verbose -log "waiting for ${proc_spawn_id}"
4801 # If somehow GDB ends up still attached to the process here, a
4802 # blocking wait hangs until gdb is killed (or until gdb / the
4803 # ptracer reaps the exit status too, but that won't happen because
4804 # something went wrong.) Passing -nowait makes expect tell Tcl to
4805 # wait for the PID in the background. That's fine because we
4806 # don't care about the exit status. */
4807 wait -nowait -i $proc_spawn_id
4810 # Returns the process id corresponding to the given spawn id.
4812 proc spawn_id_get_pid { spawn_id } {
4813 set testpid [exp_pid -i $spawn_id]
4815 if { [istarget "*-*-cygwin*"] } {
4816 # testpid is the Cygwin PID, GDB uses the Windows PID, which
4817 # might be different due to the way fork/exec works.
4818 set testpid [ exec ps -e | gawk "{ if (\$1 == $testpid) print \$4; }" ]
4824 # Start a set of programs running and then wait for a bit, to be sure
4825 # that they can be attached to. Return a list of processes spawn IDs,
4826 # one element for each process spawned. It's a test error to call
4827 # this when [can_spawn_for_attach] is false.
4829 proc spawn_wait_for_attach { executable_list } {
4830 set spawn_id_list {}
4832 if ![can_spawn_for_attach] {
4833 # The caller should have checked can_spawn_for_attach itself
4834 # before getting here.
4835 error "can't spawn for attach with this target/board"
4838 foreach {executable} $executable_list {
4839 # Note we use Expect's spawn, not Tcl's exec, because with
4840 # spawn we control when to wait for/reap the process. That
4841 # allows killing the process by PID without being subject to
4843 lappend spawn_id_list [remote_spawn target $executable]
4848 return $spawn_id_list
4852 # gdb_load_cmd -- load a file into the debugger.
4853 # ARGS - additional args to load command.
4854 # return a -1 if anything goes wrong.
4856 proc gdb_load_cmd { args } {
4859 if [target_info exists gdb_load_timeout] {
4860 set loadtimeout [target_info gdb_load_timeout]
4862 set loadtimeout 1600
4864 send_gdb "load $args\n"
4865 verbose "Timeout is now $loadtimeout seconds" 2
4866 gdb_expect $loadtimeout {
4867 -re "Loading section\[^\r\]*\r\n" {
4870 -re "Start address\[\r\]*\r\n" {
4873 -re "Transfer rate\[\r\]*\r\n" {
4876 -re "Memory access error\[^\r\]*\r\n" {
4877 perror "Failed to load program"
4880 -re "$gdb_prompt $" {
4883 -re "(.*)\r\n$gdb_prompt " {
4884 perror "Unexpected reponse from 'load' -- $expect_out(1,string)"
4888 perror "Timed out trying to load $args."
4895 # Invoke "gcore". CORE is the name of the core file to write. TEST
4896 # is the name of the test case. This will return 1 if the core file
4897 # was created, 0 otherwise. If this fails to make a core file because
4898 # this configuration of gdb does not support making core files, it
4899 # will call "unsupported", not "fail". However, if this fails to make
4900 # a core file for some other reason, then it will call "fail".
4902 proc gdb_gcore_cmd {core test} {
4906 gdb_test_multiple "gcore $core" $test {
4907 -re "Saved corefile .*\[\r\n\]+$gdb_prompt $" {
4911 -re "(?:Can't create a corefile|Target does not support core file generation\\.)\[\r\n\]+$gdb_prompt $" {
4919 # Load core file CORE. TEST is the name of the test case.
4920 # This will record a pass/fail for loading the core file.
4922 # 1 - core file is successfully loaded
4923 # 0 - core file loaded but has a non fatal error
4924 # -1 - core file failed to load
4926 proc gdb_core_cmd { core test } {
4929 gdb_test_multiple "core $core" "$test" {
4930 -re "\\\[Thread debugging using \[^ \r\n\]* enabled\\\]\r\n" {
4933 -re " is not a core dump:.*\r\n$gdb_prompt $" {
4934 fail "$test (bad file format)"
4937 -re -wrap "[string_to_regexp $core]: No such file or directory.*" {
4938 fail "$test (file not found)"
4941 -re "Couldn't find .* registers in core file.*\r\n$gdb_prompt $" {
4942 fail "$test (incomplete note section)"
4945 -re "Core was generated by .*\r\n$gdb_prompt $" {
4949 -re ".*$gdb_prompt $" {
4954 fail "$test (timeout)"
4958 fail "unsupported output from 'core' command"
4962 # Return the filename to download to the target and load on the target
4963 # for this shared library. Normally just LIBNAME, unless shared libraries
4964 # for this target have separate link and load images.
4966 proc shlib_target_file { libname } {
4970 # Return the filename GDB will load symbols from when debugging this
4971 # shared library. Normally just LIBNAME, unless shared libraries for
4972 # this target have separate link and load images.
4974 proc shlib_symbol_file { libname } {
4978 # Return the filename to download to the target and load for this
4979 # executable. Normally just BINFILE unless it is renamed to something
4980 # else for this target.
4982 proc exec_target_file { binfile } {
4986 # Return the filename GDB will load symbols from when debugging this
4987 # executable. Normally just BINFILE unless executables for this target
4988 # have separate files for symbols.
4990 proc exec_symbol_file { binfile } {
4994 # Rename the executable file. Normally this is just BINFILE1 being renamed
4995 # to BINFILE2, but some targets require multiple binary files.
4996 proc gdb_rename_execfile { binfile1 binfile2 } {
4997 file rename -force [exec_target_file ${binfile1}] \
4998 [exec_target_file ${binfile2}]
4999 if { [exec_target_file ${binfile1}] != [exec_symbol_file ${binfile1}] } {
5000 file rename -force [exec_symbol_file ${binfile1}] \
5001 [exec_symbol_file ${binfile2}]
5005 # "Touch" the executable file to update the date. Normally this is just
5006 # BINFILE, but some targets require multiple files.
5007 proc gdb_touch_execfile { binfile } {
5008 set time [clock seconds]
5009 file mtime [exec_target_file ${binfile}] $time
5010 if { [exec_target_file ${binfile}] != [exec_symbol_file ${binfile}] } {
5011 file mtime [exec_symbol_file ${binfile}] $time
5015 # Like remote_download but provides a gdb-specific behavior.
5017 # If the destination board is remote, the local file FROMFILE is transferred as
5018 # usual with remote_download to TOFILE on the remote board. The destination
5019 # filename is added to the CLEANFILES global, so it can be cleaned up at the
5022 # If the destination board is local, the destination path TOFILE is passed
5023 # through standard_output_file, and FROMFILE is copied there.
5025 # In both cases, if TOFILE is omitted, it defaults to the [file tail] of
5028 proc gdb_remote_download {dest fromfile {tofile {}}} {
5029 # If TOFILE is not given, default to the same filename as FROMFILE.
5030 if {[string length $tofile] == 0} {
5031 set tofile [file tail $fromfile]
5034 if {[is_remote $dest]} {
5035 # When the DEST is remote, we simply send the file to DEST.
5038 set destname [remote_download $dest $fromfile $tofile]
5039 lappend cleanfiles $destname
5043 # When the DEST is local, we copy the file to the test directory (where
5044 # the executable is).
5046 # Note that we pass TOFILE through standard_output_file, regardless of
5047 # whether it is absolute or relative, because we don't want the tests
5048 # to be able to write outside their standard output directory.
5050 set tofile [standard_output_file $tofile]
5052 file copy -force $fromfile $tofile
5058 # gdb_load_shlib LIB...
5060 # Copy the listed library to the target.
5062 proc gdb_load_shlib { file } {
5065 if ![info exists gdb_spawn_id] {
5066 perror "gdb_load_shlib: GDB is not running"
5069 set dest [gdb_remote_download target [shlib_target_file $file]]
5071 if {[is_remote target]} {
5072 # If the target is remote, we need to tell gdb where to find the
5075 # We could set this even when not testing remotely, but a user
5076 # generally won't set it unless necessary. In order to make the tests
5077 # more like the real-life scenarios, we don't set it for local testing.
5078 gdb_test "set solib-search-path [file dirname $file]" "" ""
5085 # gdb_load -- load a file into the debugger. Specifying no file
5086 # defaults to the executable currently being debugged.
5087 # The return value is 0 for success, -1 for failure.
5088 # Many files in config/*.exp override this procedure.
5090 proc gdb_load { arg } {
5092 return [gdb_file_cmd $arg]
5098 # with_complaints -- Execute BODY and set complaints temporary to N for the
5101 proc with_complaints { n body } {
5104 # Save current setting of complaints.
5106 set show_complaints_re \
5107 "Max number of complaints about incorrect symbols is ($decimal)\\."
5108 gdb_test_multiple "show complaints" "" {
5109 -re -wrap $show_complaints_re {
5110 set save $expect_out(1,string)
5114 if { $save == "" } {
5115 perror "Did not manage to set complaints"
5118 gdb_test_no_output "set complaints $n" ""
5121 set code [catch {uplevel 1 $body} result]
5123 # Restore saved setting of complaints.
5124 if { $save != "" } {
5125 gdb_test_no_output "set complaints $save" ""
5129 global errorInfo errorCode
5130 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
5132 return -code $code $result
5137 # gdb_load_no_complaints -- As gdb_load, but in addition verifies that
5138 # loading caused no symbol reading complaints.
5140 proc gdb_load_no_complaints { arg } {
5141 global gdb_prompt gdb_file_cmd_msg decimal
5143 # Temporarily set complaint to a small non-zero number.
5148 # Verify that there were no complaints.
5149 set re "^Reading symbols from \[^\r\n\]*\r\n$gdb_prompt $"
5150 gdb_assert {[regexp $re $gdb_file_cmd_msg]} "No complaints"
5153 # gdb_reload -- load a file into the target. Called before "running",
5154 # either the first time or after already starting the program once,
5155 # for remote targets. Most files that override gdb_load should now
5156 # override this instead.
5158 # INFERIOR_ARGS contains the arguments to pass to the inferiors, as a
5159 # single string to get interpreted by a shell. If the target board
5160 # overriding gdb_reload is a "stub", then it should arrange things such
5161 # these arguments make their way to the inferior process.
5163 proc gdb_reload { {inferior_args {}} } {
5164 # For the benefit of existing configurations, default to gdb_load.
5165 # Specifying no file defaults to the executable currently being
5167 return [gdb_load ""]
5170 proc gdb_continue { function } {
5173 return [gdb_test "continue" ".*Breakpoint $decimal, $function .*" "continue to $function"]
5176 # Default implementation of gdb_init.
5177 proc default_gdb_init { test_file_name } {
5178 global gdb_wrapper_initialized
5179 global gdb_wrapper_target
5180 global gdb_test_file_name
5184 # Reset the timeout value to the default. This way, any testcase
5185 # that changes the timeout value without resetting it cannot affect
5186 # the timeout used in subsequent testcases.
5187 global gdb_test_timeout
5189 set timeout $gdb_test_timeout
5191 if { [regexp ".*gdb\.reverse\/.*" $test_file_name]
5192 && [target_info exists gdb_reverse_timeout] } {
5193 set timeout [target_info gdb_reverse_timeout]
5196 # If GDB_INOTIFY is given, check for writes to '.'. This is a
5197 # debugging tool to help confirm that the test suite is
5198 # parallel-safe. You need "inotifywait" from the
5199 # inotify-tools package to use this.
5200 global GDB_INOTIFY inotify_pid
5201 if {[info exists GDB_INOTIFY] && ![info exists inotify_pid]} {
5202 global outdir tool inotify_log_file
5204 set exclusions {outputs temp gdb[.](log|sum) cache}
5205 set exclusion_re ([join $exclusions |])
5207 set inotify_log_file [standard_temp_file inotify.out]
5208 set inotify_pid [exec inotifywait -r -m -e move,create,delete . \
5209 --exclude $exclusion_re \
5210 |& tee -a $outdir/$tool.log $inotify_log_file &]
5212 # Wait for the watches; hopefully this is long enough.
5215 # Clear the log so that we don't emit a warning the first time
5217 set fd [open $inotify_log_file w]
5221 # Block writes to all banned variables, and invocation of all
5222 # banned procedures...
5223 global banned_variables
5224 global banned_procedures
5225 global banned_traced
5226 if (!$banned_traced) {
5227 foreach banned_var $banned_variables {
5228 global "$banned_var"
5229 trace add variable "$banned_var" write error
5231 foreach banned_proc $banned_procedures {
5232 global "$banned_proc"
5233 trace add execution "$banned_proc" enter error
5238 # We set LC_ALL, LC_CTYPE, and LANG to C so that we get the same
5239 # messages as expected.
5244 # Don't let a .inputrc file or an existing setting of INPUTRC mess
5245 # up the test results. Certain tests (style tests and TUI tests)
5246 # want to set the terminal to a non-"dumb" value, and for those we
5247 # want to disable bracketed paste mode. Versions of Readline
5248 # before 8.0 will not understand this and will issue a warning.
5249 # We tried using a $if to guard it, but Readline 8.1 had a bug in
5250 # its version-comparison code that prevented this for working.
5251 setenv INPUTRC [cached_file inputrc "set enable-bracketed-paste off"]
5253 # This disables style output, which would interfere with many
5257 # Ensure that GDBHISTFILE and GDBHISTSIZE are removed from the
5258 # environment, we don't want these modifications to the history
5260 unset -nocomplain ::env(GDBHISTFILE)
5261 unset -nocomplain ::env(GDBHISTSIZE)
5263 # Ensure that XDG_CONFIG_HOME is not set. Some tests setup a fake
5264 # home directory in order to test loading settings from gdbinit.
5265 # If XDG_CONFIG_HOME is set then GDB will load a gdbinit from
5266 # there (if one is present) rather than the home directory setup
5268 unset -nocomplain ::env(XDG_CONFIG_HOME)
5270 # Initialize GDB's pty with a fixed size, to make sure we avoid pagination
5271 # during startup. See "man expect" for details about stty_init.
5273 set stty_init "rows 25 cols 80"
5275 # Some tests (for example gdb.base/maint.exp) shell out from gdb to use
5276 # grep. Clear GREP_OPTIONS to make the behavior predictable,
5277 # especially having color output turned on can cause tests to fail.
5278 setenv GREP_OPTIONS ""
5280 # Clear $gdbserver_reconnect_p.
5281 global gdbserver_reconnect_p
5282 set gdbserver_reconnect_p 1
5283 unset gdbserver_reconnect_p
5285 # Clear $last_loaded_file
5286 global last_loaded_file
5287 unset -nocomplain last_loaded_file
5289 # Reset GDB number of instances
5290 global gdb_instances
5295 set gdb_test_file_name [file rootname [file tail $test_file_name]]
5297 # Make sure that the wrapper is rebuilt
5298 # with the appropriate multilib option.
5299 if { $gdb_wrapper_target != [current_target_name] } {
5300 set gdb_wrapper_initialized 0
5303 # Unlike most tests, we have a small number of tests that generate
5304 # a very large amount of output. We therefore increase the expect
5305 # buffer size to be able to contain the entire test output. This
5306 # is especially needed by gdb.base/info-macros.exp.
5308 # Also set this value for the currently running GDB.
5309 match_max [match_max -d]
5311 # We want to add the name of the TCL testcase to the PASS/FAIL messages.
5312 set pf_prefix "[file tail [file dirname $test_file_name]]/[file tail $test_file_name]:"
5315 if [target_info exists gdb_prompt] {
5316 set gdb_prompt [target_info gdb_prompt]
5318 set gdb_prompt "\\(gdb\\)"
5321 if [info exists use_gdb_stub] {
5325 gdb_setup_known_globals
5327 if { [info procs ::gdb_tcl_unknown] != "" } {
5328 # Dejagnu overrides proc unknown. The dejagnu version may trigger in a
5329 # test-case but abort the entire test run. To fix this, we install a
5330 # local version here, which reverts dejagnu's override, and restore
5331 # dejagnu's version in gdb_finish.
5332 rename ::unknown ::dejagnu_unknown
5333 proc unknown { args } {
5334 # Use tcl's unknown.
5335 set cmd [lindex $args 0]
5336 unresolved "testcase aborted due to invalid command name: $cmd"
5337 return [uplevel 1 ::gdb_tcl_unknown $args]
5342 # Return a path using GDB_PARALLEL.
5343 # ARGS is a list of path elements to append to "$objdir/$GDB_PARALLEL".
5344 # GDB_PARALLEL must be defined, the caller must check.
5346 # The default value for GDB_PARALLEL is, canonically, ".".
5347 # The catch is that tests don't expect an additional "./" in file paths so
5348 # omit any directory for the default case.
5349 # GDB_PARALLEL is written as "yes" for the default case in Makefile.in to mark
5350 # its special handling.
5352 proc make_gdb_parallel_path { args } {
5353 global GDB_PARALLEL objdir
5354 set joiner [list "file" "join" $objdir]
5355 if { [info exists GDB_PARALLEL] && $GDB_PARALLEL != "yes" } {
5356 lappend joiner $GDB_PARALLEL
5358 set joiner [concat $joiner $args]
5359 return [eval $joiner]
5362 # Turn BASENAME into a full file name in the standard output
5363 # directory. It is ok if BASENAME is the empty string; in this case
5364 # the directory is returned.
5366 proc standard_output_file {basename} {
5367 global objdir subdir gdb_test_file_name
5369 set dir [make_gdb_parallel_path outputs $subdir $gdb_test_file_name]
5371 # If running on MinGW, replace /c/foo with c:/foo
5372 if { [ishost *-*-mingw*] } {
5373 set dir [exec sh -c "cd ${dir} && pwd -W"]
5375 return [file join $dir $basename]
5378 # Turn BASENAME into a full file name in the standard output directory. If
5379 # GDB has been launched more than once then append the count, starting with
5382 proc standard_output_file_with_gdb_instance {basename} {
5383 global gdb_instances
5384 set count $gdb_instances
5387 return [standard_output_file $basename]
5389 return [standard_output_file ${basename}.${count}]
5392 # Return the name of a file in our standard temporary directory.
5394 proc standard_temp_file {basename} {
5395 # Since a particular runtest invocation is only executing a single test
5396 # file at any given time, we can use the runtest pid to build the
5397 # path of the temp directory.
5398 set dir [make_gdb_parallel_path temp [pid]]
5400 return [file join $dir $basename]
5403 # Rename file A to file B, if B does not already exists. Otherwise, leave B
5404 # as is and delete A. Return 1 if rename happened.
5406 proc tentative_rename { a b } {
5407 global errorInfo errorCode
5408 set code [catch {file rename -- $a $b} result]
5409 if { $code == 1 && [lindex $errorCode 0] == "POSIX" \
5410 && [lindex $errorCode 1] == "EEXIST" } {
5415 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
5416 } elseif {$code > 1} {
5417 return -code $code $result
5422 # Create a file with name FILENAME and contents TXT in the cache directory.
5423 # If EXECUTABLE, mark the new file for execution.
5425 proc cached_file { filename txt {executable 0}} {
5426 set filename [make_gdb_parallel_path cache $filename]
5428 if { [file exists $filename] } {
5432 set dir [file dirname $filename]
5435 set tmp_filename $filename.[pid]
5436 set fd [open $tmp_filename w]
5440 if { $executable } {
5441 exec chmod +x $tmp_filename
5443 tentative_rename $tmp_filename $filename
5448 # Set 'testfile', 'srcfile', and 'binfile'.
5450 # ARGS is a list of source file specifications.
5451 # Without any arguments, the .exp file's base name is used to
5452 # compute the source file name. The ".c" extension is added in this case.
5453 # If ARGS is not empty, each entry is a source file specification.
5454 # If the specification starts with a "." or "-", it is treated as a suffix
5455 # to append to the .exp file's base name.
5456 # If the specification is the empty string, it is treated as if it
5458 # Otherwise it is a file name.
5459 # The first file in the list is used to set the 'srcfile' global.
5460 # Each subsequent name is used to set 'srcfile2', 'srcfile3', etc.
5462 # Most tests should call this without arguments.
5464 # If a completely different binary file name is needed, then it
5465 # should be handled in the .exp file with a suitable comment.
5467 proc standard_testfile {args} {
5468 global gdb_test_file_name
5470 global gdb_test_file_last_vars
5473 global testfile binfile
5475 set testfile $gdb_test_file_name
5476 set binfile [standard_output_file ${testfile}]
5478 if {[llength $args] == 0} {
5482 # Unset our previous output variables.
5483 # This can help catch hidden bugs.
5484 if {[info exists gdb_test_file_last_vars]} {
5485 foreach varname $gdb_test_file_last_vars {
5487 catch {unset $varname}
5490 # 'executable' is often set by tests.
5491 set gdb_test_file_last_vars {executable}
5495 set varname srcfile$suffix
5498 # Handle an extension.
5502 set first [string range $arg 0 0]
5503 if { $first == "." || $first == "-" } {
5504 set arg $testfile$arg
5509 lappend gdb_test_file_last_vars $varname
5511 if {$suffix == ""} {
5519 # The default timeout used when testing GDB commands. We want to use
5520 # the same timeout as the default dejagnu timeout, unless the user has
5521 # already provided a specific value (probably through a site.exp file).
5522 global gdb_test_timeout
5523 if ![info exists gdb_test_timeout] {
5524 set gdb_test_timeout $timeout
5527 # A list of global variables that GDB testcases should not use.
5528 # We try to prevent their use by monitoring write accesses and raising
5529 # an error when that happens.
5530 set banned_variables { bug_id prms_id }
5532 # A list of procedures that GDB testcases should not use.
5533 # We try to prevent their use by monitoring invocations and raising
5534 # an error when that happens.
5535 set banned_procedures { strace }
5537 # gdb_init is called by runtest at start, but also by several
5538 # tests directly; gdb_finish is only called from within runtest after
5539 # each test source execution.
5540 # Placing several traces by repetitive calls to gdb_init leads
5541 # to problems, as only one trace is removed in gdb_finish.
5542 # To overcome this possible problem, we add a variable that records
5543 # if the banned variables and procedures are already traced.
5546 # Global array that holds the name of all global variables at the time
5547 # a test script is started. After the test script has completed any
5548 # global not in this list is deleted.
5549 array set gdb_known_globals {}
5551 # Setup the GDB_KNOWN_GLOBALS array with the names of all current
5553 proc gdb_setup_known_globals {} {
5554 global gdb_known_globals
5556 array set gdb_known_globals {}
5557 foreach varname [info globals] {
5558 set gdb_known_globals($varname) 1
5562 # Cleanup the global namespace. Any global not in the
5563 # GDB_KNOWN_GLOBALS array is unset, this ensures we don't "leak"
5564 # globals from one test script to another.
5565 proc gdb_cleanup_globals {} {
5566 global gdb_known_globals gdb_persistent_globals
5568 foreach varname [info globals] {
5569 if {![info exists gdb_known_globals($varname)]} {
5570 if { [info exists gdb_persistent_globals($varname)] } {
5573 uplevel #0 unset $varname
5578 # Create gdb_tcl_unknown, a copy tcl's ::unknown, provided it's present as a
5580 set temp [interp create]
5581 if { [interp eval $temp "info procs ::unknown"] != "" } {
5582 set old_args [interp eval $temp "info args ::unknown"]
5583 set old_body [interp eval $temp "info body ::unknown"]
5584 eval proc gdb_tcl_unknown {$old_args} {$old_body}
5589 # GDB implementation of ${tool}_init. Called right before executing the
5591 # Overridable function -- you can override this function in your
5593 proc gdb_init { args } {
5594 # A baseboard file overriding this proc and calling the default version
5595 # should behave the same as this proc. So, don't add code here, but to
5596 # the default version instead.
5597 return [default_gdb_init {*}$args]
5600 # GDB implementation of ${tool}_finish. Called right after executing the
5602 proc gdb_finish { } {
5603 global gdbserver_reconnect_p
5606 global known_globals
5608 if { [info procs ::gdb_tcl_unknown] != "" } {
5609 # Restore dejagnu's version of proc unknown.
5611 rename ::dejagnu_unknown ::unknown
5614 # Exit first, so that the files are no longer in use.
5617 if { [llength $cleanfiles] > 0 } {
5618 eval remote_file target delete $cleanfiles
5622 # Unblock write access to the banned variables. Dejagnu typically
5623 # resets some of them between testcases.
5624 global banned_variables
5625 global banned_procedures
5626 global banned_traced
5627 if ($banned_traced) {
5628 foreach banned_var $banned_variables {
5629 global "$banned_var"
5630 trace remove variable "$banned_var" write error
5632 foreach banned_proc $banned_procedures {
5633 global "$banned_proc"
5634 trace remove execution "$banned_proc" enter error
5639 global gdb_finish_hooks
5640 foreach gdb_finish_hook $gdb_finish_hooks {
5643 set gdb_finish_hooks [list]
5649 set debug_format "unknown"
5651 # Run the gdb command "info source" and extract the debugging format
5652 # information from the output and save it in debug_format.
5654 proc get_debug_format { } {
5659 set debug_format "unknown"
5660 send_gdb "info source\n"
5662 -re "Compiled with (.*) debugging format.\r\n.*$gdb_prompt $" {
5663 set debug_format $expect_out(1,string)
5664 verbose "debug format is $debug_format"
5667 -re "No current source file.\r\n$gdb_prompt $" {
5668 perror "get_debug_format used when no current source file"
5671 -re "$gdb_prompt $" {
5672 warning "couldn't check debug format (no valid response)."
5676 warning "couldn't check debug format (timeout)."
5682 # Return true if FORMAT matches the debug format the current test was
5683 # compiled with. FORMAT is a shell-style globbing pattern; it can use
5684 # `*', `[...]', and so on.
5686 # This function depends on variables set by `get_debug_format', above.
5688 proc test_debug_format {format} {
5691 return [expr [string match $format $debug_format] != 0]
5694 # Like setup_xfail, but takes the name of a debug format (DWARF 1,
5695 # COFF, stabs, etc). If that format matches the format that the
5696 # current test was compiled with, then the next test is expected to
5697 # fail for any target. Returns 1 if the next test or set of tests is
5698 # expected to fail, 0 otherwise (or if it is unknown). Must have
5699 # previously called get_debug_format.
5700 proc setup_xfail_format { format } {
5701 set ret [test_debug_format $format]
5709 # gdb_get_line_number TEXT [FILE]
5711 # Search the source file FILE, and return the line number of the
5712 # first line containing TEXT. If no match is found, an error is thrown.
5714 # TEXT is a string literal, not a regular expression.
5716 # The default value of FILE is "$srcdir/$subdir/$srcfile". If FILE is
5717 # specified, and does not start with "/", then it is assumed to be in
5718 # "$srcdir/$subdir". This is awkward, and can be fixed in the future,
5719 # by changing the callers and the interface at the same time.
5720 # In particular: gdb.base/break.exp, gdb.base/condbreak.exp,
5721 # gdb.base/ena-dis-br.exp.
5723 # Use this function to keep your test scripts independent of the
5724 # exact line numbering of the source file. Don't write:
5726 # send_gdb "break 20"
5728 # This means that if anyone ever edits your test's source file,
5729 # your test could break. Instead, put a comment like this on the
5730 # source file line you want to break at:
5732 # /* breakpoint spot: frotz.exp: test name */
5734 # and then write, in your test script (which we assume is named
5737 # send_gdb "break [gdb_get_line_number "frotz.exp: test name"]\n"
5739 # (Yes, Tcl knows how to handle the nested quotes and brackets.
5742 # % puts "foo [lindex "bar baz" 1]"
5745 # Tcl is quite clever, for a little stringy language.)
5749 # The previous implementation of this procedure used the gdb search command.
5750 # This version is different:
5752 # . It works with MI, and it also works when gdb is not running.
5754 # . It operates on the build machine, not the host machine.
5756 # . For now, this implementation fakes a current directory of
5757 # $srcdir/$subdir to be compatible with the old implementation.
5758 # This will go away eventually and some callers will need to
5761 # . The TEXT argument is literal text and matches literally,
5762 # not a regular expression as it was before.
5764 # . State changes in gdb, such as changing the current file
5765 # and setting $_, no longer happen.
5767 # After a bit of time we can forget about the differences from the
5768 # old implementation.
5770 # --chastain 2004-08-05
5772 proc gdb_get_line_number { text { file "" } } {
5777 if { "$file" == "" } then {
5780 if { ! [regexp "^/" "$file"] } then {
5781 set file "$srcdir/$subdir/$file"
5784 if { [ catch { set fd [open "$file"] } message ] } then {
5789 for { set line 1 } { 1 } { incr line } {
5790 if { [ catch { set nchar [gets "$fd" body] } message ] } then {
5793 if { $nchar < 0 } then {
5796 if { [string first "$text" "$body"] >= 0 } then {
5802 if { [ catch { close "$fd" } message ] } then {
5807 error "undefined tag \"$text\""
5813 # Continue the program until it ends.
5815 # MSSG is the error message that gets printed. If not given, a
5817 # COMMAND is the command to invoke. If not given, "continue" is
5819 # ALLOW_EXTRA is a flag indicating whether the test should expect
5820 # extra output between the "Continuing." line and the program
5821 # exiting. By default it is zero; if nonzero, any extra output
5824 proc gdb_continue_to_end {{mssg ""} {command continue} {allow_extra 0}} {
5825 global inferior_exited_re use_gdb_stub
5828 set text "continue until exit"
5830 set text "continue until exit at $mssg"
5838 # By default, we don't rely on exit() behavior of remote stubs --
5839 # it's common for exit() to be implemented as a simple infinite
5840 # loop, or a forced crash/reset. For native targets, by default, we
5841 # assume process exit is reported as such. If a non-reliable target
5842 # is used, we set a breakpoint at exit, and continue to that.
5843 if { [target_info exists exit_is_reliable] } {
5844 set exit_is_reliable [target_info exit_is_reliable]
5846 set exit_is_reliable [expr ! $use_gdb_stub]
5849 if { ! $exit_is_reliable } {
5850 if {![gdb_breakpoint "exit"]} {
5853 gdb_test $command "Continuing..*Breakpoint .*exit.*" \
5856 # Continue until we exit. Should not stop again.
5857 # Don't bother to check the output of the program, that may be
5858 # extremely tough for some remote systems.
5860 "Continuing.\[\r\n0-9\]+${extra}(... EXIT code 0\[\r\n\]+|$inferior_exited_re normally).*"\
5865 proc rerun_to_main {} {
5866 global gdb_prompt use_gdb_stub
5871 -re ".*Breakpoint .*main .*$gdb_prompt $"\
5872 {pass "rerun to main" ; return 0}
5873 -re "$gdb_prompt $"\
5874 {fail "rerun to main" ; return 0}
5875 timeout {fail "(timeout) rerun to main" ; return 0}
5880 -re "The program .* has been started already.*y or n. $" {
5881 send_gdb "y\n" answer
5884 -re "Starting program.*$gdb_prompt $"\
5885 {pass "rerun to main" ; return 0}
5886 -re "$gdb_prompt $"\
5887 {fail "rerun to main" ; return 0}
5888 timeout {fail "(timeout) rerun to main" ; return 0}
5893 # Return true if EXECUTABLE contains a .gdb_index or .debug_names index section.
5895 proc exec_has_index_section { executable } {
5896 set readelf_program [gdb_find_readelf]
5897 set res [catch {exec $readelf_program -S $executable \
5898 | grep -E "\.gdb_index|\.debug_names" }]
5905 # Return list with major and minor version of readelf, or an empty list.
5906 gdb_caching_proc readelf_version {
5907 set readelf_program [gdb_find_readelf]
5908 set res [catch {exec $readelf_program --version} output]
5912 set lines [split $output \n]
5913 set line [lindex $lines 0]
5914 set res [regexp {[ \t]+([0-9]+)[.]([0-9]+)[^ \t]*$} \
5915 $line dummy major minor]
5919 return [list $major $minor]
5922 # Return 1 if readelf prints the PIE flag, 0 if is doesn't, and -1 if unknown.
5923 proc readelf_prints_pie { } {
5924 set version [readelf_version]
5925 if { [llength $version] == 0 } {
5928 set major [lindex $version 0]
5929 set minor [lindex $version 1]
5930 # It would be better to construct a PIE executable and test if the PIE
5931 # flag is printed by readelf, but we cannot reliably construct a PIE
5932 # executable if the multilib_flags dictate otherwise
5933 # (--target_board=unix/-no-pie/-fno-PIE).
5934 return [version_at_least $major $minor 2 26]
5937 # Return 1 if EXECUTABLE is a Position Independent Executable, 0 if it is not,
5938 # and -1 if unknown.
5940 proc exec_is_pie { executable } {
5941 set res [readelf_prints_pie]
5945 set readelf_program [gdb_find_readelf]
5946 # We're not testing readelf -d | grep "FLAGS_1.*Flags:.*PIE"
5947 # because the PIE flag is not set by all versions of gold, see PR
5949 set res [catch {exec $readelf_program -h $executable} output]
5953 set res [regexp -line {^[ \t]*Type:[ \t]*DYN \(Shared object file\)$} \
5961 # Return true if a test should be skipped due to lack of floating
5962 # point support or GDB can't fetch the contents from floating point
5965 gdb_caching_proc gdb_skip_float_test {
5966 if [target_info exists gdb,skip_float_tests] {
5970 # There is an ARM kernel ptrace bug that hardware VFP registers
5971 # are not updated after GDB ptrace set VFP registers. The bug
5972 # was introduced by kernel commit 8130b9d7b9d858aa04ce67805e8951e3cb6e9b2f
5973 # in 2012 and is fixed in e2dfb4b880146bfd4b6aa8e138c0205407cebbaf
5974 # in May 2016. In other words, kernels older than 4.6.3, 4.4.14,
5975 # 4.1.27, 3.18.36, and 3.14.73 have this bug.
5976 # This kernel bug is detected by check how does GDB change the
5977 # program result by changing one VFP register.
5978 if { [istarget "arm*-*-linux*"] } {
5980 set compile_flags {debug nowarnings }
5982 # Set up, compile, and execute a test program having VFP
5984 set src [standard_temp_file arm_vfp[pid].c]
5985 set exe [standard_temp_file arm_vfp[pid].x]
5987 gdb_produce_source $src {
5992 asm ("vldr d0, [%0]" : : "r" (&d));
5993 asm ("vldr d1, [%0]" : : "r" (&d));
5994 asm (".global break_here\n"
5996 asm ("vcmp.f64 d0, d1\n"
5997 "vmrs APSR_nzcv, fpscr\n"
5998 "bne L_value_different\n"
6001 "L_value_different:\n"
6003 "L_end:\n" : "=r" (ret) :);
6005 /* Return $d0 != $d1. */
6010 verbose "compiling testfile $src" 2
6011 set lines [gdb_compile $src $exe executable $compile_flags]
6014 if ![string match "" $lines] then {
6015 verbose "testfile compilation failed, returning 1" 2
6019 # No error message, compilation succeeded so now run it via gdb.
6020 # Run the test up to 5 times to detect whether ptrace can
6021 # correctly update VFP registers or not.
6023 for {set i 0} {$i < 5} {incr i} {
6024 global gdb_prompt srcdir subdir
6028 gdb_reinitialize_dir $srcdir/$subdir
6032 gdb_test "break *break_here"
6033 gdb_continue_to_breakpoint "break_here"
6035 # Modify $d0 to a different value, so the exit code should
6037 gdb_test "set \$d0 = 5.0"
6039 set test "continue to exit"
6040 gdb_test_multiple "continue" "$test" {
6041 -re "exited with code 01.*$gdb_prompt $" {
6043 -re "exited normally.*$gdb_prompt $" {
6044 # However, the exit code is 0. That means something
6045 # wrong in setting VFP registers.
6053 remote_file build delete $exe
6055 return $skip_vfp_test
6060 # Print a message and return true if a test should be skipped
6061 # due to lack of stdio support.
6063 proc gdb_skip_stdio_test { msg } {
6064 if [target_info exists gdb,noinferiorio] {
6065 verbose "Skipping test '$msg': no inferior i/o."
6071 proc gdb_skip_bogus_test { msg } {
6075 # Return true if a test should be skipped due to lack of XML support
6077 # NOTE: This must be called while gdb is *not* running.
6079 gdb_caching_proc gdb_skip_xml_test {
6084 if { [info exists gdb_spawn_id] } {
6085 error "GDB must not be running in gdb_skip_xml_tests."
6088 set xml_file [gdb_remote_download host "${srcdir}/gdb.xml/trivial.xml"]
6092 gdb_test_multiple "set tdesc filename $xml_file" "" {
6093 -re ".*XML support was disabled at compile time.*$gdb_prompt $" {
6096 -re ".*$gdb_prompt $" { }
6102 # Return true if argv[0] is available.
6104 gdb_caching_proc gdb_has_argv0 {
6107 # Compile and execute a test program to check whether argv[0] is available.
6108 gdb_simple_compile has_argv0 {
6109 int main (int argc, char **argv) {
6116 proc gdb_has_argv0_1 { exe } {
6117 global srcdir subdir
6118 global gdb_prompt hex
6122 gdb_reinitialize_dir $srcdir/$subdir
6125 # Set breakpoint on main.
6126 gdb_test_multiple "break -q main" "break -q main" {
6127 -re "Breakpoint.*${gdb_prompt} $" {
6129 -re "${gdb_prompt} $" {
6136 gdb_test_multiple "" "run to main" {
6137 -re "Breakpoint.*${gdb_prompt} $" {
6139 -re "${gdb_prompt} $" {
6144 set old_elements "200"
6145 set test "show print elements"
6146 gdb_test_multiple $test $test {
6147 -re "Limit on string chars or array elements to print is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
6148 set old_elements $expect_out(1,string)
6151 set old_repeats "200"
6152 set test "show print repeats"
6153 gdb_test_multiple $test $test {
6154 -re "Threshold for repeated print elements is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
6155 set old_repeats $expect_out(1,string)
6158 gdb_test_no_output "set print elements unlimited" ""
6159 gdb_test_no_output "set print repeats unlimited" ""
6162 # Check whether argc is 1.
6163 gdb_test_multiple "p argc" "p argc" {
6164 -re " = 1\r\n${gdb_prompt} $" {
6166 gdb_test_multiple "p argv\[0\]" "p argv\[0\]" {
6167 -re " = $hex \".*[file tail $exe]\"\r\n${gdb_prompt} $" {
6170 -re "${gdb_prompt} $" {
6174 -re "${gdb_prompt} $" {
6178 gdb_test_no_output "set print elements $old_elements" ""
6179 gdb_test_no_output "set print repeats $old_repeats" ""
6184 set result [gdb_has_argv0_1 $obj]
6190 && ([istarget *-*-linux*]
6191 || [istarget *-*-freebsd*] || [istarget *-*-kfreebsd*]
6192 || [istarget *-*-netbsd*] || [istarget *-*-knetbsd*]
6193 || [istarget *-*-openbsd*]
6194 || [istarget *-*-darwin*]
6195 || [istarget *-*-solaris*]
6196 || [istarget *-*-aix*]
6197 || [istarget *-*-gnu*]
6198 || [istarget *-*-cygwin*] || [istarget *-*-mingw32*]
6199 || [istarget *-*-*djgpp*] || [istarget *-*-go32*]
6200 || [istarget *-wince-pe] || [istarget *-*-mingw32ce*]
6201 || [istarget *-*-osf*]
6202 || [istarget *-*-dicos*]
6203 || [istarget *-*-nto*]
6204 || [istarget *-*-*vms*]
6205 || [istarget *-*-lynx*178]) } {
6206 fail "argv\[0\] should be available on this target"
6212 # Note: the procedure gdb_gnu_strip_debug will produce an executable called
6213 # ${binfile}.dbglnk, which is just like the executable ($binfile) but without
6214 # the debuginfo. Instead $binfile has a .gnu_debuglink section which contains
6215 # the name of a debuginfo only file. This file will be stored in the same
6218 # Functions for separate debug info testing
6220 # starting with an executable:
6221 # foo --> original executable
6223 # at the end of the process we have:
6224 # foo.stripped --> foo w/o debug info
6225 # foo.debug --> foo's debug info
6226 # foo --> like foo, but with a new .gnu_debuglink section pointing to foo.debug.
6228 # Fetch the build id from the file.
6229 # Returns "" if there is none.
6231 proc get_build_id { filename } {
6232 if { ([istarget "*-*-mingw*"]
6233 || [istarget *-*-cygwin*]) } {
6234 set objdump_program [gdb_find_objdump]
6235 set result [catch {set data [exec $objdump_program -p $filename | grep signature | cut "-d " -f4]} output]
6236 verbose "result is $result"
6237 verbose "output is $output"
6243 set tmp [standard_output_file "${filename}-tmp"]
6244 set objcopy_program [gdb_find_objcopy]
6245 set result [catch "exec $objcopy_program -j .note.gnu.build-id -O binary $filename $tmp" output]
6246 verbose "result is $result"
6247 verbose "output is $output"
6252 fconfigure $fi -translation binary
6253 # Skip the NOTE header.
6258 if ![string compare $data ""] then {
6261 # Convert it to hex.
6262 binary scan $data H* data
6267 # Return the build-id hex string (usually 160 bits as 40 hex characters)
6268 # converted to the form: .build-id/ab/cdef1234...89.debug
6269 # Return "" if no build-id found.
6270 proc build_id_debug_filename_get { filename } {
6271 set data [get_build_id $filename]
6272 if { $data == "" } {
6275 regsub {^..} $data {\0/} data
6276 return ".build-id/${data}.debug"
6279 # Create stripped files for DEST, replacing it. If ARGS is passed, it is a
6280 # list of optional flags. The only currently supported flag is no-main,
6281 # which removes the symbol entry for main from the separate debug file.
6283 # Function returns zero on success. Function will return non-zero failure code
6284 # on some targets not supporting separate debug info (such as i386-msdos).
6286 proc gdb_gnu_strip_debug { dest args } {
6288 # Use the first separate debug info file location searched by GDB so the
6289 # run cannot be broken by some stale file searched with higher precedence.
6290 set debug_file "${dest}.debug"
6292 set strip_to_file_program [transform strip]
6293 set objcopy_program [gdb_find_objcopy]
6295 set debug_link [file tail $debug_file]
6296 set stripped_file "${dest}.stripped"
6298 # Get rid of the debug info, and store result in stripped_file
6299 # something like gdb/testsuite/gdb.base/blah.stripped.
6300 set result [catch "exec $strip_to_file_program --strip-debug ${dest} -o ${stripped_file}" output]
6301 verbose "result is $result"
6302 verbose "output is $output"
6307 # Workaround PR binutils/10802:
6308 # Preserve the 'x' bit also for PIEs (Position Independent Executables).
6309 set perm [file attributes ${dest} -permissions]
6310 file attributes ${stripped_file} -permissions $perm
6312 # Get rid of everything but the debug info, and store result in debug_file
6313 # This will be in the .debug subdirectory, see above.
6314 set result [catch "exec $strip_to_file_program --only-keep-debug ${dest} -o ${debug_file}" output]
6315 verbose "result is $result"
6316 verbose "output is $output"
6321 # If no-main is passed, strip the symbol for main from the separate
6322 # file. This is to simulate the behavior of elfutils's eu-strip, which
6323 # leaves the symtab in the original file only. There's no way to get
6324 # objcopy or strip to remove the symbol table without also removing the
6325 # debugging sections, so this is as close as we can get.
6326 if { [llength $args] == 1 && [lindex $args 0] == "no-main" } {
6327 set result [catch "exec $objcopy_program -N main ${debug_file} ${debug_file}-tmp" output]
6328 verbose "result is $result"
6329 verbose "output is $output"
6333 file delete "${debug_file}"
6334 file rename "${debug_file}-tmp" "${debug_file}"
6337 # Link the two previous output files together, adding the .gnu_debuglink
6338 # section to the stripped_file, containing a pointer to the debug_file,
6339 # save the new file in dest.
6340 # This will be the regular executable filename, in the usual location.
6341 set result [catch "exec $objcopy_program --add-gnu-debuglink=${debug_file} ${stripped_file} ${dest}" output]
6342 verbose "result is $result"
6343 verbose "output is $output"
6348 # Workaround PR binutils/10802:
6349 # Preserve the 'x' bit also for PIEs (Position Independent Executables).
6350 set perm [file attributes ${stripped_file} -permissions]
6351 file attributes ${dest} -permissions $perm
6356 # Test the output of GDB_COMMAND matches the pattern obtained
6357 # by concatenating all elements of EXPECTED_LINES. This makes
6358 # it possible to split otherwise very long string into pieces.
6359 # If third argument TESTNAME is not empty, it's used as the name of the
6360 # test to be printed on pass/fail.
6361 proc help_test_raw { gdb_command expected_lines {testname {}} } {
6362 set expected_output [join $expected_lines ""]
6363 if {$testname != {}} {
6364 gdb_test "${gdb_command}" "${expected_output}" $testname
6368 gdb_test "${gdb_command}" "${expected_output}"
6371 # A regexp that matches the end of help CLASS|PREFIX_COMMAND
6372 set help_list_trailer {
6373 "Type \"apropos word\" to search for commands related to \"word\"\.[\r\n]+"
6374 "Type \"apropos -v word\" for full documentation of commands related to \"word\"\.[\r\n]+"
6375 "Command name abbreviations are allowed if unambiguous\."
6378 # Test the output of "help COMMAND_CLASS". EXPECTED_INITIAL_LINES
6379 # are regular expressions that should match the beginning of output,
6380 # before the list of commands in that class.
6381 # LIST_OF_COMMANDS are regular expressions that should match the
6382 # list of commands in that class. If empty, the command list will be
6383 # matched automatically. The presence of standard epilogue will be tested
6385 # If last argument TESTNAME is not empty, it's used as the name of the
6386 # test to be printed on pass/fail.
6387 # Notice that the '[' and ']' characters don't need to be escaped for strings
6388 # wrapped in {} braces.
6389 proc test_class_help { command_class expected_initial_lines {list_of_commands {}} {testname {}} } {
6390 global help_list_trailer
6391 if {[llength $list_of_commands]>0} {
6392 set l_list_of_commands {"List of commands:[\r\n]+[\r\n]+"}
6393 set l_list_of_commands [concat $l_list_of_commands $list_of_commands]
6394 set l_list_of_commands [concat $l_list_of_commands {"[\r\n]+[\r\n]+"}]
6396 set l_list_of_commands {"List of commands\:.*[\r\n]+"}
6399 "Type \"help\" followed by command name for full documentation\.[\r\n]+"
6401 set l_entire_body [concat $expected_initial_lines $l_list_of_commands \
6402 $l_stock_body $help_list_trailer]
6404 help_test_raw "help ${command_class}" $l_entire_body $testname
6407 # Like test_class_help but specialised to test "help user-defined".
6408 proc test_user_defined_class_help { {list_of_commands {}} {testname {}} } {
6409 test_class_help "user-defined" {
6410 "User-defined commands\.[\r\n]+"
6411 "The commands in this class are those defined by the user\.[\r\n]+"
6412 "Use the \"define\" command to define a command\.[\r\n]+"
6413 } $list_of_commands $testname
6417 # COMMAND_LIST should have either one element -- command to test, or
6418 # two elements -- abbreviated command to test, and full command the first
6419 # element is abbreviation of.
6420 # The command must be a prefix command. EXPECTED_INITIAL_LINES
6421 # are regular expressions that should match the beginning of output,
6422 # before the list of subcommands. The presence of
6423 # subcommand list and standard epilogue will be tested automatically.
6424 proc test_prefix_command_help { command_list expected_initial_lines args } {
6425 global help_list_trailer
6426 set command [lindex $command_list 0]
6427 if {[llength $command_list]>1} {
6428 set full_command [lindex $command_list 1]
6430 set full_command $command
6432 # Use 'list' and not just {} because we want variables to
6433 # be expanded in this list.
6434 set l_stock_body [list\
6435 "List of $full_command subcommands\:.*\[\r\n\]+"\
6436 "Type \"help $full_command\" followed by $full_command subcommand name for full documentation\.\[\r\n\]+"]
6437 set l_entire_body [concat $expected_initial_lines $l_stock_body $help_list_trailer]
6438 if {[llength $args]>0} {
6439 help_test_raw "help ${command}" $l_entire_body [lindex $args 0]
6441 help_test_raw "help ${command}" $l_entire_body
6445 # Build executable named EXECUTABLE from specifications that allow
6446 # different options to be passed to different sub-compilations.
6447 # TESTNAME is the name of the test; this is passed to 'untested' if
6449 # OPTIONS is passed to the final link, using gdb_compile. If OPTIONS
6450 # contains the option "pthreads", then gdb_compile_pthreads is used.
6451 # ARGS is a flat list of source specifications, of the form:
6452 # { SOURCE1 OPTIONS1 [ SOURCE2 OPTIONS2 ]... }
6453 # Each SOURCE is compiled to an object file using its OPTIONS,
6454 # using gdb_compile.
6455 # Returns 0 on success, -1 on failure.
6456 proc build_executable_from_specs {testname executable options args} {
6460 set binfile [standard_output_file $executable]
6463 if { [lsearch -exact $options "c++"] >= 0 } {
6464 set info_options "c++"
6466 if [get_compiler_info ${info_options}] {
6470 set func gdb_compile
6471 set func_index [lsearch -regexp $options {^(pthreads|shlib|shlib_pthreads|openmp)$}]
6472 if {$func_index != -1} {
6473 set func "${func}_[lindex $options $func_index]"
6476 # gdb_compile_shlib and gdb_compile_shlib_pthreads do not use the 3rd
6477 # parameter. They also requires $sources while gdb_compile and
6478 # gdb_compile_pthreads require $objects. Moreover they ignore any options.
6479 if [string match gdb_compile_shlib* $func] {
6481 foreach {s local_options} $args {
6482 if { [regexp "^/" "$s"] } then {
6483 lappend sources_path "$s"
6485 lappend sources_path "$srcdir/$subdir/$s"
6488 set ret [$func $sources_path "${binfile}" $options]
6489 } elseif {[lsearch -exact $options rust] != -1} {
6491 foreach {s local_options} $args {
6492 if { [regexp "^/" "$s"] } then {
6493 lappend sources_path "$s"
6495 lappend sources_path "$srcdir/$subdir/$s"
6498 set ret [gdb_compile_rust $sources_path "${binfile}" $options]
6502 foreach {s local_options} $args {
6503 if { ! [regexp "^/" "$s"] } then {
6504 set s "$srcdir/$subdir/$s"
6506 if { [$func "${s}" "${binfile}${i}.o" object $local_options] != "" } {
6510 lappend objects "${binfile}${i}.o"
6513 set ret [$func $objects "${binfile}" executable $options]
6523 # Build executable named EXECUTABLE, from SOURCES. If SOURCES are not
6524 # provided, uses $EXECUTABLE.c. The TESTNAME paramer is the name of test
6525 # to pass to untested, if something is wrong. OPTIONS are passed
6526 # to gdb_compile directly.
6527 proc build_executable { testname executable {sources ""} {options {debug}} } {
6528 if {[llength $sources]==0} {
6529 set sources ${executable}.c
6532 set arglist [list $testname $executable $options]
6533 foreach source $sources {
6534 lappend arglist $source $options
6537 return [eval build_executable_from_specs $arglist]
6540 # Starts fresh GDB binary and loads an optional executable into GDB.
6541 # Usage: clean_restart [executable]
6542 # EXECUTABLE is the basename of the binary.
6543 # Return -1 if starting gdb or loading the executable failed.
6545 proc clean_restart { args } {
6551 if { [llength $args] > 1 } {
6552 error "bad number of args: [llength $args]"
6557 # This is a clean restart, so reset error and warning count.
6562 # if { [gdb_start] == -1 } {
6565 # but gdb_start is a ${tool}_start proc, which doesn't have a defined
6566 # return value. So instead, we test for errcnt.
6568 if { $errcnt > 0 } {
6572 gdb_reinitialize_dir $srcdir/$subdir
6574 if { [llength $args] >= 1 } {
6575 set executable [lindex $args 0]
6576 set binfile [standard_output_file ${executable}]
6577 return [gdb_load ${binfile}]
6583 # Prepares for testing by calling build_executable_full, then
6585 # TESTNAME is the name of the test.
6586 # Each element in ARGS is a list of the form
6587 # { EXECUTABLE OPTIONS SOURCE_SPEC... }
6588 # These are passed to build_executable_from_specs, which see.
6589 # The last EXECUTABLE is passed to clean_restart.
6590 # Returns 0 on success, non-zero on failure.
6591 proc prepare_for_testing_full {testname args} {
6592 foreach spec $args {
6593 if {[eval build_executable_from_specs [list $testname] $spec] == -1} {
6596 set executable [lindex $spec 0]
6598 clean_restart $executable
6602 # Prepares for testing, by calling build_executable, and then clean_restart.
6603 # Please refer to build_executable for parameter description.
6604 proc prepare_for_testing { testname executable {sources ""} {options {debug}}} {
6606 if {[build_executable $testname $executable $sources $options] == -1} {
6609 clean_restart $executable
6614 # Retrieve the value of EXP in the inferior, represented in format
6615 # specified in FMT (using "printFMT"). DEFAULT is used as fallback if
6616 # print fails. TEST is the test message to use. It can be omitted,
6617 # in which case a test message is built from EXP.
6619 proc get_valueof { fmt exp default {test ""} } {
6623 set test "get valueof \"${exp}\""
6627 gdb_test_multiple "print${fmt} ${exp}" "$test" {
6628 -re "\\$\[0-9\]* = (\[^\r\n\]*)\[\r\n\]*$gdb_prompt $" {
6629 set val $expect_out(1,string)
6633 fail "$test (timeout)"
6639 # Retrieve the value of local var EXP in the inferior. DEFAULT is used as
6640 # fallback if print fails. TEST is the test message to use. It can be
6641 # omitted, in which case a test message is built from EXP.
6643 proc get_local_valueof { exp default {test ""} } {
6647 set test "get local valueof \"${exp}\""
6651 gdb_test_multiple "info locals ${exp}" "$test" {
6652 -re "$exp = (\[^\r\n\]*)\[\r\n\]*$gdb_prompt $" {
6653 set val $expect_out(1,string)
6657 fail "$test (timeout)"
6663 # Retrieve the value of EXP in the inferior, as a signed decimal value
6664 # (using "print /d"). DEFAULT is used as fallback if print fails.
6665 # TEST is the test message to use. It can be omitted, in which case
6666 # a test message is built from EXP.
6668 proc get_integer_valueof { exp default {test ""} } {
6672 set test "get integer valueof \"${exp}\""
6676 gdb_test_multiple "print /d ${exp}" "$test" {
6677 -re "\\$\[0-9\]* = (\[-\]*\[0-9\]*).*$gdb_prompt $" {
6678 set val $expect_out(1,string)
6682 fail "$test (timeout)"
6688 # Retrieve the value of EXP in the inferior, as an hexadecimal value
6689 # (using "print /x"). DEFAULT is used as fallback if print fails.
6690 # TEST is the test message to use. It can be omitted, in which case
6691 # a test message is built from EXP.
6693 proc get_hexadecimal_valueof { exp default {test ""} } {
6697 set test "get hexadecimal valueof \"${exp}\""
6701 gdb_test_multiple "print /x ${exp}" $test {
6702 -re "\\$\[0-9\]* = (0x\[0-9a-zA-Z\]+).*$gdb_prompt $" {
6703 set val $expect_out(1,string)
6710 # Retrieve the size of TYPE in the inferior, as a decimal value. DEFAULT
6711 # is used as fallback if print fails. TEST is the test message to use.
6712 # It can be omitted, in which case a test message is 'sizeof (TYPE)'.
6714 proc get_sizeof { type default {test ""} } {
6715 return [get_integer_valueof "sizeof (${type})" $default $test]
6718 proc get_target_charset { } {
6721 gdb_test_multiple "show target-charset" "" {
6722 -re "The target character set is \"auto; currently (\[^\"\]*)\".*$gdb_prompt $" {
6723 return $expect_out(1,string)
6725 -re "The target character set is \"(\[^\"\]*)\".*$gdb_prompt $" {
6726 return $expect_out(1,string)
6730 # Pick a reasonable default.
6731 warning "Unable to read target-charset."
6735 # Get the address of VAR.
6737 proc get_var_address { var } {
6738 global gdb_prompt hex
6740 # Match output like:
6742 # $5 = (int (*)()) 0
6743 # $6 = (int (*)()) 0x24 <function_bar>
6745 gdb_test_multiple "print &${var}" "get address of ${var}" {
6746 -re "\\\$\[0-9\]+ = \\(.*\\) (0|$hex)( <${var}>)?\[\r\n\]+${gdb_prompt} $"
6748 pass "get address of ${var}"
6749 if { $expect_out(1,string) == "0" } {
6752 return $expect_out(1,string)
6759 # Return the frame number for the currently selected frame
6760 proc get_current_frame_number {{test_name ""}} {
6763 if { $test_name == "" } {
6764 set test_name "get current frame number"
6767 gdb_test_multiple "frame" $test_name {
6768 -re "#(\[0-9\]+) .*$gdb_prompt $" {
6769 set frame_num $expect_out(1,string)
6775 # Get the current value for remotetimeout and return it.
6776 proc get_remotetimeout { } {
6780 gdb_test_multiple "show remotetimeout" "" {
6781 -re "Timeout limit to wait for target to respond is ($decimal).*$gdb_prompt $" {
6782 return $expect_out(1,string)
6786 # Pick the default that gdb uses
6787 warning "Unable to read remotetimeout"
6791 # Set the remotetimeout to the specified timeout. Nothing is returned.
6792 proc set_remotetimeout { timeout } {
6795 gdb_test_multiple "set remotetimeout $timeout" "" {
6796 -re "$gdb_prompt $" {
6797 verbose "Set remotetimeout to $timeout\n"
6802 # Get the target's current endianness and return it.
6803 proc get_endianness { } {
6806 gdb_test_multiple "show endian" "determine endianness" {
6807 -re ".* (little|big) endian.*\r\n$gdb_prompt $" {
6809 return $expect_out(1,string)
6815 # ROOT and FULL are file names. Returns the relative path from ROOT
6816 # to FULL. Note that FULL must be in a subdirectory of ROOT.
6817 # For example, given ROOT = /usr/bin and FULL = /usr/bin/ls, this
6820 proc relative_filename {root full} {
6821 set root_split [file split $root]
6822 set full_split [file split $full]
6824 set len [llength $root_split]
6826 if {[eval file join $root_split]
6827 != [eval file join [lrange $full_split 0 [expr {$len - 1}]]]} {
6828 error "$full not a subdir of $root"
6831 return [eval file join [lrange $full_split $len end]]
6834 # If GDB_PARALLEL exists, then set up the parallel-mode directories.
6835 if {[info exists GDB_PARALLEL]} {
6836 if {[is_remote host]} {
6840 [make_gdb_parallel_path outputs] \
6841 [make_gdb_parallel_path temp] \
6842 [make_gdb_parallel_path cache]
6846 proc core_find {binfile {deletefiles {}} {arg ""}} {
6847 global objdir subdir
6849 set destcore "$binfile.core"
6850 file delete $destcore
6852 # Create a core file named "$destcore" rather than just "core", to
6853 # avoid problems with sys admin types that like to regularly prune all
6854 # files named "core" from the system.
6856 # Arbitrarily try setting the core size limit to "unlimited" since
6857 # this does not hurt on systems where the command does not work and
6858 # allows us to generate a core on systems where it does.
6860 # Some systems append "core" to the name of the program; others append
6861 # the name of the program to "core"; still others (like Linux, as of
6862 # May 2003) create cores named "core.PID". In the latter case, we
6863 # could have many core files lying around, and it may be difficult to
6864 # tell which one is ours, so let's run the program in a subdirectory.
6866 set coredir [standard_output_file coredir.[getpid]]
6868 catch "system \"(cd ${coredir}; ulimit -c unlimited; ${binfile} ${arg}; true) >/dev/null 2>&1\""
6869 # remote_exec host "${binfile}"
6870 foreach i "${coredir}/core ${coredir}/core.coremaker.c ${binfile}.core" {
6871 if [remote_file build exists $i] {
6872 remote_exec build "mv $i $destcore"
6876 # Check for "core.PID".
6877 if { $found == 0 } {
6878 set names [glob -nocomplain -directory $coredir core.*]
6879 if {[llength $names] == 1} {
6880 set corefile [file join $coredir [lindex $names 0]]
6881 remote_exec build "mv $corefile $destcore"
6885 if { $found == 0 } {
6886 # The braindamaged HPUX shell quits after the ulimit -c above
6887 # without executing ${binfile}. So we try again without the
6888 # ulimit here if we didn't find a core file above.
6889 # Oh, I should mention that any "braindamaged" non-Unix system has
6890 # the same problem. I like the cd bit too, it's really neat'n stuff.
6891 catch "system \"(cd ${objdir}/${subdir}; ${binfile}; true) >/dev/null 2>&1\""
6892 foreach i "${objdir}/${subdir}/core ${objdir}/${subdir}/core.coremaker.c ${binfile}.core" {
6893 if [remote_file build exists $i] {
6894 remote_exec build "mv $i $destcore"
6900 # Try to clean up after ourselves.
6901 foreach deletefile $deletefiles {
6902 remote_file build delete [file join $coredir $deletefile]
6904 remote_exec build "rmdir $coredir"
6906 if { $found == 0 } {
6907 warning "can't generate a core file - core tests suppressed - check ulimit -c"
6913 # gdb_target_symbol_prefix compiles a test program and then examines
6914 # the output from objdump to determine the prefix (such as underscore)
6915 # for linker symbol prefixes.
6917 gdb_caching_proc gdb_target_symbol_prefix {
6918 # Compile a simple test program...
6919 set src { int main() { return 0; } }
6920 if {![gdb_simple_compile target_symbol_prefix $src executable]} {
6926 set objdump_program [gdb_find_objdump]
6927 set result [catch "exec $objdump_program --syms $obj" output]
6930 && ![regexp -lineanchor \
6931 { ([^ a-zA-Z0-9]*)main$} $output dummy prefix] } {
6932 verbose "gdb_target_symbol_prefix: Could not find main in objdump output; returning null prefix" 2
6940 # Return 1 if target supports scheduler locking, otherwise return 0.
6942 gdb_caching_proc target_supports_scheduler_locking {
6945 set me "gdb_target_supports_scheduler_locking"
6947 set src { int main() { return 0; } }
6948 if {![gdb_simple_compile $me $src executable]} {
6957 set supports_schedule_locking -1
6958 set current_schedule_locking_mode ""
6960 set test "reading current scheduler-locking mode"
6961 gdb_test_multiple "show scheduler-locking" $test {
6962 -re "Mode for locking scheduler during execution is \"(\[\^\"\]*)\".*$gdb_prompt" {
6963 set current_schedule_locking_mode $expect_out(1,string)
6965 -re "$gdb_prompt $" {
6966 set supports_schedule_locking 0
6969 set supports_schedule_locking 0
6973 if { $supports_schedule_locking == -1 } {
6974 set test "checking for scheduler-locking support"
6975 gdb_test_multiple "set scheduler-locking $current_schedule_locking_mode" $test {
6976 -re "Target '\[^'\]+' cannot support this command\..*$gdb_prompt $" {
6977 set supports_schedule_locking 0
6979 -re "$gdb_prompt $" {
6980 set supports_schedule_locking 1
6983 set supports_schedule_locking 0
6988 if { $supports_schedule_locking == -1 } {
6989 set supports_schedule_locking 0
6993 remote_file build delete $obj
6994 verbose "$me: returning $supports_schedule_locking" 2
6995 return $supports_schedule_locking
6998 # Return 1 if compiler supports use of nested functions. Otherwise,
7001 gdb_caching_proc support_nested_function_tests {
7002 # Compile a test program containing a nested function
7003 return [gdb_can_simple_compile nested_func {
7013 # gdb_target_symbol returns the provided symbol with the correct prefix
7014 # prepended. (See gdb_target_symbol_prefix, above.)
7016 proc gdb_target_symbol { symbol } {
7017 set prefix [gdb_target_symbol_prefix]
7018 return "${prefix}${symbol}"
7021 # gdb_target_symbol_prefix_flags_asm returns a string that can be
7022 # added to gdb_compile options to define the C-preprocessor macro
7023 # SYMBOL_PREFIX with a value that can be prepended to symbols
7024 # for targets which require a prefix, such as underscore.
7026 # This version (_asm) defines the prefix without double quotes
7027 # surrounding the prefix. It is used to define the macro
7028 # SYMBOL_PREFIX for assembly language files. Another version, below,
7029 # is used for symbols in inline assembler in C/C++ files.
7031 # The lack of quotes in this version (_asm) makes it possible to
7032 # define supporting macros in the .S file. (The version which
7033 # uses quotes for the prefix won't work for such files since it's
7034 # impossible to define a quote-stripping macro in C.)
7036 # It's possible to use this version (_asm) for C/C++ source files too,
7037 # but a string is usually required in such files; providing a version
7038 # (no _asm) which encloses the prefix with double quotes makes it
7039 # somewhat easier to define the supporting macros in the test case.
7041 proc gdb_target_symbol_prefix_flags_asm {} {
7042 set prefix [gdb_target_symbol_prefix]
7043 if {$prefix ne ""} {
7044 return "additional_flags=-DSYMBOL_PREFIX=$prefix"
7050 # gdb_target_symbol_prefix_flags returns the same string as
7051 # gdb_target_symbol_prefix_flags_asm, above, but with the prefix
7052 # enclosed in double quotes if there is a prefix.
7054 # See the comment for gdb_target_symbol_prefix_flags_asm for an
7055 # extended discussion.
7057 proc gdb_target_symbol_prefix_flags {} {
7058 set prefix [gdb_target_symbol_prefix]
7059 if {$prefix ne ""} {
7060 return "additional_flags=-DSYMBOL_PREFIX=\"$prefix\""
7066 # A wrapper for 'remote_exec host' that passes or fails a test.
7067 # Returns 0 if all went well, nonzero on failure.
7068 # TEST is the name of the test, other arguments are as for remote_exec.
7070 proc run_on_host { test program args } {
7071 verbose -log "run_on_host: $program $args"
7072 # remote_exec doesn't work properly if the output is set but the
7073 # input is the empty string -- so replace an empty input with
7075 if {[llength $args] > 1 && [lindex $args 1] == ""} {
7076 set args [lreplace $args 1 1 "/dev/null"]
7078 set result [eval remote_exec host [list $program] $args]
7079 verbose "result is $result"
7080 set status [lindex $result 0]
7081 set output [lindex $result 1]
7086 verbose -log "run_on_host failed: $output"
7087 if { $output == "spawn failed" } {
7096 # Return non-zero if "board_info debug_flags" mentions Fission.
7097 # http://gcc.gnu.org/wiki/DebugFission
7098 # Fission doesn't support everything yet.
7099 # This supports working around bug 15954.
7101 proc using_fission { } {
7102 set debug_flags [board_info [target_info name] debug_flags]
7103 return [regexp -- "-gsplit-dwarf" $debug_flags]
7106 # Search the caller's ARGS list and set variables according to the list of
7107 # valid options described by ARGSET.
7109 # The first member of each one- or two-element list in ARGSET defines the
7110 # name of a variable that will be added to the caller's scope.
7112 # If only one element is given to describe an option, it the value is
7113 # 0 if the option is not present in (the caller's) ARGS or 1 if
7116 # If two elements are given, the second element is the default value of
7117 # the variable. This is then overwritten if the option exists in ARGS.
7119 # Any parse_args elements in (the caller's) ARGS will be removed, leaving
7120 # any optional components.
7123 # proc myproc {foo args} {
7124 # parse_args {{bar} {baz "abc"} {qux}}
7127 # myproc ABC -bar -baz DEF peanut butter
7128 # will define the following variables in myproc:
7129 # foo (=ABC), bar (=1), baz (=DEF), and qux (=0)
7130 # args will be the list {peanut butter}
7132 proc parse_args { argset } {
7135 foreach argument $argset {
7136 if {[llength $argument] == 1} {
7137 # No default specified, so we assume that we should set
7138 # the value to 1 if the arg is present and 0 if it's not.
7139 # It is assumed that no value is given with the argument.
7140 set result [lsearch -exact $args "-$argument"]
7141 if {$result != -1} then {
7142 uplevel 1 [list set $argument 1]
7143 set args [lreplace $args $result $result]
7145 uplevel 1 [list set $argument 0]
7147 } elseif {[llength $argument] == 2} {
7148 # There are two items in the argument. The second is a
7149 # default value to use if the item is not present.
7150 # Otherwise, the variable is set to whatever is provided
7151 # after the item in the args.
7152 set arg [lindex $argument 0]
7153 set result [lsearch -exact $args "-[lindex $arg 0]"]
7154 if {$result != -1} then {
7155 uplevel 1 [list set $arg [lindex $args [expr $result+1]]]
7156 set args [lreplace $args $result [expr $result+1]]
7158 uplevel 1 [list set $arg [lindex $argument 1]]
7161 error "Badly formatted argument \"$argument\" in argument set"
7165 # The remaining args should be checked to see that they match the
7166 # number of items expected to be passed into the procedure...
7169 # Capture the output of COMMAND in a string ignoring PREFIX (a regexp);
7170 # return that string.
7172 proc capture_command_output { command prefix } {
7176 set output_string ""
7177 gdb_test_multiple "$command" "capture_command_output for $command" {
7178 -re "[string_to_regexp ${command}]\[\r\n\]+${prefix}(.*)\[\r\n\]+$gdb_prompt $" {
7179 set output_string $expect_out(1,string)
7182 return $output_string
7185 # A convenience function that joins all the arguments together, with a
7186 # regexp that matches exactly one end of line in between each argument.
7187 # This function is ideal to write the expected output of a GDB command
7188 # that generates more than a couple of lines, as this allows us to write
7189 # each line as a separate string, which is easier to read by a human
7192 proc multi_line { args } {
7193 return [join $args "\r\n"]
7196 # Similar to the above, but while multi_line is meant to be used to
7197 # match GDB output, this one is meant to be used to build strings to
7198 # send as GDB input.
7200 proc multi_line_input { args } {
7201 return [join $args "\n"]
7204 # Return the version of the DejaGnu framework.
7206 # The return value is a list containing the major, minor and patch version
7207 # numbers. If the version does not contain a minor or patch number, they will
7208 # be set to 0. For example:
7214 proc dejagnu_version { } {
7215 # The frame_version variable is defined by DejaGnu, in runtest.exp.
7216 global frame_version
7218 verbose -log "DejaGnu version: $frame_version"
7219 verbose -log "Expect version: [exp_version]"
7220 verbose -log "Tcl version: [info tclversion]"
7222 set dg_ver [split $frame_version .]
7224 while { [llength $dg_ver] < 3 } {
7231 # Define user-defined command COMMAND using the COMMAND_LIST as the
7232 # command's definition. The terminating "end" is added automatically.
7234 proc gdb_define_cmd {command command_list} {
7237 set input [multi_line_input {*}$command_list "end"]
7238 set test "define $command"
7240 gdb_test_multiple "define $command" $test {
7242 gdb_test_multiple $input $test {
7243 -re "\r\n$gdb_prompt " {
7250 # Override the 'cd' builtin with a version that ensures that the
7251 # log file keeps pointing at the same file. We need this because
7252 # unfortunately the path to the log file is recorded using an
7253 # relative path name, and, we sometimes need to close/reopen the log
7254 # after changing the current directory. See get_compiler_info.
7256 rename cd builtin_cd
7260 # Get the existing log file flags.
7261 set log_file_info [log_file -info]
7263 # Split the flags into args and file name.
7264 set log_file_flags ""
7265 set log_file_file ""
7266 foreach arg [ split "$log_file_info" " "] {
7267 if [string match "-*" $arg] {
7268 lappend log_file_flags $arg
7270 lappend log_file_file $arg
7274 # If there was an existing file, ensure it is an absolute path, and then
7276 if { $log_file_file != "" } {
7277 set log_file_file [file normalize $log_file_file]
7279 log_file $log_file_flags "$log_file_file"
7282 # Call the builtin version of cd.
7286 # Return a list of all languages supported by GDB, suitable for use in
7287 # 'set language NAME'. This doesn't include either the 'local' or
7289 proc gdb_supported_languages {} {
7290 return [list c objective-c c++ d go fortran modula-2 asm pascal \
7291 opencl rust minimal ada]
7294 # Check if debugging is enabled for gdb.
7296 proc gdb_debug_enabled { } {
7299 # If not already read, get the debug setting from environment or board setting.
7300 if {![info exists gdbdebug]} {
7302 if [info exists env(GDB_DEBUG)] {
7303 set gdbdebug $env(GDB_DEBUG)
7304 } elseif [target_info exists gdb,debug] {
7305 set gdbdebug [target_info gdb,debug]
7311 # Ensure it not empty.
7312 return [expr { $gdbdebug != "" }]
7315 # Turn on debugging if enabled, or reset if already on.
7317 proc gdb_debug_init { } {
7321 if ![gdb_debug_enabled] {
7325 # First ensure logging is off.
7326 send_gdb "set logging off\n"
7328 set debugfile [standard_output_file gdb.debug]
7329 send_gdb "set logging file $debugfile\n"
7331 send_gdb "set logging debugredirect\n"
7334 foreach entry [split $gdbdebug ,] {
7335 send_gdb "set debug $entry 1\n"
7338 # Now that everything is set, enable logging.
7339 send_gdb "set logging on\n"
7341 -re "Copying output to $debugfile.*Redirecting debug output to $debugfile.*$gdb_prompt $" {}
7342 timeout { warning "Couldn't set logging file" }
7346 # Check if debugging is enabled for gdbserver.
7348 proc gdbserver_debug_enabled { } {
7349 # Always disabled for GDB only setups.
7353 # Open the file for logging gdb input
7355 proc gdb_stdin_log_init { } {
7356 gdb_persistent_global in_file
7358 if {[info exists in_file]} {
7359 # Close existing file.
7360 catch "close $in_file"
7363 set logfile [standard_output_file_with_gdb_instance gdb.in]
7364 set in_file [open $logfile w]
7367 # Write to the file for logging gdb input.
7368 # TYPE can be one of the following:
7369 # "standard" : Default. Standard message written to the log
7370 # "answer" : Answer to a question (eg "Y"). Not written the log.
7371 # "optional" : Optional message. Not written to the log.
7373 proc gdb_stdin_log_write { message {type standard} } {
7376 if {![info exists in_file]} {
7380 # Check message types.
7381 switch -regexp -- $type {
7390 # Write to the log and make sure the output is there, even in case
7392 puts -nonewline $in_file "$message"
7396 # Write the command line used to invocate gdb to the cmd file.
7398 proc gdb_write_cmd_file { cmdline } {
7399 set logfile [standard_output_file_with_gdb_instance gdb.cmd]
7400 set cmd_file [open $logfile w]
7401 puts $cmd_file $cmdline
7402 catch "close $cmd_file"
7405 # Compare contents of FILE to string STR. Pass with MSG if equal, otherwise
7408 proc cmp_file_string { file str msg } {
7409 if { ![file exists $file]} {
7414 set caught_error [catch {
7415 set fp [open "$file" r]
7416 set file_contents [read $fp]
7419 if { $caught_error } then {
7420 error "$error_message"
7425 if { $file_contents == $str } {
7432 # Does the compiler support CTF debug output using '-gt' compiler
7433 # flag? If not then we should skip these tests. We should also
7434 # skip them if libctf was explicitly disabled.
7436 gdb_caching_proc skip_ctf_tests {
7437 global enable_libctf
7439 if {$enable_libctf eq "no"} {
7443 set can_ctf [gdb_can_simple_compile ctfdebug {
7447 } executable "additional_flags=-gt"]
7449 return [expr {!$can_ctf}]
7452 # Return 1 if compiler supports -gstatement-frontiers. Otherwise,
7455 gdb_caching_proc supports_statement_frontiers {
7456 return [gdb_can_simple_compile supports_statement_frontiers {
7460 } executable "additional_flags=-gstatement-frontiers"]
7463 # Return 1 if compiler supports -mmpx -fcheck-pointer-bounds. Otherwise,
7466 gdb_caching_proc supports_mpx_check_pointer_bounds {
7467 set flags "additional_flags=-mmpx additional_flags=-fcheck-pointer-bounds"
7468 return [gdb_can_simple_compile supports_mpx_check_pointer_bounds {
7472 } executable $flags]
7475 # Return 1 if compiler supports -fcf-protection=. Otherwise,
7478 gdb_caching_proc supports_fcf_protection {
7479 return [gdb_can_simple_compile supports_fcf_protection {
7483 } executable "additional_flags=-fcf-protection=full"]
7486 # Return 1 if symbols were read in using -readnow. Otherwise, return 0.
7488 proc readnow { args } {
7489 if { [llength $args] == 1 } {
7490 set re [lindex $args 0]
7494 set cmd "maint print objfiles $re"
7495 gdb_test_multiple $cmd "" {
7496 -re -wrap "\r\n.gdb_index: faked for \"readnow\"\r\n.*" {
7507 # Return 1 if partial symbols are available. Otherwise, return 0.
7509 proc psymtabs_p { } {
7512 set cmd "maint info psymtab"
7513 gdb_test_multiple $cmd "" {
7514 -re "$cmd\r\n$gdb_prompt $" {
7525 # Verify that partial symtab expansion for $filename has state $readin.
7527 proc verify_psymtab_expanded { filename readin } {
7530 set cmd "maint info psymtab"
7531 set test "$cmd: $filename: $readin"
7532 set re [multi_line \
7533 " \{ psymtab \[^\r\n\]*$filename\[^\r\n\]*" \
7537 gdb_test_multiple $cmd $test {
7538 -re "$cmd\r\n$gdb_prompt $" {
7539 unsupported $gdb_test_name
7547 # Add a .gdb_index section to PROGRAM.
7548 # PROGRAM is assumed to be the output of standard_output_file.
7549 # Returns the 0 if there is a failure, otherwise 1.
7551 proc add_gdb_index { program } {
7552 global srcdir GDB env BUILD_DATA_DIRECTORY
7553 set contrib_dir "$srcdir/../contrib"
7554 set env(GDB) "$GDB --data-directory=$BUILD_DATA_DIRECTORY"
7555 set result [catch "exec $contrib_dir/gdb-add-index.sh $program" output]
7556 if { $result != 0 } {
7557 verbose -log "result is $result"
7558 verbose -log "output is $output"
7565 # Add a .gdb_index section to PROGRAM, unless it alread has an index
7566 # (.gdb_index/.debug_names). Gdb doesn't support building an index from a
7567 # program already using one. Return 1 if a .gdb_index was added, return 0
7568 # if it already contained an index, and -1 if an error occurred.
7570 proc ensure_gdb_index { binfile } {
7571 set testfile [file tail $binfile]
7572 set test "check if index present"
7573 gdb_test_multiple "mt print objfiles ${testfile}" $test {
7574 -re -wrap "gdb_index.*" {
7577 -re -wrap "debug_names.*" {
7580 -re -wrap "Psymtabs.*" {
7581 if { [add_gdb_index $binfile] != "1" } {
7590 # Return 1 if executable contains .debug_types section. Otherwise, return 0.
7592 proc debug_types { } {
7595 set cmd "maint info sections"
7596 gdb_test_multiple $cmd "" {
7597 -re -wrap "at $hex: .debug_types.*" {
7608 # Return the addresses in the line table for FILE for which is_stmt is true.
7610 proc is_stmt_addresses { file } {
7616 gdb_test_multiple "maint info line-table $file" "" {
7617 -re "\r\n$decimal\[ \t\]+$decimal\[ \t\]+($hex)\[ \t\]+Y\[^\r\n\]*" {
7618 lappend is_stmt $expect_out(1,string)
7628 # Return 1 if hex number VAL is an element of HEXLIST.
7630 proc hex_in_list { val hexlist } {
7631 # Normalize val by removing 0x prefix, and leading zeros.
7632 set val [regsub ^0x $val ""]
7633 set val [regsub ^0+ $val "0"]
7636 set index [lsearch -regexp $hexlist $re]
7637 return [expr $index != -1]
7640 # Override proc NAME to proc OVERRIDE for the duration of the execution of
7643 proc with_override { name override body } {
7644 # Implementation note: It's possible to implement the override using
7645 # rename, like this:
7646 # rename $name save_$name
7647 # rename $override $name
7648 # set code [catch {uplevel 1 $body} result]
7649 # rename $name $override
7650 # rename save_$name $name
7651 # but there are two issues here:
7652 # - the save_$name might clash with an existing proc
7653 # - the override is no longer available under its original name during
7655 # So, we use this more elaborate but cleaner mechanism.
7657 # Save the old proc.
7658 set old_args [info args $name]
7659 set old_body [info body $name]
7661 # Install the override.
7662 set new_args [info args $override]
7663 set new_body [info body $override]
7664 eval proc $name {$new_args} {$new_body}
7667 set code [catch {uplevel 1 $body} result]
7670 eval proc $name {$old_args} {$old_body}
7672 # Return as appropriate.
7674 global errorInfo errorCode
7675 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
7676 } elseif { $code > 1 } {
7677 return -code $code $result
7683 # Setup tuiterm.exp environment. To be used in test-cases instead of
7684 # "load_lib tuiterm.exp". Calls initialization function and schedules
7685 # finalization function.
7686 proc tuiterm_env { } {
7687 load_lib tuiterm.exp
7689 # Do initialization.
7692 # Schedule finalization.
7693 global gdb_finish_hooks
7694 lappend gdb_finish_hooks tuiterm_env_finish
7697 # Dejagnu has a version of note, but usage is not allowed outside of dejagnu.
7698 # Define a local version.
7699 proc gdb_note { message } {
7700 verbose -- "NOTE: $message" 0
7703 # Return 1 if compiler supports -fuse-ld=gold, otherwise return 0.
7704 gdb_caching_proc have_fuse_ld_gold {
7705 set me "have_fuse_ld_gold"
7706 set flags "additional_flags=-fuse-ld=gold"
7707 set src { int main() { return 0; } }
7708 return [gdb_simple_compile $me $src executable $flags]
7711 # Return 1 if compiler supports scalar_storage_order attribute, otherwise
7713 gdb_caching_proc supports_scalar_storage_order_attribute {
7714 set me "supports_scalar_storage_order_attribute"
7719 } __attribute__((scalar_storage_order("little-endian")));
7722 } __attribute__((scalar_storage_order("big-endian")));
7726 sle.v = sbe.v = 0x11223344;
7727 int same = memcmp (&sle, &sbe, sizeof (int)) == 0;
7732 if { ![gdb_simple_compile $me $src executable ""] } {
7736 set result [remote_exec target $obj]
7737 set status [lindex $result 0]
7738 set output [lindex $result 1]
7739 if { $output != "" } {
7746 # Return 1 if compiler supports __GNUC__, otherwise return 0.
7747 gdb_caching_proc supports_gnuc {
7748 set me "supports_gnuc"
7754 return [gdb_simple_compile $me $src object ""]
7757 # Return 1 if target supports mpx, otherwise return 0.
7758 gdb_caching_proc have_mpx {
7762 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
7763 verbose "$me: target does not support mpx, returning 0" 2
7767 # Compile a test program.
7769 #include "nat/x86-cpuid.h"
7772 unsigned int eax, ebx, ecx, edx;
7774 if (!__get_cpuid (1, &eax, &ebx, &ecx, &edx))
7777 if ((ecx & bit_OSXSAVE) == bit_OSXSAVE)
7779 if (__get_cpuid_max (0, (void *)0) < 7)
7782 __cpuid_count (7, 0, eax, ebx, ecx, edx);
7784 if ((ebx & bit_MPX) == bit_MPX)
7791 set compile_flags "incdir=${srcdir}/.."
7792 if {![gdb_simple_compile $me $src executable $compile_flags]} {
7796 set result [remote_exec target $obj]
7797 set status [lindex $result 0]
7798 set output [lindex $result 1]
7799 if { $output != "" } {
7803 remote_file build delete $obj
7805 verbose "$me: returning $status" 2
7809 # Always load compatibility stuff.