1 # Copyright 1992-2022 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 # Add VAR_ID=VAL to ENV_VAR, unless ENV_VAR already contains a VAR_ID setting.
 
  30 proc set_sanitizer_default { env_var var_id val } {
 
  33     if { ![info exists env($env_var) ]
 
  34          || $env($env_var) == "" } {
 
  35         # Set var_id (env_var non-existing / empty case).
 
  36         append env($env_var) $var_id=$val
 
  40     if { [regexp $var_id= $env($env_var)] } {
 
  41         # Don't set var_id.  It's already set by the user, leave as is.
 
  42         # Note that we could probably get the same result by unconditionally
 
  43         # prepending it, but this way is less likely to cause confusion.
 
  47     # Set var_id (env_var not empty case).
 
  48     append env($env_var) : $var_id=$val
 
  51 set_sanitizer_default TSAN_OPTIONS suppressions \
 
  52     $srcdir/../tsan-suppressions.txt
 
  54 # If GDB is built with ASAN (and because there are leaks), it will output a
 
  55 # leak report when exiting as well as exit with a non-zero (failure) status.
 
  56 # This can affect tests that are sensitive to what GDB prints on stderr or its
 
  57 # exit status.  Add `detect_leaks=0` to the ASAN_OPTIONS environment variable
 
  58 # (which will affect any spawned sub-process) to avoid this.
 
  59 set_sanitizer_default ASAN_OPTIONS detect_leaks 0
 
  61 # List of procs to run in gdb_finish.
 
  62 set gdb_finish_hooks [list]
 
  64 # Variable in which we keep track of globals that are allowed to be live
 
  66 array set gdb_persistent_globals {}
 
  68 # Mark variable names in ARG as a persistent global, and declare them as
 
  69 # global in the calling context.  Can be used to rewrite "global var_a var_b"
 
  70 # into "gdb_persistent_global var_a var_b".
 
  71 proc gdb_persistent_global { args } {
 
  72     global gdb_persistent_globals
 
  73     foreach varname $args {
 
  74         uplevel 1 global $varname
 
  75         set gdb_persistent_globals($varname) 1
 
  79 # Mark variable names in ARG as a persistent global.
 
  80 proc gdb_persistent_global_no_decl { args } {
 
  81     global gdb_persistent_globals
 
  82     foreach varname $args {
 
  83         set gdb_persistent_globals($varname) 1
 
  87 # Override proc load_lib.
 
  88 rename load_lib saved_load_lib
 
  89 # Run the runtest version of load_lib, and mark all variables that were
 
  90 # created by this call as persistent.
 
  91 proc load_lib { file } {
 
  92     array set known_global {}
 
  93     foreach varname [info globals] {
 
  94        set known_globals($varname) 1
 
  97     set code [catch "saved_load_lib $file" result]
 
  99     foreach varname [info globals] {
 
 100        if { ![info exists known_globals($varname)] } {
 
 101            gdb_persistent_global_no_decl $varname
 
 106         global errorInfo errorCode
 
 107         return -code error -errorinfo $errorInfo -errorcode $errorCode $result
 
 108     } elseif {$code > 1} {
 
 109         return -code $code $result
 
 115 load_lib libgloss.exp
 
 117 load_lib gdb-utils.exp
 
 119 load_lib check-test-names.exp
 
 121 # The path to the GDB binary to test.
 
 124 # The data directory to use for testing.  If this is the empty string,
 
 125 # then we let GDB use its own configured data directory.
 
 126 global GDB_DATA_DIRECTORY
 
 128 # The spawn ID used for I/O interaction with the inferior.  For native
 
 129 # targets, or remote targets that can do I/O through GDB
 
 130 # (semi-hosting) this will be the same as the host/GDB's spawn ID.
 
 131 # Otherwise, the board may set this to some other spawn ID.  E.g.,
 
 132 # when debugging with GDBserver, this is set to GDBserver's spawn ID,
 
 133 # so input/output is done on gdbserver's tty.
 
 134 global inferior_spawn_id
 
 136 if [info exists TOOL_EXECUTABLE] {
 
 137     set GDB $TOOL_EXECUTABLE
 
 139 if ![info exists GDB] {
 
 140     if ![is_remote host] {
 
 141         set GDB [findfile $base_dir/../../gdb/gdb "$base_dir/../../gdb/gdb" [transform gdb]]
 
 143         set GDB [transform gdb]
 
 146     # If the user specifies GDB on the command line, and doesn't
 
 147     # specify GDB_DATA_DIRECTORY, then assume we're testing an
 
 148     # installed GDB, and let it use its own configured data directory.
 
 149     if ![info exists GDB_DATA_DIRECTORY] {
 
 150         set GDB_DATA_DIRECTORY ""
 
 153 verbose "using GDB = $GDB" 2
 
 155 # The data directory the testing GDB will use.  By default, assume
 
 156 # we're testing a non-installed GDB in the build directory.  Users may
 
 157 # also explictly override the -data-directory from the command line.
 
 158 if ![info exists GDB_DATA_DIRECTORY] {
 
 159     set GDB_DATA_DIRECTORY "[pwd]/../data-directory"
 
 161 verbose "using GDB_DATA_DIRECTORY = $GDB_DATA_DIRECTORY" 2
 
 163 # GDBFLAGS is available for the user to set on the command line.
 
 164 # E.g. make check RUNTESTFLAGS=GDBFLAGS=mumble
 
 165 # Testcases may use it to add additional flags, but they must:
 
 166 # - append new flags, not overwrite
 
 167 # - restore the original value when done
 
 169 if ![info exists GDBFLAGS] {
 
 172 verbose "using GDBFLAGS = $GDBFLAGS" 2
 
 174 # Append the -data-directory option to pass to GDB to CMDLINE and
 
 175 # return the resulting string.  If GDB_DATA_DIRECTORY is empty,
 
 176 # nothing is appended.
 
 177 proc append_gdb_data_directory_option {cmdline} {
 
 178     global GDB_DATA_DIRECTORY
 
 180     if { $GDB_DATA_DIRECTORY != "" } {
 
 181         return "$cmdline -data-directory $GDB_DATA_DIRECTORY"
 
 187 # INTERNAL_GDBFLAGS contains flags that the testsuite requires.
 
 188 # `-nw' disables any of the windowed interfaces.
 
 189 # `-nx' disables ~/.gdbinit, so that it doesn't interfere with the tests.
 
 190 # `-iex "set {height,width} 0"' disables pagination.
 
 191 # `-data-directory' points to the data directory, usually in the build
 
 193 global INTERNAL_GDBFLAGS
 
 194 if ![info exists INTERNAL_GDBFLAGS] {
 
 195     set INTERNAL_GDBFLAGS \
 
 199                    {-iex "set height 0"} \
 
 200                    {-iex "set width 0"}]]
 
 202     set INTERNAL_GDBFLAGS [append_gdb_data_directory_option $INTERNAL_GDBFLAGS]
 
 205 # The variable gdb_prompt is a regexp which matches the gdb prompt.
 
 206 # Set it if it is not already set.  This is also set by default_gdb_init
 
 207 # but it's not clear what removing one of them will break.
 
 208 # See with_gdb_prompt for more details on prompt handling.
 
 210 if ![info exists gdb_prompt] then {
 
 211     set gdb_prompt "\\(gdb\\)"
 
 214 # A regexp that matches the pagination prompt.
 
 215 set pagination_prompt \
 
 216     "--Type <RET> for more, q to quit, c to continue without paging--"
 
 218 # The variable fullname_syntax_POSIX is a regexp which matches a POSIX 
 
 219 # absolute path ie. /foo/ 
 
 220 set fullname_syntax_POSIX {/[^\n]*/}
 
 221 # The variable fullname_syntax_UNC is a regexp which matches a Windows 
 
 222 # UNC path ie. \\D\foo\ 
 
 223 set fullname_syntax_UNC {\\\\[^\\]+\\[^\n]+\\}
 
 224 # The variable fullname_syntax_DOS_CASE is a regexp which matches a 
 
 225 # particular DOS case that GDB most likely will output
 
 226 # ie. \foo\, but don't match \\.*\ 
 
 227 set fullname_syntax_DOS_CASE {\\[^\\][^\n]*\\}
 
 228 # The variable fullname_syntax_DOS is a regexp which matches a DOS path
 
 229 # ie. a:\foo\ && a:foo\ 
 
 230 set fullname_syntax_DOS {[a-zA-Z]:[^\n]*\\}
 
 231 # The variable fullname_syntax is a regexp which matches what GDB considers
 
 232 # an absolute path. It is currently debatable if the Windows style paths 
 
 233 # d:foo and \abc should be considered valid as an absolute path.
 
 234 # Also, the purpse of this regexp is not to recognize a well formed 
 
 235 # absolute path, but to say with certainty that a path is absolute.
 
 236 set fullname_syntax "($fullname_syntax_POSIX|$fullname_syntax_UNC|$fullname_syntax_DOS_CASE|$fullname_syntax_DOS)"
 
 238 # Needed for some tests under Cygwin.
 
 242 if ![info exists env(EXEEXT)] {
 
 245     set EXEEXT $env(EXEEXT)
 
 250 set inferior_exited_re "(?:\\\[Inferior \[0-9\]+ \\(\[^\n\r\]*\\) exited)"
 
 252 # A regular expression that matches a value history number.
 
 254 set valnum_re "\\\$$decimal"
 
 256 ### Only procedures should come after this point.
 
 259 # gdb_version -- extract and print the version number of GDB
 
 261 proc default_gdb_version {} {
 
 263     global INTERNAL_GDBFLAGS GDBFLAGS
 
 267     if {[info exists inotify_pid]} {
 
 268         eval exec kill $inotify_pid
 
 271     set output [remote_exec host "$GDB $INTERNAL_GDBFLAGS --version"]
 
 272     set tmp [lindex $output 1]
 
 274     regexp " \[0-9\]\[^ \t\n\r\]+" "$tmp" version
 
 275     if ![is_remote host] {
 
 276         clone_output "[which $GDB] version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
 
 278         clone_output "$GDB on remote host version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
 
 282 proc gdb_version { } {
 
 283     return [default_gdb_version]
 
 287 # gdb_unload -- unload a file if one is loaded
 
 288 # Return 0 on success, -1 on error.
 
 296         -re "No executable file now\[^\r\n\]*\[\r\n\]" { exp_continue }
 
 297         -re "No symbol file now\[^\r\n\]*\[\r\n\]" { exp_continue }
 
 298         -re "A program is being debugged already.*Are you sure you want to change the file.*y or n. $" {
 
 299             send_gdb "y\n" answer
 
 302         -re "Discard symbol table from .*y or n.*$" {
 
 303             send_gdb "y\n" answer
 
 306         -re "$gdb_prompt $" {}
 
 307         -re "A problem internal to GDB has been detected" {
 
 308             perror "Couldn't unload file in $GDB (GDB internal error)."
 
 309             gdb_internal_error_resync
 
 313             perror "couldn't unload file in $GDB (timeout)."
 
 320 # Many of the tests depend on setting breakpoints at various places and
 
 321 # running until that breakpoint is reached.  At times, we want to start
 
 322 # with a clean-slate with respect to breakpoints, so this utility proc 
 
 323 # lets us do this without duplicating this code everywhere.
 
 326 proc delete_breakpoints {} {
 
 329     # we need a larger timeout value here or this thing just confuses
 
 330     # itself.  May need a better implementation if possible. - guo
 
 334     set msg "delete all breakpoints in delete_breakpoints"
 
 336     gdb_test_multiple "delete breakpoints" "$msg" {
 
 337         -re "Delete all breakpoints.*y or n.*$" {
 
 338             send_gdb "y\n" answer
 
 341         -re "$gdb_prompt $" {
 
 347         # Confirm with "info breakpoints".
 
 349         set msg "info breakpoints"
 
 350         gdb_test_multiple $msg $msg {
 
 351             -re "No breakpoints or watchpoints..*$gdb_prompt $" {
 
 354             -re "$gdb_prompt $" {
 
 360         perror "breakpoints not deleted"
 
 364 # Returns true iff the target supports using the "run" command.
 
 366 proc target_can_use_run_cmd {} {
 
 367     if [target_info exists use_gdb_stub] {
 
 368         # In this case, when we connect, the inferior is already
 
 377 # Generic run command.
 
 379 # Return 0 if we could start the program, -1 if we could not.
 
 381 # The second pattern below matches up to the first newline *only*.
 
 382 # Using ``.*$'' could swallow up output that we attempt to match
 
 385 # INFERIOR_ARGS is passed as arguments to the start command, so may contain
 
 386 # inferior arguments.
 
 388 # N.B. This function does not wait for gdb to return to the prompt,
 
 389 # that is the caller's responsibility.
 
 391 proc gdb_run_cmd { {inferior_args {}} } {
 
 392     global gdb_prompt use_gdb_stub
 
 394     foreach command [gdb_init_commands] {
 
 395         send_gdb "$command\n"
 
 397             -re "$gdb_prompt $" { }
 
 399                 perror "gdb_init_command for target failed"
 
 406         if [target_info exists gdb,do_reload_on_run] {
 
 407             if { [gdb_reload $inferior_args] != 0 } {
 
 410             send_gdb "continue\n"
 
 412                 -re "Continu\[^\r\n\]*\[\r\n\]" {}
 
 418         if [target_info exists gdb,start_symbol] {
 
 419             set start [target_info gdb,start_symbol]
 
 423         send_gdb  "jump *$start\n"
 
 425         while { $start_attempt } {
 
 426             # Cap (re)start attempts at three to ensure that this loop
 
 427             # always eventually fails.  Don't worry about trying to be
 
 428             # clever and not send a command when it has failed.
 
 429             if [expr $start_attempt > 3] {
 
 430                 perror "Jump to start() failed (retry count exceeded)"
 
 433             set start_attempt [expr $start_attempt + 1]
 
 435                 -re "Continuing at \[^\r\n\]*\[\r\n\]" {
 
 438                 -re "No symbol \"_start\" in current.*$gdb_prompt $" {
 
 439                     perror "Can't find start symbol to run in gdb_run"
 
 442                 -re "No symbol \"start\" in current.*$gdb_prompt $" {
 
 443                     send_gdb "jump *_start\n"
 
 445                 -re "No symbol.*context.*$gdb_prompt $" {
 
 448                 -re "Line.* Jump anyway.*y or n. $" {
 
 449                     send_gdb "y\n" answer
 
 451                 -re "The program is not being run.*$gdb_prompt $" {
 
 452                     if { [gdb_reload $inferior_args] != 0 } {
 
 455                     send_gdb "jump *$start\n"
 
 458                     perror "Jump to start() failed (timeout)"
 
 467     if [target_info exists gdb,do_reload_on_run] {
 
 468         if { [gdb_reload $inferior_args] != 0 } {
 
 472     send_gdb "run $inferior_args\n"
 
 473 # This doesn't work quite right yet.
 
 474 # Use -notransfer here so that test cases (like chng-sym.exp)
 
 475 # may test for additional start-up messages.
 
 477         -re "The program .* has been started already.*y or n. $" {
 
 478             send_gdb "y\n" answer
 
 481         -notransfer -re "Starting program: \[^\r\n\]*" {}
 
 482         -notransfer -re "$gdb_prompt $" {
 
 483             # There is no more input expected.
 
 485         -notransfer -re "A problem internal to GDB has been detected" {
 
 486             # Let caller handle this.
 
 493 # Generic start command.  Return 0 if we could start the program, -1
 
 496 # INFERIOR_ARGS is passed as arguments to the start command, so may contain
 
 497 # inferior arguments.
 
 499 # N.B. This function does not wait for gdb to return to the prompt,
 
 500 # that is the caller's responsibility.
 
 502 proc gdb_start_cmd { {inferior_args {}} } {
 
 503     global gdb_prompt use_gdb_stub
 
 505     foreach command [gdb_init_commands] {
 
 506         send_gdb "$command\n"
 
 508             -re "$gdb_prompt $" { }
 
 510                 perror "gdb_init_command for target failed"
 
 520     send_gdb "start $inferior_args\n"
 
 521     # Use -notransfer here so that test cases (like chng-sym.exp)
 
 522     # may test for additional start-up messages.
 
 524         -re "The program .* has been started already.*y or n. $" {
 
 525             send_gdb "y\n" answer
 
 528         -notransfer -re "Starting program: \[^\r\n\]*" {
 
 535 # Generic starti command.  Return 0 if we could start the program, -1
 
 538 # INFERIOR_ARGS is passed as arguments to the starti command, so may contain
 
 539 # inferior arguments.
 
 541 # N.B. This function does not wait for gdb to return to the prompt,
 
 542 # that is the caller's responsibility.
 
 544 proc gdb_starti_cmd { {inferior_args {}} } {
 
 545     global gdb_prompt use_gdb_stub
 
 547     foreach command [gdb_init_commands] {
 
 548         send_gdb "$command\n"
 
 550             -re "$gdb_prompt $" { }
 
 552                 perror "gdb_init_command for target failed"
 
 562     send_gdb "starti $inferior_args\n"
 
 564         -re "The program .* has been started already.*y or n. $" {
 
 565             send_gdb "y\n" answer
 
 568         -re "Starting program: \[^\r\n\]*" {
 
 575 # Set a breakpoint using LINESPEC.
 
 577 # If there is an additional argument it is a list of options; the supported
 
 578 # options are allow-pending, temporary, message, no-message and qualified.
 
 580 # The result is 1 for success, 0 for failure.
 
 582 # Note: The handling of message vs no-message is messed up, but it's based
 
 583 # on historical usage.  By default this function does not print passes,
 
 585 # no-message: turns off printing of fails (and passes, but they're already off)
 
 586 # message: turns on printing of passes (and fails, but they're already on)
 
 588 proc gdb_breakpoint { linespec args } {
 
 592     set pending_response n
 
 593     if {[lsearch -exact $args allow-pending] != -1} {
 
 594         set pending_response y
 
 597     set break_command "break"
 
 598     set break_message "Breakpoint"
 
 599     if {[lsearch -exact $args temporary] != -1} {
 
 600         set break_command "tbreak"
 
 601         set break_message "Temporary breakpoint"
 
 604     if {[lsearch -exact $args qualified] != -1} {
 
 605         append break_command " -qualified"
 
 610     set no_message_loc [lsearch -exact $args no-message]
 
 611     set message_loc [lsearch -exact $args message]
 
 612     # The last one to appear in args wins.
 
 613     if { $no_message_loc > $message_loc } {
 
 615     } elseif { $message_loc > $no_message_loc } {
 
 619     set test_name "gdb_breakpoint: set breakpoint at $linespec"
 
 621     send_gdb "$break_command $linespec\n"
 
 622     # The first two regexps are what we get with -g, the third is without -g.
 
 624         -re "$break_message \[0-9\]* at .*: file .*, line $decimal.\r\n$gdb_prompt $" {}
 
 625         -re "$break_message \[0-9\]*: file .*, line $decimal.\r\n$gdb_prompt $" {}
 
 626         -re "$break_message \[0-9\]* at .*$gdb_prompt $" {}
 
 627         -re "$break_message \[0-9\]* \\(.*\\) pending.*$gdb_prompt $" {
 
 628                 if {$pending_response == "n"} {
 
 635         -re "Make breakpoint pending.*y or \\\[n\\\]. $" { 
 
 636                 send_gdb "$pending_response\n"
 
 639         -re "A problem internal to GDB has been detected" {
 
 641                     fail "$test_name (GDB internal error)"
 
 643                 gdb_internal_error_resync
 
 646         -re "$gdb_prompt $" {
 
 653                 perror "GDB process no longer exists"
 
 655                 set wait_status [wait -i $gdb_spawn_id]
 
 656                 verbose -log "GDB process exited with wait status $wait_status"
 
 658                         fail "$test_name (eof)"
 
 664                         fail "$test_name (timeout)"
 
 675 # Set breakpoint at function and run gdb until it breaks there.
 
 676 # Since this is the only breakpoint that will be set, if it stops
 
 677 # at a breakpoint, we will assume it is the one we want.  We can't
 
 678 # just compare to "function" because it might be a fully qualified,
 
 679 # single quoted C++ function specifier.
 
 681 # If there are additional arguments, pass them to gdb_breakpoint.
 
 682 # We recognize no-message/message ourselves.
 
 684 # no-message is messed up here, like gdb_breakpoint: to preserve
 
 685 # historical usage fails are always printed by default.
 
 686 # no-message: turns off printing of fails (and passes, but they're already off)
 
 687 # message: turns on printing of passes (and fails, but they're already on)
 
 689 proc runto { linespec args } {
 
 697     set no_message_loc [lsearch -exact $args no-message]
 
 698     set message_loc [lsearch -exact $args message]
 
 699     # The last one to appear in args wins.
 
 700     if { $no_message_loc > $message_loc } {
 
 702     } elseif { $message_loc > $no_message_loc } {
 
 706     set test_name "runto: run to $linespec"
 
 708     # We need to use eval here to pass our varargs args to gdb_breakpoint
 
 709     # which is also a varargs function.
 
 710     # But we also have to be careful because $linespec may have multiple
 
 711     # elements, and we don't want Tcl to move the remaining elements after
 
 712     # the first to $args.  That is why $linespec is wrapped in {}.
 
 713     if ![eval gdb_breakpoint {$linespec} $args] {
 
 719     # the "at foo.c:36" output we get with -g.
 
 720     # the "in func" output we get without -g.
 
 722         -re "Break.* at .*:$decimal.*$gdb_prompt $" {
 
 728         -re "Breakpoint \[0-9\]*, \[0-9xa-f\]* in .*$gdb_prompt $" { 
 
 734         -re "The target does not support running in non-stop mode.\r\n$gdb_prompt $" {
 
 736                 unsupported "non-stop mode not supported"
 
 740         -re ".*A problem internal to GDB has been detected" {
 
 741             # Always emit a FAIL if we encounter an internal error: internal
 
 742             # errors are never expected.
 
 743             fail "$test_name (GDB internal error)"
 
 744             gdb_internal_error_resync
 
 747         -re "$gdb_prompt $" { 
 
 755                 fail "$test_name (eof)"
 
 761                 fail "$test_name (timeout)"
 
 772 # Ask gdb to run until we hit a breakpoint at main.
 
 774 # N.B. This function deletes all existing breakpoints.
 
 775 # If you don't want that, use gdb_start_cmd.
 
 777 proc runto_main { } {
 
 778     return [runto main qualified]
 
 781 ### Continue, and expect to hit a breakpoint.
 
 782 ### Report a pass or fail, depending on whether it seems to have
 
 783 ### worked.  Use NAME as part of the test name; each call to
 
 784 ### continue_to_breakpoint should use a NAME which is unique within
 
 786 proc gdb_continue_to_breakpoint {name {location_pattern .*}} {
 
 788     set full_name "continue to breakpoint: $name"
 
 790     set kfail_pattern "Process record does not support instruction 0xfae64 at.*"
 
 791     gdb_test_multiple "continue" $full_name {
 
 792         -re "(?:Breakpoint|Temporary breakpoint) .* (at|in) $location_pattern\r\n$gdb_prompt $" {
 
 795         -re "\[\r\n\]*(?:$kfail_pattern)\[\r\n\]+$gdb_prompt $" {
 
 796             kfail "gdb/25038" $full_name
 
 802 # gdb_internal_error_resync:
 
 804 # Answer the questions GDB asks after it reports an internal error
 
 805 # until we get back to a GDB prompt.  Decline to quit the debugging
 
 806 # session, and decline to create a core file.  Return non-zero if the
 
 809 # This procedure just answers whatever questions come up until it sees
 
 810 # a GDB prompt; it doesn't require you to have matched the input up to
 
 811 # any specific point.  However, it only answers questions it sees in
 
 812 # the output itself, so if you've matched a question, you had better
 
 813 # answer it yourself before calling this.
 
 815 # You can use this function thus:
 
 819 #     -re ".*A problem internal to GDB has been detected" {
 
 820 #         gdb_internal_error_resync
 
 825 proc gdb_internal_error_resync {} {
 
 828     verbose -log "Resyncing due to internal error."
 
 831     while {$count < 10} {
 
 833             -re "Recursive internal problem\\." {
 
 834                 perror "Could not resync from internal error (recursive internal problem)"
 
 837             -re "Quit this debugging session\\? \\(y or n\\) $" {
 
 838                 send_gdb "n\n" answer
 
 841             -re "Create a core file of GDB\\? \\(y or n\\) $" {
 
 842                 send_gdb "n\n" answer
 
 845             -re "$gdb_prompt $" {
 
 846                 # We're resynchronized.
 
 850                 perror "Could not resync from internal error (timeout)"
 
 854                 perror "Could not resync from internal error (eof)"
 
 859     perror "Could not resync from internal error (resync count exceeded)"
 
 863 # Fill in the default prompt if PROMPT_REGEXP is empty.
 
 864 proc fill_in_default_prompt {prompt_regexp} {
 
 865     if { "$prompt_regexp" == "" } {
 
 866         return "$::gdb_prompt $"
 
 868     return $prompt_regexp
 
 871 # gdb_test_multiple COMMAND MESSAGE [ -prompt PROMPT_REGEXP] [ -lbl ]
 
 873 # Send a command to gdb; test the result.
 
 875 # COMMAND is the command to execute, send to GDB with send_gdb.  If
 
 876 #   this is the null string no command is sent.
 
 877 # MESSAGE is a message to be printed with the built-in failure patterns
 
 878 #   if one of them matches.  If MESSAGE is empty COMMAND will be used.
 
 879 # -prompt PROMPT_REGEXP specifies a regexp matching the expected prompt
 
 880 #   after the command output.  If empty, defaults to "$gdb_prompt $".
 
 881 # -lbl specifies that line-by-line matching will be used.
 
 882 # EXPECT_ARGUMENTS will be fed to expect in addition to the standard
 
 883 #   patterns.  Pattern elements will be evaluated in the caller's
 
 884 #   context; action elements will be executed in the caller's context.
 
 885 #   Unlike patterns for gdb_test, these patterns should generally include
 
 886 #   the final newline and prompt.
 
 889 #    1 if the test failed, according to a built-in failure pattern
 
 890 #    0 if only user-supplied patterns matched
 
 891 #   -1 if there was an internal error.
 
 893 # You can use this function thus:
 
 895 # gdb_test_multiple "print foo" "test foo" {
 
 896 #    -re "expected output 1" {
 
 899 #    -re "expected output 2" {
 
 904 # Within action elements you can also make use of the variable
 
 905 # gdb_test_name.  This variable is setup automatically by
 
 906 # gdb_test_multiple, and contains the value of MESSAGE.  You can then
 
 907 # write this, which is equivalent to the above:
 
 909 # gdb_test_multiple "print foo" "test foo" {
 
 910 #    -re "expected output 1" {
 
 911 #        pass $gdb_test_name
 
 913 #    -re "expected output 2" {
 
 914 #        fail $gdb_test_name
 
 918 # Like with "expect", you can also specify the spawn id to match with
 
 919 # -i "$id".  Interesting spawn ids are $inferior_spawn_id and
 
 920 # $gdb_spawn_id.  The former matches inferior I/O, while the latter
 
 921 # matches GDB I/O.  E.g.:
 
 923 # send_inferior "hello\n"
 
 924 # gdb_test_multiple "continue" "test echo" {
 
 925 #    -i "$inferior_spawn_id" -re "^hello\r\nhello\r\n$" {
 
 928 #    -i "$gdb_spawn_id" -re "Breakpoint.*$gdb_prompt $" {
 
 929 #        fail "hit breakpoint"
 
 933 # The standard patterns, such as "Inferior exited..." and "A problem
 
 934 # ...", all being implicitly appended to that list.  These are always
 
 935 # expected from $gdb_spawn_id.  IOW, callers do not need to worry
 
 936 # about resetting "-i" back to $gdb_spawn_id explicitly.
 
 938 # In EXPECT_ARGUMENTS we can use a -wrap pattern flag, that wraps the regexp
 
 939 # pattern as gdb_test wraps its message argument.
 
 940 # This allows us to rewrite:
 
 941 #   gdb_test <command> <pattern> <message>
 
 943 #   gdb_test_multiple <command> <message> {
 
 944 #       -re -wrap <pattern> {
 
 945 #           pass $gdb_test_name
 
 949 # In EXPECT_ARGUMENTS, a pattern flag -early can be used.  It makes sure the
 
 950 # pattern is inserted before any implicit pattern added by gdb_test_multiple.
 
 951 # Using this pattern flag, we can f.i. setup a kfail for an assertion failure
 
 952 # <assert> during gdb_continue_to_breakpoint by the rewrite:
 
 953 #   gdb_continue_to_breakpoint <msg> <pattern>
 
 955 #   set breakpoint_pattern "(?:Breakpoint|Temporary breakpoint) .* (at|in)"
 
 956 #   gdb_test_multiple "continue" "continue to breakpoint: <msg>"  {
 
 957 #       -early -re "internal-error: <assert>" {
 
 958 #           setup_kfail gdb/nnnnn "*-*-*"
 
 961 #       -re "$breakpoint_pattern <pattern>\r\n$gdb_prompt $" {
 
 962 #           pass $gdb_test_name
 
 966 proc gdb_test_multiple { command message args } {
 
 967     global verbose use_gdb_stub
 
 968     global gdb_prompt pagination_prompt
 
 971     global inferior_exited_re
 
 972     upvar timeout timeout
 
 973     upvar expect_out expect_out
 
 978     for {set i 0} {$i < [llength $args]} {incr i} {
 
 979         set arg [lindex $args $i]
 
 980         if { $arg  == "-prompt" } {
 
 982             set prompt_regexp [lindex $args $i]
 
 983         } elseif { $arg == "-lbl" } {
 
 990     if { [expr $i + 1] < [llength $args] } {
 
 991         error "Too many arguments to gdb_test_multiple"
 
 992     } elseif { ![info exists user_code] } {
 
 993         error "Too few arguments to gdb_test_multiple"
 
 996     set prompt_regexp [fill_in_default_prompt $prompt_regexp]
 
 998     if { $message == "" } {
 
1002     if [string match "*\[\r\n\]" $command] {
 
1003         error "Invalid trailing newline in \"$message\" test"
 
1006     if [string match "*\[\r\n\]*" $message] {
 
1007         error "Invalid newline in \"$message\" test"
 
1011         && [regexp -nocase {^\s*(r|run|star|start|at|att|atta|attac|attach)\M} \
 
1013         error "gdbserver does not support $command without extended-remote"
 
1016     # TCL/EXPECT WART ALERT
 
1017     # Expect does something very strange when it receives a single braced
 
1018     # argument.  It splits it along word separators and performs substitutions.
 
1019     # This means that { "[ab]" } is evaluated as "[ab]", but { "\[ab\]" } is
 
1020     # evaluated as "\[ab\]".  But that's not how TCL normally works; inside a
 
1021     # double-quoted list item, "\[ab\]" is just a long way of representing
 
1022     # "[ab]", because the backslashes will be removed by lindex.
 
1024     # Unfortunately, there appears to be no easy way to duplicate the splitting
 
1025     # that expect will do from within TCL.  And many places make use of the
 
1026     # "\[0-9\]" construct, so we need to support that; and some places make use
 
1027     # of the "[func]" construct, so we need to support that too.  In order to
 
1028     # get this right we have to substitute quoted list elements differently
 
1029     # from braced list elements.
 
1031     # We do this roughly the same way that Expect does it.  We have to use two
 
1032     # lists, because if we leave unquoted newlines in the argument to uplevel
 
1033     # they'll be treated as command separators, and if we escape newlines
 
1034     # we mangle newlines inside of command blocks.  This assumes that the
 
1035     # input doesn't contain a pattern which contains actual embedded newlines
 
1038     regsub -all {\n} ${user_code} { } subst_code
 
1039     set subst_code [uplevel list $subst_code]
 
1041     set processed_code ""
 
1042     set early_processed_code ""
 
1043     # The variable current_list holds the name of the currently processed
 
1044     # list, either processed_code or early_processed_code.
 
1045     set current_list "processed_code"
 
1047     set expecting_action 0
 
1050     foreach item $user_code subst_item $subst_code {
 
1051         if { $item == "-n" || $item == "-notransfer" || $item == "-nocase" } {
 
1052             lappend $current_list $item
 
1055         if { $item == "-indices" || $item == "-re" || $item == "-ex" } {
 
1056             lappend $current_list $item
 
1059         if { $item == "-early" } {
 
1060             set current_list "early_processed_code"
 
1063         if { $item == "-timeout" || $item == "-i" } {
 
1065             lappend $current_list $item
 
1068         if { $item == "-wrap" } {
 
1072         if { $expecting_arg } {
 
1074             lappend $current_list $subst_item
 
1077         if { $expecting_action } {
 
1078             lappend $current_list "uplevel [list $item]"
 
1079             set expecting_action 0
 
1080             # Cosmetic, no effect on the list.
 
1081             append $current_list "\n"
 
1082             # End the effect of -early, it only applies to one action.
 
1083             set current_list "processed_code"
 
1086         set expecting_action 1
 
1087         if { $wrap_pattern } {
 
1088             # Wrap subst_item as is done for the gdb_test PATTERN argument.
 
1089             lappend $current_list \
 
1090                 "\[\r\n\]*(?:$subst_item)\[\r\n\]+$gdb_prompt $"
 
1093             lappend $current_list $subst_item
 
1095         if {$patterns != ""} {
 
1096             append patterns "; "
 
1098         append patterns "\"$subst_item\""
 
1101     # Also purely cosmetic.
 
1102     regsub -all {\r} $patterns {\\r} patterns
 
1103     regsub -all {\n} $patterns {\\n} patterns
 
1105     if $verbose>2 then {
 
1106         send_user "Sending \"$command\" to gdb\n"
 
1107         send_user "Looking to match \"$patterns\"\n"
 
1108         send_user "Message is \"$message\"\n"
 
1112     set string "${command}\n"
 
1113     if { $command != "" } {
 
1114         set multi_line_re "\[\r\n\] *>"
 
1115         while { "$string" != "" } {
 
1116             set foo [string first "\n" "$string"]
 
1117             set len [string length "$string"]
 
1118             if { $foo < [expr $len - 1] } {
 
1119                 set str [string range "$string" 0 $foo]
 
1120                 if { [send_gdb "$str"] != "" } {
 
1121                     perror "Couldn't send $command to GDB."
 
1123                 # since we're checking if each line of the multi-line
 
1124                 # command are 'accepted' by GDB here,
 
1125                 # we need to set -notransfer expect option so that
 
1126                 # command output is not lost for pattern matching
 
1129                     -notransfer -re "$multi_line_re$" { verbose "partial: match" 3 }
 
1130                     timeout { verbose "partial: timeout" 3 }
 
1132                 set string [string range "$string" [expr $foo + 1] end]
 
1133                 set multi_line_re "$multi_line_re.*\[\r\n\] *>"
 
1138         if { "$string" != "" } {
 
1139             if { [send_gdb "$string"] != "" } {
 
1140                 perror "Couldn't send $command to GDB."
 
1145     set code $early_processed_code
 
1147         -re ".*A problem internal to GDB has been detected" {
 
1148             fail "$message (GDB internal error)"
 
1149             gdb_internal_error_resync
 
1152         -re "\\*\\*\\* DOSEXIT code.*" {
 
1153             if { $message != "" } {
 
1159     append code $processed_code
 
1161     # Reset the spawn id, in case the processed code used -i.
 
1167         -re "Ending remote debugging.*$prompt_regexp" {
 
1168             if ![isnative] then {
 
1169                 warning "Can`t communicate to remote target."
 
1175         -re "Undefined\[a-z\]* command:.*$prompt_regexp" {
 
1176             perror "Undefined command \"$command\"."
 
1180         -re "Ambiguous command.*$prompt_regexp" {
 
1181             perror "\"$command\" is not a unique command name."
 
1185         -re "$inferior_exited_re with code \[0-9\]+.*$prompt_regexp" {
 
1186             if ![string match "" $message] then {
 
1187                 set errmsg "$message (the program exited)"
 
1189                 set errmsg "$command (the program exited)"
 
1194         -re "$inferior_exited_re normally.*$prompt_regexp" {
 
1195             if ![string match "" $message] then {
 
1196                 set errmsg "$message (the program exited)"
 
1198                 set errmsg "$command (the program exited)"
 
1203         -re "The program is not being run.*$prompt_regexp" {
 
1204             if ![string match "" $message] then {
 
1205                 set errmsg "$message (the program is no longer running)"
 
1207                 set errmsg "$command (the program is no longer running)"
 
1212         -re "\r\n$prompt_regexp" {
 
1213             if ![string match "" $message] then {
 
1218         -re "$pagination_prompt" {
 
1220             perror "Window too small."
 
1224         -re "\\((y or n|y or \\\[n\\\]|\\\[y\\\] or n)\\) " {
 
1225             send_gdb "n\n" answer
 
1226             gdb_expect -re "$prompt_regexp"
 
1227             fail "$message (got interactive prompt)"
 
1230         -re "\\\[0\\\] cancel\r\n\\\[1\\\] all.*\r\n> $" {
 
1232             gdb_expect -re "$prompt_regexp"
 
1233             fail "$message (got breakpoint menu)"
 
1239             perror "GDB process no longer exists"
 
1240             set wait_status [wait -i $gdb_spawn_id]
 
1241             verbose -log "GDB process exited with wait status $wait_status"
 
1242             if { $message != "" } {
 
1249     if {$line_by_line} {
 
1251            -re "\r\n\[^\r\n\]*(?=\r\n)" {
 
1257     # Now patterns that apply to any spawn id specified.
 
1261             perror "Process no longer exists"
 
1262             if { $message != "" } {
 
1268             perror "internal buffer is full."
 
1273             if ![string match "" $message] then {
 
1274                 fail "$message (timeout)"
 
1280     # remote_expect calls the eof section if there is an error on the
 
1281     # expect call.  We already have eof sections above, and we don't
 
1282     # want them to get called in that situation.  Since the last eof
 
1283     # section becomes the error section, here we define another eof
 
1284     # section, but with an empty spawn_id list, so that it won't ever
 
1288             # This comment is here because the eof section must not be
 
1289             # the empty string, otherwise remote_expect won't realize
 
1294     # Create gdb_test_name in the parent scope.  If this variable
 
1295     # already exists, which it might if we have nested calls to
 
1296     # gdb_test_multiple, then preserve the old value, otherwise,
 
1297     # create a new variable in the parent scope.
 
1298     upvar gdb_test_name gdb_test_name
 
1299     if { [info exists gdb_test_name] } {
 
1300         set gdb_test_name_old "$gdb_test_name"
 
1302     set gdb_test_name "$message"
 
1305     set code [catch {gdb_expect $code} string]
 
1307     # Clean up the gdb_test_name variable.  If we had a
 
1308     # previous value then restore it, otherwise, delete the variable
 
1309     # from the parent scope.
 
1310     if { [info exists gdb_test_name_old] } {
 
1311         set gdb_test_name "$gdb_test_name_old"
 
1317         global errorInfo errorCode
 
1318         return -code error -errorinfo $errorInfo -errorcode $errorCode $string
 
1319     } elseif {$code > 1} {
 
1320         return -code $code $string
 
1325 # Usage: gdb_test_multiline NAME INPUT RESULT {INPUT RESULT} ...
 
1326 # Run a test named NAME, consisting of multiple lines of input.
 
1327 # After each input line INPUT, search for result line RESULT.
 
1328 # Succeed if all results are seen; fail otherwise.
 
1330 proc gdb_test_multiline { name args } {
 
1333     foreach {input result} $args {
 
1335         if {[gdb_test_multiple $input "$name: input $inputnr: $input" {
 
1336             -re "\[\r\n\]*($result)\[\r\n\]+($gdb_prompt | *>)$" {
 
1347 # gdb_test [-prompt PROMPT_REGEXP] [-lbl]
 
1348 #          COMMAND [PATTERN] [MESSAGE] [QUESTION RESPONSE]
 
1349 # Send a command to gdb; test the result.
 
1351 # COMMAND is the command to execute, send to GDB with send_gdb.  If
 
1352 #   this is the null string no command is sent.
 
1353 # PATTERN is the pattern to match for a PASS, and must NOT include
 
1354 #   the \r\n sequence immediately before the gdb prompt.  This argument
 
1355 #   may be omitted to just match the prompt, ignoring whatever output 
 
1357 # MESSAGE is an optional message to be printed.  If this is
 
1358 #   omitted, then the pass/fail messages use the command string as the
 
1359 #   message.  (If this is the empty string, then sometimes we don't
 
1360 #   call pass or fail at all; I don't understand this at all.)
 
1361 # QUESTION is a question GDB should ask in response to COMMAND, like
 
1362 #   "are you sure?"  If this is specified, the test fails if GDB
 
1363 #   doesn't print the question.
 
1364 # RESPONSE is the response to send when QUESTION appears.
 
1366 # -prompt PROMPT_REGEXP specifies a regexp matching the expected prompt
 
1367 #   after the command output.  If empty, defaults to "$gdb_prompt $".
 
1368 # -lbl specifies that line-by-line matching will be used.
 
1369 # -nopass specifies that a PASS should not be issued.
 
1372 #    1 if the test failed,
 
1373 #    0 if the test passes,
 
1374 #   -1 if there was an internal error.
 
1376 proc gdb_test { args } {
 
1378     upvar timeout timeout
 
1386     lassign $args command pattern message question response
 
1388     # Can't have a question without a response.
 
1389     if { $question != "" && $response == "" || [llength $args] > 5 } {
 
1390         error "Unexpected arguments: $args"
 
1393     if { $message == "" } {
 
1394         set message $command
 
1397     set prompt [fill_in_default_prompt $prompt]
 
1403         -re "\[\r\n\]*(?:$pattern)\[\r\n\]+$prompt" {
 
1404             if { $question != "" & !$saw_question} {
 
1406             } elseif {!$nopass} {
 
1412     if { $question != "" } {
 
1416                 send_gdb "$response\n"
 
1422     set user_code [join $user_code]
 
1425     lappend opts "-prompt" "$prompt"
 
1430     return [gdb_test_multiple $command $message {*}$opts $user_code]
 
1433 # Return 1 if version MAJOR.MINOR is at least AT_LEAST_MAJOR.AT_LEAST_MINOR.
 
1434 proc version_at_least { major minor at_least_major at_least_minor} {
 
1435     if { $major > $at_least_major } {
 
1437     } elseif { $major == $at_least_major \
 
1438                    && $minor >= $at_least_minor } {
 
1445 # Return 1 if tcl version used is at least MAJOR.MINOR
 
1446 proc tcl_version_at_least { major minor } {
 
1448     regexp {^([0-9]+)\.([0-9]+)$} $tcl_version \
 
1449         dummy tcl_version_major tcl_version_minor
 
1450     return [version_at_least $tcl_version_major $tcl_version_minor \
 
1454 if { [tcl_version_at_least 8 5] == 0 } {
 
1455     # lrepeat was added in tcl 8.5.  Only add if missing.
 
1456     proc lrepeat { n element } {
 
1457         if { [string is integer -strict $n] == 0 } {
 
1458             error "expected integer but got \"$n\""
 
1461             error "bad count \"$n\": must be integer >= 0"
 
1464         for {set i 0} {$i < $n} {incr i} {
 
1465             lappend res $element
 
1471 # gdb_test_no_output [-prompt PROMPT_REGEXP] [-nopass] COMMAND [MESSAGE]
 
1472 # Send a command to GDB and verify that this command generated no output.
 
1474 # See gdb_test for a description of the -prompt, -nopass, COMMAND, and
 
1475 # MESSAGE parameters.
 
1477 proc gdb_test_no_output { args } {
 
1485     lassign $args command message
 
1487     set prompt [fill_in_default_prompt $prompt]
 
1489     set command_regex [string_to_regexp $command]
 
1490     gdb_test_multiple $command $message -prompt $prompt {
 
1491         -re "^$command_regex\r\n$prompt" {
 
1499 # Send a command and then wait for a sequence of outputs.
 
1500 # This is useful when the sequence is long and contains ".*", a single
 
1501 # regexp to match the entire output can get a timeout much easier.
 
1503 # COMMAND is the command to execute, send to GDB with send_gdb.  If
 
1504 #   this is the null string no command is sent.
 
1505 # TEST_NAME is passed to pass/fail.  COMMAND is used if TEST_NAME is "".
 
1506 # EXPECTED_OUTPUT_LIST is a list of regexps of expected output, which are
 
1507 # processed in order, and all must be present in the output.
 
1509 # The -prompt switch can be used to override the prompt expected at the end of
 
1510 # the output sequence.
 
1512 # It is unnecessary to specify ".*" at the beginning or end of any regexp,
 
1513 # there is an implicit ".*" between each element of EXPECTED_OUTPUT_LIST.
 
1514 # There is also an implicit ".*" between the last regexp and the gdb prompt.
 
1516 # Like gdb_test and gdb_test_multiple, the output is expected to end with the
 
1517 # gdb prompt, which must not be specified in EXPECTED_OUTPUT_LIST.
 
1520 #    1 if the test failed,
 
1521 #    0 if the test passes,
 
1522 #   -1 if there was an internal error.
 
1524 proc gdb_test_sequence { args } {
 
1527     parse_args {{prompt ""}}
 
1529     if { $prompt == "" } {
 
1530         set prompt "$gdb_prompt $"
 
1533     if { [llength $args] != 3 } {
 
1534         error "Unexpected # of arguments, expecting: COMMAND TEST_NAME EXPECTED_OUTPUT_LIST"
 
1537     lassign $args command test_name expected_output_list
 
1539     if { $test_name == "" } {
 
1540         set test_name $command
 
1543     lappend expected_output_list ""; # implicit ".*" before gdb prompt
 
1545     if { $command != "" } {
 
1546         send_gdb "$command\n"
 
1549     return [gdb_expect_list $test_name $prompt $expected_output_list]
 
1553 # Match output of COMMAND using RE.  Read output line-by-line.
 
1554 # Report pass/fail with MESSAGE.
 
1555 # For a command foo with output:
 
1560 # the portion matched using RE is:
 
1565 # Optionally, additional -re-not <regexp> arguments can be specified, to
 
1566 # ensure that a regexp is not match by the COMMAND output.
 
1567 # Such an additional argument generates an additional PASS/FAIL of the form:
 
1568 #   PASS: test-case.exp: $message: pattern not matched: <regexp>
 
1570 proc gdb_test_lines { command message re args } {
 
1573     for {set i 0} {$i < [llength $args]} {incr i} {
 
1574         set arg [lindex $args $i]
 
1575         if { $arg == "-re-not" } {
 
1577             if { [llength $args] == $i } {
 
1578                 error "Missing argument for -re-not"
 
1581             set arg [lindex $args $i]
 
1584             error "Unhandled argument: $arg"
 
1588     if { $message == ""} {
 
1589         set message $command
 
1593     gdb_test_multiple $command $message {
 
1594         -re "\r\n(\[^\r\n\]*)(?=\r\n)" {
 
1595             set line $expect_out(1,string)
 
1596             if { $lines eq "" } {
 
1597                 append lines "$line"
 
1599                 append lines "\r\n$line"
 
1608     gdb_assert { [regexp $re $lines] } $message
 
1610     foreach re $re_not {
 
1611         gdb_assert { ![regexp $re $lines] } "$message: pattern not matched: $re"
 
1615 # Test that a command gives an error.  For pass or fail, return
 
1616 # a 1 to indicate that more tests can proceed.  However a timeout
 
1617 # is a serious error, generates a special fail message, and causes
 
1618 # a 0 to be returned to indicate that more tests are likely to fail
 
1621 proc test_print_reject { args } {
 
1625     if [llength $args]==2 then {
 
1626         set expectthis [lindex $args 1]
 
1628         set expectthis "should never match this bogus string"
 
1630     set sendthis [lindex $args 0]
 
1631     if $verbose>2 then {
 
1632         send_user "Sending \"$sendthis\" to gdb\n"
 
1633         send_user "Looking to match \"$expectthis\"\n"
 
1635     send_gdb "$sendthis\n"
 
1636     #FIXME: Should add timeout as parameter.
 
1638         -re "A .* in expression.*\\.*$gdb_prompt $" {
 
1639             pass "reject $sendthis"
 
1642         -re "Invalid syntax in expression.*$gdb_prompt $" {
 
1643             pass "reject $sendthis"
 
1646         -re "Junk after end of expression.*$gdb_prompt $" {
 
1647             pass "reject $sendthis"
 
1650         -re "Invalid number.*$gdb_prompt $" {
 
1651             pass "reject $sendthis"
 
1654         -re "Invalid character constant.*$gdb_prompt $" {
 
1655             pass "reject $sendthis"
 
1658         -re "No symbol table is loaded.*$gdb_prompt $" {
 
1659             pass "reject $sendthis"
 
1662         -re "No symbol .* in current context.*$gdb_prompt $" {
 
1663             pass "reject $sendthis"
 
1666         -re "Unmatched single quote.*$gdb_prompt $" {
 
1667             pass "reject $sendthis"
 
1670         -re "A character constant must contain at least one character.*$gdb_prompt $" {
 
1671             pass "reject $sendthis"
 
1674         -re "$expectthis.*$gdb_prompt $" {
 
1675             pass "reject $sendthis"
 
1678         -re ".*$gdb_prompt $" {
 
1679             fail "reject $sendthis"
 
1683             fail "reject $sendthis (eof or timeout)"
 
1690 # Same as gdb_test, but the second parameter is not a regexp,
 
1691 # but a string that must match exactly.
 
1693 proc gdb_test_exact { args } {
 
1694     upvar timeout timeout
 
1696     set command [lindex $args 0]
 
1698     # This applies a special meaning to a null string pattern.  Without
 
1699     # this, "$pattern\r\n$gdb_prompt $" will match anything, including error
 
1700     # messages from commands that should have no output except a new
 
1701     # prompt.  With this, only results of a null string will match a null
 
1704     set pattern [lindex $args 1]
 
1705     if [string match $pattern ""] {
 
1706         set pattern [string_to_regexp [lindex $args 0]]
 
1708         set pattern [string_to_regexp [lindex $args 1]]
 
1711     # It is most natural to write the pattern argument with only
 
1712     # embedded \n's, especially if you are trying to avoid Tcl quoting
 
1713     # problems.  But gdb_expect really wants to see \r\n in patterns.  So
 
1714     # transform the pattern here.  First transform \r\n back to \n, in
 
1715     # case some users of gdb_test_exact already do the right thing.
 
1716     regsub -all "\r\n" $pattern "\n" pattern
 
1717     regsub -all "\n" $pattern "\r\n" pattern
 
1718     if [llength $args]==3 then {
 
1719         set message [lindex $args 2]
 
1720         return [gdb_test $command $pattern $message]
 
1723     return [gdb_test $command $pattern]
 
1726 # Wrapper around gdb_test_multiple that looks for a list of expected
 
1727 # output elements, but which can appear in any order.
 
1728 # CMD is the gdb command.
 
1729 # NAME is the name of the test.
 
1730 # ELM_FIND_REGEXP specifies how to partition the output into elements to
 
1732 # ELM_EXTRACT_REGEXP specifies the part of ELM_FIND_REGEXP to compare.
 
1733 # RESULT_MATCH_LIST is a list of exact matches for each expected element.
 
1734 # All elements of RESULT_MATCH_LIST must appear for the test to pass.
 
1736 # A typical use of ELM_FIND_REGEXP/ELM_EXTRACT_REGEXP is to extract one line
 
1737 # of text per element and then strip trailing \r\n's.
 
1739 # gdb_test_list_exact "foo" "bar" \
 
1740 #    "\[^\r\n\]+\[\r\n\]+" \
 
1743 #       {expected result 1} \
 
1744 #       {expected result 2} \
 
1747 proc gdb_test_list_exact { cmd name elm_find_regexp elm_extract_regexp result_match_list } {
 
1750     set matches [lsort $result_match_list]
 
1752     gdb_test_multiple $cmd $name {
 
1753         "$cmd\[\r\n\]" { exp_continue }
 
1754         -re $elm_find_regexp {
 
1755             set str $expect_out(0,string)
 
1756             verbose -log "seen: $str" 3
 
1757             regexp -- $elm_extract_regexp $str elm_seen
 
1758             verbose -log "extracted: $elm_seen" 3
 
1759             lappend seen $elm_seen
 
1762         -re "$gdb_prompt $" {
 
1764             foreach got [lsort $seen] have $matches {
 
1765                 if {![string equal $got $have]} {
 
1770             if {[string length $failed] != 0} {
 
1771                 fail "$name ($failed not found)"
 
1779 # gdb_test_stdio COMMAND INFERIOR_PATTERN GDB_PATTERN MESSAGE
 
1780 # Send a command to gdb; expect inferior and gdb output.
 
1782 # See gdb_test_multiple for a description of the COMMAND and MESSAGE
 
1785 # INFERIOR_PATTERN is the pattern to match against inferior output.
 
1787 # GDB_PATTERN is the pattern to match against gdb output, and must NOT
 
1788 # include the \r\n sequence immediately before the gdb prompt, nor the
 
1789 # prompt.  The default is empty.
 
1791 # Both inferior and gdb patterns must match for a PASS.
 
1793 # If MESSAGE is ommitted, then COMMAND will be used as the message.
 
1796 #    1 if the test failed,
 
1797 #    0 if the test passes,
 
1798 #   -1 if there was an internal error.
 
1801 proc gdb_test_stdio {command inferior_pattern {gdb_pattern ""} {message ""}} {
 
1802     global inferior_spawn_id gdb_spawn_id
 
1805     if {$message == ""} {
 
1806         set message $command
 
1809     set inferior_matched 0
 
1812     # Use an indirect spawn id list, and remove the inferior spawn id
 
1813     # from the expected output as soon as it matches, in case
 
1814     # $inferior_pattern happens to be a prefix of the resulting full
 
1815     # gdb pattern below (e.g., "\r\n").
 
1816     global gdb_test_stdio_spawn_id_list
 
1817     set gdb_test_stdio_spawn_id_list "$inferior_spawn_id"
 
1819     # Note that if $inferior_spawn_id and $gdb_spawn_id are different,
 
1820     # then we may see gdb's output arriving before the inferior's
 
1822     set res [gdb_test_multiple $command $message {
 
1823         -i gdb_test_stdio_spawn_id_list -re "$inferior_pattern" {
 
1824             set inferior_matched 1
 
1825             if {!$gdb_matched} {
 
1826                 set gdb_test_stdio_spawn_id_list ""
 
1830         -i $gdb_spawn_id -re "$gdb_pattern\r\n$gdb_prompt $" {
 
1832             if {!$inferior_matched} {
 
1840         verbose -log "inferior_matched=$inferior_matched, gdb_matched=$gdb_matched"
 
1845 # Wrapper around gdb_test_multiple to be used when testing expression
 
1846 # evaluation while 'set debug expression 1' is in effect.
 
1847 # Looks for some patterns that indicates the expression was rejected.
 
1849 # CMD is the command to execute, which should include an expression
 
1850 # that GDB will need to parse.
 
1852 # OUTPUT is the expected output pattern.
 
1854 # TESTNAME is the name to be used for the test, defaults to CMD if not
 
1856 proc gdb_test_debug_expr { cmd output {testname "" }} {
 
1859     if { ${testname} == "" } {
 
1863     gdb_test_multiple $cmd $testname {
 
1864         -re ".*Invalid expression.*\r\n$gdb_prompt $" {
 
1867         -re ".*\[\r\n\]$output\r\n$gdb_prompt $" {
 
1873 # get_print_expr_at_depths EXP OUTPUTS
 
1875 # Used for testing 'set print max-depth'.  Prints the expression EXP
 
1876 # with 'set print max-depth' set to various depths.  OUTPUTS is a list
 
1877 # of `n` different patterns to match at each of the depths from 0 to
 
1880 # This proc does one final check with the max-depth set to 'unlimited'
 
1881 # which is tested against the last pattern in the OUTPUTS list.  The
 
1882 # OUTPUTS list is therefore required to match every depth from 0 to a
 
1883 # depth where the whole of EXP is printed with no ellipsis.
 
1885 # This proc leaves the 'set print max-depth' set to 'unlimited'.
 
1886 proc gdb_print_expr_at_depths {exp outputs} {
 
1887     for { set depth 0 } { $depth <= [llength $outputs] } { incr depth } {
 
1888         if { $depth == [llength $outputs] } {
 
1889             set expected_result [lindex $outputs [expr [llength $outputs] - 1]]
 
1890             set depth_string "unlimited"
 
1892             set expected_result [lindex $outputs $depth]
 
1893             set depth_string $depth
 
1896         with_test_prefix "exp='$exp': depth=${depth_string}" {
 
1897             gdb_test_no_output "set print max-depth ${depth_string}"
 
1898             gdb_test "p $exp" "$expected_result"
 
1905 # Issue a PASS and return true if evaluating CONDITION in the caller's
 
1906 # frame returns true, and issue a FAIL and return false otherwise.
 
1907 # MESSAGE is the pass/fail message to be printed.  If MESSAGE is
 
1908 # omitted or is empty, then the pass/fail messages use the condition
 
1909 # string as the message.
 
1911 proc gdb_assert { condition {message ""} } {
 
1912     if { $message == ""} {
 
1913         set message $condition
 
1916     set code [catch {uplevel 1 expr $condition} res]
 
1918         # If code is 1 (TCL_ERROR), it means evaluation failed and res contains
 
1919         # an error message.  Print the error message, and set res to 0 since we
 
1920         # want to return a boolean.
 
1921         warning "While evaluating expression in gdb_assert: $res"
 
1924     } elseif { !$res } {
 
1932 proc gdb_reinitialize_dir { subdir } {
 
1935     if [is_remote host] {
 
1940         -re "Reinitialize source path to empty.*y or n. " {
 
1941             send_gdb "y\n" answer
 
1943                 -re "Source directories searched.*$gdb_prompt $" {
 
1944                     send_gdb "dir $subdir\n"
 
1946                         -re "Source directories searched.*$gdb_prompt $" {
 
1947                             verbose "Dir set to $subdir"
 
1949                         -re "$gdb_prompt $" {
 
1950                             perror "Dir \"$subdir\" failed."
 
1954                 -re "$gdb_prompt $" {
 
1955                     perror "Dir \"$subdir\" failed."
 
1959         -re "$gdb_prompt $" {
 
1960             perror "Dir \"$subdir\" failed."
 
1966 # gdb_exit -- exit the GDB, killing the target program if necessary
 
1968 proc default_gdb_exit {} {
 
1970     global INTERNAL_GDBFLAGS GDBFLAGS
 
1971     global gdb_spawn_id inferior_spawn_id
 
1972     global inotify_log_file
 
1974     if ![info exists gdb_spawn_id] {
 
1978     verbose "Quitting $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
 
1980     if {[info exists inotify_log_file] && [file exists $inotify_log_file]} {
 
1981         set fd [open $inotify_log_file]
 
1982         set data [read -nonewline $fd]
 
1985         if {[string compare $data ""] != 0} {
 
1986             warning "parallel-unsafe file creations noticed"
 
1989             set fd [open $inotify_log_file w]
 
1994     if { [is_remote host] && [board_info host exists fileid] } {
 
1998                 send_gdb "y\n" answer
 
2001             -re "DOSEXIT code" { }
 
2006     if ![is_remote host] {
 
2010     unset ::gdb_tty_name
 
2011     unset inferior_spawn_id
 
2014 # Load a file into the debugger.
 
2015 # The return value is 0 for success, -1 for failure.
 
2017 # This procedure also set the global variable GDB_FILE_CMD_DEBUG_INFO
 
2018 # to one of these values:
 
2020 #   debug    file was loaded successfully and has debug information
 
2021 #   nodebug  file was loaded successfully and has no debug information
 
2022 #   lzma     file was loaded, .gnu_debugdata found, but no LZMA support
 
2024 #   fail     file was not loaded
 
2026 # This procedure also set the global variable GDB_FILE_CMD_MSG to the
 
2027 # output of the file command in case of success.
 
2029 # I tried returning this information as part of the return value,
 
2030 # but ran into a mess because of the many re-implementations of
 
2031 # gdb_load in config/*.exp.
 
2033 # TODO: gdb.base/sepdebug.exp and gdb.stabs/weird.exp might be able to use
 
2034 # this if they can get more information set.
 
2036 proc gdb_file_cmd { arg } {
 
2039     global last_loaded_file
 
2041     # GCC for Windows target may create foo.exe given "-o foo".
 
2042     if { ![file exists $arg] && [file exists "$arg.exe"] } {
 
2046     # Save this for the benefit of gdbserver-support.exp.
 
2047     set last_loaded_file $arg
 
2049     # Set whether debug info was found.
 
2050     # Default to "fail".
 
2051     global gdb_file_cmd_debug_info gdb_file_cmd_msg
 
2052     set gdb_file_cmd_debug_info "fail"
 
2054     if [is_remote host] {
 
2055         set arg [remote_download host $arg]
 
2057             perror "download failed"
 
2062     # The file command used to kill the remote target.  For the benefit
 
2063     # of the testsuite, preserve this behavior.  Mark as optional so it doesn't
 
2064     # get written to the stdin log.
 
2065     send_gdb "kill\n" optional
 
2067         -re "Kill the program being debugged. .y or n. $" {
 
2068             send_gdb "y\n" answer
 
2069             verbose "\t\tKilling previous program being debugged"
 
2072         -re "$gdb_prompt $" {
 
2077     send_gdb "file $arg\n"
 
2078     set new_symbol_table 0
 
2079     set basename [file tail $arg]
 
2081         -re "(Reading symbols from.*LZMA support was disabled.*$gdb_prompt $)" {
 
2082             verbose "\t\tLoaded $arg into $GDB; .gnu_debugdata found but no LZMA available"
 
2083             set gdb_file_cmd_msg $expect_out(1,string)
 
2084             set gdb_file_cmd_debug_info "lzma"
 
2087         -re "(Reading symbols from.*no debugging symbols found.*$gdb_prompt $)" {
 
2088             verbose "\t\tLoaded $arg into $GDB with no debugging symbols"
 
2089             set gdb_file_cmd_msg $expect_out(1,string)
 
2090             set gdb_file_cmd_debug_info "nodebug"
 
2093         -re "(Reading symbols from.*$gdb_prompt $)" {
 
2094             verbose "\t\tLoaded $arg into $GDB"
 
2095             set gdb_file_cmd_msg $expect_out(1,string)
 
2096             set gdb_file_cmd_debug_info "debug"
 
2099         -re "Load new symbol table from \".*\".*y or n. $" {
 
2100             if { $new_symbol_table > 0 } {
 
2101                 perror [join [list "Couldn't load $basename,"
 
2102                               "interactive prompt loop detected."]]
 
2105             send_gdb "y\n" answer
 
2106             incr new_symbol_table
 
2107             set suffix "-- with new symbol table"
 
2108             set arg "$arg $suffix"
 
2109             set basename "$basename $suffix"
 
2112         -re "No such file or directory.*$gdb_prompt $" {
 
2113             perror "($basename) No such file or directory"
 
2116         -re "A problem internal to GDB has been detected" {
 
2117             perror "Couldn't load $basename into GDB (GDB internal error)."
 
2118             gdb_internal_error_resync
 
2121         -re "$gdb_prompt $" {
 
2122             perror "Couldn't load $basename into GDB."
 
2126             perror "Couldn't load $basename into GDB (timeout)."
 
2130             # This is an attempt to detect a core dump, but seems not to
 
2131             # work.  Perhaps we need to match .* followed by eof, in which
 
2132             # gdb_expect does not seem to have a way to do that.
 
2133             perror "Couldn't load $basename into GDB (eof)."
 
2139 # The expect "spawn" function puts the tty name into the spawn_out
 
2140 # array; but dejagnu doesn't export this globally.  So, we have to
 
2141 # wrap spawn with our own function and poke in the built-in spawn
 
2142 # so that we can capture this value.
 
2144 # If available, the TTY name is saved to the LAST_SPAWN_TTY_NAME global.
 
2145 # Otherwise, LAST_SPAWN_TTY_NAME is unset.
 
2147 proc spawn_capture_tty_name { args } {
 
2148     set result [uplevel builtin_spawn $args]
 
2149     upvar spawn_out spawn_out
 
2150     if { [info exists spawn_out(slave,name)] } {
 
2151         set ::last_spawn_tty_name $spawn_out(slave,name)
 
2153         # If a process is spawned as part of a pipe line (e.g. passing
 
2154         # -leaveopen to the spawn proc) then the spawned process is no
 
2155         # assigned a tty and spawn_out(slave,name) will not be set.
 
2156         # In that case we want to ensure that last_spawn_tty_name is
 
2159         # If the previous process spawned was also not assigned a tty
 
2160         # (e.g. multiple processed chained in a pipeline) then
 
2161         # last_spawn_tty_name will already be unset, so, if we don't
 
2162         # use -nocomplain here we would otherwise get an error.
 
2163         unset -nocomplain ::last_spawn_tty_name
 
2168 rename spawn builtin_spawn
 
2169 rename spawn_capture_tty_name spawn
 
2171 # Default gdb_spawn procedure.
 
2173 proc default_gdb_spawn { } {
 
2176     global INTERNAL_GDBFLAGS GDBFLAGS
 
2179     # Set the default value, it may be overriden later by specific testfile.
 
2181     # Use `set_board_info use_gdb_stub' for the board file to flag the inferior
 
2182     # is already started after connecting and run/attach are not supported.
 
2183     # This is used for the "remote" protocol.  After GDB starts you should
 
2184     # check global $use_gdb_stub instead of the board as the testfile may force
 
2185     # a specific different target protocol itself.
 
2186     set use_gdb_stub [target_info exists use_gdb_stub]
 
2188     verbose "Spawning $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
 
2189     gdb_write_cmd_file "$GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
 
2191     if [info exists gdb_spawn_id] {
 
2195     if ![is_remote host] {
 
2196         if { [which $GDB] == 0 } then {
 
2197             perror "$GDB does not exist."
 
2202     # Put GDBFLAGS last so that tests can put "--args ..." in it.
 
2203     set res [remote_spawn host "$GDB $INTERNAL_GDBFLAGS [host_info gdb_opts] $GDBFLAGS"]
 
2204     if { $res < 0 || $res == "" } {
 
2205         perror "Spawning $GDB failed."
 
2209     set gdb_spawn_id $res
 
2210     set ::gdb_tty_name $::last_spawn_tty_name
 
2214 # Default gdb_start procedure.
 
2216 proc default_gdb_start { } {
 
2219     global inferior_spawn_id
 
2221     if [info exists gdb_spawn_id] {
 
2225     # Keep track of the number of times GDB has been launched.
 
2226     global gdb_instances
 
2236     # Default to assuming inferior I/O is done on GDB's terminal.
 
2237     if {![info exists inferior_spawn_id]} {
 
2238         set inferior_spawn_id $gdb_spawn_id
 
2241     # When running over NFS, particularly if running many simultaneous
 
2242     # tests on different hosts all using the same server, things can
 
2243     # get really slow.  Give gdb at least 3 minutes to start up.
 
2245         -re "\[\r\n\]$gdb_prompt $" {
 
2246             verbose "GDB initialized."
 
2248         -re "\[\r\n\]\033\\\[.2004h$gdb_prompt $" {
 
2249             # This special case detects what happens when GDB is
 
2250             # started with bracketed paste mode enabled.  This mode is
 
2251             # usually forced off (see setting of INPUTRC in
 
2252             # default_gdb_init), but for at least one test we turn
 
2253             # bracketed paste mode back on, and then start GDB.  In
 
2254             # that case, this case is hit.
 
2255             verbose "GDB initialized."
 
2257         -re "$gdb_prompt $"     {
 
2258             perror "GDB never initialized."
 
2263             perror "(timeout) GDB never initialized after 10 seconds."
 
2269             perror "(eof) GDB never initialized."
 
2275     # force the height to "unlimited", so no pagers get used
 
2277     send_gdb "set height 0\n"
 
2279         -re "$gdb_prompt $" { 
 
2280             verbose "Setting height to 0." 2
 
2283             warning "Couldn't set the height to 0"
 
2286     # force the width to "unlimited", so no wraparound occurs
 
2287     send_gdb "set width 0\n"
 
2289         -re "$gdb_prompt $" {
 
2290             verbose "Setting width to 0." 2
 
2293             warning "Couldn't set the width to 0."
 
2301 # Utility procedure to give user control of the gdb prompt in a script. It is
 
2302 # meant to be used for debugging test cases, and should not be left in the
 
2305 proc gdb_interact { } {
 
2307     set spawn_id $gdb_spawn_id
 
2309     send_user "+------------------------------------------+\n"
 
2310     send_user "| Script interrupted, you can now interact |\n"
 
2311     send_user "| with by gdb. Type >>> to continue.       |\n"
 
2312     send_user "+------------------------------------------+\n"
 
2319 # Examine the output of compilation to determine whether compilation
 
2320 # failed or not.  If it failed determine whether it is due to missing
 
2321 # compiler or due to compiler error.  Report pass, fail or unsupported
 
2324 proc gdb_compile_test {src output} {
 
2325     set msg "compilation [file tail $src]"
 
2327     if { $output == "" } {
 
2332     if { [regexp {^[a-zA-Z_0-9]+: Can't find [^ ]+\.$} $output]
 
2333          || [regexp {.*: command not found[\r|\n]*$} $output]
 
2334          || [regexp {.*: [^\r\n]*compiler not installed[^\r\n]*[\r|\n]*$} $output] } {
 
2335         unsupported "$msg (missing compiler)"
 
2339     set gcc_re ".*: error: unrecognized command line option "
 
2340     set clang_re ".*: error: unsupported option "
 
2341     if { [regexp "(?:$gcc_re|$clang_re)(\[^ \t;\r\n\]*)" $output dummy option]
 
2342          && $option != "" } {
 
2343         unsupported "$msg (unsupported option $option)"
 
2347     # Unclassified compilation failure, be more verbose.
 
2348     verbose -log "compilation failed: $output" 2
 
2352 # Return a 1 for configurations for which we don't even want to try to
 
2355 proc skip_cplus_tests {} {
 
2356     if { [istarget "h8300-*-*"] } {
 
2360     # The C++ IO streams are too large for HC11/HC12 and are thus not
 
2361     # available.  The gdb C++ tests use them and don't compile.
 
2362     if { [istarget "m6811-*-*"] } {
 
2365     if { [istarget "m6812-*-*"] } {
 
2371 # Return a 1 for configurations for which don't have both C++ and the STL.
 
2373 proc skip_stl_tests {} {
 
2374     return [skip_cplus_tests]
 
2377 # Return a 1 if I don't even want to try to test FORTRAN.
 
2379 proc skip_fortran_tests {} {
 
2383 # Return a 1 if I don't even want to try to test ada.
 
2385 proc skip_ada_tests {} {
 
2389 # Return a 1 if I don't even want to try to test GO.
 
2391 proc skip_go_tests {} {
 
2395 # Return a 1 if I don't even want to try to test D.
 
2397 proc skip_d_tests {} {
 
2401 # Return 1 to skip Rust tests, 0 to try them.
 
2402 proc skip_rust_tests {} {
 
2403     if { ![isnative] } {
 
2407     # The rust compiler does not support "-m32", skip.
 
2408     global board board_info
 
2409     set board [target_info name]
 
2410     if {[board_info $board exists multilib_flags]} {
 
2411         foreach flag [board_info $board multilib_flags] {
 
2412             if { $flag == "-m32" } {
 
2421 # Return a 1 for configurations that do not support Python scripting.
 
2422 # PROMPT_REGEXP is the expected prompt.
 
2424 proc skip_python_tests_prompt { prompt_regexp } {
 
2425     gdb_test_multiple "python print ('test')" "verify python support" \
 
2426         -prompt "$prompt_regexp" {
 
2427             -re "not supported.*$prompt_regexp" {
 
2428                 unsupported "Python support is disabled."
 
2431             -re "$prompt_regexp" {}
 
2437 # Return a 1 for configurations that do not support Python scripting.
 
2438 # Note: This also sets various globals that specify which version of Python
 
2439 # is in use.  See skip_python_tests_prompt.
 
2441 proc skip_python_tests {} {
 
2443     return [skip_python_tests_prompt "$gdb_prompt $"]
 
2446 # Return a 1 if we should skip shared library tests.
 
2448 proc skip_shlib_tests {} {
 
2449     # Run the shared library tests on native systems.
 
2454     # An abbreviated list of remote targets where we should be able to
 
2455     # run shared library tests.
 
2456     if {([istarget *-*-linux*]
 
2457          || [istarget *-*-*bsd*]
 
2458          || [istarget *-*-solaris2*]
 
2459          || [istarget *-*-mingw*]
 
2460          || [istarget *-*-cygwin*]
 
2461          || [istarget *-*-pe*])} {
 
2468 # Return 1 if we should skip tui related tests.
 
2470 proc skip_tui_tests {} {
 
2473     gdb_test_multiple "help layout" "verify tui support" {
 
2474         -re "Undefined command: \"layout\".*$gdb_prompt $" {
 
2477         -re "$gdb_prompt $" {
 
2484 # Test files shall make sure all the test result lines in gdb.sum are
 
2485 # unique in a test run, so that comparing the gdb.sum files of two
 
2486 # test runs gives correct results.  Test files that exercise
 
2487 # variations of the same tests more than once, shall prefix the
 
2488 # different test invocations with different identifying strings in
 
2489 # order to make them unique.
 
2491 # About test prefixes:
 
2493 # $pf_prefix is the string that dejagnu prints after the result (FAIL,
 
2494 # PASS, etc.), and before the test message/name in gdb.sum.  E.g., the
 
2495 # underlined substring in
 
2497 #  PASS: gdb.base/mytest.exp: some test
 
2498 #        ^^^^^^^^^^^^^^^^^^^^
 
2502 # The easiest way to adjust the test prefix is to append a test
 
2503 # variation prefix to the $pf_prefix, using the with_test_prefix
 
2506 # proc do_tests {} {
 
2507 #   gdb_test ... ... "test foo"
 
2508 #   gdb_test ... ... "test bar"
 
2510 #   with_test_prefix "subvariation a" {
 
2511 #     gdb_test ... ... "test x"
 
2514 #   with_test_prefix "subvariation b" {
 
2515 #     gdb_test ... ... "test x"
 
2519 # with_test_prefix "variation1" {
 
2520 #   ...do setup for variation 1...
 
2524 # with_test_prefix "variation2" {
 
2525 #   ...do setup for variation 2...
 
2531 #  PASS: gdb.base/mytest.exp: variation1: test foo
 
2532 #  PASS: gdb.base/mytest.exp: variation1: test bar
 
2533 #  PASS: gdb.base/mytest.exp: variation1: subvariation a: test x
 
2534 #  PASS: gdb.base/mytest.exp: variation1: subvariation b: test x
 
2535 #  PASS: gdb.base/mytest.exp: variation2: test foo
 
2536 #  PASS: gdb.base/mytest.exp: variation2: test bar
 
2537 #  PASS: gdb.base/mytest.exp: variation2: subvariation a: test x
 
2538 #  PASS: gdb.base/mytest.exp: variation2: subvariation b: test x
 
2540 # If for some reason more flexibility is necessary, one can also
 
2541 # manipulate the pf_prefix global directly, treating it as a string.
 
2545 #   set saved_pf_prefix
 
2546 #   append pf_prefix "${foo}: bar"
 
2547 #   ... actual tests ...
 
2548 #   set pf_prefix $saved_pf_prefix
 
2551 # Run BODY in the context of the caller, with the current test prefix
 
2552 # (pf_prefix) appended with one space, then PREFIX, and then a colon.
 
2553 # Returns the result of BODY.
 
2555 proc with_test_prefix { prefix body } {
 
2558   set saved $pf_prefix
 
2559   append pf_prefix " " $prefix ":"
 
2560   set code [catch {uplevel 1 $body} result]
 
2561   set pf_prefix $saved
 
2564       global errorInfo errorCode
 
2565       return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
 
2567       return -code $code $result
 
2571 # Wrapper for foreach that calls with_test_prefix on each iteration,
 
2572 # including the iterator's name and current value in the prefix.
 
2574 proc foreach_with_prefix {var list body} {
 
2576     foreach myvar $list {
 
2577         with_test_prefix "$var=$myvar" {
 
2578             set code [catch {uplevel 1 $body} result]
 
2582             global errorInfo errorCode
 
2583             return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
 
2584         } elseif {$code == 3} {
 
2586         } elseif {$code == 2} {
 
2587             return -code $code $result
 
2592 # Like TCL's native proc, but defines a procedure that wraps its body
 
2593 # within 'with_test_prefix "$proc_name" { ... }'.
 
2594 proc proc_with_prefix {name arguments body} {
 
2595     # Define the advertised proc.
 
2596     proc $name $arguments [list with_test_prefix $name $body]
 
2599 # Return an id corresponding to the test prefix stored in $pf_prefix, which
 
2600 # is more suitable for use in a file name.
 
2601 # F.i., for a pf_prefix:
 
2602 #   gdb.dwarf2/dw2-lines.exp: \
 
2603 #     cv=5: cdw=64: lv=5: ldw=64: string_form=line_strp:
 
2605 #   cv-5-cdw-32-lv-5-ldw-64-string_form-line_strp
 
2611     # Strip ".exp: " prefix.
 
2612     set id [regsub  {.*\.exp: } $id {}]
 
2614     # Strip colon suffix.
 
2615     set id [regsub  {:$} $id {}]
 
2618     set id [regsub -all { } $id {}]
 
2620     # Replace colons, equal signs.
 
2621     set id [regsub -all \[:=\] $id -]
 
2626 # Run BODY in the context of the caller.  After BODY is run, the variables
 
2627 # listed in VARS will be reset to the values they had before BODY was run.
 
2629 # This is useful for providing a scope in which it is safe to temporarily
 
2630 # modify global variables, e.g.
 
2632 #   global INTERNAL_GDBFLAGS
 
2635 #   set foo GDBHISTSIZE
 
2637 #   save_vars { INTERNAL_GDBFLAGS env($foo) env(HOME) } {
 
2638 #       append INTERNAL_GDBFLAGS " -nx"
 
2639 #       unset -nocomplain env(GDBHISTSIZE)
 
2644 # Here, although INTERNAL_GDBFLAGS, env(GDBHISTSIZE) and env(HOME) may be
 
2645 # modified inside BODY, this proc guarantees that the modifications will be
 
2646 # undone after BODY finishes executing.
 
2648 proc save_vars { vars body } {
 
2649     array set saved_scalars { }
 
2650     array set saved_arrays { }
 
2654         # First evaluate VAR in the context of the caller in case the variable
 
2655         # name may be a not-yet-interpolated string like env($foo)
 
2656         set var [uplevel 1 list $var]
 
2658         if [uplevel 1 [list info exists $var]] {
 
2659             if [uplevel 1 [list array exists $var]] {
 
2660                 set saved_arrays($var) [uplevel 1 [list array get $var]]
 
2662                 set saved_scalars($var) [uplevel 1 [list set $var]]
 
2665             lappend unset_vars $var
 
2669     set code [catch {uplevel 1 $body} result]
 
2671     foreach {var value} [array get saved_scalars] {
 
2672         uplevel 1 [list set $var $value]
 
2675     foreach {var value} [array get saved_arrays] {
 
2676         uplevel 1 [list unset $var]
 
2677         uplevel 1 [list array set $var $value]
 
2680     foreach var $unset_vars {
 
2681         uplevel 1 [list unset -nocomplain $var]
 
2685         global errorInfo errorCode
 
2686         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
 
2688         return -code $code $result
 
2692 # As save_vars, but for variables stored in the board_info for the
 
2697 #   save_target_board_info { multilib_flags } {
 
2699 #       set board [target_info name]
 
2700 #       unset_board_info multilib_flags
 
2701 #       set_board_info multilib_flags "$multilib_flags"
 
2705 proc save_target_board_info { vars body } {
 
2706     global board board_info
 
2707     set board [target_info name]
 
2709     array set saved_target_board_info { }
 
2710     set unset_target_board_info { }
 
2713         if { [info exists board_info($board,$var)] } {
 
2714             set saved_target_board_info($var) [board_info $board $var]
 
2716             lappend unset_target_board_info $var
 
2720     set code [catch {uplevel 1 $body} result]
 
2722     foreach {var value} [array get saved_target_board_info] {
 
2723         unset_board_info $var
 
2724         set_board_info $var $value
 
2727     foreach var $unset_target_board_info {
 
2728         unset_board_info $var
 
2732         global errorInfo errorCode
 
2733         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
 
2735         return -code $code $result
 
2739 # Run tests in BODY with the current working directory (CWD) set to
 
2740 # DIR.  When BODY is finished, restore the original CWD.  Return the
 
2743 # This procedure doesn't check if DIR is a valid directory, so you
 
2744 # have to make sure of that.
 
2746 proc with_cwd { dir body } {
 
2748     verbose -log "Switching to directory $dir (saved CWD: $saved_dir)."
 
2751     set code [catch {uplevel 1 $body} result]
 
2753     verbose -log "Switching back to $saved_dir."
 
2757         global errorInfo errorCode
 
2758         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
 
2760         return -code $code $result
 
2764 # Run tests in BODY with GDB prompt and variable $gdb_prompt set to
 
2765 # PROMPT.  When BODY is finished, restore GDB prompt and variable
 
2767 # Returns the result of BODY.
 
2771 # 1) If you want to use, for example, "(foo)" as the prompt you must pass it
 
2772 # as "(foo)", and not the regexp form "\(foo\)" (expressed as "\\(foo\\)" in
 
2773 # TCL).  PROMPT is internally converted to a suitable regexp for matching.
 
2774 # We do the conversion from "(foo)" to "\(foo\)" here for a few reasons:
 
2775 #   a) It's more intuitive for callers to pass the plain text form.
 
2776 #   b) We need two forms of the prompt:
 
2777 #      - a regexp to use in output matching,
 
2778 #      - a value to pass to the "set prompt" command.
 
2779 #   c) It's easier to convert the plain text form to its regexp form.
 
2781 # 2) Don't add a trailing space, we do that here.
 
2783 proc with_gdb_prompt { prompt body } {
 
2786     # Convert "(foo)" to "\(foo\)".
 
2787     # We don't use string_to_regexp because while it works today it's not
 
2788     # clear it will work tomorrow: the value we need must work as both a
 
2789     # regexp *and* as the argument to the "set prompt" command, at least until
 
2790     # we start recording both forms separately instead of just $gdb_prompt.
 
2791     # The testsuite is pretty-much hardwired to interpret $gdb_prompt as the
 
2793     regsub -all {[]*+.|()^$\[\\]} $prompt {\\&} prompt
 
2795     set saved $gdb_prompt
 
2797     verbose -log "Setting gdb prompt to \"$prompt \"."
 
2798     set gdb_prompt $prompt
 
2799     gdb_test_no_output "set prompt $prompt " ""
 
2801     set code [catch {uplevel 1 $body} result]
 
2803     verbose -log "Restoring gdb prompt to \"$saved \"."
 
2804     set gdb_prompt $saved
 
2805     gdb_test_no_output "set prompt $saved " ""
 
2808         global errorInfo errorCode
 
2809         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
 
2811         return -code $code $result
 
2815 # Run tests in BODY with target-charset setting to TARGET_CHARSET.  When
 
2816 # BODY is finished, restore target-charset.
 
2818 proc with_target_charset { target_charset body } {
 
2822     gdb_test_multiple "show target-charset" "" {
 
2823         -re "The target character set is \".*; currently (.*)\"\..*$gdb_prompt " {
 
2824             set saved $expect_out(1,string)
 
2826         -re "The target character set is \"(.*)\".*$gdb_prompt " {
 
2827             set saved $expect_out(1,string)
 
2829         -re ".*$gdb_prompt " {
 
2830             fail "get target-charset"
 
2834     gdb_test_no_output -nopass "set target-charset $target_charset"
 
2836     set code [catch {uplevel 1 $body} result]
 
2838     gdb_test_no_output -nopass "set target-charset $saved"
 
2841         global errorInfo errorCode
 
2842         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
 
2844         return -code $code $result
 
2848 # Switch the default spawn id to SPAWN_ID, so that gdb_test,
 
2849 # mi_gdb_test etc. default to using it.
 
2851 proc switch_gdb_spawn_id {spawn_id} {
 
2853     global board board_info
 
2855     set gdb_spawn_id $spawn_id
 
2856     set board [host_info name]
 
2857     set board_info($board,fileid) $spawn_id
 
2860 # Clear the default spawn id.
 
2862 proc clear_gdb_spawn_id {} {
 
2864     global board board_info
 
2866     unset -nocomplain gdb_spawn_id
 
2867     set board [host_info name]
 
2868     unset -nocomplain board_info($board,fileid)
 
2871 # Run BODY with SPAWN_ID as current spawn id.
 
2873 proc with_spawn_id { spawn_id body } {
 
2876     if [info exists gdb_spawn_id] {
 
2877         set saved_spawn_id $gdb_spawn_id
 
2880     switch_gdb_spawn_id $spawn_id
 
2882     set code [catch {uplevel 1 $body} result]
 
2884     if [info exists saved_spawn_id] {
 
2885         switch_gdb_spawn_id $saved_spawn_id
 
2891         global errorInfo errorCode
 
2892         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
 
2894         return -code $code $result
 
2898 # Select the largest timeout from all the timeouts:
 
2899 # - the local "timeout" variable of the scope two levels above,
 
2900 # - the global "timeout" variable,
 
2901 # - the board variable "gdb,timeout".
 
2903 proc get_largest_timeout {} {
 
2904     upvar #0 timeout gtimeout
 
2905     upvar 2 timeout timeout
 
2908     if [info exists timeout] {
 
2911     if { [info exists gtimeout] && $gtimeout > $tmt } {
 
2914     if { [target_info exists gdb,timeout]
 
2915          && [target_info gdb,timeout] > $tmt } {
 
2916         set tmt [target_info gdb,timeout]
 
2926 # Run tests in BODY with timeout increased by factor of FACTOR.  When
 
2927 # BODY is finished, restore timeout.
 
2929 proc with_timeout_factor { factor body } {
 
2932     set savedtimeout $timeout
 
2934     set timeout [expr [get_largest_timeout] * $factor]
 
2935     set code [catch {uplevel 1 $body} result]
 
2937     set timeout $savedtimeout
 
2939         global errorInfo errorCode
 
2940         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
 
2942         return -code $code $result
 
2946 # Run BODY with timeout factor FACTOR if check-read1 is used.
 
2948 proc with_read1_timeout_factor { factor body } {
 
2949     if { [info exists ::env(READ1)] == 1 && $::env(READ1) == 1 } {
 
2950         # Use timeout factor
 
2952         # Reset timeout factor
 
2955     return [uplevel [list with_timeout_factor $factor $body]]
 
2958 # Return 1 if _Complex types are supported, otherwise, return 0.
 
2960 gdb_caching_proc support_complex_tests {
 
2962     if { [gdb_skip_float_test] } {
 
2963         # If floating point is not supported, _Complex is not
 
2968     # Compile a test program containing _Complex types.
 
2970     return [gdb_can_simple_compile complex {
 
2974             _Complex long double cld;
 
2980 # Return 1 if compiling go is supported.
 
2981 gdb_caching_proc support_go_compile {
 
2983     return [gdb_can_simple_compile go-hello {
 
2987             fmt.Println("hello world")
 
2992 # Return 1 if GDB can get a type for siginfo from the target, otherwise
 
2995 proc supports_get_siginfo_type {} {
 
2996     if { [istarget "*-*-linux*"] } {
 
3003 # Return 1 if memory tagging is supported at runtime, otherwise return 0.
 
3005 gdb_caching_proc supports_memtag {
 
3008     gdb_test_multiple "memory-tag check" "" {
 
3009         -re "Memory tagging not supported or disabled by the current architecture\..*$gdb_prompt $" {
 
3012         -re "Argument required \\(address or pointer\\).*$gdb_prompt $" {
 
3019 # Return 1 if the target supports hardware single stepping.
 
3021 proc can_hardware_single_step {} {
 
3023     if { [istarget "arm*-*-*"] || [istarget "mips*-*-*"]
 
3024          || [istarget "tic6x-*-*"] || [istarget "sparc*-*-linux*"]
 
3025          || [istarget "nios2-*-*"] || [istarget "riscv*-*-linux*"] } {
 
3032 # Return 1 if target hardware or OS supports single stepping to signal
 
3033 # handler, otherwise, return 0.
 
3035 proc can_single_step_to_signal_handler {} {
 
3036     # Targets don't have hardware single step.  On these targets, when
 
3037     # a signal is delivered during software single step, gdb is unable
 
3038     # to determine the next instruction addresses, because start of signal
 
3039     # handler is one of them.
 
3040     return [can_hardware_single_step]
 
3043 # Return 1 if target supports process record, otherwise return 0.
 
3045 proc supports_process_record {} {
 
3047     if [target_info exists gdb,use_precord] {
 
3048         return [target_info gdb,use_precord]
 
3051     if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
 
3052          || [istarget "i\[34567\]86-*-linux*"]
 
3053          || [istarget "aarch64*-*-linux*"]
 
3054          || [istarget "powerpc*-*-linux*"]
 
3055          || [istarget "s390*-*-linux*"] } {
 
3062 # Return 1 if target supports reverse debugging, otherwise return 0.
 
3064 proc supports_reverse {} {
 
3066     if [target_info exists gdb,can_reverse] {
 
3067         return [target_info gdb,can_reverse]
 
3070     if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
 
3071          || [istarget "i\[34567\]86-*-linux*"]
 
3072          || [istarget "aarch64*-*-linux*"]
 
3073          || [istarget "powerpc*-*-linux*"]
 
3074          || [istarget "s390*-*-linux*"] } {
 
3081 # Return 1 if readline library is used.
 
3083 proc readline_is_used { } {
 
3086     gdb_test_multiple "show editing" "" {
 
3087         -re ".*Editing of command lines as they are typed is on\..*$gdb_prompt $" {
 
3090         -re ".*$gdb_prompt $" {
 
3096 # Return 1 if target is ELF.
 
3097 gdb_caching_proc is_elf_target {
 
3098     set me "is_elf_target"
 
3100     set src { int foo () {return 0;} }
 
3101     if {![gdb_simple_compile elf_target $src]} {
 
3105     set fp_obj [open $obj "r"]
 
3106     fconfigure $fp_obj -translation binary
 
3107     set data [read $fp_obj]
 
3112     set ELFMAG "\u007FELF"
 
3114     if {[string compare -length 4 $data $ELFMAG] != 0} {
 
3115         verbose "$me:  returning 0" 2
 
3119     verbose "$me:  returning 1" 2
 
3123 # Return 1 if the memory at address zero is readable.
 
3125 gdb_caching_proc is_address_zero_readable {
 
3129     gdb_test_multiple "x 0" "" {
 
3130         -re "Cannot access memory at address 0x0.*$gdb_prompt $" {
 
3133         -re ".*$gdb_prompt $" {
 
3141 # Produce source file NAME and write SOURCES into it.
 
3143 proc gdb_produce_source { name sources } {
 
3145     set f [open $name "w"]
 
3151 # Return 1 if target is ILP32.
 
3152 # This cannot be decided simply from looking at the target string,
 
3153 # as it might depend on externally passed compiler options like -m64.
 
3154 gdb_caching_proc is_ilp32_target {
 
3155     return [gdb_can_simple_compile is_ilp32_target {
 
3156         int dummy[sizeof (int) == 4
 
3157                   && sizeof (void *) == 4
 
3158                   && sizeof (long) == 4 ? 1 : -1];
 
3162 # Return 1 if target is LP64.
 
3163 # This cannot be decided simply from looking at the target string,
 
3164 # as it might depend on externally passed compiler options like -m64.
 
3165 gdb_caching_proc is_lp64_target {
 
3166     return [gdb_can_simple_compile is_lp64_target {
 
3167         int dummy[sizeof (int) == 4
 
3168                   && sizeof (void *) == 8
 
3169                   && sizeof (long) == 8 ? 1 : -1];
 
3173 # Return 1 if target has 64 bit addresses.
 
3174 # This cannot be decided simply from looking at the target string,
 
3175 # as it might depend on externally passed compiler options like -m64.
 
3176 gdb_caching_proc is_64_target {
 
3177     return [gdb_can_simple_compile is_64_target {
 
3178         int function(void) { return 3; }
 
3179         int dummy[sizeof (&function) == 8 ? 1 : -1];
 
3183 # Return 1 if target has x86_64 registers - either amd64 or x32.
 
3184 # x32 target identifies as x86_64-*-linux*, therefore it cannot be determined
 
3185 # just from the target string.
 
3186 gdb_caching_proc is_amd64_regs_target {
 
3187     if {![istarget "x86_64-*-*"] && ![istarget "i?86-*"]} {
 
3191     return [gdb_can_simple_compile is_amd64_regs_target {
 
3201 # Return 1 if this target is an x86 or x86-64 with -m32.
 
3202 proc is_x86_like_target {} {
 
3203     if {![istarget "x86_64-*-*"] && ![istarget i?86-*]} {
 
3206     return [expr [is_ilp32_target] && ![is_amd64_regs_target]]
 
3209 # Return 1 if this target is an arm or aarch32 on aarch64.
 
3211 gdb_caching_proc is_aarch32_target {
 
3212     if { [istarget "arm*-*-*"] } {
 
3216     if { ![istarget "aarch64*-*-*"] } {
 
3223             lappend list "\tmov $reg, $reg"
 
3226     return [gdb_can_simple_compile aarch32 [join $list \n]]
 
3229 # Return 1 if this target is an aarch64, either lp64 or ilp32.
 
3231 proc is_aarch64_target {} {
 
3232     if { ![istarget "aarch64*-*-*"] } {
 
3236     return [expr ![is_aarch32_target]]
 
3239 # Return 1 if displaced stepping is supported on target, otherwise, return 0.
 
3240 proc support_displaced_stepping {} {
 
3242     if { [istarget "x86_64-*-linux*"] || [istarget "i\[34567\]86-*-linux*"]
 
3243          || [istarget "arm*-*-linux*"] || [istarget "powerpc-*-linux*"]
 
3244          || [istarget "powerpc64-*-linux*"] || [istarget "s390*-*-*"]
 
3245          || [istarget "aarch64*-*-linux*"] || [istarget "loongarch*-*-linux*"] } {
 
3252 # Run a test on the target to see if it supports vmx hardware.  Return 0 if so, 
 
3253 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
 
3255 gdb_caching_proc skip_altivec_tests {
 
3256     global srcdir subdir gdb_prompt inferior_exited_re
 
3258     set me "skip_altivec_tests"
 
3260     # Some simulators are known to not support VMX instructions.
 
3261     if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
 
3262         verbose "$me:  target known to not support VMX, returning 1" 2
 
3266     # Make sure we have a compiler that understands altivec.
 
3267     if [test_compiler_info gcc*] {
 
3268         set compile_flags "additional_flags=-maltivec"
 
3269     } elseif [test_compiler_info xlc*] {
 
3270         set compile_flags "additional_flags=-qaltivec"
 
3272         verbose "Could not compile with altivec support, returning 1" 2
 
3276     # Compile a test program containing VMX instructions.
 
3280             asm volatile ("vor v0,v0,v0");
 
3282             asm volatile ("vor 0,0,0");
 
3287     if {![gdb_simple_compile $me $src executable $compile_flags]} {
 
3291     # Compilation succeeded so now run it via gdb.
 
3295     gdb_reinitialize_dir $srcdir/$subdir
 
3299         -re ".*Illegal instruction.*${gdb_prompt} $" {
 
3300             verbose -log "\n$me altivec hardware not detected" 
 
3301             set skip_vmx_tests 1
 
3303         -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
 
3304             verbose -log "\n$me: altivec hardware detected" 
 
3305             set skip_vmx_tests 0
 
3308           warning "\n$me: default case taken"
 
3309             set skip_vmx_tests 1
 
3313     remote_file build delete $obj
 
3315     verbose "$me:  returning $skip_vmx_tests" 2
 
3316     return $skip_vmx_tests
 
3319 # Run a test on the power target to see if it supports ISA 3.1 instructions
 
3320 gdb_caching_proc skip_power_isa_3_1_tests {
 
3321     global srcdir subdir gdb_prompt inferior_exited_re
 
3323     set me "skip_power_isa_3_1_tests"
 
3325     # Compile a test program containing ISA 3.1 instructions.
 
3328         asm volatile ("pnop"); // marker
 
3329                 asm volatile ("nop");
 
3334     if {![gdb_simple_compile $me $src executable ]} {
 
3338     # No error message, compilation succeeded so now run it via gdb.
 
3342     gdb_reinitialize_dir $srcdir/$subdir
 
3346         -re ".*Illegal instruction.*${gdb_prompt} $" {
 
3347             verbose -log "\n$me Power ISA 3.1 hardware not detected"
 
3348             set skip_power_isa_3_1_tests 1
 
3350         -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
 
3351             verbose -log "\n$me: Power ISA 3.1 hardware detected"
 
3352             set skip_power_isa_3_1_tests 0
 
3355           warning "\n$me: default case taken"
 
3356             set skip_power_isa_3_1_tests 1
 
3360     remote_file build delete $obj
 
3362     verbose "$me:  returning $skip_power_isa_3_1_tests" 2
 
3363     return $skip_power_isa_3_1_tests
 
3366 # Run a test on the target to see if it supports vmx hardware.  Return 0 if so,
 
3367 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
 
3369 gdb_caching_proc skip_vsx_tests {
 
3370     global srcdir subdir gdb_prompt inferior_exited_re
 
3372     set me "skip_vsx_tests"
 
3374     # Some simulators are known to not support Altivec instructions, so
 
3375     # they won't support VSX instructions as well.
 
3376     if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
 
3377         verbose "$me:  target known to not support VSX, returning 1" 2
 
3381     # Make sure we have a compiler that understands altivec.
 
3382     if [test_compiler_info gcc*] {
 
3383         set compile_flags "additional_flags=-mvsx"
 
3384     } elseif [test_compiler_info xlc*] {
 
3385         set compile_flags "additional_flags=-qasm=gcc"
 
3387         verbose "Could not compile with vsx support, returning 1" 2
 
3391     # Compile a test program containing VSX instructions.
 
3394             double a[2] = { 1.0, 2.0 };
 
3396             asm volatile ("lxvd2x v0,v0,%[addr]" : : [addr] "r" (a));
 
3398             asm volatile ("lxvd2x 0,0,%[addr]" : : [addr] "r" (a));
 
3403     if {![gdb_simple_compile $me $src executable $compile_flags]} {
 
3407     # No error message, compilation succeeded so now run it via gdb.
 
3411     gdb_reinitialize_dir $srcdir/$subdir
 
3415         -re ".*Illegal instruction.*${gdb_prompt} $" {
 
3416             verbose -log "\n$me VSX hardware not detected"
 
3417             set skip_vsx_tests 1
 
3419         -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
 
3420             verbose -log "\n$me: VSX hardware detected"
 
3421             set skip_vsx_tests 0
 
3424           warning "\n$me: default case taken"
 
3425             set skip_vsx_tests 1
 
3429     remote_file build delete $obj
 
3431     verbose "$me:  returning $skip_vsx_tests" 2
 
3432     return $skip_vsx_tests
 
3435 # Run a test on the target to see if it supports TSX hardware.  Return 0 if so,
 
3436 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
 
3438 gdb_caching_proc skip_tsx_tests {
 
3439     global srcdir subdir gdb_prompt inferior_exited_re
 
3441     set me "skip_tsx_tests"
 
3443     # Compile a test program.
 
3446             asm volatile ("xbegin .L0");
 
3447             asm volatile ("xend");
 
3448             asm volatile (".L0: nop");
 
3452     if {![gdb_simple_compile $me $src executable]} {
 
3456     # No error message, compilation succeeded so now run it via gdb.
 
3460     gdb_reinitialize_dir $srcdir/$subdir
 
3464         -re ".*Illegal instruction.*${gdb_prompt} $" {
 
3465             verbose -log "$me:  TSX hardware not detected."
 
3466             set skip_tsx_tests 1
 
3468         -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
 
3469             verbose -log "$me:  TSX hardware detected."
 
3470             set skip_tsx_tests 0
 
3473             warning "\n$me:  default case taken."
 
3474             set skip_tsx_tests 1
 
3478     remote_file build delete $obj
 
3480     verbose "$me:  returning $skip_tsx_tests" 2
 
3481     return $skip_tsx_tests
 
3484 # Run a test on the target to see if it supports avx512bf16.  Return 0 if so,
 
3485 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
 
3487 gdb_caching_proc skip_avx512bf16_tests {
 
3488     global srcdir subdir gdb_prompt inferior_exited_re
 
3490     set me "skip_avx512bf16_tests"
 
3491     if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
 
3492         verbose "$me:  target does not support avx512bf16, returning 1" 2
 
3496     # Compile a test program.
 
3499             asm volatile ("vcvtne2ps2bf16 %xmm0, %xmm1, %xmm0");
 
3503     if {![gdb_simple_compile $me $src executable]} {
 
3507     # No error message, compilation succeeded so now run it via gdb.
 
3511     gdb_reinitialize_dir $srcdir/$subdir
 
3515         -re ".*Illegal instruction.*${gdb_prompt} $" {
 
3516             verbose -log "$me:  avx512bf16 hardware not detected."
 
3517             set skip_avx512bf16_tests 1
 
3519         -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
 
3520             verbose -log "$me:  avx512bf16 hardware detected."
 
3521             set skip_avx512bf16_tests 0
 
3524             warning "\n$me:  default case taken."
 
3525             set skip_avx512bf16_tests 1
 
3529     remote_file build delete $obj
 
3531     verbose "$me:  returning $skip_avx512bf16_tests" 2
 
3532     return $skip_avx512bf16_tests
 
3535 # Run a test on the target to see if it supports avx512fp16.  Return 0 if so,
 
3536 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
 
3538 gdb_caching_proc skip_avx512fp16_tests {
 
3539     global srcdir subdir gdb_prompt inferior_exited_re
 
3541     set me "skip_avx512fp16_tests"
 
3542     if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
 
3543         verbose "$me:  target does not support avx512fp16, returning 1" 2
 
3547     # Compile a test program.
 
3550             asm volatile ("vcvtps2phx %xmm1, %xmm0");
 
3554     if {![gdb_simple_compile $me $src executable]} {
 
3558     # No error message, compilation succeeded so now run it via gdb.
 
3562     gdb_reinitialize_dir $srcdir/$subdir
 
3566         -re ".*Illegal instruction.*${gdb_prompt} $" {
 
3567             verbose -log "$me:  avx512fp16 hardware not detected."
 
3568             set skip_avx512fp16_tests 1
 
3570         -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
 
3571             verbose -log "$me:  avx512fp16 hardware detected."
 
3572             set skip_avx512fp16_tests 0
 
3575             warning "\n$me:  default case taken."
 
3576             set skip_avx512fp16_tests 1
 
3580     remote_file build delete $obj
 
3582     verbose "$me:  returning $skip_avx512fp16_tests" 2
 
3583     return $skip_avx512fp16_tests
 
3586 # Run a test on the target to see if it supports btrace hardware.  Return 0 if so,
 
3587 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
 
3589 gdb_caching_proc skip_btrace_tests {
 
3590     global srcdir subdir gdb_prompt inferior_exited_re
 
3592     set me "skip_btrace_tests"
 
3593     if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
 
3594         verbose "$me:  target does not support btrace, returning 1" 2
 
3598     # Compile a test program.
 
3599     set src { int main() { return 0; } }
 
3600     if {![gdb_simple_compile $me $src executable]} {
 
3604     # No error message, compilation succeeded so now run it via gdb.
 
3608     gdb_reinitialize_dir $srcdir/$subdir
 
3613     # In case of an unexpected output, we return 2 as a fail value.
 
3614     set skip_btrace_tests 2
 
3615     gdb_test_multiple "record btrace" "check btrace support" {
 
3616         -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
 
3617             set skip_btrace_tests 1
 
3619         -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
 
3620             set skip_btrace_tests 1
 
3622         -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
 
3623             set skip_btrace_tests 1
 
3625         -re "^record btrace\r\n$gdb_prompt $" {
 
3626             set skip_btrace_tests 0
 
3630     remote_file build delete $obj
 
3632     verbose "$me:  returning $skip_btrace_tests" 2
 
3633     return $skip_btrace_tests
 
3636 # Run a test on the target to see if it supports btrace pt hardware.
 
3637 # Return 0 if so, 1 if it does not.  Based on 'check_vmx_hw_available'
 
3638 # from the GCC testsuite.
 
3640 gdb_caching_proc skip_btrace_pt_tests {
 
3641     global srcdir subdir gdb_prompt inferior_exited_re
 
3643     set me "skip_btrace_tests"
 
3644     if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
 
3645         verbose "$me:  target does not support btrace, returning 1" 2
 
3649     # Compile a test program.
 
3650     set src { int main() { return 0; } }
 
3651     if {![gdb_simple_compile $me $src executable]} {
 
3655     # No error message, compilation succeeded so now run it via gdb.
 
3659     gdb_reinitialize_dir $srcdir/$subdir
 
3664     # In case of an unexpected output, we return 2 as a fail value.
 
3665     set skip_btrace_tests 2
 
3666     gdb_test_multiple "record btrace pt" "check btrace pt support" {
 
3667         -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
 
3668             set skip_btrace_tests 1
 
3670         -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
 
3671             set skip_btrace_tests 1
 
3673         -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
 
3674             set skip_btrace_tests 1
 
3676         -re "support was disabled at compile time.*\r\n$gdb_prompt $" {
 
3677             set skip_btrace_tests 1
 
3679         -re "^record btrace pt\r\n$gdb_prompt $" {
 
3680             set skip_btrace_tests 0
 
3684     remote_file build delete $obj
 
3686     verbose "$me:  returning $skip_btrace_tests" 2
 
3687     return $skip_btrace_tests
 
3690 # Run a test on the target to see if it supports Aarch64 SVE hardware.
 
3691 # Return 0 if so, 1 if it does not.  Note this causes a restart of GDB.
 
3693 gdb_caching_proc skip_aarch64_sve_tests {
 
3694     global srcdir subdir gdb_prompt inferior_exited_re
 
3696     set me "skip_aarch64_sve_tests"
 
3698     if { ![is_aarch64_target]} {
 
3702     set compile_flags "{additional_flags=-march=armv8-a+sve}"
 
3704     # Compile a test program containing SVE instructions.
 
3707             asm volatile ("ptrue p0.b");
 
3711     if {![gdb_simple_compile $me $src executable $compile_flags]} {
 
3715     # Compilation succeeded so now run it via gdb.
 
3719         -re ".*Illegal instruction.*${gdb_prompt} $" {
 
3720             verbose -log "\n$me sve hardware not detected"
 
3721             set skip_sve_tests 1
 
3723         -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
 
3724             verbose -log "\n$me: sve hardware detected"
 
3725             set skip_sve_tests 0
 
3728           warning "\n$me: default case taken"
 
3729             set skip_sve_tests 1
 
3733     remote_file build delete $obj
 
3735     verbose "$me:  returning $skip_sve_tests" 2
 
3736     return $skip_sve_tests
 
3740 # A helper that compiles a test case to see if __int128 is supported.
 
3741 proc gdb_int128_helper {lang} {
 
3742     return [gdb_can_simple_compile "i128-for-$lang" {
 
3744         int main() { return 0; }
 
3748 # Return true if the C compiler understands the __int128 type.
 
3749 gdb_caching_proc has_int128_c {
 
3750     return [gdb_int128_helper c]
 
3753 # Return true if the C++ compiler understands the __int128 type.
 
3754 gdb_caching_proc has_int128_cxx {
 
3755     return [gdb_int128_helper c++]
 
3758 # Return true if the IFUNC feature is unsupported.
 
3759 gdb_caching_proc skip_ifunc_tests {
 
3760     if [gdb_can_simple_compile ifunc {
 
3762         typedef void F (void);
 
3763         F* g (void) { return &f_; }
 
3764         void f () __attribute__ ((ifunc ("g")));
 
3772 # Return whether we should skip tests for showing inlined functions in
 
3773 # backtraces.  Requires get_compiler_info and get_debug_format.
 
3775 proc skip_inline_frame_tests {} {
 
3776     # GDB only recognizes inlining information in DWARF.
 
3777     if { ! [test_debug_format "DWARF \[0-9\]"] } {
 
3781     # GCC before 4.1 does not emit DW_AT_call_file / DW_AT_call_line.
 
3782     if { ([test_compiler_info "gcc-2-*"]
 
3783           || [test_compiler_info "gcc-3-*"]
 
3784           || [test_compiler_info "gcc-4-0-*"]) } {
 
3791 # Return whether we should skip tests for showing variables from
 
3792 # inlined functions.  Requires get_compiler_info and get_debug_format.
 
3794 proc skip_inline_var_tests {} {
 
3795     # GDB only recognizes inlining information in DWARF.
 
3796     if { ! [test_debug_format "DWARF \[0-9\]"] } {
 
3803 # Return a 1 if we should skip tests that require hardware breakpoints
 
3805 proc skip_hw_breakpoint_tests {} {
 
3806     # Skip tests if requested by the board (note that no_hardware_watchpoints
 
3807     # disables both watchpoints and breakpoints)
 
3808     if { [target_info exists gdb,no_hardware_watchpoints]} {
 
3812     # These targets support hardware breakpoints natively
 
3813     if { [istarget "i?86-*-*"] 
 
3814          || [istarget "x86_64-*-*"]
 
3815          || [istarget "ia64-*-*"] 
 
3816          || [istarget "arm*-*-*"]
 
3817          || [istarget "aarch64*-*-*"]
 
3818          || [istarget "s390*-*-*"] } {
 
3825 # Return a 1 if we should skip tests that require hardware watchpoints
 
3827 proc skip_hw_watchpoint_tests {} {
 
3828     # Skip tests if requested by the board
 
3829     if { [target_info exists gdb,no_hardware_watchpoints]} {
 
3833     # These targets support hardware watchpoints natively
 
3834     # Note, not all Power 9 processors support hardware watchpoints due to a HW
 
3835     # bug.  Use has_hw_wp_support to check do a runtime check for hardware
 
3836     # watchpoint support on Powerpc.
 
3837     if { [istarget "i?86-*-*"] 
 
3838          || [istarget "x86_64-*-*"]
 
3839          || [istarget "ia64-*-*"] 
 
3840          || [istarget "arm*-*-*"]
 
3841          || [istarget "aarch64*-*-*"]
 
3842          || ([istarget "powerpc*-*-linux*"] && [has_hw_wp_support])
 
3843          || [istarget "s390*-*-*"] } {
 
3850 # Return a 1 if we should skip tests that require *multiple* hardware
 
3851 # watchpoints to be active at the same time
 
3853 proc skip_hw_watchpoint_multi_tests {} {
 
3854     if { [skip_hw_watchpoint_tests] } {
 
3858     # These targets support just a single hardware watchpoint
 
3859     if { [istarget "arm*-*-*"]
 
3860          || [istarget "powerpc*-*-linux*"] } {
 
3867 # Return a 1 if we should skip tests that require read/access watchpoints
 
3869 proc skip_hw_watchpoint_access_tests {} {
 
3870     if { [skip_hw_watchpoint_tests] } {
 
3874     # These targets support just write watchpoints
 
3875     if { [istarget "s390*-*-*"] } {
 
3882 # Return 1 if we should skip tests that require the runtime unwinder
 
3883 # hook.  This must be invoked while gdb is running, after shared
 
3884 # libraries have been loaded.  This is needed because otherwise a
 
3885 # shared libgcc won't be visible.
 
3887 proc skip_unwinder_tests {} {
 
3891     gdb_test_multiple "print _Unwind_DebugHook" "check for unwinder hook" {
 
3892         -re "= .*no debug info.*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
 
3894         -re "= .*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
 
3897         -re "No symbol .* in current context.\r\n$gdb_prompt $" {
 
3901         gdb_test_multiple "info probe" "check for stap probe in unwinder" {
 
3902             -re ".*libgcc.*unwind.*\r\n$gdb_prompt $" {
 
3905             -re "\r\n$gdb_prompt $" {
 
3912 # Return 1 if we should skip tests that require the libstdc++ stap
 
3913 # probes.  This must be invoked while gdb is running, after shared
 
3914 # libraries have been loaded.  PROMPT_REGEXP is the expected prompt.
 
3916 proc skip_libstdcxx_probe_tests_prompt { prompt_regexp } {
 
3918     gdb_test_multiple "info probe" "check for stap probe in libstdc++" \
 
3919         -prompt "$prompt_regexp" {
 
3920             -re ".*libstdcxx.*catch.*\r\n$prompt_regexp" {
 
3923             -re "\r\n$prompt_regexp" {
 
3926     set skip [expr !$supported]
 
3930 # As skip_libstdcxx_probe_tests_prompt, with gdb_prompt.
 
3932 proc skip_libstdcxx_probe_tests {} {
 
3934     return [skip_libstdcxx_probe_tests_prompt "$gdb_prompt $"]
 
3937 # Return 1 if we should skip tests of the "compile" feature.
 
3938 # This must be invoked after the inferior has been started.
 
3940 proc skip_compile_feature_tests {} {
 
3944     gdb_test_multiple "compile code -- ;" "check for working compile command" {
 
3945         "Could not load libcc1.*\r\n$gdb_prompt $" {
 
3948         -re "Command not supported on this host\\..*\r\n$gdb_prompt $" {
 
3951         -re "\r\n$gdb_prompt $" {
 
3957 # Helper for gdb_is_target_* procs.  TARGET_NAME is the name of the target
 
3958 # we're looking for (used to build the test name).  TARGET_STACK_REGEXP
 
3959 # is a regexp that will match the output of "maint print target-stack" if
 
3960 # the target in question is currently pushed.  PROMPT_REGEXP is a regexp
 
3961 # matching the expected prompt after the command output.
 
3963 # NOTE: GDB must be running BEFORE this procedure is called!
 
3965 proc gdb_is_target_1 { target_name target_stack_regexp prompt_regexp } {
 
3968     # Throw a Tcl error if gdb isn't already started.
 
3969     if {![info exists gdb_spawn_id]} {
 
3970         error "gdb_is_target_1 called with no running gdb instance"
 
3973     set test "probe for target ${target_name}"
 
3974     gdb_test_multiple "maint print target-stack" $test \
 
3975         -prompt "$prompt_regexp" {
 
3976             -re "${target_stack_regexp}${prompt_regexp}" {
 
3980             -re "$prompt_regexp" {
 
3987 # Helper for gdb_is_target_remote where the expected prompt is variable.
 
3989 # NOTE: GDB must be running BEFORE this procedure is called!
 
3991 proc gdb_is_target_remote_prompt { prompt_regexp } {
 
3992     return [gdb_is_target_1 "remote" ".*emote target using gdb-specific protocol.*" $prompt_regexp]
 
3995 # Check whether we're testing with the remote or extended-remote
 
3998 # NOTE: GDB must be running BEFORE this procedure is called!
 
4000 proc gdb_is_target_remote { } {
 
4003     return [gdb_is_target_remote_prompt "$gdb_prompt $"]
 
4006 # Check whether we're testing with the native target.
 
4008 # NOTE: GDB must be running BEFORE this procedure is called!
 
4010 proc gdb_is_target_native { } {
 
4013     return [gdb_is_target_1 "native" ".*native \\(Native process\\).*" "$gdb_prompt $"]
 
4016 # Return the effective value of use_gdb_stub.
 
4018 # If the use_gdb_stub global has been set (it is set when the gdb process is
 
4019 # spawned), return that.  Otherwise, return the value of the use_gdb_stub
 
4020 # property from the board file.
 
4022 # This is the preferred way of checking use_gdb_stub, since it allows to check
 
4023 # the value before the gdb has been spawned and it will return the correct value
 
4024 # even when it was overriden by the test.
 
4026 # Note that stub targets are not able to spawn new inferiors.  Use this
 
4027 # check for skipping respective tests.
 
4029 proc use_gdb_stub {} {
 
4032   if [info exists use_gdb_stub] {
 
4033      return $use_gdb_stub
 
4036   return [target_info exists use_gdb_stub]
 
4039 # Return 1 if the current remote target is an instance of our GDBserver, 0
 
4040 # otherwise.  Return -1 if there was an error and we can't tell.
 
4042 gdb_caching_proc target_is_gdbserver {
 
4046     set test "probing for GDBserver"
 
4048     gdb_test_multiple "monitor help" $test {
 
4049         -re "The following monitor commands are supported.*Quit GDBserver.*$gdb_prompt $" {
 
4052         -re "$gdb_prompt $" {
 
4057     if { $is_gdbserver == -1 } {
 
4058         verbose -log "Unable to tell whether we are using GDBserver or not."
 
4061     return $is_gdbserver
 
4064 # N.B. compiler_info is intended to be local to this file.
 
4065 # Call test_compiler_info with no arguments to fetch its value.
 
4066 # Yes, this is counterintuitive when there's get_compiler_info,
 
4067 # but that's the current API.
 
4068 if [info exists compiler_info] {
 
4072 # Figure out what compiler I am using.
 
4073 # The result is cached so only the first invocation runs the compiler.
 
4075 # ARG can be empty or "C++".  If empty, "C" is assumed.
 
4077 # There are several ways to do this, with various problems.
 
4079 # [ gdb_compile -E $ifile -o $binfile.ci ]
 
4080 # source $binfile.ci
 
4082 #   Single Unix Spec v3 says that "-E -o ..." together are not
 
4083 #   specified.  And in fact, the native compiler on hp-ux 11 (among
 
4084 #   others) does not work with "-E -o ...".  Most targets used to do
 
4085 #   this, and it mostly worked, because it works with gcc.
 
4087 # [ catch "exec $compiler -E $ifile > $binfile.ci" exec_output ]
 
4088 # source $binfile.ci
 
4090 #   This avoids the problem with -E and -o together.  This almost works
 
4091 #   if the build machine is the same as the host machine, which is
 
4092 #   usually true of the targets which are not gcc.  But this code does
 
4093 #   not figure which compiler to call, and it always ends up using the C
 
4094 #   compiler.  Not good for setting hp_aCC_compiler.  Target
 
4095 #   hppa*-*-hpux* used to do this.
 
4097 # [ gdb_compile -E $ifile > $binfile.ci ]
 
4098 # source $binfile.ci
 
4100 #   dejagnu target_compile says that it supports output redirection,
 
4101 #   but the code is completely different from the normal path and I
 
4102 #   don't want to sweep the mines from that path.  So I didn't even try
 
4105 # set cppout [ gdb_compile $ifile "" preprocess $args quiet ]
 
4108 #   I actually do this for all targets now.  gdb_compile runs the right
 
4109 #   compiler, and TCL captures the output, and I eval the output.
 
4111 #   Unfortunately, expect logs the output of the command as it goes by,
 
4112 #   and dejagnu helpfully prints a second copy of it right afterwards.
 
4113 #   So I turn off expect logging for a moment.
 
4115 # [ gdb_compile $ifile $ciexe_file executable $args ]
 
4116 # [ remote_exec $ciexe_file ]
 
4117 # [ source $ci_file.out ]
 
4119 #   I could give up on -E and just do this.
 
4120 #   I didn't get desperate enough to try this.
 
4122 # -- chastain 2004-01-06
 
4124 proc get_compiler_info {{language "c"}} {
 
4126     # For compiler.c, compiler.cc and compiler.F90.
 
4129     # I am going to play with the log to keep noise out.
 
4133     # These come from compiler.c, compiler.cc or compiler.F90.
 
4134     gdb_persistent_global compiler_info_cache
 
4136     if [info exists compiler_info_cache($language)] {
 
4141     # Choose which file to preprocess.
 
4142     if { $language == "c++" } {
 
4143         set ifile "${srcdir}/lib/compiler.cc"
 
4144     } elseif { $language == "f90" } {
 
4145         set ifile "${srcdir}/lib/compiler.F90"
 
4146     } elseif { $language == "c" } {
 
4147         set ifile "${srcdir}/lib/compiler.c"
 
4149         perror "Unable to fetch compiler version for language: $language"
 
4153     # Run $ifile through the right preprocessor.
 
4154     # Toggle gdb.log to keep the compiler output out of the log.
 
4155     set saved_log [log_file -info]
 
4157     if [is_remote host] {
 
4158         # We have to use -E and -o together, despite the comments
 
4159         # above, because of how DejaGnu handles remote host testing.
 
4160         set ppout "$outdir/compiler.i"
 
4161         gdb_compile "${ifile}" "$ppout" preprocess [list "$language" quiet getting_compiler_info]
 
4162         set file [open $ppout r]
 
4163         set cppout [read $file]
 
4166         # Copy $ifile to temp dir, to work around PR gcc/60447.  This will leave the
 
4167         # superfluous .s file in the temp dir instead of in the source dir.
 
4168         set tofile [file tail $ifile]
 
4169         set tofile [standard_temp_file $tofile]
 
4170         file copy -force $ifile $tofile
 
4172         set cppout [ gdb_compile "${ifile}" "" preprocess [list "$language" quiet getting_compiler_info] ]
 
4174     eval log_file $saved_log
 
4178     foreach cppline [ split "$cppout" "\n" ] {
 
4179         if { [ regexp "^#" "$cppline" ] } {
 
4181         } elseif { [ regexp "^\[\n\r\t \]*$" "$cppline" ] } {
 
4183         } elseif { [ regexp "^\[\n\r\t \]*set\[\n\r\t \]" "$cppline" ] } {
 
4185             verbose "get_compiler_info: $cppline" 2
 
4187         } elseif { [ regexp "flang.*warning.*'-fdiagnostics-color=never'" "$cppline"] } {
 
4188             # Both flang preprocessors (llvm flang and classic flang) print a
 
4189             # warning for the unused -fdiagnostics-color=never, so we skip this
 
4193             verbose -log "get_compiler_info: $cppline"
 
4198     # Set to unknown if for some reason compiler_info didn't get defined.
 
4199     if ![info exists compiler_info] {
 
4200         verbose -log "get_compiler_info: compiler_info not provided"
 
4201         set compiler_info "unknown"
 
4203     # Also set to unknown compiler if any diagnostics happened.
 
4205         verbose -log "get_compiler_info: got unexpected diagnostics"
 
4206         set compiler_info "unknown"
 
4209     set compiler_info_cache($language) $compiler_info
 
4211     # Log what happened.
 
4212     verbose -log "get_compiler_info: $compiler_info"
 
4217 # Return the compiler_info string if no arg is provided.
 
4218 # Otherwise the argument is a glob-style expression to match against
 
4221 proc test_compiler_info { {compiler ""} {language "c"} } {
 
4222     gdb_persistent_global compiler_info_cache
 
4224     if [get_compiler_info $language] {
 
4225         # An error will already have been printed in this case.  Just
 
4226         # return a suitable result depending on how the user called
 
4228         if [string match "" $compiler] {
 
4235     # If no arg, return the compiler_info string.
 
4236     if [string match "" $compiler] {
 
4237         return $compiler_info_cache($language)
 
4240     return [string match $compiler $compiler_info_cache($language)]
 
4243 # Return true if the C compiler is GCC, otherwise, return false.
 
4245 proc is_c_compiler_gcc {} {
 
4246     set compiler_info [test_compiler_info]
 
4247     set gcc_compiled false
 
4248     regexp "^gcc-(\[0-9\]+)-" "$compiler_info" matchall gcc_compiled
 
4249     return $gcc_compiled
 
4252 # Return the gcc major version, or -1.
 
4253 # For gcc 4.8.5, the major version is 4.8.
 
4254 # For gcc 7.5.0, the major version 7.
 
4255 # The COMPILER and LANGUAGE arguments are as for test_compiler_info.
 
4257 proc gcc_major_version { {compiler "gcc-*"} {language "c"} } {
 
4259     if { ![test_compiler_info $compiler $language] } {
 
4262     # Strip "gcc-*" to "gcc".
 
4263     regsub -- {-.*} $compiler "" compiler
 
4264     set res [regexp $compiler-($decimal)-($decimal)- \
 
4265                  [test_compiler_info "" $language] \
 
4266                  dummy_var major minor]
 
4273     return $major.$minor
 
4276 proc current_target_name { } {
 
4278     if [info exists target_info(target,name)] {
 
4279         set answer $target_info(target,name)
 
4286 set gdb_wrapper_initialized 0
 
4287 set gdb_wrapper_target ""
 
4288 set gdb_wrapper_file ""
 
4289 set gdb_wrapper_flags ""
 
4291 proc gdb_wrapper_init { args } {
 
4292     global gdb_wrapper_initialized
 
4293     global gdb_wrapper_file
 
4294     global gdb_wrapper_flags
 
4295     global gdb_wrapper_target
 
4297     if { $gdb_wrapper_initialized == 1 } { return; }
 
4299     if {[target_info exists needs_status_wrapper] && \
 
4300             [target_info needs_status_wrapper] != "0"} {
 
4301         set result [build_wrapper "testglue.o"]
 
4302         if { $result != "" } {
 
4303             set gdb_wrapper_file [lindex $result 0]
 
4304             if ![is_remote host] {
 
4305                 set gdb_wrapper_file [file join [pwd] $gdb_wrapper_file]
 
4307             set gdb_wrapper_flags [lindex $result 1]
 
4309             warning "Status wrapper failed to build."
 
4312         set gdb_wrapper_file ""
 
4313         set gdb_wrapper_flags ""
 
4315     verbose "set gdb_wrapper_file = $gdb_wrapper_file"
 
4316     set gdb_wrapper_initialized 1
 
4317     set gdb_wrapper_target [current_target_name]
 
4320 # Determine options that we always want to pass to the compiler.
 
4321 gdb_caching_proc universal_compile_options {
 
4322     set me "universal_compile_options"
 
4325     set src [standard_temp_file ccopts[pid].c]
 
4326     set obj [standard_temp_file ccopts[pid].o]
 
4328     gdb_produce_source $src {
 
4329         int foo(void) { return 0; }
 
4332     # Try an option for disabling colored diagnostics.  Some compilers
 
4333     # yield colored diagnostics by default (when run from a tty) unless
 
4334     # such an option is specified.
 
4335     set opt "additional_flags=-fdiagnostics-color=never"
 
4336     set lines [target_compile $src $obj object [list "quiet" $opt]]
 
4337     if [string match "" $lines] then {
 
4338         # Seems to have worked; use the option.
 
4339         lappend options $opt
 
4344     verbose "$me:  returning $options" 2
 
4348 # Compile the code in $code to a file based on $name, using the flags
 
4349 # $compile_flag as well as debug, nowarning and quiet.
 
4350 # Return 1 if code can be compiled
 
4351 # Leave the file name of the resulting object in the upvar object.
 
4353 proc gdb_simple_compile {name code {type object} {compile_flags {}} {object obj}} {
 
4356     switch -regexp -- $type {
 
4371     foreach flag $compile_flags {
 
4372         if { "$flag" == "go" } {
 
4377     set src [standard_temp_file $name-[pid].$ext]
 
4378     set obj [standard_temp_file $name-[pid].$postfix]
 
4379     set compile_flags [concat $compile_flags {debug nowarnings quiet}]
 
4381     gdb_produce_source $src $code
 
4383     verbose "$name:  compiling testfile $src" 2
 
4384     set lines [gdb_compile $src $obj $type $compile_flags]
 
4388     if ![string match "" $lines] then {
 
4389         verbose "$name:  compilation failed, returning 0" 2
 
4395 # Compile the code in $code to a file based on $name, using the flags
 
4396 # $compile_flag as well as debug, nowarning and quiet.
 
4397 # Return 1 if code can be compiled
 
4398 # Delete all created files and objects.
 
4400 proc gdb_can_simple_compile {name code {type object} {compile_flags ""}} {
 
4401     set ret [gdb_simple_compile $name $code $type $compile_flags temp_obj]
 
4402     file delete $temp_obj
 
4406 # Some targets need to always link a special object in.  Save its path here.
 
4407 global gdb_saved_set_unbuffered_mode_obj
 
4408 set gdb_saved_set_unbuffered_mode_obj ""
 
4410 # Compile source files specified by SOURCE into a binary of type TYPE at path
 
4411 # DEST.  gdb_compile is implemented using DejaGnu's target_compile, so the type
 
4412 # parameter and most options are passed directly to it.
 
4414 # The type can be one of the following:
 
4416 #   - object: Compile into an object file.
 
4417 #   - executable: Compile and link into an executable.
 
4418 #   - preprocess: Preprocess the source files.
 
4419 #   - assembly: Generate assembly listing.
 
4421 # The following options are understood and processed by gdb_compile:
 
4423 #   - shlib=so_path: Add SO_PATH to the sources, and enable some target-specific
 
4424 #     quirks to be able to use shared libraries.
 
4425 #   - shlib_load: Link with appropriate libraries to allow the test to
 
4426 #     dynamically load libraries at runtime.  For example, on Linux, this adds
 
4427 #     -ldl so that the test can use dlopen.
 
4428 #   - nowarnings:  Inhibit all compiler warnings.
 
4429 #   - pie: Force creation of PIE executables.
 
4430 #   - nopie: Prevent creation of PIE executables.
 
4431 #   - macros: Add the required compiler flag to include macro information in
 
4433 #   - text_segment=addr: Tell the linker to place the text segment at ADDR.
 
4435 # And here are some of the not too obscure options understood by DejaGnu that
 
4436 # influence the compilation:
 
4438 #   - additional_flags=flag: Add FLAG to the compiler flags.
 
4439 #   - libs=library: Add LIBRARY to the libraries passed to the linker.  The
 
4440 #     argument can be a file, in which case it's added to the sources, or a
 
4442 #   - ldflags=flag: Add FLAG to the linker flags.
 
4443 #   - incdir=path: Add PATH to the searched include directories.
 
4444 #   - libdir=path: Add PATH to the linker searched directories.
 
4445 #   - ada, c++, f90, go, rust: Compile the file as Ada, C++,
 
4446 #     Fortran 90, Go or Rust.
 
4447 #   - debug: Build with debug information.
 
4448 #   - optimize: Build with optimization.
 
4450 proc gdb_compile {source dest type options} {
 
4451     global GDB_TESTCASE_OPTIONS
 
4452     global gdb_wrapper_file
 
4453     global gdb_wrapper_flags
 
4456     global gdb_saved_set_unbuffered_mode_obj
 
4458     set outdir [file dirname $dest]
 
4460     # If this is set, calling test_compiler_info will cause recursion.
 
4461     if { [lsearch -exact $options getting_compiler_info] == -1 } {
 
4462         set getting_compiler_info false
 
4464         set getting_compiler_info true
 
4467     # Add platform-specific options if a shared library was specified using
 
4468     # "shlib=librarypath" in OPTIONS.
 
4470     if {[lsearch -exact $options rust] != -1} {
 
4471         # -fdiagnostics-color is not a rustcc option.
 
4473         set new_options [universal_compile_options]
 
4476     # Some C/C++ testcases unconditionally pass -Wno-foo as additional
 
4477     # options to disable some warning.  That is OK with GCC, because
 
4478     # by design, GCC accepts any -Wno-foo option, even if it doesn't
 
4479     # support -Wfoo.  Clang however warns about unknown -Wno-foo by
 
4480     # default, unless you pass -Wno-unknown-warning-option as well.
 
4481     # We do that here, so that individual testcases don't have to
 
4483     if {!$getting_compiler_info
 
4484         && [lsearch -exact $options rust] == -1
 
4485         && [lsearch -exact $options ada] == -1
 
4486         && [lsearch -exact $options f90] == -1
 
4487         && [lsearch -exact $options go] == -1} {
 
4488         if {[test_compiler_info "clang-*"] || [test_compiler_info "icx-*"]} {
 
4489             lappend new_options "additional_flags=-Wno-unknown-warning-option"
 
4490         } elseif {[test_compiler_info "icc-*"]} {
 
4491             # This is the equivalent for the icc compiler.
 
4492             lappend new_options "additional_flags=-diag-disable=10148"
 
4496     # Treating .c input files as C++ is deprecated in Clang, so
 
4497     # explicitly force C++ language.
 
4498     if { !$getting_compiler_info
 
4499          && [lsearch -exact $options c++] != -1
 
4500          && [string match *.c $source] != 0 } {
 
4502         # gdb_compile cannot handle this combination of options, the
 
4503         # result is a command like "clang -x c++ foo.c bar.so -o baz"
 
4504         # which tells Clang to treat bar.so as C++.  The solution is
 
4505         # to call gdb_compile twice--once to compile, once to link--
 
4506         # either directly, or via build_executable_from_specs.
 
4507         if { [lsearch $options shlib=*] != -1 } {
 
4508             error "incompatible gdb_compile options"
 
4511         if {[test_compiler_info "clang-*"]} {
 
4512             lappend new_options early_flags=-x\ c++
 
4516     # Place (and look for) Fortran `.mod` files in the output
 
4517     # directory for this specific test.  For Intel compilers the -J
 
4518     # option is not supported so instead use the -module flag.
 
4519     # Additionally, Intel compilers need the -debug-parameters flag set to
 
4520     # emit debug info for all parameters in modules.
 
4521     if { !$getting_compiler_info && [lsearch -exact $options f90] != -1 } {
 
4523         set mod_path [standard_output_file ""]
 
4524         if { [test_compiler_info {gfortran-*} f90] } {
 
4525             lappend new_options "additional_flags=-J${mod_path}"
 
4526         } elseif { [test_compiler_info {ifort-*} f90]
 
4527                    || [test_compiler_info {ifx-*} f90] } {
 
4528             lappend new_options "additional_flags=-module ${mod_path}"
 
4529             lappend new_options "additional_flags=-debug-parameters all"
 
4535     foreach opt $options {
 
4536         if {[regexp {^shlib=(.*)} $opt dummy_var shlib_name]
 
4537             && $type == "executable"} {
 
4538             if [test_compiler_info "xlc-*"] {
 
4539                 # IBM xlc compiler doesn't accept shared library named other
 
4540                 # than .so: use "-Wl," to bypass this
 
4541                 lappend source "-Wl,$shlib_name"
 
4542             } elseif { ([istarget "*-*-mingw*"]
 
4543                         || [istarget *-*-cygwin*]
 
4544                         || [istarget *-*-pe*])} {
 
4545                 lappend source "${shlib_name}.a"
 
4547                lappend source $shlib_name
 
4549             if { $shlib_found == 0 } {
 
4551                 if { ([istarget "*-*-mingw*"]
 
4552                       || [istarget *-*-cygwin*]) } {
 
4553                     lappend new_options "additional_flags=-Wl,--enable-auto-import"
 
4555                 if { [test_compiler_info "gcc-*"] || [test_compiler_info "clang-*"] } {
 
4556                     # Undo debian's change in the default.
 
4557                     # Put it at the front to not override any user-provided
 
4558                     # value, and to make sure it appears in front of all the
 
4560                     lappend new_options "early_flags=-Wl,--no-as-needed"
 
4563         } elseif { $opt == "shlib_load" && $type == "executable" } {
 
4565         } elseif { $opt == "getting_compiler_info" } {
 
4566             # Ignore this setting here as it has been handled earlier in this
 
4567             # procedure.  Do not append it to new_options as this will cause
 
4569         } elseif {[regexp "^text_segment=(.*)" $opt dummy_var addr]} {
 
4570             if { [linker_supports_Ttext_segment_flag] } {
 
4572                 lappend new_options "ldflags=-Wl,-Ttext-segment=$addr"
 
4573             } elseif { [linker_supports_image_base_flag] } {
 
4575                 lappend new_options "ldflags=-Wl,--image-base=$addr"
 
4576             } elseif { [linker_supports_Ttext_flag] } {
 
4577                 # For old GNU gold versions.
 
4578                 lappend new_options "ldflags=-Wl,-Ttext=$addr"
 
4580                 error "Don't know how to handle text_segment option."
 
4583             lappend new_options $opt
 
4587     # Ensure stack protector is disabled for GCC, as this causes problems with
 
4588     # DWARF line numbering.
 
4589     # See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88432
 
4590     # This option defaults to on for Debian/Ubuntu.
 
4591     if { !$getting_compiler_info
 
4592          && [test_compiler_info {gcc-*-*}]
 
4593          && !([test_compiler_info {gcc-[0-3]-*}]
 
4594               || [test_compiler_info {gcc-4-0-*}])
 
4595          && [lsearch -exact $options rust] == -1} {
 
4596         # Put it at the front to not override any user-provided value.
 
4597         lappend new_options "early_flags=-fno-stack-protector"
 
4600     # Because we link with libraries using their basename, we may need
 
4601     # (depending on the platform) to set a special rpath value, to allow
 
4602     # the executable to find the libraries it depends on.
 
4603     if { $shlib_load || $shlib_found } {
 
4604         if { ([istarget "*-*-mingw*"]
 
4605               || [istarget *-*-cygwin*]
 
4606               || [istarget *-*-pe*]) } {
 
4607             # Do not need anything.
 
4608         } elseif { [istarget *-*-freebsd*] || [istarget *-*-openbsd*] } {
 
4609             lappend new_options "ldflags=-Wl,-rpath,${outdir}"
 
4611             if { $shlib_load } {
 
4612                 lappend new_options "libs=-ldl"
 
4614             lappend new_options "ldflags=-Wl,-rpath,\\\$ORIGIN"
 
4617     set options $new_options
 
4619     if [info exists GDB_TESTCASE_OPTIONS] {
 
4620         lappend options "additional_flags=$GDB_TESTCASE_OPTIONS"
 
4622     verbose "options are $options"
 
4623     verbose "source is $source $dest $type $options"
 
4627     if {[target_info exists needs_status_wrapper] && \
 
4628             [target_info needs_status_wrapper] != "0" && \
 
4629             $gdb_wrapper_file != "" } {
 
4630         lappend options "libs=${gdb_wrapper_file}"
 
4631         lappend options "ldflags=${gdb_wrapper_flags}"
 
4634     # Replace the "nowarnings" option with the appropriate additional_flags
 
4635     # to disable compiler warnings.
 
4636     set nowarnings [lsearch -exact $options nowarnings]
 
4637     if {$nowarnings != -1} {
 
4638         if [target_info exists gdb,nowarnings_flag] {
 
4639             set flag "additional_flags=[target_info gdb,nowarnings_flag]"
 
4641             set flag "additional_flags=-w"
 
4643         set options [lreplace $options $nowarnings $nowarnings $flag]
 
4646     # Replace the "pie" option with the appropriate compiler and linker flags
 
4647     # to enable PIE executables.
 
4648     set pie [lsearch -exact $options pie]
 
4650         if [target_info exists gdb,pie_flag] {
 
4651             set flag "additional_flags=[target_info gdb,pie_flag]"
 
4653             # For safety, use fPIE rather than fpie. On AArch64, m68k, PowerPC
 
4654             # and SPARC, fpie can cause compile errors due to the GOT exceeding
 
4655             # a maximum size.  On other architectures the two flags are
 
4656             # identical (see the GCC manual). Note Debian9 and Ubuntu16.10
 
4657             # onwards default GCC to using fPIE.  If you do require fpie, then
 
4658             # it can be set using the pie_flag.
 
4659             set flag "additional_flags=-fPIE"
 
4661         set options [lreplace $options $pie $pie $flag]
 
4663         if [target_info exists gdb,pie_ldflag] {
 
4664             set flag "ldflags=[target_info gdb,pie_ldflag]"
 
4666             set flag "ldflags=-pie"
 
4668         lappend options "$flag"
 
4671     # Replace the "nopie" option with the appropriate compiler and linker
 
4672     # flags to disable PIE executables.
 
4673     set nopie [lsearch -exact $options nopie]
 
4675         if [target_info exists gdb,nopie_flag] {
 
4676             set flag "additional_flags=[target_info gdb,nopie_flag]"
 
4678             set flag "additional_flags=-fno-pie"
 
4680         set options [lreplace $options $nopie $nopie $flag]
 
4682         if [target_info exists gdb,nopie_ldflag] {
 
4683             set flag "ldflags=[target_info gdb,nopie_ldflag]"
 
4685             set flag "ldflags=-no-pie"
 
4687         lappend options "$flag"
 
4690   set macros [lsearch -exact $options macros]
 
4691   if {$macros != -1} {
 
4692       if { [test_compiler_info "clang-*"] } {
 
4693           set flag "additional_flags=-fdebug-macro"
 
4695           set flag "additional_flags=-g3"
 
4698       set options [lreplace $options $macros $macros $flag]
 
4701     if { $type == "executable" } {
 
4702         if { ([istarget "*-*-mingw*"]
 
4703               || [istarget "*-*-*djgpp"]
 
4704               || [istarget "*-*-cygwin*"])} {
 
4705             # Force output to unbuffered mode, by linking in an object file
 
4706             # with a global contructor that calls setvbuf.
 
4708             # Compile the special object separately for two reasons:
 
4709             #  1) Insulate it from $options.
 
4710             #  2) Avoid compiling it for every gdb_compile invocation,
 
4711             #  which is time consuming, especially if we're remote
 
4714             if { $gdb_saved_set_unbuffered_mode_obj == "" } {
 
4715                 verbose "compiling gdb_saved_set_unbuffered_obj"
 
4716                 set unbuf_src ${srcdir}/lib/set_unbuffered_mode.c
 
4717                 set unbuf_obj ${objdir}/set_unbuffered_mode.o
 
4719                 set result [gdb_compile "${unbuf_src}" "${unbuf_obj}" object {nowarnings}]
 
4720                 if { $result != "" } {
 
4723                 if {[is_remote host]} {
 
4724                     set gdb_saved_set_unbuffered_mode_obj set_unbuffered_mode_saved.o
 
4726                     set gdb_saved_set_unbuffered_mode_obj ${objdir}/set_unbuffered_mode_saved.o
 
4728                 # Link a copy of the output object, because the
 
4729                 # original may be automatically deleted.
 
4730                 remote_download host $unbuf_obj $gdb_saved_set_unbuffered_mode_obj
 
4732                 verbose "gdb_saved_set_unbuffered_obj already compiled"
 
4735             # Rely on the internal knowledge that the global ctors are ran in
 
4736             # reverse link order.  In that case, we can use ldflags to
 
4737             # avoid copying the object file to the host multiple
 
4739             # This object can only be added if standard libraries are
 
4740             # used. Thus, we need to disable it if -nostdlib option is used
 
4741             if {[lsearch -regexp $options "-nostdlib"] < 0 } {
 
4742                 lappend options "ldflags=$gdb_saved_set_unbuffered_mode_obj"
 
4747     set result [target_compile $source $dest $type $options]
 
4749     # Prune uninteresting compiler (and linker) output.
 
4750     regsub "Creating library file: \[^\r\n\]*\[\r\n\]+" $result "" result
 
4752     regsub "\[\r\n\]*$" "$result" "" result
 
4753     regsub "^\[\r\n\]*" "$result" "" result
 
4755     if { $type == "executable" && $result == "" \
 
4756              && ($nopie != -1 || $pie != -1) } {
 
4757         set is_pie [exec_is_pie "$dest"]
 
4758         if { $nopie != -1 && $is_pie == 1 } {
 
4759             set result "nopie failed to prevent PIE executable"
 
4760         } elseif { $pie != -1 && $is_pie == 0 } {
 
4761             set result "pie failed to generate PIE executable"
 
4765     if {[lsearch $options quiet] < 0} {
 
4766         if { $result != "" } {
 
4767             clone_output "gdb compile failed, $result"
 
4774 # This is just like gdb_compile, above, except that it tries compiling
 
4775 # against several different thread libraries, to see which one this
 
4777 proc gdb_compile_pthreads {source dest type options} {
 
4778     if {$type != "executable"} {
 
4779         return [gdb_compile $source $dest $type $options]
 
4782     set why_msg "unrecognized error"
 
4783     foreach lib {-lpthreads -lpthread -lthread ""} {
 
4784         # This kind of wipes out whatever libs the caller may have
 
4785         # set.  Or maybe theirs will override ours.  How infelicitous.
 
4786         set options_with_lib [concat $options [list libs=$lib quiet]]
 
4787         set ccout [gdb_compile $source $dest $type $options_with_lib]
 
4788         switch -regexp -- $ccout {
 
4789             ".*no posix threads support.*" {
 
4790                 set why_msg "missing threads include file"
 
4793             ".*cannot open -lpthread.*" {
 
4794                 set why_msg "missing runtime threads library"
 
4796             ".*Can't find library for -lpthread.*" {
 
4797                 set why_msg "missing runtime threads library"
 
4800                 pass "successfully compiled posix threads test case"
 
4806     if {!$built_binfile} {
 
4807         unsupported "couldn't compile [file tail $source]: ${why_msg}"
 
4812 # Build a shared library from SOURCES.
 
4814 proc gdb_compile_shlib_1 {sources dest options} {
 
4815     set obj_options $options
 
4818     if { [lsearch -exact $options "ada"] >= 0 } {
 
4822     if { [lsearch -exact $options "c++"] >= 0 } {
 
4823         set info_options "c++"
 
4824     } elseif { [lsearch -exact $options "f90"] >= 0 } {
 
4825         set info_options "f90"
 
4827         set info_options "c"
 
4830     switch -glob [test_compiler_info "" ${info_options}] {
 
4832             lappend obj_options "additional_flags=-qpic"
 
4835             if { [istarget "*-*-cygwin*"]
 
4836                  || [istarget "*-*-mingw*"] } {
 
4837                 lappend obj_options "additional_flags=-fPIC"
 
4839                 lappend obj_options "additional_flags=-fpic"
 
4843             if { [istarget "powerpc*-*-aix*"]
 
4844                    || [istarget "rs6000*-*-aix*"]
 
4845                    || [istarget "*-*-cygwin*"]
 
4846                    || [istarget "*-*-mingw*"]
 
4847                    || [istarget "*-*-pe*"] } {
 
4848                 lappend obj_options "additional_flags=-fPIC"
 
4850                 lappend obj_options "additional_flags=-fpic"
 
4854                 lappend obj_options "additional_flags=-fpic"
 
4857             # don't know what the compiler is...
 
4858             lappend obj_options "additional_flags=-fPIC"
 
4862     set outdir [file dirname $dest]
 
4864     foreach source $sources {
 
4865         if {[file extension $source] == ".o"} {
 
4866             # Already a .o file.
 
4867             lappend objects $source
 
4871         set sourcebase [file tail $source]
 
4874             # Gnatmake doesn't like object name foo.adb.o, use foo.o.
 
4875             set sourcebase [file rootname $sourcebase]
 
4877         set object ${outdir}/${sourcebase}.o
 
4880             # Use gdb_compile_ada_1 instead of gdb_compile_ada to avoid the
 
4882             if {[gdb_compile_ada_1 $source $object object \
 
4883                      $obj_options] != ""} {
 
4887             if {[gdb_compile $source $object object \
 
4888                      $obj_options] != ""} {
 
4893         lappend objects $object
 
4896     set link_options $options
 
4898         # If we try to use gnatmake for the link, it will interpret the
 
4899         # object file as an .adb file.  Remove ada from the options to
 
4901         set idx [lsearch $link_options "ada"]
 
4902         set link_options [lreplace $link_options $idx $idx]
 
4904     if [test_compiler_info "xlc-*"] {
 
4905         lappend link_options "additional_flags=-qmkshrobj"
 
4907         lappend link_options "additional_flags=-shared"
 
4909         if { ([istarget "*-*-mingw*"]
 
4910               || [istarget *-*-cygwin*]
 
4911               || [istarget *-*-pe*]) } {
 
4912             if { [is_remote host] } {
 
4913                 set name [file tail ${dest}]
 
4917             lappend link_options "additional_flags=-Wl,--out-implib,${name}.a"
 
4919             # Set the soname of the library.  This causes the linker on ELF
 
4920             # systems to create the DT_NEEDED entry in the executable referring
 
4921             # to the soname of the library, and not its absolute path.  This
 
4922             # (using the absolute path) would be problem when testing on a
 
4925             # In conjunction with setting the soname, we add the special
 
4926             # rpath=$ORIGIN value when building the executable, so that it's
 
4927             # able to find the library in its own directory.
 
4928             set destbase [file tail $dest]
 
4929             lappend link_options "additional_flags=-Wl,-soname,$destbase"
 
4932     if {[gdb_compile "${objects}" "${dest}" executable $link_options] != ""} {
 
4935     if { [is_remote host]
 
4936          && ([istarget "*-*-mingw*"]
 
4937              || [istarget *-*-cygwin*]
 
4938              || [istarget *-*-pe*]) } {
 
4939         set dest_tail_name [file tail ${dest}]
 
4940         remote_upload host $dest_tail_name.a ${dest}.a
 
4941         remote_file host delete $dest_tail_name.a
 
4947 # Build a shared library from SOURCES.  Ignore target boards PIE-related
 
4950 proc gdb_compile_shlib {sources dest options} {
 
4953     # Ignore PIE-related setting in multilib_flags.
 
4954     set board [target_info name]
 
4955     set multilib_flags_orig [board_info $board multilib_flags]
 
4956     set multilib_flags ""
 
4957     foreach op $multilib_flags_orig {
 
4958         if { $op == "-pie" || $op == "-no-pie" \
 
4959                  || $op == "-fPIE" || $op == "-fno-PIE"} {
 
4961             append multilib_flags " $op"
 
4965     save_target_board_info { multilib_flags } {
 
4966         unset_board_info multilib_flags
 
4967         set_board_info multilib_flags "$multilib_flags"
 
4968         set result [gdb_compile_shlib_1 $sources $dest $options]
 
4974 # This is just like gdb_compile_shlib, above, except that it tries compiling
 
4975 # against several different thread libraries, to see which one this
 
4977 proc gdb_compile_shlib_pthreads {sources dest options} {
 
4979     set why_msg "unrecognized error"
 
4980     foreach lib {-lpthreads -lpthread -lthread ""} {
 
4981         # This kind of wipes out whatever libs the caller may have
 
4982         # set.  Or maybe theirs will override ours.  How infelicitous.
 
4983         set options_with_lib [concat $options [list libs=$lib quiet]]
 
4984         set ccout [gdb_compile_shlib $sources $dest $options_with_lib]
 
4985         switch -regexp -- $ccout {
 
4986             ".*no posix threads support.*" {
 
4987                 set why_msg "missing threads include file"
 
4990             ".*cannot open -lpthread.*" {
 
4991                 set why_msg "missing runtime threads library"
 
4993             ".*Can't find library for -lpthread.*" {
 
4994                 set why_msg "missing runtime threads library"
 
4997                 pass "successfully compiled posix threads shlib test case"
 
5003     if {!$built_binfile} {
 
5004         unsupported "couldn't compile $sources: ${why_msg}"
 
5009 # This is just like gdb_compile_pthreads, above, except that we always add the
 
5010 # objc library for compiling Objective-C programs
 
5011 proc gdb_compile_objc {source dest type options} {
 
5013     set why_msg "unrecognized error"
 
5014     foreach lib {-lobjc -lpthreads -lpthread -lthread solaris} {
 
5015         # This kind of wipes out whatever libs the caller may have
 
5016         # set.  Or maybe theirs will override ours.  How infelicitous.
 
5017         if { $lib == "solaris" } {
 
5018             set lib "-lpthread -lposix4"
 
5020         if { $lib != "-lobjc" } {
 
5021           set lib "-lobjc $lib"
 
5023         set options_with_lib [concat $options [list libs=$lib quiet]]
 
5024         set ccout [gdb_compile $source $dest $type $options_with_lib]
 
5025         switch -regexp -- $ccout {
 
5026             ".*no posix threads support.*" {
 
5027                 set why_msg "missing threads include file"
 
5030             ".*cannot open -lpthread.*" {
 
5031                 set why_msg "missing runtime threads library"
 
5033             ".*Can't find library for -lpthread.*" {
 
5034                 set why_msg "missing runtime threads library"
 
5037                 pass "successfully compiled objc with posix threads test case"
 
5043     if {!$built_binfile} {
 
5044         unsupported "couldn't compile [file tail $source]: ${why_msg}"
 
5049 # Build an OpenMP program from SOURCE.  See prefatory comment for
 
5050 # gdb_compile, above, for discussion of the parameters to this proc.
 
5052 proc gdb_compile_openmp {source dest type options} {
 
5053     lappend options "additional_flags=-fopenmp"
 
5054     return [gdb_compile $source $dest $type $options]
 
5057 # Send a command to GDB.
 
5058 # For options for TYPE see gdb_stdin_log_write
 
5060 proc send_gdb { string {type standard}} {
 
5061     gdb_stdin_log_write $string $type
 
5062     return [remote_send host "$string"]
 
5065 # Send STRING to the inferior's terminal.
 
5067 proc send_inferior { string } {
 
5068     global inferior_spawn_id
 
5070     if {[catch "send -i $inferior_spawn_id -- \$string" errorInfo]} {
 
5080 proc gdb_expect { args } {
 
5081     if { [llength $args] == 2  && [lindex $args 0] != "-re" } {
 
5082         set atimeout [lindex $args 0]
 
5083         set expcode [list [lindex $args 1]]
 
5088     # A timeout argument takes precedence, otherwise of all the timeouts
 
5089     # select the largest.
 
5090     if [info exists atimeout] {
 
5093         set tmt [get_largest_timeout]
 
5097         {uplevel remote_expect host $tmt $expcode} string]
 
5100         global errorInfo errorCode
 
5102         return -code error -errorinfo $errorInfo -errorcode $errorCode $string
 
5104         return -code $code $string
 
5108 # gdb_expect_list TEST SENTINEL LIST -- expect a sequence of outputs
 
5110 # Check for long sequence of output by parts.
 
5111 # TEST: is the test message to be printed with the test success/fail.
 
5112 # SENTINEL: Is the terminal pattern indicating that output has finished.
 
5113 # LIST: is the sequence of outputs to match.
 
5114 # If the sentinel is recognized early, it is considered an error.
 
5117 #    1 if the test failed,
 
5118 #    0 if the test passes,
 
5119 #   -1 if there was an internal error.
 
5121 proc gdb_expect_list {test sentinel list} {
 
5126     while { ${index} < [llength ${list}] } {
 
5127         set pattern [lindex ${list} ${index}]
 
5128         set index [expr ${index} + 1]
 
5129         verbose -log "gdb_expect_list pattern: /$pattern/" 2
 
5130         if { ${index} == [llength ${list}] } {
 
5133                     -re "${pattern}${sentinel}" {
 
5134                         # pass "${test}, pattern ${index} + sentinel"
 
5137                         fail "${test} (pattern ${index} + sentinel)"
 
5140                     -re ".*A problem internal to GDB has been detected" {
 
5141                         fail "${test} (GDB internal error)"
 
5143                         gdb_internal_error_resync
 
5146                         fail "${test} (pattern ${index} + sentinel) (timeout)"
 
5151                 # unresolved "${test}, pattern ${index} + sentinel"
 
5157                         # pass "${test}, pattern ${index}"
 
5160                         fail "${test} (pattern ${index})"
 
5163                     -re ".*A problem internal to GDB has been detected" {
 
5164                         fail "${test} (GDB internal error)"
 
5166                         gdb_internal_error_resync
 
5169                         fail "${test} (pattern ${index}) (timeout)"
 
5174                 # unresolved "${test}, pattern ${index}"
 
5186 # Spawn the gdb process.
 
5188 # This doesn't expect any output or do any other initialization,
 
5189 # leaving those to the caller.
 
5191 # Overridable function -- you can override this function in your
 
5194 proc gdb_spawn { } {
 
5198 # Spawn GDB with CMDLINE_FLAGS appended to the GDBFLAGS global.
 
5200 proc gdb_spawn_with_cmdline_opts { cmdline_flags } {
 
5203     set saved_gdbflags $GDBFLAGS
 
5205     if {$GDBFLAGS != ""} {
 
5208     append GDBFLAGS $cmdline_flags
 
5212     set GDBFLAGS $saved_gdbflags
 
5217 # Start gdb running, wait for prompt, and disable the pagers.
 
5219 # Overridable function -- you can override this function in your
 
5222 proc gdb_start { } {
 
5227     catch default_gdb_exit
 
5230 # Return true if we can spawn a program on the target and attach to
 
5233 proc can_spawn_for_attach { } {
 
5234     # We use exp_pid to get the inferior's pid, assuming that gives
 
5235     # back the pid of the program.  On remote boards, that would give
 
5236     # us instead the PID of e.g., the ssh client, etc.
 
5237     if [is_remote target] then {
 
5238         verbose -log "can't spawn for attach (target is remote)"
 
5242     # The "attach" command doesn't make sense when the target is
 
5243     # stub-like, where GDB finds the program already started on
 
5244     # initial connection.
 
5245     if {[target_info exists use_gdb_stub]} {
 
5246         verbose -log "can't spawn for attach (target is stub)"
 
5254 # Centralize the failure checking of "attach" command.
 
5255 # Return 0 if attach failed, otherwise return 1.
 
5257 proc gdb_attach { testpid args } {
 
5262     if { [llength $args] != 0 } {
 
5263         error "Unexpected arguments: $args"
 
5266     gdb_test_multiple "attach $testpid" "attach" {
 
5267         -re -wrap "Attaching to.*ptrace: Operation not permitted\\." {
 
5268             unsupported "$gdb_test_name (Operation not permitted)"
 
5271         -re -wrap "$pattern" {
 
5280 # Start gdb with "--pid $TESTPID" on the command line and wait for the prompt.
 
5281 # Return 1 if GDB managed to start and attach to the process, 0 otherwise.
 
5283 proc_with_prefix gdb_spawn_attach_cmdline { testpid } {
 
5284     if ![can_spawn_for_attach] {
 
5285         # The caller should have checked can_spawn_for_attach itself
 
5286         # before getting here.
 
5287         error "can't spawn for attach with this target/board"
 
5290     set test "start gdb with --pid"
 
5291     set res [gdb_spawn_with_cmdline_opts "-quiet --pid=$testpid"]
 
5297     gdb_test_multiple "" "$test" {
 
5298         -re -wrap "ptrace: Operation not permitted\\." {
 
5299             unsupported "$gdb_test_name (operation not permitted)"
 
5302         -re -wrap "ptrace: No such process\\." {
 
5303             fail "$gdb_test_name (no such process)"
 
5306         -re -wrap "Attaching to process $testpid\r\n.*" {
 
5311     # Check that we actually attached to a process, in case the
 
5312     # error message is not caught by the patterns above.
 
5313     gdb_test_multiple "info thread" "" {
 
5314         -re -wrap "No threads\\." {
 
5315             fail "$gdb_test_name (no thread)"
 
5326 # Kill a progress previously started with spawn_wait_for_attach, and
 
5327 # reap its wait status.  PROC_SPAWN_ID is the spawn id associated with
 
5330 proc kill_wait_spawned_process { proc_spawn_id } {
 
5331     set pid [exp_pid -i $proc_spawn_id]
 
5333     verbose -log "killing ${pid}"
 
5334     remote_exec build "kill -9 ${pid}"
 
5336     verbose -log "closing ${proc_spawn_id}"
 
5337     catch "close -i $proc_spawn_id"
 
5338     verbose -log "waiting for ${proc_spawn_id}"
 
5340     # If somehow GDB ends up still attached to the process here, a
 
5341     # blocking wait hangs until gdb is killed (or until gdb / the
 
5342     # ptracer reaps the exit status too, but that won't happen because
 
5343     # something went wrong.)  Passing -nowait makes expect tell Tcl to
 
5344     # wait for the PID in the background.  That's fine because we
 
5345     # don't care about the exit status.  */
 
5346     wait -nowait -i $proc_spawn_id
 
5349 # Returns the process id corresponding to the given spawn id.
 
5351 proc spawn_id_get_pid { spawn_id } {
 
5352     set testpid [exp_pid -i $spawn_id]
 
5354     if { [istarget "*-*-cygwin*"] } {
 
5355         # testpid is the Cygwin PID, GDB uses the Windows PID, which
 
5356         # might be different due to the way fork/exec works.
 
5357         set testpid [ exec ps -e | gawk "{ if (\$1 == $testpid) print \$4; }" ]
 
5363 # Start a set of programs running and then wait for a bit, to be sure
 
5364 # that they can be attached to.  Return a list of processes spawn IDs,
 
5365 # one element for each process spawned.  It's a test error to call
 
5366 # this when [can_spawn_for_attach] is false.
 
5368 proc spawn_wait_for_attach { executable_list } {
 
5369     set spawn_id_list {}
 
5371     if ![can_spawn_for_attach] {
 
5372         # The caller should have checked can_spawn_for_attach itself
 
5373         # before getting here.
 
5374         error "can't spawn for attach with this target/board"
 
5377     foreach {executable} $executable_list {
 
5378         # Note we use Expect's spawn, not Tcl's exec, because with
 
5379         # spawn we control when to wait for/reap the process.  That
 
5380         # allows killing the process by PID without being subject to
 
5382         lappend spawn_id_list [remote_spawn target $executable]
 
5387     return $spawn_id_list
 
5391 # gdb_load_cmd -- load a file into the debugger.
 
5392 #                 ARGS - additional args to load command.
 
5393 #                 return a -1 if anything goes wrong.
 
5395 proc gdb_load_cmd { args } {
 
5398     if [target_info exists gdb_load_timeout] {
 
5399         set loadtimeout [target_info gdb_load_timeout]
 
5401         set loadtimeout 1600
 
5403     send_gdb "load $args\n"
 
5404     verbose "Timeout is now $loadtimeout seconds" 2
 
5405     gdb_expect $loadtimeout {
 
5406         -re "Loading section\[^\r\]*\r\n" {
 
5409         -re "Start address\[\r\]*\r\n" {
 
5412         -re "Transfer rate\[\r\]*\r\n" {
 
5415         -re "Memory access error\[^\r\]*\r\n" {
 
5416             perror "Failed to load program"
 
5419         -re "$gdb_prompt $" {
 
5422         -re "(.*)\r\n$gdb_prompt " {
 
5423             perror "Unexpected reponse from 'load' -- $expect_out(1,string)"
 
5427             perror "Timed out trying to load $args."
 
5434 # Invoke "gcore".  CORE is the name of the core file to write.  TEST
 
5435 # is the name of the test case.  This will return 1 if the core file
 
5436 # was created, 0 otherwise.  If this fails to make a core file because
 
5437 # this configuration of gdb does not support making core files, it
 
5438 # will call "unsupported", not "fail".  However, if this fails to make
 
5439 # a core file for some other reason, then it will call "fail".
 
5441 proc gdb_gcore_cmd {core test} {
 
5445     gdb_test_multiple "gcore $core" $test {
 
5446         -re "Saved corefile .*\[\r\n\]+$gdb_prompt $" {
 
5450         -re "(?:Can't create a corefile|Target does not support core file generation\\.)\[\r\n\]+$gdb_prompt $" {
 
5458 # Load core file CORE.  TEST is the name of the test case.
 
5459 # This will record a pass/fail for loading the core file.
 
5461 #  1 - core file is successfully loaded
 
5462 #  0 - core file loaded but has a non fatal error
 
5463 # -1 - core file failed to load
 
5465 proc gdb_core_cmd { core test } {
 
5468     gdb_test_multiple "core $core" "$test" {
 
5469         -re "\\\[Thread debugging using \[^ \r\n\]* enabled\\\]\r\n" {
 
5472         -re " is not a core dump:.*\r\n$gdb_prompt $" {
 
5473             fail "$test (bad file format)"
 
5476         -re -wrap "[string_to_regexp $core]: No such file or directory.*" {
 
5477             fail "$test (file not found)"
 
5480         -re "Couldn't find .* registers in core file.*\r\n$gdb_prompt $" {
 
5481             fail "$test (incomplete note section)"
 
5484         -re "Core was generated by .*\r\n$gdb_prompt $" {
 
5488         -re ".*$gdb_prompt $" {
 
5493             fail "$test (timeout)"
 
5497     fail "unsupported output from 'core' command"
 
5501 # Return the filename to download to the target and load on the target
 
5502 # for this shared library.  Normally just LIBNAME, unless shared libraries
 
5503 # for this target have separate link and load images.
 
5505 proc shlib_target_file { libname } {
 
5509 # Return the filename GDB will load symbols from when debugging this
 
5510 # shared library.  Normally just LIBNAME, unless shared libraries for
 
5511 # this target have separate link and load images.
 
5513 proc shlib_symbol_file { libname } {
 
5517 # Return the filename to download to the target and load for this
 
5518 # executable.  Normally just BINFILE unless it is renamed to something
 
5519 # else for this target.
 
5521 proc exec_target_file { binfile } {
 
5525 # Return the filename GDB will load symbols from when debugging this
 
5526 # executable.  Normally just BINFILE unless executables for this target
 
5527 # have separate files for symbols.
 
5529 proc exec_symbol_file { binfile } {
 
5533 # Rename the executable file.  Normally this is just BINFILE1 being renamed
 
5534 # to BINFILE2, but some targets require multiple binary files.
 
5535 proc gdb_rename_execfile { binfile1 binfile2 } {
 
5536     file rename -force [exec_target_file ${binfile1}] \
 
5537                        [exec_target_file ${binfile2}]
 
5538     if { [exec_target_file ${binfile1}] != [exec_symbol_file ${binfile1}] } {
 
5539         file rename -force [exec_symbol_file ${binfile1}] \
 
5540                            [exec_symbol_file ${binfile2}]
 
5544 # "Touch" the executable file to update the date.  Normally this is just
 
5545 # BINFILE, but some targets require multiple files.
 
5546 proc gdb_touch_execfile { binfile } {
 
5547     set time [clock seconds]
 
5548     file mtime [exec_target_file ${binfile}] $time
 
5549     if { [exec_target_file ${binfile}] != [exec_symbol_file ${binfile}] } {
 
5550         file mtime [exec_symbol_file ${binfile}] $time
 
5554 # Like remote_download but provides a gdb-specific behavior.
 
5556 # If the destination board is remote, the local file FROMFILE is transferred as
 
5557 # usual with remote_download to TOFILE on the remote board.  The destination
 
5558 # filename is added to the CLEANFILES global, so it can be cleaned up at the
 
5561 # If the destination board is local, the destination path TOFILE is passed
 
5562 # through standard_output_file, and FROMFILE is copied there.
 
5564 # In both cases, if TOFILE is omitted, it defaults to the [file tail] of
 
5567 proc gdb_remote_download {dest fromfile {tofile {}}} {
 
5568     # If TOFILE is not given, default to the same filename as FROMFILE.
 
5569     if {[string length $tofile] == 0} {
 
5570         set tofile [file tail $fromfile]
 
5573     if {[is_remote $dest]} {
 
5574         # When the DEST is remote, we simply send the file to DEST.
 
5575         global cleanfiles_target cleanfiles_host
 
5577         set destname [remote_download $dest $fromfile $tofile]
 
5578         if { $dest == "target" } {
 
5579             lappend cleanfiles_target $destname
 
5580         } elseif { $dest == "host" } {
 
5581             lappend cleanfiles_host $destname
 
5586         # When the DEST is local, we copy the file to the test directory (where
 
5587         # the executable is).
 
5589         # Note that we pass TOFILE through standard_output_file, regardless of
 
5590         # whether it is absolute or relative, because we don't want the tests
 
5591         # to be able to write outside their standard output directory.
 
5593         set tofile [standard_output_file $tofile]
 
5595         file copy -force $fromfile $tofile
 
5601 # gdb_load_shlib LIB...
 
5603 # Copy the listed library to the target.
 
5605 proc gdb_load_shlib { file } {
 
5608     if ![info exists gdb_spawn_id] {
 
5609         perror "gdb_load_shlib: GDB is not running"
 
5612     set dest [gdb_remote_download target [shlib_target_file $file]]
 
5614     if {[is_remote target]} {
 
5615         # If the target is remote, we need to tell gdb where to find the
 
5618         # We could set this even when not testing remotely, but a user
 
5619         # generally won't set it unless necessary.  In order to make the tests
 
5620         # more like the real-life scenarios, we don't set it for local testing.
 
5621         gdb_test "set solib-search-path [file dirname $file]" "" \
 
5622             "set solib-search-path for [file tail $file]"
 
5629 # gdb_load -- load a file into the debugger.  Specifying no file
 
5630 # defaults to the executable currently being debugged.
 
5631 # The return value is 0 for success, -1 for failure.
 
5632 # Many files in config/*.exp override this procedure.
 
5634 proc gdb_load { arg } {
 
5636         return [gdb_file_cmd $arg]
 
5642 # with_complaints -- Execute BODY and set complaints temporary to N for the
 
5645 proc with_complaints { n body } {
 
5648     # Save current setting of complaints.
 
5650     set show_complaints_re \
 
5651         "Max number of complaints about incorrect symbols is ($decimal)\\."
 
5652     gdb_test_multiple "show complaints" "" {
 
5653         -re -wrap $show_complaints_re {
 
5654             set save $expect_out(1,string)
 
5658     if { $save == "" } {
 
5659         perror "Did not manage to set complaints"
 
5662         gdb_test_no_output -nopass "set complaints $n"
 
5665     set code [catch {uplevel 1 $body} result]
 
5667     # Restore saved setting of complaints.
 
5668     if { $save != "" } {
 
5669         gdb_test_no_output -nopass "set complaints $save"
 
5673         global errorInfo errorCode
 
5674         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
 
5676         return -code $code $result
 
5681 # gdb_load_no_complaints -- As gdb_load, but in addition verifies that
 
5682 # loading caused no symbol reading complaints.
 
5684 proc gdb_load_no_complaints { arg } {
 
5685     global gdb_prompt gdb_file_cmd_msg decimal
 
5687     # Temporarily set complaint to a small non-zero number.
 
5692     # Verify that there were no complaints.
 
5695              "^(Reading symbols from \[^\r\n\]*" \
 
5696              ")+(Expanding full symbols from \[^\r\n\]*" \
 
5698     gdb_assert {[regexp $re $gdb_file_cmd_msg]} "No complaints"
 
5701 # gdb_reload -- load a file into the target.  Called before "running",
 
5702 # either the first time or after already starting the program once,
 
5703 # for remote targets.  Most files that override gdb_load should now
 
5704 # override this instead.
 
5706 # INFERIOR_ARGS contains the arguments to pass to the inferiors, as a
 
5707 # single string to get interpreted by a shell.  If the target board
 
5708 # overriding gdb_reload is a "stub", then it should arrange things such
 
5709 # these arguments make their way to the inferior process.
 
5711 proc gdb_reload { {inferior_args {}} } {
 
5712     # For the benefit of existing configurations, default to gdb_load.
 
5713     # Specifying no file defaults to the executable currently being
 
5715     return [gdb_load ""]
 
5718 proc gdb_continue { function } {
 
5721     return [gdb_test "continue" ".*Breakpoint $decimal, $function .*" "continue to $function"]
 
5724 # Default implementation of gdb_init.
 
5725 proc default_gdb_init { test_file_name } {
 
5726     global gdb_wrapper_initialized
 
5727     global gdb_wrapper_target
 
5728     global gdb_test_file_name
 
5729     global cleanfiles_target
 
5730     global cleanfiles_host
 
5733     # Reset the timeout value to the default.  This way, any testcase
 
5734     # that changes the timeout value without resetting it cannot affect
 
5735     # the timeout used in subsequent testcases.
 
5736     global gdb_test_timeout
 
5738     set timeout $gdb_test_timeout
 
5740     if { [regexp ".*gdb\.reverse\/.*" $test_file_name]
 
5741          && [target_info exists gdb_reverse_timeout] } {
 
5742         set timeout [target_info gdb_reverse_timeout]
 
5745     # If GDB_INOTIFY is given, check for writes to '.'.  This is a
 
5746     # debugging tool to help confirm that the test suite is
 
5747     # parallel-safe.  You need "inotifywait" from the
 
5748     # inotify-tools package to use this.
 
5749     global GDB_INOTIFY inotify_pid
 
5750     if {[info exists GDB_INOTIFY] && ![info exists inotify_pid]} {
 
5751         global outdir tool inotify_log_file
 
5753         set exclusions {outputs temp gdb[.](log|sum) cache}
 
5754         set exclusion_re ([join $exclusions |])
 
5756         set inotify_log_file [standard_temp_file inotify.out]
 
5757         set inotify_pid [exec inotifywait -r -m -e move,create,delete . \
 
5758                              --exclude $exclusion_re \
 
5759                              |& tee -a $outdir/$tool.log $inotify_log_file &]
 
5761         # Wait for the watches; hopefully this is long enough.
 
5764         # Clear the log so that we don't emit a warning the first time
 
5766         set fd [open $inotify_log_file w]
 
5770     # Block writes to all banned variables, and invocation of all
 
5771     # banned procedures...
 
5772     global banned_variables
 
5773     global banned_procedures
 
5774     global banned_traced
 
5775     if (!$banned_traced) {
 
5776         foreach banned_var $banned_variables {
 
5777             global "$banned_var"
 
5778             trace add variable "$banned_var" write error
 
5780         foreach banned_proc $banned_procedures {
 
5781             global "$banned_proc"
 
5782             trace add execution "$banned_proc" enter error
 
5787     # We set LC_ALL, LC_CTYPE, and LANG to C so that we get the same
 
5788     # messages as expected.
 
5793     # Don't let a .inputrc file or an existing setting of INPUTRC mess
 
5794     # up the test results.  Certain tests (style tests and TUI tests)
 
5795     # want to set the terminal to a non-"dumb" value, and for those we
 
5796     # want to disable bracketed paste mode.  Versions of Readline
 
5797     # before 8.0 will not understand this and will issue a warning.
 
5798     # We tried using a $if to guard it, but Readline 8.1 had a bug in
 
5799     # its version-comparison code that prevented this for working.
 
5800     setenv INPUTRC [cached_file inputrc "set enable-bracketed-paste off"]
 
5802     # This disables style output, which would interfere with many
 
5806     # If DEBUGINFOD_URLS is set, gdb will try to download sources and
 
5807     # debug info for f.i. system libraries.  Prevent this.
 
5808     unset -nocomplain ::env(DEBUGINFOD_URLS)
 
5810     # Ensure that GDBHISTFILE and GDBHISTSIZE are removed from the
 
5811     # environment, we don't want these modifications to the history
 
5813     unset -nocomplain ::env(GDBHISTFILE)
 
5814     unset -nocomplain ::env(GDBHISTSIZE)
 
5816     # Ensure that XDG_CONFIG_HOME is not set.  Some tests setup a fake
 
5817     # home directory in order to test loading settings from gdbinit.
 
5818     # If XDG_CONFIG_HOME is set then GDB will load a gdbinit from
 
5819     # there (if one is present) rather than the home directory setup
 
5821     unset -nocomplain ::env(XDG_CONFIG_HOME)
 
5823     # Initialize GDB's pty with a fixed size, to make sure we avoid pagination
 
5824     # during startup.  See "man expect" for details about stty_init.
 
5826     set stty_init "rows 25 cols 80"
 
5828     # Some tests (for example gdb.base/maint.exp) shell out from gdb to use
 
5829     # grep.  Clear GREP_OPTIONS to make the behavior predictable,
 
5830     # especially having color output turned on can cause tests to fail.
 
5831     setenv GREP_OPTIONS ""
 
5833     # Clear $gdbserver_reconnect_p.
 
5834     global gdbserver_reconnect_p
 
5835     set gdbserver_reconnect_p 1
 
5836     unset gdbserver_reconnect_p
 
5838     # Clear $last_loaded_file
 
5839     global last_loaded_file
 
5840     unset -nocomplain last_loaded_file
 
5842     # Reset GDB number of instances
 
5843     global gdb_instances
 
5846     set cleanfiles_target {}
 
5847     set cleanfiles_host {}
 
5849     set gdb_test_file_name [file rootname [file tail $test_file_name]]
 
5851     # Make sure that the wrapper is rebuilt
 
5852     # with the appropriate multilib option.
 
5853     if { $gdb_wrapper_target != [current_target_name] } {
 
5854         set gdb_wrapper_initialized 0
 
5857     # Unlike most tests, we have a small number of tests that generate
 
5858     # a very large amount of output.  We therefore increase the expect
 
5859     # buffer size to be able to contain the entire test output.  This
 
5860     # is especially needed by gdb.base/info-macros.exp.
 
5862     # Also set this value for the currently running GDB. 
 
5863     match_max [match_max -d]
 
5865     # We want to add the name of the TCL testcase to the PASS/FAIL messages.
 
5866     set pf_prefix "[file tail [file dirname $test_file_name]]/[file tail $test_file_name]:"
 
5869     if [target_info exists gdb_prompt] {
 
5870         set gdb_prompt [target_info gdb_prompt]
 
5872         set gdb_prompt "\\(gdb\\)"
 
5875     if [info exists use_gdb_stub] {
 
5879     gdb_setup_known_globals
 
5881     if { [info procs ::gdb_tcl_unknown] != "" } {
 
5882         # Dejagnu overrides proc unknown.  The dejagnu version may trigger in a
 
5883         # test-case but abort the entire test run.  To fix this, we install a
 
5884         # local version here, which reverts dejagnu's override, and restore
 
5885         # dejagnu's version in gdb_finish.
 
5886         rename ::unknown ::dejagnu_unknown
 
5887         proc unknown { args } {
 
5888             # Use tcl's unknown.
 
5889             set cmd [lindex $args 0]
 
5890             unresolved "testcase aborted due to invalid command name: $cmd"
 
5891             return [uplevel 1 ::gdb_tcl_unknown $args]
 
5896 # Return a path using GDB_PARALLEL.
 
5897 # ARGS is a list of path elements to append to "$objdir/$GDB_PARALLEL".
 
5898 # GDB_PARALLEL must be defined, the caller must check.
 
5900 # The default value for GDB_PARALLEL is, canonically, ".".
 
5901 # The catch is that tests don't expect an additional "./" in file paths so
 
5902 # omit any directory for the default case.
 
5903 # GDB_PARALLEL is written as "yes" for the default case in Makefile.in to mark
 
5904 # its special handling.
 
5906 proc make_gdb_parallel_path { args } {
 
5907     global GDB_PARALLEL objdir
 
5908     set joiner [list "file" "join" $objdir]
 
5909     if { [info exists GDB_PARALLEL] && $GDB_PARALLEL != "yes" } {
 
5910         lappend joiner $GDB_PARALLEL
 
5912     set joiner [concat $joiner $args]
 
5913     return [eval $joiner]
 
5916 # Turn BASENAME into a full file name in the standard output
 
5917 # directory.  It is ok if BASENAME is the empty string; in this case
 
5918 # the directory is returned.
 
5920 proc standard_output_file {basename} {
 
5921     global objdir subdir gdb_test_file_name
 
5923     set dir [make_gdb_parallel_path outputs $subdir $gdb_test_file_name]
 
5925     # If running on MinGW, replace /c/foo with c:/foo
 
5926     if { [ishost *-*-mingw*] } {
 
5927         set dir [exec sh -c "cd ${dir} && pwd -W"]
 
5929     return [file join $dir $basename]
 
5932 # Turn BASENAME into a full file name in the standard output directory.  If
 
5933 # GDB has been launched more than once then append the count, starting with
 
5936 proc standard_output_file_with_gdb_instance {basename} {
 
5937     global gdb_instances
 
5938     set count $gdb_instances
 
5941       return [standard_output_file $basename]
 
5943     return [standard_output_file ${basename}.${count}]
 
5946 # Return the name of a file in our standard temporary directory.
 
5948 proc standard_temp_file {basename} {
 
5949     # Since a particular runtest invocation is only executing a single test
 
5950     # file at any given time, we can use the runtest pid to build the
 
5951     # path of the temp directory.
 
5952     set dir [make_gdb_parallel_path temp [pid]]
 
5954     return [file join $dir $basename]
 
5957 # Rename file A to file B, if B does not already exists.  Otherwise, leave B
 
5958 # as is and delete A.  Return 1 if rename happened.
 
5960 proc tentative_rename { a b } {
 
5961     global errorInfo errorCode
 
5962     set code [catch {file rename -- $a $b} result]
 
5963     if { $code == 1 && [lindex $errorCode 0] == "POSIX" \
 
5964              && [lindex $errorCode 1] == "EEXIST" } {
 
5969         return -code error -errorinfo $errorInfo -errorcode $errorCode $result
 
5970     } elseif {$code > 1} {
 
5971         return -code $code $result
 
5976 # Create a file with name FILENAME and contents TXT in the cache directory.
 
5977 # If EXECUTABLE, mark the new file for execution.
 
5979 proc cached_file { filename txt {executable 0}} {
 
5980     set filename [make_gdb_parallel_path cache $filename]
 
5982     if { [file exists $filename] } {
 
5986     set dir [file dirname $filename]
 
5989     set tmp_filename $filename.[pid]
 
5990     set fd [open $tmp_filename w]
 
5994     if { $executable } {
 
5995         exec chmod +x $tmp_filename
 
5997     tentative_rename $tmp_filename $filename
 
6002 # Set 'testfile', 'srcfile', and 'binfile'.
 
6004 # ARGS is a list of source file specifications.
 
6005 # Without any arguments, the .exp file's base name is used to
 
6006 # compute the source file name.  The ".c" extension is added in this case.
 
6007 # If ARGS is not empty, each entry is a source file specification.
 
6008 # If the specification starts with a "." or "-", it is treated as a suffix
 
6009 # to append to the .exp file's base name.
 
6010 # If the specification is the empty string, it is treated as if it
 
6012 # Otherwise it is a file name.
 
6013 # The first file in the list is used to set the 'srcfile' global.
 
6014 # Each subsequent name is used to set 'srcfile2', 'srcfile3', etc.
 
6016 # Most tests should call this without arguments.
 
6018 # If a completely different binary file name is needed, then it
 
6019 # should be handled in the .exp file with a suitable comment.
 
6021 proc standard_testfile {args} {
 
6022     global gdb_test_file_name
 
6024     global gdb_test_file_last_vars
 
6027     global testfile binfile
 
6029     set testfile $gdb_test_file_name
 
6030     set binfile [standard_output_file ${testfile}]
 
6032     if {[llength $args] == 0} {
 
6036     # Unset our previous output variables.
 
6037     # This can help catch hidden bugs.
 
6038     if {[info exists gdb_test_file_last_vars]} {
 
6039         foreach varname $gdb_test_file_last_vars {
 
6041             catch {unset $varname}
 
6044     # 'executable' is often set by tests.
 
6045     set gdb_test_file_last_vars {executable}
 
6049         set varname srcfile$suffix
 
6052         # Handle an extension.
 
6056             set first [string range $arg 0 0]
 
6057             if { $first == "." || $first == "-" } {
 
6058                 set arg $testfile$arg
 
6063         lappend gdb_test_file_last_vars $varname
 
6065         if {$suffix == ""} {
 
6073 # The default timeout used when testing GDB commands.  We want to use
 
6074 # the same timeout as the default dejagnu timeout, unless the user has
 
6075 # already provided a specific value (probably through a site.exp file).
 
6076 global gdb_test_timeout
 
6077 if ![info exists gdb_test_timeout] {
 
6078     set gdb_test_timeout $timeout
 
6081 # A list of global variables that GDB testcases should not use.
 
6082 # We try to prevent their use by monitoring write accesses and raising
 
6083 # an error when that happens.
 
6084 set banned_variables { bug_id prms_id }
 
6086 # A list of procedures that GDB testcases should not use.
 
6087 # We try to prevent their use by monitoring invocations and raising
 
6088 # an error when that happens.
 
6089 set banned_procedures { strace }
 
6091 # gdb_init is called by runtest at start, but also by several
 
6092 # tests directly; gdb_finish is only called from within runtest after
 
6093 # each test source execution.
 
6094 # Placing several traces by repetitive calls to gdb_init leads
 
6095 # to problems, as only one trace is removed in gdb_finish.
 
6096 # To overcome this possible problem, we add a variable that records
 
6097 # if the banned variables and procedures are already traced.
 
6100 # Global array that holds the name of all global variables at the time
 
6101 # a test script is started.  After the test script has completed any
 
6102 # global not in this list is deleted.
 
6103 array set gdb_known_globals {}
 
6105 # Setup the GDB_KNOWN_GLOBALS array with the names of all current
 
6107 proc gdb_setup_known_globals {} {
 
6108     global gdb_known_globals
 
6110     array set gdb_known_globals {}
 
6111     foreach varname [info globals] {
 
6112         set gdb_known_globals($varname) 1
 
6116 # Cleanup the global namespace.  Any global not in the
 
6117 # GDB_KNOWN_GLOBALS array is unset, this ensures we don't "leak"
 
6118 # globals from one test script to another.
 
6119 proc gdb_cleanup_globals {} {
 
6120     global gdb_known_globals gdb_persistent_globals
 
6122     foreach varname [info globals] {
 
6123         if {![info exists gdb_known_globals($varname)]} {
 
6124             if { [info exists gdb_persistent_globals($varname)] } {
 
6127             uplevel #0 unset $varname
 
6132 # Create gdb_tcl_unknown, a copy tcl's ::unknown, provided it's present as a
 
6134 set temp [interp create]
 
6135 if { [interp eval $temp "info procs ::unknown"] != "" } {
 
6136     set old_args [interp eval $temp "info args ::unknown"]
 
6137     set old_body [interp eval $temp "info body ::unknown"]
 
6138     eval proc gdb_tcl_unknown {$old_args} {$old_body}
 
6143 # GDB implementation of ${tool}_init.  Called right before executing the
 
6145 # Overridable function -- you can override this function in your
 
6147 proc gdb_init { args } {
 
6148     # A baseboard file overriding this proc and calling the default version
 
6149     # should behave the same as this proc.  So, don't add code here, but to
 
6150     # the default version instead.
 
6151     return [default_gdb_init {*}$args]
 
6154 # GDB implementation of ${tool}_finish.  Called right after executing the
 
6156 proc gdb_finish { } {
 
6157     global gdbserver_reconnect_p
 
6159     global cleanfiles_target
 
6160     global cleanfiles_host
 
6161     global known_globals
 
6163     if { [info procs ::gdb_tcl_unknown] != "" } {
 
6164         # Restore dejagnu's version of proc unknown.
 
6166         rename ::dejagnu_unknown ::unknown
 
6169     # Exit first, so that the files are no longer in use.
 
6172     if { [llength $cleanfiles_target] > 0 } {
 
6173         eval remote_file target delete $cleanfiles_target
 
6174         set cleanfiles_target {}
 
6176     if { [llength $cleanfiles_host] > 0 } {
 
6177         eval remote_file host delete $cleanfiles_host
 
6178         set cleanfiles_host {}
 
6181     # Unblock write access to the banned variables.  Dejagnu typically
 
6182     # resets some of them between testcases.
 
6183     global banned_variables
 
6184     global banned_procedures
 
6185     global banned_traced
 
6186     if ($banned_traced) {
 
6187         foreach banned_var $banned_variables {
 
6188             global "$banned_var"
 
6189             trace remove variable "$banned_var" write error
 
6191         foreach banned_proc $banned_procedures {
 
6192             global "$banned_proc"
 
6193             trace remove execution "$banned_proc" enter error
 
6198     global gdb_finish_hooks
 
6199     foreach gdb_finish_hook $gdb_finish_hooks {
 
6202     set gdb_finish_hooks [list]
 
6208 set debug_format "unknown"
 
6210 # Run the gdb command "info source" and extract the debugging format
 
6211 # information from the output and save it in debug_format.
 
6213 proc get_debug_format { } {
 
6218     set debug_format "unknown"
 
6219     send_gdb "info source\n"
 
6221         -re "Compiled with (.*) debugging format.\r\n.*$gdb_prompt $" {
 
6222             set debug_format $expect_out(1,string)
 
6223             verbose "debug format is $debug_format"
 
6226         -re "No current source file.\r\n$gdb_prompt $" {
 
6227             perror "get_debug_format used when no current source file"
 
6230         -re "$gdb_prompt $" {
 
6231             warning "couldn't check debug format (no valid response)."
 
6235             warning "couldn't check debug format (timeout)."
 
6241 # Return true if FORMAT matches the debug format the current test was
 
6242 # compiled with.  FORMAT is a shell-style globbing pattern; it can use
 
6243 # `*', `[...]', and so on.
 
6245 # This function depends on variables set by `get_debug_format', above.
 
6247 proc test_debug_format {format} {
 
6250     return [expr [string match $format $debug_format] != 0]
 
6253 # Like setup_xfail, but takes the name of a debug format (DWARF 1,
 
6254 # COFF, stabs, etc).  If that format matches the format that the
 
6255 # current test was compiled with, then the next test is expected to
 
6256 # fail for any target.  Returns 1 if the next test or set of tests is
 
6257 # expected to fail, 0 otherwise (or if it is unknown).  Must have
 
6258 # previously called get_debug_format.
 
6259 proc setup_xfail_format { format } {
 
6260     set ret [test_debug_format $format]
 
6268 # gdb_get_line_number TEXT [FILE]
 
6270 # Search the source file FILE, and return the line number of the
 
6271 # first line containing TEXT.  If no match is found, an error is thrown.
 
6273 # TEXT is a string literal, not a regular expression.
 
6275 # The default value of FILE is "$srcdir/$subdir/$srcfile".  If FILE is
 
6276 # specified, and does not start with "/", then it is assumed to be in
 
6277 # "$srcdir/$subdir".  This is awkward, and can be fixed in the future,
 
6278 # by changing the callers and the interface at the same time.
 
6279 # In particular: gdb.base/break.exp, gdb.base/condbreak.exp,
 
6280 # gdb.base/ena-dis-br.exp.
 
6282 # Use this function to keep your test scripts independent of the
 
6283 # exact line numbering of the source file.  Don't write:
 
6285 #   send_gdb "break 20"
 
6287 # This means that if anyone ever edits your test's source file, 
 
6288 # your test could break.  Instead, put a comment like this on the
 
6289 # source file line you want to break at:
 
6291 #   /* breakpoint spot: frotz.exp: test name */
 
6293 # and then write, in your test script (which we assume is named
 
6296 #   send_gdb "break [gdb_get_line_number "frotz.exp: test name"]\n"
 
6298 # (Yes, Tcl knows how to handle the nested quotes and brackets.
 
6301 #       % puts "foo [lindex "bar baz" 1]"
 
6304 # Tcl is quite clever, for a little stringy language.)
 
6308 # The previous implementation of this procedure used the gdb search command.
 
6309 # This version is different:
 
6311 #   . It works with MI, and it also works when gdb is not running.
 
6313 #   . It operates on the build machine, not the host machine.
 
6315 #   . For now, this implementation fakes a current directory of
 
6316 #     $srcdir/$subdir to be compatible with the old implementation.
 
6317 #     This will go away eventually and some callers will need to
 
6320 #   . The TEXT argument is literal text and matches literally,
 
6321 #     not a regular expression as it was before.
 
6323 #   . State changes in gdb, such as changing the current file
 
6324 #     and setting $_, no longer happen.
 
6326 # After a bit of time we can forget about the differences from the
 
6327 # old implementation.
 
6329 # --chastain 2004-08-05
 
6331 proc gdb_get_line_number { text { file "" } } {
 
6336     if { "$file" == "" } then {
 
6339     if { ! [regexp "^/" "$file"] } then {
 
6340         set file "$srcdir/$subdir/$file"
 
6343     if { [ catch { set fd [open "$file"] } message ] } then {
 
6348     for { set line 1 } { 1 } { incr line } {
 
6349         if { [ catch { set nchar [gets "$fd" body] } message ] } then {
 
6352         if { $nchar < 0 } then {
 
6355         if { [string first "$text" "$body"] >= 0 } then {
 
6361     if { [ catch { close "$fd" } message ] } then {
 
6366         error "undefined tag \"$text\""
 
6372 # Continue the program until it ends.
 
6374 # MSSG is the error message that gets printed.  If not given, a
 
6376 # COMMAND is the command to invoke.  If not given, "continue" is
 
6378 # ALLOW_EXTRA is a flag indicating whether the test should expect
 
6379 #       extra output between the "Continuing." line and the program
 
6380 #       exiting.  By default it is zero; if nonzero, any extra output
 
6383 proc gdb_continue_to_end {{mssg ""} {command continue} {allow_extra 0}} {
 
6384   global inferior_exited_re use_gdb_stub
 
6387       set text "continue until exit"
 
6389       set text "continue until exit at $mssg"
 
6397   # By default, we don't rely on exit() behavior of remote stubs --
 
6398   # it's common for exit() to be implemented as a simple infinite
 
6399   # loop, or a forced crash/reset.  For native targets, by default, we
 
6400   # assume process exit is reported as such.  If a non-reliable target
 
6401   # is used, we set a breakpoint at exit, and continue to that.
 
6402   if { [target_info exists exit_is_reliable] } {
 
6403       set exit_is_reliable [target_info exit_is_reliable]
 
6405       set exit_is_reliable [expr ! $use_gdb_stub]
 
6408   if { ! $exit_is_reliable } {
 
6409     if {![gdb_breakpoint "exit"]} {
 
6412     gdb_test $command "Continuing..*Breakpoint .*exit.*" \
 
6415     # Continue until we exit.  Should not stop again.
 
6416     # Don't bother to check the output of the program, that may be
 
6417     # extremely tough for some remote systems.
 
6419       "Continuing.\[\r\n0-9\]+${extra}(... EXIT code 0\[\r\n\]+|$inferior_exited_re normally).*"\
 
6424 proc rerun_to_main {} {
 
6425   global gdb_prompt use_gdb_stub
 
6430       -re ".*Breakpoint .*main .*$gdb_prompt $"\
 
6431               {pass "rerun to main" ; return 0}
 
6432       -re "$gdb_prompt $"\
 
6433               {fail "rerun to main" ; return 0}
 
6434       timeout {fail "(timeout) rerun to main" ; return 0}
 
6439       -re "The program .* has been started already.*y or n. $" {
 
6440           send_gdb "y\n" answer
 
6443       -re "Starting program.*$gdb_prompt $"\
 
6444               {pass "rerun to main" ; return 0}
 
6445       -re "$gdb_prompt $"\
 
6446               {fail "rerun to main" ; return 0}
 
6447       timeout {fail "(timeout) rerun to main" ; return 0}
 
6452 # Return true if EXECUTABLE contains a .gdb_index or .debug_names index section.
 
6454 proc exec_has_index_section { executable } {
 
6455     set readelf_program [gdb_find_readelf]
 
6456     set res [catch {exec $readelf_program -S $executable \
 
6457                         | grep -E "\.gdb_index|\.debug_names" }]
 
6464 # Return list with major and minor version of readelf, or an empty list.
 
6465 gdb_caching_proc readelf_version {
 
6466     set readelf_program [gdb_find_readelf]
 
6467     set res [catch {exec $readelf_program --version} output]
 
6471     set lines [split $output \n]
 
6472     set line [lindex $lines 0]
 
6473     set res [regexp {[ \t]+([0-9]+)[.]([0-9]+)[^ \t]*$} \
 
6474                  $line dummy major minor]
 
6478     return [list $major $minor]
 
6481 # Return 1 if readelf prints the PIE flag, 0 if is doesn't, and -1 if unknown.
 
6482 proc readelf_prints_pie { } {
 
6483     set version [readelf_version]
 
6484     if { [llength $version] == 0 } {
 
6487     set major [lindex $version 0]
 
6488     set minor [lindex $version 1]
 
6489     # It would be better to construct a PIE executable and test if the PIE
 
6490     # flag is printed by readelf, but we cannot reliably construct a PIE
 
6491     # executable if the multilib_flags dictate otherwise
 
6492     # (--target_board=unix/-no-pie/-fno-PIE).
 
6493     return [version_at_least $major $minor 2 26]
 
6496 # Return 1 if EXECUTABLE is a Position Independent Executable, 0 if it is not,
 
6497 # and -1 if unknown.
 
6499 proc exec_is_pie { executable } {
 
6500     set res [readelf_prints_pie]
 
6504     set readelf_program [gdb_find_readelf]
 
6505     # We're not testing readelf -d | grep "FLAGS_1.*Flags:.*PIE"
 
6506     # because the PIE flag is not set by all versions of gold, see PR
 
6508     set res [catch {exec $readelf_program -h $executable} output]
 
6512     set res [regexp -line {^[ \t]*Type:[ \t]*DYN \((Position-Independent Executable|Shared object) file\)$} \
 
6520 # Return true if a test should be skipped due to lack of floating
 
6521 # point support or GDB can't fetch the contents from floating point
 
6524 gdb_caching_proc gdb_skip_float_test {
 
6525     if [target_info exists gdb,skip_float_tests] {
 
6529     # There is an ARM kernel ptrace bug that hardware VFP registers
 
6530     # are not updated after GDB ptrace set VFP registers.  The bug
 
6531     # was introduced by kernel commit 8130b9d7b9d858aa04ce67805e8951e3cb6e9b2f
 
6532     # in 2012 and is fixed in e2dfb4b880146bfd4b6aa8e138c0205407cebbaf
 
6533     # in May 2016.  In other words, kernels older than 4.6.3, 4.4.14,
 
6534     # 4.1.27, 3.18.36, and 3.14.73 have this bug.
 
6535     # This kernel bug is detected by check how does GDB change the
 
6536     # program result by changing one VFP register.
 
6537     if { [istarget "arm*-*-linux*"] } {
 
6539         set compile_flags {debug nowarnings }
 
6541         # Set up, compile, and execute a test program having VFP
 
6543         set src [standard_temp_file arm_vfp[pid].c]
 
6544         set exe [standard_temp_file arm_vfp[pid].x]
 
6546         gdb_produce_source $src {
 
6551                 asm ("vldr d0, [%0]" : : "r" (&d));
 
6552                 asm ("vldr d1, [%0]" : : "r" (&d));
 
6553                 asm (".global break_here\n"
 
6555                 asm ("vcmp.f64 d0, d1\n"
 
6556                      "vmrs APSR_nzcv, fpscr\n"
 
6557                      "bne L_value_different\n"
 
6560                      "L_value_different:\n"
 
6562                      "L_end:\n" : "=r" (ret) :);
 
6564                 /* Return $d0 != $d1.  */
 
6569         verbose "compiling testfile $src" 2
 
6570         set lines [gdb_compile $src $exe executable $compile_flags]
 
6573         if ![string match "" $lines] then {
 
6574             verbose "testfile compilation failed, returning 1" 2
 
6578         # No error message, compilation succeeded so now run it via gdb.
 
6579         # Run the test up to 5 times to detect whether ptrace can
 
6580         # correctly update VFP registers or not.
 
6582         for {set i 0} {$i < 5} {incr i} {
 
6583             global gdb_prompt srcdir subdir
 
6587             gdb_reinitialize_dir $srcdir/$subdir
 
6591             gdb_test "break *break_here"
 
6592             gdb_continue_to_breakpoint "break_here"
 
6594             # Modify $d0 to a different value, so the exit code should
 
6596             gdb_test "set \$d0 = 5.0"
 
6598             set test "continue to exit"
 
6599             gdb_test_multiple "continue" "$test" {
 
6600                 -re "exited with code 01.*$gdb_prompt $" {
 
6602                 -re "exited normally.*$gdb_prompt $" {
 
6603                     # However, the exit code is 0.  That means something
 
6604                     # wrong in setting VFP registers.
 
6612         remote_file build delete $exe
 
6614         return $skip_vfp_test
 
6619 # Print a message and return true if a test should be skipped
 
6620 # due to lack of stdio support.
 
6622 proc gdb_skip_stdio_test { msg } {
 
6623     if [target_info exists gdb,noinferiorio] {
 
6624         verbose "Skipping test '$msg': no inferior i/o."
 
6630 proc gdb_skip_bogus_test { msg } {
 
6634 # Return true if a test should be skipped due to lack of XML support
 
6636 # NOTE: This must be called while gdb is *not* running.
 
6638 gdb_caching_proc gdb_skip_xml_test {
 
6643     if { [info exists gdb_spawn_id] } {
 
6644         error "GDB must not be running in gdb_skip_xml_tests."
 
6647     set xml_file [gdb_remote_download host "${srcdir}/gdb.xml/trivial.xml"]
 
6651     gdb_test_multiple "set tdesc filename $xml_file" "" {
 
6652         -re ".*XML support was disabled at compile time.*$gdb_prompt $" {
 
6655         -re ".*$gdb_prompt $" { }
 
6661 # Return true if argv[0] is available.
 
6663 gdb_caching_proc gdb_has_argv0 {
 
6666     # Compile and execute a test program to check whether argv[0] is available.
 
6667     gdb_simple_compile has_argv0 {
 
6668         int main (int argc, char **argv) {
 
6675     proc gdb_has_argv0_1 { exe } {
 
6676         global srcdir subdir
 
6677         global gdb_prompt hex
 
6681         gdb_reinitialize_dir $srcdir/$subdir
 
6684         # Set breakpoint on main.
 
6685         gdb_test_multiple "break -q main" "break -q main" {
 
6686             -re "Breakpoint.*${gdb_prompt} $" {
 
6688             -re "${gdb_prompt} $" {
 
6695         gdb_test_multiple "" "run to main" {
 
6696             -re "Breakpoint.*${gdb_prompt} $" {
 
6698             -re "${gdb_prompt} $" {
 
6703         set old_elements "200"
 
6704         set test "show print elements"
 
6705         gdb_test_multiple $test $test {
 
6706             -re "Limit on string chars or array elements to print is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
 
6707                 set old_elements $expect_out(1,string)
 
6710         set old_repeats "200"
 
6711         set test "show print repeats"
 
6712         gdb_test_multiple $test $test {
 
6713             -re "Threshold for repeated print elements is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
 
6714                 set old_repeats $expect_out(1,string)
 
6717         gdb_test_no_output "set print elements unlimited" ""
 
6718         gdb_test_no_output "set print repeats unlimited" ""
 
6721         # Check whether argc is 1.
 
6722         gdb_test_multiple "p argc" "p argc" {
 
6723             -re " = 1\r\n${gdb_prompt} $" {
 
6725                 gdb_test_multiple "p argv\[0\]" "p argv\[0\]" {
 
6726                     -re " = $hex \".*[file tail $exe]\"\r\n${gdb_prompt} $" {
 
6729                     -re "${gdb_prompt} $" {
 
6733             -re "${gdb_prompt} $" {
 
6737         gdb_test_no_output "set print elements $old_elements" ""
 
6738         gdb_test_no_output "set print repeats $old_repeats" ""
 
6743     set result [gdb_has_argv0_1 $obj]
 
6749       && ([istarget *-*-linux*]
 
6750           || [istarget *-*-freebsd*] || [istarget *-*-kfreebsd*]
 
6751           || [istarget *-*-netbsd*] || [istarget *-*-knetbsd*]
 
6752           || [istarget *-*-openbsd*]
 
6753           || [istarget *-*-darwin*]
 
6754           || [istarget *-*-solaris*]
 
6755           || [istarget *-*-aix*]
 
6756           || [istarget *-*-gnu*]
 
6757           || [istarget *-*-cygwin*] || [istarget *-*-mingw32*]
 
6758           || [istarget *-*-*djgpp*] || [istarget *-*-go32*]
 
6759           || [istarget *-wince-pe] || [istarget *-*-mingw32ce*]
 
6760           || [istarget *-*-osf*]
 
6761           || [istarget *-*-dicos*]
 
6762           || [istarget *-*-nto*]
 
6763           || [istarget *-*-*vms*]
 
6764           || [istarget *-*-lynx*178]) } {
 
6765         fail "argv\[0\] should be available on this target"
 
6771 # Note: the procedure gdb_gnu_strip_debug will produce an executable called
 
6772 # ${binfile}.dbglnk, which is just like the executable ($binfile) but without
 
6773 # the debuginfo. Instead $binfile has a .gnu_debuglink section which contains
 
6774 # the name of a debuginfo only file. This file will be stored in the same
 
6777 # Functions for separate debug info testing
 
6779 # starting with an executable:
 
6780 # foo --> original executable
 
6782 # at the end of the process we have:
 
6783 # foo.stripped --> foo w/o debug info
 
6784 # foo.debug --> foo's debug info
 
6785 # foo --> like foo, but with a new .gnu_debuglink section pointing to foo.debug.
 
6787 # Fetch the build id from the file.
 
6788 # Returns "" if there is none.
 
6790 proc get_build_id { filename } {
 
6791     if { ([istarget "*-*-mingw*"]
 
6792           || [istarget *-*-cygwin*]) } {
 
6793         set objdump_program [gdb_find_objdump]
 
6794         set result [catch {set data [exec $objdump_program -p $filename | grep signature | cut "-d " -f4]} output]
 
6795         verbose "result is $result"
 
6796         verbose "output is $output"
 
6802         set tmp [standard_output_file "${filename}-tmp"]
 
6803         set objcopy_program [gdb_find_objcopy]
 
6804         set result [catch "exec $objcopy_program -j .note.gnu.build-id -O binary $filename $tmp" output]
 
6805         verbose "result is $result"
 
6806         verbose "output is $output"
 
6811         fconfigure $fi -translation binary
 
6812         # Skip the NOTE header.
 
6817         if ![string compare $data ""] then {
 
6820         # Convert it to hex.
 
6821         binary scan $data H* data
 
6826 # Return the build-id hex string (usually 160 bits as 40 hex characters)
 
6827 # converted to the form: .build-id/ab/cdef1234...89.debug
 
6828 # Return "" if no build-id found.
 
6829 proc build_id_debug_filename_get { filename } {
 
6830     set data [get_build_id $filename]
 
6831     if { $data == "" } {
 
6834     regsub {^..} $data {\0/} data
 
6835     return ".build-id/${data}.debug"
 
6838 # Create stripped files for DEST, replacing it.  If ARGS is passed, it is a
 
6839 # list of optional flags.  The only currently supported flag is no-main,
 
6840 # which removes the symbol entry for main from the separate debug file.
 
6842 # Function returns zero on success.  Function will return non-zero failure code
 
6843 # on some targets not supporting separate debug info (such as i386-msdos).
 
6845 proc gdb_gnu_strip_debug { dest args } {
 
6847     # Use the first separate debug info file location searched by GDB so the
 
6848     # run cannot be broken by some stale file searched with higher precedence.
 
6849     set debug_file "${dest}.debug"
 
6851     set strip_to_file_program [transform strip]
 
6852     set objcopy_program [gdb_find_objcopy]
 
6854     set debug_link [file tail $debug_file]
 
6855     set stripped_file "${dest}.stripped"
 
6857     # Get rid of the debug info, and store result in stripped_file
 
6858     # something like gdb/testsuite/gdb.base/blah.stripped.
 
6859     set result [catch "exec $strip_to_file_program --strip-debug ${dest} -o ${stripped_file}" output]
 
6860     verbose "result is $result"
 
6861     verbose "output is $output"
 
6866     # Workaround PR binutils/10802:
 
6867     # Preserve the 'x' bit also for PIEs (Position Independent Executables).
 
6868     set perm [file attributes ${dest} -permissions]
 
6869     file attributes ${stripped_file} -permissions $perm
 
6871     # Get rid of everything but the debug info, and store result in debug_file
 
6872     # This will be in the .debug subdirectory, see above.
 
6873     set result [catch "exec $strip_to_file_program --only-keep-debug ${dest} -o ${debug_file}" output]
 
6874     verbose "result is $result"
 
6875     verbose "output is $output"
 
6880     # If no-main is passed, strip the symbol for main from the separate
 
6881     # file.  This is to simulate the behavior of elfutils's eu-strip, which
 
6882     # leaves the symtab in the original file only.  There's no way to get
 
6883     # objcopy or strip to remove the symbol table without also removing the
 
6884     # debugging sections, so this is as close as we can get.
 
6885     if { [llength $args] == 1 && [lindex $args 0] == "no-main" } {
 
6886         set result [catch "exec $objcopy_program -N main ${debug_file} ${debug_file}-tmp" output]
 
6887         verbose "result is $result"
 
6888         verbose "output is $output"
 
6892         file delete "${debug_file}"
 
6893         file rename "${debug_file}-tmp" "${debug_file}"
 
6896     # Link the two previous output files together, adding the .gnu_debuglink
 
6897     # section to the stripped_file, containing a pointer to the debug_file,
 
6898     # save the new file in dest.
 
6899     # This will be the regular executable filename, in the usual location.
 
6900     set result [catch "exec $objcopy_program --add-gnu-debuglink=${debug_file} ${stripped_file} ${dest}" output]
 
6901     verbose "result is $result"
 
6902     verbose "output is $output"
 
6907     # Workaround PR binutils/10802:
 
6908     # Preserve the 'x' bit also for PIEs (Position Independent Executables).
 
6909     set perm [file attributes ${stripped_file} -permissions]
 
6910     file attributes ${dest} -permissions $perm
 
6915 # Test the output of GDB_COMMAND matches the pattern obtained
 
6916 # by concatenating all elements of EXPECTED_LINES.  This makes
 
6917 # it possible to split otherwise very long string into pieces.
 
6918 # If third argument TESTNAME is not empty, it's used as the name of the
 
6919 # test to be printed on pass/fail.
 
6920 proc help_test_raw { gdb_command expected_lines {testname {}} } {
 
6921     set expected_output [join $expected_lines ""]
 
6922     if {$testname != {}} {
 
6923         gdb_test "${gdb_command}" "${expected_output}" $testname
 
6927     gdb_test "${gdb_command}" "${expected_output}"
 
6930 # A regexp that matches the end of help CLASS|PREFIX_COMMAND
 
6931 set help_list_trailer {
 
6932     "Type \"apropos word\" to search for commands related to \"word\"\.[\r\n]+"
 
6933     "Type \"apropos -v word\" for full documentation of commands related to \"word\"\.[\r\n]+"
 
6934     "Command name abbreviations are allowed if unambiguous\."
 
6937 # Test the output of "help COMMAND_CLASS".  EXPECTED_INITIAL_LINES
 
6938 # are regular expressions that should match the beginning of output,
 
6939 # before the list of commands in that class.
 
6940 # LIST_OF_COMMANDS are regular expressions that should match the
 
6941 # list of commands in that class.  If empty, the command list will be
 
6942 # matched automatically.  The presence of standard epilogue will be tested
 
6944 # If last argument TESTNAME is not empty, it's used as the name of the
 
6945 # test to be printed on pass/fail.
 
6946 # Notice that the '[' and ']' characters don't need to be escaped for strings
 
6947 # wrapped in {} braces.
 
6948 proc test_class_help { command_class expected_initial_lines {list_of_commands {}} {testname {}} } {
 
6949     global help_list_trailer
 
6950     if {[llength $list_of_commands]>0} {
 
6951         set l_list_of_commands {"List of commands:[\r\n]+[\r\n]+"}
 
6952         set l_list_of_commands [concat $l_list_of_commands $list_of_commands]
 
6953         set l_list_of_commands [concat $l_list_of_commands {"[\r\n]+[\r\n]+"}]
 
6955         set l_list_of_commands {"List of commands\:.*[\r\n]+"}
 
6958         "Type \"help\" followed by command name for full documentation\.[\r\n]+"
 
6960     set l_entire_body [concat $expected_initial_lines $l_list_of_commands \
 
6961                        $l_stock_body $help_list_trailer]
 
6963     help_test_raw "help ${command_class}" $l_entire_body $testname
 
6966 # Like test_class_help but specialised to test "help user-defined".
 
6967 proc test_user_defined_class_help { {list_of_commands {}} {testname {}} } {
 
6968     test_class_help "user-defined" {
 
6969         "User-defined commands\.[\r\n]+"
 
6970         "The commands in this class are those defined by the user\.[\r\n]+"
 
6971         "Use the \"define\" command to define a command\.[\r\n]+"
 
6972     } $list_of_commands $testname
 
6976 # COMMAND_LIST should have either one element -- command to test, or
 
6977 # two elements -- abbreviated command to test, and full command the first
 
6978 # element is abbreviation of.
 
6979 # The command must be a prefix command.  EXPECTED_INITIAL_LINES
 
6980 # are regular expressions that should match the beginning of output,
 
6981 # before the list of subcommands.  The presence of 
 
6982 # subcommand list and standard epilogue will be tested automatically.
 
6983 proc test_prefix_command_help { command_list expected_initial_lines args } {
 
6984     global help_list_trailer
 
6985     set command [lindex $command_list 0]   
 
6986     if {[llength $command_list]>1} {        
 
6987         set full_command [lindex $command_list 1]
 
6989         set full_command $command
 
6991     # Use 'list' and not just {} because we want variables to
 
6992     # be expanded in this list.
 
6993     set l_stock_body [list\
 
6994          "List of $full_command subcommands\:.*\[\r\n\]+"\
 
6995          "Type \"help $full_command\" followed by $full_command subcommand name for full documentation\.\[\r\n\]+"]
 
6996     set l_entire_body [concat $expected_initial_lines $l_stock_body $help_list_trailer]
 
6997     if {[llength $args]>0} {
 
6998         help_test_raw "help ${command}" $l_entire_body [lindex $args 0]
 
7000         help_test_raw "help ${command}" $l_entire_body
 
7004 # Build executable named EXECUTABLE from specifications that allow
 
7005 # different options to be passed to different sub-compilations.
 
7006 # TESTNAME is the name of the test; this is passed to 'untested' if
 
7008 # OPTIONS is passed to the final link, using gdb_compile.  If OPTIONS
 
7009 # contains the option "pthreads", then gdb_compile_pthreads is used.
 
7010 # ARGS is a flat list of source specifications, of the form:
 
7011 #    { SOURCE1 OPTIONS1 [ SOURCE2 OPTIONS2 ]... }
 
7012 # Each SOURCE is compiled to an object file using its OPTIONS,
 
7013 # using gdb_compile.
 
7014 # Returns 0 on success, -1 on failure.
 
7015 proc build_executable_from_specs {testname executable options args} {
 
7019     set binfile [standard_output_file $executable]
 
7021     set func gdb_compile
 
7022     set func_index [lsearch -regexp $options {^(pthreads|shlib|shlib_pthreads|openmp)$}]
 
7023     if {$func_index != -1} {
 
7024         set func "${func}_[lindex $options $func_index]"
 
7027     # gdb_compile_shlib and gdb_compile_shlib_pthreads do not use the 3rd
 
7028     # parameter.  They also requires $sources while gdb_compile and
 
7029     # gdb_compile_pthreads require $objects.  Moreover they ignore any options.
 
7030     if [string match gdb_compile_shlib* $func] {
 
7032         foreach {s local_options} $args {
 
7033             if { [regexp "^/" "$s"] } then {
 
7034                 lappend sources_path "$s"
 
7036                 lappend sources_path "$srcdir/$subdir/$s"
 
7039         set ret [$func $sources_path "${binfile}" $options]
 
7040     } elseif {[lsearch -exact $options rust] != -1} {
 
7042         foreach {s local_options} $args {
 
7043             if { [regexp "^/" "$s"] } then {
 
7044                 lappend sources_path "$s"
 
7046                 lappend sources_path "$srcdir/$subdir/$s"
 
7049         set ret [gdb_compile_rust $sources_path "${binfile}" $options]
 
7053         foreach {s local_options} $args {
 
7054             if { ! [regexp "^/" "$s"] } then {
 
7055                 set s "$srcdir/$subdir/$s"
 
7057             if  { [$func "${s}" "${binfile}${i}.o" object $local_options] != "" } {
 
7061             lappend objects "${binfile}${i}.o"
 
7064         set ret [$func $objects "${binfile}" executable $options]
 
7074 # Build executable named EXECUTABLE, from SOURCES.  If SOURCES are not
 
7075 # provided, uses $EXECUTABLE.c.  The TESTNAME paramer is the name of test
 
7076 # to pass to untested, if something is wrong.  OPTIONS are passed
 
7077 # to gdb_compile directly.
 
7078 proc build_executable { testname executable {sources ""} {options {debug}} } {
 
7079     if {[llength $sources]==0} {
 
7080         set sources ${executable}.c
 
7083     set arglist [list $testname $executable $options]
 
7084     foreach source $sources {
 
7085         lappend arglist $source $options
 
7088     return [eval build_executable_from_specs $arglist]
 
7091 # Starts fresh GDB binary and loads an optional executable into GDB.
 
7092 # Usage: clean_restart [executable]
 
7093 # EXECUTABLE is the basename of the binary.
 
7094 # Return -1 if starting gdb or loading the executable failed.
 
7096 proc clean_restart { args } {
 
7102     if { [llength $args] > 1 } {
 
7103         error "bad number of args: [llength $args]"
 
7108     # This is a clean restart, so reset error and warning count.
 
7113     #   if { [gdb_start] == -1 } {
 
7116     # but gdb_start is a ${tool}_start proc, which doesn't have a defined
 
7117     # return value.  So instead, we test for errcnt.
 
7119     if { $errcnt > 0 } {
 
7123     gdb_reinitialize_dir $srcdir/$subdir
 
7125     if { [llength $args] >= 1 } {
 
7126         set executable [lindex $args 0]
 
7127         set binfile [standard_output_file ${executable}]
 
7128         return [gdb_load ${binfile}]
 
7134 # Prepares for testing by calling build_executable_full, then
 
7136 # TESTNAME is the name of the test.
 
7137 # Each element in ARGS is a list of the form
 
7138 #    { EXECUTABLE OPTIONS SOURCE_SPEC... }
 
7139 # These are passed to build_executable_from_specs, which see.
 
7140 # The last EXECUTABLE is passed to clean_restart.
 
7141 # Returns 0 on success, non-zero on failure.
 
7142 proc prepare_for_testing_full {testname args} {
 
7143     foreach spec $args {
 
7144         if {[eval build_executable_from_specs [list $testname] $spec] == -1} {
 
7147         set executable [lindex $spec 0]
 
7149     clean_restart $executable
 
7153 # Prepares for testing, by calling build_executable, and then clean_restart.
 
7154 # Please refer to build_executable for parameter description.
 
7155 proc prepare_for_testing { testname executable {sources ""} {options {debug}}} {
 
7157     if {[build_executable $testname $executable $sources $options] == -1} {
 
7160     clean_restart $executable
 
7165 # Retrieve the value of EXP in the inferior, represented in format
 
7166 # specified in FMT (using "printFMT").  DEFAULT is used as fallback if
 
7167 # print fails.  TEST is the test message to use.  It can be omitted,
 
7168 # in which case a test message is built from EXP.
 
7170 proc get_valueof { fmt exp default {test ""} } {
 
7174         set test "get valueof \"${exp}\""
 
7178     gdb_test_multiple "print${fmt} ${exp}" "$test" {
 
7179         -re "\\$\[0-9\]* = (\[^\r\n\]*)\[\r\n\]*$gdb_prompt $" {
 
7180             set val $expect_out(1,string)
 
7184             fail "$test (timeout)"
 
7190 # Retrieve the value of local var EXP in the inferior.  DEFAULT is used as
 
7191 # fallback if print fails.  TEST is the test message to use.  It can be
 
7192 # omitted, in which case a test message is built from EXP.
 
7194 proc get_local_valueof { exp default {test ""} } {
 
7198         set test "get local valueof \"${exp}\""
 
7202     gdb_test_multiple "info locals ${exp}" "$test" {
 
7203         -re "$exp = (\[^\r\n\]*)\[\r\n\]*$gdb_prompt $" {
 
7204             set val $expect_out(1,string)
 
7208             fail "$test (timeout)"
 
7214 # Retrieve the value of EXP in the inferior, as a signed decimal value
 
7215 # (using "print /d").  DEFAULT is used as fallback if print fails.
 
7216 # TEST is the test message to use.  It can be omitted, in which case
 
7217 # a test message is built from EXP.
 
7219 proc get_integer_valueof { exp default {test ""} } {
 
7223         set test "get integer valueof \"${exp}\""
 
7227     gdb_test_multiple "print /d ${exp}" "$test" {
 
7228         -re "\\$\[0-9\]* = (\[-\]*\[0-9\]*).*$gdb_prompt $" {
 
7229             set val $expect_out(1,string)
 
7233             fail "$test (timeout)"
 
7239 # Retrieve the value of EXP in the inferior, as an hexadecimal value
 
7240 # (using "print /x").  DEFAULT is used as fallback if print fails.
 
7241 # TEST is the test message to use.  It can be omitted, in which case
 
7242 # a test message is built from EXP.
 
7244 proc get_hexadecimal_valueof { exp default {test ""} } {
 
7248         set test "get hexadecimal valueof \"${exp}\""
 
7252     gdb_test_multiple "print /x ${exp}" $test {
 
7253         -re "\\$\[0-9\]* = (0x\[0-9a-zA-Z\]+).*$gdb_prompt $" {
 
7254             set val $expect_out(1,string)
 
7261 # Retrieve the size of TYPE in the inferior, as a decimal value.  DEFAULT
 
7262 # is used as fallback if print fails.  TEST is the test message to use.
 
7263 # It can be omitted, in which case a test message is 'sizeof (TYPE)'.
 
7265 proc get_sizeof { type default {test ""} } {
 
7266     return [get_integer_valueof "sizeof (${type})" $default $test]
 
7269 proc get_target_charset { } {
 
7272     gdb_test_multiple "show target-charset" "" {
 
7273         -re "The target character set is \"auto; currently (\[^\"\]*)\".*$gdb_prompt $" {
 
7274             return $expect_out(1,string)
 
7276         -re "The target character set is \"(\[^\"\]*)\".*$gdb_prompt $" {
 
7277             return $expect_out(1,string)
 
7281     # Pick a reasonable default.
 
7282     warning "Unable to read target-charset."
 
7286 # Get the address of VAR.
 
7288 proc get_var_address { var } {
 
7289     global gdb_prompt hex
 
7291     # Match output like:
 
7293     # $5 = (int (*)()) 0
 
7294     # $6 = (int (*)()) 0x24 <function_bar>
 
7296     gdb_test_multiple "print &${var}" "get address of ${var}" {
 
7297         -re "\\\$\[0-9\]+ = \\(.*\\) (0|$hex)( <${var}>)?\[\r\n\]+${gdb_prompt} $"
 
7299             pass "get address of ${var}"
 
7300             if { $expect_out(1,string) == "0" } {
 
7303                 return $expect_out(1,string)
 
7310 # Return the frame number for the currently selected frame
 
7311 proc get_current_frame_number {{test_name ""}} {
 
7314     if { $test_name == "" } {
 
7315         set test_name "get current frame number"
 
7318     gdb_test_multiple "frame" $test_name {
 
7319         -re "#(\[0-9\]+) .*$gdb_prompt $" {
 
7320             set frame_num $expect_out(1,string)
 
7326 # Get the current value for remotetimeout and return it.
 
7327 proc get_remotetimeout { } {
 
7331     gdb_test_multiple "show remotetimeout" "" {
 
7332         -re "Timeout limit to wait for target to respond is ($decimal).*$gdb_prompt $" {
 
7333             return $expect_out(1,string)
 
7337     # Pick the default that gdb uses
 
7338     warning "Unable to read remotetimeout"
 
7342 # Set the remotetimeout to the specified timeout.  Nothing is returned.
 
7343 proc set_remotetimeout { timeout } {
 
7346     gdb_test_multiple "set remotetimeout $timeout" "" {
 
7347         -re "$gdb_prompt $" {
 
7348             verbose "Set remotetimeout to $timeout\n"
 
7353 # Get the target's current endianness and return it.
 
7354 proc get_endianness { } {
 
7357     gdb_test_multiple "show endian" "determine endianness" {
 
7358         -re ".* (little|big) endian.*\r\n$gdb_prompt $" {
 
7360             return $expect_out(1,string)
 
7366 # Get the target's default endianness and return it.
 
7367 gdb_caching_proc target_endianness {
 
7370     set me "target_endianness"
 
7372     set src { int main() { return 0; } }
 
7373     if {![gdb_simple_compile $me $src executable]} {
 
7381     set res [get_endianness]
 
7384     remote_file build delete $obj
 
7389 # ROOT and FULL are file names.  Returns the relative path from ROOT
 
7390 # to FULL.  Note that FULL must be in a subdirectory of ROOT.
 
7391 # For example, given ROOT = /usr/bin and FULL = /usr/bin/ls, this
 
7394 proc relative_filename {root full} {
 
7395     set root_split [file split $root]
 
7396     set full_split [file split $full]
 
7398     set len [llength $root_split]
 
7400     if {[eval file join $root_split]
 
7401         != [eval file join [lrange $full_split 0 [expr {$len - 1}]]]} {
 
7402         error "$full not a subdir of $root"
 
7405     return [eval file join [lrange $full_split $len end]]
 
7408 # If GDB_PARALLEL exists, then set up the parallel-mode directories.
 
7409 if {[info exists GDB_PARALLEL]} {
 
7410     if {[is_remote host]} {
 
7414             [make_gdb_parallel_path outputs] \
 
7415             [make_gdb_parallel_path temp] \
 
7416             [make_gdb_parallel_path cache]
 
7420 # Set the inferior's cwd to the output directory, in order to have it
 
7421 # dump core there.  This must be called before the inferior is
 
7424 proc set_inferior_cwd_to_output_dir {} {
 
7425     # Note this sets the inferior's cwd ("set cwd"), not GDB's ("cd").
 
7426     # If GDB crashes, we want its core dump in gdb/testsuite/, not in
 
7427     # the testcase's dir, so we can detect the unexpected core at the
 
7428     # end of the test run.
 
7429     if {![is_remote host]} {
 
7430         set output_dir [standard_output_file ""]
 
7431         gdb_test_no_output "set cwd $output_dir" \
 
7432             "set inferior cwd to test directory"
 
7436 # Get the inferior's PID.
 
7438 proc get_inferior_pid {} {
 
7440     gdb_test_multiple "inferior" "get inferior pid" {
 
7441         -re "process (\[0-9\]*).*$::gdb_prompt $" {
 
7442             set pid $expect_out(1,string)
 
7449 # Find the kernel-produced core file dumped for the current testfile
 
7450 # program.  PID was the inferior's pid, saved before the inferior
 
7451 # exited with a signal, or -1 if not known.  If not on a remote host,
 
7452 # this assumes the core was generated in the output directory.
 
7453 # Returns the name of the core dump, or empty string if not found.
 
7455 proc find_core_file {pid} {
 
7456     # For non-remote hosts, since cores are assumed to be in the
 
7457     # output dir, which we control, we use a laxer "core.*" glob.  For
 
7458     # remote hosts, as we don't know whether the dir is being reused
 
7459     # for parallel runs, we use stricter names with no globs.  It is
 
7460     # not clear whether this is really important, but it preserves
 
7463     if {![is_remote host]} {
 
7464         lappend files core.*
 
7465     } elseif {$pid != -1} {
 
7466         lappend files core.$pid
 
7468     lappend files [list ${::testfile}.core core]
 
7470     foreach file $files {
 
7471         if {![is_remote host]} {
 
7472             set names [glob -nocomplain [standard_output_file $file]]
 
7473             if {[llength $names] == 1} {
 
7474                 return [lindex $names 0]
 
7477             if {[remote_file host exists $file]} {
 
7485 # Check for production of a core file and remove it.  PID is the
 
7486 # inferior's pid or -1 if not known.  TEST is the test's message.
 
7488 proc remove_core {pid {test ""}} {
 
7490         set test "cleanup core file"
 
7493     set file [find_core_file $pid]
 
7495         remote_file host delete $file
 
7496         pass "$test (removed)"
 
7498         pass "$test (not found)"
 
7502 proc core_find {binfile {deletefiles {}} {arg ""}} {
 
7503     global objdir subdir
 
7505     set destcore "$binfile.core"
 
7506     file delete $destcore
 
7508     # Create a core file named "$destcore" rather than just "core", to
 
7509     # avoid problems with sys admin types that like to regularly prune all
 
7510     # files named "core" from the system.
 
7512     # Arbitrarily try setting the core size limit to "unlimited" since
 
7513     # this does not hurt on systems where the command does not work and
 
7514     # allows us to generate a core on systems where it does.
 
7516     # Some systems append "core" to the name of the program; others append
 
7517     # the name of the program to "core"; still others (like Linux, as of
 
7518     # May 2003) create cores named "core.PID".  In the latter case, we
 
7519     # could have many core files lying around, and it may be difficult to
 
7520     # tell which one is ours, so let's run the program in a subdirectory.
 
7522     set coredir [standard_output_file coredir.[getpid]]
 
7524     catch "system \"(cd ${coredir}; ulimit -c unlimited; ${binfile} ${arg}; true) >/dev/null 2>&1\""
 
7525     #      remote_exec host "${binfile}"
 
7526     foreach i "${coredir}/core ${coredir}/core.coremaker.c ${binfile}.core" {
 
7527         if [remote_file build exists $i] {
 
7528             remote_exec build "mv $i $destcore"
 
7532     # Check for "core.PID", "core.EXEC.PID.HOST.TIME", etc.  It's fine
 
7533     # to use a glob here as we're looking inside a directory we
 
7534     # created.  Also, this procedure only works on non-remote hosts.
 
7535     if { $found == 0 } {
 
7536         set names [glob -nocomplain -directory $coredir core.*]
 
7537         if {[llength $names] == 1} {
 
7538             set corefile [file join $coredir [lindex $names 0]]
 
7539             remote_exec build "mv $corefile $destcore"
 
7543     if { $found == 0 } {
 
7544         # The braindamaged HPUX shell quits after the ulimit -c above
 
7545         # without executing ${binfile}.  So we try again without the
 
7546         # ulimit here if we didn't find a core file above.
 
7547         # Oh, I should mention that any "braindamaged" non-Unix system has
 
7548         # the same problem. I like the cd bit too, it's really neat'n stuff.
 
7549         catch "system \"(cd ${objdir}/${subdir}; ${binfile}; true) >/dev/null 2>&1\""
 
7550         foreach i "${objdir}/${subdir}/core ${objdir}/${subdir}/core.coremaker.c ${binfile}.core" {
 
7551             if [remote_file build exists $i] {
 
7552                 remote_exec build "mv $i $destcore"
 
7558     # Try to clean up after ourselves. 
 
7559     foreach deletefile $deletefiles {
 
7560         remote_file build delete [file join $coredir $deletefile]
 
7562     remote_exec build "rmdir $coredir"
 
7564     if { $found == 0  } {
 
7565         warning "can't generate a core file - core tests suppressed - check ulimit -c"
 
7571 # gdb_target_symbol_prefix compiles a test program and then examines
 
7572 # the output from objdump to determine the prefix (such as underscore)
 
7573 # for linker symbol prefixes.
 
7575 gdb_caching_proc gdb_target_symbol_prefix {
 
7576     # Compile a simple test program...
 
7577     set src { int main() { return 0; } }
 
7578     if {![gdb_simple_compile target_symbol_prefix $src executable]} {
 
7584     set objdump_program [gdb_find_objdump]
 
7585     set result [catch "exec $objdump_program --syms $obj" output]
 
7588         && ![regexp -lineanchor \
 
7589              { ([^ a-zA-Z0-9]*)main$} $output dummy prefix] } {
 
7590         verbose "gdb_target_symbol_prefix: Could not find main in objdump output; returning null prefix" 2
 
7598 # Return 1 if target supports scheduler locking, otherwise return 0.
 
7600 gdb_caching_proc target_supports_scheduler_locking {
 
7603     set me "gdb_target_supports_scheduler_locking"
 
7605     set src { int main() { return 0; } }
 
7606     if {![gdb_simple_compile $me $src executable]} {
 
7615     set supports_schedule_locking -1
 
7616     set current_schedule_locking_mode ""
 
7618     set test "reading current scheduler-locking mode"
 
7619     gdb_test_multiple "show scheduler-locking" $test {
 
7620         -re "Mode for locking scheduler during execution is \"(\[\^\"\]*)\".*$gdb_prompt" {
 
7621             set current_schedule_locking_mode $expect_out(1,string)
 
7623         -re "$gdb_prompt $" {
 
7624             set supports_schedule_locking 0
 
7627             set supports_schedule_locking 0
 
7631     if { $supports_schedule_locking == -1 } {
 
7632         set test "checking for scheduler-locking support"
 
7633         gdb_test_multiple "set scheduler-locking $current_schedule_locking_mode" $test {
 
7634             -re "Target '\[^'\]+' cannot support this command\..*$gdb_prompt $" {
 
7635                 set supports_schedule_locking 0
 
7637             -re "$gdb_prompt $" {
 
7638                 set supports_schedule_locking 1
 
7641                 set supports_schedule_locking 0
 
7646     if { $supports_schedule_locking == -1 } {
 
7647         set supports_schedule_locking 0
 
7651     remote_file build delete $obj
 
7652     verbose "$me:  returning $supports_schedule_locking" 2
 
7653     return $supports_schedule_locking
 
7656 # Return 1 if compiler supports use of nested functions.  Otherwise,
 
7659 gdb_caching_proc support_nested_function_tests {
 
7660     # Compile a test program containing a nested function
 
7661     return [gdb_can_simple_compile nested_func {
 
7671 # gdb_target_symbol returns the provided symbol with the correct prefix
 
7672 # prepended.  (See gdb_target_symbol_prefix, above.)
 
7674 proc gdb_target_symbol { symbol } {
 
7675   set prefix [gdb_target_symbol_prefix]
 
7676   return "${prefix}${symbol}"
 
7679 # gdb_target_symbol_prefix_flags_asm returns a string that can be
 
7680 # added to gdb_compile options to define the C-preprocessor macro
 
7681 # SYMBOL_PREFIX with a value that can be prepended to symbols
 
7682 # for targets which require a prefix, such as underscore.
 
7684 # This version (_asm) defines the prefix without double quotes
 
7685 # surrounding the prefix.  It is used to define the macro
 
7686 # SYMBOL_PREFIX for assembly language files.  Another version, below,
 
7687 # is used for symbols in inline assembler in C/C++ files.
 
7689 # The lack of quotes in this version (_asm) makes it possible to
 
7690 # define supporting macros in the .S file.  (The version which
 
7691 # uses quotes for the prefix won't work for such files since it's
 
7692 # impossible to define a quote-stripping macro in C.)
 
7694 # It's possible to use this version (_asm) for C/C++ source files too,
 
7695 # but a string is usually required in such files; providing a version
 
7696 # (no _asm) which encloses the prefix with double quotes makes it
 
7697 # somewhat easier to define the supporting macros in the test case.
 
7699 proc gdb_target_symbol_prefix_flags_asm {} {
 
7700     set prefix [gdb_target_symbol_prefix]
 
7701     if {$prefix ne ""} {
 
7702         return "additional_flags=-DSYMBOL_PREFIX=$prefix"
 
7708 # gdb_target_symbol_prefix_flags returns the same string as
 
7709 # gdb_target_symbol_prefix_flags_asm, above, but with the prefix
 
7710 # enclosed in double quotes if there is a prefix.
 
7712 # See the comment for gdb_target_symbol_prefix_flags_asm for an
 
7713 # extended discussion.
 
7715 proc gdb_target_symbol_prefix_flags {} {
 
7716     set prefix [gdb_target_symbol_prefix]
 
7717     if {$prefix ne ""} {
 
7718         return "additional_flags=-DSYMBOL_PREFIX=\"$prefix\""
 
7724 # A wrapper for 'remote_exec host' that passes or fails a test.
 
7725 # Returns 0 if all went well, nonzero on failure.
 
7726 # TEST is the name of the test, other arguments are as for remote_exec.
 
7728 proc run_on_host { test program args } {
 
7729     verbose -log "run_on_host: $program $args"
 
7730     # remote_exec doesn't work properly if the output is set but the
 
7731     # input is the empty string -- so replace an empty input with
 
7733     if {[llength $args] > 1 && [lindex $args 1] == ""} {
 
7734         set args [lreplace $args 1 1 "/dev/null"]
 
7736     set result [eval remote_exec host [list $program] $args]
 
7737     verbose "result is $result"
 
7738     set status [lindex $result 0]
 
7739     set output [lindex $result 1]
 
7744         verbose -log "run_on_host failed: $output"
 
7745         if { $output == "spawn failed" } {
 
7754 # Return non-zero if "board_info debug_flags" mentions Fission.
 
7755 # http://gcc.gnu.org/wiki/DebugFission
 
7756 # Fission doesn't support everything yet.
 
7757 # This supports working around bug 15954.
 
7759 proc using_fission { } {
 
7760     set debug_flags [board_info [target_info name] debug_flags]
 
7761     return [regexp -- "-gsplit-dwarf" $debug_flags]
 
7764 # Search LISTNAME in uplevel LEVEL caller and set variables according to the
 
7765 # list of valid options with prefix PREFIX described by ARGSET.
 
7767 # The first member of each one- or two-element list in ARGSET defines the
 
7768 # name of a variable that will be added to the caller's scope.
 
7770 # If only one element is given to describe an option, it the value is
 
7771 # 0 if the option is not present in (the caller's) ARGS or 1 if
 
7774 # If two elements are given, the second element is the default value of
 
7775 # the variable.  This is then overwritten if the option exists in ARGS.
 
7776 # If EVAL, then subst is called on the value, which allows variables
 
7779 # Any parse_args elements in (the caller's) ARGS will be removed, leaving
 
7780 # any optional components.
 
7783 # proc myproc {foo args} {
 
7784 #   parse_list args 1 {{bar} {baz "abc"} {qux}} "-" false
 
7787 # myproc ABC -bar -baz DEF peanut butter
 
7788 # will define the following variables in myproc:
 
7789 # foo (=ABC), bar (=1), baz (=DEF), and qux (=0)
 
7790 # args will be the list {peanut butter}
 
7792 proc parse_list { level listname argset prefix eval } {
 
7793     upvar $level $listname args
 
7795     foreach argument $argset {
 
7796         if {[llength $argument] == 1} {
 
7797             # Normalize argument, strip leading/trailing whitespace.
 
7798             # Allows us to treat {foo} and { foo } the same.
 
7799             set argument [string trim $argument]
 
7801             # No default specified, so we assume that we should set
 
7802             # the value to 1 if the arg is present and 0 if it's not.
 
7803             # It is assumed that no value is given with the argument.
 
7804             set pattern "$prefix$argument"
 
7805             set result [lsearch -exact $args $pattern]
 
7807             if {$result != -1} then {
 
7809                 set args [lreplace $args $result $result]
 
7813             uplevel $level [list set $argument $value]
 
7814         } elseif {[llength $argument] == 2} {
 
7815             # There are two items in the argument.  The second is a
 
7816             # default value to use if the item is not present.
 
7817             # Otherwise, the variable is set to whatever is provided
 
7818             # after the item in the args.
 
7819             set arg [lindex $argument 0]
 
7820             set pattern "$prefix[lindex $arg 0]"
 
7821             set result [lsearch -exact $args $pattern]
 
7823             if {$result != -1} then {
 
7824                 set value [lindex $args [expr $result+1]]
 
7826                     set value [uplevel [expr $level + 1] [list subst $value]]
 
7828                 set args [lreplace $args $result [expr $result+1]]
 
7830                 set value [lindex $argument 1]
 
7832                     set value [uplevel $level [list subst $value]]
 
7835             uplevel $level [list set $arg $value]
 
7837             error "Badly formatted argument \"$argument\" in argument set"
 
7842 # Search the caller's args variable and set variables according to the list of
 
7843 # valid options described by ARGSET.
 
7845 proc parse_args { argset } {
 
7846     parse_list 2 args $argset "-" false
 
7848     # The remaining args should be checked to see that they match the
 
7849     # number of items expected to be passed into the procedure...
 
7852 # Process the caller's options variable and set variables according
 
7853 # to the list of valid options described by OPTIONSET.
 
7855 proc parse_options { optionset } {
 
7856     parse_list 2 options $optionset "" true
 
7858     # Require no remaining options.
 
7859     upvar 1 options options
 
7860     if { [llength $options] != 0 } {
 
7861         error "Options left unparsed: $options"
 
7865 # Capture the output of COMMAND in a string ignoring PREFIX (a regexp);
 
7866 # return that string.
 
7868 proc capture_command_output { command prefix } {
 
7873         -re "^[string_to_regexp ${command}]\r\n" {
 
7874             if { $prefix != "" } {
 
7880     if { $prefix != "" } {
 
7883                 # Nothing, we just move onto the next gdb_test_multiple
 
7884                 # call, which actually collects the command output.
 
7889     gdb_test_multiple "$command" "capture_command_output for $command" $code
 
7891     set output_string ""
 
7892     gdb_test_multiple "" "" {
 
7893         -re "^(\[^\r\n\]+\r\n)" {
 
7894             if { ![string equal $output_string ""] } {
 
7895                 set output_string [join [list $output_string $expect_out(1,string)] ""]
 
7897                 set output_string $expect_out(1,string)
 
7902         -re "^$gdb_prompt $" {
 
7906     set output_string [regsub "\r\n$" $output_string ""]
 
7907     return $output_string
 
7910 # A convenience function that joins all the arguments together, with a
 
7911 # regexp that matches exactly one end of line in between each argument.
 
7912 # This function is ideal to write the expected output of a GDB command
 
7913 # that generates more than a couple of lines, as this allows us to write
 
7914 # each line as a separate string, which is easier to read by a human
 
7917 proc multi_line { args } {
 
7918     if { [llength $args] == 1 } {
 
7919         set hint "forgot {*} before list argument?"
 
7920         error "multi_line called with one argument ($hint)"
 
7922     return [join $args "\r\n"]
 
7925 # Similar to the above, but while multi_line is meant to be used to
 
7926 # match GDB output, this one is meant to be used to build strings to
 
7927 # send as GDB input.
 
7929 proc multi_line_input { args } {
 
7930     return [join $args "\n"]
 
7933 # Return how many newlines there are in the given string.
 
7935 proc count_newlines { string } {
 
7936     return [regexp -all "\n" $string]
 
7939 # Return the version of the DejaGnu framework.
 
7941 # The return value is a list containing the major, minor and patch version
 
7942 # numbers.  If the version does not contain a minor or patch number, they will
 
7943 # be set to 0.  For example:
 
7949 proc dejagnu_version { } {
 
7950     # The frame_version variable is defined by DejaGnu, in runtest.exp.
 
7951     global frame_version
 
7953     verbose -log "DejaGnu version: $frame_version"
 
7954     verbose -log "Expect version: [exp_version]"
 
7955     verbose -log "Tcl version: [info tclversion]"
 
7957     set dg_ver [split $frame_version .]
 
7959     while { [llength $dg_ver] < 3 } {
 
7966 # Define user-defined command COMMAND using the COMMAND_LIST as the
 
7967 # command's definition.  The terminating "end" is added automatically.
 
7969 proc gdb_define_cmd {command command_list} {
 
7972     set input [multi_line_input {*}$command_list "end"]
 
7973     set test "define $command"
 
7975     gdb_test_multiple "define $command" $test {
 
7977             gdb_test_multiple $input $test {
 
7978                 -re "\r\n$gdb_prompt " {
 
7985 # Override the 'cd' builtin with a version that ensures that the
 
7986 # log file keeps pointing at the same file.  We need this because
 
7987 # unfortunately the path to the log file is recorded using an
 
7988 # relative path name, and, we sometimes need to close/reopen the log
 
7989 # after changing the current directory.  See get_compiler_info.
 
7991 rename cd builtin_cd
 
7995     # Get the existing log file flags.
 
7996     set log_file_info [log_file -info]
 
7998     # Split the flags into args and file name.
 
7999     set log_file_flags ""
 
8000     set log_file_file ""
 
8001     foreach arg [ split "$log_file_info" " "] {
 
8002         if [string match "-*" $arg] {
 
8003             lappend log_file_flags $arg
 
8005             lappend log_file_file $arg
 
8009     # If there was an existing file, ensure it is an absolute path, and then
 
8011     if { $log_file_file != "" } {
 
8012         set log_file_file [file normalize $log_file_file]
 
8014         log_file $log_file_flags "$log_file_file"
 
8017     # Call the builtin version of cd.
 
8021 # Return a list of all languages supported by GDB, suitable for use in
 
8022 # 'set language NAME'.  This doesn't include either the 'local' or
 
8024 proc gdb_supported_languages {} {
 
8025     return [list c objective-c c++ d go fortran modula-2 asm pascal \
 
8026                 opencl rust minimal ada]
 
8029 # Check if debugging is enabled for gdb.
 
8031 proc gdb_debug_enabled { } {
 
8034     # If not already read, get the debug setting from environment or board setting.
 
8035     if {![info exists gdbdebug]} {
 
8037         if [info exists env(GDB_DEBUG)] {
 
8038             set gdbdebug $env(GDB_DEBUG)
 
8039         } elseif [target_info exists gdb,debug] {
 
8040             set gdbdebug [target_info gdb,debug]
 
8046     # Ensure it not empty.
 
8047     return [expr { $gdbdebug != "" }]
 
8050 # Turn on debugging if enabled, or reset if already on.
 
8052 proc gdb_debug_init { } {
 
8056     if ![gdb_debug_enabled] {
 
8060     # First ensure logging is off.
 
8061     send_gdb "set logging enabled off\n"
 
8063     set debugfile [standard_output_file gdb.debug]
 
8064     send_gdb "set logging file $debugfile\n"
 
8066     send_gdb "set logging debugredirect\n"
 
8069     foreach entry [split $gdbdebug ,] {
 
8070       send_gdb "set debug $entry 1\n"
 
8073     # Now that everything is set, enable logging.
 
8074     send_gdb "set logging enabled on\n"
 
8076         -re "Copying output to $debugfile.*Redirecting debug output to $debugfile.*$gdb_prompt $" {}
 
8077         timeout { warning "Couldn't set logging file" }
 
8081 # Check if debugging is enabled for gdbserver.
 
8083 proc gdbserver_debug_enabled { } {
 
8084     # Always disabled for GDB only setups.
 
8088 # Open the file for logging gdb input
 
8090 proc gdb_stdin_log_init { } {
 
8091     gdb_persistent_global in_file
 
8093     if {[info exists in_file]} {
 
8094       # Close existing file.
 
8095       catch "close $in_file"
 
8098     set logfile [standard_output_file_with_gdb_instance gdb.in]
 
8099     set in_file [open $logfile w]
 
8102 # Write to the file for logging gdb input.
 
8103 # TYPE can be one of the following:
 
8104 # "standard" : Default. Standard message written to the log
 
8105 # "answer" : Answer to a question (eg "Y"). Not written the log.
 
8106 # "optional" : Optional message. Not written to the log.
 
8108 proc gdb_stdin_log_write { message {type standard} } {
 
8111     if {![info exists in_file]} {
 
8115     # Check message types.
 
8116     switch -regexp -- $type {
 
8125     # Write to the log and make sure the output is there, even in case
 
8127     puts -nonewline $in_file "$message"
 
8131 # Write the command line used to invocate gdb to the cmd file.
 
8133 proc gdb_write_cmd_file { cmdline } {
 
8134     set logfile [standard_output_file_with_gdb_instance gdb.cmd]
 
8135     set cmd_file [open $logfile w]
 
8136     puts $cmd_file $cmdline
 
8137     catch "close $cmd_file"
 
8140 # Compare contents of FILE to string STR.  Pass with MSG if equal, otherwise
 
8143 proc cmp_file_string { file str msg } {
 
8144     if { ![file exists $file]} {
 
8149     set caught_error [catch {
 
8150         set fp [open "$file" r]
 
8151         set file_contents [read $fp]
 
8154     if { $caught_error } then {
 
8155         error "$error_message"
 
8160     if { $file_contents == $str } {
 
8167 # Does the compiler support CTF debug output using '-gctf' compiler
 
8168 # flag?  If not then we should skip these tests.  We should also
 
8169 # skip them if libctf was explicitly disabled.
 
8171 gdb_caching_proc skip_ctf_tests {
 
8172     global enable_libctf
 
8174     if {$enable_libctf eq "no"} {
 
8178     set can_ctf [gdb_can_simple_compile ctfdebug {
 
8182     } executable "additional_flags=-gctf"]
 
8184     return [expr {!$can_ctf}]
 
8187 # Return 1 if compiler supports -gstatement-frontiers.  Otherwise,
 
8190 gdb_caching_proc supports_statement_frontiers {
 
8191     return [gdb_can_simple_compile supports_statement_frontiers {
 
8195     } executable "additional_flags=-gstatement-frontiers"]
 
8198 # Return 1 if compiler supports -mmpx -fcheck-pointer-bounds.  Otherwise,
 
8201 gdb_caching_proc supports_mpx_check_pointer_bounds {
 
8202     set flags "additional_flags=-mmpx additional_flags=-fcheck-pointer-bounds"
 
8203     return [gdb_can_simple_compile supports_mpx_check_pointer_bounds {
 
8207     } executable $flags]
 
8210 # Return 1 if compiler supports -fcf-protection=.  Otherwise,
 
8213 gdb_caching_proc supports_fcf_protection {
 
8214     return [gdb_can_simple_compile supports_fcf_protection {
 
8218   } executable "additional_flags=-fcf-protection=full"]
 
8221 # Return 1 if symbols were read in using -readnow.  Otherwise, return 0.
 
8223 proc readnow { args } {
 
8224     if { [llength $args] == 1 } {
 
8225         set re [lindex $args 0]
 
8231     # Given the listing from the following command can be very verbose, match
 
8232     # the patterns line-by-line.  This prevents timeouts from waiting for
 
8233     # too much data to come at once.
 
8234     set cmd "maint print objfiles $re"
 
8235     gdb_test_multiple $cmd "" -lbl {
 
8236         -re "\r\n.gdb_index: faked for \"readnow\"" {
 
8237             # Record the we've seen the above pattern.
 
8242             # We don't care about any other input.
 
8249 # Return index name if symbols were read in using an index.
 
8250 # Otherwise, return "".
 
8252 proc have_index { objfile } {
 
8255     set cmd "maint print objfiles $objfile"
 
8256     gdb_test_multiple $cmd "" -lbl {
 
8257         -re "\r\n.gdb_index: faked for \"readnow\"" {
 
8261         -re "\r\n.gdb_index:" {
 
8265         -re "\r\n.debug_names:" {
 
8266             set res "debug_names"
 
8270             # We don't care about any other input.
 
8277 # Return 1 if partial symbols are available.  Otherwise, return 0.
 
8279 proc psymtabs_p {  } {
 
8282     set cmd "maint info psymtab"
 
8283     gdb_test_multiple $cmd "" {
 
8284         -re "$cmd\r\n$gdb_prompt $" {
 
8295 # Verify that partial symtab expansion for $filename has state $readin.
 
8297 proc verify_psymtab_expanded { filename readin } {
 
8300     set cmd "maint info psymtab"
 
8301     set test "$cmd: $filename: $readin"
 
8302     set re [multi_line \
 
8303                 "  \{ psymtab \[^\r\n\]*$filename\[^\r\n\]*" \
 
8307     gdb_test_multiple $cmd $test {
 
8308         -re "$cmd\r\n$gdb_prompt $" {
 
8309             unsupported $gdb_test_name
 
8317 # Add a .gdb_index section to PROGRAM.
 
8318 # PROGRAM is assumed to be the output of standard_output_file.
 
8319 # Returns the 0 if there is a failure, otherwise 1.
 
8321 # STYLE controls which style of index to add, if needed.  The empty
 
8322 # string (the default) means .gdb_index; "-dwarf-5" means .debug_names.
 
8324 proc add_gdb_index { program {style ""} } {
 
8325     global srcdir GDB env
 
8326     set contrib_dir "$srcdir/../contrib"
 
8327     set env(GDB) [append_gdb_data_directory_option $GDB]
 
8328     set result [catch "exec $contrib_dir/gdb-add-index.sh $style $program" output]
 
8329     if { $result != 0 } {
 
8330         verbose -log "result is $result"
 
8331         verbose -log "output is $output"
 
8338 # Add a .gdb_index section to PROGRAM, unless it alread has an index
 
8339 # (.gdb_index/.debug_names).  Gdb doesn't support building an index from a
 
8340 # program already using one.  Return 1 if a .gdb_index was added, return 0
 
8341 # if it already contained an index, and -1 if an error occurred.
 
8343 # STYLE controls which style of index to add, if needed.  The empty
 
8344 # string (the default) means .gdb_index; "-dwarf-5" means .debug_names.
 
8346 proc ensure_gdb_index { binfile {style ""} } {
 
8349     set testfile [file tail $binfile]
 
8350     set test "check if index present"
 
8353     gdb_test_multiple "mt print objfiles ${testfile}" $test -lbl {
 
8354         -re "\r\n\\.gdb_index: version ${decimal}(?=\r\n)" {
 
8356             gdb_test_lines "" $gdb_test_name ".*"
 
8358         -re "\r\n\\.debug_names: exists(?=\r\n)" {
 
8360             gdb_test_lines "" $gdb_test_name ".*"
 
8362         -re "\r\n(Cooked index in use|Psymtabs)(?=\r\n)" {
 
8363             gdb_test_lines "" $gdb_test_name ".*"
 
8365         -re ".gdb_index: faked for \"readnow\"" {
 
8367             gdb_test_lines "" $gdb_test_name ".*"
 
8378     if { $has_readnow } {
 
8382     if { [add_gdb_index $binfile $style] == "1" } {
 
8389 # Return 1 if executable contains .debug_types section.  Otherwise, return 0.
 
8391 proc debug_types { } {
 
8394     set cmd "maint info sections"
 
8395     gdb_test_multiple $cmd "" {
 
8396         -re -wrap "at $hex: .debug_types.*" {
 
8407 # Return the addresses in the line table for FILE for which is_stmt is true.
 
8409 proc is_stmt_addresses { file } {
 
8415     gdb_test_multiple "maint info line-table $file" "" {
 
8416         -re "\r\n$decimal\[ \t\]+$decimal\[ \t\]+($hex)\[ \t\]+Y\[^\r\n\]*" {
 
8417             lappend is_stmt $expect_out(1,string)
 
8427 # Return 1 if hex number VAL is an element of HEXLIST.
 
8429 proc hex_in_list { val hexlist } {
 
8430     # Normalize val by removing 0x prefix, and leading zeros.
 
8431     set val [regsub ^0x $val ""]
 
8432     set val [regsub ^0+ $val "0"]
 
8435     set index [lsearch -regexp $hexlist $re]
 
8436     return [expr $index != -1]
 
8439 # Override proc NAME to proc OVERRIDE for the duration of the execution of
 
8442 proc with_override { name override body } {
 
8443     # Implementation note: It's possible to implement the override using
 
8444     # rename, like this:
 
8445     #   rename $name save_$name
 
8446     #   rename $override $name
 
8447     #   set code [catch {uplevel 1 $body} result]
 
8448     #   rename $name $override
 
8449     #   rename save_$name $name
 
8450     # but there are two issues here:
 
8451     # - the save_$name might clash with an existing proc
 
8452     # - the override is no longer available under its original name during
 
8454     # So, we use this more elaborate but cleaner mechanism.
 
8456     # Save the old proc, if it exists.
 
8457     if { [info procs $name] != "" } {
 
8458         set old_args [info args $name]
 
8459         set old_body [info body $name]
 
8465     # Install the override.
 
8466     set new_args [info args $override]
 
8467     set new_body [info body $override]
 
8468     eval proc $name {$new_args} {$new_body}
 
8471     set code [catch {uplevel 1 $body} result]
 
8473     # Restore old proc if it existed on entry, else delete it.
 
8475         eval proc $name {$old_args} {$old_body}
 
8480     # Return as appropriate.
 
8482         global errorInfo errorCode
 
8483         return -code error -errorinfo $errorInfo -errorcode $errorCode $result
 
8484     } elseif { $code > 1 } {
 
8485         return -code $code $result
 
8491 # Setup tuiterm.exp environment.  To be used in test-cases instead of
 
8492 # "load_lib tuiterm.exp".  Calls initialization function and schedules
 
8493 # finalization function.
 
8494 proc tuiterm_env { } {
 
8495     load_lib tuiterm.exp
 
8498 # Dejagnu has a version of note, but usage is not allowed outside of dejagnu.
 
8499 # Define a local version.
 
8500 proc gdb_note { message } {
 
8501     verbose -- "NOTE: $message" 0
 
8504 # Return 1 if compiler supports -fuse-ld=gold, otherwise return 0.
 
8505 gdb_caching_proc have_fuse_ld_gold {
 
8506     set me "have_fuse_ld_gold"
 
8507     set flags "additional_flags=-fuse-ld=gold"
 
8508     set src { int main() { return 0; } }
 
8509     return [gdb_simple_compile $me $src executable $flags]
 
8512 # Return 1 if linker supports -Ttext-segment, otherwise return 0.
 
8513 gdb_caching_proc linker_supports_Ttext_segment_flag {
 
8514     set me "linker_supports_Ttext_segment_flag"
 
8515     set flags additional_flags="-Wl,-Ttext-segment=0x7000000"
 
8516     set src { int main() { return 0; } }
 
8517     return [gdb_simple_compile $me $src executable $flags]
 
8520 # Return 1 if linker supports -Ttext, otherwise return 0.
 
8521 gdb_caching_proc linker_supports_Ttext_flag {
 
8522     set me "linker_supports_Ttext_flag"
 
8523     set flags additional_flags="-Wl,-Ttext=0x7000000"
 
8524     set src { int main() { return 0; } }
 
8525     return [gdb_simple_compile $me $src executable $flags]
 
8528 # Return 1 if linker supports --image-base, otherwise 0.
 
8529 gdb_caching_proc linker_supports_image_base_flag {
 
8530     set me "linker_supports_image_base_flag"
 
8531     set flags additional_flags="-Wl,--image-base=0x7000000"
 
8532     set src { int main() { return 0; } }
 
8533     return [gdb_simple_compile $me $src executable $flags]
 
8537 # Return 1 if compiler supports scalar_storage_order attribute, otherwise
 
8539 gdb_caching_proc supports_scalar_storage_order_attribute {
 
8540     set me "supports_scalar_storage_order_attribute"
 
8545         } __attribute__((scalar_storage_order("little-endian")));
 
8548         } __attribute__((scalar_storage_order("big-endian")));
 
8552             sle.v = sbe.v = 0x11223344;
 
8553             int same = memcmp (&sle, &sbe, sizeof (int)) == 0;
 
8558     if { ![gdb_simple_compile $me $src executable ""] } {
 
8562     set result [remote_exec target $obj]
 
8563     set status [lindex $result 0]
 
8564     set output [lindex $result 1]
 
8565     if { $output != "" } {
 
8572 # Return 1 if compiler supports __GNUC__, otherwise return 0.
 
8573 gdb_caching_proc supports_gnuc {
 
8574     set me "supports_gnuc"
 
8580     return [gdb_simple_compile $me $src object ""]
 
8583 # Return 1 if target supports mpx, otherwise return 0.
 
8584 gdb_caching_proc have_mpx {
 
8588     if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
 
8589         verbose "$me: target does not support mpx, returning 0" 2
 
8593     # Compile a test program.
 
8595        #include "nat/x86-cpuid.h"
 
8598           unsigned int eax, ebx, ecx, edx;
 
8600           if (!__get_cpuid (1, &eax, &ebx, &ecx, &edx))
 
8603           if ((ecx & bit_OSXSAVE) == bit_OSXSAVE)
 
8605               if (__get_cpuid_max (0, (void *)0) < 7)
 
8608                 __cpuid_count (7, 0, eax, ebx, ecx, edx);
 
8610                 if ((ebx & bit_MPX) == bit_MPX)
 
8617     set compile_flags "incdir=${srcdir}/.."
 
8618     if {![gdb_simple_compile $me $src executable $compile_flags]} {
 
8622     set result [remote_exec target $obj]
 
8623     set status [lindex $result 0]
 
8624     set output [lindex $result 1]
 
8625     if { $output != "" } {
 
8629     remote_file build delete $obj
 
8631     if { $status == 0 } {
 
8632         verbose "$me:  returning $status" 2
 
8636     # Compile program with -mmpx -fcheck-pointer-bounds, try to trigger
 
8637     # 'No MPX support', in other words, see if kernel supports mpx.
 
8638     set src { int main (void) { return 0; } }
 
8640     append comp_flags " additional_flags=-mmpx"
 
8641     append comp_flags " additional_flags=-fcheck-pointer-bounds"
 
8642     if {![gdb_simple_compile $me-2 $src executable $comp_flags]} {
 
8646     set result [remote_exec target $obj]
 
8647     set status [lindex $result 0]
 
8648     set output [lindex $result 1]
 
8649     set status [expr ($status == 0) \
 
8650                     && ![regexp "^No MPX support\r?\n" $output]]
 
8652     remote_file build delete $obj
 
8654     verbose "$me:  returning $status" 2
 
8658 # Return 1 if target supports avx, otherwise return 0.
 
8659 gdb_caching_proc have_avx {
 
8663     if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
 
8664         verbose "$me: target does not support avx, returning 0" 2
 
8668     # Compile a test program.
 
8670        #include "nat/x86-cpuid.h"
 
8673           unsigned int eax, ebx, ecx, edx;
 
8675         if (!x86_cpuid (1, &eax, &ebx, &ecx, &edx))
 
8678         if ((ecx & (bit_AVX | bit_OSXSAVE)) == (bit_AVX | bit_OSXSAVE))
 
8684     set compile_flags "incdir=${srcdir}/.."
 
8685     if {![gdb_simple_compile $me $src executable $compile_flags]} {
 
8689     set result [remote_exec target $obj]
 
8690     set status [lindex $result 0]
 
8691     set output [lindex $result 1]
 
8692     if { $output != "" } {
 
8696     remote_file build delete $obj
 
8698     verbose "$me: returning $status" 2
 
8703 # - require EXPR VAL
 
8704 # - require EXPR OP VAL
 
8705 # In the first case, OP is ==.
 
8707 # Require EXPR OP VAL, where EXPR is evaluated in caller context.  If not,
 
8708 # return in the caller's context.
 
8710 proc require { fn arg1 {arg2 ""} } {
 
8711     if { $arg2 == "" } {
 
8718     set res [uplevel 1 $fn]
 
8719     if { [expr $res $op $val] } {
 
8723     switch "$fn $op $val" {
 
8724         "gdb_skip_xml_test == 0" { set msg "missing xml support" }
 
8725         "ensure_gdb_index $binfile != -1" -
 
8726         "ensure_gdb_index $binfile -dwarf-5 != -1" {
 
8727             set msg "Couldn't ensure index in binfile"
 
8729         "use_gdb_stub == 0" {
 
8730             set msg "Remote stub used"
 
8732         default { set msg "$fn != $val" }
 
8736     return -code return 0
 
8739 # Wait up to ::TIMEOUT seconds for file PATH to exist on the target system.
 
8740 # Return 1 if it does exist, 0 otherwise.
 
8742 proc target_file_exists_with_timeout { path } {
 
8743     for {set i 0} {$i < $::timeout} {incr i} {
 
8744         if { [remote_file target exists $path] } {
 
8754 gdb_caching_proc has_hw_wp_support {
 
8755     # Power 9, proc rev 2.2 does not support HW watchpoints due to HW bug.
 
8756     # Need to use a runtime test to determine if the Power processor has
 
8757     # support for HW watchpoints.
 
8758     global srcdir subdir gdb_prompt inferior_exited_re
 
8760     set compile_flags {debug nowarnings quiet}
 
8761     set me "has_hw_wp_support"
 
8763     # Compile a test program to test if HW watchpoints are supported
 
8774     if {![gdb_simple_compile $me $src executable $compile_flags]} {
 
8780     gdb_reinitialize_dir $srcdir/$subdir
 
8784         set has_hw_wp_support 0
 
8785         return $has_hw_wp_support
 
8788     # The goal is to determine if HW watchpoints are available in general.
 
8789     # Use "watch" and then check if gdb responds with hardware watch point.
 
8790     set test "watch local"
 
8792     gdb_test_multiple  $test "Check for HW watchpoint support" {
 
8793         -re ".*Hardware watchpoint.*" {
 
8794             #  HW watchpoint supported by platform
 
8795             verbose -log "\n$me: Hardware watchpoint detected"
 
8796             set has_hw_wp_support 1
 
8798         -re ".*$gdb_prompt $" {
 
8799             set has_hw_wp_support 0
 
8800             verbose -log "\n$me: Default, hardware watchpoint not deteced"
 
8805     remote_file build delete $obj
 
8807     verbose "$me: returning $has_hw_wp_support" 2
 
8808     return $has_hw_wp_support
 
8811 # Return a list of all the accepted values of the set command SET_CMD.
 
8813 proc get_set_option_choices {set_cmd} {
 
8818     set test "complete $set_cmd"
 
8819     gdb_test_multiple "complete $set_cmd " "$test" {
 
8820         -re "$set_cmd (\[^\r\n\]+)\r\n" {
 
8821             lappend values $expect_out(1,string)
 
8824         -re "$gdb_prompt " {
 
8831 # Return the compiler that can generate 32-bit ARM executables.  Used
 
8832 # when testing biarch support on Aarch64.  If ARM_CC_FOR_TARGET is
 
8833 # set, use that.  If not, try a few common compiler names, making sure
 
8834 # that the executable they produce can run.
 
8836 gdb_caching_proc arm_cc_for_target {
 
8837     if {[info exists ::ARM_CC_FOR_TARGET]} {
 
8838         # If the user specified the compiler explicitly, then don't
 
8839         # check whether the resulting binary runs outside GDB.  Assume
 
8840         # that it does, and if it turns out it doesn't, then the user
 
8841         # should get loud FAILs, instead of UNSUPPORTED.
 
8842         return $::ARM_CC_FOR_TARGET
 
8845     # Fallback to a few common compiler names.  Also confirm the
 
8846     # produced binary actually runs on the system before declaring
 
8847     # we've found the right compiler.
 
8849     if [istarget "*-linux*-*"] {
 
8851             arm-linux-gnueabi-gcc
 
8852             arm-none-linux-gnueabi-gcc
 
8853             arm-linux-gnueabihf-gcc
 
8859     foreach compiler $compilers {
 
8860         if {![is_remote host] && [which $compiler] == 0} {
 
8861             # Avoid "default_target_compile: Can't find
 
8862             # $compiler." warning issued from gdb_compile.
 
8866         set src { int main() { return 0; } }
 
8867         if {[gdb_simple_compile aarch64-32bit \
 
8869                  executable [list compiler=$compiler]]} {
 
8871             set result [remote_exec target $obj]
 
8872             set status [lindex $result 0]
 
8873             set output [lindex $result 1]
 
8877             if { $output == "" && $status == 0} {
 
8886 # Step until the pattern REGEXP is found.  Step at most
 
8887 # MAX_STEPS times, but stop stepping once REGEXP is found.
 
8889 # If REGEXP is found then a single pass is emitted, otherwise, after
 
8890 # MAX_STEPS steps, a single fail is emitted.
 
8892 # TEST_NAME is the name used in the pass/fail calls.
 
8894 proc gdb_step_until { regexp {test_name ""} {max_steps 10} } {
 
8895     if { $test_name == "" } {
 
8896         set test_name "stepping until regexp"
 
8900     gdb_test_multiple "step" "$test_name" {
 
8901         -re "$regexp\r\n$::gdb_prompt $" {
 
8904         -re ".*$::gdb_prompt $" {
 
8905             if {$count < $max_steps} {
 
8916 # Check if the compiler emits epilogue information associated
 
8917 # with the closing brace or with the last statement line.
 
8919 # This proc restarts GDB
 
8921 # Returns True if it is associated with the closing brace,
 
8922 # False if it is the last statement
 
8923 gdb_caching_proc have_epilogue_line_info {
 
8932     if {![gdb_simple_compile "simple_program" $main]} {
 
8938     gdb_test_multiple "info line 6" "epilogue test" {
 
8939         -re -wrap ".*starts at address.*and ends at.*" {
 
8948 # Always load compatibility stuff.