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