Skip a few tests on targets that can't use the "run" commmand.
[external/binutils.git] / gdb / testsuite / lib / gdb.exp
1 # Copyright 1992-2017 Free Software Foundation, Inc.
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 3 of the License, or
6 # (at your option) any later version.
7 #
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.
12 #
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/>.
15
16 # This file was written by Fred Fish. (fnf@cygnus.com)
17
18 # Generic gdb subroutines that should work for any target.  If these
19 # need to be modified for any target, it can be done with a variable
20 # or by passing arguments.
21
22 if {$tool == ""} {
23     # Tests would fail, logs on get_compiler_info() would be missing.
24     send_error "`site.exp' not found, run `make site.exp'!\n"
25     exit 2
26 }
27
28 load_lib libgloss.exp
29 load_lib cache.exp
30 load_lib gdb-utils.exp
31 load_lib memory.exp
32
33 global GDB
34
35 # The spawn ID used for I/O interaction with the inferior.  For native
36 # targets, or remote targets that can do I/O through GDB
37 # (semi-hosting) this will be the same as the host/GDB's spawn ID.
38 # Otherwise, the board may set this to some other spawn ID.  E.g.,
39 # when debugging with GDBserver, this is set to GDBserver's spawn ID,
40 # so input/output is done on gdbserver's tty.
41 global inferior_spawn_id
42
43 if [info exists TOOL_EXECUTABLE] {
44     set GDB $TOOL_EXECUTABLE
45 }
46 if ![info exists GDB] {
47     if ![is_remote host] {
48         set GDB [findfile $base_dir/../../gdb/gdb "$base_dir/../../gdb/gdb" [transform gdb]]
49     } else {
50         set GDB [transform gdb]
51     }
52 }
53 verbose "using GDB = $GDB" 2
54
55 # GDBFLAGS is available for the user to set on the command line.
56 # E.g. make check RUNTESTFLAGS=GDBFLAGS=mumble
57 # Testcases may use it to add additional flags, but they must:
58 # - append new flags, not overwrite
59 # - restore the original value when done
60 global GDBFLAGS
61 if ![info exists GDBFLAGS] {
62     set GDBFLAGS ""
63 }
64 verbose "using GDBFLAGS = $GDBFLAGS" 2
65
66 # Make the build data directory available to tests.
67 set BUILD_DATA_DIRECTORY "[pwd]/../data-directory"
68
69 # INTERNAL_GDBFLAGS contains flags that the testsuite requires.
70 global INTERNAL_GDBFLAGS
71 if ![info exists INTERNAL_GDBFLAGS] {
72     set INTERNAL_GDBFLAGS "-nw -nx -data-directory $BUILD_DATA_DIRECTORY"
73 }
74
75 # The variable gdb_prompt is a regexp which matches the gdb prompt.
76 # Set it if it is not already set.  This is also set by default_gdb_init
77 # but it's not clear what removing one of them will break.
78 # See with_gdb_prompt for more details on prompt handling.
79 global gdb_prompt
80 if ![info exists gdb_prompt] then {
81     set gdb_prompt "\\(gdb\\)"
82 }
83
84 # A regexp that matches the pagination prompt.
85 set pagination_prompt [string_to_regexp "---Type <return> to continue, or q <return> to quit---"]
86
87 # The variable fullname_syntax_POSIX is a regexp which matches a POSIX 
88 # absolute path ie. /foo/ 
89 set fullname_syntax_POSIX {/[^\n]*/}
90 # The variable fullname_syntax_UNC is a regexp which matches a Windows 
91 # UNC path ie. \\D\foo\ 
92 set fullname_syntax_UNC {\\\\[^\\]+\\[^\n]+\\}
93 # The variable fullname_syntax_DOS_CASE is a regexp which matches a 
94 # particular DOS case that GDB most likely will output
95 # ie. \foo\, but don't match \\.*\ 
96 set fullname_syntax_DOS_CASE {\\[^\\][^\n]*\\}
97 # The variable fullname_syntax_DOS is a regexp which matches a DOS path
98 # ie. a:\foo\ && a:foo\ 
99 set fullname_syntax_DOS {[a-zA-Z]:[^\n]*\\}
100 # The variable fullname_syntax is a regexp which matches what GDB considers
101 # an absolute path. It is currently debatable if the Windows style paths 
102 # d:foo and \abc should be considered valid as an absolute path.
103 # Also, the purpse of this regexp is not to recognize a well formed 
104 # absolute path, but to say with certainty that a path is absolute.
105 set fullname_syntax "($fullname_syntax_POSIX|$fullname_syntax_UNC|$fullname_syntax_DOS_CASE|$fullname_syntax_DOS)"
106
107 # Needed for some tests under Cygwin.
108 global EXEEXT
109 global env
110
111 if ![info exists env(EXEEXT)] {
112     set EXEEXT ""
113 } else {
114     set EXEEXT $env(EXEEXT)
115 }
116
117 set octal "\[0-7\]+"
118
119 set inferior_exited_re "(\\\[Inferior \[0-9\]+ \\(.*\\) exited)"
120
121 # A regular expression that matches a value history number.
122 # E.g., $1, $2, etc.
123 set valnum_re "\\\$$decimal"
124
125 ### Only procedures should come after this point.
126
127 #
128 # gdb_version -- extract and print the version number of GDB
129 #
130 proc default_gdb_version {} {
131     global GDB
132     global INTERNAL_GDBFLAGS GDBFLAGS
133     global gdb_prompt
134     global inotify_pid
135
136     if {[info exists inotify_pid]} {
137         eval exec kill $inotify_pid
138     }
139
140     set output [remote_exec host "$GDB $INTERNAL_GDBFLAGS --version"]
141     set tmp [lindex $output 1]
142     set version ""
143     regexp " \[0-9\]\[^ \t\n\r\]+" "$tmp" version
144     if ![is_remote host] {
145         clone_output "[which $GDB] version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
146     } else {
147         clone_output "$GDB on remote host version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
148     }
149 }
150
151 proc gdb_version { } {
152     return [default_gdb_version]
153 }
154
155 #
156 # gdb_unload -- unload a file if one is loaded
157 # Return 0 on success, -1 on error.
158 #
159
160 proc gdb_unload {} {
161     global verbose
162     global GDB
163     global gdb_prompt
164     send_gdb "file\n"
165     gdb_expect 60 {
166         -re "No executable file now\[^\r\n\]*\[\r\n\]" { exp_continue }
167         -re "No symbol file now\[^\r\n\]*\[\r\n\]" { exp_continue }
168         -re "A program is being debugged already.*Are you sure you want to change the file.*y or n. $" {
169             send_gdb "y\n"
170             exp_continue
171         }
172         -re "Discard symbol table from .*y or n.*$" {
173             send_gdb "y\n"
174             exp_continue
175         }
176         -re "$gdb_prompt $" {}
177         timeout {
178             perror "couldn't unload file in $GDB (timeout)."
179             return -1
180         }
181     }
182     return 0
183 }
184
185 # Many of the tests depend on setting breakpoints at various places and
186 # running until that breakpoint is reached.  At times, we want to start
187 # with a clean-slate with respect to breakpoints, so this utility proc 
188 # lets us do this without duplicating this code everywhere.
189 #
190
191 proc delete_breakpoints {} {
192     global gdb_prompt
193
194     # we need a larger timeout value here or this thing just confuses
195     # itself.  May need a better implementation if possible. - guo
196     #
197     set timeout 100
198
199     set msg "delete all breakpoints in delete_breakpoints"
200     set deleted 0
201     gdb_test_multiple "delete breakpoints" "$msg" {
202         -re "Delete all breakpoints.*y or n.*$" {
203             send_gdb "y\n"
204             exp_continue
205         }
206         -re "$gdb_prompt $" {
207             set deleted 1
208         }
209     }
210
211     if {$deleted} {
212         # Confirm with "info breakpoints".
213         set deleted 0
214         set msg "info breakpoints"
215         gdb_test_multiple $msg $msg {
216             -re "No breakpoints or watchpoints..*$gdb_prompt $" {
217                 set deleted 1
218             }
219             -re "$gdb_prompt $" {
220             }
221         }
222     }
223
224     if {!$deleted} {
225         perror "breakpoints not deleted"
226     }
227 }
228
229 # Returns true iff the target supports using the "run" command.
230
231 proc target_can_use_run_cmd {} {
232     if [target_info exists use_gdb_stub] {
233         # In this case, when we connect, the inferior is already
234         # running.
235         return 0
236     }
237
238     # Assume yes.
239     return 1
240 }
241
242 # Generic run command.
243 #
244 # The second pattern below matches up to the first newline *only*.
245 # Using ``.*$'' could swallow up output that we attempt to match
246 # elsewhere.
247 #
248 # N.B. This function does not wait for gdb to return to the prompt,
249 # that is the caller's responsibility.
250
251 proc gdb_run_cmd {args} {
252     global gdb_prompt use_gdb_stub
253
254     foreach command [gdb_init_commands] {
255         send_gdb "$command\n"
256         gdb_expect 30 {
257             -re "$gdb_prompt $" { }
258             default {
259                 perror "gdb_init_command for target failed"
260                 return
261             }
262         }
263     }
264
265     if $use_gdb_stub {
266         if [target_info exists gdb,do_reload_on_run] {
267             if { [gdb_reload] != 0 } {
268                 return
269             }
270             send_gdb "continue\n"
271             gdb_expect 60 {
272                 -re "Continu\[^\r\n\]*\[\r\n\]" {}
273                 default {}
274             }
275             return
276         }
277
278         if [target_info exists gdb,start_symbol] {
279             set start [target_info gdb,start_symbol]
280         } else {
281             set start "start"
282         }
283         send_gdb  "jump *$start\n"
284         set start_attempt 1
285         while { $start_attempt } {
286             # Cap (re)start attempts at three to ensure that this loop
287             # always eventually fails.  Don't worry about trying to be
288             # clever and not send a command when it has failed.
289             if [expr $start_attempt > 3] {
290                 perror "Jump to start() failed (retry count exceeded)"
291                 return
292             }
293             set start_attempt [expr $start_attempt + 1]
294             gdb_expect 30 {
295                 -re "Continuing at \[^\r\n\]*\[\r\n\]" {
296                     set start_attempt 0
297                 }
298                 -re "No symbol \"_start\" in current.*$gdb_prompt $" {
299                     perror "Can't find start symbol to run in gdb_run"
300                     return
301                 }
302                 -re "No symbol \"start\" in current.*$gdb_prompt $" {
303                     send_gdb "jump *_start\n"
304                 }
305                 -re "No symbol.*context.*$gdb_prompt $" {
306                     set start_attempt 0
307                 }
308                 -re "Line.* Jump anyway.*y or n. $" {
309                     send_gdb "y\n"
310                 }
311                 -re "The program is not being run.*$gdb_prompt $" {
312                     if { [gdb_reload] != 0 } {
313                         return
314                     }
315                     send_gdb "jump *$start\n"
316                 }
317                 timeout {
318                     perror "Jump to start() failed (timeout)"
319                     return
320                 }
321             }
322         }
323         return
324     }
325
326     if [target_info exists gdb,do_reload_on_run] {
327         if { [gdb_reload] != 0 } {
328             return
329         }
330     }
331     send_gdb "run $args\n"
332 # This doesn't work quite right yet.
333 # Use -notransfer here so that test cases (like chng-sym.exp)
334 # may test for additional start-up messages.
335    gdb_expect 60 {
336         -re "The program .* has been started already.*y or n. $" {
337             send_gdb "y\n"
338             exp_continue
339         }
340         -notransfer -re "Starting program: \[^\r\n\]*" {}
341         -notransfer -re "$gdb_prompt $" {
342             # There is no more input expected.
343         }
344     }
345 }
346
347 # Generic start command.  Return 0 if we could start the program, -1
348 # if we could not.
349 #
350 # N.B. This function does not wait for gdb to return to the prompt,
351 # that is the caller's responsibility.
352
353 proc gdb_start_cmd {args} {
354     global gdb_prompt use_gdb_stub
355
356     foreach command [gdb_init_commands] {
357         send_gdb "$command\n"
358         gdb_expect 30 {
359             -re "$gdb_prompt $" { }
360             default {
361                 perror "gdb_init_command for target failed"
362                 return -1
363             }
364         }
365     }
366
367     if $use_gdb_stub {
368         return -1
369     }
370
371     send_gdb "start $args\n"
372     # Use -notransfer here so that test cases (like chng-sym.exp)
373     # may test for additional start-up messages.
374     gdb_expect 60 {
375         -re "The program .* has been started already.*y or n. $" {
376             send_gdb "y\n"
377             exp_continue
378         }
379         -notransfer -re "Starting program: \[^\r\n\]*" {
380             return 0
381         }
382     }
383     return -1
384 }
385
386 # Generic starti command.  Return 0 if we could start the program, -1
387 # if we could not.
388 #
389 # N.B. This function does not wait for gdb to return to the prompt,
390 # that is the caller's responsibility.
391
392 proc gdb_starti_cmd {args} {
393     global gdb_prompt use_gdb_stub
394
395     foreach command [gdb_init_commands] {
396         send_gdb "$command\n"
397         gdb_expect 30 {
398             -re "$gdb_prompt $" { }
399             default {
400                 perror "gdb_init_command for target failed"
401                 return -1
402             }
403         }
404     }
405
406     if $use_gdb_stub {
407         return -1
408     }
409
410     send_gdb "starti $args\n"
411     gdb_expect 60 {
412         -re "The program .* has been started already.*y or n. $" {
413             send_gdb "y\n"
414             exp_continue
415         }
416         -re "Starting program: \[^\r\n\]*" {
417             return 0
418         }
419     }
420     return -1
421 }
422
423 # Set a breakpoint at FUNCTION.  If there is an additional argument it is
424 # a list of options; the supported options are allow-pending, temporary,
425 # message, no-message, and passfail.
426 # The result is 1 for success, 0 for failure.
427 #
428 # Note: The handling of message vs no-message is messed up, but it's based
429 # on historical usage.  By default this function does not print passes,
430 # only fails.
431 # no-message: turns off printing of fails (and passes, but they're already off)
432 # message: turns on printing of passes (and fails, but they're already on)
433
434 proc gdb_breakpoint { function args } {
435     global gdb_prompt
436     global decimal
437
438     set pending_response n
439     if {[lsearch -exact $args allow-pending] != -1} {
440         set pending_response y
441     }
442
443     set break_command "break"
444     set break_message "Breakpoint"
445     if {[lsearch -exact $args temporary] != -1} {
446         set break_command "tbreak"
447         set break_message "Temporary breakpoint"
448     }
449
450     set print_pass 0
451     set print_fail 1
452     set no_message_loc [lsearch -exact $args no-message]
453     set message_loc [lsearch -exact $args message]
454     # The last one to appear in args wins.
455     if { $no_message_loc > $message_loc } {
456         set print_fail 0
457     } elseif { $message_loc > $no_message_loc } {
458         set print_pass 1
459     }
460
461     set test_name "setting breakpoint at $function"
462
463     send_gdb "$break_command $function\n"
464     # The first two regexps are what we get with -g, the third is without -g.
465     gdb_expect 30 {
466         -re "$break_message \[0-9\]* at .*: file .*, line $decimal.\r\n$gdb_prompt $" {}
467         -re "$break_message \[0-9\]*: file .*, line $decimal.\r\n$gdb_prompt $" {}
468         -re "$break_message \[0-9\]* at .*$gdb_prompt $" {}
469         -re "$break_message \[0-9\]* \\(.*\\) pending.*$gdb_prompt $" {
470                 if {$pending_response == "n"} {
471                         if { $print_fail } {
472                                 fail $test_name
473                         }
474                         return 0
475                 }
476         }
477         -re "Make breakpoint pending.*y or \\\[n\\\]. $" { 
478                 send_gdb "$pending_response\n"
479                 exp_continue
480         }
481         -re "A problem internal to GDB has been detected" {
482                 if { $print_fail } {
483                     fail "$test_name (GDB internal error)"
484                 }
485                 gdb_internal_error_resync
486                 return 0
487         }
488         -re "$gdb_prompt $" {
489                 if { $print_fail } {
490                         fail $test_name
491                 }
492                 return 0
493         }
494         eof {
495                 if { $print_fail } {
496                         fail "$test_name (eof)"
497                 }
498                 return 0
499         }
500         timeout {
501                 if { $print_fail } {
502                         fail "$test_name (timeout)"
503                 }
504                 return 0
505         }
506     }
507     if { $print_pass } {
508         pass $test_name
509     }
510     return 1
511 }    
512
513 # Set breakpoint at function and run gdb until it breaks there.
514 # Since this is the only breakpoint that will be set, if it stops
515 # at a breakpoint, we will assume it is the one we want.  We can't
516 # just compare to "function" because it might be a fully qualified,
517 # single quoted C++ function specifier.
518 #
519 # If there are additional arguments, pass them to gdb_breakpoint.
520 # We recognize no-message/message ourselves.
521 # The default is no-message.
522 # no-message is messed up here, like gdb_breakpoint: to preserve
523 # historical usage fails are always printed by default.
524 # no-message: turns off printing of fails (and passes, but they're already off)
525 # message: turns on printing of passes (and fails, but they're already on)
526
527 proc runto { function args } {
528     global gdb_prompt
529     global decimal
530
531     delete_breakpoints
532
533     # Default to "no-message".
534     set args "no-message $args"
535
536     set print_pass 0
537     set print_fail 1
538     set no_message_loc [lsearch -exact $args no-message]
539     set message_loc [lsearch -exact $args message]
540     # The last one to appear in args wins.
541     if { $no_message_loc > $message_loc } {
542         set print_fail 0
543     } elseif { $message_loc > $no_message_loc } {
544         set print_pass 1
545     }
546
547     set test_name "running to $function in runto"
548
549     # We need to use eval here to pass our varargs args to gdb_breakpoint
550     # which is also a varargs function.
551     # But we also have to be careful because $function may have multiple
552     # elements, and we don't want Tcl to move the remaining elements after
553     # the first to $args.  That is why $function is wrapped in {}.
554     if ![eval gdb_breakpoint {$function} $args] {
555         return 0
556     }
557
558     gdb_run_cmd
559     
560     # the "at foo.c:36" output we get with -g.
561     # the "in func" output we get without -g.
562     gdb_expect 30 {
563         -re "Break.* at .*:$decimal.*$gdb_prompt $" {
564             if { $print_pass } {
565                 pass $test_name
566             }
567             return 1
568         }
569         -re "Breakpoint \[0-9\]*, \[0-9xa-f\]* in .*$gdb_prompt $" { 
570             if { $print_pass } {
571                 pass $test_name
572             }
573             return 1
574         }
575         -re "The target does not support running in non-stop mode.\r\n$gdb_prompt $" {
576             if { $print_fail } {
577                 unsupported "non-stop mode not supported"
578             }
579             return 0
580         }
581         -re ".*A problem internal to GDB has been detected" {
582             if { $print_fail } {
583                 fail "$test_name (GDB internal error)"
584             }
585             gdb_internal_error_resync
586             return 0
587         }
588         -re "$gdb_prompt $" { 
589             if { $print_fail } {
590                 fail $test_name
591             }
592             return 0
593         }
594         eof { 
595             if { $print_fail } {
596                 fail "$test_name (eof)"
597             }
598             return 0
599         }
600         timeout { 
601             if { $print_fail } {
602                 fail "$test_name (timeout)"
603             }
604             return 0
605         }
606     }
607     if { $print_pass } {
608         pass $test_name
609     }
610     return 1
611 }
612
613 # Ask gdb to run until we hit a breakpoint at main.
614 #
615 # N.B. This function deletes all existing breakpoints.
616 # If you don't want that, use gdb_start_cmd.
617
618 proc runto_main { } {
619     return [runto main no-message]
620 }
621
622 ### Continue, and expect to hit a breakpoint.
623 ### Report a pass or fail, depending on whether it seems to have
624 ### worked.  Use NAME as part of the test name; each call to
625 ### continue_to_breakpoint should use a NAME which is unique within
626 ### that test file.
627 proc gdb_continue_to_breakpoint {name {location_pattern .*}} {
628     global gdb_prompt
629     set full_name "continue to breakpoint: $name"
630
631     gdb_test_multiple "continue" $full_name {
632         -re "(?:Breakpoint|Temporary breakpoint) .* (at|in) $location_pattern\r\n$gdb_prompt $" {
633             pass $full_name
634         }
635     }
636 }
637
638
639 # gdb_internal_error_resync:
640 #
641 # Answer the questions GDB asks after it reports an internal error
642 # until we get back to a GDB prompt.  Decline to quit the debugging
643 # session, and decline to create a core file.  Return non-zero if the
644 # resync succeeds.
645 #
646 # This procedure just answers whatever questions come up until it sees
647 # a GDB prompt; it doesn't require you to have matched the input up to
648 # any specific point.  However, it only answers questions it sees in
649 # the output itself, so if you've matched a question, you had better
650 # answer it yourself before calling this.
651 #
652 # You can use this function thus:
653 #
654 # gdb_expect {
655 #     ...
656 #     -re ".*A problem internal to GDB has been detected" {
657 #         gdb_internal_error_resync
658 #     }
659 #     ...
660 # }
661 #
662 proc gdb_internal_error_resync {} {
663     global gdb_prompt
664
665     verbose -log "Resyncing due to internal error."
666
667     set count 0
668     while {$count < 10} {
669         gdb_expect {
670             -re "Quit this debugging session\\? \\(y or n\\) $" {
671                 send_gdb "n\n"
672                 incr count
673             }
674             -re "Create a core file of GDB\\? \\(y or n\\) $" {
675                 send_gdb "n\n"
676                 incr count
677             }
678             -re "$gdb_prompt $" {
679                 # We're resynchronized.
680                 return 1
681             }
682             timeout {
683                 perror "Could not resync from internal error (timeout)"
684                 return 0
685             }
686         }
687     }
688     perror "Could not resync from internal error (resync count exceeded)"
689     return 0
690 }
691
692
693 # gdb_test_multiple COMMAND MESSAGE EXPECT_ARGUMENTS
694 # Send a command to gdb; test the result.
695 #
696 # COMMAND is the command to execute, send to GDB with send_gdb.  If
697 #   this is the null string no command is sent.
698 # MESSAGE is a message to be printed with the built-in failure patterns
699 #   if one of them matches.  If MESSAGE is empty COMMAND will be used.
700 # EXPECT_ARGUMENTS will be fed to expect in addition to the standard
701 #   patterns.  Pattern elements will be evaluated in the caller's
702 #   context; action elements will be executed in the caller's context.
703 #   Unlike patterns for gdb_test, these patterns should generally include
704 #   the final newline and prompt.
705 #
706 # Returns:
707 #    1 if the test failed, according to a built-in failure pattern
708 #    0 if only user-supplied patterns matched
709 #   -1 if there was an internal error.
710 #  
711 # You can use this function thus:
712 #
713 # gdb_test_multiple "print foo" "test foo" {
714 #    -re "expected output 1" {
715 #        pass "print foo"
716 #    }
717 #    -re "expected output 2" {
718 #        fail "print foo"
719 #    }
720 # }
721 #
722 # Like with "expect", you can also specify the spawn id to match with
723 # -i "$id".  Interesting spawn ids are $inferior_spawn_id and
724 # $gdb_spawn_id.  The former matches inferior I/O, while the latter
725 # matches GDB I/O.  E.g.:
726 #
727 # send_inferior "hello\n"
728 # gdb_test_multiple "continue" "test echo" {
729 #    -i "$inferior_spawn_id" -re "^hello\r\nhello\r\n$" {
730 #        pass "got echo"
731 #    }
732 #    -i "$gdb_spawn_id" -re "Breakpoint.*$gdb_prompt $" {
733 #        fail "hit breakpoint"
734 #    }
735 # }
736 #
737 # The standard patterns, such as "Inferior exited..." and "A problem
738 # ...", all being implicitly appended to that list.  These are always
739 # expected from $gdb_spawn_id.  IOW, callers do not need to worry
740 # about resetting "-i" back to $gdb_spawn_id explicitly.
741 #
742 proc gdb_test_multiple { command message user_code } {
743     global verbose use_gdb_stub
744     global gdb_prompt pagination_prompt
745     global GDB
746     global gdb_spawn_id
747     global inferior_exited_re
748     upvar timeout timeout
749     upvar expect_out expect_out
750     global any_spawn_id
751
752     if { $message == "" } {
753         set message $command
754     }
755
756     if [string match "*\[\r\n\]" $command] {
757         error "Invalid trailing newline in \"$message\" test"
758     }
759
760     if [string match "*\[\r\n\]*" $message] {
761         error "Invalid newline in \"$message\" test"
762     }
763
764     if {$use_gdb_stub
765         && [regexp -nocase {^\s*(r|run|star|start|at|att|atta|attac|attach)\M} \
766             $command]} {
767         error "gdbserver does not support $command without extended-remote"
768     }
769
770     # TCL/EXPECT WART ALERT
771     # Expect does something very strange when it receives a single braced
772     # argument.  It splits it along word separators and performs substitutions.
773     # This means that { "[ab]" } is evaluated as "[ab]", but { "\[ab\]" } is
774     # evaluated as "\[ab\]".  But that's not how TCL normally works; inside a
775     # double-quoted list item, "\[ab\]" is just a long way of representing
776     # "[ab]", because the backslashes will be removed by lindex.
777
778     # Unfortunately, there appears to be no easy way to duplicate the splitting
779     # that expect will do from within TCL.  And many places make use of the
780     # "\[0-9\]" construct, so we need to support that; and some places make use
781     # of the "[func]" construct, so we need to support that too.  In order to
782     # get this right we have to substitute quoted list elements differently
783     # from braced list elements.
784
785     # We do this roughly the same way that Expect does it.  We have to use two
786     # lists, because if we leave unquoted newlines in the argument to uplevel
787     # they'll be treated as command separators, and if we escape newlines
788     # we mangle newlines inside of command blocks.  This assumes that the
789     # input doesn't contain a pattern which contains actual embedded newlines
790     # at this point!
791
792     regsub -all {\n} ${user_code} { } subst_code
793     set subst_code [uplevel list $subst_code]
794
795     set processed_code ""
796     set patterns ""
797     set expecting_action 0
798     set expecting_arg 0
799     foreach item $user_code subst_item $subst_code {
800         if { $item == "-n" || $item == "-notransfer" || $item == "-nocase" } {
801             lappend processed_code $item
802             continue
803         }
804         if { $item == "-indices" || $item == "-re" || $item == "-ex" } {
805             lappend processed_code $item
806             continue
807         }
808         if { $item == "-timeout" || $item == "-i" } {
809             set expecting_arg 1
810             lappend processed_code $item
811             continue
812         }
813         if { $expecting_arg } {
814             set expecting_arg 0
815             lappend processed_code $subst_item
816             continue
817         }
818         if { $expecting_action } {
819             lappend processed_code "uplevel [list $item]"
820             set expecting_action 0
821             # Cosmetic, no effect on the list.
822             append processed_code "\n"
823             continue
824         }
825         set expecting_action 1
826         lappend processed_code $subst_item
827         if {$patterns != ""} {
828             append patterns "; "
829         }
830         append patterns "\"$subst_item\""
831     }
832
833     # Also purely cosmetic.
834     regsub -all {\r} $patterns {\\r} patterns
835     regsub -all {\n} $patterns {\\n} patterns
836
837     if $verbose>2 then {
838         send_user "Sending \"$command\" to gdb\n"
839         send_user "Looking to match \"$patterns\"\n"
840         send_user "Message is \"$message\"\n"
841     }
842
843     set result -1
844     set string "${command}\n"
845     if { $command != "" } {
846         set multi_line_re "\[\r\n\] *>"
847         while { "$string" != "" } {
848             set foo [string first "\n" "$string"]
849             set len [string length "$string"]
850             if { $foo < [expr $len - 1] } {
851                 set str [string range "$string" 0 $foo]
852                 if { [send_gdb "$str"] != "" } {
853                     global suppress_flag
854
855                     if { ! $suppress_flag } {
856                         perror "Couldn't send $command to GDB."
857                     }
858                     fail "$message"
859                     return $result
860                 }
861                 # since we're checking if each line of the multi-line
862                 # command are 'accepted' by GDB here,
863                 # we need to set -notransfer expect option so that
864                 # command output is not lost for pattern matching
865                 # - guo
866                 gdb_expect 2 {
867                     -notransfer -re "$multi_line_re$" { verbose "partial: match" 3 }
868                     timeout { verbose "partial: timeout" 3 }
869                 }
870                 set string [string range "$string" [expr $foo + 1] end]
871                 set multi_line_re "$multi_line_re.*\[\r\n\] *>"
872             } else {
873                 break
874             }
875         }
876         if { "$string" != "" } {
877             if { [send_gdb "$string"] != "" } {
878                 global suppress_flag
879
880                 if { ! $suppress_flag } {
881                     perror "Couldn't send $command to GDB."
882                 }
883                 fail "$message"
884                 return $result
885             }
886         }
887     }
888
889     set code {
890         -re ".*A problem internal to GDB has been detected" {
891             fail "$message (GDB internal error)"
892             gdb_internal_error_resync
893             set result -1
894         }
895         -re "\\*\\*\\* DOSEXIT code.*" {
896             if { $message != "" } {
897                 fail "$message"
898             }
899             gdb_suppress_entire_file "GDB died"
900             set result -1
901         }
902     }
903     append code $processed_code
904     append code {
905         # Reset the spawn id, in case the processed code used -i.
906         -i "$gdb_spawn_id"
907
908         -re "Ending remote debugging.*$gdb_prompt $" {
909             if ![isnative] then {
910                 warning "Can`t communicate to remote target."
911             }
912             gdb_exit
913             gdb_start
914             set result -1
915         }
916         -re "Undefined\[a-z\]* command:.*$gdb_prompt $" {
917             perror "Undefined command \"$command\"."
918             fail "$message"
919             set result 1
920         }
921         -re "Ambiguous command.*$gdb_prompt $" {
922             perror "\"$command\" is not a unique command name."
923             fail "$message"
924             set result 1
925         }
926         -re "$inferior_exited_re with code \[0-9\]+.*$gdb_prompt $" {
927             if ![string match "" $message] then {
928                 set errmsg "$message (the program exited)"
929             } else {
930                 set errmsg "$command (the program exited)"
931             }
932             fail "$errmsg"
933             set result -1
934         }
935         -re "$inferior_exited_re normally.*$gdb_prompt $" {
936             if ![string match "" $message] then {
937                 set errmsg "$message (the program exited)"
938             } else {
939                 set errmsg "$command (the program exited)"
940             }
941             fail "$errmsg"
942             set result -1
943         }
944         -re "The program is not being run.*$gdb_prompt $" {
945             if ![string match "" $message] then {
946                 set errmsg "$message (the program is no longer running)"
947             } else {
948                 set errmsg "$command (the program is no longer running)"
949             }
950             fail "$errmsg"
951             set result -1
952         }
953         -re "\r\n$gdb_prompt $" {
954             if ![string match "" $message] then {
955                 fail "$message"
956             }
957             set result 1
958         }
959         -re "$pagination_prompt" {
960             send_gdb "\n"
961             perror "Window too small."
962             fail "$message"
963             set result -1
964         }
965         -re "\\((y or n|y or \\\[n\\\]|\\\[y\\\] or n)\\) " {
966             send_gdb "n\n"
967             gdb_expect -re "$gdb_prompt $"
968             fail "$message (got interactive prompt)"
969             set result -1
970         }
971         -re "\\\[0\\\] cancel\r\n\\\[1\\\] all.*\r\n> $" {
972             send_gdb "0\n"
973             gdb_expect -re "$gdb_prompt $"
974             fail "$message (got breakpoint menu)"
975             set result -1
976         }
977
978         # Patterns below apply to any spawn id specified.
979         -i $any_spawn_id
980         eof {
981             perror "Process no longer exists"
982             if { $message != "" } {
983                 fail "$message"
984             }
985             return -1
986         }
987         full_buffer {
988             perror "internal buffer is full."
989             fail "$message"
990             set result -1
991         }
992         timeout {
993             if ![string match "" $message] then {
994                 fail "$message (timeout)"
995             }
996             set result 1
997         }
998     }
999
1000     set result 0
1001     set code [catch {gdb_expect $code} string]
1002     if {$code == 1} {
1003         global errorInfo errorCode
1004         return -code error -errorinfo $errorInfo -errorcode $errorCode $string
1005     } elseif {$code > 1} {
1006         return -code $code $string
1007     }
1008     return $result
1009 }
1010
1011 # gdb_test COMMAND PATTERN MESSAGE QUESTION RESPONSE
1012 # Send a command to gdb; test the result.
1013 #
1014 # COMMAND is the command to execute, send to GDB with send_gdb.  If
1015 #   this is the null string no command is sent.
1016 # PATTERN is the pattern to match for a PASS, and must NOT include
1017 #   the \r\n sequence immediately before the gdb prompt.  This argument
1018 #   may be omitted to just match the prompt, ignoring whatever output 
1019 #   precedes it.
1020 # MESSAGE is an optional message to be printed.  If this is
1021 #   omitted, then the pass/fail messages use the command string as the
1022 #   message.  (If this is the empty string, then sometimes we don't
1023 #   call pass or fail at all; I don't understand this at all.)
1024 # QUESTION is a question GDB may ask in response to COMMAND, like
1025 #   "are you sure?"
1026 # RESPONSE is the response to send if QUESTION appears.
1027 #
1028 # Returns:
1029 #    1 if the test failed,
1030 #    0 if the test passes,
1031 #   -1 if there was an internal error.
1032 #  
1033 proc gdb_test { args } {
1034     global gdb_prompt
1035     upvar timeout timeout
1036
1037     if [llength $args]>2 then {
1038         set message [lindex $args 2]
1039     } else {
1040         set message [lindex $args 0]
1041     }
1042     set command [lindex $args 0]
1043     set pattern [lindex $args 1]
1044
1045     if [llength $args]==5 {
1046         set question_string [lindex $args 3]
1047         set response_string [lindex $args 4]
1048     } else {
1049         set question_string "^FOOBAR$"
1050     }
1051
1052     return [gdb_test_multiple $command $message {
1053         -re "\[\r\n\]*(?:$pattern)\[\r\n\]+$gdb_prompt $" {
1054             if ![string match "" $message] then {
1055                 pass "$message"
1056             }
1057         }
1058         -re "(${question_string})$" {
1059             send_gdb "$response_string\n"
1060             exp_continue
1061         }
1062      }]
1063 }
1064
1065 # gdb_test_no_output COMMAND MESSAGE
1066 # Send a command to GDB and verify that this command generated no output.
1067 #
1068 # See gdb_test_multiple for a description of the COMMAND and MESSAGE
1069 # parameters.  If MESSAGE is ommitted, then COMMAND will be used as
1070 # the message.  (If MESSAGE is the empty string, then sometimes we do not
1071 # call pass or fail at all; I don't understand this at all.)
1072
1073 proc gdb_test_no_output { args } {
1074     global gdb_prompt
1075     set command [lindex $args 0]
1076     if [llength $args]>1 then {
1077         set message [lindex $args 1]
1078     } else {
1079         set message $command
1080     }
1081
1082     set command_regex [string_to_regexp $command]
1083     gdb_test_multiple $command $message {
1084         -re "^$command_regex\r\n$gdb_prompt $" {
1085             if ![string match "" $message] then {
1086                 pass "$message"
1087             }
1088         }
1089     }
1090 }
1091
1092 # Send a command and then wait for a sequence of outputs.
1093 # This is useful when the sequence is long and contains ".*", a single
1094 # regexp to match the entire output can get a timeout much easier.
1095 #
1096 # COMMAND is the command to send.
1097 # TEST_NAME is passed to pass/fail.  COMMAND is used if TEST_NAME is "".
1098 # EXPECTED_OUTPUT_LIST is a list of regexps of expected output, which are
1099 # processed in order, and all must be present in the output.
1100 #
1101 # It is unnecessary to specify ".*" at the beginning or end of any regexp,
1102 # there is an implicit ".*" between each element of EXPECTED_OUTPUT_LIST.
1103 # There is also an implicit ".*" between the last regexp and the gdb prompt.
1104 #
1105 # Like gdb_test and gdb_test_multiple, the output is expected to end with the
1106 # gdb prompt, which must not be specified in EXPECTED_OUTPUT_LIST.
1107 #
1108 # Returns:
1109 #    1 if the test failed,
1110 #    0 if the test passes,
1111 #   -1 if there was an internal error.
1112
1113 proc gdb_test_sequence { command test_name expected_output_list } {
1114     global gdb_prompt
1115     if { $test_name == "" } {
1116         set test_name $command
1117     }
1118     lappend expected_output_list ""; # implicit ".*" before gdb prompt
1119     send_gdb "$command\n"
1120     return [gdb_expect_list $test_name "$gdb_prompt $" $expected_output_list]
1121 }
1122
1123 \f
1124 # Test that a command gives an error.  For pass or fail, return
1125 # a 1 to indicate that more tests can proceed.  However a timeout
1126 # is a serious error, generates a special fail message, and causes
1127 # a 0 to be returned to indicate that more tests are likely to fail
1128 # as well.
1129
1130 proc test_print_reject { args } {
1131     global gdb_prompt
1132     global verbose
1133
1134     if [llength $args]==2 then {
1135         set expectthis [lindex $args 1]
1136     } else {
1137         set expectthis "should never match this bogus string"
1138     }
1139     set sendthis [lindex $args 0]
1140     if $verbose>2 then {
1141         send_user "Sending \"$sendthis\" to gdb\n"
1142         send_user "Looking to match \"$expectthis\"\n"
1143     }
1144     send_gdb "$sendthis\n"
1145     #FIXME: Should add timeout as parameter.
1146     gdb_expect {
1147         -re "A .* in expression.*\\.*$gdb_prompt $" {
1148             pass "reject $sendthis"
1149             return 1
1150         }
1151         -re "Invalid syntax in expression.*$gdb_prompt $" {
1152             pass "reject $sendthis"
1153             return 1
1154         }
1155         -re "Junk after end of expression.*$gdb_prompt $" {
1156             pass "reject $sendthis"
1157             return 1
1158         }
1159         -re "Invalid number.*$gdb_prompt $" {
1160             pass "reject $sendthis"
1161             return 1
1162         }
1163         -re "Invalid character constant.*$gdb_prompt $" {
1164             pass "reject $sendthis"
1165             return 1
1166         }
1167         -re "No symbol table is loaded.*$gdb_prompt $" {
1168             pass "reject $sendthis"
1169             return 1
1170         }
1171         -re "No symbol .* in current context.*$gdb_prompt $" {
1172             pass "reject $sendthis"
1173             return 1
1174         }
1175         -re "Unmatched single quote.*$gdb_prompt $" {
1176             pass "reject $sendthis"
1177             return 1
1178         }
1179         -re "A character constant must contain at least one character.*$gdb_prompt $" {
1180             pass "reject $sendthis"
1181             return 1
1182         }
1183         -re "$expectthis.*$gdb_prompt $" {
1184             pass "reject $sendthis"
1185             return 1
1186         }
1187         -re ".*$gdb_prompt $" {
1188             fail "reject $sendthis"
1189             return 1
1190         }
1191         default {
1192             fail "reject $sendthis (eof or timeout)"
1193             return 0
1194         }
1195     }
1196 }
1197 \f
1198
1199 # Same as gdb_test, but the second parameter is not a regexp,
1200 # but a string that must match exactly.
1201
1202 proc gdb_test_exact { args } {
1203     upvar timeout timeout
1204
1205     set command [lindex $args 0]
1206
1207     # This applies a special meaning to a null string pattern.  Without
1208     # this, "$pattern\r\n$gdb_prompt $" will match anything, including error
1209     # messages from commands that should have no output except a new
1210     # prompt.  With this, only results of a null string will match a null
1211     # string pattern.
1212
1213     set pattern [lindex $args 1]
1214     if [string match $pattern ""] {
1215         set pattern [string_to_regexp [lindex $args 0]]
1216     } else {
1217         set pattern [string_to_regexp [lindex $args 1]]
1218     }
1219
1220     # It is most natural to write the pattern argument with only
1221     # embedded \n's, especially if you are trying to avoid Tcl quoting
1222     # problems.  But gdb_expect really wants to see \r\n in patterns.  So
1223     # transform the pattern here.  First transform \r\n back to \n, in
1224     # case some users of gdb_test_exact already do the right thing.
1225     regsub -all "\r\n" $pattern "\n" pattern
1226     regsub -all "\n" $pattern "\r\n" pattern
1227     if [llength $args]==3 then {
1228         set message [lindex $args 2]
1229     } else {
1230         set message $command
1231     }
1232
1233     return [gdb_test $command $pattern $message]
1234 }
1235
1236 # Wrapper around gdb_test_multiple that looks for a list of expected
1237 # output elements, but which can appear in any order.
1238 # CMD is the gdb command.
1239 # NAME is the name of the test.
1240 # ELM_FIND_REGEXP specifies how to partition the output into elements to
1241 # compare.
1242 # ELM_EXTRACT_REGEXP specifies the part of ELM_FIND_REGEXP to compare.
1243 # RESULT_MATCH_LIST is a list of exact matches for each expected element.
1244 # All elements of RESULT_MATCH_LIST must appear for the test to pass.
1245 #
1246 # A typical use of ELM_FIND_REGEXP/ELM_EXTRACT_REGEXP is to extract one line
1247 # of text per element and then strip trailing \r\n's.
1248 # Example:
1249 # gdb_test_list_exact "foo" "bar" \
1250 #    "\[^\r\n\]+\[\r\n\]+" \
1251 #    "\[^\r\n\]+" \
1252 #     { \
1253 #       {expected result 1} \
1254 #       {expected result 2} \
1255 #     }
1256
1257 proc gdb_test_list_exact { cmd name elm_find_regexp elm_extract_regexp result_match_list } {
1258     global gdb_prompt
1259
1260     set matches [lsort $result_match_list]
1261     set seen {}
1262     gdb_test_multiple $cmd $name {
1263         "$cmd\[\r\n\]" { exp_continue }
1264         -re $elm_find_regexp {
1265             set str $expect_out(0,string)
1266             verbose -log "seen: $str" 3
1267             regexp -- $elm_extract_regexp $str elm_seen
1268             verbose -log "extracted: $elm_seen" 3
1269             lappend seen $elm_seen
1270             exp_continue
1271         }
1272         -re "$gdb_prompt $" {
1273             set failed ""
1274             foreach got [lsort $seen] have $matches {
1275                 if {![string equal $got $have]} {
1276                     set failed $have
1277                     break
1278                 }
1279             }
1280             if {[string length $failed] != 0} {
1281                 fail "$name ($failed not found)"
1282             } else {
1283                 pass $name
1284             }
1285         }
1286     }
1287 }
1288
1289 # gdb_test_stdio COMMAND INFERIOR_PATTERN GDB_PATTERN MESSAGE
1290 # Send a command to gdb; expect inferior and gdb output.
1291 #
1292 # See gdb_test_multiple for a description of the COMMAND and MESSAGE
1293 # parameters.
1294 #
1295 # INFERIOR_PATTERN is the pattern to match against inferior output.
1296 #
1297 # GDB_PATTERN is the pattern to match against gdb output, and must NOT
1298 # include the \r\n sequence immediately before the gdb prompt, nor the
1299 # prompt.  The default is empty.
1300 #
1301 # Both inferior and gdb patterns must match for a PASS.
1302 #
1303 # If MESSAGE is ommitted, then COMMAND will be used as the message.
1304 #
1305 # Returns:
1306 #    1 if the test failed,
1307 #    0 if the test passes,
1308 #   -1 if there was an internal error.
1309 #
1310
1311 proc gdb_test_stdio {command inferior_pattern {gdb_pattern ""} {message ""}} {
1312     global inferior_spawn_id gdb_spawn_id
1313     global gdb_prompt
1314
1315     if {$message == ""} {
1316         set message $command
1317     }
1318
1319     set inferior_matched 0
1320     set gdb_matched 0
1321
1322     # Use an indirect spawn id list, and remove the inferior spawn id
1323     # from the expected output as soon as it matches, in case
1324     # $inferior_pattern happens to be a prefix of the resulting full
1325     # gdb pattern below (e.g., "\r\n").
1326     global gdb_test_stdio_spawn_id_list
1327     set gdb_test_stdio_spawn_id_list "$inferior_spawn_id"
1328
1329     # Note that if $inferior_spawn_id and $gdb_spawn_id are different,
1330     # then we may see gdb's output arriving before the inferior's
1331     # output.
1332     set res [gdb_test_multiple $command $message {
1333         -i gdb_test_stdio_spawn_id_list -re "$inferior_pattern" {
1334             set inferior_matched 1
1335             if {!$gdb_matched} {
1336                 set gdb_test_stdio_spawn_id_list ""
1337                 exp_continue
1338             }
1339         }
1340         -i $gdb_spawn_id -re "$gdb_pattern\r\n$gdb_prompt $" {
1341             set gdb_matched 1
1342             if {!$inferior_matched} {
1343                 exp_continue
1344             }
1345         }
1346     }]
1347     if {$res == 0} {
1348         pass $message
1349     } else {
1350         verbose -log "inferior_matched=$inferior_matched, gdb_matched=$gdb_matched"
1351     }
1352     return $res
1353 }
1354
1355 \f
1356
1357 # Issue a PASS and return true if evaluating CONDITION in the caller's
1358 # frame returns true, and issue a FAIL and return false otherwise.
1359 # MESSAGE is the pass/fail message to be printed.  If MESSAGE is
1360 # omitted or is empty, then the pass/fail messages use the condition
1361 # string as the message.
1362
1363 proc gdb_assert { condition {message ""} } {
1364     if { $message == ""} {
1365         set message $condition
1366     }
1367
1368     set res [uplevel 1 expr $condition]
1369     if {!$res} {
1370         fail $message
1371     } else {
1372         pass $message
1373     }
1374     return $res
1375 }
1376
1377 proc gdb_reinitialize_dir { subdir } {
1378     global gdb_prompt
1379
1380     if [is_remote host] {
1381         return ""
1382     }
1383     send_gdb "dir\n"
1384     gdb_expect 60 {
1385         -re "Reinitialize source path to empty.*y or n. " {
1386             send_gdb "y\n"
1387             gdb_expect 60 {
1388                 -re "Source directories searched.*$gdb_prompt $" {
1389                     send_gdb "dir $subdir\n"
1390                     gdb_expect 60 {
1391                         -re "Source directories searched.*$gdb_prompt $" {
1392                             verbose "Dir set to $subdir"
1393                         }
1394                         -re "$gdb_prompt $" {
1395                             perror "Dir \"$subdir\" failed."
1396                         }
1397                     }
1398                 }
1399                 -re "$gdb_prompt $" {
1400                     perror "Dir \"$subdir\" failed."
1401                 }
1402             }
1403         }
1404         -re "$gdb_prompt $" {
1405             perror "Dir \"$subdir\" failed."
1406         }
1407     }
1408 }
1409
1410 #
1411 # gdb_exit -- exit the GDB, killing the target program if necessary
1412 #
1413 proc default_gdb_exit {} {
1414     global GDB
1415     global INTERNAL_GDBFLAGS GDBFLAGS
1416     global verbose
1417     global gdb_spawn_id inferior_spawn_id
1418     global inotify_log_file
1419
1420     gdb_stop_suppressing_tests
1421
1422     if ![info exists gdb_spawn_id] {
1423         return
1424     }
1425
1426     verbose "Quitting $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
1427
1428     if {[info exists inotify_log_file] && [file exists $inotify_log_file]} {
1429         set fd [open $inotify_log_file]
1430         set data [read -nonewline $fd]
1431         close $fd
1432
1433         if {[string compare $data ""] != 0} {
1434             warning "parallel-unsafe file creations noticed"
1435
1436             # Clear the log.
1437             set fd [open $inotify_log_file w]
1438             close $fd
1439         }
1440     }
1441
1442     if { [is_remote host] && [board_info host exists fileid] } {
1443         send_gdb "quit\n"
1444         gdb_expect 10 {
1445             -re "y or n" {
1446                 send_gdb "y\n"
1447                 exp_continue
1448             }
1449             -re "DOSEXIT code" { }
1450             default { }
1451         }
1452     }
1453
1454     if ![is_remote host] {
1455         remote_close host
1456     }
1457     unset gdb_spawn_id
1458     unset inferior_spawn_id
1459 }
1460
1461 # Load a file into the debugger.
1462 # The return value is 0 for success, -1 for failure.
1463 #
1464 # This procedure also set the global variable GDB_FILE_CMD_DEBUG_INFO
1465 # to one of these values:
1466 #
1467 #   debug    file was loaded successfully and has debug information
1468 #   nodebug  file was loaded successfully and has no debug information
1469 #   lzma     file was loaded, .gnu_debugdata found, but no LZMA support
1470 #            compiled in
1471 #   fail     file was not loaded
1472 #
1473 # I tried returning this information as part of the return value,
1474 # but ran into a mess because of the many re-implementations of
1475 # gdb_load in config/*.exp.
1476 #
1477 # TODO: gdb.base/sepdebug.exp and gdb.stabs/weird.exp might be able to use
1478 # this if they can get more information set.
1479
1480 proc gdb_file_cmd { arg } {
1481     global gdb_prompt
1482     global verbose
1483     global GDB
1484     global last_loaded_file
1485
1486     # Save this for the benefit of gdbserver-support.exp.
1487     set last_loaded_file $arg
1488
1489     # Set whether debug info was found.
1490     # Default to "fail".
1491     global gdb_file_cmd_debug_info
1492     set gdb_file_cmd_debug_info "fail"
1493
1494     if [is_remote host] {
1495         set arg [remote_download host $arg]
1496         if { $arg == "" } {
1497             perror "download failed"
1498             return -1
1499         }
1500     }
1501
1502     # The file command used to kill the remote target.  For the benefit
1503     # of the testsuite, preserve this behavior.
1504     send_gdb "kill\n"
1505     gdb_expect 120 {
1506         -re "Kill the program being debugged. .y or n. $" {
1507             send_gdb "y\n"
1508             verbose "\t\tKilling previous program being debugged"
1509             exp_continue
1510         }
1511         -re "$gdb_prompt $" {
1512             # OK.
1513         }
1514     }
1515
1516     send_gdb "file $arg\n"
1517     gdb_expect 120 {
1518         -re "Reading symbols from.*LZMA support was disabled.*done.*$gdb_prompt $" {
1519             verbose "\t\tLoaded $arg into $GDB; .gnu_debugdata found but no LZMA available"
1520             set gdb_file_cmd_debug_info "lzma"
1521             return 0
1522         }
1523         -re "Reading symbols from.*no debugging symbols found.*done.*$gdb_prompt $" {
1524             verbose "\t\tLoaded $arg into $GDB with no debugging symbols"
1525             set gdb_file_cmd_debug_info "nodebug"
1526             return 0
1527         }
1528         -re "Reading symbols from.*done.*$gdb_prompt $" {
1529             verbose "\t\tLoaded $arg into $GDB"
1530             set gdb_file_cmd_debug_info "debug"
1531             return 0
1532         }
1533         -re "Load new symbol table from \".*\".*y or n. $" {
1534             send_gdb "y\n"
1535             gdb_expect 120 {
1536                 -re "Reading symbols from.*done.*$gdb_prompt $" {
1537                     verbose "\t\tLoaded $arg with new symbol table into $GDB"
1538                     set gdb_file_cmd_debug_info "debug"
1539                     return 0
1540                 }
1541                 timeout {
1542                     perror "Couldn't load $arg, other program already loaded (timeout)."
1543                     return -1
1544                 }
1545                 eof {
1546                     perror "Couldn't load $arg, other program already loaded (eof)."
1547                     return -1
1548                 }
1549             }
1550         }
1551         -re "No such file or directory.*$gdb_prompt $" {
1552             perror "($arg) No such file or directory"
1553             return -1
1554         }
1555         -re "A problem internal to GDB has been detected" {
1556             fail "($arg) (GDB internal error)"
1557             gdb_internal_error_resync
1558             return -1
1559         }
1560         -re "$gdb_prompt $" {
1561             perror "Couldn't load $arg into $GDB."
1562             return -1
1563             }
1564         timeout {
1565             perror "Couldn't load $arg into $GDB (timeout)."
1566             return -1
1567         }
1568         eof {
1569             # This is an attempt to detect a core dump, but seems not to
1570             # work.  Perhaps we need to match .* followed by eof, in which
1571             # gdb_expect does not seem to have a way to do that.
1572             perror "Couldn't load $arg into $GDB (eof)."
1573             return -1
1574         }
1575     }
1576 }
1577
1578 # Default gdb_spawn procedure.
1579
1580 proc default_gdb_spawn { } {
1581     global use_gdb_stub
1582     global GDB
1583     global INTERNAL_GDBFLAGS GDBFLAGS
1584     global gdb_spawn_id
1585
1586     gdb_stop_suppressing_tests
1587
1588     # Set the default value, it may be overriden later by specific testfile.
1589     #
1590     # Use `set_board_info use_gdb_stub' for the board file to flag the inferior
1591     # is already started after connecting and run/attach are not supported.
1592     # This is used for the "remote" protocol.  After GDB starts you should
1593     # check global $use_gdb_stub instead of the board as the testfile may force
1594     # a specific different target protocol itself.
1595     set use_gdb_stub [target_info exists use_gdb_stub]
1596
1597     verbose "Spawning $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
1598
1599     if [info exists gdb_spawn_id] {
1600         return 0
1601     }
1602
1603     if ![is_remote host] {
1604         if { [which $GDB] == 0 } then {
1605             perror "$GDB does not exist."
1606             exit 1
1607         }
1608     }
1609     set res [remote_spawn host "$GDB $INTERNAL_GDBFLAGS $GDBFLAGS [host_info gdb_opts]"]
1610     if { $res < 0 || $res == "" } {
1611         perror "Spawning $GDB failed."
1612         return 1
1613     }
1614
1615     set gdb_spawn_id $res
1616     return 0
1617 }
1618
1619 # Default gdb_start procedure.
1620
1621 proc default_gdb_start { } {
1622     global gdb_prompt pagination_prompt
1623     global gdb_spawn_id
1624     global inferior_spawn_id
1625
1626     if [info exists gdb_spawn_id] {
1627         return 0
1628     }
1629
1630     set res [gdb_spawn]
1631     if { $res != 0} {
1632         return $res
1633     }
1634
1635     # Default to assuming inferior I/O is done on GDB's terminal.
1636     if {![info exists inferior_spawn_id]} {
1637         set inferior_spawn_id $gdb_spawn_id
1638     }
1639
1640     # When running over NFS, particularly if running many simultaneous
1641     # tests on different hosts all using the same server, things can
1642     # get really slow.  Give gdb at least 3 minutes to start up.
1643     set loop_again 1
1644     while { $loop_again } {
1645         set loop_again 0
1646         gdb_expect 360 {
1647             -re "$pagination_prompt" {
1648                 verbose "Hit pagination during startup. Pressing enter to continue."
1649                 send_gdb "\n"
1650                 set loop_again 1
1651             }
1652             -re "\[\r\n\]$gdb_prompt $" {
1653                 verbose "GDB initialized."
1654             }
1655             -re "$gdb_prompt $" {
1656                 perror "GDB never initialized."
1657                 unset gdb_spawn_id
1658                 return -1
1659             }
1660             timeout     {
1661                 perror "(timeout) GDB never initialized after 10 seconds."
1662                 remote_close host
1663                 unset gdb_spawn_id
1664                 return -1
1665             }
1666         }
1667     }
1668
1669     # force the height to "unlimited", so no pagers get used
1670
1671     send_gdb "set height 0\n"
1672     gdb_expect 10 {
1673         -re "$gdb_prompt $" { 
1674             verbose "Setting height to 0." 2
1675         }
1676         timeout {
1677             warning "Couldn't set the height to 0"
1678         }
1679     }
1680     # force the width to "unlimited", so no wraparound occurs
1681     send_gdb "set width 0\n"
1682     gdb_expect 10 {
1683         -re "$gdb_prompt $" {
1684             verbose "Setting width to 0." 2
1685         }
1686         timeout {
1687             warning "Couldn't set the width to 0."
1688         }
1689     }
1690     return 0
1691 }
1692
1693 # Utility procedure to give user control of the gdb prompt in a script. It is
1694 # meant to be used for debugging test cases, and should not be left in the
1695 # test cases code.
1696
1697 proc gdb_interact { } {
1698     global gdb_spawn_id
1699     set spawn_id $gdb_spawn_id
1700
1701     send_user "+------------------------------------------+\n"
1702     send_user "| Script interrupted, you can now interact |\n"
1703     send_user "| with by gdb. Type >>> to continue.       |\n"
1704     send_user "+------------------------------------------+\n"
1705
1706     interact {
1707         ">>>" return
1708     }
1709 }
1710
1711 # Examine the output of compilation to determine whether compilation
1712 # failed or not.  If it failed determine whether it is due to missing
1713 # compiler or due to compiler error.  Report pass, fail or unsupported
1714 # as appropriate
1715
1716 proc gdb_compile_test {src output} {
1717     if { $output == "" } {
1718         pass "compilation [file tail $src]"
1719     } elseif { [regexp {^[a-zA-Z_0-9]+: Can't find [^ ]+\.$} $output] } {
1720         unsupported "compilation [file tail $src]"
1721     } elseif { [regexp {.*: command not found[\r|\n]*$} $output] } {
1722         unsupported "compilation [file tail $src]"
1723     } elseif { [regexp {.*: [^\r\n]*compiler not installed[^\r\n]*[\r|\n]*$} $output] } {
1724         unsupported "compilation [file tail $src]"
1725     } else {
1726         verbose -log "compilation failed: $output" 2
1727         fail "compilation [file tail $src]"
1728     }
1729 }
1730
1731 # Return a 1 for configurations for which we don't even want to try to
1732 # test C++.
1733
1734 proc skip_cplus_tests {} {
1735     if { [istarget "h8300-*-*"] } {
1736         return 1
1737     }
1738
1739     # The C++ IO streams are too large for HC11/HC12 and are thus not
1740     # available.  The gdb C++ tests use them and don't compile.
1741     if { [istarget "m6811-*-*"] } {
1742         return 1
1743     }
1744     if { [istarget "m6812-*-*"] } {
1745         return 1
1746     }
1747     return 0
1748 }
1749
1750 # Return a 1 for configurations for which don't have both C++ and the STL.
1751
1752 proc skip_stl_tests {} {
1753     # Symbian supports the C++ language, but the STL is missing
1754     # (both headers and libraries).
1755     if { [istarget "arm*-*-symbianelf*"] } {
1756         return 1
1757     }
1758
1759     return [skip_cplus_tests]
1760 }
1761
1762 # Return a 1 if I don't even want to try to test FORTRAN.
1763
1764 proc skip_fortran_tests {} {
1765     return 0
1766 }
1767
1768 # Return a 1 if I don't even want to try to test ada.
1769
1770 proc skip_ada_tests {} {
1771     return 0
1772 }
1773
1774 # Return a 1 if I don't even want to try to test GO.
1775
1776 proc skip_go_tests {} {
1777     return 0
1778 }
1779
1780 # Return a 1 if I don't even want to try to test D.
1781
1782 proc skip_d_tests {} {
1783     return 0
1784 }
1785
1786 # Return 1 to skip Rust tests, 0 to try them.
1787 proc skip_rust_tests {} {
1788     return [expr {![isnative]}]
1789 }
1790
1791 # Return a 1 for configurations that do not support Python scripting.
1792 # PROMPT_REGEXP is the expected prompt.
1793
1794 proc skip_python_tests_prompt { prompt_regexp } {
1795     global gdb_py_is_py3k
1796     global gdb_py_is_py24
1797
1798     gdb_test_multiple "python print ('test')" "verify python support" {
1799         -re "not supported.*$prompt_regexp" {
1800             unsupported "Python support is disabled."
1801             return 1
1802         }
1803         -re "$prompt_regexp" {}
1804     }
1805
1806     set gdb_py_is_py24 0
1807     gdb_test_multiple "python print (sys.version_info\[0\])" "check if python 3" {
1808         -re "3.*$prompt_regexp" {
1809             set gdb_py_is_py3k 1
1810         }
1811         -re ".*$prompt_regexp" {
1812             set gdb_py_is_py3k 0
1813         }
1814     }
1815     if { $gdb_py_is_py3k == 0 } {
1816         gdb_test_multiple "python print (sys.version_info\[1\])" "check if python 2.4" {
1817             -re "\[45\].*$prompt_regexp" {
1818                 set gdb_py_is_py24 1
1819             }
1820             -re ".*$prompt_regexp" {
1821                 set gdb_py_is_py24 0
1822             }
1823         }
1824     }
1825
1826     return 0
1827 }
1828
1829 # Return a 1 for configurations that do not support Python scripting.
1830 # Note: This also sets various globals that specify which version of Python
1831 # is in use.  See skip_python_tests_prompt.
1832
1833 proc skip_python_tests {} {
1834     global gdb_prompt
1835     return [skip_python_tests_prompt "$gdb_prompt $"]
1836 }
1837
1838 # Return a 1 if we should skip shared library tests.
1839
1840 proc skip_shlib_tests {} {
1841     # Run the shared library tests on native systems.
1842     if {[isnative]} {
1843         return 0
1844     }
1845
1846     # An abbreviated list of remote targets where we should be able to
1847     # run shared library tests.
1848     if {([istarget *-*-linux*]
1849          || [istarget *-*-*bsd*]
1850          || [istarget *-*-solaris2*]
1851          || [istarget arm*-*-symbianelf*]
1852          || [istarget *-*-mingw*]
1853          || [istarget *-*-cygwin*]
1854          || [istarget *-*-pe*])} {
1855         return 0
1856     }
1857
1858     return 1
1859 }
1860
1861 # Return 1 if we should skip tui related tests.
1862
1863 proc skip_tui_tests {} {
1864     global gdb_prompt
1865
1866     gdb_test_multiple "help layout" "verify tui support" {
1867         -re "Undefined command: \"layout\".*$gdb_prompt $" {
1868             return 1
1869         }
1870         -re "$gdb_prompt $" {
1871         }
1872     }
1873
1874     return 0
1875 }
1876
1877 # Test files shall make sure all the test result lines in gdb.sum are
1878 # unique in a test run, so that comparing the gdb.sum files of two
1879 # test runs gives correct results.  Test files that exercise
1880 # variations of the same tests more than once, shall prefix the
1881 # different test invocations with different identifying strings in
1882 # order to make them unique.
1883 #
1884 # About test prefixes:
1885 #
1886 # $pf_prefix is the string that dejagnu prints after the result (FAIL,
1887 # PASS, etc.), and before the test message/name in gdb.sum.  E.g., the
1888 # underlined substring in
1889 #
1890 #  PASS: gdb.base/mytest.exp: some test
1891 #        ^^^^^^^^^^^^^^^^^^^^
1892 #
1893 # is $pf_prefix.
1894 #
1895 # The easiest way to adjust the test prefix is to append a test
1896 # variation prefix to the $pf_prefix, using the with_test_prefix
1897 # procedure.  E.g.,
1898 #
1899 # proc do_tests {} {
1900 #   gdb_test ... ... "test foo"
1901 #   gdb_test ... ... "test bar"
1902 #
1903 #   with_test_prefix "subvariation a" {
1904 #     gdb_test ... ... "test x"
1905 #   }
1906 #
1907 #   with_test_prefix "subvariation b" {
1908 #     gdb_test ... ... "test x"
1909 #   }
1910 # }
1911 #
1912 # with_test_prefix "variation1" {
1913 #   ...do setup for variation 1...
1914 #   do_tests
1915 # }
1916 #
1917 # with_test_prefix "variation2" {
1918 #   ...do setup for variation 2...
1919 #   do_tests
1920 # }
1921 #
1922 # Results in:
1923 #
1924 #  PASS: gdb.base/mytest.exp: variation1: test foo
1925 #  PASS: gdb.base/mytest.exp: variation1: test bar
1926 #  PASS: gdb.base/mytest.exp: variation1: subvariation a: test x
1927 #  PASS: gdb.base/mytest.exp: variation1: subvariation b: test x
1928 #  PASS: gdb.base/mytest.exp: variation2: test foo
1929 #  PASS: gdb.base/mytest.exp: variation2: test bar
1930 #  PASS: gdb.base/mytest.exp: variation2: subvariation a: test x
1931 #  PASS: gdb.base/mytest.exp: variation2: subvariation b: test x
1932 #
1933 # If for some reason more flexibility is necessary, one can also
1934 # manipulate the pf_prefix global directly, treating it as a string.
1935 # E.g.,
1936 #
1937 #   global pf_prefix
1938 #   set saved_pf_prefix
1939 #   append pf_prefix "${foo}: bar"
1940 #   ... actual tests ...
1941 #   set pf_prefix $saved_pf_prefix
1942 #
1943
1944 # Run BODY in the context of the caller, with the current test prefix
1945 # (pf_prefix) appended with one space, then PREFIX, and then a colon.
1946 # Returns the result of BODY.
1947 #
1948 proc with_test_prefix { prefix body } {
1949   global pf_prefix
1950
1951   set saved $pf_prefix
1952   append pf_prefix " " $prefix ":"
1953   set code [catch {uplevel 1 $body} result]
1954   set pf_prefix $saved
1955
1956   if {$code == 1} {
1957       global errorInfo errorCode
1958       return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
1959   } else {
1960       return -code $code $result
1961   }
1962 }
1963
1964 # Wrapper for foreach that calls with_test_prefix on each iteration,
1965 # including the iterator's name and current value in the prefix.
1966
1967 proc foreach_with_prefix {var list body} {
1968     upvar 1 $var myvar
1969     foreach myvar $list {
1970         with_test_prefix "$var=$myvar" {
1971             uplevel 1 $body
1972         }
1973     }
1974 }
1975
1976 # Like TCL's native proc, but defines a procedure that wraps its body
1977 # within 'with_test_prefix "$proc_name" { ... }'.
1978 proc proc_with_prefix {name arguments body} {
1979     # Define the advertised proc.
1980     proc $name $arguments [list with_test_prefix $name $body]
1981 }
1982
1983
1984 # Run BODY in the context of the caller.  After BODY is run, the variables
1985 # listed in VARS will be reset to the values they had before BODY was run.
1986 #
1987 # This is useful for providing a scope in which it is safe to temporarily
1988 # modify global variables, e.g.
1989 #
1990 #   global INTERNAL_GDBFLAGS
1991 #   global env
1992 #
1993 #   set foo GDBHISTSIZE
1994 #
1995 #   save_vars { INTERNAL_GDBFLAGS env($foo) env(HOME) } {
1996 #       append INTERNAL_GDBFLAGS " -nx"
1997 #       unset -nocomplain env(GDBHISTSIZE)
1998 #       gdb_start
1999 #       gdb_test ...
2000 #   }
2001 #
2002 # Here, although INTERNAL_GDBFLAGS, env(GDBHISTSIZE) and env(HOME) may be
2003 # modified inside BODY, this proc guarantees that the modifications will be
2004 # undone after BODY finishes executing.
2005
2006 proc save_vars { vars body } {
2007     array set saved_scalars { }
2008     array set saved_arrays { }
2009     set unset_vars { }
2010
2011     foreach var $vars {
2012         # First evaluate VAR in the context of the caller in case the variable
2013         # name may be a not-yet-interpolated string like env($foo)
2014         set var [uplevel 1 list $var]
2015
2016         if [uplevel 1 [list info exists $var]] {
2017             if [uplevel 1 [list array exists $var]] {
2018                 set saved_arrays($var) [uplevel 1 [list array get $var]]
2019             } else {
2020                 set saved_scalars($var) [uplevel 1 [list set $var]]
2021             }
2022         } else {
2023             lappend unset_vars $var
2024         }
2025     }
2026
2027     set code [catch {uplevel 1 $body} result]
2028
2029     foreach {var value} [array get saved_scalars] {
2030         uplevel 1 [list set $var $value]
2031     }
2032
2033     foreach {var value} [array get saved_arrays] {
2034         uplevel 1 [list unset $var]
2035         uplevel 1 [list array set $var $value]
2036     }
2037
2038     foreach var $unset_vars {
2039         uplevel 1 [list unset -nocomplain $var]
2040     }
2041
2042     if {$code == 1} {
2043         global errorInfo errorCode
2044         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2045     } else {
2046         return -code $code $result
2047     }
2048 }
2049
2050
2051 # Run tests in BODY with GDB prompt and variable $gdb_prompt set to
2052 # PROMPT.  When BODY is finished, restore GDB prompt and variable
2053 # $gdb_prompt.
2054 # Returns the result of BODY.
2055 #
2056 # Notes:
2057 #
2058 # 1) If you want to use, for example, "(foo)" as the prompt you must pass it
2059 # as "(foo)", and not the regexp form "\(foo\)" (expressed as "\\(foo\\)" in
2060 # TCL).  PROMPT is internally converted to a suitable regexp for matching.
2061 # We do the conversion from "(foo)" to "\(foo\)" here for a few reasons:
2062 #   a) It's more intuitive for callers to pass the plain text form.
2063 #   b) We need two forms of the prompt:
2064 #      - a regexp to use in output matching,
2065 #      - a value to pass to the "set prompt" command.
2066 #   c) It's easier to convert the plain text form to its regexp form.
2067 #
2068 # 2) Don't add a trailing space, we do that here.
2069
2070 proc with_gdb_prompt { prompt body } {
2071     global gdb_prompt
2072
2073     # Convert "(foo)" to "\(foo\)".
2074     # We don't use string_to_regexp because while it works today it's not
2075     # clear it will work tomorrow: the value we need must work as both a
2076     # regexp *and* as the argument to the "set prompt" command, at least until
2077     # we start recording both forms separately instead of just $gdb_prompt.
2078     # The testsuite is pretty-much hardwired to interpret $gdb_prompt as the
2079     # regexp form.
2080     regsub -all {[]*+.|()^$\[\\]} $prompt {\\&} prompt
2081
2082     set saved $gdb_prompt
2083
2084     verbose -log "Setting gdb prompt to \"$prompt \"."
2085     set gdb_prompt $prompt
2086     gdb_test_no_output "set prompt $prompt " ""
2087
2088     set code [catch {uplevel 1 $body} result]
2089
2090     verbose -log "Restoring gdb prompt to \"$saved \"."
2091     set gdb_prompt $saved
2092     gdb_test_no_output "set prompt $saved " ""
2093
2094     if {$code == 1} {
2095         global errorInfo errorCode
2096         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2097     } else {
2098         return -code $code $result
2099     }
2100 }
2101
2102 # Run tests in BODY with target-charset setting to TARGET_CHARSET.  When
2103 # BODY is finished, restore target-charset.
2104
2105 proc with_target_charset { target_charset body } {
2106     global gdb_prompt
2107
2108     set saved ""
2109     gdb_test_multiple "show target-charset" "" {
2110         -re "The target character set is \".*; currently (.*)\"\..*$gdb_prompt " {
2111             set saved $expect_out(1,string)
2112         }
2113         -re "The target character set is \"(.*)\".*$gdb_prompt " {
2114             set saved $expect_out(1,string)
2115         }
2116         -re ".*$gdb_prompt " {
2117             fail "get target-charset"
2118         }
2119     }
2120
2121     gdb_test_no_output "set target-charset $target_charset" ""
2122
2123     set code [catch {uplevel 1 $body} result]
2124
2125     gdb_test_no_output "set target-charset $saved" ""
2126
2127     if {$code == 1} {
2128         global errorInfo errorCode
2129         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2130     } else {
2131         return -code $code $result
2132     }
2133 }
2134
2135 # Switch the default spawn id to SPAWN_ID, so that gdb_test,
2136 # mi_gdb_test etc. default to using it.
2137
2138 proc switch_gdb_spawn_id {spawn_id} {
2139     global gdb_spawn_id
2140     global board board_info
2141
2142     set gdb_spawn_id $spawn_id
2143     set board [host_info name]
2144     set board_info($board,fileid) $spawn_id
2145 }
2146
2147 # Clear the default spawn id.
2148
2149 proc clear_gdb_spawn_id {} {
2150     global gdb_spawn_id
2151     global board board_info
2152
2153     unset -nocomplain gdb_spawn_id
2154     set board [host_info name]
2155     unset -nocomplain board_info($board,fileid)
2156 }
2157
2158 # Run BODY with SPAWN_ID as current spawn id.
2159
2160 proc with_spawn_id { spawn_id body } {
2161     global gdb_spawn_id
2162
2163     if [info exists gdb_spawn_id] {
2164         set saved_spawn_id $gdb_spawn_id
2165     }
2166
2167     switch_gdb_spawn_id $spawn_id
2168
2169     set code [catch {uplevel 1 $body} result]
2170
2171     if [info exists saved_spawn_id] {
2172         switch_gdb_spawn_id $saved_spawn_id
2173     } else {
2174         clear_gdb_spawn_id
2175     }
2176
2177     if {$code == 1} {
2178         global errorInfo errorCode
2179         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2180     } else {
2181         return -code $code $result
2182     }
2183 }
2184
2185 # Select the largest timeout from all the timeouts:
2186 # - the local "timeout" variable of the scope two levels above,
2187 # - the global "timeout" variable,
2188 # - the board variable "gdb,timeout".
2189
2190 proc get_largest_timeout {} {
2191     upvar #0 timeout gtimeout
2192     upvar 2 timeout timeout
2193
2194     set tmt 0
2195     if [info exists timeout] {
2196       set tmt $timeout
2197     }
2198     if { [info exists gtimeout] && $gtimeout > $tmt } {
2199         set tmt $gtimeout
2200     }
2201     if { [target_info exists gdb,timeout]
2202          && [target_info gdb,timeout] > $tmt } {
2203         set tmt [target_info gdb,timeout]
2204     }
2205     if { $tmt == 0 } {
2206         # Eeeeew.
2207         set tmt 60
2208     }
2209
2210     return $tmt
2211 }
2212
2213 # Run tests in BODY with timeout increased by factor of FACTOR.  When
2214 # BODY is finished, restore timeout.
2215
2216 proc with_timeout_factor { factor body } {
2217     global timeout
2218
2219     set savedtimeout $timeout
2220
2221     set timeout [expr [get_largest_timeout] * $factor]
2222     set code [catch {uplevel 1 $body} result]
2223
2224     set timeout $savedtimeout
2225     if {$code == 1} {
2226         global errorInfo errorCode
2227         return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2228     } else {
2229         return -code $code $result
2230     }
2231 }
2232
2233 # Return 1 if _Complex types are supported, otherwise, return 0.
2234
2235 gdb_caching_proc support_complex_tests {
2236
2237     if { [gdb_skip_float_test] } {
2238         # If floating point is not supported, _Complex is not
2239         # supported.
2240         return 0
2241     }
2242
2243     # Set up, compile, and execute a test program containing _Complex types.
2244     # Include the current process ID in the file names to prevent conflicts
2245     # with invocations for multiple testsuites.
2246     set src [standard_temp_file complex[pid].c]
2247     set exe [standard_temp_file complex[pid].x]
2248
2249     gdb_produce_source $src {
2250         int main() {
2251             _Complex float cf;
2252             _Complex double cd;
2253             _Complex long double cld;
2254             return 0;
2255         }
2256     }
2257
2258     verbose "compiling testfile $src" 2
2259     set compile_flags {debug nowarnings quiet}
2260     set lines [gdb_compile $src $exe executable $compile_flags]
2261     file delete $src
2262     file delete $exe
2263
2264     if ![string match "" $lines] then {
2265         verbose "testfile compilation failed, returning 0" 2
2266         set result 0
2267     } else {
2268         set result 1
2269     }
2270
2271     return $result
2272 }
2273
2274 # Return 1 if GDB can get a type for siginfo from the target, otherwise
2275 # return 0.
2276
2277 proc supports_get_siginfo_type {} {
2278     if { [istarget "*-*-linux*"] } {
2279         return 1
2280     } else {
2281         return 0
2282     }
2283 }
2284
2285 # Return 1 if the target supports hardware single stepping.
2286
2287 proc can_hardware_single_step {} {
2288
2289     if { [istarget "arm*-*-*"] || [istarget "mips*-*-*"]
2290          || [istarget "tic6x-*-*"] || [istarget "sparc*-*-linux*"]
2291          || [istarget "nios2-*-*"] } {
2292         return 0
2293     }
2294
2295     return 1
2296 }
2297
2298 # Return 1 if target hardware or OS supports single stepping to signal
2299 # handler, otherwise, return 0.
2300
2301 proc can_single_step_to_signal_handler {} {
2302     # Targets don't have hardware single step.  On these targets, when
2303     # a signal is delivered during software single step, gdb is unable
2304     # to determine the next instruction addresses, because start of signal
2305     # handler is one of them.
2306     return [can_hardware_single_step]
2307 }
2308
2309 # Return 1 if target supports process record, otherwise return 0.
2310
2311 proc supports_process_record {} {
2312
2313     if [target_info exists gdb,use_precord] {
2314         return [target_info gdb,use_precord]
2315     }
2316
2317     if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
2318          || [istarget "i\[34567\]86-*-linux*"]
2319          || [istarget "aarch64*-*-linux*"]
2320          || [istarget "powerpc*-*-linux*"]
2321          || [istarget "s390*-*-linux*"] } {
2322         return 1
2323     }
2324
2325     return 0
2326 }
2327
2328 # Return 1 if target supports reverse debugging, otherwise return 0.
2329
2330 proc supports_reverse {} {
2331
2332     if [target_info exists gdb,can_reverse] {
2333         return [target_info gdb,can_reverse]
2334     }
2335
2336     if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
2337          || [istarget "i\[34567\]86-*-linux*"]
2338          || [istarget "aarch64*-*-linux*"]
2339          || [istarget "powerpc*-*-linux*"]
2340          || [istarget "s390*-*-linux*"] } {
2341         return 1
2342     }
2343
2344     return 0
2345 }
2346
2347 # Return 1 if readline library is used.
2348
2349 proc readline_is_used { } {
2350     global gdb_prompt
2351
2352     gdb_test_multiple "show editing" "" {
2353         -re ".*Editing of command lines as they are typed is on\..*$gdb_prompt $" {
2354             return 1
2355         }
2356         -re ".*$gdb_prompt $" {
2357             return 0
2358         }
2359     }
2360 }
2361
2362 # Return 1 if target is ELF.
2363 gdb_caching_proc is_elf_target {
2364     set me "is_elf_target"
2365
2366     set src [standard_temp_file is_elf_target[pid].c]
2367     set obj [standard_temp_file is_elf_target[pid].o]
2368
2369     gdb_produce_source $src {
2370         int foo () {return 0;}
2371     }
2372
2373     verbose "$me:  compiling testfile $src" 2
2374     set lines [gdb_compile $src $obj object {quiet}]
2375
2376     file delete $src
2377
2378     if ![string match "" $lines] then {
2379         verbose "$me:  testfile compilation failed, returning 0" 2
2380         return 0
2381     }
2382
2383     set fp_obj [open $obj "r"]
2384     fconfigure $fp_obj -translation binary
2385     set data [read $fp_obj]
2386     close $fp_obj
2387
2388     file delete $obj
2389
2390     set ELFMAG "\u007FELF"
2391
2392     if {[string compare -length 4 $data $ELFMAG] != 0} {
2393         verbose "$me:  returning 0" 2
2394         return 0
2395     }
2396
2397     verbose "$me:  returning 1" 2
2398     return 1
2399 }
2400
2401 # Return 1 if the memory at address zero is readable.
2402
2403 gdb_caching_proc is_address_zero_readable {
2404     global gdb_prompt
2405
2406     set ret 0
2407     gdb_test_multiple "x 0" "" {
2408         -re "Cannot access memory at address 0x0.*$gdb_prompt $" {
2409             set ret 0
2410         }
2411         -re ".*$gdb_prompt $" {
2412             set ret 1
2413         }
2414     }
2415
2416     return $ret
2417 }
2418
2419 # Produce source file NAME and write SOURCES into it.
2420
2421 proc gdb_produce_source { name sources } {
2422     set index 0
2423     set f [open $name "w"]
2424
2425     puts $f $sources
2426     close $f
2427 }
2428
2429 # Return 1 if target is ILP32.
2430 # This cannot be decided simply from looking at the target string,
2431 # as it might depend on externally passed compiler options like -m64.
2432 gdb_caching_proc is_ilp32_target {
2433     set me "is_ilp32_target"
2434
2435     set src [standard_temp_file ilp32[pid].c]
2436     set obj [standard_temp_file ilp32[pid].o]
2437
2438     gdb_produce_source $src {
2439         int dummy[sizeof (int) == 4
2440                   && sizeof (void *) == 4
2441                   && sizeof (long) == 4 ? 1 : -1];
2442     }
2443
2444     verbose "$me:  compiling testfile $src" 2
2445     set lines [gdb_compile $src $obj object {quiet}]
2446     file delete $src
2447     file delete $obj
2448
2449     if ![string match "" $lines] then {
2450         verbose "$me:  testfile compilation failed, returning 0" 2
2451         return 0
2452     }
2453
2454     verbose "$me:  returning 1" 2
2455     return 1
2456 }
2457
2458 # Return 1 if target is LP64.
2459 # This cannot be decided simply from looking at the target string,
2460 # as it might depend on externally passed compiler options like -m64.
2461 gdb_caching_proc is_lp64_target {
2462     set me "is_lp64_target"
2463
2464     set src [standard_temp_file lp64[pid].c]
2465     set obj [standard_temp_file lp64[pid].o]
2466
2467     gdb_produce_source $src {
2468         int dummy[sizeof (int) == 4
2469                   && sizeof (void *) == 8
2470                   && sizeof (long) == 8 ? 1 : -1];
2471     }
2472
2473     verbose "$me:  compiling testfile $src" 2
2474     set lines [gdb_compile $src $obj object {quiet}]
2475     file delete $src
2476     file delete $obj
2477
2478     if ![string match "" $lines] then {
2479         verbose "$me:  testfile compilation failed, returning 0" 2
2480         return 0
2481     }
2482
2483     verbose "$me:  returning 1" 2
2484     return 1
2485 }
2486
2487 # Return 1 if target has 64 bit addresses.
2488 # This cannot be decided simply from looking at the target string,
2489 # as it might depend on externally passed compiler options like -m64.
2490 gdb_caching_proc is_64_target {
2491     set me "is_64_target"
2492
2493     set src [standard_temp_file is64[pid].c]
2494     set obj [standard_temp_file is64[pid].o]
2495
2496     gdb_produce_source $src {
2497         int function(void) { return 3; }
2498         int dummy[sizeof (&function) == 8 ? 1 : -1];
2499     }
2500
2501     verbose "$me:  compiling testfile $src" 2
2502     set lines [gdb_compile $src $obj object {quiet}]
2503     file delete $src
2504     file delete $obj
2505
2506     if ![string match "" $lines] then {
2507         verbose "$me:  testfile compilation failed, returning 0" 2
2508         return 0
2509     }
2510
2511     verbose "$me:  returning 1" 2
2512     return 1
2513 }
2514
2515 # Return 1 if target has x86_64 registers - either amd64 or x32.
2516 # x32 target identifies as x86_64-*-linux*, therefore it cannot be determined
2517 # just from the target string.
2518 gdb_caching_proc is_amd64_regs_target {
2519     if {![istarget "x86_64-*-*"] && ![istarget "i?86-*"]} {
2520         return 0
2521     }
2522
2523     set me "is_amd64_regs_target"
2524
2525     set src [standard_temp_file reg64[pid].s]
2526     set obj [standard_temp_file reg64[pid].o]
2527
2528     set list {}
2529     foreach reg \
2530         {rax rbx rcx rdx rsi rdi rbp rsp r8 r9 r10 r11 r12 r13 r14 r15} {
2531             lappend list "\tincq %$reg"
2532         }
2533     gdb_produce_source $src [join $list \n]
2534
2535     verbose "$me:  compiling testfile $src" 2
2536     set lines [gdb_compile $src $obj object {quiet}]
2537     file delete $src
2538     file delete $obj
2539
2540     if ![string match "" $lines] then {
2541         verbose "$me:  testfile compilation failed, returning 0" 2
2542         return 0
2543     }
2544
2545     verbose "$me:  returning 1" 2
2546     return 1
2547 }
2548
2549 # Return 1 if this target is an x86 or x86-64 with -m32.
2550 proc is_x86_like_target {} {
2551     if {![istarget "x86_64-*-*"] && ![istarget i?86-*]} {
2552         return 0
2553     }
2554     return [expr [is_ilp32_target] && ![is_amd64_regs_target]]
2555 }
2556
2557 # Return 1 if this target is an arm or aarch32 on aarch64.
2558
2559 gdb_caching_proc is_aarch32_target {
2560     if { [istarget "arm*-*-*"] } {
2561         return 1
2562     }
2563
2564     if { ![istarget "aarch64*-*-*"] } {
2565         return 0
2566     }
2567
2568     set me "is_aarch32_target"
2569
2570     set src [standard_temp_file aarch32[pid].s]
2571     set obj [standard_temp_file aarch32[pid].o]
2572
2573     set list {}
2574     foreach reg \
2575         {r0 r1 r2 r3} {
2576             lappend list "\tmov $reg, $reg"
2577         }
2578     gdb_produce_source $src [join $list \n]
2579
2580     verbose "$me:  compiling testfile $src" 2
2581     set lines [gdb_compile $src $obj object {quiet}]
2582     file delete $src
2583     file delete $obj
2584
2585     if ![string match "" $lines] then {
2586         verbose "$me:  testfile compilation failed, returning 0" 2
2587         return 0
2588     }
2589
2590     verbose "$me:  returning 1" 2
2591     return 1
2592 }
2593
2594 # Return 1 if this target is an aarch64, either lp64 or ilp32.
2595
2596 proc is_aarch64_target {} {
2597     if { ![istarget "aarch64*-*-*"] } {
2598         return 0
2599     }
2600
2601     return [expr ![is_aarch32_target]]
2602 }
2603
2604 # Return 1 if displaced stepping is supported on target, otherwise, return 0.
2605 proc support_displaced_stepping {} {
2606
2607     if { [istarget "x86_64-*-linux*"] || [istarget "i\[34567\]86-*-linux*"]
2608          || [istarget "arm*-*-linux*"] || [istarget "powerpc-*-linux*"]
2609          || [istarget "powerpc64-*-linux*"] || [istarget "s390*-*-*"]
2610          || [istarget "aarch64*-*-linux*"] } {
2611         return 1
2612     }
2613
2614     return 0
2615 }
2616
2617 # Run a test on the target to see if it supports vmx hardware.  Return 0 if so, 
2618 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
2619
2620 gdb_caching_proc skip_altivec_tests {
2621     global srcdir subdir gdb_prompt inferior_exited_re
2622
2623     set me "skip_altivec_tests"
2624
2625     # Some simulators are known to not support VMX instructions.
2626     if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
2627         verbose "$me:  target known to not support VMX, returning 1" 2
2628         return 1
2629     }
2630
2631     # Make sure we have a compiler that understands altivec.
2632     set compile_flags {debug nowarnings}
2633     if [get_compiler_info] {
2634        warning "Could not get compiler info"
2635        return 1
2636     }
2637     if [test_compiler_info gcc*] {
2638         set compile_flags "$compile_flags additional_flags=-maltivec"
2639     } elseif [test_compiler_info xlc*] {
2640         set compile_flags "$compile_flags additional_flags=-qaltivec"
2641     } else {
2642         verbose "Could not compile with altivec support, returning 1" 2
2643         return 1
2644     }
2645
2646     # Set up, compile, and execute a test program containing VMX instructions.
2647     # Include the current process ID in the file names to prevent conflicts
2648     # with invocations for multiple testsuites.
2649     set src [standard_temp_file vmx[pid].c]
2650     set exe [standard_temp_file vmx[pid].x]
2651
2652     gdb_produce_source $src {
2653         int main() {
2654             #ifdef __MACH__
2655             asm volatile ("vor v0,v0,v0");
2656             #else
2657             asm volatile ("vor 0,0,0");
2658             #endif
2659             return 0;
2660         }
2661     }
2662
2663     verbose "$me:  compiling testfile $src" 2
2664     set lines [gdb_compile $src $exe executable $compile_flags]
2665     file delete $src
2666
2667     if ![string match "" $lines] then {
2668         verbose "$me:  testfile compilation failed, returning 1" 2
2669         return 1
2670     }
2671
2672     # No error message, compilation succeeded so now run it via gdb.
2673
2674     gdb_exit
2675     gdb_start
2676     gdb_reinitialize_dir $srcdir/$subdir
2677     gdb_load "$exe"
2678     gdb_run_cmd
2679     gdb_expect {
2680         -re ".*Illegal instruction.*${gdb_prompt} $" {
2681             verbose -log "\n$me altivec hardware not detected" 
2682             set skip_vmx_tests 1
2683         }
2684         -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
2685             verbose -log "\n$me: altivec hardware detected" 
2686             set skip_vmx_tests 0
2687         }
2688         default {
2689           warning "\n$me: default case taken"
2690             set skip_vmx_tests 1
2691         }
2692     }
2693     gdb_exit
2694     remote_file build delete $exe
2695
2696     verbose "$me:  returning $skip_vmx_tests" 2
2697     return $skip_vmx_tests
2698 }
2699
2700 # Run a test on the target to see if it supports vmx hardware.  Return 0 if so,
2701 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
2702
2703 gdb_caching_proc skip_vsx_tests {
2704     global srcdir subdir gdb_prompt inferior_exited_re
2705
2706     set me "skip_vsx_tests"
2707
2708     # Some simulators are known to not support Altivec instructions, so
2709     # they won't support VSX instructions as well.
2710     if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
2711         verbose "$me:  target known to not support VSX, returning 1" 2
2712         return 1
2713     }
2714
2715     # Make sure we have a compiler that understands altivec.
2716     set compile_flags {debug nowarnings quiet}
2717     if [get_compiler_info] {
2718        warning "Could not get compiler info"
2719        return 1
2720     }
2721     if [test_compiler_info gcc*] {
2722         set compile_flags "$compile_flags additional_flags=-mvsx"
2723     } elseif [test_compiler_info xlc*] {
2724         set compile_flags "$compile_flags additional_flags=-qasm=gcc"
2725     } else {
2726         verbose "Could not compile with vsx support, returning 1" 2
2727         return 1
2728     }
2729
2730     set src [standard_temp_file vsx[pid].c]
2731     set exe [standard_temp_file vsx[pid].x]
2732
2733     gdb_produce_source $src {
2734         int main() {
2735             double a[2] = { 1.0, 2.0 };
2736             #ifdef __MACH__
2737             asm volatile ("lxvd2x v0,v0,%[addr]" : : [addr] "r" (a));
2738             #else
2739             asm volatile ("lxvd2x 0,0,%[addr]" : : [addr] "r" (a));
2740             #endif
2741             return 0;
2742         }
2743     }
2744
2745     verbose "$me:  compiling testfile $src" 2
2746     set lines [gdb_compile $src $exe executable $compile_flags]
2747     file delete $src
2748
2749     if ![string match "" $lines] then {
2750         verbose "$me:  testfile compilation failed, returning 1" 2
2751         return 1
2752     }
2753
2754     # No error message, compilation succeeded so now run it via gdb.
2755
2756     gdb_exit
2757     gdb_start
2758     gdb_reinitialize_dir $srcdir/$subdir
2759     gdb_load "$exe"
2760     gdb_run_cmd
2761     gdb_expect {
2762         -re ".*Illegal instruction.*${gdb_prompt} $" {
2763             verbose -log "\n$me VSX hardware not detected"
2764             set skip_vsx_tests 1
2765         }
2766         -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
2767             verbose -log "\n$me: VSX hardware detected"
2768             set skip_vsx_tests 0
2769         }
2770         default {
2771           warning "\n$me: default case taken"
2772             set skip_vsx_tests 1
2773         }
2774     }
2775     gdb_exit
2776     remote_file build delete $exe
2777
2778     verbose "$me:  returning $skip_vsx_tests" 2
2779     return $skip_vsx_tests
2780 }
2781
2782 # Run a test on the target to see if it supports TSX hardware.  Return 0 if so,
2783 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
2784
2785 gdb_caching_proc skip_tsx_tests {
2786     global srcdir subdir gdb_prompt inferior_exited_re
2787
2788     set me "skip_tsx_tests"
2789
2790     set src [standard_temp_file tsx[pid].c]
2791     set exe [standard_temp_file tsx[pid].x]
2792
2793     gdb_produce_source $src {
2794     int main() {
2795         asm volatile ("xbegin .L0");
2796         asm volatile ("xend");
2797         asm volatile (".L0: nop");
2798         return 0;
2799     }
2800     }
2801
2802     verbose "$me:  compiling testfile $src" 2
2803     set lines [gdb_compile $src $exe executable {nowarnings quiet}]
2804     file delete $src
2805
2806     if ![string match "" $lines] then {
2807         verbose "$me:  testfile compilation failed." 2
2808         return 1
2809     }
2810
2811     # No error message, compilation succeeded so now run it via gdb.
2812
2813     gdb_exit
2814     gdb_start
2815     gdb_reinitialize_dir $srcdir/$subdir
2816     gdb_load "$exe"
2817     gdb_run_cmd
2818     gdb_expect {
2819         -re ".*Illegal instruction.*${gdb_prompt} $" {
2820             verbose -log "$me:  TSX hardware not detected."
2821             set skip_tsx_tests 1
2822         }
2823         -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
2824             verbose -log "$me:  TSX hardware detected."
2825             set skip_tsx_tests 0
2826         }
2827         default {
2828             warning "\n$me:  default case taken."
2829             set skip_tsx_tests 1
2830         }
2831     }
2832     gdb_exit
2833     remote_file build delete $exe
2834
2835     verbose "$me:  returning $skip_tsx_tests" 2
2836     return $skip_tsx_tests
2837 }
2838
2839 # Run a test on the target to see if it supports btrace hardware.  Return 0 if so,
2840 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
2841
2842 gdb_caching_proc skip_btrace_tests {
2843     global srcdir subdir gdb_prompt inferior_exited_re
2844
2845     set me "skip_btrace_tests"
2846     if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
2847         verbose "$me:  target does not support btrace, returning 1" 2
2848         return 1
2849     }
2850
2851     # Set up, compile, and execute a test program.
2852     # Include the current process ID in the file names to prevent conflicts
2853     # with invocations for multiple testsuites.
2854     set src [standard_temp_file btrace[pid].c]
2855     set exe [standard_temp_file btrace[pid].x]
2856
2857     gdb_produce_source $src {
2858         int main(void) { return 0; }
2859     }
2860
2861     verbose "$me:  compiling testfile $src" 2
2862     set compile_flags {debug nowarnings quiet}
2863     set lines [gdb_compile $src $exe executable $compile_flags]
2864
2865     if ![string match "" $lines] then {
2866         verbose "$me:  testfile compilation failed, returning 1" 2
2867         file delete $src
2868         return 1
2869     }
2870
2871     # No error message, compilation succeeded so now run it via gdb.
2872
2873     gdb_exit
2874     gdb_start
2875     gdb_reinitialize_dir $srcdir/$subdir
2876     gdb_load $exe
2877     if ![runto_main] {
2878         file delete $src
2879         return 1
2880     }
2881     file delete $src
2882     # In case of an unexpected output, we return 2 as a fail value.
2883     set skip_btrace_tests 2
2884     gdb_test_multiple "record btrace" "check btrace support" {
2885         -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
2886             set skip_btrace_tests 1
2887         }
2888         -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
2889             set skip_btrace_tests 1
2890         }
2891         -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
2892             set skip_btrace_tests 1
2893         }
2894         -re "^record btrace\r\n$gdb_prompt $" {
2895             set skip_btrace_tests 0
2896         }
2897     }
2898     gdb_exit
2899     remote_file build delete $exe
2900
2901     verbose "$me:  returning $skip_btrace_tests" 2
2902     return $skip_btrace_tests
2903 }
2904
2905 # Run a test on the target to see if it supports btrace pt hardware.
2906 # Return 0 if so, 1 if it does not.  Based on 'check_vmx_hw_available'
2907 # from the GCC testsuite.
2908
2909 gdb_caching_proc skip_btrace_pt_tests {
2910     global srcdir subdir gdb_prompt inferior_exited_re
2911
2912     set me "skip_btrace_tests"
2913     if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
2914         verbose "$me:  target does not support btrace, returning 1" 2
2915         return 1
2916     }
2917
2918     # Set up, compile, and execute a test program.
2919     # Include the current process ID in the file names to prevent conflicts
2920     # with invocations for multiple testsuites.
2921     set src [standard_temp_file btrace[pid].c]
2922     set exe [standard_temp_file btrace[pid].x]
2923
2924     gdb_produce_source $src {
2925         int main(void) { return 0; }
2926     }
2927
2928     verbose "$me:  compiling testfile $src" 2
2929     set compile_flags {debug nowarnings quiet}
2930     set lines [gdb_compile $src $exe executable $compile_flags]
2931
2932     if ![string match "" $lines] then {
2933         verbose "$me:  testfile compilation failed, returning 1" 2
2934         file delete $src
2935         return 1
2936     }
2937
2938     # No error message, compilation succeeded so now run it via gdb.
2939
2940     gdb_exit
2941     gdb_start
2942     gdb_reinitialize_dir $srcdir/$subdir
2943     gdb_load $exe
2944     if ![runto_main] {
2945         file delete $src
2946         return 1
2947     }
2948     file delete $src
2949     # In case of an unexpected output, we return 2 as a fail value.
2950     set skip_btrace_tests 2
2951     gdb_test_multiple "record btrace pt" "check btrace support" {
2952         -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
2953             set skip_btrace_tests 1
2954         }
2955         -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
2956             set skip_btrace_tests 1
2957         }
2958         -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
2959             set skip_btrace_tests 1
2960         }
2961         -re "GDB does not support.*\r\n$gdb_prompt $" {
2962             set skip_btrace_tests 1
2963         }
2964         -re "^record btrace pt\r\n$gdb_prompt $" {
2965             set skip_btrace_tests 0
2966         }
2967     }
2968     gdb_exit
2969     remote_file build delete $exe
2970
2971     verbose "$me:  returning $skip_btrace_tests" 2
2972     return $skip_btrace_tests
2973 }
2974
2975 # Return whether we should skip tests for showing inlined functions in
2976 # backtraces.  Requires get_compiler_info and get_debug_format.
2977
2978 proc skip_inline_frame_tests {} {
2979     # GDB only recognizes inlining information in DWARF 2 (DWARF 3).
2980     if { ! [test_debug_format "DWARF 2"] } {
2981         return 1
2982     }
2983
2984     # GCC before 4.1 does not emit DW_AT_call_file / DW_AT_call_line.
2985     if { ([test_compiler_info "gcc-2-*"]
2986           || [test_compiler_info "gcc-3-*"]
2987           || [test_compiler_info "gcc-4-0-*"]) } {
2988         return 1
2989     }
2990
2991     return 0
2992 }
2993
2994 # Return whether we should skip tests for showing variables from
2995 # inlined functions.  Requires get_compiler_info and get_debug_format.
2996
2997 proc skip_inline_var_tests {} {
2998     # GDB only recognizes inlining information in DWARF 2 (DWARF 3).
2999     if { ! [test_debug_format "DWARF 2"] } {
3000         return 1
3001     }
3002
3003     return 0
3004 }
3005
3006 # Return a 1 if we should skip tests that require hardware breakpoints
3007
3008 proc skip_hw_breakpoint_tests {} {
3009     # Skip tests if requested by the board (note that no_hardware_watchpoints
3010     # disables both watchpoints and breakpoints)
3011     if { [target_info exists gdb,no_hardware_watchpoints]} {
3012         return 1
3013     }
3014
3015     # These targets support hardware breakpoints natively
3016     if { [istarget "i?86-*-*"] 
3017          || [istarget "x86_64-*-*"]
3018          || [istarget "ia64-*-*"] 
3019          || [istarget "arm*-*-*"]
3020          || [istarget "aarch64*-*-*"]
3021          || [istarget "s390*-*-*"] } {
3022         return 0
3023     }
3024
3025     return 1
3026 }
3027
3028 # Return a 1 if we should skip tests that require hardware watchpoints
3029
3030 proc skip_hw_watchpoint_tests {} {
3031     # Skip tests if requested by the board
3032     if { [target_info exists gdb,no_hardware_watchpoints]} {
3033         return 1
3034     }
3035
3036     # These targets support hardware watchpoints natively
3037     if { [istarget "i?86-*-*"] 
3038          || [istarget "x86_64-*-*"]
3039          || [istarget "ia64-*-*"] 
3040          || [istarget "arm*-*-*"]
3041          || [istarget "aarch64*-*-*"]
3042          || [istarget "powerpc*-*-linux*"]
3043          || [istarget "s390*-*-*"] } {
3044         return 0
3045     }
3046
3047     return 1
3048 }
3049
3050 # Return a 1 if we should skip tests that require *multiple* hardware
3051 # watchpoints to be active at the same time
3052
3053 proc skip_hw_watchpoint_multi_tests {} {
3054     if { [skip_hw_watchpoint_tests] } {
3055         return 1
3056     }
3057
3058     # These targets support just a single hardware watchpoint
3059     if { [istarget "arm*-*-*"]
3060          || [istarget "powerpc*-*-linux*"] } {
3061         return 1
3062     }
3063
3064     return 0
3065 }
3066
3067 # Return a 1 if we should skip tests that require read/access watchpoints
3068
3069 proc skip_hw_watchpoint_access_tests {} {
3070     if { [skip_hw_watchpoint_tests] } {
3071         return 1
3072     }
3073
3074     # These targets support just write watchpoints
3075     if { [istarget "s390*-*-*"] } {
3076         return 1
3077     }
3078
3079     return 0
3080 }
3081
3082 # Return 1 if we should skip tests that require the runtime unwinder
3083 # hook.  This must be invoked while gdb is running, after shared
3084 # libraries have been loaded.  This is needed because otherwise a
3085 # shared libgcc won't be visible.
3086
3087 proc skip_unwinder_tests {} {
3088     global gdb_prompt
3089
3090     set ok 0
3091     gdb_test_multiple "print _Unwind_DebugHook" "check for unwinder hook" {
3092         -re "= .*no debug info.*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
3093         }
3094         -re "= .*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
3095             set ok 1
3096         }
3097         -re "No symbol .* in current context.\r\n$gdb_prompt $" {
3098         }
3099     }
3100     if {!$ok} {
3101         gdb_test_multiple "info probe" "check for stap probe in unwinder" {
3102             -re ".*libgcc.*unwind.*\r\n$gdb_prompt $" {
3103                 set ok 1
3104             }
3105             -re "\r\n$gdb_prompt $" {
3106             }
3107         }
3108     }
3109     return $ok
3110 }
3111
3112 # Return 0 if we should skip tests that require the libstdc++ stap
3113 # probes.  This must be invoked while gdb is running, after shared
3114 # libraries have been loaded.
3115
3116 proc skip_libstdcxx_probe_tests {} {
3117     global gdb_prompt
3118
3119     set ok 0
3120     gdb_test_multiple "info probe" "check for stap probe in libstdc++" {
3121         -re ".*libstdcxx.*catch.*\r\n$gdb_prompt $" {
3122             set ok 1
3123         }
3124         -re "\r\n$gdb_prompt $" {
3125         }
3126     }
3127     return $ok
3128 }
3129
3130 # Return 1 if we should skip tests of the "compile" feature.
3131 # This must be invoked after the inferior has been started.
3132
3133 proc skip_compile_feature_tests {} {
3134     global gdb_prompt
3135
3136     set result 0
3137     gdb_test_multiple "compile code -- ;" "check for working compile command" {
3138         "Could not load libcc1.*\r\n$gdb_prompt $" {
3139             set result 1
3140         }
3141         -re "Command not supported on this host\\..*\r\n$gdb_prompt $" {
3142             set result 1
3143         }
3144         -re "\r\n$gdb_prompt $" {
3145         }
3146     }
3147     return $result
3148 }
3149
3150 # Helper for gdb_is_target_remote.  PROMPT_REGEXP is the expected
3151 # prompt.
3152
3153 proc gdb_is_target_remote_prompt { prompt_regexp } {
3154
3155     set test "probe for target remote"
3156     gdb_test_multiple "maint print target-stack" $test {
3157         -re ".*emote serial target in gdb-specific protocol.*$prompt_regexp" {
3158             pass $test
3159             return 1
3160         }
3161         -re "$prompt_regexp" {
3162             pass $test
3163         }
3164     }
3165     return 0
3166 }
3167
3168 # Check whether we're testing with the remote or extended-remote
3169 # targets.
3170
3171 proc gdb_is_target_remote {} {
3172     global gdb_prompt
3173
3174     return [gdb_is_target_remote_prompt "$gdb_prompt $"]
3175 }
3176
3177 # Return the effective value of use_gdb_stub.
3178 #
3179 # If the use_gdb_stub global has been set (it is set when the gdb process is
3180 # spawned), return that.  Otherwise, return the value of the use_gdb_stub
3181 # property from the board file.
3182 #
3183 # This is the preferred way of checking use_gdb_stub, since it allows to check
3184 # the value before the gdb has been spawned and it will return the correct value
3185 # even when it was overriden by the test.
3186
3187 proc use_gdb_stub {} {
3188   global use_gdb_stub
3189
3190   if [info exists use_gdb_stub] {
3191      return $use_gdb_stub
3192   }
3193
3194   return [target_info exists use_gdb_stub]
3195 }
3196
3197 # Return 1 if the current remote target is an instance of our GDBserver, 0
3198 # otherwise.  Return -1 if there was an error and we can't tell.
3199
3200 gdb_caching_proc target_is_gdbserver {
3201     global gdb_prompt
3202
3203     set is_gdbserver -1
3204     set test "probing for GDBserver"
3205
3206     gdb_test_multiple "monitor help" $test {
3207         -re "The following monitor commands are supported.*Quit GDBserver.*$gdb_prompt $" {
3208             set is_gdbserver 1
3209         }
3210         -re "$gdb_prompt $" {
3211             set is_gdbserver 0
3212         }
3213     }
3214
3215     if { $is_gdbserver == -1 } {
3216         verbose -log "Unable to tell whether we are using GDBserver or not."
3217     }
3218
3219     return $is_gdbserver
3220 }
3221
3222 # N.B. compiler_info is intended to be local to this file.
3223 # Call test_compiler_info with no arguments to fetch its value.
3224 # Yes, this is counterintuitive when there's get_compiler_info,
3225 # but that's the current API.
3226 if [info exists compiler_info] {
3227     unset compiler_info
3228 }
3229
3230 set gcc_compiled                0
3231
3232 # Figure out what compiler I am using.
3233 # The result is cached so only the first invocation runs the compiler.
3234 #
3235 # ARG can be empty or "C++".  If empty, "C" is assumed.
3236 #
3237 # There are several ways to do this, with various problems.
3238 #
3239 # [ gdb_compile -E $ifile -o $binfile.ci ]
3240 # source $binfile.ci
3241 #
3242 #   Single Unix Spec v3 says that "-E -o ..." together are not
3243 #   specified.  And in fact, the native compiler on hp-ux 11 (among
3244 #   others) does not work with "-E -o ...".  Most targets used to do
3245 #   this, and it mostly worked, because it works with gcc.
3246 #
3247 # [ catch "exec $compiler -E $ifile > $binfile.ci" exec_output ]
3248 # source $binfile.ci
3249
3250 #   This avoids the problem with -E and -o together.  This almost works
3251 #   if the build machine is the same as the host machine, which is
3252 #   usually true of the targets which are not gcc.  But this code does
3253 #   not figure which compiler to call, and it always ends up using the C
3254 #   compiler.  Not good for setting hp_aCC_compiler.  Target
3255 #   hppa*-*-hpux* used to do this.
3256 #
3257 # [ gdb_compile -E $ifile > $binfile.ci ]
3258 # source $binfile.ci
3259 #
3260 #   dejagnu target_compile says that it supports output redirection,
3261 #   but the code is completely different from the normal path and I
3262 #   don't want to sweep the mines from that path.  So I didn't even try
3263 #   this.
3264 #
3265 # set cppout [ gdb_compile $ifile "" preprocess $args quiet ]
3266 # eval $cppout
3267 #
3268 #   I actually do this for all targets now.  gdb_compile runs the right
3269 #   compiler, and TCL captures the output, and I eval the output.
3270 #
3271 #   Unfortunately, expect logs the output of the command as it goes by,
3272 #   and dejagnu helpfully prints a second copy of it right afterwards.
3273 #   So I turn off expect logging for a moment.
3274 #   
3275 # [ gdb_compile $ifile $ciexe_file executable $args ]
3276 # [ remote_exec $ciexe_file ]
3277 # [ source $ci_file.out ]
3278 #
3279 #   I could give up on -E and just do this.
3280 #   I didn't get desperate enough to try this.
3281 #
3282 # -- chastain 2004-01-06
3283
3284 proc get_compiler_info {{arg ""}} {
3285     # For compiler.c and compiler.cc
3286     global srcdir
3287
3288     # I am going to play with the log to keep noise out.
3289     global outdir
3290     global tool
3291
3292     # These come from compiler.c or compiler.cc
3293     global compiler_info
3294
3295     # Legacy global data symbols.
3296     global gcc_compiled
3297
3298     if [info exists compiler_info] {
3299         # Already computed.
3300         return 0
3301     }
3302
3303     # Choose which file to preprocess.
3304     set ifile "${srcdir}/lib/compiler.c"
3305     if { $arg == "c++" } {
3306         set ifile "${srcdir}/lib/compiler.cc"
3307     }
3308
3309     # Run $ifile through the right preprocessor.
3310     # Toggle gdb.log to keep the compiler output out of the log.
3311     set saved_log [log_file -info]
3312     log_file
3313     if [is_remote host] {
3314         # We have to use -E and -o together, despite the comments
3315         # above, because of how DejaGnu handles remote host testing.
3316         set ppout "$outdir/compiler.i"
3317         gdb_compile "${ifile}" "$ppout" preprocess [list "$arg" quiet]
3318         set file [open $ppout r]
3319         set cppout [read $file]
3320         close $file
3321     } else {
3322         set cppout [ gdb_compile "${ifile}" "" preprocess [list "$arg" quiet] ]
3323     }
3324     eval log_file $saved_log
3325
3326     # Eval the output.
3327     set unknown 0
3328     foreach cppline [ split "$cppout" "\n" ] {
3329         if { [ regexp "^#" "$cppline" ] } {
3330             # line marker
3331         } elseif { [ regexp "^\[\n\r\t \]*$" "$cppline" ] } {
3332             # blank line
3333         } elseif { [ regexp "^\[\n\r\t \]*set\[\n\r\t \]" "$cppline" ] } {
3334             # eval this line
3335             verbose "get_compiler_info: $cppline" 2
3336             eval "$cppline"
3337         } else {
3338             # unknown line
3339             verbose -log "get_compiler_info: $cppline"
3340             set unknown 1
3341         }
3342     }
3343
3344     # Set to unknown if for some reason compiler_info didn't get defined.
3345     if ![info exists compiler_info] {
3346         verbose -log "get_compiler_info: compiler_info not provided"
3347         set compiler_info "unknown"
3348     }
3349     # Also set to unknown compiler if any diagnostics happened.
3350     if { $unknown } {
3351         verbose -log "get_compiler_info: got unexpected diagnostics"
3352         set compiler_info "unknown"
3353     }
3354
3355     # Set the legacy symbols.
3356     set gcc_compiled 0
3357     regexp "^gcc-(\[0-9\]+)-" "$compiler_info" matchall gcc_compiled
3358
3359     # Log what happened.
3360     verbose -log "get_compiler_info: $compiler_info"
3361
3362     # Most compilers will evaluate comparisons and other boolean
3363     # operations to 0 or 1.
3364     uplevel \#0 { set true 1 }
3365     uplevel \#0 { set false 0 }
3366
3367     return 0
3368 }
3369
3370 # Return the compiler_info string if no arg is provided.
3371 # Otherwise the argument is a glob-style expression to match against
3372 # compiler_info.
3373
3374 proc test_compiler_info { {compiler ""} } {
3375     global compiler_info
3376     get_compiler_info
3377
3378     # If no arg, return the compiler_info string.
3379     if [string match "" $compiler] {
3380         return $compiler_info
3381     }
3382
3383     return [string match $compiler $compiler_info]
3384 }
3385
3386 proc current_target_name { } {
3387     global target_info
3388     if [info exists target_info(target,name)] {
3389         set answer $target_info(target,name)
3390     } else {
3391         set answer ""
3392     }
3393     return $answer
3394 }
3395
3396 set gdb_wrapper_initialized 0
3397 set gdb_wrapper_target ""
3398
3399 proc gdb_wrapper_init { args } {
3400     global gdb_wrapper_initialized
3401     global gdb_wrapper_file
3402     global gdb_wrapper_flags
3403     global gdb_wrapper_target
3404
3405     if { $gdb_wrapper_initialized == 1 } { return; }
3406
3407     if {[target_info exists needs_status_wrapper] && \
3408             [target_info needs_status_wrapper] != "0"} {
3409         set result [build_wrapper "testglue.o"]
3410         if { $result != "" } {
3411             set gdb_wrapper_file [lindex $result 0]
3412             set gdb_wrapper_flags [lindex $result 1]
3413         } else {
3414             warning "Status wrapper failed to build."
3415         }
3416     }
3417     set gdb_wrapper_initialized 1
3418     set gdb_wrapper_target [current_target_name]
3419 }
3420
3421 # Determine options that we always want to pass to the compiler.
3422 gdb_caching_proc universal_compile_options {
3423     set me "universal_compile_options"
3424     set options {}
3425
3426     set src [standard_temp_file ccopts[pid].c]
3427     set obj [standard_temp_file ccopts[pid].o]
3428
3429     gdb_produce_source $src {
3430         int foo(void) { return 0; }
3431     }
3432
3433     # Try an option for disabling colored diagnostics.  Some compilers
3434     # yield colored diagnostics by default (when run from a tty) unless
3435     # such an option is specified.
3436     set opt "additional_flags=-fdiagnostics-color=never"
3437     set lines [target_compile $src $obj object [list "quiet" $opt]]
3438     if [string match "" $lines] then {
3439         # Seems to have worked; use the option.
3440         lappend options $opt
3441     }
3442     file delete $src
3443     file delete $obj
3444
3445     verbose "$me:  returning $options" 2
3446     return $options
3447 }
3448
3449 # Some targets need to always link a special object in.  Save its path here.
3450 global gdb_saved_set_unbuffered_mode_obj
3451 set gdb_saved_set_unbuffered_mode_obj ""
3452
3453 # Compile source files specified by SOURCE into a binary of type TYPE at path
3454 # DEST.  gdb_compile is implemented using DejaGnu's target_compile, so the type
3455 # parameter and most options are passed directly to it.
3456 #
3457 # The type can be one of the following:
3458 #
3459 #   - object: Compile into an object file.
3460 #   - executable: Compile and link into an executable.
3461 #   - preprocess: Preprocess the source files.
3462 #   - assembly: Generate assembly listing.
3463 #
3464 # The following options are understood and processed by gdb_compile:
3465 #
3466 #   - shlib=so_path: Add SO_PATH to the sources, and enable some target-specific
3467 #     quirks to be able to use shared libraries.
3468 #   - shlib_load: Link with appropriate libraries to allow the test to
3469 #     dynamically load libraries at runtime.  For example, on Linux, this adds
3470 #     -ldl so that the test can use dlopen.
3471 #   - nowarnings:  Inhibit all compiler warnings.
3472 #
3473 # And here are some of the not too obscure options understood by DejaGnu that
3474 # influence the compilation:
3475 #
3476 #   - additional_flags=flag: Add FLAG to the compiler flags.
3477 #   - libs=library: Add LIBRARY to the libraries passed to the linker.  The
3478 #     argument can be a file, in which case it's added to the sources, or a
3479 #     linker flag.
3480 #   - ldflags=flag: Add FLAG to the linker flags.
3481 #   - incdir=path: Add PATH to the searched include directories.
3482 #   - libdir=path: Add PATH to the linker searched directories.
3483 #   - ada, c++, f77: Compile the file as Ada, C++ or Fortran.
3484 #   - debug: Build with debug information.
3485 #   - optimize: Build with optimization.
3486
3487 proc gdb_compile {source dest type options} {
3488     global GDB_TESTCASE_OPTIONS
3489     global gdb_wrapper_file
3490     global gdb_wrapper_flags
3491     global gdb_wrapper_initialized
3492     global srcdir
3493     global objdir
3494     global gdb_saved_set_unbuffered_mode_obj
3495
3496     set outdir [file dirname $dest]
3497
3498     # Add platform-specific options if a shared library was specified using
3499     # "shlib=librarypath" in OPTIONS.
3500     if {[lsearch -exact $options rust] != -1} {
3501         # -fdiagnostics-color is not a rustcc option.
3502     } else {
3503         set new_options [universal_compile_options]
3504     }
3505     set new_options {}
3506     set shlib_found 0
3507     set shlib_load 0
3508     foreach opt $options {
3509         if [regexp {^shlib=(.*)} $opt dummy_var shlib_name] {
3510             if [test_compiler_info "xlc-*"] {
3511                 # IBM xlc compiler doesn't accept shared library named other
3512                 # than .so: use "-Wl," to bypass this
3513                 lappend source "-Wl,$shlib_name"
3514             } elseif { ([istarget "*-*-mingw*"]
3515                         || [istarget *-*-cygwin*]
3516                         || [istarget *-*-pe*])} {
3517                 lappend source "${shlib_name}.a"
3518             } else {
3519                lappend source $shlib_name
3520             }
3521             if { $shlib_found == 0 } {
3522                 set shlib_found 1
3523                 if { ([istarget "*-*-mingw*"]
3524                       || [istarget *-*-cygwin*]) } {
3525                     lappend new_options "additional_flags=-Wl,--enable-auto-import"
3526                 }
3527                 if { [test_compiler_info "gcc-*"] || [test_compiler_info "clang-*"] } {
3528                     # Undo debian's change in the default.
3529                     # Put it at the front to not override any user-provided
3530                     # value, and to make sure it appears in front of all the
3531                     # shlibs!
3532                     lappend new_options "early_flags=-Wl,--no-as-needed"
3533                 }
3534             }
3535         } elseif { $opt == "shlib_load" } {
3536             set shlib_load 1
3537         } else {
3538             lappend new_options $opt
3539         }
3540     }
3541
3542     # Because we link with libraries using their basename, we may need
3543     # (depending on the platform) to set a special rpath value, to allow
3544     # the executable to find the libraries it depends on.
3545     if { $shlib_load || $shlib_found } {
3546         if { ([istarget "*-*-mingw*"]
3547               || [istarget *-*-cygwin*]
3548               || [istarget *-*-pe*]) } {
3549             # Do not need anything.
3550         } elseif { [istarget *-*-freebsd*] || [istarget *-*-openbsd*] } {
3551             lappend new_options "ldflags=-Wl,-rpath,${outdir}"
3552         } elseif { [istarget arm*-*-symbianelf*] } {
3553             if { $shlib_load } {
3554                 lappend new_options "libs=-ldl"
3555             }
3556         } else {
3557             if { $shlib_load } {
3558                 lappend new_options "libs=-ldl"
3559             }
3560             lappend new_options "ldflags=-Wl,-rpath,\\\$ORIGIN"
3561         }
3562     }
3563     set options $new_options
3564
3565     if [info exists GDB_TESTCASE_OPTIONS] {
3566         lappend options "additional_flags=$GDB_TESTCASE_OPTIONS"
3567     }
3568     verbose "options are $options"
3569     verbose "source is $source $dest $type $options"
3570
3571     if { $gdb_wrapper_initialized == 0 } { gdb_wrapper_init }
3572
3573     if {[target_info exists needs_status_wrapper] && \
3574             [target_info needs_status_wrapper] != "0" && \
3575             [info exists gdb_wrapper_file]} {
3576         lappend options "libs=${gdb_wrapper_file}"
3577         lappend options "ldflags=${gdb_wrapper_flags}"
3578     }
3579
3580     # Replace the "nowarnings" option with the appropriate additional_flags
3581     # to disable compiler warnings.
3582     set nowarnings [lsearch -exact $options nowarnings]
3583     if {$nowarnings != -1} {
3584         if [target_info exists gdb,nowarnings_flag] {
3585             set flag "additional_flags=[target_info gdb,nowarnings_flag]"
3586         } else {
3587             set flag "additional_flags=-w"
3588         }
3589         set options [lreplace $options $nowarnings $nowarnings $flag]
3590     }
3591
3592     if { $type == "executable" } {
3593         if { ([istarget "*-*-mingw*"]
3594               || [istarget "*-*-*djgpp"]
3595               || [istarget "*-*-cygwin*"])} {
3596             # Force output to unbuffered mode, by linking in an object file
3597             # with a global contructor that calls setvbuf.
3598             #
3599             # Compile the special object seperatelly for two reasons:
3600             #  1) Insulate it from $options.
3601             #  2) Avoid compiling it for every gdb_compile invocation,
3602             #  which is time consuming, especially if we're remote
3603             #  host testing.
3604             #
3605             if { $gdb_saved_set_unbuffered_mode_obj == "" } {
3606                 verbose "compiling gdb_saved_set_unbuffered_obj"
3607                 set unbuf_src ${srcdir}/lib/set_unbuffered_mode.c
3608                 set unbuf_obj ${objdir}/set_unbuffered_mode.o
3609
3610                 set result [gdb_compile "${unbuf_src}" "${unbuf_obj}" object {nowarnings}]
3611                 if { $result != "" } {
3612                     return $result
3613                 }
3614                 if {[is_remote host]} {
3615                     set gdb_saved_set_unbuffered_mode_obj set_unbuffered_mode_saved.o
3616                 } else {
3617                     set gdb_saved_set_unbuffered_mode_obj ${objdir}/set_unbuffered_mode_saved.o
3618                 }
3619                 # Link a copy of the output object, because the
3620                 # original may be automatically deleted.
3621                 remote_download host $unbuf_obj $gdb_saved_set_unbuffered_mode_obj
3622             } else {
3623                 verbose "gdb_saved_set_unbuffered_obj already compiled"
3624             }
3625
3626             # Rely on the internal knowledge that the global ctors are ran in
3627             # reverse link order.  In that case, we can use ldflags to
3628             # avoid copying the object file to the host multiple
3629             # times.
3630             # This object can only be added if standard libraries are
3631             # used. Thus, we need to disable it if -nostdlib option is used
3632             if {[lsearch -regexp $options "-nostdlib"] < 0 } {
3633                 lappend options "ldflags=$gdb_saved_set_unbuffered_mode_obj"
3634             }
3635         }
3636     }
3637
3638     set result [target_compile $source $dest $type $options]
3639
3640     # Prune uninteresting compiler (and linker) output.
3641     regsub "Creating library file: \[^\r\n\]*\[\r\n\]+" $result "" result
3642
3643     regsub "\[\r\n\]*$" "$result" "" result
3644     regsub "^\[\r\n\]*" "$result" "" result
3645     
3646     if {[lsearch $options quiet] < 0} {
3647         # We shall update this on a per language basis, to avoid
3648         # changing the entire testsuite in one go.
3649         if {[lsearch $options f77] >= 0} {
3650             gdb_compile_test $source $result
3651         } elseif { $result != "" } {
3652             clone_output "gdb compile failed, $result"
3653         }
3654     }
3655     return $result
3656 }
3657
3658
3659 # This is just like gdb_compile, above, except that it tries compiling
3660 # against several different thread libraries, to see which one this
3661 # system has.
3662 proc gdb_compile_pthreads {source dest type options} {
3663     set built_binfile 0
3664     set why_msg "unrecognized error"
3665     foreach lib {-lpthreads -lpthread -lthread ""} {
3666         # This kind of wipes out whatever libs the caller may have
3667         # set.  Or maybe theirs will override ours.  How infelicitous.
3668         set options_with_lib [concat $options [list libs=$lib quiet]]
3669         set ccout [gdb_compile $source $dest $type $options_with_lib]
3670         switch -regexp -- $ccout {
3671             ".*no posix threads support.*" {
3672                 set why_msg "missing threads include file"
3673                 break
3674             }
3675             ".*cannot open -lpthread.*" {
3676                 set why_msg "missing runtime threads library"
3677             }
3678             ".*Can't find library for -lpthread.*" {
3679                 set why_msg "missing runtime threads library"
3680             }
3681             {^$} {
3682                 pass "successfully compiled posix threads test case"
3683                 set built_binfile 1
3684                 break
3685             }
3686         }
3687     }
3688     if {!$built_binfile} {
3689         unsupported "couldn't compile [file tail $source]: ${why_msg}"
3690         return -1
3691     }
3692 }
3693
3694 # Build a shared library from SOURCES.
3695
3696 proc gdb_compile_shlib {sources dest options} {
3697     set obj_options $options
3698
3699     set info_options ""
3700     if { [lsearch -exact $options "c++"] >= 0 } {
3701         set info_options "c++"
3702     }
3703     if [get_compiler_info ${info_options}] {
3704        return -1
3705     }
3706
3707     switch -glob [test_compiler_info] {
3708         "xlc-*" {
3709             lappend obj_options "additional_flags=-qpic"
3710         }
3711         "clang-*" {
3712             if { !([istarget "*-*-cygwin*"]
3713                    || [istarget "*-*-mingw*"]) } {
3714                 lappend obj_options "additional_flags=-fpic"
3715             }
3716         }
3717         "gcc-*" {
3718             if { !([istarget "powerpc*-*-aix*"]
3719                    || [istarget "rs6000*-*-aix*"]
3720                    || [istarget "*-*-cygwin*"]
3721                    || [istarget "*-*-mingw*"]
3722                    || [istarget "*-*-pe*"]) } {
3723                 lappend obj_options "additional_flags=-fpic"
3724             }
3725         }
3726         "icc-*" {
3727                 lappend obj_options "additional_flags=-fpic"
3728         }
3729         default {
3730             # don't know what the compiler is...
3731         }
3732     }
3733
3734     set outdir [file dirname $dest]
3735     set objects ""
3736     foreach source $sources {
3737        set sourcebase [file tail $source]
3738        if {[gdb_compile $source "${outdir}/${sourcebase}.o" object $obj_options] != ""} {
3739            return -1
3740        }
3741        lappend objects ${outdir}/${sourcebase}.o
3742     }
3743
3744     set link_options $options
3745     if [test_compiler_info "xlc-*"] {
3746         lappend link_options "additional_flags=-qmkshrobj"
3747     } else {
3748         lappend link_options "additional_flags=-shared"
3749
3750         if { ([istarget "*-*-mingw*"]
3751               || [istarget *-*-cygwin*]
3752               || [istarget *-*-pe*]) } {
3753             if { [is_remote host] } {
3754                 set name [file tail ${dest}]
3755             } else {
3756                 set name ${dest}
3757             }
3758             lappend link_options "additional_flags=-Wl,--out-implib,${name}.a"
3759         } else {
3760             # Set the soname of the library.  This causes the linker on ELF
3761             # systems to create the DT_NEEDED entry in the executable referring
3762             # to the soname of the library, and not its absolute path.  This
3763             # (using the absolute path) would be problem when testing on a
3764             # remote target.
3765             #
3766             # In conjunction with setting the soname, we add the special
3767             # rpath=$ORIGIN value when building the executable, so that it's
3768             # able to find the library in its own directory.
3769             set destbase [file tail $dest]
3770             lappend link_options "additional_flags=-Wl,-soname,$destbase"
3771         }
3772     }
3773     if {[gdb_compile "${objects}" "${dest}" executable $link_options] != ""} {
3774         return -1
3775     }
3776     if { [is_remote host]
3777          && ([istarget "*-*-mingw*"]
3778              || [istarget *-*-cygwin*]
3779              || [istarget *-*-pe*]) } {
3780         set dest_tail_name [file tail ${dest}]
3781         remote_upload host $dest_tail_name.a ${dest}.a
3782         remote_file host delete $dest_tail_name.a
3783     }
3784
3785     return ""
3786 }
3787
3788 # This is just like gdb_compile_shlib, above, except that it tries compiling
3789 # against several different thread libraries, to see which one this
3790 # system has.
3791 proc gdb_compile_shlib_pthreads {sources dest options} {
3792     set built_binfile 0
3793     set why_msg "unrecognized error"
3794     foreach lib {-lpthreads -lpthread -lthread ""} {
3795         # This kind of wipes out whatever libs the caller may have
3796         # set.  Or maybe theirs will override ours.  How infelicitous.
3797         set options_with_lib [concat $options [list libs=$lib quiet]]
3798         set ccout [gdb_compile_shlib $sources $dest $options_with_lib]
3799         switch -regexp -- $ccout {
3800             ".*no posix threads support.*" {
3801                 set why_msg "missing threads include file"
3802                 break
3803             }
3804             ".*cannot open -lpthread.*" {
3805                 set why_msg "missing runtime threads library"
3806             }
3807             ".*Can't find library for -lpthread.*" {
3808                 set why_msg "missing runtime threads library"
3809             }
3810             {^$} {
3811                 pass "successfully compiled posix threads test case"
3812                 set built_binfile 1
3813                 break
3814             }
3815         }
3816     }
3817     if {!$built_binfile} {
3818         unsupported "couldn't compile $sources: ${why_msg}"
3819         return -1
3820     }
3821 }
3822
3823 # This is just like gdb_compile_pthreads, above, except that we always add the
3824 # objc library for compiling Objective-C programs
3825 proc gdb_compile_objc {source dest type options} {
3826     set built_binfile 0
3827     set why_msg "unrecognized error"
3828     foreach lib {-lobjc -lpthreads -lpthread -lthread solaris} {
3829         # This kind of wipes out whatever libs the caller may have
3830         # set.  Or maybe theirs will override ours.  How infelicitous.
3831         if { $lib == "solaris" } {
3832             set lib "-lpthread -lposix4"
3833         }
3834         if { $lib != "-lobjc" } {
3835           set lib "-lobjc $lib"
3836         }
3837         set options_with_lib [concat $options [list libs=$lib quiet]]
3838         set ccout [gdb_compile $source $dest $type $options_with_lib]
3839         switch -regexp -- $ccout {
3840             ".*no posix threads support.*" {
3841                 set why_msg "missing threads include file"
3842                 break
3843             }
3844             ".*cannot open -lpthread.*" {
3845                 set why_msg "missing runtime threads library"
3846             }
3847             ".*Can't find library for -lpthread.*" {
3848                 set why_msg "missing runtime threads library"
3849             }
3850             {^$} {
3851                 pass "successfully compiled objc with posix threads test case"
3852                 set built_binfile 1
3853                 break
3854             }
3855         }
3856     }
3857     if {!$built_binfile} {
3858         unsupported "couldn't compile [file tail $source]: ${why_msg}"
3859         return -1
3860     }
3861 }
3862
3863 proc send_gdb { string } {
3864     global suppress_flag
3865     if { $suppress_flag } {
3866         return "suppressed"
3867     }
3868     return [remote_send host "$string"]
3869 }
3870
3871 # Send STRING to the inferior's terminal.
3872
3873 proc send_inferior { string } {
3874     global inferior_spawn_id
3875
3876     if {[catch "send -i $inferior_spawn_id -- \$string" errorInfo]} {
3877         return "$errorInfo"
3878     } else {
3879         return ""
3880     }
3881 }
3882
3883 #
3884 #
3885
3886 proc gdb_expect { args } {
3887     if { [llength $args] == 2  && [lindex $args 0] != "-re" } {
3888         set atimeout [lindex $args 0]
3889         set expcode [list [lindex $args 1]]
3890     } else {
3891         set expcode $args
3892     }
3893
3894     # A timeout argument takes precedence, otherwise of all the timeouts
3895     # select the largest.
3896     if [info exists atimeout] {
3897         set tmt $atimeout
3898     } else {
3899         set tmt [get_largest_timeout]
3900     }
3901
3902     global suppress_flag
3903     global remote_suppress_flag
3904     if [info exists remote_suppress_flag] {
3905         set old_val $remote_suppress_flag
3906     }
3907     if [info exists suppress_flag] {
3908         if { $suppress_flag } {
3909             set remote_suppress_flag 1
3910         }
3911     }
3912     set code [catch \
3913         {uplevel remote_expect host $tmt $expcode} string]
3914     if [info exists old_val] {
3915         set remote_suppress_flag $old_val
3916     } else {
3917         if [info exists remote_suppress_flag] {
3918             unset remote_suppress_flag
3919         }
3920     }
3921
3922     if {$code == 1} {
3923         global errorInfo errorCode
3924
3925         return -code error -errorinfo $errorInfo -errorcode $errorCode $string
3926     } else {
3927         return -code $code $string
3928     }
3929 }
3930
3931 # gdb_expect_list TEST SENTINEL LIST -- expect a sequence of outputs
3932 #
3933 # Check for long sequence of output by parts.
3934 # TEST: is the test message to be printed with the test success/fail.
3935 # SENTINEL: Is the terminal pattern indicating that output has finished.
3936 # LIST: is the sequence of outputs to match.
3937 # If the sentinel is recognized early, it is considered an error.
3938 #
3939 # Returns:
3940 #    1 if the test failed,
3941 #    0 if the test passes,
3942 #   -1 if there was an internal error.
3943
3944 proc gdb_expect_list {test sentinel list} {
3945     global gdb_prompt
3946     global suppress_flag
3947     set index 0
3948     set ok 1
3949     if { $suppress_flag } {
3950         set ok 0
3951         unresolved "${test}"
3952     }
3953     while { ${index} < [llength ${list}] } {
3954         set pattern [lindex ${list} ${index}]
3955         set index [expr ${index} + 1]
3956         verbose -log "gdb_expect_list pattern: /$pattern/" 2
3957         if { ${index} == [llength ${list}] } {
3958             if { ${ok} } {
3959                 gdb_expect {
3960                     -re "${pattern}${sentinel}" {
3961                         # pass "${test}, pattern ${index} + sentinel"
3962                     }
3963                     -re "${sentinel}" {
3964                         fail "${test} (pattern ${index} + sentinel)"
3965                         set ok 0
3966                     }
3967                     -re ".*A problem internal to GDB has been detected" {
3968                         fail "${test} (GDB internal error)"
3969                         set ok 0
3970                         gdb_internal_error_resync
3971                     }
3972                     timeout {
3973                         fail "${test} (pattern ${index} + sentinel) (timeout)"
3974                         set ok 0
3975                     }
3976                 }
3977             } else {
3978                 # unresolved "${test}, pattern ${index} + sentinel"
3979             }
3980         } else {
3981             if { ${ok} } {
3982                 gdb_expect {
3983                     -re "${pattern}" {
3984                         # pass "${test}, pattern ${index}"
3985                     }
3986                     -re "${sentinel}" {
3987                         fail "${test} (pattern ${index})"
3988                         set ok 0
3989                     }
3990                     -re ".*A problem internal to GDB has been detected" {
3991                         fail "${test} (GDB internal error)"
3992                         set ok 0
3993                         gdb_internal_error_resync
3994                     }
3995                     timeout {
3996                         fail "${test} (pattern ${index}) (timeout)"
3997                         set ok 0
3998                     }
3999                 }
4000             } else {
4001                 # unresolved "${test}, pattern ${index}"
4002             }
4003         }
4004     }
4005     if { ${ok} } {
4006         pass "${test}"
4007         return 0
4008     } else {
4009         return 1
4010     }
4011 }
4012
4013 #
4014 #
4015 proc gdb_suppress_entire_file { reason } {
4016     global suppress_flag
4017
4018     warning "$reason\n"
4019     set suppress_flag -1
4020 }
4021
4022 #
4023 # Set suppress_flag, which will cause all subsequent calls to send_gdb and
4024 # gdb_expect to fail immediately (until the next call to 
4025 # gdb_stop_suppressing_tests).
4026 #
4027 proc gdb_suppress_tests { args } {
4028     global suppress_flag
4029
4030     return;  # fnf - disable pending review of results where
4031              # testsuite ran better without this
4032     incr suppress_flag
4033
4034     if { $suppress_flag == 1 } {
4035         if { [llength $args] > 0 } {
4036             warning "[lindex $args 0]\n"
4037         } else {
4038             warning "Because of previous failure, all subsequent tests in this group will automatically fail.\n"
4039         }
4040     }
4041 }
4042
4043 #
4044 # Clear suppress_flag.
4045 #
4046 proc gdb_stop_suppressing_tests { } {
4047     global suppress_flag
4048
4049     if [info exists suppress_flag] {
4050         if { $suppress_flag > 0 } {
4051             set suppress_flag 0
4052             clone_output "Tests restarted.\n"
4053         }
4054     } else {
4055         set suppress_flag 0
4056     }
4057 }
4058
4059 proc gdb_clear_suppressed { } {
4060     global suppress_flag
4061
4062     set suppress_flag 0
4063 }
4064
4065 # Spawn the gdb process.
4066 #
4067 # This doesn't expect any output or do any other initialization,
4068 # leaving those to the caller.
4069 #
4070 # Overridable function -- you can override this function in your
4071 # baseboard file.
4072
4073 proc gdb_spawn { } {
4074     default_gdb_spawn
4075 }
4076
4077 # Spawn GDB with CMDLINE_FLAGS appended to the GDBFLAGS global.
4078
4079 proc gdb_spawn_with_cmdline_opts { cmdline_flags } {
4080     global GDBFLAGS
4081
4082     set saved_gdbflags $GDBFLAGS
4083
4084     if {$GDBFLAGS != ""} {
4085         append GDBFLAGS " "
4086     }
4087     append GDBFLAGS $cmdline_flags
4088
4089     set res [gdb_spawn]
4090
4091     set GDBFLAGS $saved_gdbflags
4092
4093     return $res
4094 }
4095
4096 # Start gdb running, wait for prompt, and disable the pagers.
4097
4098 # Overridable function -- you can override this function in your
4099 # baseboard file.
4100
4101 proc gdb_start { } {
4102     default_gdb_start
4103 }
4104
4105 proc gdb_exit { } {
4106     catch default_gdb_exit
4107 }
4108
4109 # Return true if we can spawn a program on the target and attach to
4110 # it.
4111
4112 proc can_spawn_for_attach { } {
4113     # We use exp_pid to get the inferior's pid, assuming that gives
4114     # back the pid of the program.  On remote boards, that would give
4115     # us instead the PID of e.g., the ssh client, etc.
4116     if [is_remote target] then {
4117         return 0
4118     }
4119
4120     # The "attach" command doesn't make sense when the target is
4121     # stub-like, where GDB finds the program already started on
4122     # initial connection.
4123     if {[target_info exists use_gdb_stub]} {
4124         return 0
4125     }
4126
4127     # Assume yes.
4128     return 1
4129 }
4130
4131 # Kill a progress previously started with spawn_wait_for_attach, and
4132 # reap its wait status.  PROC_SPAWN_ID is the spawn id associated with
4133 # the process.
4134
4135 proc kill_wait_spawned_process { proc_spawn_id } {
4136     set pid [exp_pid -i $proc_spawn_id]
4137
4138     verbose -log "killing ${pid}"
4139     remote_exec build "kill -9 ${pid}"
4140
4141     verbose -log "closing ${proc_spawn_id}"
4142     catch "close -i $proc_spawn_id"
4143     verbose -log "waiting for ${proc_spawn_id}"
4144
4145     # If somehow GDB ends up still attached to the process here, a
4146     # blocking wait hangs until gdb is killed (or until gdb / the
4147     # ptracer reaps the exit status too, but that won't happen because
4148     # something went wrong.)  Passing -nowait makes expect tell Tcl to
4149     # wait for the PID in the background.  That's fine because we
4150     # don't care about the exit status.  */
4151     wait -nowait -i $proc_spawn_id
4152 }
4153
4154 # Returns the process id corresponding to the given spawn id.
4155
4156 proc spawn_id_get_pid { spawn_id } {
4157     set testpid [exp_pid -i $spawn_id]
4158
4159     if { [istarget "*-*-cygwin*"] } {
4160         # testpid is the Cygwin PID, GDB uses the Windows PID, which
4161         # might be different due to the way fork/exec works.
4162         set testpid [ exec ps -e | gawk "{ if (\$1 == $testpid) print \$4; }" ]
4163     }
4164
4165     return $testpid
4166 }
4167
4168 # Start a set of programs running and then wait for a bit, to be sure
4169 # that they can be attached to.  Return a list of processes spawn IDs,
4170 # one element for each process spawned.  It's a test error to call
4171 # this when [can_spawn_for_attach] is false.
4172
4173 proc spawn_wait_for_attach { executable_list } {
4174     set spawn_id_list {}
4175
4176     if ![can_spawn_for_attach] {
4177         # The caller should have checked can_spawn_for_attach itself
4178         # before getting here.
4179         error "can't spawn for attach with this target/board"
4180     }
4181
4182     foreach {executable} $executable_list {
4183         # Note we use Expect's spawn, not Tcl's exec, because with
4184         # spawn we control when to wait for/reap the process.  That
4185         # allows killing the process by PID without being subject to
4186         # pid-reuse races.
4187         lappend spawn_id_list [remote_spawn target $executable]
4188     }
4189
4190     sleep 2
4191
4192     return $spawn_id_list
4193 }
4194
4195 #
4196 # gdb_load_cmd -- load a file into the debugger.
4197 #                 ARGS - additional args to load command.
4198 #                 return a -1 if anything goes wrong.
4199 #
4200 proc gdb_load_cmd { args } {
4201     global gdb_prompt
4202
4203     if [target_info exists gdb_load_timeout] {
4204         set loadtimeout [target_info gdb_load_timeout]
4205     } else {
4206         set loadtimeout 1600
4207     }
4208     send_gdb "load $args\n"
4209     verbose "Timeout is now $loadtimeout seconds" 2
4210     gdb_expect $loadtimeout {
4211         -re "Loading section\[^\r\]*\r\n" {
4212             exp_continue
4213         }
4214         -re "Start address\[\r\]*\r\n" {
4215             exp_continue
4216         }
4217         -re "Transfer rate\[\r\]*\r\n" {
4218             exp_continue
4219         }
4220         -re "Memory access error\[^\r\]*\r\n" {
4221             perror "Failed to load program"
4222             return -1
4223         }
4224         -re "$gdb_prompt $" {
4225             return 0
4226         }
4227         -re "(.*)\r\n$gdb_prompt " {
4228             perror "Unexpected reponse from 'load' -- $expect_out(1,string)"
4229             return -1
4230         }
4231         timeout {
4232             perror "Timed out trying to load $args."
4233             return -1
4234         }
4235     }
4236     return -1
4237 }
4238
4239 # Invoke "gcore".  CORE is the name of the core file to write.  TEST
4240 # is the name of the test case.  This will return 1 if the core file
4241 # was created, 0 otherwise.  If this fails to make a core file because
4242 # this configuration of gdb does not support making core files, it
4243 # will call "unsupported", not "fail".  However, if this fails to make
4244 # a core file for some other reason, then it will call "fail".
4245
4246 proc gdb_gcore_cmd {core test} {
4247     global gdb_prompt
4248
4249     set result 0
4250     gdb_test_multiple "gcore $core" $test {
4251         -re "Saved corefile .*\[\r\n\]+$gdb_prompt $" {
4252             pass $test
4253             set result 1
4254         }
4255         -re "(?:Can't create a corefile|Target does not support core file generation\\.)\[\r\n\]+$gdb_prompt $" {
4256             unsupported $test
4257         }
4258     }
4259
4260     return $result
4261 }
4262
4263 # Load core file CORE.  TEST is the name of the test case.
4264 # This will record a pass/fail for loading the core file.
4265 # Returns:
4266 #  1 - core file is successfully loaded
4267 #  0 - core file loaded but has a non fatal error
4268 # -1 - core file failed to load
4269
4270 proc gdb_core_cmd { core test } {
4271     global gdb_prompt
4272
4273     gdb_test_multiple "core $core" "$test" {
4274         -re "\\\[Thread debugging using \[^ \r\n\]* enabled\\\]\r\n" {
4275             exp_continue
4276         }
4277         -re " is not a core dump:.*\r\n$gdb_prompt $" {
4278             fail "$test (bad file format)"
4279             return -1
4280         }
4281         -re ": No such file or directory.*\r\n$gdb_prompt $" {
4282             fail "$test (file not found)"
4283             return -1
4284         }
4285         -re "Couldn't find .* registers in core file.*\r\n$gdb_prompt $" {
4286             fail "$test (incomplete note section)"
4287             return 0
4288         }
4289         -re "Core was generated by .*\r\n$gdb_prompt $" {
4290             pass "$test"
4291             return 1
4292         }
4293         -re ".*$gdb_prompt $" {
4294             fail "$test"
4295             return -1
4296         }
4297         timeout {
4298             fail "$test (timeout)"
4299             return -1
4300         }
4301     }
4302     fail "unsupported output from 'core' command"
4303     return -1
4304 }
4305
4306 # Return the filename to download to the target and load on the target
4307 # for this shared library.  Normally just LIBNAME, unless shared libraries
4308 # for this target have separate link and load images.
4309
4310 proc shlib_target_file { libname } {
4311     return $libname
4312 }
4313
4314 # Return the filename GDB will load symbols from when debugging this
4315 # shared library.  Normally just LIBNAME, unless shared libraries for
4316 # this target have separate link and load images.
4317
4318 proc shlib_symbol_file { libname } {
4319     return $libname
4320 }
4321
4322 # Return the filename to download to the target and load for this
4323 # executable.  Normally just BINFILE unless it is renamed to something
4324 # else for this target.
4325
4326 proc exec_target_file { binfile } {
4327     return $binfile
4328 }
4329
4330 # Return the filename GDB will load symbols from when debugging this
4331 # executable.  Normally just BINFILE unless executables for this target
4332 # have separate files for symbols.
4333
4334 proc exec_symbol_file { binfile } {
4335     return $binfile
4336 }
4337
4338 # Rename the executable file.  Normally this is just BINFILE1 being renamed
4339 # to BINFILE2, but some targets require multiple binary files.
4340 proc gdb_rename_execfile { binfile1 binfile2 } {
4341     file rename -force [exec_target_file ${binfile1}] \
4342                        [exec_target_file ${binfile2}]
4343     if { [exec_target_file ${binfile1}] != [exec_symbol_file ${binfile1}] } {
4344         file rename -force [exec_symbol_file ${binfile1}] \
4345                            [exec_symbol_file ${binfile2}]
4346     }
4347 }
4348
4349 # "Touch" the executable file to update the date.  Normally this is just
4350 # BINFILE, but some targets require multiple files.
4351 proc gdb_touch_execfile { binfile } {
4352     set time [clock seconds]
4353     file mtime [exec_target_file ${binfile}] $time
4354     if { [exec_target_file ${binfile}] != [exec_symbol_file ${binfile}] } {
4355         file mtime [exec_symbol_file ${binfile}] $time
4356     }
4357 }
4358
4359 # Like remote_download but provides a gdb-specific behavior.
4360 #
4361 # If the destination board is remote, the local file FROMFILE is transferred as
4362 # usual with remote_download to TOFILE on the remote board.  The destination
4363 # filename is added to the CLEANFILES global, so it can be cleaned up at the
4364 # end of the test.
4365 #
4366 # If the destination board is local, the destination path TOFILE is passed
4367 # through standard_output_file, and FROMFILE is copied there.
4368 #
4369 # In both cases, if TOFILE is omitted, it defaults to the [file tail] of
4370 # FROMFILE.
4371
4372 proc gdb_remote_download {dest fromfile {tofile {}}} {
4373     # If TOFILE is not given, default to the same filename as FROMFILE.
4374     if {[string length $tofile] == 0} {
4375         set tofile [file tail $fromfile]
4376     }
4377
4378     if {[is_remote $dest]} {
4379         # When the DEST is remote, we simply send the file to DEST.
4380         global cleanfiles
4381
4382         set destname [remote_download $dest $fromfile $tofile]
4383         lappend cleanfiles $destname
4384
4385         return $destname
4386     } else {
4387         # When the DEST is local, we copy the file to the test directory (where
4388         # the executable is).
4389         #
4390         # Note that we pass TOFILE through standard_output_file, regardless of
4391         # whether it is absolute or relative, because we don't want the tests
4392         # to be able to write outside their standard output directory.
4393
4394         set tofile [standard_output_file $tofile]
4395
4396         file copy -force $fromfile $tofile
4397
4398         return $tofile
4399     }
4400 }
4401
4402 # gdb_load_shlib LIB...
4403 #
4404 # Copy the listed library to the target.
4405
4406 proc gdb_load_shlib { file } {
4407     set dest [gdb_remote_download target [shlib_target_file $file]]
4408
4409     if {[is_remote target]} {
4410         # If the target is remote, we need to tell gdb where to find the
4411         # libraries.
4412         #
4413         # We could set this even when not testing remotely, but a user
4414         # generally won't set it unless necessary.  In order to make the tests
4415         # more like the real-life scenarios, we don't set it for local testing.
4416         gdb_test "set solib-search-path [file dirname $file]" "" ""
4417     }
4418
4419     return $dest
4420 }
4421
4422 #
4423 # gdb_load -- load a file into the debugger.  Specifying no file
4424 # defaults to the executable currently being debugged.
4425 # The return value is 0 for success, -1 for failure.
4426 # Many files in config/*.exp override this procedure.
4427 #
4428 proc gdb_load { arg } {
4429     if { $arg != "" } {
4430         return [gdb_file_cmd $arg]
4431     }
4432     return 0
4433 }
4434
4435 # gdb_reload -- load a file into the target.  Called before "running",
4436 # either the first time or after already starting the program once,
4437 # for remote targets.  Most files that override gdb_load should now
4438 # override this instead.
4439
4440 proc gdb_reload { } {
4441     # For the benefit of existing configurations, default to gdb_load.
4442     # Specifying no file defaults to the executable currently being
4443     # debugged.
4444     return [gdb_load ""]
4445 }
4446
4447 proc gdb_continue { function } {
4448     global decimal
4449
4450     return [gdb_test "continue" ".*Breakpoint $decimal, $function .*" "continue to $function"]
4451 }
4452
4453 proc default_gdb_init { test_file_name } {
4454     global gdb_wrapper_initialized
4455     global gdb_wrapper_target
4456     global gdb_test_file_name
4457     global cleanfiles
4458     global pf_prefix
4459     
4460     set cleanfiles {}
4461
4462     gdb_clear_suppressed
4463
4464     set gdb_test_file_name [file rootname [file tail $test_file_name]]
4465
4466     # Make sure that the wrapper is rebuilt
4467     # with the appropriate multilib option.
4468     if { $gdb_wrapper_target != [current_target_name] } {
4469         set gdb_wrapper_initialized 0
4470     }
4471     
4472     # Unlike most tests, we have a small number of tests that generate
4473     # a very large amount of output.  We therefore increase the expect
4474     # buffer size to be able to contain the entire test output.  This
4475     # is especially needed by gdb.base/info-macros.exp.
4476     match_max -d 65536
4477     # Also set this value for the currently running GDB. 
4478     match_max [match_max -d]
4479
4480     # We want to add the name of the TCL testcase to the PASS/FAIL messages.
4481     set pf_prefix "[file tail [file dirname $test_file_name]]/[file tail $test_file_name]:"
4482
4483     global gdb_prompt
4484     if [target_info exists gdb_prompt] {
4485         set gdb_prompt [target_info gdb_prompt]
4486     } else {
4487         set gdb_prompt "\\(gdb\\)"
4488     }
4489     global use_gdb_stub
4490     if [info exists use_gdb_stub] {
4491         unset use_gdb_stub
4492     }
4493 }
4494
4495 # Return a path using GDB_PARALLEL.
4496 # ARGS is a list of path elements to append to "$objdir/$GDB_PARALLEL".
4497 # GDB_PARALLEL must be defined, the caller must check.
4498 #
4499 # The default value for GDB_PARALLEL is, canonically, ".".
4500 # The catch is that tests don't expect an additional "./" in file paths so
4501 # omit any directory for the default case.
4502 # GDB_PARALLEL is written as "yes" for the default case in Makefile.in to mark
4503 # its special handling.
4504
4505 proc make_gdb_parallel_path { args } {
4506     global GDB_PARALLEL objdir
4507     set joiner [list "file" "join" $objdir]
4508     if { [info exists GDB_PARALLEL] && $GDB_PARALLEL != "yes" } {
4509         lappend joiner $GDB_PARALLEL
4510     }
4511     set joiner [concat $joiner $args]
4512     return [eval $joiner]
4513 }
4514
4515 # Turn BASENAME into a full file name in the standard output
4516 # directory.  It is ok if BASENAME is the empty string; in this case
4517 # the directory is returned.
4518
4519 proc standard_output_file {basename} {
4520     global objdir subdir gdb_test_file_name
4521
4522     set dir [make_gdb_parallel_path outputs $subdir $gdb_test_file_name]
4523     file mkdir $dir
4524     return [file join $dir $basename]
4525 }
4526
4527 # Return the name of a file in our standard temporary directory.
4528
4529 proc standard_temp_file {basename} {
4530     # Since a particular runtest invocation is only executing a single test
4531     # file at any given time, we can use the runtest pid to build the
4532     # path of the temp directory.
4533     set dir [make_gdb_parallel_path temp [pid]]
4534     file mkdir $dir
4535     return [file join $dir $basename]
4536 }
4537
4538 # Set 'testfile', 'srcfile', and 'binfile'.
4539 #
4540 # ARGS is a list of source file specifications.
4541 # Without any arguments, the .exp file's base name is used to
4542 # compute the source file name.  The ".c" extension is added in this case.
4543 # If ARGS is not empty, each entry is a source file specification.
4544 # If the specification starts with a ".", it is treated as a suffix
4545 # to append to the .exp file's base name.
4546 # If the specification is the empty string, it is treated as if it
4547 # were ".c".
4548 # Otherwise it is a file name.
4549 # The first file in the list is used to set the 'srcfile' global.
4550 # Each subsequent name is used to set 'srcfile2', 'srcfile3', etc.
4551 #
4552 # Most tests should call this without arguments.
4553 #
4554 # If a completely different binary file name is needed, then it
4555 # should be handled in the .exp file with a suitable comment.
4556
4557 proc standard_testfile {args} {
4558     global gdb_test_file_name
4559     global subdir
4560     global gdb_test_file_last_vars
4561
4562     # Outputs.
4563     global testfile binfile
4564
4565     set testfile $gdb_test_file_name
4566     set binfile [standard_output_file ${testfile}]
4567
4568     if {[llength $args] == 0} {
4569         set args .c
4570     }
4571
4572     # Unset our previous output variables.
4573     # This can help catch hidden bugs.
4574     if {[info exists gdb_test_file_last_vars]} {
4575         foreach varname $gdb_test_file_last_vars {
4576             global $varname
4577             catch {unset $varname}
4578         }
4579     }
4580     # 'executable' is often set by tests.
4581     set gdb_test_file_last_vars {executable}
4582
4583     set suffix ""
4584     foreach arg $args {
4585         set varname srcfile$suffix
4586         global $varname
4587
4588         # Handle an extension.
4589         if {$arg == ""} {
4590             set arg $testfile.c
4591         } elseif {[string range $arg 0 0] == "."} {
4592             set arg $testfile$arg
4593         }
4594
4595         set $varname $arg
4596         lappend gdb_test_file_last_vars $varname
4597
4598         if {$suffix == ""} {
4599             set suffix 2
4600         } else {
4601             incr suffix
4602         }
4603     }
4604 }
4605
4606 # The default timeout used when testing GDB commands.  We want to use
4607 # the same timeout as the default dejagnu timeout, unless the user has
4608 # already provided a specific value (probably through a site.exp file).
4609 global gdb_test_timeout
4610 if ![info exists gdb_test_timeout] {
4611     set gdb_test_timeout $timeout
4612 }
4613
4614 # A list of global variables that GDB testcases should not use.
4615 # We try to prevent their use by monitoring write accesses and raising
4616 # an error when that happens.
4617 set banned_variables { bug_id prms_id }
4618
4619 # A list of procedures that GDB testcases should not use.
4620 # We try to prevent their use by monitoring invocations and raising
4621 # an error when that happens.
4622 set banned_procedures { strace }
4623
4624 # gdb_init is called by runtest at start, but also by several
4625 # tests directly; gdb_finish is only called from within runtest after
4626 # each test source execution.
4627 # Placing several traces by repetitive calls to gdb_init leads
4628 # to problems, as only one trace is removed in gdb_finish.
4629 # To overcome this possible problem, we add a variable that records
4630 # if the banned variables and procedures are already traced.
4631 set banned_traced 0
4632
4633 proc gdb_init { test_file_name } {
4634     # Reset the timeout value to the default.  This way, any testcase
4635     # that changes the timeout value without resetting it cannot affect
4636     # the timeout used in subsequent testcases.
4637     global gdb_test_timeout
4638     global timeout
4639     set timeout $gdb_test_timeout
4640
4641     if { [regexp ".*gdb\.reverse\/.*" $test_file_name]
4642          && [target_info exists gdb_reverse_timeout] } {
4643         set timeout [target_info gdb_reverse_timeout]
4644     }
4645
4646     # If GDB_INOTIFY is given, check for writes to '.'.  This is a
4647     # debugging tool to help confirm that the test suite is
4648     # parallel-safe.  You need "inotifywait" from the
4649     # inotify-tools package to use this.
4650     global GDB_INOTIFY inotify_pid
4651     if {[info exists GDB_INOTIFY] && ![info exists inotify_pid]} {
4652         global outdir tool inotify_log_file
4653
4654         set exclusions {outputs temp gdb[.](log|sum) cache}
4655         set exclusion_re ([join $exclusions |])
4656
4657         set inotify_log_file [standard_temp_file inotify.out]
4658         set inotify_pid [exec inotifywait -r -m -e move,create,delete . \
4659                              --exclude $exclusion_re \
4660                              |& tee -a $outdir/$tool.log $inotify_log_file &]
4661
4662         # Wait for the watches; hopefully this is long enough.
4663         sleep 2
4664
4665         # Clear the log so that we don't emit a warning the first time
4666         # we check it.
4667         set fd [open $inotify_log_file w]
4668         close $fd
4669     }
4670
4671     # Block writes to all banned variables, and invocation of all
4672     # banned procedures...
4673     global banned_variables
4674     global banned_procedures
4675     global banned_traced
4676     if (!$banned_traced) {
4677         foreach banned_var $banned_variables {
4678             global "$banned_var"
4679             trace add variable "$banned_var" write error
4680         }
4681         foreach banned_proc $banned_procedures {
4682             global "$banned_proc"
4683             trace add execution "$banned_proc" enter error
4684         }
4685         set banned_traced 1
4686     }
4687
4688     # We set LC_ALL, LC_CTYPE, and LANG to C so that we get the same
4689     # messages as expected.
4690     setenv LC_ALL C
4691     setenv LC_CTYPE C
4692     setenv LANG C
4693
4694     # Don't let a .inputrc file or an existing setting of INPUTRC mess up
4695     # the test results.  Even if /dev/null doesn't exist on the particular
4696     # platform, the readline library will use the default setting just by
4697     # failing to open the file.  OTOH, opening /dev/null successfully will
4698     # also result in the default settings being used since nothing will be
4699     # read from this file.
4700     setenv INPUTRC "/dev/null"
4701
4702     # The gdb.base/readline.exp arrow key test relies on the standard VT100
4703     # bindings, so make sure that an appropriate terminal is selected.
4704     # The same bug doesn't show up if we use ^P / ^N instead.
4705     setenv TERM "vt100"
4706
4707     # Some tests (for example gdb.base/maint.exp) shell out from gdb to use
4708     # grep.  Clear GREP_OPTIONS to make the behavior predictable,
4709     # especially having color output turned on can cause tests to fail.
4710     setenv GREP_OPTIONS ""
4711
4712     # Clear $gdbserver_reconnect_p.
4713     global gdbserver_reconnect_p
4714     set gdbserver_reconnect_p 1
4715     unset gdbserver_reconnect_p
4716
4717     return [default_gdb_init $test_file_name]
4718 }
4719
4720 proc gdb_finish { } {
4721     global gdbserver_reconnect_p
4722     global gdb_prompt
4723     global cleanfiles
4724
4725     # Exit first, so that the files are no longer in use.
4726     gdb_exit
4727
4728     if { [llength $cleanfiles] > 0 } {
4729         eval remote_file target delete $cleanfiles
4730         set cleanfiles {}
4731     }
4732
4733     # Unblock write access to the banned variables.  Dejagnu typically
4734     # resets some of them between testcases.
4735     global banned_variables
4736     global banned_procedures
4737     global banned_traced
4738     if ($banned_traced) {
4739         foreach banned_var $banned_variables {
4740             global "$banned_var"
4741             trace remove variable "$banned_var" write error
4742         }
4743         foreach banned_proc $banned_procedures {
4744             global "$banned_proc"
4745             trace remove execution "$banned_proc" enter error
4746         }
4747         set banned_traced 0
4748     }
4749 }
4750
4751 global debug_format
4752 set debug_format "unknown"
4753
4754 # Run the gdb command "info source" and extract the debugging format
4755 # information from the output and save it in debug_format.
4756
4757 proc get_debug_format { } {
4758     global gdb_prompt
4759     global verbose
4760     global expect_out
4761     global debug_format
4762
4763     set debug_format "unknown"
4764     send_gdb "info source\n"
4765     gdb_expect 10 {
4766         -re "Compiled with (.*) debugging format.\r\n.*$gdb_prompt $" {
4767             set debug_format $expect_out(1,string)
4768             verbose "debug format is $debug_format"
4769             return 1
4770         }
4771         -re "No current source file.\r\n$gdb_prompt $" {
4772             perror "get_debug_format used when no current source file"
4773             return 0
4774         }
4775         -re "$gdb_prompt $" {
4776             warning "couldn't check debug format (no valid response)."
4777             return 1
4778         }
4779         timeout {
4780             warning "couldn't check debug format (timeout)."
4781             return 1
4782         }
4783     }
4784 }
4785
4786 # Return true if FORMAT matches the debug format the current test was
4787 # compiled with.  FORMAT is a shell-style globbing pattern; it can use
4788 # `*', `[...]', and so on.
4789 #
4790 # This function depends on variables set by `get_debug_format', above.
4791
4792 proc test_debug_format {format} {
4793     global debug_format
4794
4795     return [expr [string match $format $debug_format] != 0]
4796 }
4797
4798 # Like setup_xfail, but takes the name of a debug format (DWARF 1,
4799 # COFF, stabs, etc).  If that format matches the format that the
4800 # current test was compiled with, then the next test is expected to
4801 # fail for any target.  Returns 1 if the next test or set of tests is
4802 # expected to fail, 0 otherwise (or if it is unknown).  Must have
4803 # previously called get_debug_format.
4804 proc setup_xfail_format { format } {
4805     set ret [test_debug_format $format]
4806
4807     if {$ret} then {
4808         setup_xfail "*-*-*"
4809     }
4810     return $ret
4811 }
4812
4813 # gdb_get_line_number TEXT [FILE]
4814 #
4815 # Search the source file FILE, and return the line number of the
4816 # first line containing TEXT.  If no match is found, an error is thrown.
4817
4818 # TEXT is a string literal, not a regular expression.
4819 #
4820 # The default value of FILE is "$srcdir/$subdir/$srcfile".  If FILE is
4821 # specified, and does not start with "/", then it is assumed to be in
4822 # "$srcdir/$subdir".  This is awkward, and can be fixed in the future,
4823 # by changing the callers and the interface at the same time.
4824 # In particular: gdb.base/break.exp, gdb.base/condbreak.exp,
4825 # gdb.base/ena-dis-br.exp.
4826 #
4827 # Use this function to keep your test scripts independent of the
4828 # exact line numbering of the source file.  Don't write:
4829
4830 #   send_gdb "break 20"
4831
4832 # This means that if anyone ever edits your test's source file, 
4833 # your test could break.  Instead, put a comment like this on the
4834 # source file line you want to break at:
4835
4836 #   /* breakpoint spot: frotz.exp: test name */
4837
4838 # and then write, in your test script (which we assume is named
4839 # frotz.exp):
4840
4841 #   send_gdb "break [gdb_get_line_number "frotz.exp: test name"]\n"
4842 #
4843 # (Yes, Tcl knows how to handle the nested quotes and brackets.
4844 # Try this:
4845 #       $ tclsh
4846 #       % puts "foo [lindex "bar baz" 1]"
4847 #       foo baz
4848 #       % 
4849 # Tcl is quite clever, for a little stringy language.)
4850 #
4851 # ===
4852 #
4853 # The previous implementation of this procedure used the gdb search command.
4854 # This version is different:
4855 #
4856 #   . It works with MI, and it also works when gdb is not running.
4857 #
4858 #   . It operates on the build machine, not the host machine.
4859 #
4860 #   . For now, this implementation fakes a current directory of
4861 #     $srcdir/$subdir to be compatible with the old implementation.
4862 #     This will go away eventually and some callers will need to
4863 #     be changed.
4864 #
4865 #   . The TEXT argument is literal text and matches literally,
4866 #     not a regular expression as it was before.
4867 #
4868 #   . State changes in gdb, such as changing the current file
4869 #     and setting $_, no longer happen.
4870 #
4871 # After a bit of time we can forget about the differences from the
4872 # old implementation.
4873 #
4874 # --chastain 2004-08-05
4875
4876 proc gdb_get_line_number { text { file "" } } {
4877     global srcdir
4878     global subdir
4879     global srcfile
4880
4881     if { "$file" == "" } then {
4882         set file "$srcfile"
4883     }
4884     if { ! [regexp "^/" "$file"] } then {
4885         set file "$srcdir/$subdir/$file"
4886     }
4887
4888     if { [ catch { set fd [open "$file"] } message ] } then {
4889         error "$message"
4890     }
4891
4892     set found -1
4893     for { set line 1 } { 1 } { incr line } {
4894         if { [ catch { set nchar [gets "$fd" body] } message ] } then {
4895             error "$message"
4896         }
4897         if { $nchar < 0 } then {
4898             break
4899         }
4900         if { [string first "$text" "$body"] >= 0 } then {
4901             set found $line
4902             break
4903         }
4904     }
4905
4906     if { [ catch { close "$fd" } message ] } then {
4907         error "$message"
4908     }
4909
4910     if {$found == -1} {
4911         error "undefined tag \"$text\""
4912     }
4913
4914     return $found
4915 }
4916
4917 # Continue the program until it ends.
4918 #
4919 # MSSG is the error message that gets printed.  If not given, a
4920 #       default is used.
4921 # COMMAND is the command to invoke.  If not given, "continue" is
4922 #       used.
4923 # ALLOW_EXTRA is a flag indicating whether the test should expect
4924 #       extra output between the "Continuing." line and the program
4925 #       exiting.  By default it is zero; if nonzero, any extra output
4926 #       is accepted.
4927
4928 proc gdb_continue_to_end {{mssg ""} {command continue} {allow_extra 0}} {
4929   global inferior_exited_re use_gdb_stub
4930
4931   if {$mssg == ""} {
4932       set text "continue until exit"
4933   } else {
4934       set text "continue until exit at $mssg"
4935   }
4936   if {$allow_extra} {
4937       set extra ".*"
4938   } else {
4939       set extra ""
4940   }
4941
4942   # By default, we don't rely on exit() behavior of remote stubs --
4943   # it's common for exit() to be implemented as a simple infinite
4944   # loop, or a forced crash/reset.  For native targets, by default, we
4945   # assume process exit is reported as such.  If a non-reliable target
4946   # is used, we set a breakpoint at exit, and continue to that.
4947   if { [target_info exists exit_is_reliable] } {
4948       set exit_is_reliable [target_info exit_is_reliable]
4949   } else {
4950       set exit_is_reliable [expr ! $use_gdb_stub]
4951   }
4952
4953   if { ! $exit_is_reliable } {
4954     if {![gdb_breakpoint "exit"]} {
4955       return 0
4956     }
4957     gdb_test $command "Continuing..*Breakpoint .*exit.*" \
4958         $text
4959   } else {
4960     # Continue until we exit.  Should not stop again.
4961     # Don't bother to check the output of the program, that may be
4962     # extremely tough for some remote systems.
4963     gdb_test $command \
4964       "Continuing.\[\r\n0-9\]+${extra}(... EXIT code 0\[\r\n\]+|$inferior_exited_re normally).*"\
4965         $text
4966   }
4967 }
4968
4969 proc rerun_to_main {} {
4970   global gdb_prompt use_gdb_stub
4971
4972   if $use_gdb_stub {
4973     gdb_run_cmd
4974     gdb_expect {
4975       -re ".*Breakpoint .*main .*$gdb_prompt $"\
4976               {pass "rerun to main" ; return 0}
4977       -re "$gdb_prompt $"\
4978               {fail "rerun to main" ; return 0}
4979       timeout {fail "(timeout) rerun to main" ; return 0}
4980     }
4981   } else {
4982     send_gdb "run\n"
4983     gdb_expect {
4984       -re "The program .* has been started already.*y or n. $" {
4985           send_gdb "y\n"
4986           exp_continue
4987       }
4988       -re "Starting program.*$gdb_prompt $"\
4989               {pass "rerun to main" ; return 0}
4990       -re "$gdb_prompt $"\
4991               {fail "rerun to main" ; return 0}
4992       timeout {fail "(timeout) rerun to main" ; return 0}
4993     }
4994   }
4995 }
4996
4997 # Return true if a test should be skipped due to lack of floating
4998 # point support or GDB can't fetch the contents from floating point
4999 # registers.
5000
5001 gdb_caching_proc gdb_skip_float_test {
5002     if [target_info exists gdb,skip_float_tests] {
5003         return 1
5004     }
5005
5006     # There is an ARM kernel ptrace bug that hardware VFP registers
5007     # are not updated after GDB ptrace set VFP registers.  The bug
5008     # was introduced by kernel commit 8130b9d7b9d858aa04ce67805e8951e3cb6e9b2f
5009     # in 2012 and is fixed in e2dfb4b880146bfd4b6aa8e138c0205407cebbaf
5010     # in May 2016.  In other words, kernels older than 4.6.3, 4.4.14,
5011     # 4.1.27, 3.18.36, and 3.14.73 have this bug.
5012     # This kernel bug is detected by check how does GDB change the
5013     # program result by changing one VFP register.
5014     if { [istarget "arm*-*-linux*"] } {
5015
5016         set compile_flags {debug nowarnings }
5017
5018         # Set up, compile, and execute a test program having VFP
5019         # operations.
5020         set src [standard_temp_file arm_vfp[pid].c]
5021         set exe [standard_temp_file arm_vfp[pid].x]
5022
5023         gdb_produce_source $src {
5024             int main() {
5025                 double d = 4.0;
5026                 int ret;
5027
5028                 asm ("vldr d0, [%0]" : : "r" (&d));
5029                 asm ("vldr d1, [%0]" : : "r" (&d));
5030                 asm (".global break_here\n"
5031                      "break_here:");
5032                 asm ("vcmp.f64 d0, d1\n"
5033                      "vmrs APSR_nzcv, fpscr\n"
5034                      "bne L_value_different\n"
5035                      "movs %0, #0\n"
5036                      "b L_end\n"
5037                      "L_value_different:\n"
5038                      "movs %0, #1\n"
5039                      "L_end:\n" : "=r" (ret) :);
5040
5041                 /* Return $d0 != $d1.  */
5042                 return ret;
5043             }
5044         }
5045
5046         verbose "compiling testfile $src" 2
5047         set lines [gdb_compile $src $exe executable $compile_flags]
5048         file delete $src
5049
5050         if ![string match "" $lines] then {
5051             verbose "testfile compilation failed, returning 1" 2
5052             return 0
5053         }
5054
5055         # No error message, compilation succeeded so now run it via gdb.
5056         # Run the test up to 5 times to detect whether ptrace can
5057         # correctly update VFP registers or not.
5058         set skip_vfp_test 0
5059         for {set i 0} {$i < 5} {incr i} {
5060             global gdb_prompt srcdir subdir
5061
5062             gdb_exit
5063             gdb_start
5064             gdb_reinitialize_dir $srcdir/$subdir
5065             gdb_load "$exe"
5066
5067             runto_main
5068             gdb_test "break *break_here"
5069             gdb_continue_to_breakpoint "break_here"
5070
5071             # Modify $d0 to a different value, so the exit code should
5072             # be 1.
5073             gdb_test "set \$d0 = 5.0"
5074
5075             set test "continue to exit"
5076             gdb_test_multiple "continue" "$test" {
5077                 -re "exited with code 01.*$gdb_prompt $" {
5078                 }
5079                 -re "exited normally.*$gdb_prompt $" {
5080                     # However, the exit code is 0.  That means something
5081                     # wrong in setting VFP registers.
5082                     set skip_vfp_test 1
5083                     break
5084                 }
5085             }
5086         }
5087
5088         gdb_exit
5089         remote_file build delete $exe
5090
5091         return $skip_vfp_test
5092     }
5093     return 0
5094 }
5095
5096 # Print a message and return true if a test should be skipped
5097 # due to lack of stdio support.
5098
5099 proc gdb_skip_stdio_test { msg } {
5100     if [target_info exists gdb,noinferiorio] {
5101         verbose "Skipping test '$msg': no inferior i/o."
5102         return 1
5103     }
5104     return 0
5105 }
5106
5107 proc gdb_skip_bogus_test { msg } {
5108     return 0
5109 }
5110
5111 # Return true if a test should be skipped due to lack of XML support
5112 # in the host GDB.
5113 # NOTE: This must be called while gdb is *not* running.
5114
5115 gdb_caching_proc gdb_skip_xml_test {
5116     global gdb_spawn_id
5117     global gdb_prompt
5118     global srcdir
5119
5120     if { [info exists gdb_spawn_id] } {
5121         error "GDB must not be running in gdb_skip_xml_tests."
5122     }
5123
5124     set xml_file [gdb_remote_download host "${srcdir}/gdb.xml/trivial.xml"]
5125
5126     gdb_start
5127     set xml_missing 0
5128     gdb_test_multiple "set tdesc filename $xml_file" "" {
5129         -re ".*XML support was disabled at compile time.*$gdb_prompt $" {
5130             set xml_missing 1
5131         }
5132         -re ".*$gdb_prompt $" { }
5133     }
5134     gdb_exit
5135     return $xml_missing
5136 }
5137
5138 # Return true if argv[0] is available.
5139
5140 gdb_caching_proc gdb_has_argv0 {
5141     set result 0
5142
5143     # Set up, compile, and execute a test program to check whether
5144     # argv[0] is available.
5145     set src [standard_temp_file has_argv0[pid].c]
5146     set exe [standard_temp_file has_argv0[pid].x]
5147
5148     gdb_produce_source $src {
5149         int main (int argc, char **argv) {
5150             return 0;
5151         }
5152     }
5153
5154     gdb_compile $src $exe executable {debug}
5155
5156     # Helper proc.
5157     proc gdb_has_argv0_1 { exe } {
5158         global srcdir subdir
5159         global gdb_prompt hex
5160
5161         gdb_exit
5162         gdb_start
5163         gdb_reinitialize_dir $srcdir/$subdir
5164         gdb_load "$exe"
5165
5166         # Set breakpoint on main.
5167         gdb_test_multiple "break main" "break main" {
5168             -re "Breakpoint.*${gdb_prompt} $" {
5169             }
5170             -re "${gdb_prompt} $" {
5171                 return 0
5172             }
5173         }
5174
5175         # Run to main.
5176         gdb_run_cmd
5177         gdb_test_multiple "" "run to main" {
5178             -re "Breakpoint.*${gdb_prompt} $" {
5179             }
5180             -re "${gdb_prompt} $" {
5181                 return 0
5182             }
5183         }
5184
5185         set old_elements "200"
5186         set test "show print elements"
5187         gdb_test_multiple $test $test {
5188             -re "Limit on string chars or array elements to print is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
5189                 set old_elements $expect_out(1,string)
5190             }
5191         }
5192         set old_repeats "200"
5193         set test "show print repeats"
5194         gdb_test_multiple $test $test {
5195             -re "Threshold for repeated print elements is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
5196                 set old_repeats $expect_out(1,string)
5197             }
5198         }
5199         gdb_test_no_output "set print elements unlimited" ""
5200         gdb_test_no_output "set print repeats unlimited" ""
5201
5202         set retval 0
5203         # Check whether argc is 1.
5204         gdb_test_multiple "p argc" "p argc" {
5205             -re " = 1\r\n${gdb_prompt} $" {
5206
5207                 gdb_test_multiple "p argv\[0\]" "p argv\[0\]" {
5208                     -re " = $hex \".*[file tail $exe]\"\r\n${gdb_prompt} $" {
5209                         set retval 1
5210                     }
5211                     -re "${gdb_prompt} $" {
5212                     }
5213                 }
5214             }
5215             -re "${gdb_prompt} $" {
5216             }
5217         }
5218         
5219         gdb_test_no_output "set print elements $old_elements" ""
5220         gdb_test_no_output "set print repeats $old_repeats" ""
5221
5222         return $retval
5223     }
5224
5225     set result [gdb_has_argv0_1 $exe]
5226
5227     gdb_exit
5228     file delete $src
5229     file delete $exe
5230
5231     if { !$result
5232       && ([istarget *-*-linux*]
5233           || [istarget *-*-freebsd*] || [istarget *-*-kfreebsd*]
5234           || [istarget *-*-netbsd*] || [istarget *-*-knetbsd*]
5235           || [istarget *-*-openbsd*]
5236           || [istarget *-*-darwin*]
5237           || [istarget *-*-solaris*]
5238           || [istarget *-*-aix*]
5239           || [istarget *-*-gnu*]
5240           || [istarget *-*-cygwin*] || [istarget *-*-mingw32*]
5241           || [istarget *-*-*djgpp*] || [istarget *-*-go32*]
5242           || [istarget *-wince-pe] || [istarget *-*-mingw32ce*]
5243           || [istarget *-*-symbianelf*]
5244           || [istarget *-*-osf*]
5245           || [istarget *-*-dicos*]
5246           || [istarget *-*-nto*]
5247           || [istarget *-*-*vms*]
5248           || [istarget *-*-lynx*178]) } {
5249         fail "argv\[0\] should be available on this target"
5250     }
5251
5252     return $result
5253 }
5254
5255 # Note: the procedure gdb_gnu_strip_debug will produce an executable called
5256 # ${binfile}.dbglnk, which is just like the executable ($binfile) but without
5257 # the debuginfo. Instead $binfile has a .gnu_debuglink section which contains
5258 # the name of a debuginfo only file. This file will be stored in the same
5259 # subdirectory.
5260
5261 # Functions for separate debug info testing
5262
5263 # starting with an executable:
5264 # foo --> original executable
5265
5266 # at the end of the process we have:
5267 # foo.stripped --> foo w/o debug info
5268 # foo.debug --> foo's debug info
5269 # foo --> like foo, but with a new .gnu_debuglink section pointing to foo.debug.
5270
5271 # Fetch the build id from the file.
5272 # Returns "" if there is none.
5273
5274 proc get_build_id { filename } {
5275     if { ([istarget "*-*-mingw*"]
5276           || [istarget *-*-cygwin*]) } {
5277         set objdump_program [gdb_find_objdump]
5278         set result [catch {set data [exec $objdump_program -p $filename | grep signature | cut "-d " -f4]} output]
5279         verbose "result is $result"
5280         verbose "output is $output"
5281         if {$result == 1} {
5282             return ""
5283         }
5284         return $data
5285     } else {
5286         set tmp [standard_output_file "${filename}-tmp"]
5287         set objcopy_program [gdb_find_objcopy]
5288         set result [catch "exec $objcopy_program -j .note.gnu.build-id -O binary $filename $tmp" output]
5289         verbose "result is $result"
5290         verbose "output is $output"
5291         if {$result == 1} {
5292             return ""
5293         }
5294         set fi [open $tmp]
5295         fconfigure $fi -translation binary
5296         # Skip the NOTE header.
5297         read $fi 16
5298         set data [read $fi]
5299         close $fi
5300         file delete $tmp
5301         if ![string compare $data ""] then {
5302             return ""
5303         }
5304         # Convert it to hex.
5305         binary scan $data H* data
5306         return $data
5307     }
5308 }
5309
5310 # Return the build-id hex string (usually 160 bits as 40 hex characters)
5311 # converted to the form: .build-id/ab/cdef1234...89.debug
5312 # Return "" if no build-id found.
5313 proc build_id_debug_filename_get { filename } {
5314     set data [get_build_id $filename]
5315     if { $data == "" } {
5316         return ""
5317     }
5318     regsub {^..} $data {\0/} data
5319     return ".build-id/${data}.debug"
5320 }
5321
5322 # Create stripped files for DEST, replacing it.  If ARGS is passed, it is a
5323 # list of optional flags.  The only currently supported flag is no-main,
5324 # which removes the symbol entry for main from the separate debug file.
5325 #
5326 # Function returns zero on success.  Function will return non-zero failure code
5327 # on some targets not supporting separate debug info (such as i386-msdos).
5328
5329 proc gdb_gnu_strip_debug { dest args } {
5330
5331     # Use the first separate debug info file location searched by GDB so the
5332     # run cannot be broken by some stale file searched with higher precedence.
5333     set debug_file "${dest}.debug"
5334
5335     set strip_to_file_program [transform strip]
5336     set objcopy_program [gdb_find_objcopy]
5337
5338     set debug_link [file tail $debug_file]
5339     set stripped_file "${dest}.stripped"
5340
5341     # Get rid of the debug info, and store result in stripped_file
5342     # something like gdb/testsuite/gdb.base/blah.stripped.
5343     set result [catch "exec $strip_to_file_program --strip-debug ${dest} -o ${stripped_file}" output]
5344     verbose "result is $result"
5345     verbose "output is $output"
5346     if {$result == 1} {
5347       return 1
5348     }
5349
5350     # Workaround PR binutils/10802:
5351     # Preserve the 'x' bit also for PIEs (Position Independent Executables).
5352     set perm [file attributes ${dest} -permissions]
5353     file attributes ${stripped_file} -permissions $perm
5354
5355     # Get rid of everything but the debug info, and store result in debug_file
5356     # This will be in the .debug subdirectory, see above.
5357     set result [catch "exec $strip_to_file_program --only-keep-debug ${dest} -o ${debug_file}" output]
5358     verbose "result is $result"
5359     verbose "output is $output"
5360     if {$result == 1} {
5361       return 1
5362     }
5363
5364     # If no-main is passed, strip the symbol for main from the separate
5365     # file.  This is to simulate the behavior of elfutils's eu-strip, which
5366     # leaves the symtab in the original file only.  There's no way to get
5367     # objcopy or strip to remove the symbol table without also removing the
5368     # debugging sections, so this is as close as we can get.
5369     if { [llength $args] == 1 && [lindex $args 0] == "no-main" } {
5370         set result [catch "exec $objcopy_program -N main ${debug_file} ${debug_file}-tmp" output]
5371         verbose "result is $result"
5372         verbose "output is $output"
5373         if {$result == 1} {
5374             return 1
5375         }
5376         file delete "${debug_file}"
5377         file rename "${debug_file}-tmp" "${debug_file}"
5378     }
5379
5380     # Link the two previous output files together, adding the .gnu_debuglink
5381     # section to the stripped_file, containing a pointer to the debug_file,
5382     # save the new file in dest.
5383     # This will be the regular executable filename, in the usual location.
5384     set result [catch "exec $objcopy_program --add-gnu-debuglink=${debug_file} ${stripped_file} ${dest}" output]
5385     verbose "result is $result"
5386     verbose "output is $output"
5387     if {$result == 1} {
5388       return 1
5389     }
5390
5391     # Workaround PR binutils/10802:
5392     # Preserve the 'x' bit also for PIEs (Position Independent Executables).
5393     set perm [file attributes ${stripped_file} -permissions]
5394     file attributes ${dest} -permissions $perm
5395
5396     return 0
5397 }
5398
5399 # Test the output of GDB_COMMAND matches the pattern obtained
5400 # by concatenating all elements of EXPECTED_LINES.  This makes
5401 # it possible to split otherwise very long string into pieces.
5402 # If third argument is not empty, it's used as the name of the
5403 # test to be printed on pass/fail.
5404 proc help_test_raw { gdb_command expected_lines args } {
5405     set message $gdb_command
5406     if [llength $args]>0 then {
5407         set message [lindex $args 0]
5408     } 
5409     set expected_output [join $expected_lines ""]
5410     gdb_test "${gdb_command}" "${expected_output}" $message
5411 }
5412
5413 # Test the output of "help COMMAND_CLASS". EXPECTED_INITIAL_LINES
5414 # are regular expressions that should match the beginning of output,
5415 # before the list of commands in that class.  The presence of 
5416 # command list and standard epilogue will be tested automatically.
5417 # Notice that the '[' and ']' characters don't need to be escaped for strings
5418 # wrapped in {} braces.
5419 proc test_class_help { command_class expected_initial_lines args } {
5420     set l_stock_body {
5421         "List of commands\:.*[\r\n]+"
5422         "Type \"help\" followed by command name for full documentation\.[\r\n]+"
5423         "Type \"apropos word\" to search for commands related to \"word\"\.[\r\n]+"
5424         "Command name abbreviations are allowed if unambiguous\." 
5425     }
5426     set l_entire_body [concat $expected_initial_lines $l_stock_body]
5427
5428     eval [list help_test_raw "help ${command_class}" $l_entire_body] $args
5429 }
5430
5431 # COMMAND_LIST should have either one element -- command to test, or
5432 # two elements -- abbreviated command to test, and full command the first
5433 # element is abbreviation of.
5434 # The command must be a prefix command.  EXPECTED_INITIAL_LINES
5435 # are regular expressions that should match the beginning of output,
5436 # before the list of subcommands.  The presence of 
5437 # subcommand list and standard epilogue will be tested automatically.
5438 proc test_prefix_command_help { command_list expected_initial_lines args } {
5439     set command [lindex $command_list 0]   
5440     if {[llength $command_list]>1} {        
5441         set full_command [lindex $command_list 1]
5442     } else {
5443         set full_command $command
5444     }
5445     # Use 'list' and not just {} because we want variables to
5446     # be expanded in this list.
5447     set l_stock_body [list\
5448          "List of $full_command subcommands\:.*\[\r\n\]+"\
5449          "Type \"help $full_command\" followed by $full_command subcommand name for full documentation\.\[\r\n\]+"\
5450          "Type \"apropos word\" to search for commands related to \"word\"\.\[\r\n\]+"\
5451          "Command name abbreviations are allowed if unambiguous\."]
5452     set l_entire_body [concat $expected_initial_lines $l_stock_body]
5453     if {[llength $args]>0} {
5454         help_test_raw "help ${command}" $l_entire_body [lindex $args 0]
5455     } else {
5456         help_test_raw "help ${command}" $l_entire_body
5457     }
5458 }
5459
5460 # Build executable named EXECUTABLE from specifications that allow
5461 # different options to be passed to different sub-compilations.
5462 # TESTNAME is the name of the test; this is passed to 'untested' if
5463 # something fails.
5464 # OPTIONS is passed to the final link, using gdb_compile.  If OPTIONS
5465 # contains the option "pthreads", then gdb_compile_pthreads is used.
5466 # ARGS is a flat list of source specifications, of the form:
5467 #    { SOURCE1 OPTIONS1 [ SOURCE2 OPTIONS2 ]... }
5468 # Each SOURCE is compiled to an object file using its OPTIONS,
5469 # using gdb_compile.
5470 # Returns 0 on success, -1 on failure.
5471 proc build_executable_from_specs {testname executable options args} {
5472     global subdir
5473     global srcdir
5474
5475     set binfile [standard_output_file $executable]
5476
5477     set info_options ""
5478     if { [lsearch -exact $options "c++"] >= 0 } {
5479         set info_options "c++"
5480     }
5481     if [get_compiler_info ${info_options}] {
5482         return -1
5483     }
5484
5485     set func gdb_compile
5486     set func_index [lsearch -regexp $options {^(pthreads|shlib|shlib_pthreads)$}]
5487     if {$func_index != -1} {
5488         set func "${func}_[lindex $options $func_index]"
5489     }
5490
5491     # gdb_compile_shlib and gdb_compile_shlib_pthreads do not use the 3rd
5492     # parameter.  They also requires $sources while gdb_compile and
5493     # gdb_compile_pthreads require $objects.  Moreover they ignore any options.
5494     if [string match gdb_compile_shlib* $func] {
5495         set sources_path {}
5496         foreach {s local_options} $args {
5497             if { [regexp "^/" "$s"] } then {
5498                 lappend sources_path "$s"
5499             } else {
5500                 lappend sources_path "$srcdir/$subdir/$s"
5501             }
5502         }
5503         set ret [$func $sources_path "${binfile}" $options]
5504     } elseif {[lsearch -exact $options rust] != -1} {
5505         set sources_path {}
5506         foreach {s local_options} $args {
5507             if { [regexp "^/" "$s"] } then {
5508                 lappend sources_path "$s"
5509             } else {
5510                 lappend sources_path "$srcdir/$subdir/$s"
5511             }
5512         }
5513         set ret [gdb_compile_rust $sources_path "${binfile}" $options]
5514     } else {
5515         set objects {}
5516         set i 0
5517         foreach {s local_options} $args {
5518             if { ! [regexp "^/" "$s"] } then {
5519                 set s "$srcdir/$subdir/$s"
5520             }
5521             if  { [gdb_compile "${s}" "${binfile}${i}.o" object $local_options] != "" } {
5522                 untested $testname
5523                 return -1
5524             }
5525             lappend objects "${binfile}${i}.o"
5526             incr i
5527         }
5528         set ret [$func $objects "${binfile}" executable $options]
5529     }
5530     if  { $ret != "" } {
5531         untested $testname
5532         return -1
5533     }
5534
5535     return 0
5536 }
5537
5538 # Build executable named EXECUTABLE, from SOURCES.  If SOURCES are not
5539 # provided, uses $EXECUTABLE.c.  The TESTNAME paramer is the name of test
5540 # to pass to untested, if something is wrong.  OPTIONS are passed
5541 # to gdb_compile directly.
5542 proc build_executable { testname executable {sources ""} {options {debug}} } {
5543     if {[llength $sources]==0} {
5544         set sources ${executable}.c
5545     }
5546
5547     set arglist [list $testname $executable $options]
5548     foreach source $sources {
5549         lappend arglist $source $options
5550     }
5551
5552     return [eval build_executable_from_specs $arglist]
5553 }
5554
5555 # Starts fresh GDB binary and loads an optional executable into GDB.
5556 # Usage: clean_restart [executable]
5557 # EXECUTABLE is the basename of the binary.
5558
5559 proc clean_restart { args } {
5560     global srcdir
5561     global subdir
5562
5563     if { [llength $args] > 1 } {
5564         error "bad number of args: [llength $args]"
5565     }
5566
5567     gdb_exit
5568     gdb_start
5569     gdb_reinitialize_dir $srcdir/$subdir
5570
5571     if { [llength $args] >= 1 } {
5572         set executable [lindex $args 0]
5573         set binfile [standard_output_file ${executable}]
5574         gdb_load ${binfile}
5575     }
5576 }
5577
5578 # Prepares for testing by calling build_executable_full, then
5579 # clean_restart.
5580 # TESTNAME is the name of the test.
5581 # Each element in ARGS is a list of the form
5582 #    { EXECUTABLE OPTIONS SOURCE_SPEC... }
5583 # These are passed to build_executable_from_specs, which see.
5584 # The last EXECUTABLE is passed to clean_restart.
5585 # Returns 0 on success, non-zero on failure.
5586 proc prepare_for_testing_full {testname args} {
5587     foreach spec $args {
5588         if {[eval build_executable_from_specs [list $testname] $spec] == -1} {
5589             return -1
5590         }
5591         set executable [lindex $spec 0]
5592     }
5593     clean_restart $executable
5594     return 0
5595 }
5596
5597 # Prepares for testing, by calling build_executable, and then clean_restart.
5598 # Please refer to build_executable for parameter description.
5599 proc prepare_for_testing { testname executable {sources ""} {options {debug}}} {
5600
5601     if {[build_executable $testname $executable $sources $options] == -1} {
5602         return -1
5603     }
5604     clean_restart $executable
5605
5606     return 0
5607 }
5608
5609 # Retrieve the value of EXP in the inferior, represented in format
5610 # specified in FMT (using "printFMT").  DEFAULT is used as fallback if
5611 # print fails.  TEST is the test message to use.  It can be omitted,
5612 # in which case a test message is built from EXP.
5613
5614 proc get_valueof { fmt exp default {test ""} } {
5615     global gdb_prompt
5616
5617     if {$test == "" } {
5618         set test "get valueof \"${exp}\""
5619     }
5620
5621     set val ${default}
5622     gdb_test_multiple "print${fmt} ${exp}" "$test" {
5623         -re "\\$\[0-9\]* = (\[^\r\n\]*)\[\r\n\]*$gdb_prompt $" {
5624             set val $expect_out(1,string)
5625             pass "$test ($val)"
5626         }
5627         timeout {
5628             fail "$test (timeout)"
5629         }
5630     }
5631     return ${val}
5632 }
5633
5634 # Retrieve the value of EXP in the inferior, as a signed decimal value
5635 # (using "print /d").  DEFAULT is used as fallback if print fails.
5636 # TEST is the test message to use.  It can be omitted, in which case
5637 # a test message is built from EXP.
5638
5639 proc get_integer_valueof { exp default {test ""} } {
5640     global gdb_prompt
5641
5642     if {$test == ""} {
5643         set test "get integer valueof \"${exp}\""
5644     }
5645
5646     set val ${default}
5647     gdb_test_multiple "print /d ${exp}" "$test" {
5648         -re "\\$\[0-9\]* = (\[-\]*\[0-9\]*).*$gdb_prompt $" {
5649             set val $expect_out(1,string)
5650             pass "$test"
5651         }
5652         timeout {
5653             fail "$test (timeout)"
5654         }
5655     }
5656     return ${val}
5657 }
5658
5659 # Retrieve the value of EXP in the inferior, as an hexadecimal value
5660 # (using "print /x").  DEFAULT is used as fallback if print fails.
5661 # TEST is the test message to use.  It can be omitted, in which case
5662 # a test message is built from EXP.
5663
5664 proc get_hexadecimal_valueof { exp default {test ""} } {
5665     global gdb_prompt
5666
5667     if {$test == ""} {
5668         set test "get hexadecimal valueof \"${exp}\""
5669     }
5670
5671     set val ${default}
5672     gdb_test_multiple "print /x ${exp}" $test {
5673         -re "\\$\[0-9\]* = (0x\[0-9a-zA-Z\]+).*$gdb_prompt $" {
5674             set val $expect_out(1,string)
5675             pass "$test"
5676         }
5677     }
5678     return ${val}
5679 }
5680
5681 # Retrieve the size of TYPE in the inferior, as a decimal value.  DEFAULT
5682 # is used as fallback if print fails.  TEST is the test message to use.
5683 # It can be omitted, in which case a test message is 'sizeof (TYPE)'.
5684
5685 proc get_sizeof { type default {test ""} } {
5686     return [get_integer_valueof "sizeof (${type})" $default $test]
5687 }
5688
5689 proc get_target_charset { } {
5690     global gdb_prompt
5691
5692     gdb_test_multiple "show target-charset" "" {
5693         -re "The target character set is \"auto; currently (\[^\"\]*)\".*$gdb_prompt $" {
5694             return $expect_out(1,string)
5695         }
5696         -re "The target character set is \"(\[^\"\]*)\".*$gdb_prompt $" {
5697             return $expect_out(1,string)
5698         }
5699     }
5700
5701     # Pick a reasonable default.
5702     warning "Unable to read target-charset."
5703     return "UTF-8"
5704 }
5705
5706 # Get the address of VAR.
5707
5708 proc get_var_address { var } {
5709     global gdb_prompt hex
5710
5711     # Match output like:
5712     # $1 = (int *) 0x0
5713     # $5 = (int (*)()) 0
5714     # $6 = (int (*)()) 0x24 <function_bar>
5715
5716     gdb_test_multiple "print &${var}" "get address of ${var}" {
5717         -re "\\\$\[0-9\]+ = \\(.*\\) (0|$hex)( <${var}>)?\[\r\n\]+${gdb_prompt} $"
5718         {
5719             pass "get address of ${var}"
5720             if { $expect_out(1,string) == "0" } {
5721                 return "0x0"
5722             } else {
5723                 return $expect_out(1,string)
5724             }
5725         }
5726     }
5727     return ""
5728 }
5729
5730 # Get the current value for remotetimeout and return it.
5731 proc get_remotetimeout { } {
5732     global gdb_prompt
5733     global decimal
5734
5735     gdb_test_multiple "show remotetimeout" "" {
5736         -re "Timeout limit to wait for target to respond is ($decimal).*$gdb_prompt $" {
5737             return $expect_out(1,string)
5738         }
5739     }
5740
5741     # Pick the default that gdb uses
5742     warning "Unable to read remotetimeout"
5743     return 300
5744 }
5745
5746 # Set the remotetimeout to the specified timeout.  Nothing is returned.
5747 proc set_remotetimeout { timeout } {
5748     global gdb_prompt
5749
5750     gdb_test_multiple "set remotetimeout $timeout" "" {
5751         -re "$gdb_prompt $" {
5752             verbose "Set remotetimeout to $timeout\n"
5753         }
5754     }
5755 }
5756
5757 # Get the target's current endianness and return it.
5758 proc get_endianness { } {
5759     global gdb_prompt
5760
5761     gdb_test_multiple "show endian" "determine endianness" {
5762         -re ".* (little|big) endian.*\r\n$gdb_prompt $" {
5763             # Pass silently.
5764             return $expect_out(1,string)
5765         }
5766     }
5767     return "little"
5768 }
5769
5770 # ROOT and FULL are file names.  Returns the relative path from ROOT
5771 # to FULL.  Note that FULL must be in a subdirectory of ROOT.
5772 # For example, given ROOT = /usr/bin and FULL = /usr/bin/ls, this
5773 # will return "ls".
5774
5775 proc relative_filename {root full} {
5776     set root_split [file split $root]
5777     set full_split [file split $full]
5778
5779     set len [llength $root_split]
5780
5781     if {[eval file join $root_split]
5782         != [eval file join [lrange $full_split 0 [expr {$len - 1}]]]} {
5783         error "$full not a subdir of $root"
5784     }
5785
5786     return [eval file join [lrange $full_split $len end]]
5787 }
5788
5789 # Log gdb command line and script if requested.
5790 if {[info exists TRANSCRIPT]} {
5791   rename send_gdb real_send_gdb
5792   rename remote_spawn real_remote_spawn
5793   rename remote_close real_remote_close
5794
5795   global gdb_transcript
5796   set gdb_transcript ""
5797
5798   global gdb_trans_count
5799   set gdb_trans_count 1
5800
5801   proc remote_spawn {args} {
5802     global gdb_transcript gdb_trans_count outdir
5803
5804     if {$gdb_transcript != ""} {
5805       close $gdb_transcript
5806     }
5807     set gdb_transcript [open [file join $outdir transcript.$gdb_trans_count] w]
5808     puts $gdb_transcript [lindex $args 1]
5809     incr gdb_trans_count
5810
5811     return [uplevel real_remote_spawn $args]
5812   }
5813
5814   proc remote_close {args} {
5815     global gdb_transcript
5816
5817     if {$gdb_transcript != ""} {
5818       close $gdb_transcript
5819       set gdb_transcript ""
5820     }
5821
5822     return [uplevel real_remote_close $args]
5823   }
5824
5825   proc send_gdb {args} {
5826     global gdb_transcript
5827
5828     if {$gdb_transcript != ""} {
5829       puts -nonewline $gdb_transcript [lindex $args 0]
5830     }
5831
5832     return [uplevel real_send_gdb $args]
5833   }
5834 }
5835
5836 # If GDB_PARALLEL exists, then set up the parallel-mode directories.
5837 if {[info exists GDB_PARALLEL]} {
5838     if {[is_remote host]} {
5839         unset GDB_PARALLEL
5840     } else {
5841         file mkdir \
5842             [make_gdb_parallel_path outputs] \
5843             [make_gdb_parallel_path temp] \
5844             [make_gdb_parallel_path cache]
5845     }
5846 }
5847
5848 proc core_find {binfile {deletefiles {}} {arg ""}} {
5849     global objdir subdir
5850
5851     set destcore "$binfile.core"
5852     file delete $destcore
5853
5854     # Create a core file named "$destcore" rather than just "core", to
5855     # avoid problems with sys admin types that like to regularly prune all
5856     # files named "core" from the system.
5857     #
5858     # Arbitrarily try setting the core size limit to "unlimited" since
5859     # this does not hurt on systems where the command does not work and
5860     # allows us to generate a core on systems where it does.
5861     #
5862     # Some systems append "core" to the name of the program; others append
5863     # the name of the program to "core"; still others (like Linux, as of
5864     # May 2003) create cores named "core.PID".  In the latter case, we
5865     # could have many core files lying around, and it may be difficult to
5866     # tell which one is ours, so let's run the program in a subdirectory.
5867     set found 0
5868     set coredir [standard_output_file coredir.[getpid]]
5869     file mkdir $coredir
5870     catch "system \"(cd ${coredir}; ulimit -c unlimited; ${binfile} ${arg}; true) >/dev/null 2>&1\""
5871     #      remote_exec host "${binfile}"
5872     foreach i "${coredir}/core ${coredir}/core.coremaker.c ${binfile}.core" {
5873         if [remote_file build exists $i] {
5874             remote_exec build "mv $i $destcore"
5875             set found 1
5876         }
5877     }
5878     # Check for "core.PID".
5879     if { $found == 0 } {
5880         set names [glob -nocomplain -directory $coredir core.*]
5881         if {[llength $names] == 1} {
5882             set corefile [file join $coredir [lindex $names 0]]
5883             remote_exec build "mv $corefile $destcore"
5884             set found 1
5885         }
5886     }
5887     if { $found == 0 } {
5888         # The braindamaged HPUX shell quits after the ulimit -c above
5889         # without executing ${binfile}.  So we try again without the
5890         # ulimit here if we didn't find a core file above.
5891         # Oh, I should mention that any "braindamaged" non-Unix system has
5892         # the same problem. I like the cd bit too, it's really neat'n stuff.
5893         catch "system \"(cd ${objdir}/${subdir}; ${binfile}; true) >/dev/null 2>&1\""
5894         foreach i "${objdir}/${subdir}/core ${objdir}/${subdir}/core.coremaker.c ${binfile}.core" {
5895             if [remote_file build exists $i] {
5896                 remote_exec build "mv $i $destcore"
5897                 set found 1
5898             }
5899         }
5900     }
5901
5902     # Try to clean up after ourselves. 
5903     foreach deletefile $deletefiles {
5904         remote_file build delete [file join $coredir $deletefile]
5905     }
5906     remote_exec build "rmdir $coredir"
5907         
5908     if { $found == 0  } {
5909         warning "can't generate a core file - core tests suppressed - check ulimit -c"
5910         return ""
5911     }
5912     return $destcore
5913 }
5914
5915 # gdb_target_symbol_prefix compiles a test program and then examines
5916 # the output from objdump to determine the prefix (such as underscore)
5917 # for linker symbol prefixes.
5918
5919 gdb_caching_proc gdb_target_symbol_prefix {
5920     # Set up and compile a simple test program...
5921     set src [standard_temp_file main[pid].c]
5922     set exe [standard_temp_file main[pid].x]
5923
5924     gdb_produce_source $src {
5925         int main() {
5926             return 0;
5927         }
5928     }
5929
5930     verbose "compiling testfile $src" 2
5931     set compile_flags {debug nowarnings quiet}
5932     set lines [gdb_compile $src $exe executable $compile_flags]
5933
5934     set prefix ""
5935
5936     if ![string match "" $lines] then {
5937         verbose "gdb_target_symbol_prefix: testfile compilation failed, returning null prefix" 2
5938     } else {
5939         set objdump_program [gdb_find_objdump]
5940         set result [catch "exec $objdump_program --syms $exe" output]
5941
5942         if { $result == 0 \
5943              && ![regexp -lineanchor \
5944                   { ([^ a-zA-Z0-9]*)main$} $output dummy prefix] } {
5945             verbose "gdb_target_symbol_prefix: Could not find main in objdump output; returning null prefix" 2
5946         }
5947     }
5948
5949     file delete $src
5950     file delete $exe
5951
5952     return $prefix
5953 }
5954
5955 # gdb_target_symbol returns the provided symbol with the correct prefix
5956 # prepended.  (See gdb_target_symbol_prefix, above.)
5957
5958 proc gdb_target_symbol { symbol } {
5959   set prefix [gdb_target_symbol_prefix]
5960   return "${prefix}${symbol}"
5961 }
5962
5963 # gdb_target_symbol_prefix_flags_asm returns a string that can be
5964 # added to gdb_compile options to define the C-preprocessor macro
5965 # SYMBOL_PREFIX with a value that can be prepended to symbols
5966 # for targets which require a prefix, such as underscore.
5967 #
5968 # This version (_asm) defines the prefix without double quotes
5969 # surrounding the prefix.  It is used to define the macro
5970 # SYMBOL_PREFIX for assembly language files.  Another version, below,
5971 # is used for symbols in inline assembler in C/C++ files.
5972
5973 # The lack of quotes in this version (_asm) makes it possible to
5974 # define supporting macros in the .S file.  (The version which
5975 # uses quotes for the prefix won't work for such files since it's
5976 # impossible to define a quote-stripping macro in C.)
5977 #
5978 # It's possible to use this version (_asm) for C/C++ source files too,
5979 # but a string is usually required in such files; providing a version
5980 # (no _asm) which encloses the prefix with double quotes makes it
5981 # somewhat easier to define the supporting macros in the test case.
5982
5983 proc gdb_target_symbol_prefix_flags_asm {} {
5984     set prefix [gdb_target_symbol_prefix]
5985     if {$prefix ne ""} {
5986         return "additional_flags=-DSYMBOL_PREFIX=$prefix"
5987     } else {
5988         return "";
5989     }
5990 }
5991
5992 # gdb_target_symbol_prefix_flags returns the same string as
5993 # gdb_target_symbol_prefix_flags_asm, above, but with the prefix
5994 # enclosed in double quotes if there is a prefix.
5995 #
5996 # See the comment for gdb_target_symbol_prefix_flags_asm for an
5997 # extended discussion.
5998
5999 proc gdb_target_symbol_prefix_flags {} {
6000     set prefix [gdb_target_symbol_prefix]
6001     if {$prefix ne ""} {
6002         return "additional_flags=-DSYMBOL_PREFIX=\"$prefix\""
6003     } else {
6004         return "";
6005     }
6006 }
6007
6008 # A wrapper for 'remote_exec host' that passes or fails a test.
6009 # Returns 0 if all went well, nonzero on failure.
6010 # TEST is the name of the test, other arguments are as for remote_exec.
6011
6012 proc run_on_host { test program args } {
6013     verbose -log "run_on_host: $program $args"
6014     # remote_exec doesn't work properly if the output is set but the
6015     # input is the empty string -- so replace an empty input with
6016     # /dev/null.
6017     if {[llength $args] > 1 && [lindex $args 1] == ""} {
6018         set args [lreplace $args 1 1 "/dev/null"]
6019     }
6020     set result [eval remote_exec host [list $program] $args]
6021     verbose "result is $result"
6022     set status [lindex $result 0]
6023     set output [lindex $result 1]
6024     if {$status == 0} {
6025         pass $test
6026         return 0
6027     } else {
6028         verbose -log "run_on_host failed: $output"
6029         fail $test
6030         return -1
6031     }
6032 }
6033
6034 # Return non-zero if "board_info debug_flags" mentions Fission.
6035 # http://gcc.gnu.org/wiki/DebugFission
6036 # Fission doesn't support everything yet.
6037 # This supports working around bug 15954.
6038
6039 proc using_fission { } {
6040     set debug_flags [board_info [target_info name] debug_flags]
6041     return [regexp -- "-gsplit-dwarf" $debug_flags]
6042 }
6043
6044 # Search the caller's ARGS list and set variables according to the list of
6045 # valid options described by ARGSET.
6046 #
6047 # The first member of each one- or two-element list in ARGSET defines the
6048 # name of a variable that will be added to the caller's scope.
6049 #
6050 # If only one element is given to describe an option, it the value is
6051 # 0 if the option is not present in (the caller's) ARGS or 1 if
6052 # it is.
6053 #
6054 # If two elements are given, the second element is the default value of
6055 # the variable.  This is then overwritten if the option exists in ARGS.
6056 #
6057 # Any parse_args elements in (the caller's) ARGS will be removed, leaving
6058 # any optional components.
6059
6060 # Example:
6061 # proc myproc {foo args} {
6062 #  parse_args {{bar} {baz "abc"} {qux}}
6063 #    # ...
6064 # }
6065 # myproc ABC -bar -baz DEF peanut butter
6066 # will define the following variables in myproc:
6067 # foo (=ABC), bar (=1), baz (=DEF), and qux (=0)
6068 # args will be the list {peanut butter}
6069
6070 proc parse_args { argset } {
6071     upvar args args
6072
6073     foreach argument $argset {
6074         if {[llength $argument] == 1} {
6075             # No default specified, so we assume that we should set
6076             # the value to 1 if the arg is present and 0 if it's not.
6077             # It is assumed that no value is given with the argument.
6078             set result [lsearch -exact $args "-$argument"]
6079             if {$result != -1} then {
6080                 uplevel 1 [list set $argument 1]
6081                 set args [lreplace $args $result $result]
6082             } else {
6083                 uplevel 1 [list set $argument 0]
6084             }
6085         } elseif {[llength $argument] == 2} {
6086             # There are two items in the argument.  The second is a
6087             # default value to use if the item is not present.
6088             # Otherwise, the variable is set to whatever is provided
6089             # after the item in the args.
6090             set arg [lindex $argument 0]
6091             set result [lsearch -exact $args "-[lindex $arg 0]"]
6092             if {$result != -1} then {
6093                 uplevel 1 [list set $arg [lindex $args [expr $result+1]]]
6094                 set args [lreplace $args $result [expr $result+1]]
6095             } else {
6096                 uplevel 1 [list set $arg [lindex $argument 1]]
6097             }
6098         } else {
6099             error "Badly formatted argument \"$argument\" in argument set"
6100         }
6101     }
6102
6103     # The remaining args should be checked to see that they match the
6104     # number of items expected to be passed into the procedure...
6105 }
6106
6107 # Capture the output of COMMAND in a string ignoring PREFIX (a regexp);
6108 # return that string.
6109
6110 proc capture_command_output { command prefix } {
6111     global gdb_prompt
6112     global expect_out
6113
6114     set output_string ""
6115     gdb_test_multiple "$command" "capture_command_output for $command" {
6116         -re "[string_to_regexp ${command}]\[\r\n\]+${prefix}(.*)\[\r\n\]+$gdb_prompt $" {
6117             set output_string $expect_out(1,string)
6118         }
6119     }
6120     return $output_string
6121 }
6122
6123 # A convenience function that joins all the arguments together, with a
6124 # regexp that matches exactly one end of line in between each argument.
6125 # This function is ideal to write the expected output of a GDB command
6126 # that generates more than a couple of lines, as this allows us to write
6127 # each line as a separate string, which is easier to read by a human
6128 # being.
6129
6130 proc multi_line { args } {
6131     return [join $args "\r\n"]
6132 }
6133
6134 # Similar to the above, but while multi_line is meant to be used to
6135 # match GDB output, this one is meant to be used to build strings to
6136 # send as GDB input.
6137
6138 proc multi_line_input { args } {
6139     return [join $args "\n"]
6140 }
6141
6142 # Return the version of the DejaGnu framework.
6143 #
6144 # The return value is a list containing the major, minor and patch version
6145 # numbers.  If the version does not contain a minor or patch number, they will
6146 # be set to 0.  For example:
6147 #
6148 #   1.6   -> {1 6 0}
6149 #   1.6.1 -> {1 6 1}
6150 #   2     -> {2 0 0}
6151
6152 proc dejagnu_version { } {
6153     # The frame_version variable is defined by DejaGnu, in runtest.exp.
6154     global frame_version
6155
6156     verbose -log "DejaGnu version: $frame_version"
6157     verbose -log "Expect version: [exp_version]"
6158     verbose -log "Tcl version: [info tclversion]"
6159
6160     set dg_ver [split $frame_version .]
6161
6162     while { [llength $dg_ver] < 3 } {
6163         lappend dg_ver 0
6164     }
6165
6166     return $dg_ver
6167 }
6168
6169 # Define user-defined command COMMAND using the COMMAND_LIST as the
6170 # command's definition.  The terminating "end" is added automatically.
6171
6172 proc gdb_define_cmd {command command_list} {
6173     global gdb_prompt
6174
6175     set input [multi_line_input {*}$command_list "end"]
6176     set test "define $command"
6177
6178     gdb_test_multiple "define $command" $test {
6179         -re "End with"  {
6180             gdb_test_multiple $input $test {
6181                 -re "\r\n$gdb_prompt " {
6182                 }
6183             }
6184         }
6185     }
6186 }
6187
6188 # Always load compatibility stuff.
6189 load_lib future.exp