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