gdb/
[platform/upstream/binutils.git] / gdb / testsuite / lib / gdb.exp
1 # Copyright 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
2 # 2003, 2004, 2005, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
3
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 # This file was written by Fred Fish. (fnf@cygnus.com)
18
19 # Generic gdb subroutines that should work for any target.  If these
20 # need to be modified for any target, it can be done with a variable
21 # or by passing arguments.
22
23 if {$tool == ""} {
24     # Tests would fail, logs on get_compiler_info() would be missing.
25     send_error "`site.exp' not found, run `make site.exp'!\n"
26     exit 2
27 }
28
29 load_lib libgloss.exp
30
31 global GDB
32
33 if [info exists TOOL_EXECUTABLE] {
34     set GDB $TOOL_EXECUTABLE;
35 }
36 if ![info exists GDB] {
37     if ![is_remote host] {
38         set GDB [findfile $base_dir/../../gdb/gdb "$base_dir/../../gdb/gdb" [transform gdb]]
39     } else {
40         set GDB [transform gdb];
41     }
42 }
43 verbose "using GDB = $GDB" 2
44
45 # GDBFLAGS is available for the user to set on the command line.
46 # E.g. make check RUNTESTFLAGS=GDBFLAGS=mumble
47 # Testcases may use it to add additional flags, but they must:
48 # - append new flags, not overwrite
49 # - restore the original value when done
50 global GDBFLAGS
51 if ![info exists GDBFLAGS] {
52     set GDBFLAGS ""
53 }
54 verbose "using GDBFLAGS = $GDBFLAGS" 2
55
56 # INTERNAL_GDBFLAGS contains flags that the testsuite requires.
57 global INTERNAL_GDBFLAGS
58 if ![info exists INTERNAL_GDBFLAGS] {
59     set INTERNAL_GDBFLAGS "-nw -nx"
60 }
61
62 # The variable gdb_prompt is a regexp which matches the gdb prompt.
63 # Set it if it is not already set.
64 global gdb_prompt
65 if ![info exists gdb_prompt] then {
66     set gdb_prompt "\[(\]gdb\[)\]"
67 }
68
69 # The variable fullname_syntax_POSIX is a regexp which matches a POSIX 
70 # absolute path ie. /foo/ 
71 set fullname_syntax_POSIX {/[^\n]*/}
72 # The variable fullname_syntax_UNC is a regexp which matches a Windows 
73 # UNC path ie. \\D\foo\ 
74 set fullname_syntax_UNC {\\\\[^\\]+\\[^\n]+\\}
75 # The variable fullname_syntax_DOS_CASE is a regexp which matches a 
76 # particular DOS case that GDB most likely will output
77 # ie. \foo\, but don't match \\.*\ 
78 set fullname_syntax_DOS_CASE {\\[^\\][^\n]*\\}
79 # The variable fullname_syntax_DOS is a regexp which matches a DOS path
80 # ie. a:\foo\ && a:foo\ 
81 set fullname_syntax_DOS {[a-zA-Z]:[^\n]*\\}
82 # The variable fullname_syntax is a regexp which matches what GDB considers
83 # an absolute path. It is currently debatable if the Windows style paths 
84 # d:foo and \abc should be considered valid as an absolute path.
85 # Also, the purpse of this regexp is not to recognize a well formed 
86 # absolute path, but to say with certainty that a path is absolute.
87 set fullname_syntax "($fullname_syntax_POSIX|$fullname_syntax_UNC|$fullname_syntax_DOS_CASE|$fullname_syntax_DOS)"
88
89 # Needed for some tests under Cygwin.
90 global EXEEXT
91 global env
92
93 if ![info exists env(EXEEXT)] {
94     set EXEEXT ""
95 } else {
96     set EXEEXT $env(EXEEXT)
97 }
98
99 set octal "\[0-7\]+"
100
101 ### Only procedures should come after this point.
102
103 #
104 # gdb_version -- extract and print the version number of GDB
105 #
106 proc default_gdb_version {} {
107     global GDB
108     global INTERNAL_GDBFLAGS GDBFLAGS
109     global gdb_prompt
110     set output [remote_exec host "$GDB $INTERNAL_GDBFLAGS --version"]
111     set tmp [lindex $output 1];
112     set version ""
113     regexp " \[0-9\]\[^ \t\n\r\]+" "$tmp" version
114     if ![is_remote host] {
115         clone_output "[which $GDB] version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
116     } else {
117         clone_output "$GDB on remote host version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
118     }
119 }
120
121 proc gdb_version { } {
122     return [default_gdb_version];
123 }
124
125 #
126 # gdb_unload -- unload a file if one is loaded
127 #
128
129 proc gdb_unload {} {
130     global verbose
131     global GDB
132     global gdb_prompt
133     send_gdb "file\n"
134     gdb_expect 60 {
135         -re "No executable file now\[^\r\n\]*\[\r\n\]" { exp_continue }
136         -re "No symbol file now\[^\r\n\]*\[\r\n\]" { exp_continue }
137         -re "A program is being debugged already..*Kill it.*y or n. $"\
138             { send_gdb "y\n"
139                 verbose "\t\tKilling previous program being debugged"
140             exp_continue
141         }
142         -re "Discard symbol table from .*y or n.*$" {
143             send_gdb "y\n"
144             exp_continue
145         }
146         -re "$gdb_prompt $" {}
147         timeout {
148             perror "couldn't unload file in $GDB (timed out)."
149             return -1
150         }
151     }
152 }
153
154 # Many of the tests depend on setting breakpoints at various places and
155 # running until that breakpoint is reached.  At times, we want to start
156 # with a clean-slate with respect to breakpoints, so this utility proc 
157 # lets us do this without duplicating this code everywhere.
158 #
159
160 proc delete_breakpoints {} {
161     global gdb_prompt
162
163     # we need a larger timeout value here or this thing just confuses
164     # itself.  May need a better implementation if possible. - guo
165     #
166     send_gdb "delete breakpoints\n"
167     gdb_expect 100 {
168          -re "Delete all breakpoints.*y or n.*$" {
169             send_gdb "y\n";
170             exp_continue
171         }
172          -re "$gdb_prompt $" { # This happens if there were no breakpoints
173             }
174          timeout { perror "Delete all breakpoints in delete_breakpoints (timeout)" ; return }
175     }
176     send_gdb "info breakpoints\n"
177     gdb_expect 100 {
178          -re "No breakpoints or watchpoints..*$gdb_prompt $" {}
179          -re "$gdb_prompt $" { perror "breakpoints not deleted" ; return }
180          -re "Delete all breakpoints.*or n.*$" {
181             send_gdb "y\n";
182             exp_continue
183         }
184          timeout { perror "info breakpoints (timeout)" ; return }
185     }
186 }
187
188
189 #
190 # Generic run command.
191 #
192 # The second pattern below matches up to the first newline *only*.
193 # Using ``.*$'' could swallow up output that we attempt to match
194 # elsewhere.
195 #
196 proc gdb_run_cmd {args} {
197     global gdb_prompt
198
199     if [target_info exists gdb_init_command] {
200         send_gdb "[target_info gdb_init_command]\n";
201         gdb_expect 30 {
202             -re "$gdb_prompt $" { }
203             default {
204                 perror "gdb_init_command for target failed";
205                 return;
206             }
207         }
208     }
209
210     if [target_info exists use_gdb_stub] {
211         if [target_info exists gdb,do_reload_on_run] {
212             if { [gdb_reload] != 0 } {
213                 return;
214             }
215             send_gdb "continue\n";
216             gdb_expect 60 {
217                 -re "Continu\[^\r\n\]*\[\r\n\]" {}
218                 default {}
219             }
220             return;
221         }
222
223         if [target_info exists gdb,start_symbol] {
224             set start [target_info gdb,start_symbol];
225         } else {
226             set start "start";
227         }
228         send_gdb  "jump *$start\n"
229         set start_attempt 1;
230         while { $start_attempt } {
231             # Cap (re)start attempts at three to ensure that this loop
232             # always eventually fails.  Don't worry about trying to be
233             # clever and not send a command when it has failed.
234             if [expr $start_attempt > 3] {
235                 perror "Jump to start() failed (retry count exceeded)";
236                 return;
237             }
238             set start_attempt [expr $start_attempt + 1];
239             gdb_expect 30 {
240                 -re "Continuing at \[^\r\n\]*\[\r\n\]" {
241                     set start_attempt 0;
242                 }
243                 -re "No symbol \"_start\" in current.*$gdb_prompt $" {
244                     perror "Can't find start symbol to run in gdb_run";
245                     return;
246                 }
247                 -re "No symbol \"start\" in current.*$gdb_prompt $" {
248                     send_gdb "jump *_start\n";
249                 }
250                 -re "No symbol.*context.*$gdb_prompt $" {
251                     set start_attempt 0;
252                 }
253                 -re "Line.* Jump anyway.*y or n. $" {
254                     send_gdb "y\n"
255                 }
256                 -re "The program is not being run.*$gdb_prompt $" {
257                     if { [gdb_reload] != 0 } {
258                         return;
259                     }
260                     send_gdb "jump *$start\n";
261                 }
262                 timeout {
263                     perror "Jump to start() failed (timeout)"; 
264                     return
265                 }
266             }
267         }
268         if [target_info exists gdb_stub] {
269             gdb_expect 60 {
270                 -re "$gdb_prompt $" {
271                     send_gdb "continue\n"
272                 }
273             }
274         }
275         return
276     }
277
278     if [target_info exists gdb,do_reload_on_run] {
279         if { [gdb_reload] != 0 } {
280             return;
281         }
282     }
283     send_gdb "run $args\n"
284 # This doesn't work quite right yet.
285 # Use -notransfer here so that test cases (like chng-sym.exp)
286 # may test for additional start-up messages.
287    gdb_expect 60 {
288         -re "The program .* has been started already.*y or n. $" {
289             send_gdb "y\n"
290             exp_continue
291         }
292         -notransfer -re "Starting program: \[^\r\n\]*" {}
293         -notransfer -re "$gdb_prompt $" {
294             # There is no more input expected.
295         }
296     }
297 }
298
299 # Generic start command.  Return 0 if we could start the program, -1
300 # if we could not.
301
302 proc gdb_start_cmd {args} {
303     global gdb_prompt
304
305     if [target_info exists gdb_init_command] {
306         send_gdb "[target_info gdb_init_command]\n";
307         gdb_expect 30 {
308             -re "$gdb_prompt $" { }
309             default {
310                 perror "gdb_init_command for target failed";
311                 return;
312             }
313         }
314     }
315
316     if [target_info exists use_gdb_stub] {
317         return -1
318     }
319
320     send_gdb "start $args\n"
321     # Use -notransfer here so that test cases (like chng-sym.exp)
322     # may test for additional start-up messages.
323     gdb_expect 60 {
324         -re "The program .* has been started already.*y or n. $" {
325             send_gdb "y\n"
326             exp_continue
327         }
328         -notransfer -re "Starting program: \[^\r\n\]*" {
329             return 0
330         }
331     }
332     return -1
333 }
334
335 # Set a breakpoint at FUNCTION.  If there is an additional argument it is
336 # a list of options; the supported options are allow-pending, temporary,
337 # and no-message.
338
339 proc gdb_breakpoint { function args } {
340     global gdb_prompt
341     global decimal
342
343     set pending_response n
344     if {[lsearch -exact [lindex $args 0] allow-pending] != -1} {
345         set pending_response y
346     }
347
348     set break_command "break"
349     set break_message "Breakpoint"
350     if {[lsearch -exact [lindex $args 0] temporary] != -1} {
351         set break_command "tbreak"
352         set break_message "Temporary breakpoint"
353     }
354
355     set no_message 0
356     if {[lsearch -exact [lindex $args 0] no-message] != -1} {
357         set no_message 1
358     }
359
360     send_gdb "$break_command $function\n"
361     # The first two regexps are what we get with -g, the third is without -g.
362     gdb_expect 30 {
363         -re "$break_message \[0-9\]* at .*: file .*, line $decimal.\r\n$gdb_prompt $" {}
364         -re "$break_message \[0-9\]*: file .*, line $decimal.\r\n$gdb_prompt $" {}
365         -re "$break_message \[0-9\]* at .*$gdb_prompt $" {}
366         -re "$break_message \[0-9\]* \\(.*\\) pending.*$gdb_prompt $" {
367                 if {$pending_response == "n"} {
368                         if { $no_message == 0 } {
369                                 fail "setting breakpoint at $function"
370                         }
371                         return 0
372                 }
373         }
374         -re "Make breakpoint pending.*y or \\\[n\\\]. $" { 
375                 send_gdb "$pending_response\n"
376                 exp_continue
377         }
378         -re "$gdb_prompt $" {
379                 if { $no_message == 0 } {
380                         fail "setting breakpoint at $function"
381                 }
382                 return 0
383         }
384         timeout {
385                 if { $no_message == 0 } {
386                         fail "setting breakpoint at $function (timeout)"
387                 }
388                 return 0
389         }
390     }
391     return 1;
392 }    
393
394 # Set breakpoint at function and run gdb until it breaks there.
395 # Since this is the only breakpoint that will be set, if it stops
396 # at a breakpoint, we will assume it is the one we want.  We can't
397 # just compare to "function" because it might be a fully qualified,
398 # single quoted C++ function specifier.  If there's an additional argument,
399 # pass it to gdb_breakpoint.
400
401 proc runto { function args } {
402     global gdb_prompt
403     global decimal
404
405     delete_breakpoints
406
407     if ![gdb_breakpoint $function [lindex $args 0]] {
408         return 0;
409     }
410
411     gdb_run_cmd
412     
413     # the "at foo.c:36" output we get with -g.
414     # the "in func" output we get without -g.
415     gdb_expect 30 {
416         -re "Break.* at .*:$decimal.*$gdb_prompt $" {
417             return 1
418         }
419         -re "Breakpoint \[0-9\]*, \[0-9xa-f\]* in .*$gdb_prompt $" { 
420             return 1
421         }
422         -re "The target does not support running in non-stop mode.\r\n$gdb_prompt $" {
423             unsupported "Non-stop mode not supported"
424             return 0
425         }
426         -re ".*A problem internal to GDB has been detected" {
427             fail "running to $function in runto (GDB internal error)"
428             gdb_internal_error_resync
429             return 0
430         }
431         -re "$gdb_prompt $" { 
432             fail "running to $function in runto"
433             return 0
434         }
435         eof { 
436             fail "running to $function in runto (end of file)"
437             return 0
438         }
439         timeout { 
440             fail "running to $function in runto (timeout)"
441             return 0
442         }
443     }
444     return 1
445 }
446
447 #
448 # runto_main -- ask gdb to run until we hit a breakpoint at main.
449 #               The case where the target uses stubs has to be handled
450 #               specially--if it uses stubs, assuming we hit
451 #               breakpoint() and just step out of the function.
452 #
453 proc runto_main { } {
454     global gdb_prompt
455     global decimal
456
457     if ![target_info exists gdb_stub] {
458         return [runto main]
459     }                   
460
461     delete_breakpoints
462
463     gdb_step_for_stub;
464
465     return 1
466 }
467
468
469 ### Continue, and expect to hit a breakpoint.
470 ### Report a pass or fail, depending on whether it seems to have
471 ### worked.  Use NAME as part of the test name; each call to
472 ### continue_to_breakpoint should use a NAME which is unique within
473 ### that test file.
474 proc gdb_continue_to_breakpoint {name {location_pattern .*}} {
475     global gdb_prompt
476     set full_name "continue to breakpoint: $name"
477
478     send_gdb "continue\n"
479     gdb_expect {
480         -re "Breakpoint .* (at|in) $location_pattern\r\n$gdb_prompt $" {
481             pass $full_name
482         }
483         -re ".*$gdb_prompt $" {
484             fail $full_name
485         }
486         timeout { 
487             fail "$full_name (timeout)"
488         }
489     }
490 }
491
492
493 # gdb_internal_error_resync:
494 #
495 # Answer the questions GDB asks after it reports an internal error
496 # until we get back to a GDB prompt.  Decline to quit the debugging
497 # session, and decline to create a core file.  Return non-zero if the
498 # resync succeeds.
499 #
500 # This procedure just answers whatever questions come up until it sees
501 # a GDB prompt; it doesn't require you to have matched the input up to
502 # any specific point.  However, it only answers questions it sees in
503 # the output itself, so if you've matched a question, you had better
504 # answer it yourself before calling this.
505 #
506 # You can use this function thus:
507 #
508 # gdb_expect {
509 #     ...
510 #     -re ".*A problem internal to GDB has been detected" {
511 #         gdb_internal_error_resync
512 #     }
513 #     ...
514 # }
515 #
516 proc gdb_internal_error_resync {} {
517     global gdb_prompt
518
519     set count 0
520     while {$count < 10} {
521         gdb_expect {
522             -re "Quit this debugging session\\? \\(y or n\\) $" {
523                 send_gdb "n\n"
524                 incr count
525             }
526             -re "Create a core file of GDB\\? \\(y or n\\) $" {
527                 send_gdb "n\n"
528                 incr count
529             }
530             -re "$gdb_prompt $" {
531                 # We're resynchronized.
532                 return 1
533             }
534             timeout {
535                 perror "Could not resync from internal error (timeout)"
536                 return 0
537             }
538         }
539     }
540     perror "Could not resync from internal error (resync count exceeded)"
541     return 0
542 }
543
544
545 # gdb_test_multiple COMMAND MESSAGE EXPECT_ARGUMENTS
546 # Send a command to gdb; test the result.
547 #
548 # COMMAND is the command to execute, send to GDB with send_gdb.  If
549 #   this is the null string no command is sent.
550 # MESSAGE is a message to be printed with the built-in failure patterns
551 #   if one of them matches.  If MESSAGE is empty COMMAND will be used.
552 # EXPECT_ARGUMENTS will be fed to expect in addition to the standard
553 #   patterns.  Pattern elements will be evaluated in the caller's
554 #   context; action elements will be executed in the caller's context.
555 #   Unlike patterns for gdb_test, these patterns should generally include
556 #   the final newline and prompt.
557 #
558 # Returns:
559 #    1 if the test failed, according to a built-in failure pattern
560 #    0 if only user-supplied patterns matched
561 #   -1 if there was an internal error.
562 #  
563 # You can use this function thus:
564 #
565 # gdb_test_multiple "print foo" "test foo" {
566 #    -re "expected output 1" {
567 #        pass "print foo"
568 #    }
569 #    -re "expected output 2" {
570 #        fail "print foo"
571 #    }
572 # }
573 #
574 # The standard patterns, such as "Program exited..." and "A problem
575 # ...", all being implicitly appended to that list.
576 #
577 proc gdb_test_multiple { command message user_code } {
578     global verbose
579     global gdb_prompt
580     global GDB
581     upvar timeout timeout
582     upvar expect_out expect_out
583
584     if { $message == "" } {
585         set message $command
586     }
587
588     if [string match "*\[\r\n\]" $command] {
589         error "Invalid trailing newline in \"$message\" test"
590     }
591
592     # TCL/EXPECT WART ALERT
593     # Expect does something very strange when it receives a single braced
594     # argument.  It splits it along word separators and performs substitutions.
595     # This means that { "[ab]" } is evaluated as "[ab]", but { "\[ab\]" } is
596     # evaluated as "\[ab\]".  But that's not how TCL normally works; inside a
597     # double-quoted list item, "\[ab\]" is just a long way of representing
598     # "[ab]", because the backslashes will be removed by lindex.
599
600     # Unfortunately, there appears to be no easy way to duplicate the splitting
601     # that expect will do from within TCL.  And many places make use of the
602     # "\[0-9\]" construct, so we need to support that; and some places make use
603     # of the "[func]" construct, so we need to support that too.  In order to
604     # get this right we have to substitute quoted list elements differently
605     # from braced list elements.
606
607     # We do this roughly the same way that Expect does it.  We have to use two
608     # lists, because if we leave unquoted newlines in the argument to uplevel
609     # they'll be treated as command separators, and if we escape newlines
610     # we mangle newlines inside of command blocks.  This assumes that the
611     # input doesn't contain a pattern which contains actual embedded newlines
612     # at this point!
613
614     regsub -all {\n} ${user_code} { } subst_code
615     set subst_code [uplevel list $subst_code]
616
617     set processed_code ""
618     set patterns ""
619     set expecting_action 0
620     set expecting_arg 0
621     foreach item $user_code subst_item $subst_code {
622         if { $item == "-n" || $item == "-notransfer" || $item == "-nocase" } {
623             lappend processed_code $item
624             continue
625         }
626         if { $item == "-indices" || $item == "-re" || $item == "-ex" } {
627             lappend processed_code $item
628             continue
629         }
630         if { $item == "-timeout" } {
631             set expecting_arg 1
632             lappend processed_code $item
633             continue
634         }
635         if { $expecting_arg } {
636             set expecting_arg 0
637             lappend processed_code $item
638             continue
639         }
640         if { $expecting_action } {
641             lappend processed_code "uplevel [list $item]"
642             set expecting_action 0
643             # Cosmetic, no effect on the list.
644             append processed_code "\n"
645             continue
646         }
647         set expecting_action 1
648         lappend processed_code $subst_item
649         if {$patterns != ""} {
650             append patterns "; "
651         }
652         append patterns "\"$subst_item\""
653     }
654
655     # Also purely cosmetic.
656     regsub -all {\r} $patterns {\\r} patterns
657     regsub -all {\n} $patterns {\\n} patterns
658
659     if $verbose>2 then {
660         send_user "Sending \"$command\" to gdb\n"
661         send_user "Looking to match \"$patterns\"\n"
662         send_user "Message is \"$message\"\n"
663     }
664
665     set result -1
666     set string "${command}\n";
667     if { $command != "" } {
668         while { "$string" != "" } {
669             set foo [string first "\n" "$string"];
670             set len [string length "$string"];
671             if { $foo < [expr $len - 1] } {
672                 set str [string range "$string" 0 $foo];
673                 if { [send_gdb "$str"] != "" } {
674                     global suppress_flag;
675
676                     if { ! $suppress_flag } {
677                         perror "Couldn't send $command to GDB.";
678                     }
679                     fail "$message";
680                     return $result;
681                 }
682                 # since we're checking if each line of the multi-line
683                 # command are 'accepted' by GDB here,
684                 # we need to set -notransfer expect option so that
685                 # command output is not lost for pattern matching
686                 # - guo
687                 gdb_expect 2 {
688                     -notransfer -re "\[\r\n\]" { verbose "partial: match" 3 }
689                     timeout { verbose "partial: timeout" 3 }
690                 }
691                 set string [string range "$string" [expr $foo + 1] end];
692             } else {
693                 break;
694             }
695         }
696         if { "$string" != "" } {
697             if { [send_gdb "$string"] != "" } {
698                 global suppress_flag;
699
700                 if { ! $suppress_flag } {
701                     perror "Couldn't send $command to GDB.";
702                 }
703                 fail "$message";
704                 return $result;
705             }
706         }
707     }
708
709     if [target_info exists gdb,timeout] {
710         set tmt [target_info gdb,timeout];
711     } else {
712         if [info exists timeout] {
713             set tmt $timeout;
714         } else {
715             global timeout;
716             if [info exists timeout] {
717                 set tmt $timeout;
718             } else {
719                 set tmt 60;
720             }
721         }
722     }
723
724     set code {
725          -re ".*A problem internal to GDB has been detected" {
726              fail "$message (GDB internal error)"
727              gdb_internal_error_resync
728          }
729          -re "\\*\\*\\* DOSEXIT code.*" {
730              if { $message != "" } {
731                  fail "$message";
732              }
733              gdb_suppress_entire_file "GDB died";
734              set result -1;
735          }
736     }
737     append code $processed_code
738     append code {
739          -re "Ending remote debugging.*$gdb_prompt $" {
740             if ![isnative] then {
741                 warning "Can`t communicate to remote target."
742             }
743             gdb_exit
744             gdb_start
745             set result -1
746         }
747          -re "Undefined\[a-z\]* command:.*$gdb_prompt $" {
748             perror "Undefined command \"$command\"."
749             fail "$message"
750             set result 1
751         }
752          -re "Ambiguous command.*$gdb_prompt $" {
753             perror "\"$command\" is not a unique command name."
754             fail "$message"
755             set result 1
756         }
757          -re "Program exited with code \[0-9\]+.*$gdb_prompt $" {
758             if ![string match "" $message] then {
759                 set errmsg "$message (the program exited)"
760             } else {
761                 set errmsg "$command (the program exited)"
762             }
763             fail "$errmsg"
764             set result -1
765         }
766          -re "Program exited normally.*$gdb_prompt $" {
767             if ![string match "" $message] then {
768                 set errmsg "$message (the program exited)"
769             } else {
770                 set errmsg "$command (the program exited)"
771             }
772             fail "$errmsg"
773             set result -1
774         }
775          -re "The program is not being run.*$gdb_prompt $" {
776             if ![string match "" $message] then {
777                 set errmsg "$message (the program is no longer running)"
778             } else {
779                 set errmsg "$command (the program is no longer running)"
780             }
781             fail "$errmsg"
782             set result -1
783         }
784          -re "\r\n$gdb_prompt $" {
785             if ![string match "" $message] then {
786                 fail "$message"
787             }
788             set result 1
789         }
790          "<return>" {
791             send_gdb "\n"
792             perror "Window too small."
793             fail "$message"
794             set result -1
795         }
796         -re "\\((y or n|y or \\\[n\\\]|\\\[y\\\] or n)\\) " {
797             send_gdb "n\n"
798             gdb_expect -re "$gdb_prompt $"
799             fail "$message (got interactive prompt)"
800             set result -1
801         }
802         -re "\\\[0\\\] cancel\r\n\\\[1\\\] all.*\r\n> $" {
803             send_gdb "0\n"
804             gdb_expect -re "$gdb_prompt $"
805             fail "$message (got breakpoint menu)"
806             set result -1
807         }
808          eof {
809              perror "Process no longer exists"
810              if { $message != "" } {
811                  fail "$message"
812              }
813              return -1
814         }
815          full_buffer {
816             perror "internal buffer is full."
817             fail "$message"
818             set result -1
819         }
820         timeout {
821             if ![string match "" $message] then {
822                 fail "$message (timeout)"
823             }
824             set result 1
825         }
826     }
827
828     set result 0
829     set code [catch {gdb_expect $tmt $code} string]
830     if {$code == 1} {
831         global errorInfo errorCode;
832         return -code error -errorinfo $errorInfo -errorcode $errorCode $string
833     } elseif {$code == 2} {
834         return -code return $string
835     } elseif {$code == 3} {
836         return
837     } elseif {$code > 4} {
838         return -code $code $string
839     }
840     return $result
841 }
842
843 # gdb_test COMMAND PATTERN MESSAGE QUESTION RESPONSE
844 # Send a command to gdb; test the result.
845 #
846 # COMMAND is the command to execute, send to GDB with send_gdb.  If
847 #   this is the null string no command is sent.
848 # PATTERN is the pattern to match for a PASS, and must NOT include
849 #   the \r\n sequence immediately before the gdb prompt.
850 # MESSAGE is an optional message to be printed.  If this is
851 #   omitted, then the pass/fail messages use the command string as the
852 #   message.  (If this is the empty string, then sometimes we don't
853 #   call pass or fail at all; I don't understand this at all.)
854 # QUESTION is a question GDB may ask in response to COMMAND, like
855 #   "are you sure?"
856 # RESPONSE is the response to send if QUESTION appears.
857 #
858 # Returns:
859 #    1 if the test failed,
860 #    0 if the test passes,
861 #   -1 if there was an internal error.
862 #  
863 proc gdb_test { args } {
864     global verbose
865     global gdb_prompt
866     global GDB
867     upvar timeout timeout
868
869     if [llength $args]>2 then {
870         set message [lindex $args 2]
871     } else {
872         set message [lindex $args 0]
873     }
874     set command [lindex $args 0]
875     set pattern [lindex $args 1]
876
877     if [llength $args]==5 {
878         set question_string [lindex $args 3];
879         set response_string [lindex $args 4];
880     } else {
881         set question_string "^FOOBAR$"
882     }
883
884     return [gdb_test_multiple $command $message {
885         -re "\[\r\n\]*($pattern)\[\r\n\]+$gdb_prompt $" {
886             if ![string match "" $message] then {
887                 pass "$message"
888             }
889         }
890         -re "(${question_string})$" {
891             send_gdb "$response_string\n";
892             exp_continue;
893         }
894      }]
895 }
896
897 # gdb_test_no_output COMMAND MESSAGE
898 # Send a command to GDB and verify that this command generated no output.
899 #
900 # See gdb_test_multiple for a description of the COMMAND and MESSAGE
901 # parameters.  If MESSAGE is ommitted, then COMMAND will be used as
902 # the message.  (If MESSAGE is the empty string, then sometimes we do not
903 # call pass or fail at all; I don't understand this at all.)
904
905 proc gdb_test_no_output { args } {
906     global gdb_prompt
907     set command [lindex $args 0]
908     if [llength $args]>1 then {
909         set message [lindex $args 1]
910     } else {
911         set message $command
912     }
913
914     set command_regex [string_to_regexp $command]
915     gdb_test_multiple $command $message {
916         -re "^$command_regex\r\n$gdb_prompt $" {
917             if ![string match "" $message] then {
918                 pass "$message"
919             }
920         }
921     }
922 }
923
924 \f
925 # Test that a command gives an error.  For pass or fail, return
926 # a 1 to indicate that more tests can proceed.  However a timeout
927 # is a serious error, generates a special fail message, and causes
928 # a 0 to be returned to indicate that more tests are likely to fail
929 # as well.
930
931 proc test_print_reject { args } {
932     global gdb_prompt
933     global verbose
934
935     if [llength $args]==2 then {
936         set expectthis [lindex $args 1]
937     } else {
938         set expectthis "should never match this bogus string"
939     }
940     set sendthis [lindex $args 0]
941     if $verbose>2 then {
942         send_user "Sending \"$sendthis\" to gdb\n"
943         send_user "Looking to match \"$expectthis\"\n"
944     }
945     send_gdb "$sendthis\n"
946     #FIXME: Should add timeout as parameter.
947     gdb_expect {
948         -re "A .* in expression.*\\.*$gdb_prompt $" {
949             pass "reject $sendthis"
950             return 1
951         }
952         -re "Invalid syntax in expression.*$gdb_prompt $" {
953             pass "reject $sendthis"
954             return 1
955         }
956         -re "Junk after end of expression.*$gdb_prompt $" {
957             pass "reject $sendthis"
958             return 1
959         }
960         -re "Invalid number.*$gdb_prompt $" {
961             pass "reject $sendthis"
962             return 1
963         }
964         -re "Invalid character constant.*$gdb_prompt $" {
965             pass "reject $sendthis"
966             return 1
967         }
968         -re "No symbol table is loaded.*$gdb_prompt $" {
969             pass "reject $sendthis"
970             return 1
971         }
972         -re "No symbol .* in current context.*$gdb_prompt $" {
973             pass "reject $sendthis"
974             return 1
975         }
976         -re "Unmatched single quote.*$gdb_prompt $" {
977             pass "reject $sendthis"
978             return 1
979         }
980         -re "A character constant must contain at least one character.*$gdb_prompt $" {
981             pass "reject $sendthis"
982             return 1
983         }
984         -re "$expectthis.*$gdb_prompt $" {
985             pass "reject $sendthis"
986             return 1
987         }
988         -re ".*$gdb_prompt $" {
989             fail "reject $sendthis"
990             return 1
991         }
992         default {
993             fail "reject $sendthis (eof or timeout)"
994             return 0
995         }
996     }
997 }
998 \f
999 # Given an input string, adds backslashes as needed to create a
1000 # regexp that will match the string.
1001
1002 proc string_to_regexp {str} {
1003     set result $str
1004     regsub -all {[]*+.|()^$\[\\]} $str {\\&} result
1005     return $result
1006 }
1007
1008 # Same as gdb_test, but the second parameter is not a regexp,
1009 # but a string that must match exactly.
1010
1011 proc gdb_test_exact { args } {
1012     upvar timeout timeout
1013
1014     set command [lindex $args 0]
1015
1016     # This applies a special meaning to a null string pattern.  Without
1017     # this, "$pattern\r\n$gdb_prompt $" will match anything, including error
1018     # messages from commands that should have no output except a new
1019     # prompt.  With this, only results of a null string will match a null
1020     # string pattern.
1021
1022     set pattern [lindex $args 1]
1023     if [string match $pattern ""] {
1024         set pattern [string_to_regexp [lindex $args 0]]
1025     } else {
1026         set pattern [string_to_regexp [lindex $args 1]]
1027     }
1028
1029     # It is most natural to write the pattern argument with only
1030     # embedded \n's, especially if you are trying to avoid Tcl quoting
1031     # problems.  But gdb_expect really wants to see \r\n in patterns.  So
1032     # transform the pattern here.  First transform \r\n back to \n, in
1033     # case some users of gdb_test_exact already do the right thing.
1034     regsub -all "\r\n" $pattern "\n" pattern
1035     regsub -all "\n" $pattern "\r\n" pattern
1036     if [llength $args]==3 then {
1037         set message [lindex $args 2]
1038     } else {
1039         set message $command
1040     }
1041
1042     return [gdb_test $command $pattern $message]
1043 }
1044
1045 # Wrapper around gdb_test_multiple that looks for a list of expected
1046 # output elements, but which can appear in any order.
1047 # CMD is the gdb command.
1048 # NAME is the name of the test.
1049 # ELM_FIND_REGEXP specifies how to partition the output into elements to
1050 # compare.
1051 # ELM_EXTRACT_REGEXP specifies the part of ELM_FIND_REGEXP to compare.
1052 # RESULT_MATCH_LIST is a list of exact matches for each expected element.
1053 # All elements of RESULT_MATCH_LIST must appear for the test to pass.
1054 #
1055 # A typical use of ELM_FIND_REGEXP/ELM_EXTRACT_REGEXP is to extract one line
1056 # of text per element and then strip trailing \r\n's.
1057 # Example:
1058 # gdb_test_list_exact "foo" "bar" \
1059 #     {[^\r\n]+[\r\n]+} \
1060 #     {[^\r\n]+} \
1061 #     { \
1062 #       {expected result 1} \
1063 #       {expected result 2} \
1064 #     }
1065
1066 proc gdb_test_list_exact { cmd name elm_find_regexp elm_extract_regexp result_match_list } {
1067     global gdb_prompt
1068
1069     set matches [lsort $result_match_list]
1070     set seen {}
1071     gdb_test_multiple $cmd $name {
1072         "$cmd\[\r\n\]" { exp_continue }
1073         -re $elm_find_regexp {
1074             set str $expect_out(0,string)
1075             verbose -log "seen: $str" 3
1076             regexp -- $elm_extract_regexp $str elm_seen
1077             verbose -log "extracted: $elm_seen" 3
1078             lappend seen $elm_seen
1079             exp_continue
1080         }
1081         -re "$gdb_prompt $" {
1082             set failed ""
1083             foreach got [lsort $seen] have $matches {
1084                 if {![string equal $got $have]} {
1085                     set failed $have
1086                     break
1087                 }
1088             }
1089             if {[string length $failed] != 0} {
1090                 fail "$name ($failed not found)"
1091             } else {
1092                 pass $name
1093             }
1094         }
1095     }
1096 }
1097 \f
1098 proc gdb_reinitialize_dir { subdir } {
1099     global gdb_prompt
1100
1101     if [is_remote host] {
1102         return "";
1103     }
1104     send_gdb "dir\n"
1105     gdb_expect 60 {
1106         -re "Reinitialize source path to empty.*y or n. " {
1107             send_gdb "y\n"
1108             gdb_expect 60 {
1109                 -re "Source directories searched.*$gdb_prompt $" {
1110                     send_gdb "dir $subdir\n"
1111                     gdb_expect 60 {
1112                         -re "Source directories searched.*$gdb_prompt $" {
1113                             verbose "Dir set to $subdir"
1114                         }
1115                         -re "$gdb_prompt $" {
1116                             perror "Dir \"$subdir\" failed."
1117                         }
1118                     }
1119                 }
1120                 -re "$gdb_prompt $" {
1121                     perror "Dir \"$subdir\" failed."
1122                 }
1123             }
1124         }
1125         -re "$gdb_prompt $" {
1126             perror "Dir \"$subdir\" failed."
1127         }
1128     }
1129 }
1130
1131 #
1132 # gdb_exit -- exit the GDB, killing the target program if necessary
1133 #
1134 proc default_gdb_exit {} {
1135     global GDB
1136     global INTERNAL_GDBFLAGS GDBFLAGS
1137     global verbose
1138     global gdb_spawn_id;
1139
1140     gdb_stop_suppressing_tests;
1141
1142     if ![info exists gdb_spawn_id] {
1143         return;
1144     }
1145
1146     verbose "Quitting $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
1147
1148     if { [is_remote host] && [board_info host exists fileid] } {
1149         send_gdb "quit\n";
1150         gdb_expect 10 {
1151             -re "y or n" {
1152                 send_gdb "y\n";
1153                 exp_continue;
1154             }
1155             -re "DOSEXIT code" { }
1156             default { }
1157         }
1158     }
1159
1160     if ![is_remote host] {
1161         remote_close host;
1162     }
1163     unset gdb_spawn_id
1164 }
1165
1166 # Load a file into the debugger.
1167 # The return value is 0 for success, -1 for failure.
1168 #
1169 # This procedure also set the global variable GDB_FILE_CMD_DEBUG_INFO
1170 # to one of these values:
1171 #
1172 #   debug    file was loaded successfully and has debug information
1173 #   nodebug  file was loaded successfully and has no debug information
1174 #   fail     file was not loaded
1175 #
1176 # I tried returning this information as part of the return value,
1177 # but ran into a mess because of the many re-implementations of
1178 # gdb_load in config/*.exp.
1179 #
1180 # TODO: gdb.base/sepdebug.exp and gdb.stabs/weird.exp might be able to use
1181 # this if they can get more information set.
1182
1183 proc gdb_file_cmd { arg } {
1184     global gdb_prompt
1185     global verbose
1186     global GDB
1187     global last_loaded_file
1188
1189     set last_loaded_file $arg
1190
1191     # Set whether debug info was found.
1192     # Default to "fail".
1193     global gdb_file_cmd_debug_info
1194     set gdb_file_cmd_debug_info "fail"
1195
1196     if [is_remote host] {
1197         set arg [remote_download host $arg]
1198         if { $arg == "" } {
1199             perror "download failed"
1200             return -1
1201         }
1202     }
1203
1204     # The file command used to kill the remote target.  For the benefit
1205     # of the testsuite, preserve this behavior.
1206     send_gdb "kill\n"
1207     gdb_expect 120 {
1208         -re "Kill the program being debugged. .y or n. $" {
1209             send_gdb "y\n"
1210             verbose "\t\tKilling previous program being debugged"
1211             exp_continue
1212         }
1213         -re "$gdb_prompt $" {
1214             # OK.
1215         }
1216     }
1217
1218     send_gdb "file $arg\n"
1219     gdb_expect 120 {
1220         -re "Reading symbols from.*no debugging symbols found.*done.*$gdb_prompt $" {
1221             verbose "\t\tLoaded $arg into the $GDB with no debugging symbols"
1222             set gdb_file_cmd_debug_info "nodebug"
1223             return 0
1224         }
1225         -re "Reading symbols from.*done.*$gdb_prompt $" {
1226             verbose "\t\tLoaded $arg into the $GDB"
1227             set gdb_file_cmd_debug_info "debug"
1228             return 0
1229         }
1230         -re "Load new symbol table from \".*\".*y or n. $" {
1231             send_gdb "y\n"
1232             gdb_expect 120 {
1233                 -re "Reading symbols from.*done.*$gdb_prompt $" {
1234                     verbose "\t\tLoaded $arg with new symbol table into $GDB"
1235                     set gdb_file_cmd_debug_info "debug"
1236                     return 0
1237                 }
1238                 timeout {
1239                     perror "(timeout) Couldn't load $arg, other program already loaded."
1240                     return -1
1241                 }
1242             }
1243         }
1244         -re "No such file or directory.*$gdb_prompt $" {
1245             perror "($arg) No such file or directory"
1246             return -1
1247         }
1248         -re "$gdb_prompt $" {
1249             perror "couldn't load $arg into $GDB."
1250             return -1
1251             }
1252         timeout {
1253             perror "couldn't load $arg into $GDB (timed out)."
1254             return -1
1255         }
1256         eof {
1257             # This is an attempt to detect a core dump, but seems not to
1258             # work.  Perhaps we need to match .* followed by eof, in which
1259             # gdb_expect does not seem to have a way to do that.
1260             perror "couldn't load $arg into $GDB (end of file)."
1261             return -1
1262         }
1263     }
1264 }
1265
1266 #
1267 # start gdb -- start gdb running, default procedure
1268 #
1269 # When running over NFS, particularly if running many simultaneous
1270 # tests on different hosts all using the same server, things can
1271 # get really slow.  Give gdb at least 3 minutes to start up.
1272 #
1273 proc default_gdb_start { } {
1274     global verbose
1275     global GDB
1276     global INTERNAL_GDBFLAGS GDBFLAGS
1277     global gdb_prompt
1278     global timeout
1279     global gdb_spawn_id;
1280     global env
1281
1282     gdb_stop_suppressing_tests;
1283
1284     set env(LC_CTYPE) C
1285
1286     # Don't let a .inputrc file or an existing setting of INPUTRC mess up
1287     # the test results.  Even if /dev/null doesn't exist on the particular
1288     # platform, the readline library will use the default setting just by
1289     # failing to open the file.  OTOH, opening /dev/null successfully will
1290     # also result in the default settings being used since nothing will be
1291     # read from this file.
1292     set env(INPUTRC) "/dev/null"
1293
1294     # The gdb.base/readline.exp arrow key test relies on the standard VT100
1295     # bindings, so make sure that an appropriate terminal is selected.
1296     # The same bug doesn't show up if we use ^P / ^N instead.
1297     set env(TERM) "vt100"
1298
1299     verbose "Spawning $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
1300
1301     if [info exists gdb_spawn_id] {
1302         return 0;
1303     }
1304
1305     if ![is_remote host] {
1306         if { [which $GDB] == 0 } then {
1307             perror "$GDB does not exist."
1308             exit 1
1309         }
1310     }
1311     set res [remote_spawn host "$GDB $INTERNAL_GDBFLAGS $GDBFLAGS [host_info gdb_opts]"];
1312     if { $res < 0 || $res == "" } {
1313         perror "Spawning $GDB failed."
1314         return 1;
1315     }
1316     gdb_expect 360 {
1317         -re "\[\r\n\]$gdb_prompt $" {
1318             verbose "GDB initialized."
1319         }
1320         -re "$gdb_prompt $"     {
1321             perror "GDB never initialized."
1322             return -1
1323         }
1324         timeout {
1325             perror "(timeout) GDB never initialized after 10 seconds."
1326             remote_close host;
1327             return -1
1328         }
1329     }
1330     set gdb_spawn_id -1;
1331     # force the height to "unlimited", so no pagers get used
1332
1333     send_gdb "set height 0\n"
1334     gdb_expect 10 {
1335         -re "$gdb_prompt $" { 
1336             verbose "Setting height to 0." 2
1337         }
1338         timeout {
1339             warning "Couldn't set the height to 0"
1340         }
1341     }
1342     # force the width to "unlimited", so no wraparound occurs
1343     send_gdb "set width 0\n"
1344     gdb_expect 10 {
1345         -re "$gdb_prompt $" {
1346             verbose "Setting width to 0." 2
1347         }
1348         timeout {
1349             warning "Couldn't set the width to 0."
1350         }
1351     }
1352     return 0;
1353 }
1354
1355 # Examine the output of compilation to determine whether compilation
1356 # failed or not.  If it failed determine whether it is due to missing
1357 # compiler or due to compiler error.  Report pass, fail or unsupported
1358 # as appropriate
1359
1360 proc gdb_compile_test {src output} {
1361     if { $output == "" } {
1362         pass "compilation [file tail $src]"
1363     } elseif { [regexp {^[a-zA-Z_0-9]+: Can't find [^ ]+\.$} $output] } {
1364         unsupported "compilation [file tail $src]"
1365     } elseif { [regexp {.*: command not found[\r|\n]*$} $output] } {
1366         unsupported "compilation [file tail $src]"
1367     } elseif { [regexp {.*: [^\r\n]*compiler not installed[^\r\n]*[\r|\n]*$} $output] } {
1368         unsupported "compilation [file tail $src]"
1369     } else {
1370         verbose -log "compilation failed: $output" 2
1371         fail "compilation [file tail $src]"
1372     }
1373 }
1374
1375 # Return a 1 for configurations for which we don't even want to try to
1376 # test C++.
1377
1378 proc skip_cplus_tests {} {
1379     if { [istarget "h8300-*-*"] } {
1380         return 1
1381     }
1382
1383     # The C++ IO streams are too large for HC11/HC12 and are thus not
1384     # available.  The gdb C++ tests use them and don't compile.
1385     if { [istarget "m6811-*-*"] } {
1386         return 1
1387     }
1388     if { [istarget "m6812-*-*"] } {
1389         return 1
1390     }
1391     return 0
1392 }
1393
1394 # Return a 1 for configurations for which don't have both C++ and the STL.
1395
1396 proc skip_stl_tests {} {
1397     # Symbian supports the C++ language, but the STL is missing
1398     # (both headers and libraries).
1399     if { [istarget "arm*-*-symbianelf*"] } {
1400         return 1
1401     }
1402
1403     return [skip_cplus_tests]
1404 }
1405
1406 # Return a 1 if I don't even want to try to test FORTRAN.
1407
1408 proc skip_fortran_tests {} {
1409     return 0
1410 }
1411
1412 # Return a 1 if I don't even want to try to test ada.
1413
1414 proc skip_ada_tests {} {
1415     return 0
1416 }
1417
1418 # Return a 1 if I don't even want to try to test java.
1419
1420 proc skip_java_tests {} {
1421     return 0
1422 }
1423
1424 # Return a 1 for configurations that do not support Python scripting.
1425
1426 proc skip_python_tests {} {
1427     global gdb_prompt
1428     gdb_test_multiple "python print 'test'" "verify python support" {
1429         -re "not supported.*$gdb_prompt $"      {
1430             unsupported "Python support is disabled."
1431             return 1
1432         }
1433         -re "$gdb_prompt $"     {}
1434     }
1435
1436     return 0
1437 }
1438
1439 # Return a 1 if we should skip shared library tests.
1440
1441 proc skip_shlib_tests {} {
1442     # Run the shared library tests on native systems.
1443     if {[isnative]} {
1444         return 0
1445     }
1446
1447     # An abbreviated list of remote targets where we should be able to
1448     # run shared library tests.
1449     if {([istarget *-*-linux*]
1450          || [istarget *-*-*bsd*]
1451          || [istarget *-*-solaris2*]
1452          || [istarget arm*-*-symbianelf*]
1453          || [istarget *-*-mingw*]
1454          || [istarget *-*-cygwin*]
1455          || [istarget *-*-pe*])} {
1456         return 0
1457     }
1458
1459     return 1
1460 }
1461
1462 # Return 1 if target is ILP32.
1463 # This cannot be decided simply from looking at the target string,
1464 # as it might depend on externally passed compiler options like -m64.
1465 proc is_ilp32_target {} {
1466     global is_ilp32_target_saved
1467
1468     # Use the cached value, if it exists.  Cache value per "board" to handle
1469     # runs with multiple options (e.g. unix/{-m32,-64}) correctly.
1470     set me "is_ilp32_target"
1471     set board [target_info name]
1472     if [info exists is_ilp32_target_saved($board)] {
1473         verbose "$me:  returning saved $is_ilp32_target_saved($board)" 2
1474         return $is_ilp32_target_saved($board)
1475     }
1476
1477
1478     set src ilp32[pid].c
1479     set obj ilp32[pid].o
1480
1481     set f [open $src "w"]
1482     puts $f "int dummy\[sizeof (int) == 4"
1483     puts $f "           && sizeof (void *) == 4"
1484     puts $f "           && sizeof (long) == 4 ? 1 : -1\];"
1485     close $f
1486
1487     verbose "$me:  compiling testfile $src" 2
1488     set lines [gdb_compile $src $obj object {quiet}]
1489     file delete $src
1490     file delete $obj
1491
1492     if ![string match "" $lines] then {
1493         verbose "$me:  testfile compilation failed, returning 0" 2
1494         return [set is_ilp32_target_saved($board) 0]
1495     }
1496
1497     verbose "$me:  returning 1" 2
1498     return [set is_ilp32_target_saved($board) 1]
1499 }
1500
1501 # Return 1 if target is LP64.
1502 # This cannot be decided simply from looking at the target string,
1503 # as it might depend on externally passed compiler options like -m64.
1504 proc is_lp64_target {} {
1505     global is_lp64_target_saved
1506
1507     # Use the cached value, if it exists.  Cache value per "board" to handle
1508     # runs with multiple options (e.g. unix/{-m32,-64}) correctly.
1509     set me "is_lp64_target"
1510     set board [target_info name]
1511     if [info exists is_lp64_target_saved($board)] {
1512         verbose "$me:  returning saved $is_lp64_target_saved($board)" 2
1513         return $is_lp64_target_saved($board)
1514     }
1515
1516     set src lp64[pid].c
1517     set obj lp64[pid].o
1518
1519     set f [open $src "w"]
1520     puts $f "int dummy\[sizeof (int) == 4"
1521     puts $f "           && sizeof (void *) == 8"
1522     puts $f "           && sizeof (long) == 8 ? 1 : -1\];"
1523     close $f
1524
1525     verbose "$me:  compiling testfile $src" 2
1526     set lines [gdb_compile $src $obj object {quiet}]
1527     file delete $src
1528     file delete $obj
1529
1530     if ![string match "" $lines] then {
1531         verbose "$me:  testfile compilation failed, returning 0" 2
1532         return [set is_lp64_target_saved($board) 0]
1533     }
1534
1535     verbose "$me:  returning 1" 2
1536     return [set is_lp64_target_saved($board) 1]
1537 }
1538
1539 # Run a test on the target to see if it supports vmx hardware.  Return 0 if so, 
1540 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
1541
1542 proc skip_altivec_tests {} {
1543     global skip_vmx_tests_saved
1544     global srcdir subdir gdb_prompt
1545
1546     # Use the cached value, if it exists.
1547     set me "skip_altivec_tests"
1548     if [info exists skip_vmx_tests_saved] {
1549         verbose "$me:  returning saved $skip_vmx_tests_saved" 2
1550         return $skip_vmx_tests_saved
1551     }
1552
1553     # Some simulators are known to not support VMX instructions.
1554     if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
1555         verbose "$me:  target known to not support VMX, returning 1" 2
1556         return [set skip_vmx_tests_saved 1]
1557     }
1558
1559     # Make sure we have a compiler that understands altivec.
1560     set compile_flags {debug nowarnings}
1561     if [get_compiler_info not-used] {
1562        warning "Could not get compiler info"
1563        return 1
1564     }
1565     if [test_compiler_info gcc*] {
1566         set compile_flags "$compile_flags additional_flags=-maltivec"
1567     } elseif [test_compiler_info xlc*] {
1568         set compile_flags "$compile_flags additional_flags=-qaltivec"
1569     } else {
1570         verbose "Could not compile with altivec support, returning 1" 2
1571         return 1
1572     }
1573
1574     # Set up, compile, and execute a test program containing VMX instructions.
1575     # Include the current process ID in the file names to prevent conflicts
1576     # with invocations for multiple testsuites.
1577     set src vmx[pid].c
1578     set exe vmx[pid].x
1579
1580     set f [open $src "w"]
1581     puts $f "int main() {"
1582     puts $f "#ifdef __MACH__"
1583     puts $f "  asm volatile (\"vor v0,v0,v0\");"
1584     puts $f "#else"
1585     puts $f "  asm volatile (\"vor 0,0,0\");"
1586     puts $f "#endif"
1587     puts $f "  return 0; }"
1588     close $f
1589
1590     verbose "$me:  compiling testfile $src" 2
1591     set lines [gdb_compile $src $exe executable $compile_flags]
1592     file delete $src
1593
1594     if ![string match "" $lines] then {
1595         verbose "$me:  testfile compilation failed, returning 1" 2
1596         return [set skip_vmx_tests_saved 1]
1597     }
1598
1599     # No error message, compilation succeeded so now run it via gdb.
1600
1601     gdb_exit
1602     gdb_start
1603     gdb_reinitialize_dir $srcdir/$subdir
1604     gdb_load "$exe"
1605     gdb_run_cmd
1606     gdb_expect {
1607         -re ".*Illegal instruction.*${gdb_prompt} $" {
1608             verbose -log "\n$me altivec hardware not detected" 
1609             set skip_vmx_tests_saved 1
1610         }
1611         -re ".*Program exited normally.*${gdb_prompt} $" {
1612             verbose -log "\n$me: altivec hardware detected" 
1613             set skip_vmx_tests_saved 0
1614         }
1615         default {
1616           warning "\n$me: default case taken"
1617             set skip_vmx_tests_saved 1
1618         }
1619     }
1620     gdb_exit
1621     remote_file build delete $exe
1622
1623     verbose "$me:  returning $skip_vmx_tests_saved" 2
1624     return $skip_vmx_tests_saved
1625 }
1626
1627 # Run a test on the target to see if it supports vmx hardware.  Return 0 if so,
1628 # 1 if it does not.  Based on 'check_vmx_hw_available' from the GCC testsuite.
1629
1630 proc skip_vsx_tests {} {
1631     global skip_vsx_tests_saved
1632     global srcdir subdir gdb_prompt
1633
1634     # Use the cached value, if it exists.
1635     set me "skip_vsx_tests"
1636     if [info exists skip_vsx_tests_saved] {
1637         verbose "$me:  returning saved $skip_vsx_tests_saved" 2
1638         return $skip_vsx_tests_saved
1639     }
1640
1641     # Some simulators are known to not support Altivec instructions, so
1642     # they won't support VSX instructions as well.
1643     if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
1644         verbose "$me:  target known to not support VSX, returning 1" 2
1645         return [set skip_vsx_tests_saved 1]
1646     }
1647
1648     # Make sure we have a compiler that understands altivec.
1649     set compile_flags {debug nowarnings quiet}
1650     if [get_compiler_info not-used] {
1651        warning "Could not get compiler info"
1652        return 1
1653     }
1654     if [test_compiler_info gcc*] {
1655         set compile_flags "$compile_flags additional_flags=-mvsx"
1656     } elseif [test_compiler_info xlc*] {
1657         set compile_flags "$compile_flags additional_flags=-qvsx"
1658     } else {
1659         verbose "Could not compile with vsx support, returning 1" 2
1660         return 1
1661     }
1662
1663     set src vsx[pid].c
1664     set exe vsx[pid].x
1665
1666     set f [open $src "w"]
1667     puts $f "int main() {"
1668     puts $f "#ifdef __MACH__"
1669     puts $f "  asm volatile (\"lxvd2x v0,v0,v0\");"
1670     puts $f "#else"
1671     puts $f "  asm volatile (\"lxvd2x 0,0,0\");"
1672     puts $f "#endif"
1673     puts $f "  return 0; }"
1674     close $f
1675
1676     verbose "$me:  compiling testfile $src" 2
1677     set lines [gdb_compile $src $exe executable $compile_flags]
1678     file delete $src
1679
1680     if ![string match "" $lines] then {
1681         verbose "$me:  testfile compilation failed, returning 1" 2
1682         return [set skip_vsx_tests_saved 1]
1683     }
1684
1685     # No error message, compilation succeeded so now run it via gdb.
1686
1687     gdb_exit
1688     gdb_start
1689     gdb_reinitialize_dir $srcdir/$subdir
1690     gdb_load "$exe"
1691     gdb_run_cmd
1692     gdb_expect {
1693         -re ".*Illegal instruction.*${gdb_prompt} $" {
1694             verbose -log "\n$me VSX hardware not detected"
1695             set skip_vsx_tests_saved 1
1696         }
1697         -re ".*Program exited normally.*${gdb_prompt} $" {
1698             verbose -log "\n$me: VSX hardware detected"
1699             set skip_vsx_tests_saved 0
1700         }
1701         default {
1702           warning "\n$me: default case taken"
1703             set skip_vsx_tests_saved 1
1704         }
1705     }
1706     gdb_exit
1707     remote_file build delete $exe
1708
1709     verbose "$me:  returning $skip_vsx_tests_saved" 2
1710     return $skip_vsx_tests_saved
1711 }
1712
1713 # Skip all the tests in the file if you are not on an hppa running
1714 # hpux target.
1715
1716 proc skip_hp_tests {} {
1717     eval set skip_hp [ expr ![isnative] || ![istarget "hppa*-*-hpux*"] ]
1718     verbose "Skip hp tests is $skip_hp"
1719     return $skip_hp
1720 }
1721
1722 # Return whether we should skip tests for showing inlined functions in
1723 # backtraces.  Requires get_compiler_info and get_debug_format.
1724
1725 proc skip_inline_frame_tests {} {
1726     # GDB only recognizes inlining information in DWARF 2 (DWARF 3).
1727     if { ! [test_debug_format "DWARF 2"] } {
1728         return 1
1729     }
1730
1731     # GCC before 4.1 does not emit DW_AT_call_file / DW_AT_call_line.
1732     if { ([test_compiler_info "gcc-2-*"]
1733           || [test_compiler_info "gcc-3-*"]
1734           || [test_compiler_info "gcc-4-0-*"]) } {
1735         return 1
1736     }
1737
1738     return 0
1739 }
1740
1741 # Return whether we should skip tests for showing variables from
1742 # inlined functions.  Requires get_compiler_info and get_debug_format.
1743
1744 proc skip_inline_var_tests {} {
1745     # GDB only recognizes inlining information in DWARF 2 (DWARF 3).
1746     if { ! [test_debug_format "DWARF 2"] } {
1747         return 1
1748     }
1749
1750     return 0
1751 }
1752
1753 set compiler_info               "unknown"
1754 set gcc_compiled                0
1755 set hp_cc_compiler              0
1756 set hp_aCC_compiler             0
1757
1758 # Figure out what compiler I am using.
1759 #
1760 # BINFILE is a "compiler information" output file.  This implementation
1761 # does not use BINFILE.
1762 #
1763 # ARGS can be empty or "C++".  If empty, "C" is assumed.
1764 #
1765 # There are several ways to do this, with various problems.
1766 #
1767 # [ gdb_compile -E $ifile -o $binfile.ci ]
1768 # source $binfile.ci
1769 #
1770 #   Single Unix Spec v3 says that "-E -o ..." together are not
1771 #   specified.  And in fact, the native compiler on hp-ux 11 (among
1772 #   others) does not work with "-E -o ...".  Most targets used to do
1773 #   this, and it mostly worked, because it works with gcc.
1774 #
1775 # [ catch "exec $compiler -E $ifile > $binfile.ci" exec_output ]
1776 # source $binfile.ci
1777
1778 #   This avoids the problem with -E and -o together.  This almost works
1779 #   if the build machine is the same as the host machine, which is
1780 #   usually true of the targets which are not gcc.  But this code does
1781 #   not figure which compiler to call, and it always ends up using the C
1782 #   compiler.  Not good for setting hp_aCC_compiler.  Targets
1783 #   hppa*-*-hpux* and mips*-*-irix* used to do this.
1784 #
1785 # [ gdb_compile -E $ifile > $binfile.ci ]
1786 # source $binfile.ci
1787 #
1788 #   dejagnu target_compile says that it supports output redirection,
1789 #   but the code is completely different from the normal path and I
1790 #   don't want to sweep the mines from that path.  So I didn't even try
1791 #   this.
1792 #
1793 # set cppout [ gdb_compile $ifile "" preprocess $args quiet ]
1794 # eval $cppout
1795 #
1796 #   I actually do this for all targets now.  gdb_compile runs the right
1797 #   compiler, and TCL captures the output, and I eval the output.
1798 #
1799 #   Unfortunately, expect logs the output of the command as it goes by,
1800 #   and dejagnu helpfully prints a second copy of it right afterwards.
1801 #   So I turn off expect logging for a moment.
1802 #   
1803 # [ gdb_compile $ifile $ciexe_file executable $args ]
1804 # [ remote_exec $ciexe_file ]
1805 # [ source $ci_file.out ]
1806 #
1807 #   I could give up on -E and just do this.
1808 #   I didn't get desperate enough to try this.
1809 #
1810 # -- chastain 2004-01-06
1811
1812 proc get_compiler_info {binfile args} {
1813     # For compiler.c and compiler.cc
1814     global srcdir
1815
1816     # I am going to play with the log to keep noise out.
1817     global outdir
1818     global tool
1819
1820     # These come from compiler.c or compiler.cc
1821     global compiler_info
1822
1823     # Legacy global data symbols.
1824     global gcc_compiled
1825     global hp_cc_compiler
1826     global hp_aCC_compiler
1827
1828     # Choose which file to preprocess.
1829     set ifile "${srcdir}/lib/compiler.c"
1830     if { [llength $args] > 0 && [lindex $args 0] == "c++" } {
1831         set ifile "${srcdir}/lib/compiler.cc"
1832     }
1833
1834     # Run $ifile through the right preprocessor.
1835     # Toggle gdb.log to keep the compiler output out of the log.
1836     log_file
1837     if [is_remote host] {
1838         # We have to use -E and -o together, despite the comments
1839         # above, because of how DejaGnu handles remote host testing.
1840         set ppout "$outdir/compiler.i"
1841         gdb_compile "${ifile}" "$ppout" preprocess [list "$args" quiet]
1842         set file [open $ppout r]
1843         set cppout [read $file]
1844         close $file
1845     } else {
1846         set cppout [ gdb_compile "${ifile}" "" preprocess [list "$args" quiet] ]
1847     }
1848     log_file -a "$outdir/$tool.log" 
1849
1850     # Eval the output.
1851     set unknown 0
1852     foreach cppline [ split "$cppout" "\n" ] {
1853         if { [ regexp "^#" "$cppline" ] } {
1854             # line marker
1855         } elseif { [ regexp "^\[\n\r\t \]*$" "$cppline" ] } {
1856             # blank line
1857         } elseif { [ regexp "^\[\n\r\t \]*set\[\n\r\t \]" "$cppline" ] } {
1858             # eval this line
1859             verbose "get_compiler_info: $cppline" 2
1860             eval "$cppline"
1861         } else {
1862             # unknown line
1863             verbose -log "get_compiler_info: $cppline"
1864             set unknown 1
1865         }
1866     }
1867
1868     # Reset to unknown compiler if any diagnostics happened.
1869     if { $unknown } {
1870         set compiler_info "unknown"
1871     }
1872
1873     # Set the legacy symbols.
1874     set gcc_compiled     0
1875     set hp_cc_compiler   0
1876     set hp_aCC_compiler  0
1877     if { [regexp "^gcc-1-" "$compiler_info" ] } { set gcc_compiled 1 }
1878     if { [regexp "^gcc-2-" "$compiler_info" ] } { set gcc_compiled 2 }
1879     if { [regexp "^gcc-3-" "$compiler_info" ] } { set gcc_compiled 3 }
1880     if { [regexp "^gcc-4-" "$compiler_info" ] } { set gcc_compiled 4 }
1881     if { [regexp "^gcc-5-" "$compiler_info" ] } { set gcc_compiled 5 }
1882     if { [regexp "^hpcc-"  "$compiler_info" ] } { set hp_cc_compiler 1 }
1883     if { [regexp "^hpacc-" "$compiler_info" ] } { set hp_aCC_compiler 1 }
1884
1885     # Log what happened.
1886     verbose -log "get_compiler_info: $compiler_info"
1887
1888     # Most compilers will evaluate comparisons and other boolean
1889     # operations to 0 or 1.
1890     uplevel \#0 { set true 1 }
1891     uplevel \#0 { set false 0 }
1892
1893     # Use of aCC results in boolean results being displayed as
1894     # "true" or "false"
1895     if { $hp_aCC_compiler } {
1896       uplevel \#0 { set true true }
1897       uplevel \#0 { set false false }
1898     }
1899
1900     return 0;
1901 }
1902
1903 proc test_compiler_info { {compiler ""} } {
1904     global compiler_info
1905
1906      # if no arg, return the compiler_info string
1907
1908      if [string match "" $compiler] {
1909          if [info exists compiler_info] {
1910              return $compiler_info
1911          } else {
1912              perror "No compiler info found."
1913          }
1914      }
1915
1916     return [string match $compiler $compiler_info]
1917 }
1918
1919 proc current_target_name { } {
1920     global target_info
1921     if [info exists target_info(target,name)] {
1922         set answer $target_info(target,name)
1923     } else {
1924         set answer ""
1925     }
1926     return $answer
1927 }
1928
1929 set gdb_wrapper_initialized 0
1930 set gdb_wrapper_target ""
1931
1932 proc gdb_wrapper_init { args } {
1933     global gdb_wrapper_initialized;
1934     global gdb_wrapper_file;
1935     global gdb_wrapper_flags;
1936     global gdb_wrapper_target
1937
1938     if { $gdb_wrapper_initialized == 1 } { return; }
1939
1940     if {[target_info exists needs_status_wrapper] && \
1941             [target_info needs_status_wrapper] != "0"} {
1942         set result [build_wrapper "testglue.o"];
1943         if { $result != "" } {
1944             set gdb_wrapper_file [lindex $result 0];
1945             set gdb_wrapper_flags [lindex $result 1];
1946         } else {
1947             warning "Status wrapper failed to build."
1948         }
1949     }
1950     set gdb_wrapper_initialized 1
1951     set gdb_wrapper_target [current_target_name]
1952 }
1953
1954 # Some targets need to always link a special object in.  Save its path here.
1955 global gdb_saved_set_unbuffered_mode_obj
1956 set gdb_saved_set_unbuffered_mode_obj ""
1957
1958 proc gdb_compile {source dest type options} {
1959     global GDB_TESTCASE_OPTIONS;
1960     global gdb_wrapper_file;
1961     global gdb_wrapper_flags;
1962     global gdb_wrapper_initialized;
1963     global srcdir
1964     global objdir
1965     global gdb_saved_set_unbuffered_mode_obj
1966
1967     set outdir [file dirname $dest]
1968
1969     # Add platform-specific options if a shared library was specified using
1970     # "shlib=librarypath" in OPTIONS.
1971     set new_options ""
1972     set shlib_found 0
1973     set shlib_load 0
1974     foreach opt $options {
1975         if [regexp {^shlib=(.*)} $opt dummy_var shlib_name] {
1976             if [test_compiler_info "xlc-*"] {
1977                 # IBM xlc compiler doesn't accept shared library named other
1978                 # than .so: use "-Wl," to bypass this
1979                 lappend source "-Wl,$shlib_name"
1980             } elseif { ([istarget "*-*-mingw*"]
1981                         || [istarget *-*-cygwin*]
1982                         || [istarget *-*-pe*])} {
1983                 lappend source "${shlib_name}.a"
1984             } else {
1985                lappend source $shlib_name
1986             }
1987             if { $shlib_found == 0 } {
1988                 set shlib_found 1
1989                 if { ([istarget "*-*-mingw*"]
1990                       || [istarget *-*-cygwin*]) } {
1991                     lappend new_options "additional_flags=-Wl,--enable-auto-import"
1992                 }
1993             }
1994         } elseif { $opt == "shlib_load" } {
1995             set shlib_load 1
1996         } else {
1997             lappend new_options $opt
1998         }
1999     }
2000
2001     # We typically link to shared libraries using an absolute path, and
2002     # that's how they are found at runtime.  If we are going to
2003     # dynamically load one by basename, we must specify rpath.  If we
2004     # are using a remote host, DejaGNU will link to the shared library
2005     # using a relative path, so again we must specify an rpath.
2006     if { $shlib_load || ($shlib_found && [is_remote host]) } {
2007         if { ([istarget "*-*-mingw*"]
2008               || [istarget *-*-cygwin*]
2009               || [istarget *-*-pe*]
2010               || [istarget hppa*-*-hpux*])} {
2011             # Do not need anything.
2012         } elseif { [istarget *-*-openbsd*] } {
2013             lappend new_options "additional_flags=-Wl,-rpath,${outdir}"
2014         } elseif { [istarget arm*-*-symbianelf*] } {
2015             if { $shlib_load } {
2016                 lappend new_options "libs=-ldl"
2017             }
2018         } else {
2019             if { $shlib_load } {
2020                 lappend new_options "libs=-ldl"
2021             }
2022             lappend new_options "additional_flags=-Wl,-rpath,\\\$ORIGIN"
2023         }
2024     }
2025     set options $new_options
2026
2027     if [target_info exists gdb_stub] {
2028         set options2 { "additional_flags=-Dusestubs" }
2029         lappend options "libs=[target_info gdb_stub]";
2030         set options [concat $options2 $options]
2031     }
2032     if [target_info exists is_vxworks] {
2033         set options2 { "additional_flags=-Dvxworks" }
2034         lappend options "libs=[target_info gdb_stub]";
2035         set options [concat $options2 $options]
2036     }
2037     if [info exists GDB_TESTCASE_OPTIONS] {
2038         lappend options "additional_flags=$GDB_TESTCASE_OPTIONS";
2039     }
2040     verbose "options are $options"
2041     verbose "source is $source $dest $type $options"
2042
2043     if { $gdb_wrapper_initialized == 0 } { gdb_wrapper_init }
2044
2045     if {[target_info exists needs_status_wrapper] && \
2046             [target_info needs_status_wrapper] != "0" && \
2047             [info exists gdb_wrapper_file]} {
2048         lappend options "libs=${gdb_wrapper_file}"
2049         lappend options "ldflags=${gdb_wrapper_flags}"
2050     }
2051
2052     # Replace the "nowarnings" option with the appropriate additional_flags
2053     # to disable compiler warnings.
2054     set nowarnings [lsearch -exact $options nowarnings]
2055     if {$nowarnings != -1} {
2056         if [target_info exists gdb,nowarnings_flag] {
2057             set flag "additional_flags=[target_info gdb,nowarnings_flag]"
2058         } else {
2059             set flag "additional_flags=-w"
2060         }
2061         set options [lreplace $options $nowarnings $nowarnings $flag]
2062     }
2063
2064     if { $type == "executable" } {
2065         if { ([istarget "*-*-mingw*"]
2066               || [istarget "*-*-*djgpp"]
2067               || [istarget "*-*-cygwin*"])} {
2068             # Force output to unbuffered mode, by linking in an object file
2069             # with a global contructor that calls setvbuf.
2070             #
2071             # Compile the special object seperatelly for two reasons:
2072             #  1) Insulate it from $options.
2073             #  2) Avoid compiling it for every gdb_compile invocation,
2074             #  which is time consuming, especially if we're remote
2075             #  host testing.
2076             #
2077             if { $gdb_saved_set_unbuffered_mode_obj == "" } {
2078                 verbose "compiling gdb_saved_set_unbuffered_obj"
2079                 set unbuf_src ${srcdir}/lib/set_unbuffered_mode.c
2080                 set unbuf_obj ${objdir}/set_unbuffered_mode.o
2081
2082                 set result [gdb_compile "${unbuf_src}" "${unbuf_obj}" object {nowarnings}]
2083                 if { $result != "" } {
2084                     return $result
2085                 }
2086
2087                 set gdb_saved_set_unbuffered_mode_obj ${objdir}/set_unbuffered_mode_saved.o
2088                 # Link a copy of the output object, because the
2089                 # original may be automatically deleted.
2090                 remote_exec host "cp -f $unbuf_obj $gdb_saved_set_unbuffered_mode_obj"
2091             } else {
2092                 verbose "gdb_saved_set_unbuffered_obj already compiled"
2093             }
2094
2095             # Rely on the internal knowledge that the global ctors are ran in
2096             # reverse link order.  In that case, we can use ldflags to
2097             # avoid copying the object file to the host multiple
2098             # times.
2099             # This object can only be added if standard libraries are
2100             # used. Thus, we need to disable it if -nostdlib option is used
2101             if {[lsearch -regexp $options "-nostdlib"] < 0 } {
2102                 lappend options "ldflags=$gdb_saved_set_unbuffered_mode_obj"
2103             }
2104         }
2105     }
2106
2107     set result [target_compile $source $dest $type $options];
2108
2109     # Prune uninteresting compiler (and linker) output.
2110     regsub "Creating library file: \[^\r\n\]*\[\r\n\]+" $result "" result
2111
2112     regsub "\[\r\n\]*$" "$result" "" result;
2113     regsub "^\[\r\n\]*" "$result" "" result;
2114     
2115     if {[lsearch $options quiet] < 0} {
2116         # We shall update this on a per language basis, to avoid
2117         # changing the entire testsuite in one go.
2118         if {[lsearch $options f77] >= 0} {
2119             gdb_compile_test $source $result
2120         } elseif { $result != "" } {
2121             clone_output "gdb compile failed, $result"
2122         }
2123     }
2124     return $result;
2125 }
2126
2127
2128 # This is just like gdb_compile, above, except that it tries compiling
2129 # against several different thread libraries, to see which one this
2130 # system has.
2131 proc gdb_compile_pthreads {source dest type options} {
2132     set built_binfile 0
2133     set why_msg "unrecognized error"
2134     foreach lib {-lpthreads -lpthread -lthread ""} {
2135         # This kind of wipes out whatever libs the caller may have
2136         # set.  Or maybe theirs will override ours.  How infelicitous.
2137         set options_with_lib [concat $options [list libs=$lib quiet]]
2138         set ccout [gdb_compile $source $dest $type $options_with_lib]
2139         switch -regexp -- $ccout {
2140             ".*no posix threads support.*" {
2141                 set why_msg "missing threads include file"
2142                 break
2143             }
2144             ".*cannot open -lpthread.*" {
2145                 set why_msg "missing runtime threads library"
2146             }
2147             ".*Can't find library for -lpthread.*" {
2148                 set why_msg "missing runtime threads library"
2149             }
2150             {^$} {
2151                 pass "successfully compiled posix threads test case"
2152                 set built_binfile 1
2153                 break
2154             }
2155         }
2156     }
2157     if {!$built_binfile} {
2158         unsupported "Couldn't compile $source: ${why_msg}"
2159         return -1
2160     }
2161 }
2162
2163 # Build a shared library from SOURCES.  You must use get_compiler_info
2164 # first.
2165
2166 proc gdb_compile_shlib {sources dest options} {
2167     set obj_options $options
2168
2169     switch -glob [test_compiler_info] {
2170         "xlc-*" {
2171             lappend obj_options "additional_flags=-qpic"
2172         }
2173         "gcc-*" {
2174             if { !([istarget "powerpc*-*-aix*"]
2175                    || [istarget "rs6000*-*-aix*"]
2176                    || [istarget "*-*-cygwin*"]
2177                    || [istarget "*-*-mingw*"]
2178                    || [istarget "*-*-pe*"]) } {
2179                 lappend obj_options "additional_flags=-fpic"
2180             }
2181         }
2182         default {
2183             switch -glob [istarget] {
2184                 "hppa*-hp-hpux*" {
2185                     lappend obj_options "additional_flags=+z"
2186                 }
2187                 "mips-sgi-irix*" {
2188                     # Disable SGI compiler's implicit -Dsgi
2189                     lappend obj_options "additional_flags=-Usgi"
2190                 } 
2191                 default {
2192                     # don't know what the compiler is...
2193                 }
2194             }
2195         }
2196     }
2197
2198     set outdir [file dirname $dest]
2199     set objects ""
2200     foreach source $sources {
2201        set sourcebase [file tail $source]
2202        if {[gdb_compile $source "${outdir}/${sourcebase}.o" object $obj_options] != ""} {
2203            return -1
2204        }
2205        lappend objects ${outdir}/${sourcebase}.o
2206     }
2207
2208     if [istarget "hppa*-*-hpux*"] {
2209        remote_exec build "ld -b ${objects} -o ${dest}"
2210     } else {
2211        set link_options $options
2212        if [test_compiler_info "xlc-*"] {
2213           lappend link_options "additional_flags=-qmkshrobj"
2214        } else {
2215           lappend link_options "additional_flags=-shared"
2216
2217            if { ([istarget "*-*-mingw*"]
2218                  || [istarget *-*-cygwin*]
2219                  || [istarget *-*-pe*])} {
2220                lappend link_options "additional_flags=-Wl,--out-implib,${dest}.a"
2221            }
2222        }
2223        if {[gdb_compile "${objects}" "${dest}" executable $link_options] != ""} {
2224            return -1
2225        }
2226     }
2227 }
2228
2229 # This is just like gdb_compile_pthreads, above, except that we always add the
2230 # objc library for compiling Objective-C programs
2231 proc gdb_compile_objc {source dest type options} {
2232     set built_binfile 0
2233     set why_msg "unrecognized error"
2234     foreach lib {-lobjc -lpthreads -lpthread -lthread solaris} {
2235         # This kind of wipes out whatever libs the caller may have
2236         # set.  Or maybe theirs will override ours.  How infelicitous.
2237         if { $lib == "solaris" } {
2238             set lib "-lpthread -lposix4"
2239         }
2240         if { $lib != "-lobjc" } {
2241           set lib "-lobjc $lib"
2242         }
2243         set options_with_lib [concat $options [list libs=$lib quiet]]
2244         set ccout [gdb_compile $source $dest $type $options_with_lib]
2245         switch -regexp -- $ccout {
2246             ".*no posix threads support.*" {
2247                 set why_msg "missing threads include file"
2248                 break
2249             }
2250             ".*cannot open -lpthread.*" {
2251                 set why_msg "missing runtime threads library"
2252             }
2253             ".*Can't find library for -lpthread.*" {
2254                 set why_msg "missing runtime threads library"
2255             }
2256             {^$} {
2257                 pass "successfully compiled objc with posix threads test case"
2258                 set built_binfile 1
2259                 break
2260             }
2261         }
2262     }
2263     if {!$built_binfile} {
2264         unsupported "Couldn't compile $source: ${why_msg}"
2265         return -1
2266     }
2267 }
2268
2269 proc send_gdb { string } {
2270     global suppress_flag;
2271     if { $suppress_flag } {
2272         return "suppressed";
2273     }
2274     return [remote_send host "$string"];
2275 }
2276
2277 #
2278 #
2279
2280 proc gdb_expect { args } {
2281     if { [llength $args] == 2  && [lindex $args 0] != "-re" } {
2282         set atimeout [lindex $args 0];
2283         set expcode [list [lindex $args 1]];
2284     } else {
2285         set expcode $args;
2286     }
2287
2288     upvar timeout timeout;
2289
2290     if [target_info exists gdb,timeout] {
2291         if [info exists timeout] {
2292             if { $timeout < [target_info gdb,timeout] } {
2293                 set gtimeout [target_info gdb,timeout];
2294             } else {
2295                 set gtimeout $timeout;
2296             }
2297         } else {
2298             set gtimeout [target_info gdb,timeout];
2299         }
2300     }
2301
2302     if ![info exists gtimeout] {
2303         global timeout;
2304         if [info exists timeout] {
2305             set gtimeout $timeout;
2306         }
2307     }
2308
2309     if [info exists atimeout] {
2310         if { ![info exists gtimeout] || $gtimeout < $atimeout } {
2311             set gtimeout $atimeout;
2312         }
2313     } else {
2314         if ![info exists gtimeout] {
2315             # Eeeeew.
2316             set gtimeout 60;
2317         }
2318     }
2319
2320     global suppress_flag;
2321     global remote_suppress_flag;
2322     if [info exists remote_suppress_flag] {
2323         set old_val $remote_suppress_flag;
2324     }
2325     if [info exists suppress_flag] {
2326         if { $suppress_flag } {
2327             set remote_suppress_flag 1;
2328         }
2329     }
2330     set code [catch \
2331         {uplevel remote_expect host $gtimeout $expcode} string];
2332     if [info exists old_val] {
2333         set remote_suppress_flag $old_val;
2334     } else {
2335         if [info exists remote_suppress_flag] {
2336             unset remote_suppress_flag;
2337         }
2338     }
2339
2340     if {$code == 1} {
2341         global errorInfo errorCode;
2342
2343         return -code error -errorinfo $errorInfo -errorcode $errorCode $string
2344     } elseif {$code == 2} {
2345         return -code return $string
2346     } elseif {$code == 3} {
2347         return
2348     } elseif {$code > 4} {
2349         return -code $code $string
2350     }
2351 }
2352
2353 # gdb_expect_list MESSAGE SENTINEL LIST -- expect a sequence of outputs
2354 #
2355 # Check for long sequence of output by parts.
2356 # MESSAGE: is the test message to be printed with the test success/fail.
2357 # SENTINEL: Is the terminal pattern indicating that output has finished.
2358 # LIST: is the sequence of outputs to match.
2359 # If the sentinel is recognized early, it is considered an error.
2360 #
2361 # Returns:
2362 #    1 if the test failed,
2363 #    0 if the test passes,
2364 #   -1 if there was an internal error.
2365 #
2366 proc gdb_expect_list {test sentinel list} {
2367     global gdb_prompt
2368     global suppress_flag
2369     set index 0
2370     set ok 1
2371     if { $suppress_flag } {
2372         set ok 0
2373         unresolved "${test}"
2374     }
2375     while { ${index} < [llength ${list}] } {
2376         set pattern [lindex ${list} ${index}]
2377         set index [expr ${index} + 1]
2378         if { ${index} == [llength ${list}] } {
2379             if { ${ok} } {
2380                 gdb_expect {
2381                     -re "${pattern}${sentinel}" {
2382                         # pass "${test}, pattern ${index} + sentinel"
2383                     }
2384                     -re "${sentinel}" {
2385                         fail "${test} (pattern ${index} + sentinel)"
2386                         set ok 0
2387                     }
2388                     -re ".*A problem internal to GDB has been detected" {
2389                         fail "${test} (GDB internal error)"
2390                         set ok 0
2391                         gdb_internal_error_resync
2392                     }
2393                     timeout {
2394                         fail "${test} (pattern ${index} + sentinel) (timeout)"
2395                         set ok 0
2396                     }
2397                 }
2398             } else {
2399                 # unresolved "${test}, pattern ${index} + sentinel"
2400             }
2401         } else {
2402             if { ${ok} } {
2403                 gdb_expect {
2404                     -re "${pattern}" {
2405                         # pass "${test}, pattern ${index}"
2406                     }
2407                     -re "${sentinel}" {
2408                         fail "${test} (pattern ${index})"
2409                         set ok 0
2410                     }
2411                     -re ".*A problem internal to GDB has been detected" {
2412                         fail "${test} (GDB internal error)"
2413                         set ok 0
2414                         gdb_internal_error_resync
2415                     }
2416                     timeout {
2417                         fail "${test} (pattern ${index}) (timeout)"
2418                         set ok 0
2419                     }
2420                 }
2421             } else {
2422                 # unresolved "${test}, pattern ${index}"
2423             }
2424         }
2425     }
2426     if { ${ok} } {
2427         pass "${test}"
2428         return 0
2429     } else {
2430         return 1
2431     }
2432 }
2433
2434 #
2435 #
2436 proc gdb_suppress_entire_file { reason } {
2437     global suppress_flag;
2438
2439     warning "$reason\n";
2440     set suppress_flag -1;
2441 }
2442
2443 #
2444 # Set suppress_flag, which will cause all subsequent calls to send_gdb and
2445 # gdb_expect to fail immediately (until the next call to 
2446 # gdb_stop_suppressing_tests).
2447 #
2448 proc gdb_suppress_tests { args } {
2449     global suppress_flag;
2450
2451     return;  # fnf - disable pending review of results where
2452              # testsuite ran better without this
2453     incr suppress_flag;
2454
2455     if { $suppress_flag == 1 } {
2456         if { [llength $args] > 0 } {
2457             warning "[lindex $args 0]\n";
2458         } else {
2459             warning "Because of previous failure, all subsequent tests in this group will automatically fail.\n";
2460         }
2461     }
2462 }
2463
2464 #
2465 # Clear suppress_flag.
2466 #
2467 proc gdb_stop_suppressing_tests { } {
2468     global suppress_flag;
2469
2470     if [info exists suppress_flag] {
2471         if { $suppress_flag > 0 } {
2472             set suppress_flag 0;
2473             clone_output "Tests restarted.\n";
2474         }
2475     } else {
2476         set suppress_flag 0;
2477     }
2478 }
2479
2480 proc gdb_clear_suppressed { } {
2481     global suppress_flag;
2482
2483     set suppress_flag 0;
2484 }
2485
2486 proc gdb_start { } {
2487     default_gdb_start
2488 }
2489
2490 proc gdb_exit { } {
2491     catch default_gdb_exit
2492 }
2493
2494 #
2495 # gdb_load_cmd -- load a file into the debugger.
2496 #                 ARGS - additional args to load command.
2497 #                 return a -1 if anything goes wrong.
2498 #
2499 proc gdb_load_cmd { args } {
2500     global gdb_prompt
2501
2502     if [target_info exists gdb_load_timeout] {
2503         set loadtimeout [target_info gdb_load_timeout]
2504     } else {
2505         set loadtimeout 1600
2506     }
2507     send_gdb "load $args\n"
2508     verbose "Timeout is now $loadtimeout seconds" 2
2509     gdb_expect $loadtimeout {
2510         -re "Loading section\[^\r\]*\r\n" {
2511             exp_continue
2512         }
2513         -re "Start address\[\r\]*\r\n" {
2514             exp_continue
2515         }
2516         -re "Transfer rate\[\r\]*\r\n" {
2517             exp_continue
2518         }
2519         -re "Memory access error\[^\r\]*\r\n" {
2520             perror "Failed to load program"
2521             return -1
2522         }
2523         -re "$gdb_prompt $" {
2524             return 0
2525         }
2526         -re "(.*)\r\n$gdb_prompt " {
2527             perror "Unexpected reponse from 'load' -- $expect_out(1,string)"
2528             return -1
2529         }
2530         timeout {
2531             perror "Timed out trying to load $args."
2532             return -1
2533         }
2534     }
2535     return -1
2536 }
2537
2538 # Return the filename to download to the target and load on the target
2539 # for this shared library.  Normally just LIBNAME, unless shared libraries
2540 # for this target have separate link and load images.
2541
2542 proc shlib_target_file { libname } {
2543     return $libname
2544 }
2545
2546 # Return the filename GDB will load symbols from when debugging this
2547 # shared library.  Normally just LIBNAME, unless shared libraries for
2548 # this target have separate link and load images.
2549
2550 proc shlib_symbol_file { libname } {
2551     return $libname
2552 }
2553
2554 # gdb_download
2555 #
2556 # Copy a file to the remote target and return its target filename.
2557 # Schedule the file to be deleted at the end of this test.
2558
2559 proc gdb_download { filename } {
2560     global cleanfiles
2561
2562     set destname [remote_download target $filename]
2563     lappend cleanfiles $destname
2564     return $destname
2565 }
2566
2567 # gdb_load_shlibs LIB...
2568 #
2569 # Copy the listed libraries to the target.
2570
2571 proc gdb_load_shlibs { args } {
2572     if {![is_remote target]} {
2573         return
2574     }
2575
2576     foreach file $args {
2577         gdb_download [shlib_target_file $file]
2578     }
2579
2580     # Even if the target supplies full paths for shared libraries,
2581     # they may not be paths for this system.
2582     gdb_test "set solib-search-path [file dirname [lindex $args 0]]" "" ""
2583 }
2584
2585 #
2586 # gdb_load -- load a file into the debugger.
2587 # Many files in config/*.exp override this procedure.
2588 #
2589 proc gdb_load { arg } {
2590     return [gdb_file_cmd $arg]
2591 }
2592
2593 # gdb_reload -- load a file into the target.  Called before "running",
2594 # either the first time or after already starting the program once,
2595 # for remote targets.  Most files that override gdb_load should now
2596 # override this instead.
2597
2598 proc gdb_reload { } {
2599     # For the benefit of existing configurations, default to gdb_load.
2600     # Specifying no file defaults to the executable currently being
2601     # debugged.
2602     return [gdb_load ""]
2603 }
2604
2605 proc gdb_continue { function } {
2606     global decimal
2607
2608     return [gdb_test "continue" ".*Breakpoint $decimal, $function .*" "continue to $function"];
2609 }
2610
2611 proc default_gdb_init { args } {
2612     global gdb_wrapper_initialized
2613     global gdb_wrapper_target
2614     global cleanfiles
2615     
2616     set cleanfiles {}
2617
2618     gdb_clear_suppressed;
2619
2620     # Make sure that the wrapper is rebuilt
2621     # with the appropriate multilib option.
2622     if { $gdb_wrapper_target != [current_target_name] } {
2623         set gdb_wrapper_initialized 0
2624     }
2625     
2626     # Unlike most tests, we have a small number of tests that generate
2627     # a very large amount of output.  We therefore increase the expect
2628     # buffer size to be able to contain the entire test output.
2629     match_max -d 30000
2630     # Also set this value for the currently running GDB. 
2631     match_max [match_max -d]
2632
2633     # We want to add the name of the TCL testcase to the PASS/FAIL messages.
2634     if { [llength $args] > 0 } {
2635         global pf_prefix
2636
2637         set file [lindex $args 0];
2638
2639         set pf_prefix "[file tail [file dirname $file]]/[file tail $file]:";
2640     }
2641     global gdb_prompt;
2642     if [target_info exists gdb_prompt] {
2643         set gdb_prompt [target_info gdb_prompt];
2644     } else {
2645         set gdb_prompt "\\(gdb\\)"
2646     }
2647 }
2648
2649 # The default timeout used when testing GDB commands.  We want to use
2650 # the same timeout as the default dejagnu timeout, unless the user has
2651 # already provided a specific value (probably through a site.exp file).
2652 global gdb_test_timeout
2653 if ![info exists gdb_test_timeout] {
2654     set gdb_test_timeout $timeout
2655 }
2656
2657 # A list of global variables that GDB testcases should not use.
2658 # We try to prevent their use by monitoring write accesses and raising
2659 # an error when that happens.
2660 set banned_variables { bug_id prms_id }
2661
2662 # gdb_init is called by runtest at start, but also by several
2663 # tests directly; gdb_finish is only called from within runtest after
2664 # each test source execution.
2665 # Placing several traces by repetitive calls to gdb_init leads
2666 # to problems, as only one trace is removed in gdb_finish.
2667 # To overcome this possible problem, we add a variable that records
2668 # if the banned variables are traced.
2669 set banned_variables_traced 0
2670
2671 proc gdb_init { args } {
2672     # Reset the timeout value to the default.  This way, any testcase
2673     # that changes the timeout value without resetting it cannot affect
2674     # the timeout used in subsequent testcases.
2675     global gdb_test_timeout
2676     global timeout
2677     set timeout $gdb_test_timeout
2678
2679     # Block writes to all banned variables...
2680     global banned_variables
2681     global banned_variables_traced
2682     if (!$banned_variables_traced) {
2683         foreach banned_var $banned_variables {
2684             global "$banned_var"
2685             trace add variable "$banned_var" write error
2686         }
2687         set banned_variables_traced 1
2688     }
2689
2690     return [eval default_gdb_init $args];
2691 }
2692
2693 proc gdb_finish { } {
2694     global cleanfiles
2695
2696     # Exit first, so that the files are no longer in use.
2697     gdb_exit
2698
2699     if { [llength $cleanfiles] > 0 } {
2700         eval remote_file target delete $cleanfiles
2701         set cleanfiles {}
2702     }
2703
2704     # Unblock write access to the banned variables.  Dejagnu typically
2705     # resets some of them between testcases.
2706     global banned_variables
2707     global banned_variables_traced
2708     if ($banned_variables_traced) {
2709         foreach banned_var $banned_variables {
2710             global "$banned_var"
2711             trace remove variable "$banned_var" write error
2712         }
2713         set banned_variables_traced 0
2714     }
2715 }
2716
2717 global debug_format
2718 set debug_format "unknown"
2719
2720 # Run the gdb command "info source" and extract the debugging format
2721 # information from the output and save it in debug_format.
2722
2723 proc get_debug_format { } {
2724     global gdb_prompt
2725     global verbose
2726     global expect_out
2727     global debug_format
2728
2729     set debug_format "unknown"
2730     send_gdb "info source\n"
2731     gdb_expect 10 {
2732         -re "Compiled with (.*) debugging format.\r\n.*$gdb_prompt $" {
2733             set debug_format $expect_out(1,string)
2734             verbose "debug format is $debug_format"
2735             return 1;
2736         }
2737         -re "No current source file.\r\n$gdb_prompt $" {
2738             perror "get_debug_format used when no current source file"
2739             return 0;
2740         }
2741         -re "$gdb_prompt $" {
2742             warning "couldn't check debug format (no valid response)."
2743             return 1;
2744         }
2745         timeout {
2746             warning "couldn't check debug format (timed out)."
2747             return 1;
2748         }
2749     }
2750 }
2751
2752 # Return true if FORMAT matches the debug format the current test was
2753 # compiled with.  FORMAT is a shell-style globbing pattern; it can use
2754 # `*', `[...]', and so on.
2755 #
2756 # This function depends on variables set by `get_debug_format', above.
2757
2758 proc test_debug_format {format} {
2759     global debug_format
2760
2761     return [expr [string match $format $debug_format] != 0]
2762 }
2763
2764 # Like setup_xfail, but takes the name of a debug format (DWARF 1,
2765 # COFF, stabs, etc).  If that format matches the format that the
2766 # current test was compiled with, then the next test is expected to
2767 # fail for any target.  Returns 1 if the next test or set of tests is
2768 # expected to fail, 0 otherwise (or if it is unknown).  Must have
2769 # previously called get_debug_format.
2770 proc setup_xfail_format { format } {
2771     set ret [test_debug_format $format];
2772
2773     if {$ret} then {
2774         setup_xfail "*-*-*"
2775     }
2776     return $ret;
2777 }
2778
2779 proc gdb_step_for_stub { } {
2780     global gdb_prompt;
2781
2782     if ![target_info exists gdb,use_breakpoint_for_stub] {
2783         if [target_info exists gdb_stub_step_command] {
2784             set command [target_info gdb_stub_step_command];
2785         } else {
2786             set command "step";
2787         }
2788         send_gdb "${command}\n";
2789         set tries 0;
2790         gdb_expect 60 {
2791             -re "(main.* at |.*in .*start).*$gdb_prompt" {
2792                 return;
2793             }
2794             -re ".*$gdb_prompt" {
2795                 incr tries;
2796                 if { $tries == 5 } {
2797                     fail "stepping out of breakpoint function";
2798                     return;
2799                 }
2800                 send_gdb "${command}\n";
2801                 exp_continue;
2802             }
2803             default {
2804                 fail "stepping out of breakpoint function";
2805                 return;
2806             }
2807         }
2808     }
2809     send_gdb "where\n";
2810     gdb_expect {
2811         -re "main\[^\r\n\]*at \(\[^:]+\):\(\[0-9\]+\)" {
2812             set file $expect_out(1,string);
2813             set linenum [expr $expect_out(2,string) + 1];
2814             set breakplace "${file}:${linenum}";
2815         }
2816         default {}
2817     }
2818     send_gdb "break ${breakplace}\n";
2819     gdb_expect 60 {
2820         -re "Breakpoint (\[0-9\]+) at.*$gdb_prompt" {
2821             set breakpoint $expect_out(1,string);
2822         }
2823         -re "Breakpoint (\[0-9\]+): file.*$gdb_prompt" {
2824             set breakpoint $expect_out(1,string);
2825         }
2826         default {}
2827     }
2828     send_gdb "continue\n";
2829     gdb_expect 60 {
2830         -re "Breakpoint ${breakpoint},.*$gdb_prompt" {
2831             gdb_test "delete $breakpoint" ".*" "";
2832             return;
2833         }
2834         default {}
2835     }
2836 }
2837
2838 # gdb_get_line_number TEXT [FILE]
2839 #
2840 # Search the source file FILE, and return the line number of the
2841 # first line containing TEXT.  If no match is found, return -1.
2842
2843 # TEXT is a string literal, not a regular expression.
2844 #
2845 # The default value of FILE is "$srcdir/$subdir/$srcfile".  If FILE is
2846 # specified, and does not start with "/", then it is assumed to be in
2847 # "$srcdir/$subdir".  This is awkward, and can be fixed in the future,
2848 # by changing the callers and the interface at the same time.
2849 # In particular: gdb.base/break.exp, gdb.base/condbreak.exp,
2850 # gdb.base/ena-dis-br.exp.
2851 #
2852 # Use this function to keep your test scripts independent of the
2853 # exact line numbering of the source file.  Don't write:
2854
2855 #   send_gdb "break 20"
2856
2857 # This means that if anyone ever edits your test's source file, 
2858 # your test could break.  Instead, put a comment like this on the
2859 # source file line you want to break at:
2860
2861 #   /* breakpoint spot: frotz.exp: test name */
2862
2863 # and then write, in your test script (which we assume is named
2864 # frotz.exp):
2865
2866 #   send_gdb "break [gdb_get_line_number "frotz.exp: test name"]\n"
2867 #
2868 # (Yes, Tcl knows how to handle the nested quotes and brackets.
2869 # Try this:
2870 #       $ tclsh
2871 #       % puts "foo [lindex "bar baz" 1]"
2872 #       foo baz
2873 #       % 
2874 # Tcl is quite clever, for a little stringy language.)
2875 #
2876 # ===
2877 #
2878 # The previous implementation of this procedure used the gdb search command.
2879 # This version is different:
2880 #
2881 #   . It works with MI, and it also works when gdb is not running.
2882 #
2883 #   . It operates on the build machine, not the host machine.
2884 #
2885 #   . For now, this implementation fakes a current directory of
2886 #     $srcdir/$subdir to be compatible with the old implementation.
2887 #     This will go away eventually and some callers will need to
2888 #     be changed.
2889 #
2890 #   . The TEXT argument is literal text and matches literally,
2891 #     not a regular expression as it was before.
2892 #
2893 #   . State changes in gdb, such as changing the current file
2894 #     and setting $_, no longer happen.
2895 #
2896 # After a bit of time we can forget about the differences from the
2897 # old implementation.
2898 #
2899 # --chastain 2004-08-05
2900
2901 proc gdb_get_line_number { text { file "" } } {
2902     global srcdir
2903     global subdir
2904     global srcfile
2905
2906     if { "$file" == "" } then {
2907         set file "$srcfile"
2908     }
2909     if { ! [regexp "^/" "$file"] } then {
2910         set file "$srcdir/$subdir/$file"
2911     }
2912
2913     if { [ catch { set fd [open "$file"] } message ] } then {
2914         perror "$message"
2915         return -1
2916     }
2917
2918     set found -1
2919     for { set line 1 } { 1 } { incr line } {
2920         if { [ catch { set nchar [gets "$fd" body] } message ] } then {
2921             perror "$message"
2922             return -1
2923         }
2924         if { $nchar < 0 } then {
2925             break
2926         }
2927         if { [string first "$text" "$body"] >= 0 } then {
2928             set found $line
2929             break
2930         }
2931     }
2932
2933     if { [ catch { close "$fd" } message ] } then {
2934         perror "$message"
2935         return -1
2936     }
2937
2938     return $found
2939 }
2940
2941 # gdb_continue_to_end:
2942 #       The case where the target uses stubs has to be handled specially. If a
2943 #       stub is used, we set a breakpoint at exit because we cannot rely on
2944 #       exit() behavior of a remote target.
2945
2946 # mssg is the error message that gets printed.
2947
2948 proc gdb_continue_to_end {mssg} {
2949   if [target_info exists use_gdb_stub] {
2950     if {![gdb_breakpoint "exit"]} {
2951       return 0
2952     }
2953     gdb_test "continue" "Continuing..*Breakpoint .*exit.*" \
2954       "continue until exit at $mssg"
2955   } else {
2956     # Continue until we exit.  Should not stop again.
2957     # Don't bother to check the output of the program, that may be
2958     # extremely tough for some remote systems.
2959     gdb_test "continue"\
2960       "Continuing.\[\r\n0-9\]+(... EXIT code 0\[\r\n\]+|Program exited normally\\.).*"\
2961       "continue until exit at $mssg"
2962   }
2963 }
2964
2965 proc rerun_to_main {} {
2966   global gdb_prompt
2967
2968   if [target_info exists use_gdb_stub] {
2969     gdb_run_cmd
2970     gdb_expect {
2971       -re ".*Breakpoint .*main .*$gdb_prompt $"\
2972               {pass "rerun to main" ; return 0}
2973       -re "$gdb_prompt $"\
2974               {fail "rerun to main" ; return 0}
2975       timeout {fail "(timeout) rerun to main" ; return 0}
2976     }
2977   } else {
2978     send_gdb "run\n"
2979     gdb_expect {
2980       -re "The program .* has been started already.*y or n. $" {
2981           send_gdb "y\n"
2982           exp_continue
2983       }
2984       -re "Starting program.*$gdb_prompt $"\
2985               {pass "rerun to main" ; return 0}
2986       -re "$gdb_prompt $"\
2987               {fail "rerun to main" ; return 0}
2988       timeout {fail "(timeout) rerun to main" ; return 0}
2989     }
2990   }
2991 }
2992
2993 # Print a message and return true if a test should be skipped
2994 # due to lack of floating point suport.
2995
2996 proc gdb_skip_float_test { msg } {
2997     if [target_info exists gdb,skip_float_tests] {
2998         verbose "Skipping test '$msg': no float tests.";
2999         return 1;
3000     }
3001     return 0;
3002 }
3003
3004 # Print a message and return true if a test should be skipped
3005 # due to lack of stdio support.
3006
3007 proc gdb_skip_stdio_test { msg } {
3008     if [target_info exists gdb,noinferiorio] {
3009         verbose "Skipping test '$msg': no inferior i/o.";
3010         return 1;
3011     }
3012     return 0;
3013 }
3014
3015 proc gdb_skip_bogus_test { msg } {
3016     return 0;
3017 }
3018
3019 # Return true if a test should be skipped due to lack of XML support
3020 # in the host GDB.
3021 # NOTE: This must be called while gdb is *not* running.
3022
3023 proc gdb_skip_xml_test { } {
3024     global gdb_prompt
3025     global srcdir
3026     global xml_missing_cached
3027
3028     if {[info exists xml_missing_cached]} {
3029         return $xml_missing_cached
3030     }
3031
3032     gdb_start
3033     set xml_missing_cached 0
3034     gdb_test_multiple "set tdesc filename ${srcdir}/gdb.xml/trivial.xml" "" {
3035         -re ".*XML support was disabled at compile time.*$gdb_prompt $" {
3036             set xml_missing_cached 1
3037         }
3038         -re ".*$gdb_prompt $" { }
3039     }
3040     gdb_exit
3041     return $xml_missing_cached
3042 }
3043
3044 # Note: the procedure gdb_gnu_strip_debug will produce an executable called
3045 # ${binfile}.dbglnk, which is just like the executable ($binfile) but without
3046 # the debuginfo. Instead $binfile has a .gnu_debuglink section which contains
3047 # the name of a debuginfo only file. This file will be stored in the same
3048 # subdirectory.
3049
3050 # Functions for separate debug info testing
3051
3052 # starting with an executable:
3053 # foo --> original executable
3054
3055 # at the end of the process we have:
3056 # foo.stripped --> foo w/o debug info
3057 # foo.debug --> foo's debug info
3058 # foo --> like foo, but with a new .gnu_debuglink section pointing to foo.debug.
3059
3060 # Return the build-id hex string (usually 160 bits as 40 hex characters)
3061 # converted to the form: .build-id/ab/cdef1234...89.debug
3062 # Return "" if no build-id found.
3063 proc build_id_debug_filename_get { exec } {
3064     set tmp "${exec}-tmp"
3065     set objcopy_program [transform objcopy]
3066
3067     set result [catch "exec $objcopy_program -j .note.gnu.build-id -O binary $exec $tmp" output]
3068     verbose "result is $result"
3069     verbose "output is $output"
3070     if {$result == 1} {
3071         return ""
3072     }
3073     set fi [open $tmp]
3074     fconfigure $fi -translation binary
3075     # Skip the NOTE header.
3076     read $fi 16
3077     set data [read $fi]
3078     close $fi
3079     file delete $tmp
3080     if ![string compare $data ""] then {
3081         return ""
3082     }
3083     # Convert it to hex.
3084     binary scan $data H* data
3085     regsub {^..} $data {\0/} data
3086     return ".build-id/${data}.debug";
3087 }
3088
3089 # Create stripped files for DEST, replacing it.  If ARGS is passed, it is a
3090 # list of optional flags.  The only currently supported flag is no-main,
3091 # which removes the symbol entry for main from the separate debug file.
3092 #
3093 # Function returns zero on success.  Function will return non-zero failure code
3094 # on some targets not supporting separate debug info (such as i386-msdos).
3095
3096 proc gdb_gnu_strip_debug { dest args } {
3097
3098     # Use the first separate debug info file location searched by GDB so the
3099     # run cannot be broken by some stale file searched with higher precedence.
3100     set debug_file "${dest}.debug"
3101
3102     set strip_to_file_program [transform strip]
3103     set objcopy_program [transform objcopy]
3104
3105     set debug_link [file tail $debug_file]
3106     set stripped_file "${dest}.stripped"
3107
3108     # Get rid of the debug info, and store result in stripped_file
3109     # something like gdb/testsuite/gdb.base/blah.stripped.
3110     set result [catch "exec $strip_to_file_program --strip-debug ${dest} -o ${stripped_file}" output]
3111     verbose "result is $result"
3112     verbose "output is $output"
3113     if {$result == 1} {
3114       return 1
3115     }
3116
3117     # Workaround PR binutils/10802:
3118     # Preserve the 'x' bit also for PIEs (Position Independent Executables).
3119     set perm [file attributes ${dest} -permissions]
3120     file attributes ${stripped_file} -permissions $perm
3121
3122     # Get rid of everything but the debug info, and store result in debug_file
3123     # This will be in the .debug subdirectory, see above.
3124     set result [catch "exec $strip_to_file_program --only-keep-debug ${dest} -o ${debug_file}" output]
3125     verbose "result is $result"
3126     verbose "output is $output"
3127     if {$result == 1} {
3128       return 1
3129     }
3130
3131     # If no-main is passed, strip the symbol for main from the separate
3132     # file.  This is to simulate the behavior of elfutils's eu-strip, which
3133     # leaves the symtab in the original file only.  There's no way to get
3134     # objcopy or strip to remove the symbol table without also removing the
3135     # debugging sections, so this is as close as we can get.
3136     if { [llength $args] == 1 && [lindex $args 0] == "no-main" } {
3137         set result [catch "exec $objcopy_program -N main ${debug_file} ${debug_file}-tmp" output]
3138         verbose "result is $result"
3139         verbose "output is $output"
3140         if {$result == 1} {
3141             return 1
3142         }
3143         file delete "${debug_file}"
3144         file rename "${debug_file}-tmp" "${debug_file}"
3145     }
3146
3147     # Link the two previous output files together, adding the .gnu_debuglink
3148     # section to the stripped_file, containing a pointer to the debug_file,
3149     # save the new file in dest.
3150     # This will be the regular executable filename, in the usual location.
3151     set result [catch "exec $objcopy_program --add-gnu-debuglink=${debug_file} ${stripped_file} ${dest}" output]
3152     verbose "result is $result"
3153     verbose "output is $output"
3154     if {$result == 1} {
3155       return 1
3156     }
3157
3158     # Workaround PR binutils/10802:
3159     # Preserve the 'x' bit also for PIEs (Position Independent Executables).
3160     set perm [file attributes ${stripped_file} -permissions]
3161     file attributes ${dest} -permissions $perm
3162
3163     return 0
3164 }
3165
3166 # Test the output of GDB_COMMAND matches the pattern obtained
3167 # by concatenating all elements of EXPECTED_LINES.  This makes
3168 # it possible to split otherwise very long string into pieces.
3169 # If third argument is not empty, it's used as the name of the
3170 # test to be printed on pass/fail.
3171 proc help_test_raw { gdb_command expected_lines args } {
3172     set message $gdb_command
3173     if [llength $args]>0 then {
3174         set message [lindex $args 0]
3175     } 
3176     set expected_output [join $expected_lines ""]
3177     gdb_test "${gdb_command}" "${expected_output}" $message
3178 }
3179
3180 # Test the output of "help COMMNAD_CLASS". EXPECTED_INITIAL_LINES
3181 # are regular expressions that should match the beginning of output,
3182 # before the list of commands in that class.  The presence of 
3183 # command list and standard epilogue will be tested automatically.
3184 proc test_class_help { command_class expected_initial_lines args } {
3185     set l_stock_body {
3186         "List of commands\:.*\[\r\n\]+"
3187         "Type \"help\" followed by command name for full documentation\.\[\r\n\]+"
3188         "Type \"apropos word\" to search for commands related to \"word\"\.[\r\n\]+"
3189         "Command name abbreviations are allowed if unambiguous\." 
3190     }
3191     set l_entire_body [concat $expected_initial_lines $l_stock_body]
3192
3193     eval [list help_test_raw "help ${command_class}" $l_entire_body] $args
3194 }
3195
3196 # COMMAND_LIST should have either one element -- command to test, or
3197 # two elements -- abbreviated command to test, and full command the first
3198 # element is abbreviation of.
3199 # The command must be a prefix command.  EXPECTED_INITIAL_LINES
3200 # are regular expressions that should match the beginning of output,
3201 # before the list of subcommands.  The presence of 
3202 # subcommand list and standard epilogue will be tested automatically.
3203 proc test_prefix_command_help { command_list expected_initial_lines args } {
3204     set command [lindex $command_list 0]   
3205     if {[llength $command_list]>1} {        
3206         set full_command [lindex $command_list 1]
3207     } else {
3208         set full_command $command
3209     }
3210     # Use 'list' and not just {} because we want variables to
3211     # be expanded in this list.
3212     set l_stock_body [list\
3213          "List of $full_command subcommands\:.*\[\r\n\]+"\
3214          "Type \"help $full_command\" followed by $full_command subcommand name for full documentation\.\[\r\n\]+"\
3215          "Type \"apropos word\" to search for commands related to \"word\"\.\[\r\n\]+"\
3216          "Command name abbreviations are allowed if unambiguous\."]
3217     set l_entire_body [concat $expected_initial_lines $l_stock_body]
3218     if {[llength $args]>0} {
3219         help_test_raw "help ${command}" $l_entire_body [lindex $args 0]
3220     } else {
3221         help_test_raw "help ${command}" $l_entire_body
3222     }
3223 }
3224
3225 # Build executable named EXECUTABLE, from SOURCES.  If SOURCES are not
3226 # provided, uses $EXECUTABLE.c.  The TESTNAME paramer is the name of test
3227 # to pass to untested, if something is wrong.  OPTIONS are passed
3228 # to gdb_compile directly.
3229 proc build_executable { testname executable {sources ""} {options {debug}} } {
3230
3231     global objdir
3232     global subdir
3233     global srcdir
3234     if {[llength $sources]==0} {
3235         set sources ${executable}.c
3236     }
3237
3238     set binfile ${objdir}/${subdir}/${executable}
3239
3240     set objects {}
3241     for {set i 0} "\$i<[llength $sources]" {incr i} {
3242         set s [lindex $sources $i]
3243         if  { [gdb_compile "${srcdir}/${subdir}/${s}" "${binfile}${i}.o" object $options] != "" } {
3244             untested $testname
3245             return -1
3246         }
3247         lappend objects "${binfile}${i}.o"
3248     }
3249     
3250     if  { [gdb_compile $objects "${binfile}" executable $options] != "" } {
3251         untested $testname
3252         return -1
3253     }
3254
3255     if [get_compiler_info ${binfile}] {
3256         return -1
3257     }
3258     return 0
3259 }
3260
3261 # Starts fresh GDB binary and loads EXECUTABLE into GDB. EXECUTABLE is
3262 # the name of binary in ${objdir}/${subdir}.
3263 proc clean_restart { executable } {
3264     global srcdir
3265     global objdir
3266     global subdir
3267     set binfile ${objdir}/${subdir}/${executable}
3268
3269     gdb_exit
3270     gdb_start
3271     gdb_reinitialize_dir $srcdir/$subdir
3272     gdb_load ${binfile}
3273
3274     if [target_info exists gdb_stub] {
3275         gdb_step_for_stub;
3276     }    
3277 }
3278
3279 # Prepares for testing, by calling build_executable, and then clean_restart.
3280 # Please refer to build_executable for parameter description.
3281 proc prepare_for_testing { testname executable {sources ""} {options {debug}}} {
3282
3283     if {[build_executable $testname $executable $sources $options] == -1} {
3284         return -1
3285     }
3286     clean_restart $executable
3287
3288     return 0
3289 }
3290
3291 proc get_valueof { fmt exp default } {
3292     global gdb_prompt
3293
3294     set test "get valueof \"${exp}\""
3295     set val ${default}
3296     gdb_test_multiple "print${fmt} ${exp}" "$test" {
3297         -re "\\$\[0-9\]* = (.*)\[\r\n\]*$gdb_prompt $" {
3298             set val $expect_out(1,string)
3299             pass "$test ($val)"
3300         }
3301         timeout {
3302             fail "$test (timeout)"
3303         }
3304     }
3305     return ${val}
3306 }
3307
3308 proc get_integer_valueof { exp default } {
3309     global gdb_prompt
3310
3311     set test "get integer valueof \"${exp}\""
3312     set val ${default}
3313     gdb_test_multiple "print /d ${exp}" "$test" {
3314         -re "\\$\[0-9\]* = (\[-\]*\[0-9\]*).*$gdb_prompt $" {
3315             set val $expect_out(1,string)
3316             pass "$test ($val)"
3317         }
3318         timeout {
3319             fail "$test (timeout)"
3320         }
3321     }
3322     return ${val}
3323 }
3324
3325 proc get_hexadecimal_valueof { exp default } {
3326     global gdb_prompt
3327     send_gdb "print /x ${exp}\n"
3328     set test "get hexadecimal valueof \"${exp}\""
3329     gdb_expect {
3330         -re "\\$\[0-9\]* = (0x\[0-9a-zA-Z\]+).*$gdb_prompt $" {
3331             set val $expect_out(1,string)
3332             pass "$test"
3333         }
3334         timeout {
3335             set val ${default}
3336             fail "$test (timeout)"
3337         }
3338     }
3339     return ${val}
3340 }
3341
3342 proc get_sizeof { type default } {
3343     return [get_integer_valueof "sizeof (${type})" $default]
3344 }
3345
3346 # Log gdb command line and script if requested.
3347 if {[info exists TRANSCRIPT]} {
3348   rename send_gdb real_send_gdb
3349   rename remote_spawn real_remote_spawn
3350   rename remote_close real_remote_close
3351
3352   global gdb_transcript
3353   set gdb_transcript ""
3354
3355   global gdb_trans_count
3356   set gdb_trans_count 1
3357
3358   proc remote_spawn {args} {
3359     global gdb_transcript gdb_trans_count outdir
3360
3361     if {$gdb_transcript != ""} {
3362       close $gdb_transcript
3363     }
3364     set gdb_transcript [open [file join $outdir transcript.$gdb_trans_count] w]
3365     puts $gdb_transcript [lindex $args 1]
3366     incr gdb_trans_count
3367
3368     return [uplevel real_remote_spawn $args]
3369   }
3370
3371   proc remote_close {args} {
3372     global gdb_transcript
3373
3374     if {$gdb_transcript != ""} {
3375       close $gdb_transcript
3376       set gdb_transcript ""
3377     }
3378
3379     return [uplevel real_remote_close $args]
3380   }
3381
3382   proc send_gdb {args} {
3383     global gdb_transcript
3384
3385     if {$gdb_transcript != ""} {
3386       puts -nonewline $gdb_transcript [lindex $args 0]
3387     }
3388
3389     return [uplevel real_send_gdb $args]
3390   }
3391 }
3392
3393 proc core_find {binfile {deletefiles {}} {arg ""}} {
3394     global objdir subdir
3395
3396     set destcore "$binfile.core"
3397     file delete $destcore
3398
3399     # Create a core file named "$destcore" rather than just "core", to
3400     # avoid problems with sys admin types that like to regularly prune all
3401     # files named "core" from the system.
3402     #
3403     # Arbitrarily try setting the core size limit to "unlimited" since
3404     # this does not hurt on systems where the command does not work and
3405     # allows us to generate a core on systems where it does.
3406     #
3407     # Some systems append "core" to the name of the program; others append
3408     # the name of the program to "core"; still others (like Linux, as of
3409     # May 2003) create cores named "core.PID".  In the latter case, we
3410     # could have many core files lying around, and it may be difficult to
3411     # tell which one is ours, so let's run the program in a subdirectory.
3412     set found 0
3413     set coredir "${objdir}/${subdir}/coredir.[getpid]"
3414     file mkdir $coredir
3415     catch "system \"(cd ${coredir}; ulimit -c unlimited; ${binfile} ${arg}; true) >/dev/null 2>&1\""
3416     #      remote_exec host "${binfile}"
3417     foreach i "${coredir}/core ${coredir}/core.coremaker.c ${binfile}.core" {
3418         if [remote_file build exists $i] {
3419             remote_exec build "mv $i $destcore"
3420             set found 1
3421         }
3422     }
3423     # Check for "core.PID".
3424     if { $found == 0 } {
3425         set names [glob -nocomplain -directory $coredir core.*]
3426         if {[llength $names] == 1} {
3427             set corefile [file join $coredir [lindex $names 0]]
3428             remote_exec build "mv $corefile $destcore"
3429             set found 1
3430         }
3431     }
3432     if { $found == 0 } {
3433         # The braindamaged HPUX shell quits after the ulimit -c above
3434         # without executing ${binfile}.  So we try again without the
3435         # ulimit here if we didn't find a core file above.
3436         # Oh, I should mention that any "braindamaged" non-Unix system has
3437         # the same problem. I like the cd bit too, it's really neat'n stuff.
3438         catch "system \"(cd ${objdir}/${subdir}; ${binfile}; true) >/dev/null 2>&1\""
3439         foreach i "${objdir}/${subdir}/core ${objdir}/${subdir}/core.coremaker.c ${binfile}.core" {
3440             if [remote_file build exists $i] {
3441                 remote_exec build "mv $i $destcore"
3442                 set found 1
3443             }
3444         }
3445     }
3446
3447     # Try to clean up after ourselves. 
3448     foreach deletefile $deletefiles {
3449         remote_file build delete [file join $coredir $deletefile]
3450     }
3451     remote_exec build "rmdir $coredir"
3452         
3453     if { $found == 0  } {
3454         warning "can't generate a core file - core tests suppressed - check ulimit -c"
3455         return ""
3456     }
3457     return $destcore
3458 }