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