88dfdafb6545258f5d74c2384b56400ff5e0626d
[binutils-gdb.git] / gdb / testsuite / lib / gdb.exp
1 # Copyright 1992-2023 Free Software Foundation, Inc.
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 3 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15
16 # This file was written by Fred Fish. (fnf@cygnus.com)
17
18 # Generic gdb subroutines that should work for any target. If these
19 # need to be modified for any target, it can be done with a variable
20 # or by passing arguments.
21
22 if {$tool == ""} {
23 # Tests would fail, logs on get_compiler_info() would be missing.
24 send_error "`site.exp' not found, run `make site.exp'!\n"
25 exit 2
26 }
27
28 # Execute BODY, if COND wrapped in proc WRAP.
29 # Instead of writing the verbose and repetitive:
30 # if { $cond } {
31 # wrap $body
32 # } else {
33 # $body
34 # }
35 # we can use instead:
36 # cond_wrap $cond wrap $body
37
38 proc cond_wrap { cond wrap body } {
39 if { $cond } {
40 $wrap {
41 uplevel 1 $body
42 }
43 } else {
44 uplevel 1 $body
45 }
46 }
47
48 # Add VAR_ID=VAL to ENV_VAR, unless ENV_VAR already contains a VAR_ID setting.
49
50 proc set_sanitizer_default { env_var var_id val } {
51 global env
52
53 if { ![info exists env($env_var) ]
54 || $env($env_var) == "" } {
55 # Set var_id (env_var non-existing / empty case).
56 append env($env_var) $var_id=$val
57 return
58 }
59
60 if { [regexp $var_id= $env($env_var)] } {
61 # Don't set var_id. It's already set by the user, leave as is.
62 # Note that we could probably get the same result by unconditionally
63 # prepending it, but this way is less likely to cause confusion.
64 return
65 }
66
67 # Set var_id (env_var not empty case).
68 append env($env_var) : $var_id=$val
69 }
70
71 set_sanitizer_default TSAN_OPTIONS suppressions \
72 $srcdir/../tsan-suppressions.txt
73
74 # If GDB is built with ASAN (and because there are leaks), it will output a
75 # leak report when exiting as well as exit with a non-zero (failure) status.
76 # This can affect tests that are sensitive to what GDB prints on stderr or its
77 # exit status. Add `detect_leaks=0` to the ASAN_OPTIONS environment variable
78 # (which will affect any spawned sub-process) to avoid this.
79 set_sanitizer_default ASAN_OPTIONS detect_leaks 0
80
81 # List of procs to run in gdb_finish.
82 set gdb_finish_hooks [list]
83
84 # Variable in which we keep track of globals that are allowed to be live
85 # across test-cases.
86 array set gdb_persistent_globals {}
87
88 # Mark variable names in ARG as a persistent global, and declare them as
89 # global in the calling context. Can be used to rewrite "global var_a var_b"
90 # into "gdb_persistent_global var_a var_b".
91 proc gdb_persistent_global { args } {
92 global gdb_persistent_globals
93 foreach varname $args {
94 uplevel 1 global $varname
95 set gdb_persistent_globals($varname) 1
96 }
97 }
98
99 # Mark variable names in ARG as a persistent global.
100 proc gdb_persistent_global_no_decl { args } {
101 global gdb_persistent_globals
102 foreach varname $args {
103 set gdb_persistent_globals($varname) 1
104 }
105 }
106
107 # Override proc load_lib.
108 rename load_lib saved_load_lib
109 # Run the runtest version of load_lib, and mark all variables that were
110 # created by this call as persistent.
111 proc load_lib { file } {
112 array set known_global {}
113 foreach varname [info globals] {
114 set known_globals($varname) 1
115 }
116
117 set code [catch "saved_load_lib $file" result]
118
119 foreach varname [info globals] {
120 if { ![info exists known_globals($varname)] } {
121 gdb_persistent_global_no_decl $varname
122 }
123 }
124
125 if {$code == 1} {
126 global errorInfo errorCode
127 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
128 } elseif {$code > 1} {
129 return -code $code $result
130 }
131
132 return $result
133 }
134
135 load_lib libgloss.exp
136 load_lib cache.exp
137 load_lib gdb-utils.exp
138 load_lib memory.exp
139 load_lib check-test-names.exp
140
141 # The path to the GDB binary to test.
142 global GDB
143
144 # The data directory to use for testing. If this is the empty string,
145 # then we let GDB use its own configured data directory.
146 global GDB_DATA_DIRECTORY
147
148 # The spawn ID used for I/O interaction with the inferior. For native
149 # targets, or remote targets that can do I/O through GDB
150 # (semi-hosting) this will be the same as the host/GDB's spawn ID.
151 # Otherwise, the board may set this to some other spawn ID. E.g.,
152 # when debugging with GDBserver, this is set to GDBserver's spawn ID,
153 # so input/output is done on gdbserver's tty.
154 global inferior_spawn_id
155
156 if [info exists TOOL_EXECUTABLE] {
157 set GDB $TOOL_EXECUTABLE
158 }
159 if ![info exists GDB] {
160 if ![is_remote host] {
161 set GDB [findfile $base_dir/../../gdb/gdb "$base_dir/../../gdb/gdb" [transform gdb]]
162 } else {
163 set GDB [transform gdb]
164 }
165 } else {
166 # If the user specifies GDB on the command line, and doesn't
167 # specify GDB_DATA_DIRECTORY, then assume we're testing an
168 # installed GDB, and let it use its own configured data directory.
169 if ![info exists GDB_DATA_DIRECTORY] {
170 set GDB_DATA_DIRECTORY ""
171 }
172 }
173 verbose "using GDB = $GDB" 2
174
175 # The data directory the testing GDB will use. By default, assume
176 # we're testing a non-installed GDB in the build directory. Users may
177 # also explictly override the -data-directory from the command line.
178 if ![info exists GDB_DATA_DIRECTORY] {
179 set GDB_DATA_DIRECTORY "[pwd]/../data-directory"
180 }
181 verbose "using GDB_DATA_DIRECTORY = $GDB_DATA_DIRECTORY" 2
182
183 # GDBFLAGS is available for the user to set on the command line.
184 # E.g. make check RUNTESTFLAGS=GDBFLAGS=mumble
185 # Testcases may use it to add additional flags, but they must:
186 # - append new flags, not overwrite
187 # - restore the original value when done
188 global GDBFLAGS
189 if ![info exists GDBFLAGS] {
190 set GDBFLAGS ""
191 }
192 verbose "using GDBFLAGS = $GDBFLAGS" 2
193
194 # Append the -data-directory option to pass to GDB to CMDLINE and
195 # return the resulting string. If GDB_DATA_DIRECTORY is empty,
196 # nothing is appended.
197 proc append_gdb_data_directory_option {cmdline} {
198 global GDB_DATA_DIRECTORY
199
200 if { $GDB_DATA_DIRECTORY != "" } {
201 return "$cmdline -data-directory $GDB_DATA_DIRECTORY"
202 } else {
203 return $cmdline
204 }
205 }
206
207 # INTERNAL_GDBFLAGS contains flags that the testsuite requires.
208 # `-nw' disables any of the windowed interfaces.
209 # `-nx' disables ~/.gdbinit, so that it doesn't interfere with the tests.
210 # `-iex "set {height,width} 0"' disables pagination.
211 # `-data-directory' points to the data directory, usually in the build
212 # directory.
213 global INTERNAL_GDBFLAGS
214 if ![info exists INTERNAL_GDBFLAGS] {
215 set INTERNAL_GDBFLAGS \
216 [join [list \
217 "-nw" \
218 "-nx" \
219 {-iex "set height 0"} \
220 {-iex "set width 0"}]]
221
222 set INTERNAL_GDBFLAGS [append_gdb_data_directory_option $INTERNAL_GDBFLAGS]
223 }
224
225 # The variable gdb_prompt is a regexp which matches the gdb prompt.
226 # Set it if it is not already set. This is also set by default_gdb_init
227 # but it's not clear what removing one of them will break.
228 # See with_gdb_prompt for more details on prompt handling.
229 global gdb_prompt
230 if {![info exists gdb_prompt]} {
231 set gdb_prompt "\\(gdb\\)"
232 }
233
234 # A regexp that matches the pagination prompt.
235 set pagination_prompt \
236 "--Type <RET> for more, q to quit, c to continue without paging--"
237
238 # The variable fullname_syntax_POSIX is a regexp which matches a POSIX
239 # absolute path ie. /foo/
240 set fullname_syntax_POSIX {/[^\n]*/}
241 # The variable fullname_syntax_UNC is a regexp which matches a Windows
242 # UNC path ie. \\D\foo\
243 set fullname_syntax_UNC {\\\\[^\\]+\\[^\n]+\\}
244 # The variable fullname_syntax_DOS_CASE is a regexp which matches a
245 # particular DOS case that GDB most likely will output
246 # ie. \foo\, but don't match \\.*\
247 set fullname_syntax_DOS_CASE {\\[^\\][^\n]*\\}
248 # The variable fullname_syntax_DOS is a regexp which matches a DOS path
249 # ie. a:\foo\ && a:foo\
250 set fullname_syntax_DOS {[a-zA-Z]:[^\n]*\\}
251 # The variable fullname_syntax is a regexp which matches what GDB considers
252 # an absolute path. It is currently debatable if the Windows style paths
253 # d:foo and \abc should be considered valid as an absolute path.
254 # Also, the purpse of this regexp is not to recognize a well formed
255 # absolute path, but to say with certainty that a path is absolute.
256 set fullname_syntax "($fullname_syntax_POSIX|$fullname_syntax_UNC|$fullname_syntax_DOS_CASE|$fullname_syntax_DOS)"
257
258 # Needed for some tests under Cygwin.
259 global EXEEXT
260 global env
261
262 if ![info exists env(EXEEXT)] {
263 set EXEEXT ""
264 } else {
265 set EXEEXT $env(EXEEXT)
266 }
267
268 set octal "\[0-7\]+"
269
270 set inferior_exited_re "(?:\\\[Inferior \[0-9\]+ \\(\[^\n\r\]*\\) exited)"
271
272 # A regular expression that matches a value history number.
273 # E.g., $1, $2, etc.
274 set valnum_re "\\\$$decimal"
275
276 # A regular expression that matches a breakpoint hit with a breakpoint
277 # having several code locations.
278 set bkptno_num_re "$decimal\\.$decimal"
279
280 # A regular expression that matches a breakpoint hit
281 # with one or several code locations.
282 set bkptno_numopt_re "($decimal\\.$decimal|$decimal)"
283
284 ### Only procedures should come after this point.
285
286 #
287 # gdb_version -- extract and print the version number of GDB
288 #
289 proc default_gdb_version {} {
290 global GDB
291 global INTERNAL_GDBFLAGS GDBFLAGS
292 global gdb_prompt
293 global inotify_pid
294
295 if {[info exists inotify_pid]} {
296 eval exec kill $inotify_pid
297 }
298
299 set output [remote_exec host "$GDB $INTERNAL_GDBFLAGS --version"]
300 set tmp [lindex $output 1]
301 set version ""
302 regexp " \[0-9\]\[^ \t\n\r\]+" "$tmp" version
303 if ![is_remote host] {
304 clone_output "[which $GDB] version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
305 } else {
306 clone_output "$GDB on remote host version $version $INTERNAL_GDBFLAGS $GDBFLAGS\n"
307 }
308 }
309
310 proc gdb_version { } {
311 return [default_gdb_version]
312 }
313
314 # gdb_unload -- unload a file if one is loaded
315 #
316 # Returns the same as gdb_test_multiple.
317
318 proc gdb_unload { {msg "file"} } {
319 global GDB
320 global gdb_prompt
321 return [gdb_test_multiple "file" $msg {
322 -re "A program is being debugged already.\r\nAre you sure you want to change the file. .y or n. $" {
323 send_gdb "y\n" answer
324 exp_continue
325 }
326
327 -re "No executable file now\\.\r\n" {
328 exp_continue
329 }
330
331 -re "Discard symbol table from `.*'. .y or n. $" {
332 send_gdb "y\n" answer
333 exp_continue
334 }
335
336 -re -wrap "No symbol file now\\." {
337 pass $gdb_test_name
338 }
339 }]
340 }
341
342 # Many of the tests depend on setting breakpoints at various places and
343 # running until that breakpoint is reached. At times, we want to start
344 # with a clean-slate with respect to breakpoints, so this utility proc
345 # lets us do this without duplicating this code everywhere.
346 #
347
348 proc delete_breakpoints {} {
349 global gdb_prompt
350
351 # we need a larger timeout value here or this thing just confuses
352 # itself. May need a better implementation if possible. - guo
353 #
354 set timeout 100
355
356 set msg "delete all breakpoints in delete_breakpoints"
357 set deleted 0
358 gdb_test_multiple "delete breakpoints" "$msg" {
359 -re "Delete all breakpoints.*y or n.*$" {
360 send_gdb "y\n" answer
361 exp_continue
362 }
363 -re "$gdb_prompt $" {
364 set deleted 1
365 }
366 }
367
368 if {$deleted} {
369 # Confirm with "info breakpoints".
370 set deleted 0
371 set msg "info breakpoints"
372 gdb_test_multiple $msg $msg {
373 -re "No breakpoints or watchpoints..*$gdb_prompt $" {
374 set deleted 1
375 }
376 -re "$gdb_prompt $" {
377 }
378 }
379 }
380
381 if {!$deleted} {
382 perror "breakpoints not deleted"
383 }
384 }
385
386 # Returns true iff the target supports using the "run" command.
387
388 proc target_can_use_run_cmd {} {
389 if [target_info exists use_gdb_stub] {
390 # In this case, when we connect, the inferior is already
391 # running.
392 return 0
393 }
394
395 # Assume yes.
396 return 1
397 }
398
399 # Generic run command.
400 #
401 # Return 0 if we could start the program, -1 if we could not.
402 #
403 # The second pattern below matches up to the first newline *only*.
404 # Using ``.*$'' could swallow up output that we attempt to match
405 # elsewhere.
406 #
407 # INFERIOR_ARGS is passed as arguments to the start command, so may contain
408 # inferior arguments.
409 #
410 # N.B. This function does not wait for gdb to return to the prompt,
411 # that is the caller's responsibility.
412
413 proc gdb_run_cmd { {inferior_args {}} } {
414 global gdb_prompt use_gdb_stub
415
416 foreach command [gdb_init_commands] {
417 send_gdb "$command\n"
418 gdb_expect 30 {
419 -re "$gdb_prompt $" { }
420 default {
421 perror "gdb_init_command for target failed"
422 return
423 }
424 }
425 }
426
427 if $use_gdb_stub {
428 if [target_info exists gdb,do_reload_on_run] {
429 if { [gdb_reload $inferior_args] != 0 } {
430 return -1
431 }
432 send_gdb "continue\n"
433 gdb_expect 60 {
434 -re "Continu\[^\r\n\]*\[\r\n\]" {}
435 default {}
436 }
437 return 0
438 }
439
440 if [target_info exists gdb,start_symbol] {
441 set start [target_info gdb,start_symbol]
442 } else {
443 set start "start"
444 }
445 send_gdb "jump *$start\n"
446 set start_attempt 1
447 while { $start_attempt } {
448 # Cap (re)start attempts at three to ensure that this loop
449 # always eventually fails. Don't worry about trying to be
450 # clever and not send a command when it has failed.
451 if [expr $start_attempt > 3] {
452 perror "Jump to start() failed (retry count exceeded)"
453 return -1
454 }
455 set start_attempt [expr $start_attempt + 1]
456 gdb_expect 30 {
457 -re "Continuing at \[^\r\n\]*\[\r\n\]" {
458 set start_attempt 0
459 }
460 -re "No symbol \"_start\" in current.*$gdb_prompt $" {
461 perror "Can't find start symbol to run in gdb_run"
462 return -1
463 }
464 -re "No symbol \"start\" in current.*$gdb_prompt $" {
465 send_gdb "jump *_start\n"
466 }
467 -re "No symbol.*context.*$gdb_prompt $" {
468 set start_attempt 0
469 }
470 -re "Line.* Jump anyway.*y or n. $" {
471 send_gdb "y\n" answer
472 }
473 -re "The program is not being run.*$gdb_prompt $" {
474 if { [gdb_reload $inferior_args] != 0 } {
475 return -1
476 }
477 send_gdb "jump *$start\n"
478 }
479 timeout {
480 perror "Jump to start() failed (timeout)"
481 return -1
482 }
483 }
484 }
485
486 return 0
487 }
488
489 if [target_info exists gdb,do_reload_on_run] {
490 if { [gdb_reload $inferior_args] != 0 } {
491 return -1
492 }
493 }
494 send_gdb "run $inferior_args\n"
495 # This doesn't work quite right yet.
496 # Use -notransfer here so that test cases (like chng-sym.exp)
497 # may test for additional start-up messages.
498 gdb_expect 60 {
499 -re "The program .* has been started already.*y or n. $" {
500 send_gdb "y\n" answer
501 exp_continue
502 }
503 -notransfer -re "Starting program: \[^\r\n\]*" {}
504 -notransfer -re "$gdb_prompt $" {
505 # There is no more input expected.
506 }
507 -notransfer -re "A problem internal to GDB has been detected" {
508 # Let caller handle this.
509 }
510 }
511
512 return 0
513 }
514
515 # Generic start command. Return 0 if we could start the program, -1
516 # if we could not.
517 #
518 # INFERIOR_ARGS is passed as arguments to the start command, so may contain
519 # inferior arguments.
520 #
521 # N.B. This function does not wait for gdb to return to the prompt,
522 # that is the caller's responsibility.
523
524 proc gdb_start_cmd { {inferior_args {}} } {
525 global gdb_prompt use_gdb_stub
526
527 foreach command [gdb_init_commands] {
528 send_gdb "$command\n"
529 gdb_expect 30 {
530 -re "$gdb_prompt $" { }
531 default {
532 perror "gdb_init_command for target failed"
533 return -1
534 }
535 }
536 }
537
538 if $use_gdb_stub {
539 return -1
540 }
541
542 send_gdb "start $inferior_args\n"
543 # Use -notransfer here so that test cases (like chng-sym.exp)
544 # may test for additional start-up messages.
545 gdb_expect 60 {
546 -re "The program .* has been started already.*y or n. $" {
547 send_gdb "y\n" answer
548 exp_continue
549 }
550 -notransfer -re "Starting program: \[^\r\n\]*" {
551 return 0
552 }
553 -re "$gdb_prompt $" { }
554 }
555 return -1
556 }
557
558 # Generic starti command. Return 0 if we could start the program, -1
559 # if we could not.
560 #
561 # INFERIOR_ARGS is passed as arguments to the starti command, so may contain
562 # inferior arguments.
563 #
564 # N.B. This function does not wait for gdb to return to the prompt,
565 # that is the caller's responsibility.
566
567 proc gdb_starti_cmd { {inferior_args {}} } {
568 global gdb_prompt use_gdb_stub
569
570 foreach command [gdb_init_commands] {
571 send_gdb "$command\n"
572 gdb_expect 30 {
573 -re "$gdb_prompt $" { }
574 default {
575 perror "gdb_init_command for target failed"
576 return -1
577 }
578 }
579 }
580
581 if $use_gdb_stub {
582 return -1
583 }
584
585 send_gdb "starti $inferior_args\n"
586 gdb_expect 60 {
587 -re "The program .* has been started already.*y or n. $" {
588 send_gdb "y\n" answer
589 exp_continue
590 }
591 -re "Starting program: \[^\r\n\]*" {
592 return 0
593 }
594 }
595 return -1
596 }
597
598 # Set a breakpoint using LINESPEC.
599 #
600 # If there is an additional argument it is a list of options; the supported
601 # options are allow-pending, temporary, message, no-message and qualified.
602 #
603 # The result is 1 for success, 0 for failure.
604 #
605 # Note: The handling of message vs no-message is messed up, but it's based
606 # on historical usage. By default this function does not print passes,
607 # only fails.
608 # no-message: turns off printing of fails (and passes, but they're already off)
609 # message: turns on printing of passes (and fails, but they're already on)
610
611 proc gdb_breakpoint { linespec args } {
612 global gdb_prompt
613 global decimal
614
615 set pending_response n
616 if {[lsearch -exact $args allow-pending] != -1} {
617 set pending_response y
618 }
619
620 set break_command "break"
621 set break_message "Breakpoint"
622 if {[lsearch -exact $args temporary] != -1} {
623 set break_command "tbreak"
624 set break_message "Temporary breakpoint"
625 }
626
627 if {[lsearch -exact $args qualified] != -1} {
628 append break_command " -qualified"
629 }
630
631 set print_pass 0
632 set print_fail 1
633 set no_message_loc [lsearch -exact $args no-message]
634 set message_loc [lsearch -exact $args message]
635 # The last one to appear in args wins.
636 if { $no_message_loc > $message_loc } {
637 set print_fail 0
638 } elseif { $message_loc > $no_message_loc } {
639 set print_pass 1
640 }
641
642 set test_name "gdb_breakpoint: set breakpoint at $linespec"
643 # The first two regexps are what we get with -g, the third is without -g.
644 gdb_test_multiple "$break_command $linespec" $test_name {
645 -re "$break_message \[0-9\]* at .*: file .*, line $decimal.\r\n$gdb_prompt $" {}
646 -re "$break_message \[0-9\]*: file .*, line $decimal.\r\n$gdb_prompt $" {}
647 -re "$break_message \[0-9\]* at .*$gdb_prompt $" {}
648 -re "$break_message \[0-9\]* \\(.*\\) pending.*$gdb_prompt $" {
649 if {$pending_response == "n"} {
650 if { $print_fail } {
651 fail $gdb_name_name
652 }
653 return 0
654 }
655 }
656 -re "Make breakpoint pending.*y or \\\[n\\\]. $" {
657 send_gdb "$pending_response\n"
658 exp_continue
659 }
660 -re "$gdb_prompt $" {
661 if { $print_fail } {
662 fail $test_name
663 }
664 return 0
665 }
666 }
667 if { $print_pass } {
668 pass $test_name
669 }
670 return 1
671 }
672
673 # Set breakpoint at function and run gdb until it breaks there.
674 # Since this is the only breakpoint that will be set, if it stops
675 # at a breakpoint, we will assume it is the one we want. We can't
676 # just compare to "function" because it might be a fully qualified,
677 # single quoted C++ function specifier.
678 #
679 # If there are additional arguments, pass them to gdb_breakpoint.
680 # We recognize no-message/message ourselves.
681 #
682 # no-message is messed up here, like gdb_breakpoint: to preserve
683 # historical usage fails are always printed by default.
684 # no-message: turns off printing of fails (and passes, but they're already off)
685 # message: turns on printing of passes (and fails, but they're already on)
686
687 proc runto { linespec args } {
688 global gdb_prompt
689 global bkptno_numopt_re
690 global decimal
691
692 delete_breakpoints
693
694 set print_pass 0
695 set print_fail 1
696 set no_message_loc [lsearch -exact $args no-message]
697 set message_loc [lsearch -exact $args message]
698 # The last one to appear in args wins.
699 if { $no_message_loc > $message_loc } {
700 set print_fail 0
701 } elseif { $message_loc > $no_message_loc } {
702 set print_pass 1
703 }
704
705 set test_name "runto: run to $linespec"
706
707 # We need to use eval here to pass our varargs args to gdb_breakpoint
708 # which is also a varargs function.
709 # But we also have to be careful because $linespec may have multiple
710 # elements, and we don't want Tcl to move the remaining elements after
711 # the first to $args. That is why $linespec is wrapped in {}.
712 if ![eval gdb_breakpoint {$linespec} $args] {
713 return 0
714 }
715
716 gdb_run_cmd
717
718 # the "at foo.c:36" output we get with -g.
719 # the "in func" output we get without -g.
720 gdb_expect 30 {
721 -re "(?:Break|Temporary break).* at .*:$decimal.*$gdb_prompt $" {
722 if { $print_pass } {
723 pass $test_name
724 }
725 return 1
726 }
727 -re "(?:Breakpoint|Temporary breakpoint) $bkptno_numopt_re, \[0-9xa-f\]* in .*$gdb_prompt $" {
728 if { $print_pass } {
729 pass $test_name
730 }
731 return 1
732 }
733 -re "The target does not support running in non-stop mode.\r\n$gdb_prompt $" {
734 if { $print_fail } {
735 unsupported "non-stop mode not supported"
736 }
737 return 0
738 }
739 -re ".*A problem internal to GDB has been detected" {
740 # Always emit a FAIL if we encounter an internal error: internal
741 # errors are never expected.
742 fail "$test_name (GDB internal error)"
743 gdb_internal_error_resync
744 return 0
745 }
746 -re "$gdb_prompt $" {
747 if { $print_fail } {
748 fail $test_name
749 }
750 return 0
751 }
752 eof {
753 if { $print_fail } {
754 fail "$test_name (eof)"
755 }
756 return 0
757 }
758 timeout {
759 if { $print_fail } {
760 fail "$test_name (timeout)"
761 }
762 return 0
763 }
764 }
765 if { $print_pass } {
766 pass $test_name
767 }
768 return 1
769 }
770
771 # Ask gdb to run until we hit a breakpoint at main.
772 #
773 # N.B. This function deletes all existing breakpoints.
774 # If you don't want that, use gdb_start_cmd.
775
776 proc runto_main { } {
777 return [runto main qualified]
778 }
779
780 ### Continue, and expect to hit a breakpoint.
781 ### Report a pass or fail, depending on whether it seems to have
782 ### worked. Use NAME as part of the test name; each call to
783 ### continue_to_breakpoint should use a NAME which is unique within
784 ### that test file.
785 proc gdb_continue_to_breakpoint {name {location_pattern .*}} {
786 global gdb_prompt
787 set full_name "continue to breakpoint: $name"
788
789 set kfail_pattern "Process record does not support instruction 0xfae64 at.*"
790 gdb_test_multiple "continue" $full_name {
791 -re "(?:Breakpoint|Temporary breakpoint) .* (at|in) $location_pattern\r\n$gdb_prompt $" {
792 pass $full_name
793 }
794 -re "\[\r\n\]*(?:$kfail_pattern)\[\r\n\]+$gdb_prompt $" {
795 kfail "gdb/25038" $full_name
796 }
797 }
798 }
799
800
801 # gdb_internal_error_resync:
802 #
803 # Answer the questions GDB asks after it reports an internal error
804 # until we get back to a GDB prompt. Decline to quit the debugging
805 # session, and decline to create a core file. Return non-zero if the
806 # resync succeeds.
807 #
808 # This procedure just answers whatever questions come up until it sees
809 # a GDB prompt; it doesn't require you to have matched the input up to
810 # any specific point. However, it only answers questions it sees in
811 # the output itself, so if you've matched a question, you had better
812 # answer it yourself before calling this.
813 #
814 # You can use this function thus:
815 #
816 # gdb_expect {
817 # ...
818 # -re ".*A problem internal to GDB has been detected" {
819 # gdb_internal_error_resync
820 # }
821 # ...
822 # }
823 #
824 proc gdb_internal_error_resync {} {
825 global gdb_prompt
826
827 verbose -log "Resyncing due to internal error."
828
829 set count 0
830 while {$count < 10} {
831 gdb_expect {
832 -re "Recursive internal problem\\." {
833 perror "Could not resync from internal error (recursive internal problem)"
834 return 0
835 }
836 -re "Quit this debugging session\\? \\(y or n\\) $" {
837 send_gdb "n\n" answer
838 incr count
839 }
840 -re "Create a core file of GDB\\? \\(y or n\\) $" {
841 send_gdb "n\n" answer
842 incr count
843 }
844 -re "$gdb_prompt $" {
845 # We're resynchronized.
846 return 1
847 }
848 timeout {
849 perror "Could not resync from internal error (timeout)"
850 return 0
851 }
852 eof {
853 perror "Could not resync from internal error (eof)"
854 return 0
855 }
856 }
857 }
858 perror "Could not resync from internal error (resync count exceeded)"
859 return 0
860 }
861
862 # Fill in the default prompt if PROMPT_REGEXP is empty.
863 #
864 # If WITH_ANCHOR is true and the default prompt is used, append a `$` at the end
865 # of the regexp, to anchor the match at the end of the buffer.
866 proc fill_in_default_prompt {prompt_regexp with_anchor} {
867 if { "$prompt_regexp" == "" } {
868 set prompt "$::gdb_prompt "
869
870 if { $with_anchor } {
871 append prompt "$"
872 }
873
874 return $prompt
875 }
876 return $prompt_regexp
877 }
878
879 # gdb_test_multiple COMMAND MESSAGE [ -prompt PROMPT_REGEXP] [ -lbl ]
880 # EXPECT_ARGUMENTS
881 # Send a command to gdb; test the result.
882 #
883 # COMMAND is the command to execute, send to GDB with send_gdb. If
884 # this is the null string no command is sent.
885 # MESSAGE is a message to be printed with the built-in failure patterns
886 # if one of them matches. If MESSAGE is empty COMMAND will be used.
887 # -prompt PROMPT_REGEXP specifies a regexp matching the expected prompt
888 # after the command output. If empty, defaults to "$gdb_prompt $".
889 # -lbl specifies that line-by-line matching will be used.
890 # EXPECT_ARGUMENTS will be fed to expect in addition to the standard
891 # patterns. Pattern elements will be evaluated in the caller's
892 # context; action elements will be executed in the caller's context.
893 # Unlike patterns for gdb_test, these patterns should generally include
894 # the final newline and prompt.
895 #
896 # Returns:
897 # 1 if the test failed, according to a built-in failure pattern
898 # 0 if only user-supplied patterns matched
899 # -1 if there was an internal error.
900 #
901 # You can use this function thus:
902 #
903 # gdb_test_multiple "print foo" "test foo" {
904 # -re "expected output 1" {
905 # pass "test foo"
906 # }
907 # -re "expected output 2" {
908 # fail "test foo"
909 # }
910 # }
911 #
912 # Within action elements you can also make use of the variable
913 # gdb_test_name. This variable is setup automatically by
914 # gdb_test_multiple, and contains the value of MESSAGE. You can then
915 # write this, which is equivalent to the above:
916 #
917 # gdb_test_multiple "print foo" "test foo" {
918 # -re "expected output 1" {
919 # pass $gdb_test_name
920 # }
921 # -re "expected output 2" {
922 # fail $gdb_test_name
923 # }
924 # }
925 #
926 # Like with "expect", you can also specify the spawn id to match with
927 # -i "$id". Interesting spawn ids are $inferior_spawn_id and
928 # $gdb_spawn_id. The former matches inferior I/O, while the latter
929 # matches GDB I/O. E.g.:
930 #
931 # send_inferior "hello\n"
932 # gdb_test_multiple "continue" "test echo" {
933 # -i "$inferior_spawn_id" -re "^hello\r\nhello\r\n$" {
934 # pass "got echo"
935 # }
936 # -i "$gdb_spawn_id" -re "Breakpoint.*$gdb_prompt $" {
937 # fail "hit breakpoint"
938 # }
939 # }
940 #
941 # The standard patterns, such as "Inferior exited..." and "A problem
942 # ...", all being implicitly appended to that list. These are always
943 # expected from $gdb_spawn_id. IOW, callers do not need to worry
944 # about resetting "-i" back to $gdb_spawn_id explicitly.
945 #
946 # In EXPECT_ARGUMENTS we can use a -wrap pattern flag, that wraps the regexp
947 # pattern as gdb_test wraps its message argument.
948 # This allows us to rewrite:
949 # gdb_test <command> <pattern> <message>
950 # into:
951 # gdb_test_multiple <command> <message> {
952 # -re -wrap <pattern> {
953 # pass $gdb_test_name
954 # }
955 # }
956 #
957 # In EXPECT_ARGUMENTS, a pattern flag -early can be used. It makes sure the
958 # pattern is inserted before any implicit pattern added by gdb_test_multiple.
959 # Using this pattern flag, we can f.i. setup a kfail for an assertion failure
960 # <assert> during gdb_continue_to_breakpoint by the rewrite:
961 # gdb_continue_to_breakpoint <msg> <pattern>
962 # into:
963 # set breakpoint_pattern "(?:Breakpoint|Temporary breakpoint) .* (at|in)"
964 # gdb_test_multiple "continue" "continue to breakpoint: <msg>" {
965 # -early -re "internal-error: <assert>" {
966 # setup_kfail gdb/nnnnn "*-*-*"
967 # exp_continue
968 # }
969 # -re "$breakpoint_pattern <pattern>\r\n$gdb_prompt $" {
970 # pass $gdb_test_name
971 # }
972 # }
973 #
974 proc gdb_test_multiple { command message args } {
975 global verbose use_gdb_stub
976 global gdb_prompt pagination_prompt
977 global GDB
978 global gdb_spawn_id
979 global inferior_exited_re
980 upvar timeout timeout
981 upvar expect_out expect_out
982 global any_spawn_id
983
984 set line_by_line 0
985 set prompt_regexp ""
986 for {set i 0} {$i < [llength $args]} {incr i} {
987 set arg [lindex $args $i]
988 if { $arg == "-prompt" } {
989 incr i
990 set prompt_regexp [lindex $args $i]
991 } elseif { $arg == "-lbl" } {
992 set line_by_line 1
993 } else {
994 set user_code $arg
995 break
996 }
997 }
998 if { [expr $i + 1] < [llength $args] } {
999 error "Too many arguments to gdb_test_multiple"
1000 } elseif { ![info exists user_code] } {
1001 error "Too few arguments to gdb_test_multiple"
1002 }
1003
1004 set prompt_regexp [fill_in_default_prompt $prompt_regexp true]
1005
1006 if { $message == "" } {
1007 set message $command
1008 }
1009
1010 if [string match "*\[\r\n\]" $command] {
1011 error "Invalid trailing newline in \"$command\" command"
1012 }
1013
1014 if [string match "*\[\003\004\]" $command] {
1015 error "Invalid trailing control code in \"$command\" command"
1016 }
1017
1018 if [string match "*\[\r\n\]*" $message] {
1019 error "Invalid newline in \"$message\" test"
1020 }
1021
1022 if {$use_gdb_stub
1023 && [regexp -nocase {^\s*(r|run|star|start|at|att|atta|attac|attach)\M} \
1024 $command]} {
1025 error "gdbserver does not support $command without extended-remote"
1026 }
1027
1028 # TCL/EXPECT WART ALERT
1029 # Expect does something very strange when it receives a single braced
1030 # argument. It splits it along word separators and performs substitutions.
1031 # This means that { "[ab]" } is evaluated as "[ab]", but { "\[ab\]" } is
1032 # evaluated as "\[ab\]". But that's not how TCL normally works; inside a
1033 # double-quoted list item, "\[ab\]" is just a long way of representing
1034 # "[ab]", because the backslashes will be removed by lindex.
1035
1036 # Unfortunately, there appears to be no easy way to duplicate the splitting
1037 # that expect will do from within TCL. And many places make use of the
1038 # "\[0-9\]" construct, so we need to support that; and some places make use
1039 # of the "[func]" construct, so we need to support that too. In order to
1040 # get this right we have to substitute quoted list elements differently
1041 # from braced list elements.
1042
1043 # We do this roughly the same way that Expect does it. We have to use two
1044 # lists, because if we leave unquoted newlines in the argument to uplevel
1045 # they'll be treated as command separators, and if we escape newlines
1046 # we mangle newlines inside of command blocks. This assumes that the
1047 # input doesn't contain a pattern which contains actual embedded newlines
1048 # at this point!
1049
1050 regsub -all {\n} ${user_code} { } subst_code
1051 set subst_code [uplevel list $subst_code]
1052
1053 set processed_code ""
1054 set early_processed_code ""
1055 # The variable current_list holds the name of the currently processed
1056 # list, either processed_code or early_processed_code.
1057 set current_list "processed_code"
1058 set patterns ""
1059 set expecting_action 0
1060 set expecting_arg 0
1061 set wrap_pattern 0
1062 foreach item $user_code subst_item $subst_code {
1063 if { $item == "-n" || $item == "-notransfer" || $item == "-nocase" } {
1064 lappend $current_list $item
1065 continue
1066 }
1067 if { $item == "-indices" || $item == "-re" || $item == "-ex" } {
1068 lappend $current_list $item
1069 continue
1070 }
1071 if { $item == "-early" } {
1072 set current_list "early_processed_code"
1073 continue
1074 }
1075 if { $item == "-timeout" || $item == "-i" } {
1076 set expecting_arg 1
1077 lappend $current_list $item
1078 continue
1079 }
1080 if { $item == "-wrap" } {
1081 set wrap_pattern 1
1082 continue
1083 }
1084 if { $expecting_arg } {
1085 set expecting_arg 0
1086 lappend $current_list $subst_item
1087 continue
1088 }
1089 if { $expecting_action } {
1090 lappend $current_list "uplevel [list $item]"
1091 set expecting_action 0
1092 # Cosmetic, no effect on the list.
1093 append $current_list "\n"
1094 # End the effect of -early, it only applies to one action.
1095 set current_list "processed_code"
1096 continue
1097 }
1098 set expecting_action 1
1099 if { $wrap_pattern } {
1100 # Wrap subst_item as is done for the gdb_test PATTERN argument.
1101 lappend $current_list \
1102 "\[\r\n\]*(?:$subst_item)\[\r\n\]+$gdb_prompt $"
1103 set wrap_pattern 0
1104 } else {
1105 lappend $current_list $subst_item
1106 }
1107 if {$patterns != ""} {
1108 append patterns "; "
1109 }
1110 append patterns "\"$subst_item\""
1111 }
1112
1113 # Also purely cosmetic.
1114 regsub -all {\r} $patterns {\\r} patterns
1115 regsub -all {\n} $patterns {\\n} patterns
1116
1117 if {$verbose > 2} {
1118 send_user "Sending \"$command\" to gdb\n"
1119 send_user "Looking to match \"$patterns\"\n"
1120 send_user "Message is \"$message\"\n"
1121 }
1122
1123 set result -1
1124 set string "${command}\n"
1125 if { $command != "" } {
1126 set multi_line_re "\[\r\n\] *>"
1127 while { "$string" != "" } {
1128 set foo [string first "\n" "$string"]
1129 set len [string length "$string"]
1130 if { $foo < [expr $len - 1] } {
1131 set str [string range "$string" 0 $foo]
1132 if { [send_gdb "$str"] != "" } {
1133 verbose -log "Couldn't send $command to GDB."
1134 unresolved $message
1135 return -1
1136 }
1137 # since we're checking if each line of the multi-line
1138 # command are 'accepted' by GDB here,
1139 # we need to set -notransfer expect option so that
1140 # command output is not lost for pattern matching
1141 # - guo
1142 gdb_expect 2 {
1143 -notransfer -re "$multi_line_re$" { verbose "partial: match" 3 }
1144 timeout { verbose "partial: timeout" 3 }
1145 }
1146 set string [string range "$string" [expr $foo + 1] end]
1147 set multi_line_re "$multi_line_re.*\[\r\n\] *>"
1148 } else {
1149 break
1150 }
1151 }
1152 if { "$string" != "" } {
1153 if { [send_gdb "$string"] != "" } {
1154 verbose -log "Couldn't send $command to GDB."
1155 unresolved $message
1156 return -1
1157 }
1158 }
1159 }
1160
1161 set code $early_processed_code
1162 append code {
1163 -re ".*A problem internal to GDB has been detected" {
1164 fail "$message (GDB internal error)"
1165 gdb_internal_error_resync
1166 set result -1
1167 }
1168 -re "\\*\\*\\* DOSEXIT code.*" {
1169 if { $message != "" } {
1170 fail "$message"
1171 }
1172 set result -1
1173 }
1174 -re "Corrupted shared library list.*$prompt_regexp" {
1175 fail "$message (shared library list corrupted)"
1176 set result -1
1177 }
1178 -re "Invalid cast\.\r\nwarning: Probes-based dynamic linker interface failed.*$prompt_regexp" {
1179 fail "$message (probes interface failure)"
1180 set result -1
1181 }
1182 }
1183 append code $processed_code
1184
1185 # Reset the spawn id, in case the processed code used -i.
1186 append code {
1187 -i "$gdb_spawn_id"
1188 }
1189
1190 append code {
1191 -re "Ending remote debugging.*$prompt_regexp" {
1192 if {![isnative]} {
1193 warning "Can`t communicate to remote target."
1194 }
1195 gdb_exit
1196 gdb_start
1197 set result -1
1198 }
1199 -re "Undefined\[a-z\]* command:.*$prompt_regexp" {
1200 perror "Undefined command \"$command\"."
1201 fail "$message"
1202 set result 1
1203 }
1204 -re "Ambiguous command.*$prompt_regexp" {
1205 perror "\"$command\" is not a unique command name."
1206 fail "$message"
1207 set result 1
1208 }
1209 -re "$inferior_exited_re with code \[0-9\]+.*$prompt_regexp" {
1210 if {![string match "" $message]} {
1211 set errmsg "$message (the program exited)"
1212 } else {
1213 set errmsg "$command (the program exited)"
1214 }
1215 fail "$errmsg"
1216 set result -1
1217 }
1218 -re "$inferior_exited_re normally.*$prompt_regexp" {
1219 if {![string match "" $message]} {
1220 set errmsg "$message (the program exited)"
1221 } else {
1222 set errmsg "$command (the program exited)"
1223 }
1224 fail "$errmsg"
1225 set result -1
1226 }
1227 -re "The program is not being run.*$prompt_regexp" {
1228 if {![string match "" $message]} {
1229 set errmsg "$message (the program is no longer running)"
1230 } else {
1231 set errmsg "$command (the program is no longer running)"
1232 }
1233 fail "$errmsg"
1234 set result -1
1235 }
1236 -re "\r\n$prompt_regexp" {
1237 if {![string match "" $message]} {
1238 fail "$message"
1239 }
1240 set result 1
1241 }
1242 -re "$pagination_prompt" {
1243 send_gdb "\n"
1244 perror "Window too small."
1245 fail "$message"
1246 set result -1
1247 }
1248 -re "\\((y or n|y or \\\[n\\\]|\\\[y\\\] or n)\\) " {
1249 send_gdb "n\n" answer
1250 gdb_expect -re "$prompt_regexp"
1251 fail "$message (got interactive prompt)"
1252 set result -1
1253 }
1254 -re "\\\[0\\\] cancel\r\n\\\[1\\\] all.*\r\n> $" {
1255 send_gdb "0\n"
1256 gdb_expect -re "$prompt_regexp"
1257 fail "$message (got breakpoint menu)"
1258 set result -1
1259 }
1260
1261 -i $gdb_spawn_id
1262 eof {
1263 perror "GDB process no longer exists"
1264 set wait_status [wait -i $gdb_spawn_id]
1265 verbose -log "GDB process exited with wait status $wait_status"
1266 if { $message != "" } {
1267 fail "$message"
1268 }
1269 return -1
1270 }
1271 }
1272
1273 if {$line_by_line} {
1274 append code {
1275 -re "\r\n\[^\r\n\]*(?=\r\n)" {
1276 exp_continue
1277 }
1278 }
1279 }
1280
1281 # Now patterns that apply to any spawn id specified.
1282 append code {
1283 -i $any_spawn_id
1284 eof {
1285 perror "Process no longer exists"
1286 if { $message != "" } {
1287 fail "$message"
1288 }
1289 return -1
1290 }
1291 full_buffer {
1292 perror "internal buffer is full."
1293 fail "$message"
1294 set result -1
1295 }
1296 timeout {
1297 if {![string match "" $message]} {
1298 fail "$message (timeout)"
1299 }
1300 set result 1
1301 }
1302 }
1303
1304 # remote_expect calls the eof section if there is an error on the
1305 # expect call. We already have eof sections above, and we don't
1306 # want them to get called in that situation. Since the last eof
1307 # section becomes the error section, here we define another eof
1308 # section, but with an empty spawn_id list, so that it won't ever
1309 # match.
1310 append code {
1311 -i "" eof {
1312 # This comment is here because the eof section must not be
1313 # the empty string, otherwise remote_expect won't realize
1314 # it exists.
1315 }
1316 }
1317
1318 # Create gdb_test_name in the parent scope. If this variable
1319 # already exists, which it might if we have nested calls to
1320 # gdb_test_multiple, then preserve the old value, otherwise,
1321 # create a new variable in the parent scope.
1322 upvar gdb_test_name gdb_test_name
1323 if { [info exists gdb_test_name] } {
1324 set gdb_test_name_old "$gdb_test_name"
1325 }
1326 set gdb_test_name "$message"
1327
1328 set result 0
1329 set code [catch {gdb_expect $code} string]
1330
1331 # Clean up the gdb_test_name variable. If we had a
1332 # previous value then restore it, otherwise, delete the variable
1333 # from the parent scope.
1334 if { [info exists gdb_test_name_old] } {
1335 set gdb_test_name "$gdb_test_name_old"
1336 } else {
1337 unset gdb_test_name
1338 }
1339
1340 if {$code == 1} {
1341 global errorInfo errorCode
1342 return -code error -errorinfo $errorInfo -errorcode $errorCode $string
1343 } elseif {$code > 1} {
1344 return -code $code $string
1345 }
1346 return $result
1347 }
1348
1349 # Usage: gdb_test_multiline NAME INPUT RESULT {INPUT RESULT} ...
1350 # Run a test named NAME, consisting of multiple lines of input.
1351 # After each input line INPUT, search for result line RESULT.
1352 # Succeed if all results are seen; fail otherwise.
1353
1354 proc gdb_test_multiline { name args } {
1355 global gdb_prompt
1356 set inputnr 0
1357 foreach {input result} $args {
1358 incr inputnr
1359 if {[gdb_test_multiple $input "$name: input $inputnr: $input" {
1360 -re "\[\r\n\]*($result)\[\r\n\]+($gdb_prompt | *>)$" {
1361 pass $gdb_test_name
1362 }
1363 }]} {
1364 return 1
1365 }
1366 }
1367 return 0
1368 }
1369
1370
1371 # gdb_test [-prompt PROMPT_REGEXP] [-lbl]
1372 # COMMAND [PATTERN] [MESSAGE] [QUESTION RESPONSE]
1373 # Send a command to gdb; test the result.
1374 #
1375 # COMMAND is the command to execute, send to GDB with send_gdb. If
1376 # this is the null string no command is sent.
1377 # PATTERN is the pattern to match for a PASS, and must NOT include
1378 # the \r\n sequence immediately before the gdb prompt. This argument
1379 # may be omitted to just match the prompt, ignoring whatever output
1380 # precedes it.
1381 # MESSAGE is an optional message to be printed. If this is
1382 # omitted, then the pass/fail messages use the command string as the
1383 # message. (If this is the empty string, then sometimes we don't
1384 # call pass or fail at all; I don't understand this at all.)
1385 # QUESTION is a question GDB should ask in response to COMMAND, like
1386 # "are you sure?" If this is specified, the test fails if GDB
1387 # doesn't print the question.
1388 # RESPONSE is the response to send when QUESTION appears.
1389 #
1390 # -prompt PROMPT_REGEXP specifies a regexp matching the expected prompt
1391 # after the command output. If empty, defaults to "$gdb_prompt $".
1392 # -no-prompt-anchor specifies that if the default prompt regexp is used, it
1393 # should not be anchored at the end of the buffer. This means that the
1394 # pattern can match even if there is stuff output after the prompt. Does not
1395 # have any effect if -prompt is specified.
1396 # -lbl specifies that line-by-line matching will be used.
1397 # -nopass specifies that a PASS should not be issued.
1398 #
1399 # Returns:
1400 # 1 if the test failed,
1401 # 0 if the test passes,
1402 # -1 if there was an internal error.
1403 #
1404 proc gdb_test { args } {
1405 global gdb_prompt
1406 upvar timeout timeout
1407
1408 parse_args {
1409 {prompt ""}
1410 {no-prompt-anchor}
1411 {lbl}
1412 {nopass}
1413 }
1414
1415 lassign $args command pattern message question response
1416
1417 # Can't have a question without a response.
1418 if { $question != "" && $response == "" || [llength $args] > 5 } {
1419 error "Unexpected arguments: $args"
1420 }
1421
1422 if { $message == "" } {
1423 set message $command
1424 }
1425
1426 set prompt [fill_in_default_prompt $prompt [expr !${no-prompt-anchor}]]
1427
1428 set saw_question 0
1429
1430 set user_code {}
1431 lappend user_code {
1432 -re "\[\r\n\]*(?:$pattern)\[\r\n\]+$prompt" {
1433 if { $question != "" & !$saw_question} {
1434 fail $message
1435 } elseif {!$nopass} {
1436 pass $message
1437 }
1438 }
1439 }
1440
1441 if { $question != "" } {
1442 lappend user_code {
1443 -re "$question$" {
1444 set saw_question 1
1445 send_gdb "$response\n"
1446 exp_continue
1447 }
1448 }
1449 }
1450
1451 set user_code [join $user_code]
1452
1453 set opts {}
1454 lappend opts "-prompt" "$prompt"
1455 if {$lbl} {
1456 lappend opts "-lbl"
1457 }
1458
1459 return [gdb_test_multiple $command $message {*}$opts $user_code]
1460 }
1461
1462 # Return 1 if version MAJOR.MINOR is at least AT_LEAST_MAJOR.AT_LEAST_MINOR.
1463 proc version_at_least { major minor at_least_major at_least_minor} {
1464 if { $major > $at_least_major } {
1465 return 1
1466 } elseif { $major == $at_least_major \
1467 && $minor >= $at_least_minor } {
1468 return 1
1469 } else {
1470 return 0
1471 }
1472 }
1473
1474 # Return 1 if tcl version used is at least MAJOR.MINOR
1475 proc tcl_version_at_least { major minor } {
1476 global tcl_version
1477 regexp {^([0-9]+)\.([0-9]+)$} $tcl_version \
1478 dummy tcl_version_major tcl_version_minor
1479 return [version_at_least $tcl_version_major $tcl_version_minor \
1480 $major $minor]
1481 }
1482
1483 if { [tcl_version_at_least 8 5] == 0 } {
1484 # lrepeat was added in tcl 8.5. Only add if missing.
1485 proc lrepeat { n element } {
1486 if { [string is integer -strict $n] == 0 } {
1487 error "expected integer but got \"$n\""
1488 }
1489 if { $n < 0 } {
1490 error "bad count \"$n\": must be integer >= 0"
1491 }
1492 set res [list]
1493 for {set i 0} {$i < $n} {incr i} {
1494 lappend res $element
1495 }
1496 return $res
1497 }
1498 }
1499
1500 # gdb_test_no_output [-prompt PROMPT_REGEXP] [-nopass] COMMAND [MESSAGE]
1501 # Send a command to GDB and verify that this command generated no output.
1502 #
1503 # See gdb_test for a description of the -prompt, -no-prompt-anchor, -nopass,
1504 # COMMAND, and MESSAGE parameters.
1505
1506 proc gdb_test_no_output { args } {
1507 global gdb_prompt
1508
1509 parse_args {
1510 {prompt ""}
1511 {no-prompt-anchor}
1512 {nopass}
1513 }
1514
1515 lassign $args command message
1516
1517 set prompt [fill_in_default_prompt $prompt [expr !${no-prompt-anchor}]]
1518
1519 set command_regex [string_to_regexp $command]
1520 gdb_test_multiple $command $message -prompt $prompt {
1521 -re "^$command_regex\r\n$prompt" {
1522 if {!$nopass} {
1523 pass $gdb_test_name
1524 }
1525 }
1526 }
1527 }
1528
1529 # Send a command and then wait for a sequence of outputs.
1530 # This is useful when the sequence is long and contains ".*", a single
1531 # regexp to match the entire output can get a timeout much easier.
1532 #
1533 # COMMAND is the command to execute, send to GDB with send_gdb. If
1534 # this is the null string no command is sent.
1535 # TEST_NAME is passed to pass/fail. COMMAND is used if TEST_NAME is "".
1536 # EXPECTED_OUTPUT_LIST is a list of regexps of expected output, which are
1537 # processed in order, and all must be present in the output.
1538 #
1539 # The -prompt switch can be used to override the prompt expected at the end of
1540 # the output sequence.
1541 #
1542 # It is unnecessary to specify ".*" at the beginning or end of any regexp,
1543 # there is an implicit ".*" between each element of EXPECTED_OUTPUT_LIST.
1544 # There is also an implicit ".*" between the last regexp and the gdb prompt.
1545 #
1546 # Like gdb_test and gdb_test_multiple, the output is expected to end with the
1547 # gdb prompt, which must not be specified in EXPECTED_OUTPUT_LIST.
1548 #
1549 # Returns:
1550 # 1 if the test failed,
1551 # 0 if the test passes,
1552 # -1 if there was an internal error.
1553
1554 proc gdb_test_sequence { args } {
1555 global gdb_prompt
1556
1557 parse_args {{prompt ""}}
1558
1559 if { $prompt == "" } {
1560 set prompt "$gdb_prompt $"
1561 }
1562
1563 if { [llength $args] != 3 } {
1564 error "Unexpected # of arguments, expecting: COMMAND TEST_NAME EXPECTED_OUTPUT_LIST"
1565 }
1566
1567 lassign $args command test_name expected_output_list
1568
1569 if { $test_name == "" } {
1570 set test_name $command
1571 }
1572
1573 lappend expected_output_list ""; # implicit ".*" before gdb prompt
1574
1575 if { $command != "" } {
1576 send_gdb "$command\n"
1577 }
1578
1579 return [gdb_expect_list $test_name $prompt $expected_output_list]
1580 }
1581
1582 \f
1583 # Match output of COMMAND using RE. Read output line-by-line.
1584 # Report pass/fail with MESSAGE.
1585 # For a command foo with output:
1586 # (gdb) foo^M
1587 # <line1>^M
1588 # <line2>^M
1589 # (gdb)
1590 # the portion matched using RE is:
1591 # '<line1>^M
1592 # <line2>^M
1593 # '
1594 #
1595 # Optionally, additional -re-not <regexp> arguments can be specified, to
1596 # ensure that a regexp is not match by the COMMAND output.
1597 # Such an additional argument generates an additional PASS/FAIL of the form:
1598 # PASS: test-case.exp: $message: pattern not matched: <regexp>
1599
1600 proc gdb_test_lines { command message re args } {
1601 set re_not [list]
1602
1603 for {set i 0} {$i < [llength $args]} {incr i} {
1604 set arg [lindex $args $i]
1605 if { $arg == "-re-not" } {
1606 incr i
1607 if { [llength $args] == $i } {
1608 error "Missing argument for -re-not"
1609 break
1610 }
1611 set arg [lindex $args $i]
1612 lappend re_not $arg
1613 } else {
1614 error "Unhandled argument: $arg"
1615 }
1616 }
1617
1618 if { $message == ""} {
1619 set message $command
1620 }
1621
1622 set lines ""
1623 gdb_test_multiple $command $message {
1624 -re "\r\n(\[^\r\n\]*)(?=\r\n)" {
1625 set line $expect_out(1,string)
1626 if { $lines eq "" } {
1627 append lines "$line"
1628 } else {
1629 append lines "\r\n$line"
1630 }
1631 exp_continue
1632 }
1633 -re -wrap "" {
1634 append lines "\r\n"
1635 }
1636 }
1637
1638 gdb_assert { [regexp $re $lines] } $message
1639
1640 foreach re $re_not {
1641 gdb_assert { ![regexp $re $lines] } "$message: pattern not matched: $re"
1642 }
1643 }
1644
1645 # Test that a command gives an error. For pass or fail, return
1646 # a 1 to indicate that more tests can proceed. However a timeout
1647 # is a serious error, generates a special fail message, and causes
1648 # a 0 to be returned to indicate that more tests are likely to fail
1649 # as well.
1650
1651 proc test_print_reject { args } {
1652 global gdb_prompt
1653 global verbose
1654
1655 if {[llength $args] == 2} {
1656 set expectthis [lindex $args 1]
1657 } else {
1658 set expectthis "should never match this bogus string"
1659 }
1660 set sendthis [lindex $args 0]
1661 if {$verbose > 2} {
1662 send_user "Sending \"$sendthis\" to gdb\n"
1663 send_user "Looking to match \"$expectthis\"\n"
1664 }
1665 send_gdb "$sendthis\n"
1666 #FIXME: Should add timeout as parameter.
1667 gdb_expect {
1668 -re "A .* in expression.*\\.*$gdb_prompt $" {
1669 pass "reject $sendthis"
1670 return 1
1671 }
1672 -re "Invalid syntax in expression.*$gdb_prompt $" {
1673 pass "reject $sendthis"
1674 return 1
1675 }
1676 -re "Junk after end of expression.*$gdb_prompt $" {
1677 pass "reject $sendthis"
1678 return 1
1679 }
1680 -re "Invalid number.*$gdb_prompt $" {
1681 pass "reject $sendthis"
1682 return 1
1683 }
1684 -re "Invalid character constant.*$gdb_prompt $" {
1685 pass "reject $sendthis"
1686 return 1
1687 }
1688 -re "No symbol table is loaded.*$gdb_prompt $" {
1689 pass "reject $sendthis"
1690 return 1
1691 }
1692 -re "No symbol .* in current context.*$gdb_prompt $" {
1693 pass "reject $sendthis"
1694 return 1
1695 }
1696 -re "Unmatched single quote.*$gdb_prompt $" {
1697 pass "reject $sendthis"
1698 return 1
1699 }
1700 -re "A character constant must contain at least one character.*$gdb_prompt $" {
1701 pass "reject $sendthis"
1702 return 1
1703 }
1704 -re "$expectthis.*$gdb_prompt $" {
1705 pass "reject $sendthis"
1706 return 1
1707 }
1708 -re ".*$gdb_prompt $" {
1709 fail "reject $sendthis"
1710 return 1
1711 }
1712 default {
1713 fail "reject $sendthis (eof or timeout)"
1714 return 0
1715 }
1716 }
1717 }
1718 \f
1719
1720 # Same as gdb_test, but the second parameter is not a regexp,
1721 # but a string that must match exactly.
1722
1723 proc gdb_test_exact { args } {
1724 upvar timeout timeout
1725
1726 set command [lindex $args 0]
1727
1728 # This applies a special meaning to a null string pattern. Without
1729 # this, "$pattern\r\n$gdb_prompt $" will match anything, including error
1730 # messages from commands that should have no output except a new
1731 # prompt. With this, only results of a null string will match a null
1732 # string pattern.
1733
1734 set pattern [lindex $args 1]
1735 if [string match $pattern ""] {
1736 set pattern [string_to_regexp [lindex $args 0]]
1737 } else {
1738 set pattern [string_to_regexp [lindex $args 1]]
1739 }
1740
1741 # It is most natural to write the pattern argument with only
1742 # embedded \n's, especially if you are trying to avoid Tcl quoting
1743 # problems. But gdb_expect really wants to see \r\n in patterns. So
1744 # transform the pattern here. First transform \r\n back to \n, in
1745 # case some users of gdb_test_exact already do the right thing.
1746 regsub -all "\r\n" $pattern "\n" pattern
1747 regsub -all "\n" $pattern "\r\n" pattern
1748 if {[llength $args] == 3} {
1749 set message [lindex $args 2]
1750 return [gdb_test $command $pattern $message]
1751 }
1752
1753 return [gdb_test $command $pattern]
1754 }
1755
1756 # Wrapper around gdb_test_multiple that looks for a list of expected
1757 # output elements, but which can appear in any order.
1758 # CMD is the gdb command.
1759 # NAME is the name of the test.
1760 # ELM_FIND_REGEXP specifies how to partition the output into elements to
1761 # compare.
1762 # ELM_EXTRACT_REGEXP specifies the part of ELM_FIND_REGEXP to compare.
1763 # RESULT_MATCH_LIST is a list of exact matches for each expected element.
1764 # All elements of RESULT_MATCH_LIST must appear for the test to pass.
1765 #
1766 # A typical use of ELM_FIND_REGEXP/ELM_EXTRACT_REGEXP is to extract one line
1767 # of text per element and then strip trailing \r\n's.
1768 # Example:
1769 # gdb_test_list_exact "foo" "bar" \
1770 # "\[^\r\n\]+\[\r\n\]+" \
1771 # "\[^\r\n\]+" \
1772 # { \
1773 # {expected result 1} \
1774 # {expected result 2} \
1775 # }
1776
1777 proc gdb_test_list_exact { cmd name elm_find_regexp elm_extract_regexp result_match_list } {
1778 global gdb_prompt
1779
1780 set matches [lsort $result_match_list]
1781 set seen {}
1782 gdb_test_multiple $cmd $name {
1783 "$cmd\[\r\n\]" { exp_continue }
1784 -re $elm_find_regexp {
1785 set str $expect_out(0,string)
1786 verbose -log "seen: $str" 3
1787 regexp -- $elm_extract_regexp $str elm_seen
1788 verbose -log "extracted: $elm_seen" 3
1789 lappend seen $elm_seen
1790 exp_continue
1791 }
1792 -re "$gdb_prompt $" {
1793 set failed ""
1794 foreach got [lsort $seen] have $matches {
1795 if {![string equal $got $have]} {
1796 set failed $have
1797 break
1798 }
1799 }
1800 if {[string length $failed] != 0} {
1801 fail "$name ($failed not found)"
1802 } else {
1803 pass $name
1804 }
1805 }
1806 }
1807 }
1808
1809 # gdb_test_stdio COMMAND INFERIOR_PATTERN GDB_PATTERN MESSAGE
1810 # Send a command to gdb; expect inferior and gdb output.
1811 #
1812 # See gdb_test_multiple for a description of the COMMAND and MESSAGE
1813 # parameters.
1814 #
1815 # INFERIOR_PATTERN is the pattern to match against inferior output.
1816 #
1817 # GDB_PATTERN is the pattern to match against gdb output, and must NOT
1818 # include the \r\n sequence immediately before the gdb prompt, nor the
1819 # prompt. The default is empty.
1820 #
1821 # Both inferior and gdb patterns must match for a PASS.
1822 #
1823 # If MESSAGE is ommitted, then COMMAND will be used as the message.
1824 #
1825 # Returns:
1826 # 1 if the test failed,
1827 # 0 if the test passes,
1828 # -1 if there was an internal error.
1829 #
1830
1831 proc gdb_test_stdio {command inferior_pattern {gdb_pattern ""} {message ""}} {
1832 global inferior_spawn_id gdb_spawn_id
1833 global gdb_prompt
1834
1835 if {$message == ""} {
1836 set message $command
1837 }
1838
1839 set inferior_matched 0
1840 set gdb_matched 0
1841
1842 # Use an indirect spawn id list, and remove the inferior spawn id
1843 # from the expected output as soon as it matches, in case
1844 # $inferior_pattern happens to be a prefix of the resulting full
1845 # gdb pattern below (e.g., "\r\n").
1846 global gdb_test_stdio_spawn_id_list
1847 set gdb_test_stdio_spawn_id_list "$inferior_spawn_id"
1848
1849 # Note that if $inferior_spawn_id and $gdb_spawn_id are different,
1850 # then we may see gdb's output arriving before the inferior's
1851 # output.
1852 set res [gdb_test_multiple $command $message {
1853 -i gdb_test_stdio_spawn_id_list -re "$inferior_pattern" {
1854 set inferior_matched 1
1855 if {!$gdb_matched} {
1856 set gdb_test_stdio_spawn_id_list ""
1857 exp_continue
1858 }
1859 }
1860 -i $gdb_spawn_id -re "$gdb_pattern\r\n$gdb_prompt $" {
1861 set gdb_matched 1
1862 if {!$inferior_matched} {
1863 exp_continue
1864 }
1865 }
1866 }]
1867 if {$res == 0} {
1868 pass $message
1869 } else {
1870 verbose -log "inferior_matched=$inferior_matched, gdb_matched=$gdb_matched"
1871 }
1872 return $res
1873 }
1874
1875 # Wrapper around gdb_test_multiple to be used when testing expression
1876 # evaluation while 'set debug expression 1' is in effect.
1877 # Looks for some patterns that indicates the expression was rejected.
1878 #
1879 # CMD is the command to execute, which should include an expression
1880 # that GDB will need to parse.
1881 #
1882 # OUTPUT is the expected output pattern.
1883 #
1884 # TESTNAME is the name to be used for the test, defaults to CMD if not
1885 # given.
1886 proc gdb_test_debug_expr { cmd output {testname "" }} {
1887 global gdb_prompt
1888
1889 if { ${testname} == "" } {
1890 set testname $cmd
1891 }
1892
1893 gdb_test_multiple $cmd $testname {
1894 -re ".*Invalid expression.*\r\n$gdb_prompt $" {
1895 fail $gdb_test_name
1896 }
1897 -re ".*\[\r\n\]$output\r\n$gdb_prompt $" {
1898 pass $gdb_test_name
1899 }
1900 }
1901 }
1902
1903 # get_print_expr_at_depths EXP OUTPUTS
1904 #
1905 # Used for testing 'set print max-depth'. Prints the expression EXP
1906 # with 'set print max-depth' set to various depths. OUTPUTS is a list
1907 # of `n` different patterns to match at each of the depths from 0 to
1908 # (`n` - 1).
1909 #
1910 # This proc does one final check with the max-depth set to 'unlimited'
1911 # which is tested against the last pattern in the OUTPUTS list. The
1912 # OUTPUTS list is therefore required to match every depth from 0 to a
1913 # depth where the whole of EXP is printed with no ellipsis.
1914 #
1915 # This proc leaves the 'set print max-depth' set to 'unlimited'.
1916 proc gdb_print_expr_at_depths {exp outputs} {
1917 for { set depth 0 } { $depth <= [llength $outputs] } { incr depth } {
1918 if { $depth == [llength $outputs] } {
1919 set expected_result [lindex $outputs [expr [llength $outputs] - 1]]
1920 set depth_string "unlimited"
1921 } else {
1922 set expected_result [lindex $outputs $depth]
1923 set depth_string $depth
1924 }
1925
1926 with_test_prefix "exp='$exp': depth=${depth_string}" {
1927 gdb_test_no_output "set print max-depth ${depth_string}"
1928 gdb_test "p $exp" "$expected_result"
1929 }
1930 }
1931 }
1932
1933 \f
1934
1935 # Issue a PASS and return true if evaluating CONDITION in the caller's
1936 # frame returns true, and issue a FAIL and return false otherwise.
1937 # MESSAGE is the pass/fail message to be printed. If MESSAGE is
1938 # omitted or is empty, then the pass/fail messages use the condition
1939 # string as the message.
1940
1941 proc gdb_assert { condition {message ""} } {
1942 if { $message == ""} {
1943 set message $condition
1944 }
1945
1946 set code [catch {uplevel 1 expr $condition} res]
1947 if {$code == 1} {
1948 # If code is 1 (TCL_ERROR), it means evaluation failed and res contains
1949 # an error message. Print the error message, and set res to 0 since we
1950 # want to return a boolean.
1951 warning "While evaluating expression in gdb_assert: $res"
1952 unresolved $message
1953 set res 0
1954 } elseif { !$res } {
1955 fail $message
1956 } else {
1957 pass $message
1958 }
1959 return $res
1960 }
1961
1962 proc gdb_reinitialize_dir { subdir } {
1963 global gdb_prompt
1964
1965 if [is_remote host] {
1966 return ""
1967 }
1968 send_gdb "dir\n"
1969 gdb_expect 60 {
1970 -re "Reinitialize source path to empty.*y or n. " {
1971 send_gdb "y\n" answer
1972 gdb_expect 60 {
1973 -re "Source directories searched.*$gdb_prompt $" {
1974 send_gdb "dir $subdir\n"
1975 gdb_expect 60 {
1976 -re "Source directories searched.*$gdb_prompt $" {
1977 verbose "Dir set to $subdir"
1978 }
1979 -re "$gdb_prompt $" {
1980 perror "Dir \"$subdir\" failed."
1981 }
1982 }
1983 }
1984 -re "$gdb_prompt $" {
1985 perror "Dir \"$subdir\" failed."
1986 }
1987 }
1988 }
1989 -re "$gdb_prompt $" {
1990 perror "Dir \"$subdir\" failed."
1991 }
1992 }
1993 }
1994
1995 #
1996 # gdb_exit -- exit the GDB, killing the target program if necessary
1997 #
1998 proc default_gdb_exit {} {
1999 global GDB
2000 global INTERNAL_GDBFLAGS GDBFLAGS
2001 global gdb_spawn_id inferior_spawn_id
2002 global inotify_log_file
2003
2004 if ![info exists gdb_spawn_id] {
2005 return
2006 }
2007
2008 verbose "Quitting $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
2009
2010 if {[info exists inotify_log_file] && [file exists $inotify_log_file]} {
2011 set fd [open $inotify_log_file]
2012 set data [read -nonewline $fd]
2013 close $fd
2014
2015 if {[string compare $data ""] != 0} {
2016 warning "parallel-unsafe file creations noticed"
2017
2018 # Clear the log.
2019 set fd [open $inotify_log_file w]
2020 close $fd
2021 }
2022 }
2023
2024 if { [is_remote host] && [board_info host exists fileid] } {
2025 send_gdb "quit\n"
2026 gdb_expect 10 {
2027 -re "y or n" {
2028 send_gdb "y\n" answer
2029 exp_continue
2030 }
2031 -re "DOSEXIT code" { }
2032 default { }
2033 }
2034 }
2035
2036 if ![is_remote host] {
2037 remote_close host
2038 }
2039 unset gdb_spawn_id
2040 unset ::gdb_tty_name
2041 unset inferior_spawn_id
2042 }
2043
2044 # Load a file into the debugger.
2045 # The return value is 0 for success, -1 for failure.
2046 #
2047 # This procedure also set the global variable GDB_FILE_CMD_DEBUG_INFO
2048 # to one of these values:
2049 #
2050 # debug file was loaded successfully and has debug information
2051 # nodebug file was loaded successfully and has no debug information
2052 # lzma file was loaded, .gnu_debugdata found, but no LZMA support
2053 # compiled in
2054 # fail file was not loaded
2055 #
2056 # This procedure also set the global variable GDB_FILE_CMD_MSG to the
2057 # output of the file command in case of success.
2058 #
2059 # I tried returning this information as part of the return value,
2060 # but ran into a mess because of the many re-implementations of
2061 # gdb_load in config/*.exp.
2062 #
2063 # TODO: gdb.base/sepdebug.exp and gdb.stabs/weird.exp might be able to use
2064 # this if they can get more information set.
2065
2066 proc gdb_file_cmd { arg } {
2067 global gdb_prompt
2068 global GDB
2069 global last_loaded_file
2070
2071 # GCC for Windows target may create foo.exe given "-o foo".
2072 if { ![file exists $arg] && [file exists "$arg.exe"] } {
2073 set arg "$arg.exe"
2074 }
2075
2076 # Save this for the benefit of gdbserver-support.exp.
2077 set last_loaded_file $arg
2078
2079 # Set whether debug info was found.
2080 # Default to "fail".
2081 global gdb_file_cmd_debug_info gdb_file_cmd_msg
2082 set gdb_file_cmd_debug_info "fail"
2083
2084 if [is_remote host] {
2085 set arg [remote_download host $arg]
2086 if { $arg == "" } {
2087 perror "download failed"
2088 return -1
2089 }
2090 }
2091
2092 # The file command used to kill the remote target. For the benefit
2093 # of the testsuite, preserve this behavior. Mark as optional so it doesn't
2094 # get written to the stdin log.
2095 send_gdb "kill\n" optional
2096 gdb_expect 120 {
2097 -re "Kill the program being debugged. .y or n. $" {
2098 send_gdb "y\n" answer
2099 verbose "\t\tKilling previous program being debugged"
2100 exp_continue
2101 }
2102 -re "$gdb_prompt $" {
2103 # OK.
2104 }
2105 }
2106
2107 send_gdb "file $arg\n"
2108 set new_symbol_table 0
2109 set basename [file tail $arg]
2110 gdb_expect 120 {
2111 -re "(Reading symbols from.*LZMA support was disabled.*$gdb_prompt $)" {
2112 verbose "\t\tLoaded $arg into $GDB; .gnu_debugdata found but no LZMA available"
2113 set gdb_file_cmd_msg $expect_out(1,string)
2114 set gdb_file_cmd_debug_info "lzma"
2115 return 0
2116 }
2117 -re "(Reading symbols from.*No debugging symbols found.*$gdb_prompt $)" {
2118 verbose "\t\tLoaded $arg into $GDB with no debugging symbols"
2119 set gdb_file_cmd_msg $expect_out(1,string)
2120 set gdb_file_cmd_debug_info "nodebug"
2121 return 0
2122 }
2123 -re "(Reading symbols from.*$gdb_prompt $)" {
2124 verbose "\t\tLoaded $arg into $GDB"
2125 set gdb_file_cmd_msg $expect_out(1,string)
2126 set gdb_file_cmd_debug_info "debug"
2127 return 0
2128 }
2129 -re "Load new symbol table from \".*\".*y or n. $" {
2130 if { $new_symbol_table > 0 } {
2131 perror [join [list "Couldn't load $basename,"
2132 "interactive prompt loop detected."]]
2133 return -1
2134 }
2135 send_gdb "y\n" answer
2136 incr new_symbol_table
2137 set suffix "-- with new symbol table"
2138 set arg "$arg $suffix"
2139 set basename "$basename $suffix"
2140 exp_continue
2141 }
2142 -re "No such file or directory.*$gdb_prompt $" {
2143 perror "($basename) No such file or directory"
2144 return -1
2145 }
2146 -re "A problem internal to GDB has been detected" {
2147 perror "Couldn't load $basename into GDB (GDB internal error)."
2148 gdb_internal_error_resync
2149 return -1
2150 }
2151 -re "$gdb_prompt $" {
2152 perror "Couldn't load $basename into GDB."
2153 return -1
2154 }
2155 timeout {
2156 perror "Couldn't load $basename into GDB (timeout)."
2157 return -1
2158 }
2159 eof {
2160 # This is an attempt to detect a core dump, but seems not to
2161 # work. Perhaps we need to match .* followed by eof, in which
2162 # gdb_expect does not seem to have a way to do that.
2163 perror "Couldn't load $basename into GDB (eof)."
2164 return -1
2165 }
2166 }
2167 }
2168
2169 # The expect "spawn" function puts the tty name into the spawn_out
2170 # array; but dejagnu doesn't export this globally. So, we have to
2171 # wrap spawn with our own function and poke in the built-in spawn
2172 # so that we can capture this value.
2173 #
2174 # If available, the TTY name is saved to the LAST_SPAWN_TTY_NAME global.
2175 # Otherwise, LAST_SPAWN_TTY_NAME is unset.
2176
2177 proc spawn_capture_tty_name { args } {
2178 set result [uplevel builtin_spawn $args]
2179 upvar spawn_out spawn_out
2180 if { [info exists spawn_out(slave,name)] } {
2181 set ::last_spawn_tty_name $spawn_out(slave,name)
2182 } else {
2183 # If a process is spawned as part of a pipe line (e.g. passing
2184 # -leaveopen to the spawn proc) then the spawned process is no
2185 # assigned a tty and spawn_out(slave,name) will not be set.
2186 # In that case we want to ensure that last_spawn_tty_name is
2187 # not set.
2188 #
2189 # If the previous process spawned was also not assigned a tty
2190 # (e.g. multiple processed chained in a pipeline) then
2191 # last_spawn_tty_name will already be unset, so, if we don't
2192 # use -nocomplain here we would otherwise get an error.
2193 unset -nocomplain ::last_spawn_tty_name
2194 }
2195 return $result
2196 }
2197
2198 rename spawn builtin_spawn
2199 rename spawn_capture_tty_name spawn
2200
2201 # Default gdb_spawn procedure.
2202
2203 proc default_gdb_spawn { } {
2204 global use_gdb_stub
2205 global GDB
2206 global INTERNAL_GDBFLAGS GDBFLAGS
2207 global gdb_spawn_id
2208
2209 # Set the default value, it may be overriden later by specific testfile.
2210 #
2211 # Use `set_board_info use_gdb_stub' for the board file to flag the inferior
2212 # is already started after connecting and run/attach are not supported.
2213 # This is used for the "remote" protocol. After GDB starts you should
2214 # check global $use_gdb_stub instead of the board as the testfile may force
2215 # a specific different target protocol itself.
2216 set use_gdb_stub [target_info exists use_gdb_stub]
2217
2218 verbose "Spawning $GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
2219 gdb_write_cmd_file "$GDB $INTERNAL_GDBFLAGS $GDBFLAGS"
2220
2221 if [info exists gdb_spawn_id] {
2222 return 0
2223 }
2224
2225 if ![is_remote host] {
2226 if {[which $GDB] == 0} {
2227 perror "$GDB does not exist."
2228 exit 1
2229 }
2230 }
2231
2232 # Put GDBFLAGS last so that tests can put "--args ..." in it.
2233 set res [remote_spawn host "$GDB $INTERNAL_GDBFLAGS [host_info gdb_opts] $GDBFLAGS"]
2234 if { $res < 0 || $res == "" } {
2235 perror "Spawning $GDB failed."
2236 return 1
2237 }
2238
2239 set gdb_spawn_id $res
2240 set ::gdb_tty_name $::last_spawn_tty_name
2241 return 0
2242 }
2243
2244 # Default gdb_start procedure.
2245
2246 proc default_gdb_start { } {
2247 global gdb_prompt
2248 global gdb_spawn_id
2249 global inferior_spawn_id
2250
2251 if [info exists gdb_spawn_id] {
2252 return 0
2253 }
2254
2255 # Keep track of the number of times GDB has been launched.
2256 global gdb_instances
2257 incr gdb_instances
2258
2259 gdb_stdin_log_init
2260
2261 set res [gdb_spawn]
2262 if { $res != 0} {
2263 return $res
2264 }
2265
2266 # Default to assuming inferior I/O is done on GDB's terminal.
2267 if {![info exists inferior_spawn_id]} {
2268 set inferior_spawn_id $gdb_spawn_id
2269 }
2270
2271 # When running over NFS, particularly if running many simultaneous
2272 # tests on different hosts all using the same server, things can
2273 # get really slow. Give gdb at least 3 minutes to start up.
2274 gdb_expect 360 {
2275 -re "\[\r\n\]$gdb_prompt $" {
2276 verbose "GDB initialized."
2277 }
2278 -re "\[\r\n\]\033\\\[.2004h$gdb_prompt $" {
2279 # This special case detects what happens when GDB is
2280 # started with bracketed paste mode enabled. This mode is
2281 # usually forced off (see setting of INPUTRC in
2282 # default_gdb_init), but for at least one test we turn
2283 # bracketed paste mode back on, and then start GDB. In
2284 # that case, this case is hit.
2285 verbose "GDB initialized."
2286 }
2287 -re "$gdb_prompt $" {
2288 perror "GDB never initialized."
2289 unset gdb_spawn_id
2290 return -1
2291 }
2292 timeout {
2293 perror "(timeout) GDB never initialized after 10 seconds."
2294 remote_close host
2295 unset gdb_spawn_id
2296 return -1
2297 }
2298 eof {
2299 perror "(eof) GDB never initialized."
2300 unset gdb_spawn_id
2301 return -1
2302 }
2303 }
2304
2305 # force the height to "unlimited", so no pagers get used
2306
2307 send_gdb "set height 0\n"
2308 gdb_expect 10 {
2309 -re "$gdb_prompt $" {
2310 verbose "Setting height to 0." 2
2311 }
2312 timeout {
2313 warning "Couldn't set the height to 0"
2314 }
2315 }
2316 # force the width to "unlimited", so no wraparound occurs
2317 send_gdb "set width 0\n"
2318 gdb_expect 10 {
2319 -re "$gdb_prompt $" {
2320 verbose "Setting width to 0." 2
2321 }
2322 timeout {
2323 warning "Couldn't set the width to 0."
2324 }
2325 }
2326
2327 gdb_debug_init
2328 return 0
2329 }
2330
2331 # Utility procedure to give user control of the gdb prompt in a script. It is
2332 # meant to be used for debugging test cases, and should not be left in the
2333 # test cases code.
2334
2335 proc gdb_interact { } {
2336 global gdb_spawn_id
2337 set spawn_id $gdb_spawn_id
2338
2339 send_user "+------------------------------------------+\n"
2340 send_user "| Script interrupted, you can now interact |\n"
2341 send_user "| with by gdb. Type >>> to continue. |\n"
2342 send_user "+------------------------------------------+\n"
2343
2344 interact {
2345 ">>>" return
2346 }
2347 }
2348
2349 # Examine the output of compilation to determine whether compilation
2350 # failed or not. If it failed determine whether it is due to missing
2351 # compiler or due to compiler error. Report pass, fail or unsupported
2352 # as appropriate.
2353
2354 proc gdb_compile_test {src output} {
2355 set msg "compilation [file tail $src]"
2356
2357 if { $output == "" } {
2358 pass $msg
2359 return
2360 }
2361
2362 if { [regexp {^[a-zA-Z_0-9]+: Can't find [^ ]+\.$} $output]
2363 || [regexp {.*: command not found[\r|\n]*$} $output]
2364 || [regexp {.*: [^\r\n]*compiler not installed[^\r\n]*[\r|\n]*$} $output] } {
2365 unsupported "$msg (missing compiler)"
2366 return
2367 }
2368
2369 set gcc_re ".*: error: unrecognized command line option "
2370 set clang_re ".*: error: unsupported option "
2371 if { [regexp "(?:$gcc_re|$clang_re)(\[^ \t;\r\n\]*)" $output dummy option]
2372 && $option != "" } {
2373 unsupported "$msg (unsupported option $option)"
2374 return
2375 }
2376
2377 # Unclassified compilation failure, be more verbose.
2378 verbose -log "compilation failed: $output" 2
2379 fail "$msg"
2380 }
2381
2382 # Return a 1 for configurations for which we don't even want to try to
2383 # test C++.
2384
2385 proc skip_cplus_tests {} {
2386 if { [istarget "h8300-*-*"] } {
2387 return 1
2388 }
2389
2390 # The C++ IO streams are too large for HC11/HC12 and are thus not
2391 # available. The gdb C++ tests use them and don't compile.
2392 if { [istarget "m6811-*-*"] } {
2393 return 1
2394 }
2395 if { [istarget "m6812-*-*"] } {
2396 return 1
2397 }
2398 return 0
2399 }
2400
2401 # Return a 1 for configurations for which don't have both C++ and the STL.
2402
2403 proc skip_stl_tests {} {
2404 return [skip_cplus_tests]
2405 }
2406
2407 # Return a 1 if I don't even want to try to test FORTRAN.
2408
2409 proc skip_fortran_tests {} {
2410 return 0
2411 }
2412
2413 # Return a 1 if I don't even want to try to test ada.
2414
2415 proc skip_ada_tests {} {
2416 return 0
2417 }
2418
2419 # Return a 1 if I don't even want to try to test GO.
2420
2421 proc skip_go_tests {} {
2422 return 0
2423 }
2424
2425 # Return a 1 if I don't even want to try to test D.
2426
2427 proc skip_d_tests {} {
2428 return 0
2429 }
2430
2431 # Return 1 to skip Rust tests, 0 to try them.
2432 proc skip_rust_tests {} {
2433 if { ![isnative] } {
2434 return 1
2435 }
2436
2437 # The rust compiler does not support "-m32", skip.
2438 global board board_info
2439 set board [target_info name]
2440 if {[board_info $board exists multilib_flags]} {
2441 foreach flag [board_info $board multilib_flags] {
2442 if { $flag == "-m32" } {
2443 return 1
2444 }
2445 }
2446 }
2447
2448 return 0
2449 }
2450
2451 # Return a 1 for configurations that do not support Python scripting.
2452 # PROMPT_REGEXP is the expected prompt.
2453
2454 proc skip_python_tests_prompt { prompt_regexp } {
2455 gdb_test_multiple "python print ('test')" "verify python support" \
2456 -prompt "$prompt_regexp" {
2457 -re "not supported.*$prompt_regexp" {
2458 unsupported "Python support is disabled."
2459 return 1
2460 }
2461 -re "$prompt_regexp" {}
2462 }
2463
2464 return 0
2465 }
2466
2467 # Return a 1 for configurations that do not support Python scripting.
2468 # Note: This also sets various globals that specify which version of Python
2469 # is in use. See skip_python_tests_prompt.
2470
2471 proc skip_python_tests {} {
2472 global gdb_prompt
2473 return [skip_python_tests_prompt "$gdb_prompt $"]
2474 }
2475
2476 # Return a 1 if we should skip shared library tests.
2477
2478 proc skip_shlib_tests {} {
2479 # Run the shared library tests on native systems.
2480 if {[isnative]} {
2481 return 0
2482 }
2483
2484 # An abbreviated list of remote targets where we should be able to
2485 # run shared library tests.
2486 if {([istarget *-*-linux*]
2487 || [istarget *-*-*bsd*]
2488 || [istarget *-*-solaris2*]
2489 || [istarget *-*-mingw*]
2490 || [istarget *-*-cygwin*]
2491 || [istarget *-*-pe*])} {
2492 return 0
2493 }
2494
2495 return 1
2496 }
2497
2498 # Return 1 if we should skip dlmopen tests, 0 if we should not.
2499
2500 gdb_caching_proc skip_dlmopen_tests {
2501 global srcdir subdir gdb_prompt inferior_exited_re
2502
2503 # We need shared library support.
2504 if { [skip_shlib_tests] } {
2505 return 1
2506 }
2507
2508 set me "skip_dlmopen_tests"
2509 set lib {
2510 int foo (void) {
2511 return 42;
2512 }
2513 }
2514 set src {
2515 #define _GNU_SOURCE
2516 #include <dlfcn.h>
2517 #include <link.h>
2518 #include <stdio.h>
2519 #include <errno.h>
2520
2521 int main (void) {
2522 struct r_debug *r_debug;
2523 ElfW(Dyn) *dyn;
2524 void *handle;
2525
2526 /* The version is kept at 1 until we create a new namespace. */
2527 handle = dlmopen (LM_ID_NEWLM, DSO_NAME, RTLD_LAZY | RTLD_LOCAL);
2528 if (!handle) {
2529 printf ("dlmopen failed: %s.\n", dlerror ());
2530 return 1;
2531 }
2532
2533 r_debug = 0;
2534 /* Taken from /usr/include/link.h. */
2535 for (dyn = _DYNAMIC; dyn->d_tag != DT_NULL; ++dyn)
2536 if (dyn->d_tag == DT_DEBUG)
2537 r_debug = (struct r_debug *) dyn->d_un.d_ptr;
2538
2539 if (!r_debug) {
2540 printf ("r_debug not found.\n");
2541 return 1;
2542 }
2543 if (r_debug->r_version < 2) {
2544 printf ("dlmopen debug not supported.\n");
2545 return 1;
2546 }
2547 printf ("dlmopen debug supported.\n");
2548 return 0;
2549 }
2550 }
2551
2552 set libsrc [standard_temp_file "libfoo.c"]
2553 set libout [standard_temp_file "libfoo.so"]
2554 gdb_produce_source $libsrc $lib
2555
2556 if { [gdb_compile_shlib $libsrc $libout {debug}] != "" } {
2557 verbose -log "failed to build library"
2558 return 1
2559 }
2560 if { ![gdb_simple_compile $me $src executable \
2561 [list shlib_load debug \
2562 additional_flags=-DDSO_NAME=\"$libout\"]] } {
2563 verbose -log "failed to build executable"
2564 return 1
2565 }
2566
2567 gdb_exit
2568 gdb_start
2569 gdb_reinitialize_dir $srcdir/$subdir
2570 gdb_load $obj
2571
2572 if { [gdb_run_cmd] != 0 } {
2573 verbose -log "failed to start skip test"
2574 return 1
2575 }
2576 gdb_expect {
2577 -re "$inferior_exited_re normally.*${gdb_prompt} $" {
2578 set skip_dlmopen_tests 0
2579 }
2580 -re "$inferior_exited_re with code.*${gdb_prompt} $" {
2581 set skip_dlmopen_tests 1
2582 }
2583 default {
2584 warning "\n$me: default case taken"
2585 set skip_dlmopen_tests 1
2586 }
2587 }
2588 gdb_exit
2589
2590 verbose "$me: returning $skip_dlmopen_tests" 2
2591 return $skip_dlmopen_tests
2592 }
2593
2594 # Return 1 if we should skip tui related tests.
2595
2596 proc skip_tui_tests {} {
2597 global gdb_prompt
2598
2599 gdb_test_multiple "help layout" "verify tui support" {
2600 -re "Undefined command: \"layout\".*$gdb_prompt $" {
2601 return 1
2602 }
2603 -re "$gdb_prompt $" {
2604 }
2605 }
2606
2607 return 0
2608 }
2609
2610 # Test files shall make sure all the test result lines in gdb.sum are
2611 # unique in a test run, so that comparing the gdb.sum files of two
2612 # test runs gives correct results. Test files that exercise
2613 # variations of the same tests more than once, shall prefix the
2614 # different test invocations with different identifying strings in
2615 # order to make them unique.
2616 #
2617 # About test prefixes:
2618 #
2619 # $pf_prefix is the string that dejagnu prints after the result (FAIL,
2620 # PASS, etc.), and before the test message/name in gdb.sum. E.g., the
2621 # underlined substring in
2622 #
2623 # PASS: gdb.base/mytest.exp: some test
2624 # ^^^^^^^^^^^^^^^^^^^^
2625 #
2626 # is $pf_prefix.
2627 #
2628 # The easiest way to adjust the test prefix is to append a test
2629 # variation prefix to the $pf_prefix, using the with_test_prefix
2630 # procedure. E.g.,
2631 #
2632 # proc do_tests {} {
2633 # gdb_test ... ... "test foo"
2634 # gdb_test ... ... "test bar"
2635 #
2636 # with_test_prefix "subvariation a" {
2637 # gdb_test ... ... "test x"
2638 # }
2639 #
2640 # with_test_prefix "subvariation b" {
2641 # gdb_test ... ... "test x"
2642 # }
2643 # }
2644 #
2645 # with_test_prefix "variation1" {
2646 # ...do setup for variation 1...
2647 # do_tests
2648 # }
2649 #
2650 # with_test_prefix "variation2" {
2651 # ...do setup for variation 2...
2652 # do_tests
2653 # }
2654 #
2655 # Results in:
2656 #
2657 # PASS: gdb.base/mytest.exp: variation1: test foo
2658 # PASS: gdb.base/mytest.exp: variation1: test bar
2659 # PASS: gdb.base/mytest.exp: variation1: subvariation a: test x
2660 # PASS: gdb.base/mytest.exp: variation1: subvariation b: test x
2661 # PASS: gdb.base/mytest.exp: variation2: test foo
2662 # PASS: gdb.base/mytest.exp: variation2: test bar
2663 # PASS: gdb.base/mytest.exp: variation2: subvariation a: test x
2664 # PASS: gdb.base/mytest.exp: variation2: subvariation b: test x
2665 #
2666 # If for some reason more flexibility is necessary, one can also
2667 # manipulate the pf_prefix global directly, treating it as a string.
2668 # E.g.,
2669 #
2670 # global pf_prefix
2671 # set saved_pf_prefix
2672 # append pf_prefix "${foo}: bar"
2673 # ... actual tests ...
2674 # set pf_prefix $saved_pf_prefix
2675 #
2676
2677 # Run BODY in the context of the caller, with the current test prefix
2678 # (pf_prefix) appended with one space, then PREFIX, and then a colon.
2679 # Returns the result of BODY.
2680 #
2681 proc with_test_prefix { prefix body } {
2682 global pf_prefix
2683
2684 set saved $pf_prefix
2685 append pf_prefix " " $prefix ":"
2686 set code [catch {uplevel 1 $body} result]
2687 set pf_prefix $saved
2688
2689 if {$code == 1} {
2690 global errorInfo errorCode
2691 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2692 } else {
2693 return -code $code $result
2694 }
2695 }
2696
2697 # Wrapper for foreach that calls with_test_prefix on each iteration,
2698 # including the iterator's name and current value in the prefix.
2699
2700 proc foreach_with_prefix {var list body} {
2701 upvar 1 $var myvar
2702 foreach myvar $list {
2703 with_test_prefix "$var=$myvar" {
2704 set code [catch {uplevel 1 $body} result]
2705 }
2706
2707 if {$code == 1} {
2708 global errorInfo errorCode
2709 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2710 } elseif {$code == 3} {
2711 break
2712 } elseif {$code == 2} {
2713 return -code $code $result
2714 }
2715 }
2716 }
2717
2718 # Like TCL's native proc, but defines a procedure that wraps its body
2719 # within 'with_test_prefix "$proc_name" { ... }'.
2720 proc proc_with_prefix {name arguments body} {
2721 # Define the advertised proc.
2722 proc $name $arguments [list with_test_prefix $name $body]
2723 }
2724
2725 # Return an id corresponding to the test prefix stored in $pf_prefix, which
2726 # is more suitable for use in a file name.
2727 # F.i., for a pf_prefix:
2728 # gdb.dwarf2/dw2-lines.exp: \
2729 # cv=5: cdw=64: lv=5: ldw=64: string_form=line_strp:
2730 # return an id:
2731 # cv-5-cdw-32-lv-5-ldw-64-string_form-line_strp
2732
2733 proc prefix_id {} {
2734 global pf_prefix
2735 set id $pf_prefix
2736
2737 # Strip ".exp: " prefix.
2738 set id [regsub {.*\.exp: } $id {}]
2739
2740 # Strip colon suffix.
2741 set id [regsub {:$} $id {}]
2742
2743 # Strip spaces.
2744 set id [regsub -all { } $id {}]
2745
2746 # Replace colons, equal signs.
2747 set id [regsub -all \[:=\] $id -]
2748
2749 return $id
2750 }
2751
2752 # Run BODY in the context of the caller. After BODY is run, the variables
2753 # listed in VARS will be reset to the values they had before BODY was run.
2754 #
2755 # This is useful for providing a scope in which it is safe to temporarily
2756 # modify global variables, e.g.
2757 #
2758 # global INTERNAL_GDBFLAGS
2759 # global env
2760 #
2761 # set foo GDBHISTSIZE
2762 #
2763 # save_vars { INTERNAL_GDBFLAGS env($foo) env(HOME) } {
2764 # append INTERNAL_GDBFLAGS " -nx"
2765 # unset -nocomplain env(GDBHISTSIZE)
2766 # gdb_start
2767 # gdb_test ...
2768 # }
2769 #
2770 # Here, although INTERNAL_GDBFLAGS, env(GDBHISTSIZE) and env(HOME) may be
2771 # modified inside BODY, this proc guarantees that the modifications will be
2772 # undone after BODY finishes executing.
2773
2774 proc save_vars { vars body } {
2775 array set saved_scalars { }
2776 array set saved_arrays { }
2777 set unset_vars { }
2778
2779 foreach var $vars {
2780 # First evaluate VAR in the context of the caller in case the variable
2781 # name may be a not-yet-interpolated string like env($foo)
2782 set var [uplevel 1 list $var]
2783
2784 if [uplevel 1 [list info exists $var]] {
2785 if [uplevel 1 [list array exists $var]] {
2786 set saved_arrays($var) [uplevel 1 [list array get $var]]
2787 } else {
2788 set saved_scalars($var) [uplevel 1 [list set $var]]
2789 }
2790 } else {
2791 lappend unset_vars $var
2792 }
2793 }
2794
2795 set code [catch {uplevel 1 $body} result]
2796
2797 foreach {var value} [array get saved_scalars] {
2798 uplevel 1 [list set $var $value]
2799 }
2800
2801 foreach {var value} [array get saved_arrays] {
2802 uplevel 1 [list unset $var]
2803 uplevel 1 [list array set $var $value]
2804 }
2805
2806 foreach var $unset_vars {
2807 uplevel 1 [list unset -nocomplain $var]
2808 }
2809
2810 if {$code == 1} {
2811 global errorInfo errorCode
2812 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2813 } else {
2814 return -code $code $result
2815 }
2816 }
2817
2818 # As save_vars, but for variables stored in the board_info for the
2819 # target board.
2820 #
2821 # Usage example:
2822 #
2823 # save_target_board_info { multilib_flags } {
2824 # global board
2825 # set board [target_info name]
2826 # unset_board_info multilib_flags
2827 # set_board_info multilib_flags "$multilib_flags"
2828 # ...
2829 # }
2830
2831 proc save_target_board_info { vars body } {
2832 global board board_info
2833 set board [target_info name]
2834
2835 array set saved_target_board_info { }
2836 set unset_target_board_info { }
2837
2838 foreach var $vars {
2839 if { [info exists board_info($board,$var)] } {
2840 set saved_target_board_info($var) [board_info $board $var]
2841 } else {
2842 lappend unset_target_board_info $var
2843 }
2844 }
2845
2846 set code [catch {uplevel 1 $body} result]
2847
2848 foreach {var value} [array get saved_target_board_info] {
2849 unset_board_info $var
2850 set_board_info $var $value
2851 }
2852
2853 foreach var $unset_target_board_info {
2854 unset_board_info $var
2855 }
2856
2857 if {$code == 1} {
2858 global errorInfo errorCode
2859 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2860 } else {
2861 return -code $code $result
2862 }
2863 }
2864
2865 # Run tests in BODY with the current working directory (CWD) set to
2866 # DIR. When BODY is finished, restore the original CWD. Return the
2867 # result of BODY.
2868 #
2869 # This procedure doesn't check if DIR is a valid directory, so you
2870 # have to make sure of that.
2871
2872 proc with_cwd { dir body } {
2873 set saved_dir [pwd]
2874 verbose -log "Switching to directory $dir (saved CWD: $saved_dir)."
2875 cd $dir
2876
2877 set code [catch {uplevel 1 $body} result]
2878
2879 verbose -log "Switching back to $saved_dir."
2880 cd $saved_dir
2881
2882 if {$code == 1} {
2883 global errorInfo errorCode
2884 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2885 } else {
2886 return -code $code $result
2887 }
2888 }
2889
2890 # Use GDB's 'cd' command to switch to DIR. Return true if the switch
2891 # was successful, otherwise, call perror and return false.
2892
2893 proc gdb_cd { dir } {
2894 set new_dir ""
2895 gdb_test_multiple "cd $dir" "" {
2896 -re "^cd \[^\r\n\]+\r\n" {
2897 exp_continue
2898 }
2899
2900 -re "^Working directory (\[^\r\n\]+)\\.\r\n" {
2901 set new_dir $expect_out(1,string)
2902 exp_continue
2903 }
2904
2905 -re "^$::gdb_prompt $" {
2906 if { $new_dir == "" || $new_dir != $dir } {
2907 perror "failed to switch to $dir"
2908 return false
2909 }
2910 }
2911 }
2912
2913 return true
2914 }
2915
2916 # Use GDB's 'pwd' command to figure out the current working directory.
2917 # Return the directory as a string. If we can't figure out the
2918 # current working directory, then call perror, and return the empty
2919 # string.
2920
2921 proc gdb_pwd { } {
2922 set dir ""
2923 gdb_test_multiple "pwd" "" {
2924 -re "^pwd\r\n" {
2925 exp_continue
2926 }
2927
2928 -re "^Working directory (\[^\r\n\]+)\\.\r\n" {
2929 set dir $expect_out(1,string)
2930 exp_continue
2931 }
2932
2933 -re "^$::gdb_prompt $" {
2934 }
2935 }
2936
2937 if { $dir == "" } {
2938 perror "failed to read GDB's current working directory"
2939 }
2940
2941 return $dir
2942 }
2943
2944 # Similar to the with_cwd proc, this proc runs BODY with the current
2945 # working directory changed to CWD.
2946 #
2947 # Unlike with_cwd, the directory change here is done within GDB
2948 # itself, so GDB must be running before this proc is called.
2949
2950 proc with_gdb_cwd { dir body } {
2951 set saved_dir [gdb_pwd]
2952 if { $saved_dir == "" } {
2953 return
2954 }
2955
2956 verbose -log "Switching to directory $dir (saved CWD: $saved_dir)."
2957 if ![gdb_cd $dir] {
2958 return
2959 }
2960
2961 set code [catch {uplevel 1 $body} result]
2962
2963 verbose -log "Switching back to $saved_dir."
2964 if ![gdb_cd $saved_dir] {
2965 return
2966 }
2967
2968 # Check that GDB is still alive. If GDB crashed in the above code
2969 # then any corefile will have been left in DIR, not the root
2970 # testsuite directory. As a result the corefile will not be
2971 # brought to the users attention. Instead, if GDB crashed, then
2972 # this check should cause a FAIL, which should be enough to alert
2973 # the user.
2974 set saw_result false
2975 gdb_test_multiple "p 123" "" {
2976 -re "p 123\r\n" {
2977 exp_continue
2978 }
2979
2980 -re "^\\\$$::decimal = 123\r\n" {
2981 set saw_result true
2982 exp_continue
2983 }
2984
2985 -re "^$::gdb_prompt $" {
2986 if { !$saw_result } {
2987 fail "check gdb is alive in with_gdb_cwd"
2988 }
2989 }
2990 }
2991
2992 if {$code == 1} {
2993 global errorInfo errorCode
2994 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
2995 } else {
2996 return -code $code $result
2997 }
2998 }
2999
3000 # Run tests in BODY with GDB prompt and variable $gdb_prompt set to
3001 # PROMPT. When BODY is finished, restore GDB prompt and variable
3002 # $gdb_prompt.
3003 # Returns the result of BODY.
3004 #
3005 # Notes:
3006 #
3007 # 1) If you want to use, for example, "(foo)" as the prompt you must pass it
3008 # as "(foo)", and not the regexp form "\(foo\)" (expressed as "\\(foo\\)" in
3009 # TCL). PROMPT is internally converted to a suitable regexp for matching.
3010 # We do the conversion from "(foo)" to "\(foo\)" here for a few reasons:
3011 # a) It's more intuitive for callers to pass the plain text form.
3012 # b) We need two forms of the prompt:
3013 # - a regexp to use in output matching,
3014 # - a value to pass to the "set prompt" command.
3015 # c) It's easier to convert the plain text form to its regexp form.
3016 #
3017 # 2) Don't add a trailing space, we do that here.
3018
3019 proc with_gdb_prompt { prompt body } {
3020 global gdb_prompt
3021
3022 # Convert "(foo)" to "\(foo\)".
3023 # We don't use string_to_regexp because while it works today it's not
3024 # clear it will work tomorrow: the value we need must work as both a
3025 # regexp *and* as the argument to the "set prompt" command, at least until
3026 # we start recording both forms separately instead of just $gdb_prompt.
3027 # The testsuite is pretty-much hardwired to interpret $gdb_prompt as the
3028 # regexp form.
3029 regsub -all {[]*+.|()^$\[\\]} $prompt {\\&} prompt
3030
3031 set saved $gdb_prompt
3032
3033 verbose -log "Setting gdb prompt to \"$prompt \"."
3034 set gdb_prompt $prompt
3035 gdb_test_no_output "set prompt $prompt " ""
3036
3037 set code [catch {uplevel 1 $body} result]
3038
3039 verbose -log "Restoring gdb prompt to \"$saved \"."
3040 set gdb_prompt $saved
3041 gdb_test_no_output "set prompt $saved " ""
3042
3043 if {$code == 1} {
3044 global errorInfo errorCode
3045 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3046 } else {
3047 return -code $code $result
3048 }
3049 }
3050
3051 # Run tests in BODY with target-charset setting to TARGET_CHARSET. When
3052 # BODY is finished, restore target-charset.
3053
3054 proc with_target_charset { target_charset body } {
3055 global gdb_prompt
3056
3057 set saved ""
3058 gdb_test_multiple "show target-charset" "" {
3059 -re "The target character set is \".*; currently (.*)\"\..*$gdb_prompt " {
3060 set saved $expect_out(1,string)
3061 }
3062 -re "The target character set is \"(.*)\".*$gdb_prompt " {
3063 set saved $expect_out(1,string)
3064 }
3065 -re ".*$gdb_prompt " {
3066 fail "get target-charset"
3067 }
3068 }
3069
3070 gdb_test_no_output -nopass "set target-charset $target_charset"
3071
3072 set code [catch {uplevel 1 $body} result]
3073
3074 gdb_test_no_output -nopass "set target-charset $saved"
3075
3076 if {$code == 1} {
3077 global errorInfo errorCode
3078 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3079 } else {
3080 return -code $code $result
3081 }
3082 }
3083
3084 # Switch the default spawn id to SPAWN_ID, so that gdb_test,
3085 # mi_gdb_test etc. default to using it.
3086
3087 proc switch_gdb_spawn_id {spawn_id} {
3088 global gdb_spawn_id
3089 global board board_info
3090
3091 set gdb_spawn_id $spawn_id
3092 set board [host_info name]
3093 set board_info($board,fileid) $spawn_id
3094 }
3095
3096 # Clear the default spawn id.
3097
3098 proc clear_gdb_spawn_id {} {
3099 global gdb_spawn_id
3100 global board board_info
3101
3102 unset -nocomplain gdb_spawn_id
3103 set board [host_info name]
3104 unset -nocomplain board_info($board,fileid)
3105 }
3106
3107 # Run BODY with SPAWN_ID as current spawn id.
3108
3109 proc with_spawn_id { spawn_id body } {
3110 global gdb_spawn_id
3111
3112 if [info exists gdb_spawn_id] {
3113 set saved_spawn_id $gdb_spawn_id
3114 }
3115
3116 switch_gdb_spawn_id $spawn_id
3117
3118 set code [catch {uplevel 1 $body} result]
3119
3120 if [info exists saved_spawn_id] {
3121 switch_gdb_spawn_id $saved_spawn_id
3122 } else {
3123 clear_gdb_spawn_id
3124 }
3125
3126 if {$code == 1} {
3127 global errorInfo errorCode
3128 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3129 } else {
3130 return -code $code $result
3131 }
3132 }
3133
3134 # Select the largest timeout from all the timeouts:
3135 # - the local "timeout" variable of the scope two levels above,
3136 # - the global "timeout" variable,
3137 # - the board variable "gdb,timeout".
3138
3139 proc get_largest_timeout {} {
3140 upvar #0 timeout gtimeout
3141 upvar 2 timeout timeout
3142
3143 set tmt 0
3144 if [info exists timeout] {
3145 set tmt $timeout
3146 }
3147 if { [info exists gtimeout] && $gtimeout > $tmt } {
3148 set tmt $gtimeout
3149 }
3150 if { [target_info exists gdb,timeout]
3151 && [target_info gdb,timeout] > $tmt } {
3152 set tmt [target_info gdb,timeout]
3153 }
3154 if { $tmt == 0 } {
3155 # Eeeeew.
3156 set tmt 60
3157 }
3158
3159 return $tmt
3160 }
3161
3162 # Run tests in BODY with timeout increased by factor of FACTOR. When
3163 # BODY is finished, restore timeout.
3164
3165 proc with_timeout_factor { factor body } {
3166 global timeout
3167
3168 set savedtimeout $timeout
3169
3170 set timeout [expr [get_largest_timeout] * $factor]
3171 set code [catch {uplevel 1 $body} result]
3172
3173 set timeout $savedtimeout
3174 if {$code == 1} {
3175 global errorInfo errorCode
3176 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
3177 } else {
3178 return -code $code $result
3179 }
3180 }
3181
3182 # Run BODY with timeout factor FACTOR if check-read1 is used.
3183
3184 proc with_read1_timeout_factor { factor body } {
3185 if { [info exists ::env(READ1)] == 1 && $::env(READ1) == 1 } {
3186 # Use timeout factor
3187 } else {
3188 # Reset timeout factor
3189 set factor 1
3190 }
3191 return [uplevel [list with_timeout_factor $factor $body]]
3192 }
3193
3194 # Return 1 if _Complex types are supported, otherwise, return 0.
3195
3196 gdb_caching_proc support_complex_tests {
3197
3198 if { [gdb_skip_float_test] } {
3199 # If floating point is not supported, _Complex is not
3200 # supported.
3201 return 0
3202 }
3203
3204 # Compile a test program containing _Complex types.
3205
3206 return [gdb_can_simple_compile complex {
3207 int main() {
3208 _Complex float cf;
3209 _Complex double cd;
3210 _Complex long double cld;
3211 return 0;
3212 }
3213 } executable]
3214 }
3215
3216 # Return 1 if compiling go is supported.
3217 gdb_caching_proc support_go_compile {
3218
3219 return [gdb_can_simple_compile go-hello {
3220 package main
3221 import "fmt"
3222 func main() {
3223 fmt.Println("hello world")
3224 }
3225 } executable go]
3226 }
3227
3228 # Return 1 if GDB can get a type for siginfo from the target, otherwise
3229 # return 0.
3230
3231 proc supports_get_siginfo_type {} {
3232 if { [istarget "*-*-linux*"] } {
3233 return 1
3234 } else {
3235 return 0
3236 }
3237 }
3238
3239 # Return 1 if memory tagging is supported at runtime, otherwise return 0.
3240
3241 gdb_caching_proc supports_memtag {
3242 global gdb_prompt
3243
3244 gdb_test_multiple "memory-tag check" "" {
3245 -re "Memory tagging not supported or disabled by the current architecture\..*$gdb_prompt $" {
3246 return 0
3247 }
3248 -re "Argument required \\(address or pointer\\).*$gdb_prompt $" {
3249 return 1
3250 }
3251 }
3252 return 0
3253 }
3254
3255 # Return 1 if the target supports hardware single stepping.
3256
3257 proc can_hardware_single_step {} {
3258
3259 if { [istarget "arm*-*-*"] || [istarget "mips*-*-*"]
3260 || [istarget "tic6x-*-*"] || [istarget "sparc*-*-linux*"]
3261 || [istarget "nios2-*-*"] || [istarget "riscv*-*-linux*"] } {
3262 return 0
3263 }
3264
3265 return 1
3266 }
3267
3268 # Return 1 if target hardware or OS supports single stepping to signal
3269 # handler, otherwise, return 0.
3270
3271 proc can_single_step_to_signal_handler {} {
3272 # Targets don't have hardware single step. On these targets, when
3273 # a signal is delivered during software single step, gdb is unable
3274 # to determine the next instruction addresses, because start of signal
3275 # handler is one of them.
3276 return [can_hardware_single_step]
3277 }
3278
3279 # Return 1 if target supports process record, otherwise return 0.
3280
3281 proc supports_process_record {} {
3282
3283 if [target_info exists gdb,use_precord] {
3284 return [target_info gdb,use_precord]
3285 }
3286
3287 if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
3288 || [istarget "i\[34567\]86-*-linux*"]
3289 || [istarget "aarch64*-*-linux*"]
3290 || [istarget "powerpc*-*-linux*"]
3291 || [istarget "s390*-*-linux*"] } {
3292 return 1
3293 }
3294
3295 return 0
3296 }
3297
3298 # Return 1 if target supports reverse debugging, otherwise return 0.
3299
3300 proc supports_reverse {} {
3301
3302 if [target_info exists gdb,can_reverse] {
3303 return [target_info gdb,can_reverse]
3304 }
3305
3306 if { [istarget "arm*-*-linux*"] || [istarget "x86_64-*-linux*"]
3307 || [istarget "i\[34567\]86-*-linux*"]
3308 || [istarget "aarch64*-*-linux*"]
3309 || [istarget "powerpc*-*-linux*"]
3310 || [istarget "s390*-*-linux*"] } {
3311 return 1
3312 }
3313
3314 return 0
3315 }
3316
3317 # Return 1 if readline library is used.
3318
3319 proc readline_is_used { } {
3320 global gdb_prompt
3321
3322 gdb_test_multiple "show editing" "" {
3323 -re ".*Editing of command lines as they are typed is on\..*$gdb_prompt $" {
3324 return 1
3325 }
3326 -re ".*$gdb_prompt $" {
3327 return 0
3328 }
3329 }
3330 }
3331
3332 # Return 1 if target is ELF.
3333 gdb_caching_proc is_elf_target {
3334 set me "is_elf_target"
3335
3336 set src { int foo () {return 0;} }
3337 if {![gdb_simple_compile elf_target $src]} {
3338 return 0
3339 }
3340
3341 set fp_obj [open $obj "r"]
3342 fconfigure $fp_obj -translation binary
3343 set data [read $fp_obj]
3344 close $fp_obj
3345
3346 file delete $obj
3347
3348 set ELFMAG "\u007FELF"
3349
3350 if {[string compare -length 4 $data $ELFMAG] != 0} {
3351 verbose "$me: returning 0" 2
3352 return 0
3353 }
3354
3355 verbose "$me: returning 1" 2
3356 return 1
3357 }
3358
3359 # Return 1 if the memory at address zero is readable.
3360
3361 gdb_caching_proc is_address_zero_readable {
3362 global gdb_prompt
3363
3364 set ret 0
3365 gdb_test_multiple "x 0" "" {
3366 -re "Cannot access memory at address 0x0.*$gdb_prompt $" {
3367 set ret 0
3368 }
3369 -re ".*$gdb_prompt $" {
3370 set ret 1
3371 }
3372 }
3373
3374 return $ret
3375 }
3376
3377 # Produce source file NAME and write SOURCES into it.
3378
3379 proc gdb_produce_source { name sources } {
3380 set index 0
3381 set f [open $name "w"]
3382
3383 puts $f $sources
3384 close $f
3385 }
3386
3387 # Return 1 if target is ILP32.
3388 # This cannot be decided simply from looking at the target string,
3389 # as it might depend on externally passed compiler options like -m64.
3390 gdb_caching_proc is_ilp32_target {
3391 return [gdb_can_simple_compile is_ilp32_target {
3392 int dummy[sizeof (int) == 4
3393 && sizeof (void *) == 4
3394 && sizeof (long) == 4 ? 1 : -1];
3395 }]
3396 }
3397
3398 # Return 1 if target is LP64.
3399 # This cannot be decided simply from looking at the target string,
3400 # as it might depend on externally passed compiler options like -m64.
3401 gdb_caching_proc is_lp64_target {
3402 return [gdb_can_simple_compile is_lp64_target {
3403 int dummy[sizeof (int) == 4
3404 && sizeof (void *) == 8
3405 && sizeof (long) == 8 ? 1 : -1];
3406 }]
3407 }
3408
3409 # Return 1 if target has 64 bit addresses.
3410 # This cannot be decided simply from looking at the target string,
3411 # as it might depend on externally passed compiler options like -m64.
3412 gdb_caching_proc is_64_target {
3413 return [gdb_can_simple_compile is_64_target {
3414 int function(void) { return 3; }
3415 int dummy[sizeof (&function) == 8 ? 1 : -1];
3416 }]
3417 }
3418
3419 # Return 1 if target has x86_64 registers - either amd64 or x32.
3420 # x32 target identifies as x86_64-*-linux*, therefore it cannot be determined
3421 # just from the target string.
3422 gdb_caching_proc is_amd64_regs_target {
3423 if {![istarget "x86_64-*-*"] && ![istarget "i?86-*"]} {
3424 return 0
3425 }
3426
3427 return [gdb_can_simple_compile is_amd64_regs_target {
3428 int main (void) {
3429 asm ("incq %rax");
3430 asm ("incq %r15");
3431
3432 return 0;
3433 }
3434 }]
3435 }
3436
3437 # Return 1 if this target is an x86 or x86-64 with -m32.
3438 proc is_x86_like_target {} {
3439 if {![istarget "x86_64-*-*"] && ![istarget i?86-*]} {
3440 return 0
3441 }
3442 return [expr [is_ilp32_target] && ![is_amd64_regs_target]]
3443 }
3444
3445 # Return 1 if this target is an arm or aarch32 on aarch64.
3446
3447 gdb_caching_proc is_aarch32_target {
3448 if { [istarget "arm*-*-*"] } {
3449 return 1
3450 }
3451
3452 if { ![istarget "aarch64*-*-*"] } {
3453 return 0
3454 }
3455
3456 set list {}
3457 foreach reg \
3458 {r0 r1 r2 r3} {
3459 lappend list "\tmov $reg, $reg"
3460 }
3461
3462 return [gdb_can_simple_compile aarch32 [join $list \n]]
3463 }
3464
3465 # Return 1 if this target is an aarch64, either lp64 or ilp32.
3466
3467 proc is_aarch64_target {} {
3468 if { ![istarget "aarch64*-*-*"] } {
3469 return 0
3470 }
3471
3472 return [expr ![is_aarch32_target]]
3473 }
3474
3475 # Return 1 if displaced stepping is supported on target, otherwise, return 0.
3476 proc support_displaced_stepping {} {
3477
3478 if { [istarget "x86_64-*-linux*"] || [istarget "i\[34567\]86-*-linux*"]
3479 || [istarget "arm*-*-linux*"] || [istarget "powerpc-*-linux*"]
3480 || [istarget "powerpc64-*-linux*"] || [istarget "s390*-*-*"]
3481 || [istarget "aarch64*-*-linux*"] || [istarget "loongarch*-*-linux*"] } {
3482 return 1
3483 }
3484
3485 return 0
3486 }
3487
3488 # Run a test on the target to see if it supports vmx hardware. Return 0 if so,
3489 # 1 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3490
3491 gdb_caching_proc skip_altivec_tests {
3492 global srcdir subdir gdb_prompt inferior_exited_re
3493
3494 set me "skip_altivec_tests"
3495
3496 # Some simulators are known to not support VMX instructions.
3497 if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
3498 verbose "$me: target known to not support VMX, returning 1" 2
3499 return 1
3500 }
3501
3502 # Make sure we have a compiler that understands altivec.
3503 if [test_compiler_info gcc*] {
3504 set compile_flags "additional_flags=-maltivec"
3505 } elseif [test_compiler_info xlc*] {
3506 set compile_flags "additional_flags=-qaltivec"
3507 } else {
3508 verbose "Could not compile with altivec support, returning 1" 2
3509 return 1
3510 }
3511
3512 # Compile a test program containing VMX instructions.
3513 set src {
3514 int main() {
3515 #ifdef __MACH__
3516 asm volatile ("vor v0,v0,v0");
3517 #else
3518 asm volatile ("vor 0,0,0");
3519 #endif
3520 return 0;
3521 }
3522 }
3523 if {![gdb_simple_compile $me $src executable $compile_flags]} {
3524 return 1
3525 }
3526
3527 # Compilation succeeded so now run it via gdb.
3528
3529 gdb_exit
3530 gdb_start
3531 gdb_reinitialize_dir $srcdir/$subdir
3532 gdb_load "$obj"
3533 gdb_run_cmd
3534 gdb_expect {
3535 -re ".*Illegal instruction.*${gdb_prompt} $" {
3536 verbose -log "\n$me altivec hardware not detected"
3537 set skip_vmx_tests 1
3538 }
3539 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3540 verbose -log "\n$me: altivec hardware detected"
3541 set skip_vmx_tests 0
3542 }
3543 default {
3544 warning "\n$me: default case taken"
3545 set skip_vmx_tests 1
3546 }
3547 }
3548 gdb_exit
3549 remote_file build delete $obj
3550
3551 verbose "$me: returning $skip_vmx_tests" 2
3552 return $skip_vmx_tests
3553 }
3554
3555 # Run a test on the power target to see if it supports ISA 3.1 instructions
3556 gdb_caching_proc skip_power_isa_3_1_tests {
3557 global srcdir subdir gdb_prompt inferior_exited_re
3558
3559 set me "skip_power_isa_3_1_tests"
3560
3561 # Compile a test program containing ISA 3.1 instructions.
3562 set src {
3563 int main() {
3564 asm volatile ("pnop"); // marker
3565 asm volatile ("nop");
3566 return 0;
3567 }
3568 }
3569
3570 if {![gdb_simple_compile $me $src executable ]} {
3571 return 1
3572 }
3573
3574 # No error message, compilation succeeded so now run it via gdb.
3575
3576 gdb_exit
3577 gdb_start
3578 gdb_reinitialize_dir $srcdir/$subdir
3579 gdb_load "$obj"
3580 gdb_run_cmd
3581 gdb_expect {
3582 -re ".*Illegal instruction.*${gdb_prompt} $" {
3583 verbose -log "\n$me Power ISA 3.1 hardware not detected"
3584 set skip_power_isa_3_1_tests 1
3585 }
3586 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3587 verbose -log "\n$me: Power ISA 3.1 hardware detected"
3588 set skip_power_isa_3_1_tests 0
3589 }
3590 default {
3591 warning "\n$me: default case taken"
3592 set skip_power_isa_3_1_tests 1
3593 }
3594 }
3595 gdb_exit
3596 remote_file build delete $obj
3597
3598 verbose "$me: returning $skip_power_isa_3_1_tests" 2
3599 return $skip_power_isa_3_1_tests
3600 }
3601
3602 # Run a test on the target to see if it supports vmx hardware. Return 0 if so,
3603 # 1 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3604
3605 gdb_caching_proc skip_vsx_tests {
3606 global srcdir subdir gdb_prompt inferior_exited_re
3607
3608 set me "skip_vsx_tests"
3609
3610 # Some simulators are known to not support Altivec instructions, so
3611 # they won't support VSX instructions as well.
3612 if { [istarget powerpc-*-eabi] || [istarget powerpc*-*-eabispe] } {
3613 verbose "$me: target known to not support VSX, returning 1" 2
3614 return 1
3615 }
3616
3617 # Make sure we have a compiler that understands altivec.
3618 if [test_compiler_info gcc*] {
3619 set compile_flags "additional_flags=-mvsx"
3620 } elseif [test_compiler_info xlc*] {
3621 set compile_flags "additional_flags=-qasm=gcc"
3622 } else {
3623 verbose "Could not compile with vsx support, returning 1" 2
3624 return 1
3625 }
3626
3627 # Compile a test program containing VSX instructions.
3628 set src {
3629 int main() {
3630 double a[2] = { 1.0, 2.0 };
3631 #ifdef __MACH__
3632 asm volatile ("lxvd2x v0,v0,%[addr]" : : [addr] "r" (a));
3633 #else
3634 asm volatile ("lxvd2x 0,0,%[addr]" : : [addr] "r" (a));
3635 #endif
3636 return 0;
3637 }
3638 }
3639 if {![gdb_simple_compile $me $src executable $compile_flags]} {
3640 return 1
3641 }
3642
3643 # No error message, compilation succeeded so now run it via gdb.
3644
3645 gdb_exit
3646 gdb_start
3647 gdb_reinitialize_dir $srcdir/$subdir
3648 gdb_load "$obj"
3649 gdb_run_cmd
3650 gdb_expect {
3651 -re ".*Illegal instruction.*${gdb_prompt} $" {
3652 verbose -log "\n$me VSX hardware not detected"
3653 set skip_vsx_tests 1
3654 }
3655 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3656 verbose -log "\n$me: VSX hardware detected"
3657 set skip_vsx_tests 0
3658 }
3659 default {
3660 warning "\n$me: default case taken"
3661 set skip_vsx_tests 1
3662 }
3663 }
3664 gdb_exit
3665 remote_file build delete $obj
3666
3667 verbose "$me: returning $skip_vsx_tests" 2
3668 return $skip_vsx_tests
3669 }
3670
3671 # Run a test on the target to see if it supports TSX hardware. Return 0 if so,
3672 # 1 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3673
3674 gdb_caching_proc skip_tsx_tests {
3675 global srcdir subdir gdb_prompt inferior_exited_re
3676
3677 set me "skip_tsx_tests"
3678
3679 # Compile a test program.
3680 set src {
3681 int main() {
3682 asm volatile ("xbegin .L0");
3683 asm volatile ("xend");
3684 asm volatile (".L0: nop");
3685 return 0;
3686 }
3687 }
3688 if {![gdb_simple_compile $me $src executable]} {
3689 return 1
3690 }
3691
3692 # No error message, compilation succeeded so now run it via gdb.
3693
3694 gdb_exit
3695 gdb_start
3696 gdb_reinitialize_dir $srcdir/$subdir
3697 gdb_load "$obj"
3698 gdb_run_cmd
3699 gdb_expect {
3700 -re ".*Illegal instruction.*${gdb_prompt} $" {
3701 verbose -log "$me: TSX hardware not detected."
3702 set skip_tsx_tests 1
3703 }
3704 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3705 verbose -log "$me: TSX hardware detected."
3706 set skip_tsx_tests 0
3707 }
3708 default {
3709 warning "\n$me: default case taken."
3710 set skip_tsx_tests 1
3711 }
3712 }
3713 gdb_exit
3714 remote_file build delete $obj
3715
3716 verbose "$me: returning $skip_tsx_tests" 2
3717 return $skip_tsx_tests
3718 }
3719
3720 # Run a test on the target to see if it supports avx512bf16. Return 0 if so,
3721 # 1 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3722
3723 gdb_caching_proc skip_avx512bf16_tests {
3724 global srcdir subdir gdb_prompt inferior_exited_re
3725
3726 set me "skip_avx512bf16_tests"
3727 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
3728 verbose "$me: target does not support avx512bf16, returning 1" 2
3729 return 1
3730 }
3731
3732 # Compile a test program.
3733 set src {
3734 int main() {
3735 asm volatile ("vcvtne2ps2bf16 %xmm0, %xmm1, %xmm0");
3736 return 0;
3737 }
3738 }
3739 if {![gdb_simple_compile $me $src executable]} {
3740 return 1
3741 }
3742
3743 # No error message, compilation succeeded so now run it via gdb.
3744
3745 gdb_exit
3746 gdb_start
3747 gdb_reinitialize_dir $srcdir/$subdir
3748 gdb_load "$obj"
3749 gdb_run_cmd
3750 gdb_expect {
3751 -re ".*Illegal instruction.*${gdb_prompt} $" {
3752 verbose -log "$me: avx512bf16 hardware not detected."
3753 set skip_avx512bf16_tests 1
3754 }
3755 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3756 verbose -log "$me: avx512bf16 hardware detected."
3757 set skip_avx512bf16_tests 0
3758 }
3759 default {
3760 warning "\n$me: default case taken."
3761 set skip_avx512bf16_tests 1
3762 }
3763 }
3764 gdb_exit
3765 remote_file build delete $obj
3766
3767 verbose "$me: returning $skip_avx512bf16_tests" 2
3768 return $skip_avx512bf16_tests
3769 }
3770
3771 # Run a test on the target to see if it supports avx512fp16. Return 0 if so,
3772 # 1 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3773
3774 gdb_caching_proc skip_avx512fp16_tests {
3775 global srcdir subdir gdb_prompt inferior_exited_re
3776
3777 set me "skip_avx512fp16_tests"
3778 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
3779 verbose "$me: target does not support avx512fp16, returning 1" 2
3780 return 1
3781 }
3782
3783 # Compile a test program.
3784 set src {
3785 int main() {
3786 asm volatile ("vcvtps2phx %xmm1, %xmm0");
3787 return 0;
3788 }
3789 }
3790 if {![gdb_simple_compile $me $src executable]} {
3791 return 1
3792 }
3793
3794 # No error message, compilation succeeded so now run it via gdb.
3795
3796 gdb_exit
3797 gdb_start
3798 gdb_reinitialize_dir $srcdir/$subdir
3799 gdb_load "$obj"
3800 gdb_run_cmd
3801 gdb_expect {
3802 -re ".*Illegal instruction.*${gdb_prompt} $" {
3803 verbose -log "$me: avx512fp16 hardware not detected."
3804 set skip_avx512fp16_tests 1
3805 }
3806 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3807 verbose -log "$me: avx512fp16 hardware detected."
3808 set skip_avx512fp16_tests 0
3809 }
3810 default {
3811 warning "\n$me: default case taken."
3812 set skip_avx512fp16_tests 1
3813 }
3814 }
3815 gdb_exit
3816 remote_file build delete $obj
3817
3818 verbose "$me: returning $skip_avx512fp16_tests" 2
3819 return $skip_avx512fp16_tests
3820 }
3821
3822 # Run a test on the target to see if it supports btrace hardware. Return 0 if so,
3823 # 1 if it does not. Based on 'check_vmx_hw_available' from the GCC testsuite.
3824
3825 gdb_caching_proc skip_btrace_tests {
3826 global srcdir subdir gdb_prompt inferior_exited_re
3827
3828 set me "skip_btrace_tests"
3829 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
3830 verbose "$me: target does not support btrace, returning 1" 2
3831 return 1
3832 }
3833
3834 # Compile a test program.
3835 set src { int main() { return 0; } }
3836 if {![gdb_simple_compile $me $src executable]} {
3837 return 1
3838 }
3839
3840 # No error message, compilation succeeded so now run it via gdb.
3841
3842 gdb_exit
3843 gdb_start
3844 gdb_reinitialize_dir $srcdir/$subdir
3845 gdb_load $obj
3846 if ![runto_main] {
3847 return 1
3848 }
3849 # In case of an unexpected output, we return 2 as a fail value.
3850 set skip_btrace_tests 2
3851 gdb_test_multiple "record btrace" "check btrace support" {
3852 -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
3853 set skip_btrace_tests 1
3854 }
3855 -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
3856 set skip_btrace_tests 1
3857 }
3858 -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
3859 set skip_btrace_tests 1
3860 }
3861 -re "^record btrace\r\n$gdb_prompt $" {
3862 set skip_btrace_tests 0
3863 }
3864 }
3865 gdb_exit
3866 remote_file build delete $obj
3867
3868 verbose "$me: returning $skip_btrace_tests" 2
3869 return $skip_btrace_tests
3870 }
3871
3872 # Run a test on the target to see if it supports btrace pt hardware.
3873 # Return 0 if so, 1 if it does not. Based on 'check_vmx_hw_available'
3874 # from the GCC testsuite.
3875
3876 gdb_caching_proc skip_btrace_pt_tests {
3877 global srcdir subdir gdb_prompt inferior_exited_re
3878
3879 set me "skip_btrace_tests"
3880 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
3881 verbose "$me: target does not support btrace, returning 1" 2
3882 return 1
3883 }
3884
3885 # Compile a test program.
3886 set src { int main() { return 0; } }
3887 if {![gdb_simple_compile $me $src executable]} {
3888 return 1
3889 }
3890
3891 # No error message, compilation succeeded so now run it via gdb.
3892
3893 gdb_exit
3894 gdb_start
3895 gdb_reinitialize_dir $srcdir/$subdir
3896 gdb_load $obj
3897 if ![runto_main] {
3898 return 1
3899 }
3900 # In case of an unexpected output, we return 2 as a fail value.
3901 set skip_btrace_tests 2
3902 gdb_test_multiple "record btrace pt" "check btrace pt support" {
3903 -re "You can't do that when your target is.*\r\n$gdb_prompt $" {
3904 set skip_btrace_tests 1
3905 }
3906 -re "Target does not support branch tracing.*\r\n$gdb_prompt $" {
3907 set skip_btrace_tests 1
3908 }
3909 -re "Could not enable branch tracing.*\r\n$gdb_prompt $" {
3910 set skip_btrace_tests 1
3911 }
3912 -re "support was disabled at compile time.*\r\n$gdb_prompt $" {
3913 set skip_btrace_tests 1
3914 }
3915 -re "^record btrace pt\r\n$gdb_prompt $" {
3916 set skip_btrace_tests 0
3917 }
3918 }
3919 gdb_exit
3920 remote_file build delete $obj
3921
3922 verbose "$me: returning $skip_btrace_tests" 2
3923 return $skip_btrace_tests
3924 }
3925
3926 # Run a test on the target to see if it supports Aarch64 SVE hardware.
3927 # Return 0 if so, 1 if it does not. Note this causes a restart of GDB.
3928
3929 gdb_caching_proc skip_aarch64_sve_tests {
3930 global srcdir subdir gdb_prompt inferior_exited_re
3931
3932 set me "skip_aarch64_sve_tests"
3933
3934 if { ![is_aarch64_target]} {
3935 return 1
3936 }
3937
3938 set compile_flags "{additional_flags=-march=armv8-a+sve}"
3939
3940 # Compile a test program containing SVE instructions.
3941 set src {
3942 int main() {
3943 asm volatile ("ptrue p0.b");
3944 return 0;
3945 }
3946 }
3947 if {![gdb_simple_compile $me $src executable $compile_flags]} {
3948 return 1
3949 }
3950
3951 # Compilation succeeded so now run it via gdb.
3952 clean_restart $obj
3953 gdb_run_cmd
3954 gdb_expect {
3955 -re ".*Illegal instruction.*${gdb_prompt} $" {
3956 verbose -log "\n$me sve hardware not detected"
3957 set skip_sve_tests 1
3958 }
3959 -re ".*$inferior_exited_re normally.*${gdb_prompt} $" {
3960 verbose -log "\n$me: sve hardware detected"
3961 set skip_sve_tests 0
3962 }
3963 default {
3964 warning "\n$me: default case taken"
3965 set skip_sve_tests 1
3966 }
3967 }
3968 gdb_exit
3969 remote_file build delete $obj
3970
3971 verbose "$me: returning $skip_sve_tests" 2
3972 return $skip_sve_tests
3973 }
3974
3975
3976 # A helper that compiles a test case to see if __int128 is supported.
3977 proc gdb_int128_helper {lang} {
3978 return [gdb_can_simple_compile "i128-for-$lang" {
3979 __int128 x;
3980 int main() { return 0; }
3981 } executable $lang]
3982 }
3983
3984 # Return true if the C compiler understands the __int128 type.
3985 gdb_caching_proc has_int128_c {
3986 return [gdb_int128_helper c]
3987 }
3988
3989 # Return true if the C++ compiler understands the __int128 type.
3990 gdb_caching_proc has_int128_cxx {
3991 return [gdb_int128_helper c++]
3992 }
3993
3994 # Return true if the IFUNC feature is unsupported.
3995 gdb_caching_proc skip_ifunc_tests {
3996 if [gdb_can_simple_compile ifunc {
3997 extern void f_ ();
3998 typedef void F (void);
3999 F* g (void) { return &f_; }
4000 void f () __attribute__ ((ifunc ("g")));
4001 } object] {
4002 return 0
4003 } else {
4004 return 1
4005 }
4006 }
4007
4008 # Return whether we should skip tests for showing inlined functions in
4009 # backtraces. Requires get_compiler_info and get_debug_format.
4010
4011 proc skip_inline_frame_tests {} {
4012 # GDB only recognizes inlining information in DWARF.
4013 if { ! [test_debug_format "DWARF \[0-9\]"] } {
4014 return 1
4015 }
4016
4017 # GCC before 4.1 does not emit DW_AT_call_file / DW_AT_call_line.
4018 if { ([test_compiler_info "gcc-2-*"]
4019 || [test_compiler_info "gcc-3-*"]
4020 || [test_compiler_info "gcc-4-0-*"]) } {
4021 return 1
4022 }
4023
4024 return 0
4025 }
4026
4027 # Return whether we should skip tests for showing variables from
4028 # inlined functions. Requires get_compiler_info and get_debug_format.
4029
4030 proc skip_inline_var_tests {} {
4031 # GDB only recognizes inlining information in DWARF.
4032 if { ! [test_debug_format "DWARF \[0-9\]"] } {
4033 return 1
4034 }
4035
4036 return 0
4037 }
4038
4039 # Return a 1 if we should skip tests that require hardware breakpoints
4040
4041 proc skip_hw_breakpoint_tests {} {
4042 # Skip tests if requested by the board (note that no_hardware_watchpoints
4043 # disables both watchpoints and breakpoints)
4044 if { [target_info exists gdb,no_hardware_watchpoints]} {
4045 return 1
4046 }
4047
4048 # These targets support hardware breakpoints natively
4049 if { [istarget "i?86-*-*"]
4050 || [istarget "x86_64-*-*"]
4051 || [istarget "ia64-*-*"]
4052 || [istarget "arm*-*-*"]
4053 || [istarget "aarch64*-*-*"]
4054 || [istarget "s390*-*-*"] } {
4055 return 0
4056 }
4057
4058 return 1
4059 }
4060
4061 # Return a 1 if we should skip tests that require hardware watchpoints
4062
4063 proc skip_hw_watchpoint_tests {} {
4064 # Skip tests if requested by the board
4065 if { [target_info exists gdb,no_hardware_watchpoints]} {
4066 return 1
4067 }
4068
4069 # These targets support hardware watchpoints natively
4070 # Note, not all Power 9 processors support hardware watchpoints due to a HW
4071 # bug. Use has_hw_wp_support to check do a runtime check for hardware
4072 # watchpoint support on Powerpc.
4073 if { [istarget "i?86-*-*"]
4074 || [istarget "x86_64-*-*"]
4075 || [istarget "ia64-*-*"]
4076 || [istarget "arm*-*-*"]
4077 || [istarget "aarch64*-*-*"]
4078 || ([istarget "powerpc*-*-linux*"] && [has_hw_wp_support])
4079 || [istarget "s390*-*-*"] } {
4080 return 0
4081 }
4082
4083 return 1
4084 }
4085
4086 # Return a 1 if we should skip tests that require *multiple* hardware
4087 # watchpoints to be active at the same time
4088
4089 proc skip_hw_watchpoint_multi_tests {} {
4090 if { [skip_hw_watchpoint_tests] } {
4091 return 1
4092 }
4093
4094 # These targets support just a single hardware watchpoint
4095 if { [istarget "arm*-*-*"]
4096 || [istarget "powerpc*-*-linux*"] } {
4097 return 1
4098 }
4099
4100 return 0
4101 }
4102
4103 # Return a 1 if we should skip tests that require read/access watchpoints
4104
4105 proc skip_hw_watchpoint_access_tests {} {
4106 if { [skip_hw_watchpoint_tests] } {
4107 return 1
4108 }
4109
4110 # These targets support just write watchpoints
4111 if { [istarget "s390*-*-*"] } {
4112 return 1
4113 }
4114
4115 return 0
4116 }
4117
4118 # Return 1 if we should skip tests that require the runtime unwinder
4119 # hook. This must be invoked while gdb is running, after shared
4120 # libraries have been loaded. This is needed because otherwise a
4121 # shared libgcc won't be visible.
4122
4123 proc skip_unwinder_tests {} {
4124 global gdb_prompt
4125
4126 set ok 0
4127 gdb_test_multiple "print _Unwind_DebugHook" "check for unwinder hook" {
4128 -re "= .*no debug info.*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
4129 }
4130 -re "= .*_Unwind_DebugHook.*\r\n$gdb_prompt $" {
4131 set ok 1
4132 }
4133 -re "No symbol .* in current context.\r\n$gdb_prompt $" {
4134 }
4135 }
4136 if {!$ok} {
4137 gdb_test_multiple "info probe" "check for stap probe in unwinder" {
4138 -re ".*libgcc.*unwind.*\r\n$gdb_prompt $" {
4139 set ok 1
4140 }
4141 -re "\r\n$gdb_prompt $" {
4142 }
4143 }
4144 }
4145 return $ok
4146 }
4147
4148 # Return 1 if we should skip tests that require the libstdc++ stap
4149 # probes. This must be invoked while gdb is running, after shared
4150 # libraries have been loaded. PROMPT_REGEXP is the expected prompt.
4151
4152 proc skip_libstdcxx_probe_tests_prompt { prompt_regexp } {
4153 set supported 0
4154 gdb_test_multiple "info probe" "check for stap probe in libstdc++" \
4155 -prompt "$prompt_regexp" {
4156 -re ".*libstdcxx.*catch.*\r\n$prompt_regexp" {
4157 set supported 1
4158 }
4159 -re "\r\n$prompt_regexp" {
4160 }
4161 }
4162 set skip [expr !$supported]
4163 return $skip
4164 }
4165
4166 # As skip_libstdcxx_probe_tests_prompt, with gdb_prompt.
4167
4168 proc skip_libstdcxx_probe_tests {} {
4169 global gdb_prompt
4170 return [skip_libstdcxx_probe_tests_prompt "$gdb_prompt $"]
4171 }
4172
4173 # Helper for gdb_is_target_* procs. TARGET_NAME is the name of the target
4174 # we're looking for (used to build the test name). TARGET_STACK_REGEXP
4175 # is a regexp that will match the output of "maint print target-stack" if
4176 # the target in question is currently pushed. PROMPT_REGEXP is a regexp
4177 # matching the expected prompt after the command output.
4178 #
4179 # NOTE: GDB must be running BEFORE this procedure is called!
4180
4181 proc gdb_is_target_1 { target_name target_stack_regexp prompt_regexp } {
4182 global gdb_spawn_id
4183
4184 # Throw a Tcl error if gdb isn't already started.
4185 if {![info exists gdb_spawn_id]} {
4186 error "gdb_is_target_1 called with no running gdb instance"
4187 }
4188
4189 set test "probe for target ${target_name}"
4190 gdb_test_multiple "maint print target-stack" $test \
4191 -prompt "$prompt_regexp" {
4192 -re "${target_stack_regexp}${prompt_regexp}" {
4193 pass $test
4194 return 1
4195 }
4196 -re "$prompt_regexp" {
4197 pass $test
4198 }
4199 }
4200 return 0
4201 }
4202
4203 # Helper for gdb_is_target_remote where the expected prompt is variable.
4204 #
4205 # NOTE: GDB must be running BEFORE this procedure is called!
4206
4207 proc gdb_is_target_remote_prompt { prompt_regexp } {
4208 return [gdb_is_target_1 "remote" ".*emote target using gdb-specific protocol.*" $prompt_regexp]
4209 }
4210
4211 # Check whether we're testing with the remote or extended-remote
4212 # targets.
4213 #
4214 # NOTE: GDB must be running BEFORE this procedure is called!
4215
4216 proc gdb_is_target_remote { } {
4217 global gdb_prompt
4218
4219 return [gdb_is_target_remote_prompt "$gdb_prompt $"]
4220 }
4221
4222 # Check whether we're testing with the native target.
4223 #
4224 # NOTE: GDB must be running BEFORE this procedure is called!
4225
4226 proc gdb_is_target_native { } {
4227 global gdb_prompt
4228
4229 return [gdb_is_target_1 "native" ".*native \\(Native process\\).*" "$gdb_prompt $"]
4230 }
4231
4232 # Return the effective value of use_gdb_stub.
4233 #
4234 # If the use_gdb_stub global has been set (it is set when the gdb process is
4235 # spawned), return that. Otherwise, return the value of the use_gdb_stub
4236 # property from the board file.
4237 #
4238 # This is the preferred way of checking use_gdb_stub, since it allows to check
4239 # the value before the gdb has been spawned and it will return the correct value
4240 # even when it was overriden by the test.
4241 #
4242 # Note that stub targets are not able to spawn new inferiors. Use this
4243 # check for skipping respective tests.
4244
4245 proc use_gdb_stub {} {
4246 global use_gdb_stub
4247
4248 if [info exists use_gdb_stub] {
4249 return $use_gdb_stub
4250 }
4251
4252 return [target_info exists use_gdb_stub]
4253 }
4254
4255 # Return 1 if the current remote target is an instance of our GDBserver, 0
4256 # otherwise. Return -1 if there was an error and we can't tell.
4257
4258 gdb_caching_proc target_is_gdbserver {
4259 global gdb_prompt
4260
4261 set is_gdbserver -1
4262 set test "probing for GDBserver"
4263
4264 gdb_test_multiple "monitor help" $test {
4265 -re "The following monitor commands are supported.*Quit GDBserver.*$gdb_prompt $" {
4266 set is_gdbserver 1
4267 }
4268 -re "$gdb_prompt $" {
4269 set is_gdbserver 0
4270 }
4271 }
4272
4273 if { $is_gdbserver == -1 } {
4274 verbose -log "Unable to tell whether we are using GDBserver or not."
4275 }
4276
4277 return $is_gdbserver
4278 }
4279
4280 # N.B. compiler_info is intended to be local to this file.
4281 # Call test_compiler_info with no arguments to fetch its value.
4282 # Yes, this is counterintuitive when there's get_compiler_info,
4283 # but that's the current API.
4284 if [info exists compiler_info] {
4285 unset compiler_info
4286 }
4287
4288 # Figure out what compiler I am using.
4289 # The result is cached so only the first invocation runs the compiler.
4290 #
4291 # ARG can be empty or "C++". If empty, "C" is assumed.
4292 #
4293 # There are several ways to do this, with various problems.
4294 #
4295 # [ gdb_compile -E $ifile -o $binfile.ci ]
4296 # source $binfile.ci
4297 #
4298 # Single Unix Spec v3 says that "-E -o ..." together are not
4299 # specified. And in fact, the native compiler on hp-ux 11 (among
4300 # others) does not work with "-E -o ...". Most targets used to do
4301 # this, and it mostly worked, because it works with gcc.
4302 #
4303 # [ catch "exec $compiler -E $ifile > $binfile.ci" exec_output ]
4304 # source $binfile.ci
4305 #
4306 # This avoids the problem with -E and -o together. This almost works
4307 # if the build machine is the same as the host machine, which is
4308 # usually true of the targets which are not gcc. But this code does
4309 # not figure which compiler to call, and it always ends up using the C
4310 # compiler. Not good for setting hp_aCC_compiler. Target
4311 # hppa*-*-hpux* used to do this.
4312 #
4313 # [ gdb_compile -E $ifile > $binfile.ci ]
4314 # source $binfile.ci
4315 #
4316 # dejagnu target_compile says that it supports output redirection,
4317 # but the code is completely different from the normal path and I
4318 # don't want to sweep the mines from that path. So I didn't even try
4319 # this.
4320 #
4321 # set cppout [ gdb_compile $ifile "" preprocess $args quiet ]
4322 # eval $cppout
4323 #
4324 # I actually do this for all targets now. gdb_compile runs the right
4325 # compiler, and TCL captures the output, and I eval the output.
4326 #
4327 # Unfortunately, expect logs the output of the command as it goes by,
4328 # and dejagnu helpfully prints a second copy of it right afterwards.
4329 # So I turn off expect logging for a moment.
4330 #
4331 # [ gdb_compile $ifile $ciexe_file executable $args ]
4332 # [ remote_exec $ciexe_file ]
4333 # [ source $ci_file.out ]
4334 #
4335 # I could give up on -E and just do this.
4336 # I didn't get desperate enough to try this.
4337 #
4338 # -- chastain 2004-01-06
4339
4340 proc get_compiler_info {{language "c"}} {
4341
4342 # For compiler.c, compiler.cc and compiler.F90.
4343 global srcdir
4344
4345 # I am going to play with the log to keep noise out.
4346 global outdir
4347 global tool
4348
4349 # These come from compiler.c, compiler.cc or compiler.F90.
4350 gdb_persistent_global compiler_info_cache
4351
4352 if [info exists compiler_info_cache($language)] {
4353 # Already computed.
4354 return 0
4355 }
4356
4357 # Choose which file to preprocess.
4358 if { $language == "c++" } {
4359 set ifile "${srcdir}/lib/compiler.cc"
4360 } elseif { $language == "f90" } {
4361 set ifile "${srcdir}/lib/compiler.F90"
4362 } elseif { $language == "c" } {
4363 set ifile "${srcdir}/lib/compiler.c"
4364 } else {
4365 perror "Unable to fetch compiler version for language: $language"
4366 return -1
4367 }
4368
4369 # Run $ifile through the right preprocessor.
4370 # Toggle gdb.log to keep the compiler output out of the log.
4371 set saved_log [log_file -info]
4372 log_file
4373 if [is_remote host] {
4374 # We have to use -E and -o together, despite the comments
4375 # above, because of how DejaGnu handles remote host testing.
4376 set ppout "$outdir/compiler.i"
4377 gdb_compile "${ifile}" "$ppout" preprocess [list "$language" quiet getting_compiler_info]
4378 set file [open $ppout r]
4379 set cppout [read $file]
4380 close $file
4381 } else {
4382 # Copy $ifile to temp dir, to work around PR gcc/60447. This will leave the
4383 # superfluous .s file in the temp dir instead of in the source dir.
4384 set tofile [file tail $ifile]
4385 set tofile [standard_temp_file $tofile]
4386 file copy -force $ifile $tofile
4387 set ifile $tofile
4388 set cppout [ gdb_compile "${ifile}" "" preprocess [list "$language" quiet getting_compiler_info] ]
4389 }
4390 eval log_file $saved_log
4391
4392 # Eval the output.
4393 set unknown 0
4394 foreach cppline [ split "$cppout" "\n" ] {
4395 if { [ regexp "^#" "$cppline" ] } {
4396 # line marker
4397 } elseif { [ regexp "^\[\n\r\t \]*$" "$cppline" ] } {
4398 # blank line
4399 } elseif { [ regexp "^\[\n\r\t \]*set\[\n\r\t \]" "$cppline" ] } {
4400 # eval this line
4401 verbose "get_compiler_info: $cppline" 2
4402 eval "$cppline"
4403 } elseif { [ regexp "flang.*warning.*'-fdiagnostics-color=never'" "$cppline"] } {
4404 # Both flang preprocessors (llvm flang and classic flang) print a
4405 # warning for the unused -fdiagnostics-color=never, so we skip this
4406 # output line here.
4407 } else {
4408 # unknown line
4409 verbose -log "get_compiler_info: $cppline"
4410 set unknown 1
4411 }
4412 }
4413
4414 # Set to unknown if for some reason compiler_info didn't get defined.
4415 if ![info exists compiler_info] {
4416 verbose -log "get_compiler_info: compiler_info not provided"
4417 set compiler_info "unknown"
4418 }
4419 # Also set to unknown compiler if any diagnostics happened.
4420 if { $unknown } {
4421 verbose -log "get_compiler_info: got unexpected diagnostics"
4422 set compiler_info "unknown"
4423 }
4424
4425 set compiler_info_cache($language) $compiler_info
4426
4427 # Log what happened.
4428 verbose -log "get_compiler_info: $compiler_info"
4429
4430 return 0
4431 }
4432
4433 # Return the compiler_info string if no arg is provided.
4434 # Otherwise the argument is a glob-style expression to match against
4435 # compiler_info.
4436
4437 proc test_compiler_info { {compiler ""} {language "c"} } {
4438 gdb_persistent_global compiler_info_cache
4439
4440 if [get_compiler_info $language] {
4441 # An error will already have been printed in this case. Just
4442 # return a suitable result depending on how the user called
4443 # this function.
4444 if [string match "" $compiler] {
4445 return ""
4446 } else {
4447 return false
4448 }
4449 }
4450
4451 # If no arg, return the compiler_info string.
4452 if [string match "" $compiler] {
4453 return $compiler_info_cache($language)
4454 }
4455
4456 return [string match $compiler $compiler_info_cache($language)]
4457 }
4458
4459 # Return true if the C compiler is GCC, otherwise, return false.
4460
4461 proc is_c_compiler_gcc {} {
4462 set compiler_info [test_compiler_info]
4463 set gcc_compiled false
4464 regexp "^gcc-(\[0-9\]+)-" "$compiler_info" matchall gcc_compiled
4465 return $gcc_compiled
4466 }
4467
4468 # Return the gcc major version, or -1.
4469 # For gcc 4.8.5, the major version is 4.8.
4470 # For gcc 7.5.0, the major version 7.
4471 # The COMPILER and LANGUAGE arguments are as for test_compiler_info.
4472
4473 proc gcc_major_version { {compiler "gcc-*"} {language "c"} } {
4474 global decimal
4475 if { ![test_compiler_info $compiler $language] } {
4476 return -1
4477 }
4478 # Strip "gcc-*" to "gcc".
4479 regsub -- {-.*} $compiler "" compiler
4480 set res [regexp $compiler-($decimal)-($decimal)- \
4481 [test_compiler_info "" $language] \
4482 dummy_var major minor]
4483 if { $res != 1 } {
4484 return -1
4485 }
4486 if { $major >= 5} {
4487 return $major
4488 }
4489 return $major.$minor
4490 }
4491
4492 proc current_target_name { } {
4493 global target_info
4494 if [info exists target_info(target,name)] {
4495 set answer $target_info(target,name)
4496 } else {
4497 set answer ""
4498 }
4499 return $answer
4500 }
4501
4502 set gdb_wrapper_initialized 0
4503 set gdb_wrapper_target ""
4504 set gdb_wrapper_file ""
4505 set gdb_wrapper_flags ""
4506
4507 proc gdb_wrapper_init { args } {
4508 global gdb_wrapper_initialized
4509 global gdb_wrapper_file
4510 global gdb_wrapper_flags
4511 global gdb_wrapper_target
4512
4513 if { $gdb_wrapper_initialized == 1 } { return; }
4514
4515 if {[target_info exists needs_status_wrapper] && \
4516 [target_info needs_status_wrapper] != "0"} {
4517 set result [build_wrapper "testglue.o"]
4518 if { $result != "" } {
4519 set gdb_wrapper_file [lindex $result 0]
4520 if ![is_remote host] {
4521 set gdb_wrapper_file [file join [pwd] $gdb_wrapper_file]
4522 }
4523 set gdb_wrapper_flags [lindex $result 1]
4524 } else {
4525 warning "Status wrapper failed to build."
4526 }
4527 } else {
4528 set gdb_wrapper_file ""
4529 set gdb_wrapper_flags ""
4530 }
4531 verbose "set gdb_wrapper_file = $gdb_wrapper_file"
4532 set gdb_wrapper_initialized 1
4533 set gdb_wrapper_target [current_target_name]
4534 }
4535
4536 # Determine options that we always want to pass to the compiler.
4537 gdb_caching_proc universal_compile_options {
4538 set me "universal_compile_options"
4539 set options {}
4540
4541 set src [standard_temp_file ccopts[pid].c]
4542 set obj [standard_temp_file ccopts[pid].o]
4543
4544 gdb_produce_source $src {
4545 int foo(void) { return 0; }
4546 }
4547
4548 # Try an option for disabling colored diagnostics. Some compilers
4549 # yield colored diagnostics by default (when run from a tty) unless
4550 # such an option is specified.
4551 set opt "additional_flags=-fdiagnostics-color=never"
4552 set lines [target_compile $src $obj object [list "quiet" $opt]]
4553 if {[string match "" $lines]} {
4554 # Seems to have worked; use the option.
4555 lappend options $opt
4556 }
4557 file delete $src
4558 file delete $obj
4559
4560 verbose "$me: returning $options" 2
4561 return $options
4562 }
4563
4564 # Compile the code in $code to a file based on $name, using the flags
4565 # $compile_flag as well as debug, nowarning and quiet.
4566 # Return 1 if code can be compiled
4567 # Leave the file name of the resulting object in the upvar object.
4568
4569 proc gdb_simple_compile {name code {type object} {compile_flags {}} {object obj}} {
4570 upvar $object obj
4571
4572 switch -regexp -- $type {
4573 "executable" {
4574 set postfix "x"
4575 }
4576 "object" {
4577 set postfix "o"
4578 }
4579 "preprocess" {
4580 set postfix "i"
4581 }
4582 "assembly" {
4583 set postfix "s"
4584 }
4585 }
4586 set ext "c"
4587 foreach flag $compile_flags {
4588 if { "$flag" == "go" } {
4589 set ext "go"
4590 break
4591 }
4592 }
4593 set src [standard_temp_file $name-[pid].$ext]
4594 set obj [standard_temp_file $name-[pid].$postfix]
4595 set compile_flags [concat $compile_flags {debug nowarnings quiet}]
4596
4597 gdb_produce_source $src $code
4598
4599 verbose "$name: compiling testfile $src" 2
4600 set lines [gdb_compile $src $obj $type $compile_flags]
4601
4602 file delete $src
4603
4604 if {![string match "" $lines]} {
4605 verbose "$name: compilation failed, returning 0" 2
4606 return 0
4607 }
4608 return 1
4609 }
4610
4611 # Compile the code in $code to a file based on $name, using the flags
4612 # $compile_flag as well as debug, nowarning and quiet.
4613 # Return 1 if code can be compiled
4614 # Delete all created files and objects.
4615
4616 proc gdb_can_simple_compile {name code {type object} {compile_flags ""}} {
4617 set ret [gdb_simple_compile $name $code $type $compile_flags temp_obj]
4618 file delete $temp_obj
4619 return $ret
4620 }
4621
4622 # Some targets need to always link a special object in. Save its path here.
4623 global gdb_saved_set_unbuffered_mode_obj
4624 set gdb_saved_set_unbuffered_mode_obj ""
4625
4626 # Compile source files specified by SOURCE into a binary of type TYPE at path
4627 # DEST. gdb_compile is implemented using DejaGnu's target_compile, so the type
4628 # parameter and most options are passed directly to it.
4629 #
4630 # The type can be one of the following:
4631 #
4632 # - object: Compile into an object file.
4633 # - executable: Compile and link into an executable.
4634 # - preprocess: Preprocess the source files.
4635 # - assembly: Generate assembly listing.
4636 #
4637 # The following options are understood and processed by gdb_compile:
4638 #
4639 # - shlib=so_path: Add SO_PATH to the sources, and enable some target-specific
4640 # quirks to be able to use shared libraries.
4641 # - shlib_load: Link with appropriate libraries to allow the test to
4642 # dynamically load libraries at runtime. For example, on Linux, this adds
4643 # -ldl so that the test can use dlopen.
4644 # - nowarnings: Inhibit all compiler warnings.
4645 # - pie: Force creation of PIE executables.
4646 # - nopie: Prevent creation of PIE executables.
4647 # - macros: Add the required compiler flag to include macro information in
4648 # debug information
4649 # - text_segment=addr: Tell the linker to place the text segment at ADDR.
4650 # - build-id: Ensure the final binary includes a build-id.
4651 #
4652 # And here are some of the not too obscure options understood by DejaGnu that
4653 # influence the compilation:
4654 #
4655 # - additional_flags=flag: Add FLAG to the compiler flags.
4656 # - libs=library: Add LIBRARY to the libraries passed to the linker. The
4657 # argument can be a file, in which case it's added to the sources, or a
4658 # linker flag.
4659 # - ldflags=flag: Add FLAG to the linker flags.
4660 # - incdir=path: Add PATH to the searched include directories.
4661 # - libdir=path: Add PATH to the linker searched directories.
4662 # - ada, c++, f90, go, rust: Compile the file as Ada, C++,
4663 # Fortran 90, Go or Rust.
4664 # - debug: Build with debug information.
4665 # - optimize: Build with optimization.
4666
4667 proc gdb_compile {source dest type options} {
4668 global GDB_TESTCASE_OPTIONS
4669 global gdb_wrapper_file
4670 global gdb_wrapper_flags
4671 global srcdir
4672 global objdir
4673 global gdb_saved_set_unbuffered_mode_obj
4674
4675 set outdir [file dirname $dest]
4676
4677 # If this is set, calling test_compiler_info will cause recursion.
4678 if { [lsearch -exact $options getting_compiler_info] == -1 } {
4679 set getting_compiler_info false
4680 } else {
4681 set getting_compiler_info true
4682 }
4683
4684 # Add platform-specific options if a shared library was specified using
4685 # "shlib=librarypath" in OPTIONS.
4686 set new_options {}
4687 if {[lsearch -exact $options rust] != -1} {
4688 # -fdiagnostics-color is not a rustcc option.
4689 } else {
4690 set new_options [universal_compile_options]
4691 }
4692
4693 # C/C++ specific settings.
4694 if {!$getting_compiler_info
4695 && [lsearch -exact $options rust] == -1
4696 && [lsearch -exact $options ada] == -1
4697 && [lsearch -exact $options f90] == -1
4698 && [lsearch -exact $options go] == -1} {
4699
4700 # Some C/C++ testcases unconditionally pass -Wno-foo as additional
4701 # options to disable some warning. That is OK with GCC, because
4702 # by design, GCC accepts any -Wno-foo option, even if it doesn't
4703 # support -Wfoo. Clang however warns about unknown -Wno-foo by
4704 # default, unless you pass -Wno-unknown-warning-option as well.
4705 # We do that here, so that individual testcases don't have to
4706 # worry about it.
4707 if {[test_compiler_info "clang-*"] || [test_compiler_info "icx-*"]} {
4708 lappend new_options "additional_flags=-Wno-unknown-warning-option"
4709 } elseif {[test_compiler_info "icc-*"]} {
4710 # This is the equivalent for the icc compiler.
4711 lappend new_options "additional_flags=-diag-disable=10148"
4712 }
4713
4714 # icpx/icx give the following warning if '-g' is used without '-O'.
4715 #
4716 # icpx: remark: Note that use of '-g' without any
4717 # optimization-level option will turn off most compiler
4718 # optimizations similar to use of '-O0'
4719 #
4720 # The warning makes dejagnu think that compilation has failed.
4721 #
4722 # Furthermore, if no -O flag is passed, icx and icc optimize
4723 # the code by default. This breaks assumptions in many GDB
4724 # tests that the code is unoptimized by default.
4725 #
4726 # To fix both problems, pass the -O0 flag explicitly, if no
4727 # optimization option is given.
4728 if {[test_compiler_info "icx-*"] || [test_compiler_info "icc-*"]} {
4729 if {[lsearch $options optimize=*] == -1
4730 && [lsearch $options additional_flags=-O*] == -1} {
4731 lappend new_options "optimize=-O0"
4732 }
4733 }
4734
4735 # Starting with 2021.7.0 (recognized as icc-20-21-7 by GDB) icc and
4736 # icpc are marked as deprecated and both compilers emit the remark
4737 # #10441. To let GDB still compile successfully, we disable these
4738 # warnings here.
4739 if {([lsearch -exact $options c++] != -1
4740 && [test_compiler_info {icc-20-21-[7-9]} c++])
4741 || [test_compiler_info {icc-20-21-[7-9]}]} {
4742 lappend new_options "additional_flags=-diag-disable=10441"
4743 }
4744 }
4745
4746 # If the 'build-id' option is used, then ensure that we generate a
4747 # build-id. GCC does this by default, but Clang does not, so
4748 # enable it now.
4749 if {[lsearch -exact $options build-id] > 0
4750 && [test_compiler_info "clang-*"]} {
4751 lappend new_options "additional_flags=-Wl,--build-id"
4752 }
4753
4754 # Treating .c input files as C++ is deprecated in Clang, so
4755 # explicitly force C++ language.
4756 if { !$getting_compiler_info
4757 && [lsearch -exact $options c++] != -1
4758 && [string match *.c $source] != 0 } {
4759
4760 # gdb_compile cannot handle this combination of options, the
4761 # result is a command like "clang -x c++ foo.c bar.so -o baz"
4762 # which tells Clang to treat bar.so as C++. The solution is
4763 # to call gdb_compile twice--once to compile, once to link--
4764 # either directly, or via build_executable_from_specs.
4765 if { [lsearch $options shlib=*] != -1 } {
4766 error "incompatible gdb_compile options"
4767 }
4768
4769 if {[test_compiler_info "clang-*"]} {
4770 lappend new_options early_flags=-x\ c++
4771 }
4772 }
4773
4774 # Place (and look for) Fortran `.mod` files in the output
4775 # directory for this specific test. For Intel compilers the -J
4776 # option is not supported so instead use the -module flag.
4777 # Additionally, Intel compilers need the -debug-parameters flag set to
4778 # emit debug info for all parameters in modules.
4779 #
4780 # ifx gives the following warning if '-g' is used without '-O'.
4781 #
4782 # ifx: remark #10440: Note that use of a debug option
4783 # without any optimization-level option will turnoff most
4784 # compiler optimizations similar to use of '-O0'
4785 #
4786 # The warning makes dejagnu think that compilation has failed.
4787 #
4788 # Furthermore, if no -O flag is passed, Intel compilers optimize
4789 # the code by default. This breaks assumptions in many GDB
4790 # tests that the code is unoptimized by default.
4791 #
4792 # To fix both problems, pass the -O0 flag explicitly, if no
4793 # optimization option is given.
4794 if { !$getting_compiler_info && [lsearch -exact $options f90] != -1 } {
4795 # Fortran compile.
4796 set mod_path [standard_output_file ""]
4797 if { [test_compiler_info {gfortran-*} f90] } {
4798 lappend new_options "additional_flags=-J${mod_path}"
4799 } elseif { [test_compiler_info {ifort-*} f90]
4800 || [test_compiler_info {ifx-*} f90] } {
4801 lappend new_options "additional_flags=-module ${mod_path}"
4802 lappend new_options "additional_flags=-debug-parameters all"
4803
4804 if {[lsearch $options optimize=*] == -1
4805 && [lsearch $options additional_flags=-O*] == -1} {
4806 lappend new_options "optimize=-O0"
4807 }
4808 }
4809 }
4810
4811 set shlib_found 0
4812 set shlib_load 0
4813 foreach opt $options {
4814 if {[regexp {^shlib=(.*)} $opt dummy_var shlib_name]
4815 && $type == "executable"} {
4816 if [test_compiler_info "xlc-*"] {
4817 # IBM xlc compiler doesn't accept shared library named other
4818 # than .so: use "-Wl," to bypass this
4819 lappend source "-Wl,$shlib_name"
4820 } elseif { ([istarget "*-*-mingw*"]
4821 || [istarget *-*-cygwin*]
4822 || [istarget *-*-pe*])} {
4823 lappend source "${shlib_name}.a"
4824 } else {
4825 lappend source $shlib_name
4826 }
4827 if { $shlib_found == 0 } {
4828 set shlib_found 1
4829 if { ([istarget "*-*-mingw*"]
4830 || [istarget *-*-cygwin*]) } {
4831 lappend new_options "ldflags=-Wl,--enable-auto-import"
4832 }
4833 if { [test_compiler_info "gcc-*"] || [test_compiler_info "clang-*"] } {
4834 # Undo debian's change in the default.
4835 # Put it at the front to not override any user-provided
4836 # value, and to make sure it appears in front of all the
4837 # shlibs!
4838 lappend new_options "early_flags=-Wl,--no-as-needed"
4839 }
4840 }
4841 } elseif { $opt == "shlib_load" && $type == "executable" } {
4842 set shlib_load 1
4843 } elseif { $opt == "getting_compiler_info" } {
4844 # Ignore this setting here as it has been handled earlier in this
4845 # procedure. Do not append it to new_options as this will cause
4846 # recursion.
4847 } elseif {[regexp "^text_segment=(.*)" $opt dummy_var addr]} {
4848 if { [linker_supports_Ttext_segment_flag] } {
4849 # For GNU ld.
4850 lappend new_options "ldflags=-Wl,-Ttext-segment=$addr"
4851 } elseif { [linker_supports_image_base_flag] } {
4852 # For LLVM's lld.
4853 lappend new_options "ldflags=-Wl,--image-base=$addr"
4854 } elseif { [linker_supports_Ttext_flag] } {
4855 # For old GNU gold versions.
4856 lappend new_options "ldflags=-Wl,-Ttext=$addr"
4857 } else {
4858 error "Don't know how to handle text_segment option."
4859 }
4860 } else {
4861 lappend new_options $opt
4862 }
4863 }
4864
4865 # Ensure stack protector is disabled for GCC, as this causes problems with
4866 # DWARF line numbering.
4867 # See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88432
4868 # This option defaults to on for Debian/Ubuntu.
4869 if { !$getting_compiler_info
4870 && [test_compiler_info {gcc-*-*}]
4871 && !([test_compiler_info {gcc-[0-3]-*}]
4872 || [test_compiler_info {gcc-4-0-*}])
4873 && [lsearch -exact $options rust] == -1} {
4874 # Put it at the front to not override any user-provided value.
4875 lappend new_options "early_flags=-fno-stack-protector"
4876 }
4877
4878 # Because we link with libraries using their basename, we may need
4879 # (depending on the platform) to set a special rpath value, to allow
4880 # the executable to find the libraries it depends on.
4881 if { $shlib_load || $shlib_found } {
4882 if { ([istarget "*-*-mingw*"]
4883 || [istarget *-*-cygwin*]
4884 || [istarget *-*-pe*]) } {
4885 # Do not need anything.
4886 } elseif { [istarget *-*-freebsd*] || [istarget *-*-openbsd*] } {
4887 lappend new_options "ldflags=-Wl,-rpath,${outdir}"
4888 } else {
4889 if { $shlib_load } {
4890 lappend new_options "libs=-ldl"
4891 }
4892 lappend new_options "ldflags=-Wl,-rpath,\\\$ORIGIN"
4893 }
4894 }
4895 set options $new_options
4896
4897 if [info exists GDB_TESTCASE_OPTIONS] {
4898 lappend options "additional_flags=$GDB_TESTCASE_OPTIONS"
4899 }
4900 verbose "options are $options"
4901 verbose "source is $source $dest $type $options"
4902
4903 gdb_wrapper_init
4904
4905 if {[target_info exists needs_status_wrapper] && \
4906 [target_info needs_status_wrapper] != "0" && \
4907 $gdb_wrapper_file != "" } {
4908 lappend options "libs=${gdb_wrapper_file}"
4909 lappend options "ldflags=${gdb_wrapper_flags}"
4910 }
4911
4912 # Replace the "nowarnings" option with the appropriate additional_flags
4913 # to disable compiler warnings.
4914 set nowarnings [lsearch -exact $options nowarnings]
4915 if {$nowarnings != -1} {
4916 if [target_info exists gdb,nowarnings_flag] {
4917 set flag "additional_flags=[target_info gdb,nowarnings_flag]"
4918 } else {
4919 set flag "additional_flags=-w"
4920 }
4921 set options [lreplace $options $nowarnings $nowarnings $flag]
4922 }
4923
4924 # Replace the "pie" option with the appropriate compiler and linker flags
4925 # to enable PIE executables.
4926 set pie [lsearch -exact $options pie]
4927 if {$pie != -1} {
4928 if [target_info exists gdb,pie_flag] {
4929 set flag "additional_flags=[target_info gdb,pie_flag]"
4930 } else {
4931 # For safety, use fPIE rather than fpie. On AArch64, m68k, PowerPC
4932 # and SPARC, fpie can cause compile errors due to the GOT exceeding
4933 # a maximum size. On other architectures the two flags are
4934 # identical (see the GCC manual). Note Debian9 and Ubuntu16.10
4935 # onwards default GCC to using fPIE. If you do require fpie, then
4936 # it can be set using the pie_flag.
4937 set flag "additional_flags=-fPIE"
4938 }
4939 set options [lreplace $options $pie $pie $flag]
4940
4941 if [target_info exists gdb,pie_ldflag] {
4942 set flag "ldflags=[target_info gdb,pie_ldflag]"
4943 } else {
4944 set flag "ldflags=-pie"
4945 }
4946 lappend options "$flag"
4947 }
4948
4949 # Replace the "nopie" option with the appropriate compiler and linker
4950 # flags to disable PIE executables.
4951 set nopie [lsearch -exact $options nopie]
4952 if {$nopie != -1} {
4953 if [target_info exists gdb,nopie_flag] {
4954 set flag "additional_flags=[target_info gdb,nopie_flag]"
4955 } else {
4956 set flag "additional_flags=-fno-pie"
4957 }
4958 set options [lreplace $options $nopie $nopie $flag]
4959
4960 if [target_info exists gdb,nopie_ldflag] {
4961 set flag "ldflags=[target_info gdb,nopie_ldflag]"
4962 } else {
4963 set flag "ldflags=-no-pie"
4964 }
4965 lappend options "$flag"
4966 }
4967
4968 set macros [lsearch -exact $options macros]
4969 if {$macros != -1} {
4970 if { [test_compiler_info "clang-*"] } {
4971 set flag "additional_flags=-fdebug-macro"
4972 } else {
4973 set flag "additional_flags=-g3"
4974 }
4975
4976 set options [lreplace $options $macros $macros $flag]
4977 }
4978
4979 if { $type == "executable" } {
4980 if { ([istarget "*-*-mingw*"]
4981 || [istarget "*-*-*djgpp"]
4982 || [istarget "*-*-cygwin*"])} {
4983 # Force output to unbuffered mode, by linking in an object file
4984 # with a global contructor that calls setvbuf.
4985 #
4986 # Compile the special object separately for two reasons:
4987 # 1) Insulate it from $options.
4988 # 2) Avoid compiling it for every gdb_compile invocation,
4989 # which is time consuming, especially if we're remote
4990 # host testing.
4991 #
4992 if { $gdb_saved_set_unbuffered_mode_obj == "" } {
4993 verbose "compiling gdb_saved_set_unbuffered_obj"
4994 set unbuf_src ${srcdir}/lib/set_unbuffered_mode.c
4995 set unbuf_obj ${objdir}/set_unbuffered_mode.o
4996
4997 set result [gdb_compile "${unbuf_src}" "${unbuf_obj}" object {nowarnings}]
4998 if { $result != "" } {
4999 return $result
5000 }
5001 if {[is_remote host]} {
5002 set gdb_saved_set_unbuffered_mode_obj set_unbuffered_mode_saved.o
5003 } else {
5004 set gdb_saved_set_unbuffered_mode_obj ${objdir}/set_unbuffered_mode_saved.o
5005 }
5006 # Link a copy of the output object, because the
5007 # original may be automatically deleted.
5008 remote_download host $unbuf_obj $gdb_saved_set_unbuffered_mode_obj
5009 } else {
5010 verbose "gdb_saved_set_unbuffered_obj already compiled"
5011 }
5012
5013 # Rely on the internal knowledge that the global ctors are ran in
5014 # reverse link order. In that case, we can use ldflags to
5015 # avoid copying the object file to the host multiple
5016 # times.
5017 # This object can only be added if standard libraries are
5018 # used. Thus, we need to disable it if -nostdlib option is used
5019 if {[lsearch -regexp $options "-nostdlib"] < 0 } {
5020 lappend options "ldflags=$gdb_saved_set_unbuffered_mode_obj"
5021 }
5022 }
5023 }
5024
5025 cond_wrap [expr $pie != -1 || $nopie != -1] \
5026 with_PIE_multilib_flags_filtered {
5027 set result [target_compile $source $dest $type $options]
5028 }
5029
5030 # Prune uninteresting compiler (and linker) output.
5031 regsub "Creating library file: \[^\r\n\]*\[\r\n\]+" $result "" result
5032
5033 # Starting with 2021.7.0 icc and icpc are marked as deprecated and both
5034 # compilers emit a remark #10441. To let GDB still compile successfully,
5035 # we disable these warnings. When $getting_compiler_info is true however,
5036 # we do not yet know the compiler (nor its version) and instead prune these
5037 # lines from the compiler output to let the get_compiler_info pass.
5038 if {$getting_compiler_info} {
5039 regsub \
5040 "(icc|icpc): remark #10441: The Intel\\(R\\) C\\+\\+ Compiler Classic \\(ICC\\) is deprecated\[^\r\n\]*" \
5041 "$result" "" result
5042 }
5043
5044 regsub "\[\r\n\]*$" "$result" "" result
5045 regsub "^\[\r\n\]*" "$result" "" result
5046
5047 if { $type == "executable" && $result == "" \
5048 && ($nopie != -1 || $pie != -1) } {
5049 set is_pie [exec_is_pie "$dest"]
5050 if { $nopie != -1 && $is_pie == 1 } {
5051 set result "nopie failed to prevent PIE executable"
5052 } elseif { $pie != -1 && $is_pie == 0 } {
5053 set result "pie failed to generate PIE executable"
5054 }
5055 }
5056
5057 if {[lsearch $options quiet] < 0} {
5058 if { $result != "" } {
5059 clone_output "gdb compile failed, $result"
5060 }
5061 }
5062 return $result
5063 }
5064
5065
5066 # This is just like gdb_compile, above, except that it tries compiling
5067 # against several different thread libraries, to see which one this
5068 # system has.
5069 proc gdb_compile_pthreads {source dest type options} {
5070 if {$type != "executable"} {
5071 return [gdb_compile $source $dest $type $options]
5072 }
5073 set built_binfile 0
5074 set why_msg "unrecognized error"
5075 foreach lib {-lpthreads -lpthread -lthread ""} {
5076 # This kind of wipes out whatever libs the caller may have
5077 # set. Or maybe theirs will override ours. How infelicitous.
5078 set options_with_lib [concat $options [list libs=$lib quiet]]
5079 set ccout [gdb_compile $source $dest $type $options_with_lib]
5080 switch -regexp -- $ccout {
5081 ".*no posix threads support.*" {
5082 set why_msg "missing threads include file"
5083 break
5084 }
5085 ".*cannot open -lpthread.*" {
5086 set why_msg "missing runtime threads library"
5087 }
5088 ".*Can't find library for -lpthread.*" {
5089 set why_msg "missing runtime threads library"
5090 }
5091 {^$} {
5092 pass "successfully compiled posix threads test case"
5093 set built_binfile 1
5094 break
5095 }
5096 }
5097 }
5098 if {!$built_binfile} {
5099 unsupported "couldn't compile [file tail $source]: ${why_msg}"
5100 return -1
5101 }
5102 }
5103
5104 # Build a shared library from SOURCES.
5105
5106 proc gdb_compile_shlib_1 {sources dest options} {
5107 set obj_options $options
5108
5109 set ada 0
5110 if { [lsearch -exact $options "ada"] >= 0 } {
5111 set ada 1
5112 }
5113
5114 if { [lsearch -exact $options "c++"] >= 0 } {
5115 set info_options "c++"
5116 } elseif { [lsearch -exact $options "f90"] >= 0 } {
5117 set info_options "f90"
5118 } else {
5119 set info_options "c"
5120 }
5121
5122 switch -glob [test_compiler_info "" ${info_options}] {
5123 "xlc-*" {
5124 lappend obj_options "additional_flags=-qpic"
5125 }
5126 "clang-*" {
5127 if { [istarget "*-*-cygwin*"]
5128 || [istarget "*-*-mingw*"] } {
5129 lappend obj_options "additional_flags=-fPIC"
5130 } else {
5131 lappend obj_options "additional_flags=-fpic"
5132 }
5133 }
5134 "gcc-*" {
5135 if { [istarget "powerpc*-*-aix*"]
5136 || [istarget "rs6000*-*-aix*"]
5137 || [istarget "*-*-cygwin*"]
5138 || [istarget "*-*-mingw*"]
5139 || [istarget "*-*-pe*"] } {
5140 lappend obj_options "additional_flags=-fPIC"
5141 } else {
5142 lappend obj_options "additional_flags=-fpic"
5143 }
5144 }
5145 "icc-*" {
5146 lappend obj_options "additional_flags=-fpic"
5147 }
5148 default {
5149 # don't know what the compiler is...
5150 lappend obj_options "additional_flags=-fPIC"
5151 }
5152 }
5153
5154 set outdir [file dirname $dest]
5155 set objects ""
5156 foreach source $sources {
5157 if {[file extension $source] == ".o"} {
5158 # Already a .o file.
5159 lappend objects $source
5160 continue
5161 }
5162
5163 set sourcebase [file tail $source]
5164
5165 if { $ada } {
5166 # Gnatmake doesn't like object name foo.adb.o, use foo.o.
5167 set sourcebase [file rootname $sourcebase]
5168 }
5169 set object ${outdir}/${sourcebase}.o
5170
5171 if { $ada } {
5172 # Use gdb_compile_ada_1 instead of gdb_compile_ada to avoid the
5173 # PASS message.
5174 if {[gdb_compile_ada_1 $source $object object \
5175 $obj_options] != ""} {
5176 return -1
5177 }
5178 } else {
5179 if {[gdb_compile $source $object object \
5180 $obj_options] != ""} {
5181 return -1
5182 }
5183 }
5184
5185 lappend objects $object
5186 }
5187
5188 set link_options $options
5189 if { $ada } {
5190 # If we try to use gnatmake for the link, it will interpret the
5191 # object file as an .adb file. Remove ada from the options to
5192 # avoid it.
5193 set idx [lsearch $link_options "ada"]
5194 set link_options [lreplace $link_options $idx $idx]
5195 }
5196 if [test_compiler_info "xlc-*"] {
5197 lappend link_options "additional_flags=-qmkshrobj"
5198 } else {
5199 lappend link_options "additional_flags=-shared"
5200
5201 if { ([istarget "*-*-mingw*"]
5202 || [istarget *-*-cygwin*]
5203 || [istarget *-*-pe*]) } {
5204 if { [is_remote host] } {
5205 set name [file tail ${dest}]
5206 } else {
5207 set name ${dest}
5208 }
5209 lappend link_options "ldflags=-Wl,--out-implib,${name}.a"
5210 } else {
5211 # Set the soname of the library. This causes the linker on ELF
5212 # systems to create the DT_NEEDED entry in the executable referring
5213 # to the soname of the library, and not its absolute path. This
5214 # (using the absolute path) would be problem when testing on a
5215 # remote target.
5216 #
5217 # In conjunction with setting the soname, we add the special
5218 # rpath=$ORIGIN value when building the executable, so that it's
5219 # able to find the library in its own directory.
5220 set destbase [file tail $dest]
5221 lappend link_options "ldflags=-Wl,-soname,$destbase"
5222 }
5223 }
5224 if {[gdb_compile "${objects}" "${dest}" executable $link_options] != ""} {
5225 return -1
5226 }
5227 if { [is_remote host]
5228 && ([istarget "*-*-mingw*"]
5229 || [istarget *-*-cygwin*]
5230 || [istarget *-*-pe*]) } {
5231 set dest_tail_name [file tail ${dest}]
5232 remote_upload host $dest_tail_name.a ${dest}.a
5233 remote_file host delete $dest_tail_name.a
5234 }
5235
5236 return ""
5237 }
5238
5239 # Ignore FLAGS in target board multilib_flags while executing BODY.
5240
5241 proc with_multilib_flags_filtered { flags body } {
5242 global board
5243
5244 # Ignore flags in multilib_flags.
5245 set board [target_info name]
5246 set multilib_flags_orig [board_info $board multilib_flags]
5247 set multilib_flags ""
5248 foreach op $multilib_flags_orig {
5249 if { [lsearch -exact $flags $op] == -1 } {
5250 append multilib_flags " $op"
5251 }
5252 }
5253
5254 save_target_board_info { multilib_flags } {
5255 unset_board_info multilib_flags
5256 set_board_info multilib_flags "$multilib_flags"
5257 set result [uplevel 1 $body]
5258 }
5259
5260 return $result
5261 }
5262
5263 # Ignore PIE-related flags in target board multilib_flags while executing BODY.
5264
5265 proc with_PIE_multilib_flags_filtered { body } {
5266 set pie_flags [list "-pie" "-no-pie" "-fPIE" "-fno-PIE"]
5267 return [uplevel 1 [list with_multilib_flags_filtered $pie_flags $body]]
5268 }
5269
5270 # Build a shared library from SOURCES. Ignore target boards PIE-related
5271 # multilib_flags.
5272
5273 proc gdb_compile_shlib {sources dest options} {
5274 with_PIE_multilib_flags_filtered {
5275 set result [gdb_compile_shlib_1 $sources $dest $options]
5276 }
5277
5278 return $result
5279 }
5280
5281 # This is just like gdb_compile_shlib, above, except that it tries compiling
5282 # against several different thread libraries, to see which one this
5283 # system has.
5284 proc gdb_compile_shlib_pthreads {sources dest options} {
5285 set built_binfile 0
5286 set why_msg "unrecognized error"
5287 foreach lib {-lpthreads -lpthread -lthread ""} {
5288 # This kind of wipes out whatever libs the caller may have
5289 # set. Or maybe theirs will override ours. How infelicitous.
5290 set options_with_lib [concat $options [list libs=$lib quiet]]
5291 set ccout [gdb_compile_shlib $sources $dest $options_with_lib]
5292 switch -regexp -- $ccout {
5293 ".*no posix threads support.*" {
5294 set why_msg "missing threads include file"
5295 break
5296 }
5297 ".*cannot open -lpthread.*" {
5298 set why_msg "missing runtime threads library"
5299 }
5300 ".*Can't find library for -lpthread.*" {
5301 set why_msg "missing runtime threads library"
5302 }
5303 {^$} {
5304 pass "successfully compiled posix threads shlib test case"
5305 set built_binfile 1
5306 break
5307 }
5308 }
5309 }
5310 if {!$built_binfile} {
5311 unsupported "couldn't compile $sources: ${why_msg}"
5312 return -1
5313 }
5314 }
5315
5316 # This is just like gdb_compile_pthreads, above, except that we always add the
5317 # objc library for compiling Objective-C programs
5318 proc gdb_compile_objc {source dest type options} {
5319 set built_binfile 0
5320 set why_msg "unrecognized error"
5321 foreach lib {-lobjc -lpthreads -lpthread -lthread solaris} {
5322 # This kind of wipes out whatever libs the caller may have
5323 # set. Or maybe theirs will override ours. How infelicitous.
5324 if { $lib == "solaris" } {
5325 set lib "-lpthread -lposix4"
5326 }
5327 if { $lib != "-lobjc" } {
5328 set lib "-lobjc $lib"
5329 }
5330 set options_with_lib [concat $options [list libs=$lib quiet]]
5331 set ccout [gdb_compile $source $dest $type $options_with_lib]
5332 switch -regexp -- $ccout {
5333 ".*no posix threads support.*" {
5334 set why_msg "missing threads include file"
5335 break
5336 }
5337 ".*cannot open -lpthread.*" {
5338 set why_msg "missing runtime threads library"
5339 }
5340 ".*Can't find library for -lpthread.*" {
5341 set why_msg "missing runtime threads library"
5342 }
5343 {^$} {
5344 pass "successfully compiled objc with posix threads test case"
5345 set built_binfile 1
5346 break
5347 }
5348 }
5349 }
5350 if {!$built_binfile} {
5351 unsupported "couldn't compile [file tail $source]: ${why_msg}"
5352 return -1
5353 }
5354 }
5355
5356 # Build an OpenMP program from SOURCE. See prefatory comment for
5357 # gdb_compile, above, for discussion of the parameters to this proc.
5358
5359 proc gdb_compile_openmp {source dest type options} {
5360 lappend options "additional_flags=-fopenmp"
5361 return [gdb_compile $source $dest $type $options]
5362 }
5363
5364 # Send a command to GDB.
5365 # For options for TYPE see gdb_stdin_log_write
5366
5367 proc send_gdb { string {type standard}} {
5368 gdb_stdin_log_write $string $type
5369 return [remote_send host "$string"]
5370 }
5371
5372 # Send STRING to the inferior's terminal.
5373
5374 proc send_inferior { string } {
5375 global inferior_spawn_id
5376
5377 if {[catch "send -i $inferior_spawn_id -- \$string" errorInfo]} {
5378 return "$errorInfo"
5379 } else {
5380 return ""
5381 }
5382 }
5383
5384 #
5385 #
5386
5387 proc gdb_expect { args } {
5388 if { [llength $args] == 2 && [lindex $args 0] != "-re" } {
5389 set atimeout [lindex $args 0]
5390 set expcode [list [lindex $args 1]]
5391 } else {
5392 set expcode $args
5393 }
5394
5395 # A timeout argument takes precedence, otherwise of all the timeouts
5396 # select the largest.
5397 if [info exists atimeout] {
5398 set tmt $atimeout
5399 } else {
5400 set tmt [get_largest_timeout]
5401 }
5402
5403 set code [catch \
5404 {uplevel remote_expect host $tmt $expcode} string]
5405
5406 if {$code == 1} {
5407 global errorInfo errorCode
5408
5409 return -code error -errorinfo $errorInfo -errorcode $errorCode $string
5410 } else {
5411 return -code $code $string
5412 }
5413 }
5414
5415 # gdb_expect_list TEST SENTINEL LIST -- expect a sequence of outputs
5416 #
5417 # Check for long sequence of output by parts.
5418 # TEST: is the test message to be printed with the test success/fail.
5419 # SENTINEL: Is the terminal pattern indicating that output has finished.
5420 # LIST: is the sequence of outputs to match.
5421 # If the sentinel is recognized early, it is considered an error.
5422 #
5423 # Returns:
5424 # 1 if the test failed,
5425 # 0 if the test passes,
5426 # -1 if there was an internal error.
5427
5428 proc gdb_expect_list {test sentinel list} {
5429 global gdb_prompt
5430 set index 0
5431 set ok 1
5432
5433 while { ${index} < [llength ${list}] } {
5434 set pattern [lindex ${list} ${index}]
5435 set index [expr ${index} + 1]
5436 verbose -log "gdb_expect_list pattern: /$pattern/" 2
5437 if { ${index} == [llength ${list}] } {
5438 if { ${ok} } {
5439 gdb_expect {
5440 -re "${pattern}${sentinel}" {
5441 # pass "${test}, pattern ${index} + sentinel"
5442 }
5443 -re "${sentinel}" {
5444 fail "${test} (pattern ${index} + sentinel)"
5445 set ok 0
5446 }
5447 -re ".*A problem internal to GDB has been detected" {
5448 fail "${test} (GDB internal error)"
5449 set ok 0
5450 gdb_internal_error_resync
5451 }
5452 timeout {
5453 fail "${test} (pattern ${index} + sentinel) (timeout)"
5454 set ok 0
5455 }
5456 }
5457 } else {
5458 # unresolved "${test}, pattern ${index} + sentinel"
5459 }
5460 } else {
5461 if { ${ok} } {
5462 gdb_expect {
5463 -re "${pattern}" {
5464 # pass "${test}, pattern ${index}"
5465 }
5466 -re "${sentinel}" {
5467 fail "${test} (pattern ${index})"
5468 set ok 0
5469 }
5470 -re ".*A problem internal to GDB has been detected" {
5471 fail "${test} (GDB internal error)"
5472 set ok 0
5473 gdb_internal_error_resync
5474 }
5475 timeout {
5476 fail "${test} (pattern ${index}) (timeout)"
5477 set ok 0
5478 }
5479 }
5480 } else {
5481 # unresolved "${test}, pattern ${index}"
5482 }
5483 }
5484 }
5485 if { ${ok} } {
5486 pass "${test}"
5487 return 0
5488 } else {
5489 return 1
5490 }
5491 }
5492
5493 # Spawn the gdb process.
5494 #
5495 # This doesn't expect any output or do any other initialization,
5496 # leaving those to the caller.
5497 #
5498 # Overridable function -- you can override this function in your
5499 # baseboard file.
5500
5501 proc gdb_spawn { } {
5502 default_gdb_spawn
5503 }
5504
5505 # Spawn GDB with CMDLINE_FLAGS appended to the GDBFLAGS global.
5506
5507 proc gdb_spawn_with_cmdline_opts { cmdline_flags } {
5508 global GDBFLAGS
5509
5510 set saved_gdbflags $GDBFLAGS
5511
5512 if {$GDBFLAGS != ""} {
5513 append GDBFLAGS " "
5514 }
5515 append GDBFLAGS $cmdline_flags
5516
5517 set res [gdb_spawn]
5518
5519 set GDBFLAGS $saved_gdbflags
5520
5521 return $res
5522 }
5523
5524 # Start gdb running, wait for prompt, and disable the pagers.
5525
5526 # Overridable function -- you can override this function in your
5527 # baseboard file.
5528
5529 proc gdb_start { } {
5530 default_gdb_start
5531 }
5532
5533 proc gdb_exit { } {
5534 catch default_gdb_exit
5535 }
5536
5537 # Return true if we can spawn a program on the target and attach to
5538 # it.
5539
5540 proc can_spawn_for_attach { } {
5541 # We use exp_pid to get the inferior's pid, assuming that gives
5542 # back the pid of the program. On remote boards, that would give
5543 # us instead the PID of e.g., the ssh client, etc.
5544 if {[is_remote target]} {
5545 verbose -log "can't spawn for attach (target is remote)"
5546 return 0
5547 }
5548
5549 # The "attach" command doesn't make sense when the target is
5550 # stub-like, where GDB finds the program already started on
5551 # initial connection.
5552 if {[target_info exists use_gdb_stub]} {
5553 verbose -log "can't spawn for attach (target is stub)"
5554 return 0
5555 }
5556
5557 # Assume yes.
5558 return 1
5559 }
5560
5561 # Centralize the failure checking of "attach" command.
5562 # Return 0 if attach failed, otherwise return 1.
5563
5564 proc gdb_attach { testpid args } {
5565 parse_args {
5566 {pattern ""}
5567 }
5568
5569 if { [llength $args] != 0 } {
5570 error "Unexpected arguments: $args"
5571 }
5572
5573 gdb_test_multiple "attach $testpid" "attach" {
5574 -re -wrap "Attaching to.*ptrace: Operation not permitted\\." {
5575 unsupported "$gdb_test_name (Operation not permitted)"
5576 return 0
5577 }
5578 -re -wrap "$pattern" {
5579 pass $gdb_test_name
5580 return 1
5581 }
5582 }
5583
5584 return 0
5585 }
5586
5587 # Start gdb with "--pid $TESTPID" on the command line and wait for the prompt.
5588 # Return 1 if GDB managed to start and attach to the process, 0 otherwise.
5589
5590 proc_with_prefix gdb_spawn_attach_cmdline { testpid } {
5591 if ![can_spawn_for_attach] {
5592 # The caller should have checked can_spawn_for_attach itself
5593 # before getting here.
5594 error "can't spawn for attach with this target/board"
5595 }
5596
5597 set test "start gdb with --pid"
5598 set res [gdb_spawn_with_cmdline_opts "-quiet --pid=$testpid"]
5599 if { $res != 0 } {
5600 fail $test
5601 return 0
5602 }
5603
5604 gdb_test_multiple "" "$test" {
5605 -re -wrap "ptrace: Operation not permitted\\." {
5606 unsupported "$gdb_test_name (operation not permitted)"
5607 return 0
5608 }
5609 -re -wrap "ptrace: No such process\\." {
5610 fail "$gdb_test_name (no such process)"
5611 return 0
5612 }
5613 -re -wrap "Attaching to process $testpid\r\n.*" {
5614 pass $gdb_test_name
5615 }
5616 }
5617
5618 # Check that we actually attached to a process, in case the
5619 # error message is not caught by the patterns above.
5620 gdb_test_multiple "info thread" "" {
5621 -re -wrap "No threads\\." {
5622 fail "$gdb_test_name (no thread)"
5623 }
5624 -re -wrap "Id.*" {
5625 pass $gdb_test_name
5626 return 1
5627 }
5628 }
5629
5630 return 0
5631 }
5632
5633 # Kill a progress previously started with spawn_wait_for_attach, and
5634 # reap its wait status. PROC_SPAWN_ID is the spawn id associated with
5635 # the process.
5636
5637 proc kill_wait_spawned_process { proc_spawn_id } {
5638 set pid [exp_pid -i $proc_spawn_id]
5639
5640 verbose -log "killing ${pid}"
5641 remote_exec build "kill -9 ${pid}"
5642
5643 verbose -log "closing ${proc_spawn_id}"
5644 catch "close -i $proc_spawn_id"
5645 verbose -log "waiting for ${proc_spawn_id}"
5646
5647 # If somehow GDB ends up still attached to the process here, a
5648 # blocking wait hangs until gdb is killed (or until gdb / the
5649 # ptracer reaps the exit status too, but that won't happen because
5650 # something went wrong.) Passing -nowait makes expect tell Tcl to
5651 # wait for the PID in the background. That's fine because we
5652 # don't care about the exit status. */
5653 wait -nowait -i $proc_spawn_id
5654 }
5655
5656 # Returns the process id corresponding to the given spawn id.
5657
5658 proc spawn_id_get_pid { spawn_id } {
5659 set testpid [exp_pid -i $spawn_id]
5660
5661 if { [istarget "*-*-cygwin*"] } {
5662 # testpid is the Cygwin PID, GDB uses the Windows PID, which
5663 # might be different due to the way fork/exec works.
5664 set testpid [ exec ps -e | gawk "{ if (\$1 == $testpid) print \$4; }" ]
5665 }
5666
5667 return $testpid
5668 }
5669
5670 # Start a set of programs running and then wait for a bit, to be sure
5671 # that they can be attached to. Return a list of processes spawn IDs,
5672 # one element for each process spawned. It's a test error to call
5673 # this when [can_spawn_for_attach] is false.
5674
5675 proc spawn_wait_for_attach { executable_list } {
5676 set spawn_id_list {}
5677
5678 if ![can_spawn_for_attach] {
5679 # The caller should have checked can_spawn_for_attach itself
5680 # before getting here.
5681 error "can't spawn for attach with this target/board"
5682 }
5683
5684 foreach {executable} $executable_list {
5685 # Note we use Expect's spawn, not Tcl's exec, because with
5686 # spawn we control when to wait for/reap the process. That
5687 # allows killing the process by PID without being subject to
5688 # pid-reuse races.
5689 lappend spawn_id_list [remote_spawn target $executable]
5690 }
5691
5692 sleep 2
5693
5694 return $spawn_id_list
5695 }
5696
5697 #
5698 # gdb_load_cmd -- load a file into the debugger.
5699 # ARGS - additional args to load command.
5700 # return a -1 if anything goes wrong.
5701 #
5702 proc gdb_load_cmd { args } {
5703 global gdb_prompt
5704
5705 if [target_info exists gdb_load_timeout] {
5706 set loadtimeout [target_info gdb_load_timeout]
5707 } else {
5708 set loadtimeout 1600
5709 }
5710 send_gdb "load $args\n"
5711 verbose "Timeout is now $loadtimeout seconds" 2
5712 gdb_expect $loadtimeout {
5713 -re "Loading section\[^\r\]*\r\n" {
5714 exp_continue
5715 }
5716 -re "Start address\[\r\]*\r\n" {
5717 exp_continue
5718 }
5719 -re "Transfer rate\[\r\]*\r\n" {
5720 exp_continue
5721 }
5722 -re "Memory access error\[^\r\]*\r\n" {
5723 perror "Failed to load program"
5724 return -1
5725 }
5726 -re "$gdb_prompt $" {
5727 return 0
5728 }
5729 -re "(.*)\r\n$gdb_prompt " {
5730 perror "Unexpected reponse from 'load' -- $expect_out(1,string)"
5731 return -1
5732 }
5733 timeout {
5734 perror "Timed out trying to load $args."
5735 return -1
5736 }
5737 }
5738 return -1
5739 }
5740
5741 # Invoke "gcore". CORE is the name of the core file to write. TEST
5742 # is the name of the test case. This will return 1 if the core file
5743 # was created, 0 otherwise. If this fails to make a core file because
5744 # this configuration of gdb does not support making core files, it
5745 # will call "unsupported", not "fail". However, if this fails to make
5746 # a core file for some other reason, then it will call "fail".
5747
5748 proc gdb_gcore_cmd {core test} {
5749 global gdb_prompt
5750
5751 set result 0
5752
5753 set re_unsupported \
5754 "(?:Can't create a corefile|Target does not support core file generation\\.)"
5755
5756 with_timeout_factor 3 {
5757 gdb_test_multiple "gcore $core" $test {
5758 -re -wrap "Saved corefile .*" {
5759 pass $test
5760 set result 1
5761 }
5762 -re -wrap $re_unsupported {
5763 unsupported $test
5764 }
5765 }
5766 }
5767
5768 return $result
5769 }
5770
5771 # Load core file CORE. TEST is the name of the test case.
5772 # This will record a pass/fail for loading the core file.
5773 # Returns:
5774 # 1 - core file is successfully loaded
5775 # 0 - core file loaded but has a non fatal error
5776 # -1 - core file failed to load
5777
5778 proc gdb_core_cmd { core test } {
5779 global gdb_prompt
5780
5781 gdb_test_multiple "core $core" "$test" {
5782 -re "\\\[Thread debugging using \[^ \r\n\]* enabled\\\]\r\n" {
5783 exp_continue
5784 }
5785 -re " is not a core dump:.*\r\n$gdb_prompt $" {
5786 fail "$test (bad file format)"
5787 return -1
5788 }
5789 -re -wrap "[string_to_regexp $core]: No such file or directory.*" {
5790 fail "$test (file not found)"
5791 return -1
5792 }
5793 -re "Couldn't find .* registers in core file.*\r\n$gdb_prompt $" {
5794 fail "$test (incomplete note section)"
5795 return 0
5796 }
5797 -re "Core was generated by .*\r\n$gdb_prompt $" {
5798 pass "$test"
5799 return 1
5800 }
5801 -re ".*$gdb_prompt $" {
5802 fail "$test"
5803 return -1
5804 }
5805 timeout {
5806 fail "$test (timeout)"
5807 return -1
5808 }
5809 }
5810 fail "unsupported output from 'core' command"
5811 return -1
5812 }
5813
5814 # Return the filename to download to the target and load on the target
5815 # for this shared library. Normally just LIBNAME, unless shared libraries
5816 # for this target have separate link and load images.
5817
5818 proc shlib_target_file { libname } {
5819 return $libname
5820 }
5821
5822 # Return the filename GDB will load symbols from when debugging this
5823 # shared library. Normally just LIBNAME, unless shared libraries for
5824 # this target have separate link and load images.
5825
5826 proc shlib_symbol_file { libname } {
5827 return $libname
5828 }
5829
5830 # Return the filename to download to the target and load for this
5831 # executable. Normally just BINFILE unless it is renamed to something
5832 # else for this target.
5833
5834 proc exec_target_file { binfile } {
5835 return $binfile
5836 }
5837
5838 # Return the filename GDB will load symbols from when debugging this
5839 # executable. Normally just BINFILE unless executables for this target
5840 # have separate files for symbols.
5841
5842 proc exec_symbol_file { binfile } {
5843 return $binfile
5844 }
5845
5846 # Rename the executable file. Normally this is just BINFILE1 being renamed
5847 # to BINFILE2, but some targets require multiple binary files.
5848 proc gdb_rename_execfile { binfile1 binfile2 } {
5849 file rename -force [exec_target_file ${binfile1}] \
5850 [exec_target_file ${binfile2}]
5851 if { [exec_target_file ${binfile1}] != [exec_symbol_file ${binfile1}] } {
5852 file rename -force [exec_symbol_file ${binfile1}] \
5853 [exec_symbol_file ${binfile2}]
5854 }
5855 }
5856
5857 # "Touch" the executable file to update the date. Normally this is just
5858 # BINFILE, but some targets require multiple files.
5859 proc gdb_touch_execfile { binfile } {
5860 set time [clock seconds]
5861 file mtime [exec_target_file ${binfile}] $time
5862 if { [exec_target_file ${binfile}] != [exec_symbol_file ${binfile}] } {
5863 file mtime [exec_symbol_file ${binfile}] $time
5864 }
5865 }
5866
5867 # Like remote_download but provides a gdb-specific behavior.
5868 #
5869 # If the destination board is remote, the local file FROMFILE is transferred as
5870 # usual with remote_download to TOFILE on the remote board. The destination
5871 # filename is added to the CLEANFILES global, so it can be cleaned up at the
5872 # end of the test.
5873 #
5874 # If the destination board is local, the destination path TOFILE is passed
5875 # through standard_output_file, and FROMFILE is copied there.
5876 #
5877 # In both cases, if TOFILE is omitted, it defaults to the [file tail] of
5878 # FROMFILE.
5879
5880 proc gdb_remote_download {dest fromfile {tofile {}}} {
5881 # If TOFILE is not given, default to the same filename as FROMFILE.
5882 if {[string length $tofile] == 0} {
5883 set tofile [file tail $fromfile]
5884 }
5885
5886 if {[is_remote $dest]} {
5887 # When the DEST is remote, we simply send the file to DEST.
5888 global cleanfiles_target cleanfiles_host
5889
5890 set destname [remote_download $dest $fromfile $tofile]
5891 if { $dest == "target" } {
5892 lappend cleanfiles_target $destname
5893 } elseif { $dest == "host" } {
5894 lappend cleanfiles_host $destname
5895 }
5896
5897 return $destname
5898 } else {
5899 # When the DEST is local, we copy the file to the test directory (where
5900 # the executable is).
5901 #
5902 # Note that we pass TOFILE through standard_output_file, regardless of
5903 # whether it is absolute or relative, because we don't want the tests
5904 # to be able to write outside their standard output directory.
5905
5906 set tofile [standard_output_file $tofile]
5907
5908 file copy -force $fromfile $tofile
5909
5910 return $tofile
5911 }
5912 }
5913
5914 # Copy shlib FILE to the target.
5915
5916 proc gdb_download_shlib { file } {
5917 return [gdb_remote_download target [shlib_target_file $file]]
5918 }
5919
5920 # Set solib-search-path to allow gdb to locate shlib FILE.
5921
5922 proc gdb_locate_shlib { file } {
5923 global gdb_spawn_id
5924
5925 if ![info exists gdb_spawn_id] {
5926 perror "gdb_load_shlib: GDB is not running"
5927 }
5928
5929 # If the target is remote, we need to tell gdb where to find the
5930 # libraries.
5931 if { ![is_remote target] } {
5932 return
5933 }
5934
5935 # We could set this even when not testing remotely, but a user
5936 # generally won't set it unless necessary. In order to make the tests
5937 # more like the real-life scenarios, we don't set it for local testing.
5938 gdb_test "set solib-search-path [file dirname $file]" "" \
5939 "set solib-search-path for [file tail $file]"
5940 }
5941
5942 # Copy shlib FILE to the target and set solib-search-path to allow gdb to
5943 # locate it.
5944
5945 proc gdb_load_shlib { file } {
5946 set dest [gdb_download_shlib $file]
5947 gdb_locate_shlib $file
5948 return $dest
5949 }
5950
5951 #
5952 # gdb_load -- load a file into the debugger. Specifying no file
5953 # defaults to the executable currently being debugged.
5954 # The return value is 0 for success, -1 for failure.
5955 # Many files in config/*.exp override this procedure.
5956 #
5957 proc gdb_load { arg } {
5958 if { $arg != "" } {
5959 return [gdb_file_cmd $arg]
5960 }
5961 return 0
5962 }
5963
5964 #
5965 # with_set -- Execute BODY and set VAR temporary to VAL for the
5966 # duration.
5967 #
5968 proc with_set { var val body } {
5969 set save ""
5970 set show_re \
5971 "is (\[^\r\n\]+)\\."
5972 gdb_test_multiple "show $var" "" {
5973 -re -wrap $show_re {
5974 set save $expect_out(1,string)
5975 }
5976 }
5977
5978 # Handle 'set to "auto" (currently "i386")'.
5979 set save [regsub {^set to} $save ""]
5980 set save [regsub {\([^\r\n]+\)$} $save ""]
5981 set save [string trim $save]
5982 set save [regsub -all {^"|"$} $save ""]
5983
5984 if { $save == "" } {
5985 perror "Did not manage to set $var"
5986 } else {
5987 # Set var.
5988 set cmd "set $var $val"
5989 gdb_test_multiple $cmd "" {
5990 -re -wrap "^$cmd" {
5991 }
5992 -re -wrap " is set to \"?$val\"?\\." {
5993 }
5994 }
5995 }
5996
5997 set code [catch {uplevel 1 $body} result]
5998
5999 # Restore saved setting.
6000 if { $save != "" } {
6001 set cmd "set $var $save"
6002 gdb_test_multiple $cmd "" {
6003 -re -wrap "^$cmd" {
6004 }
6005 -re -wrap "is set to \"?$save\"?( \\(\[^)\]*\\))?\\." {
6006 }
6007 }
6008 }
6009
6010 if {$code == 1} {
6011 global errorInfo errorCode
6012 return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
6013 } else {
6014 return -code $code $result
6015 }
6016 }
6017
6018 #
6019 # with_complaints -- Execute BODY and set complaints temporary to N for the
6020 # duration.
6021 #
6022 proc with_complaints { n body } {
6023 return [uplevel [list with_set complaints $n $body]]
6024 }
6025
6026 #
6027 # gdb_load_no_complaints -- As gdb_load, but in addition verifies that
6028 # loading caused no symbol reading complaints.
6029 #
6030 proc gdb_load_no_complaints { arg } {
6031 global gdb_prompt gdb_file_cmd_msg decimal
6032
6033 # Temporarily set complaint to a small non-zero number.
6034 with_complaints 5 {
6035 gdb_load $arg
6036 }
6037
6038 # Verify that there were no complaints.
6039 set re \
6040 [multi_line \
6041 "^(Reading symbols from \[^\r\n\]*" \
6042 ")+(Expanding full symbols from \[^\r\n\]*" \
6043 ")?$gdb_prompt $"]
6044 gdb_assert {[regexp $re $gdb_file_cmd_msg]} "No complaints"
6045 }
6046
6047 # gdb_reload -- load a file into the target. Called before "running",
6048 # either the first time or after already starting the program once,
6049 # for remote targets. Most files that override gdb_load should now
6050 # override this instead.
6051 #
6052 # INFERIOR_ARGS contains the arguments to pass to the inferiors, as a
6053 # single string to get interpreted by a shell. If the target board
6054 # overriding gdb_reload is a "stub", then it should arrange things such
6055 # these arguments make their way to the inferior process.
6056
6057 proc gdb_reload { {inferior_args {}} } {
6058 # For the benefit of existing configurations, default to gdb_load.
6059 # Specifying no file defaults to the executable currently being
6060 # debugged.
6061 return [gdb_load ""]
6062 }
6063
6064 proc gdb_continue { function } {
6065 global decimal
6066
6067 return [gdb_test "continue" ".*Breakpoint $decimal, $function .*" "continue to $function"]
6068 }
6069
6070 # Default implementation of gdb_init.
6071 proc default_gdb_init { test_file_name } {
6072 global gdb_wrapper_initialized
6073 global gdb_wrapper_target
6074 global gdb_test_file_name
6075 global cleanfiles_target
6076 global cleanfiles_host
6077 global pf_prefix
6078
6079 # Reset the timeout value to the default. This way, any testcase
6080 # that changes the timeout value without resetting it cannot affect
6081 # the timeout used in subsequent testcases.
6082 global gdb_test_timeout
6083 global timeout
6084 set timeout $gdb_test_timeout
6085
6086 if { [regexp ".*gdb\.reverse\/.*" $test_file_name]
6087 && [target_info exists gdb_reverse_timeout] } {
6088 set timeout [target_info gdb_reverse_timeout]
6089 }
6090
6091 # If GDB_INOTIFY is given, check for writes to '.'. This is a
6092 # debugging tool to help confirm that the test suite is
6093 # parallel-safe. You need "inotifywait" from the
6094 # inotify-tools package to use this.
6095 global GDB_INOTIFY inotify_pid
6096 if {[info exists GDB_INOTIFY] && ![info exists inotify_pid]} {
6097 global outdir tool inotify_log_file
6098
6099 set exclusions {outputs temp gdb[.](log|sum) cache}
6100 set exclusion_re ([join $exclusions |])
6101
6102 set inotify_log_file [standard_temp_file inotify.out]
6103 set inotify_pid [exec inotifywait -r -m -e move,create,delete . \
6104 --exclude $exclusion_re \
6105 |& tee -a $outdir/$tool.log $inotify_log_file &]
6106
6107 # Wait for the watches; hopefully this is long enough.
6108 sleep 2
6109
6110 # Clear the log so that we don't emit a warning the first time
6111 # we check it.
6112 set fd [open $inotify_log_file w]
6113 close $fd
6114 }
6115
6116 # Block writes to all banned variables, and invocation of all
6117 # banned procedures...
6118 global banned_variables
6119 global banned_procedures
6120 global banned_traced
6121 if (!$banned_traced) {
6122 foreach banned_var $banned_variables {
6123 global "$banned_var"
6124 trace add variable "$banned_var" write error
6125 }
6126 foreach banned_proc $banned_procedures {
6127 global "$banned_proc"
6128 trace add execution "$banned_proc" enter error
6129 }
6130 set banned_traced 1
6131 }
6132
6133 # We set LC_ALL, LC_CTYPE, and LANG to C so that we get the same
6134 # messages as expected.
6135 setenv LC_ALL C
6136 setenv LC_CTYPE C
6137 setenv LANG C
6138
6139 # Don't let a .inputrc file or an existing setting of INPUTRC mess
6140 # up the test results. Certain tests (style tests and TUI tests)
6141 # want to set the terminal to a non-"dumb" value, and for those we
6142 # want to disable bracketed paste mode. Versions of Readline
6143 # before 8.0 will not understand this and will issue a warning.
6144 # We tried using a $if to guard it, but Readline 8.1 had a bug in
6145 # its version-comparison code that prevented this for working.
6146 setenv INPUTRC [cached_file inputrc "set enable-bracketed-paste off"]
6147
6148 # This disables style output, which would interfere with many
6149 # tests.
6150 setenv TERM "dumb"
6151
6152 # If DEBUGINFOD_URLS is set, gdb will try to download sources and
6153 # debug info for f.i. system libraries. Prevent this.
6154 unset -nocomplain ::env(DEBUGINFOD_URLS)
6155
6156 # Ensure that GDBHISTFILE and GDBHISTSIZE are removed from the
6157 # environment, we don't want these modifications to the history
6158 # settings.
6159 unset -nocomplain ::env(GDBHISTFILE)
6160 unset -nocomplain ::env(GDBHISTSIZE)
6161
6162 # Ensure that XDG_CONFIG_HOME is not set. Some tests setup a fake
6163 # home directory in order to test loading settings from gdbinit.
6164 # If XDG_CONFIG_HOME is set then GDB will load a gdbinit from
6165 # there (if one is present) rather than the home directory setup
6166 # in the test.
6167 unset -nocomplain ::env(XDG_CONFIG_HOME)
6168
6169 # Initialize GDB's pty with a fixed size, to make sure we avoid pagination
6170 # during startup. See "man expect" for details about stty_init.
6171 global stty_init
6172 set stty_init "rows 25 cols 80"
6173
6174 # Some tests (for example gdb.base/maint.exp) shell out from gdb to use
6175 # grep. Clear GREP_OPTIONS to make the behavior predictable,
6176 # especially having color output turned on can cause tests to fail.
6177 setenv GREP_OPTIONS ""
6178
6179 # Clear $gdbserver_reconnect_p.
6180 global gdbserver_reconnect_p
6181 set gdbserver_reconnect_p 1
6182 unset gdbserver_reconnect_p
6183
6184 # Clear $last_loaded_file
6185 global last_loaded_file
6186 unset -nocomplain last_loaded_file
6187
6188 # Reset GDB number of instances
6189 global gdb_instances
6190 set gdb_instances 0
6191
6192 set cleanfiles_target {}
6193 set cleanfiles_host {}
6194
6195 set gdb_test_file_name [file rootname [file tail $test_file_name]]
6196
6197 # Make sure that the wrapper is rebuilt
6198 # with the appropriate multilib option.
6199 if { $gdb_wrapper_target != [current_target_name] } {
6200 set gdb_wrapper_initialized 0
6201 }
6202
6203 # Unlike most tests, we have a small number of tests that generate
6204 # a very large amount of output. We therefore increase the expect
6205 # buffer size to be able to contain the entire test output. This
6206 # is especially needed by gdb.base/info-macros.exp.
6207 match_max -d 65536
6208 # Also set this value for the currently running GDB.
6209 match_max [match_max -d]
6210
6211 # We want to add the name of the TCL testcase to the PASS/FAIL messages.
6212 set pf_prefix "[file tail [file dirname $test_file_name]]/[file tail $test_file_name]:"
6213
6214 global gdb_prompt
6215 if [target_info exists gdb_prompt] {
6216 set gdb_prompt [target_info gdb_prompt]
6217 } else {
6218 set gdb_prompt "\\(gdb\\)"
6219 }
6220 global use_gdb_stub
6221 if [info exists use_gdb_stub] {
6222 unset use_gdb_stub
6223 }
6224
6225 gdb_setup_known_globals
6226
6227 if { [info procs ::gdb_tcl_unknown] != "" } {
6228 # Dejagnu overrides proc unknown. The dejagnu version may trigger in a
6229 # test-case but abort the entire test run. To fix this, we install a
6230 # local version here, which reverts dejagnu's override, and restore
6231 # dejagnu's version in gdb_finish.
6232 rename ::unknown ::dejagnu_unknown
6233 proc unknown { args } {
6234 # Use tcl's unknown.
6235 set cmd [lindex $args 0]
6236 unresolved "testcase aborted due to invalid command name: $cmd"
6237 return [uplevel 1 ::gdb_tcl_unknown $args]
6238 }
6239 }
6240 }
6241
6242 # Return a path using GDB_PARALLEL.
6243 # ARGS is a list of path elements to append to "$objdir/$GDB_PARALLEL".
6244 # GDB_PARALLEL must be defined, the caller must check.
6245 #
6246 # The default value for GDB_PARALLEL is, canonically, ".".
6247 # The catch is that tests don't expect an additional "./" in file paths so
6248 # omit any directory for the default case.
6249 # GDB_PARALLEL is written as "yes" for the default case in Makefile.in to mark
6250 # its special handling.
6251
6252 proc make_gdb_parallel_path { args } {
6253 global GDB_PARALLEL objdir
6254 set joiner [list "file" "join" $objdir]
6255 if { [info exists GDB_PARALLEL] && $GDB_PARALLEL != "yes" } {
6256 lappend joiner $GDB_PARALLEL
6257 }
6258 set joiner [concat $joiner $args]
6259 return [eval $joiner]
6260 }
6261
6262 # Turn BASENAME into a full file name in the standard output
6263 # directory. It is ok if BASENAME is the empty string; in this case
6264 # the directory is returned.
6265
6266 proc standard_output_file {basename} {
6267 global objdir subdir gdb_test_file_name
6268
6269 set dir [make_gdb_parallel_path outputs $subdir $gdb_test_file_name]
6270 file mkdir $dir
6271 # If running on MinGW, replace /c/foo with c:/foo
6272 if { [ishost *-*-mingw*] } {
6273 set dir [exec sh -c "cd ${dir} && pwd -W"]
6274 }
6275 return [file join $dir $basename]
6276 }
6277
6278 # Turn BASENAME into a full file name in the standard output directory. If
6279 # GDB has been launched more than once then append the count, starting with
6280 # a ".1" postfix.
6281
6282 proc standard_output_file_with_gdb_instance {basename} {
6283 global gdb_instances
6284 set count $gdb_instances
6285
6286 if {$count == 0} {
6287 return [standard_output_file $basename]
6288 }
6289 return [standard_output_file ${basename}.${count}]
6290 }
6291
6292 # Return the name of a file in our standard temporary directory.
6293
6294 proc standard_temp_file {basename} {
6295 # Since a particular runtest invocation is only executing a single test
6296 # file at any given time, we can use the runtest pid to build the
6297 # path of the temp directory.
6298 set dir [make_gdb_parallel_path temp [pid]]
6299 file mkdir $dir
6300 return [file join $dir $basename]
6301 }
6302
6303 # Rename file A to file B, if B does not already exists. Otherwise, leave B
6304 # as is and delete A. Return 1 if rename happened.
6305
6306 proc tentative_rename { a b } {
6307 global errorInfo errorCode
6308 set code [catch {file rename -- $a $b} result]
6309 if { $code == 1 && [lindex $errorCode 0] == "POSIX" \
6310 && [lindex $errorCode 1] == "EEXIST" } {
6311 file delete $a
6312 return 0
6313 }
6314 if {$code == 1} {
6315 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
6316 } elseif {$code > 1} {
6317 return -code $code $result
6318 }
6319 return 1
6320 }
6321
6322 # Create a file with name FILENAME and contents TXT in the cache directory.
6323 # If EXECUTABLE, mark the new file for execution.
6324
6325 proc cached_file { filename txt {executable 0}} {
6326 set filename [make_gdb_parallel_path cache $filename]
6327
6328 if { [file exists $filename] } {
6329 return $filename
6330 }
6331
6332 set dir [file dirname $filename]
6333 file mkdir $dir
6334
6335 set tmp_filename $filename.[pid]
6336 set fd [open $tmp_filename w]
6337 puts $fd $txt
6338 close $fd
6339
6340 if { $executable } {
6341 exec chmod +x $tmp_filename
6342 }
6343 tentative_rename $tmp_filename $filename
6344
6345 return $filename
6346 }
6347
6348 # Return a wrapper around gdb that prevents generating a core file.
6349
6350 proc gdb_no_core { } {
6351 set script \
6352 [list \
6353 "ulimit -c 0" \
6354 [join [list exec $::GDB {"$@"}]]]
6355 set script [join $script "\n"]
6356 return [cached_file gdb-no-core.sh $script 1]
6357 }
6358
6359 # Set 'testfile', 'srcfile', and 'binfile'.
6360 #
6361 # ARGS is a list of source file specifications.
6362 # Without any arguments, the .exp file's base name is used to
6363 # compute the source file name. The ".c" extension is added in this case.
6364 # If ARGS is not empty, each entry is a source file specification.
6365 # If the specification starts with a "." or "-", it is treated as a suffix
6366 # to append to the .exp file's base name.
6367 # If the specification is the empty string, it is treated as if it
6368 # were ".c".
6369 # Otherwise it is a file name.
6370 # The first file in the list is used to set the 'srcfile' global.
6371 # Each subsequent name is used to set 'srcfile2', 'srcfile3', etc.
6372 #
6373 # Most tests should call this without arguments.
6374 #
6375 # If a completely different binary file name is needed, then it
6376 # should be handled in the .exp file with a suitable comment.
6377
6378 proc standard_testfile {args} {
6379 global gdb_test_file_name
6380 global subdir
6381 global gdb_test_file_last_vars
6382
6383 # Outputs.
6384 global testfile binfile
6385
6386 set testfile $gdb_test_file_name
6387 set binfile [standard_output_file ${testfile}]
6388
6389 if {[llength $args] == 0} {
6390 set args .c
6391 }
6392
6393 # Unset our previous output variables.
6394 # This can help catch hidden bugs.
6395 if {[info exists gdb_test_file_last_vars]} {
6396 foreach varname $gdb_test_file_last_vars {
6397 global $varname
6398 catch {unset $varname}
6399 }
6400 }
6401 # 'executable' is often set by tests.
6402 set gdb_test_file_last_vars {executable}
6403
6404 set suffix ""
6405 foreach arg $args {
6406 set varname srcfile$suffix
6407 global $varname
6408
6409 # Handle an extension.
6410 if {$arg == ""} {
6411 set arg $testfile.c
6412 } else {
6413 set first [string range $arg 0 0]
6414 if { $first == "." || $first == "-" } {
6415 set arg $testfile$arg
6416 }
6417 }
6418
6419 set $varname $arg
6420 lappend gdb_test_file_last_vars $varname
6421
6422 if {$suffix == ""} {
6423 set suffix 2
6424 } else {
6425 incr suffix
6426 }
6427 }
6428 }
6429
6430 # The default timeout used when testing GDB commands. We want to use
6431 # the same timeout as the default dejagnu timeout, unless the user has
6432 # already provided a specific value (probably through a site.exp file).
6433 global gdb_test_timeout
6434 if ![info exists gdb_test_timeout] {
6435 set gdb_test_timeout $timeout
6436 }
6437
6438 # A list of global variables that GDB testcases should not use.
6439 # We try to prevent their use by monitoring write accesses and raising
6440 # an error when that happens.
6441 set banned_variables { bug_id prms_id }
6442
6443 # A list of procedures that GDB testcases should not use.
6444 # We try to prevent their use by monitoring invocations and raising
6445 # an error when that happens.
6446 set banned_procedures { strace }
6447
6448 # gdb_init is called by runtest at start, but also by several
6449 # tests directly; gdb_finish is only called from within runtest after
6450 # each test source execution.
6451 # Placing several traces by repetitive calls to gdb_init leads
6452 # to problems, as only one trace is removed in gdb_finish.
6453 # To overcome this possible problem, we add a variable that records
6454 # if the banned variables and procedures are already traced.
6455 set banned_traced 0
6456
6457 # Global array that holds the name of all global variables at the time
6458 # a test script is started. After the test script has completed any
6459 # global not in this list is deleted.
6460 array set gdb_known_globals {}
6461
6462 # Setup the GDB_KNOWN_GLOBALS array with the names of all current
6463 # global variables.
6464 proc gdb_setup_known_globals {} {
6465 global gdb_known_globals
6466
6467 array set gdb_known_globals {}
6468 foreach varname [info globals] {
6469 set gdb_known_globals($varname) 1
6470 }
6471 }
6472
6473 # Cleanup the global namespace. Any global not in the
6474 # GDB_KNOWN_GLOBALS array is unset, this ensures we don't "leak"
6475 # globals from one test script to another.
6476 proc gdb_cleanup_globals {} {
6477 global gdb_known_globals gdb_persistent_globals
6478
6479 foreach varname [info globals] {
6480 if {![info exists gdb_known_globals($varname)]} {
6481 if { [info exists gdb_persistent_globals($varname)] } {
6482 continue
6483 }
6484 uplevel #0 unset $varname
6485 }
6486 }
6487 }
6488
6489 # Create gdb_tcl_unknown, a copy tcl's ::unknown, provided it's present as a
6490 # proc.
6491 set temp [interp create]
6492 if { [interp eval $temp "info procs ::unknown"] != "" } {
6493 set old_args [interp eval $temp "info args ::unknown"]
6494 set old_body [interp eval $temp "info body ::unknown"]
6495 eval proc gdb_tcl_unknown {$old_args} {$old_body}
6496 }
6497 interp delete $temp
6498 unset temp
6499
6500 # GDB implementation of ${tool}_init. Called right before executing the
6501 # test-case.
6502 # Overridable function -- you can override this function in your
6503 # baseboard file.
6504 proc gdb_init { args } {
6505 # A baseboard file overriding this proc and calling the default version
6506 # should behave the same as this proc. So, don't add code here, but to
6507 # the default version instead.
6508 return [default_gdb_init {*}$args]
6509 }
6510
6511 # GDB implementation of ${tool}_finish. Called right after executing the
6512 # test-case.
6513 proc gdb_finish { } {
6514 global gdbserver_reconnect_p
6515 global gdb_prompt
6516 global cleanfiles_target
6517 global cleanfiles_host
6518 global known_globals
6519
6520 if { [info procs ::gdb_tcl_unknown] != "" } {
6521 # Restore dejagnu's version of proc unknown.
6522 rename ::unknown ""
6523 rename ::dejagnu_unknown ::unknown
6524 }
6525
6526 # Exit first, so that the files are no longer in use.
6527 gdb_exit
6528
6529 if { [llength $cleanfiles_target] > 0 } {
6530 eval remote_file target delete $cleanfiles_target
6531 set cleanfiles_target {}
6532 }
6533 if { [llength $cleanfiles_host] > 0 } {
6534 eval remote_file host delete $cleanfiles_host
6535 set cleanfiles_host {}
6536 }
6537
6538 # Unblock write access to the banned variables. Dejagnu typically
6539 # resets some of them between testcases.
6540 global banned_variables
6541 global banned_procedures
6542 global banned_traced
6543 if ($banned_traced) {
6544 foreach banned_var $banned_variables {
6545 global "$banned_var"
6546 trace remove variable "$banned_var" write error
6547 }
6548 foreach banned_proc $banned_procedures {
6549 global "$banned_proc"
6550 trace remove execution "$banned_proc" enter error
6551 }
6552 set banned_traced 0
6553 }
6554
6555 global gdb_finish_hooks
6556 foreach gdb_finish_hook $gdb_finish_hooks {
6557 $gdb_finish_hook
6558 }
6559 set gdb_finish_hooks [list]
6560
6561 gdb_cleanup_globals
6562 }
6563
6564 global debug_format
6565 set debug_format "unknown"
6566
6567 # Run the gdb command "info source" and extract the debugging format
6568 # information from the output and save it in debug_format.
6569
6570 proc get_debug_format { } {
6571 global gdb_prompt
6572 global expect_out
6573 global debug_format
6574
6575 set debug_format "unknown"
6576 send_gdb "info source\n"
6577 gdb_expect 10 {
6578 -re "Compiled with (.*) debugging format.\r\n.*$gdb_prompt $" {
6579 set debug_format $expect_out(1,string)
6580 verbose "debug format is $debug_format"
6581 return 1
6582 }
6583 -re "No current source file.\r\n$gdb_prompt $" {
6584 perror "get_debug_format used when no current source file"
6585 return 0
6586 }
6587 -re "$gdb_prompt $" {
6588 warning "couldn't check debug format (no valid response)."
6589 return 1
6590 }
6591 timeout {
6592 warning "couldn't check debug format (timeout)."
6593 return 1
6594 }
6595 }
6596 }
6597
6598 # Return true if FORMAT matches the debug format the current test was
6599 # compiled with. FORMAT is a shell-style globbing pattern; it can use
6600 # `*', `[...]', and so on.
6601 #
6602 # This function depends on variables set by `get_debug_format', above.
6603
6604 proc test_debug_format {format} {
6605 global debug_format
6606
6607 return [expr [string match $format $debug_format] != 0]
6608 }
6609
6610 # Like setup_xfail, but takes the name of a debug format (DWARF 1,
6611 # COFF, stabs, etc). If that format matches the format that the
6612 # current test was compiled with, then the next test is expected to
6613 # fail for any target. Returns 1 if the next test or set of tests is
6614 # expected to fail, 0 otherwise (or if it is unknown). Must have
6615 # previously called get_debug_format.
6616 proc setup_xfail_format { format } {
6617 set ret [test_debug_format $format]
6618
6619 if {$ret} {
6620 setup_xfail "*-*-*"
6621 }
6622 return $ret
6623 }
6624
6625 # gdb_get_line_number TEXT [FILE]
6626 #
6627 # Search the source file FILE, and return the line number of the
6628 # first line containing TEXT. If no match is found, an error is thrown.
6629 #
6630 # TEXT is a string literal, not a regular expression.
6631 #
6632 # The default value of FILE is "$srcdir/$subdir/$srcfile". If FILE is
6633 # specified, and does not start with "/", then it is assumed to be in
6634 # "$srcdir/$subdir". This is awkward, and can be fixed in the future,
6635 # by changing the callers and the interface at the same time.
6636 # In particular: gdb.base/break.exp, gdb.base/condbreak.exp,
6637 # gdb.base/ena-dis-br.exp.
6638 #
6639 # Use this function to keep your test scripts independent of the
6640 # exact line numbering of the source file. Don't write:
6641 #
6642 # send_gdb "break 20"
6643 #
6644 # This means that if anyone ever edits your test's source file,
6645 # your test could break. Instead, put a comment like this on the
6646 # source file line you want to break at:
6647 #
6648 # /* breakpoint spot: frotz.exp: test name */
6649 #
6650 # and then write, in your test script (which we assume is named
6651 # frotz.exp):
6652 #
6653 # send_gdb "break [gdb_get_line_number "frotz.exp: test name"]\n"
6654 #
6655 # (Yes, Tcl knows how to handle the nested quotes and brackets.
6656 # Try this:
6657 # $ tclsh
6658 # % puts "foo [lindex "bar baz" 1]"
6659 # foo baz
6660 # %
6661 # Tcl is quite clever, for a little stringy language.)
6662 #
6663 # ===
6664 #
6665 # The previous implementation of this procedure used the gdb search command.
6666 # This version is different:
6667 #
6668 # . It works with MI, and it also works when gdb is not running.
6669 #
6670 # . It operates on the build machine, not the host machine.
6671 #
6672 # . For now, this implementation fakes a current directory of
6673 # $srcdir/$subdir to be compatible with the old implementation.
6674 # This will go away eventually and some callers will need to
6675 # be changed.
6676 #
6677 # . The TEXT argument is literal text and matches literally,
6678 # not a regular expression as it was before.
6679 #
6680 # . State changes in gdb, such as changing the current file
6681 # and setting $_, no longer happen.
6682 #
6683 # After a bit of time we can forget about the differences from the
6684 # old implementation.
6685 #
6686 # --chastain 2004-08-05
6687
6688 proc gdb_get_line_number { text { file "" } } {
6689 global srcdir
6690 global subdir
6691 global srcfile
6692
6693 if {"$file" == ""} {
6694 set file "$srcfile"
6695 }
6696 if {![regexp "^/" "$file"]} {
6697 set file "$srcdir/$subdir/$file"
6698 }
6699
6700 if {[catch { set fd [open "$file"] } message]} {
6701 error "$message"
6702 }
6703
6704 set found -1
6705 for { set line 1 } { 1 } { incr line } {
6706 if {[catch { set nchar [gets "$fd" body] } message]} {
6707 error "$message"
6708 }
6709 if {$nchar < 0} {
6710 break
6711 }
6712 if {[string first "$text" "$body"] >= 0} {
6713 set found $line
6714 break
6715 }
6716 }
6717
6718 if {[catch { close "$fd" } message]} {
6719 error "$message"
6720 }
6721
6722 if {$found == -1} {
6723 error "undefined tag \"$text\""
6724 }
6725
6726 return $found
6727 }
6728
6729 # Continue the program until it ends.
6730 #
6731 # MSSG is the error message that gets printed. If not given, a
6732 # default is used.
6733 # COMMAND is the command to invoke. If not given, "continue" is
6734 # used.
6735 # ALLOW_EXTRA is a flag indicating whether the test should expect
6736 # extra output between the "Continuing." line and the program
6737 # exiting. By default it is zero; if nonzero, any extra output
6738 # is accepted.
6739
6740 proc gdb_continue_to_end {{mssg ""} {command continue} {allow_extra 0}} {
6741 global inferior_exited_re use_gdb_stub
6742
6743 if {$mssg == ""} {
6744 set text "continue until exit"
6745 } else {
6746 set text "continue until exit at $mssg"
6747 }
6748 if {$allow_extra} {
6749 set extra ".*"
6750 } else {
6751 set extra ""
6752 }
6753
6754 # By default, we don't rely on exit() behavior of remote stubs --
6755 # it's common for exit() to be implemented as a simple infinite
6756 # loop, or a forced crash/reset. For native targets, by default, we
6757 # assume process exit is reported as such. If a non-reliable target
6758 # is used, we set a breakpoint at exit, and continue to that.
6759 if { [target_info exists exit_is_reliable] } {
6760 set exit_is_reliable [target_info exit_is_reliable]
6761 } else {
6762 set exit_is_reliable [expr ! $use_gdb_stub]
6763 }
6764
6765 if { ! $exit_is_reliable } {
6766 if {![gdb_breakpoint "exit"]} {
6767 return 0
6768 }
6769 gdb_test $command "Continuing..*Breakpoint .*exit.*" \
6770 $text
6771 } else {
6772 # Continue until we exit. Should not stop again.
6773 # Don't bother to check the output of the program, that may be
6774 # extremely tough for some remote systems.
6775 gdb_test $command \
6776 "Continuing.\[\r\n0-9\]+${extra}(... EXIT code 0\[\r\n\]+|$inferior_exited_re normally).*"\
6777 $text
6778 }
6779 }
6780
6781 proc rerun_to_main {} {
6782 global gdb_prompt use_gdb_stub
6783
6784 if $use_gdb_stub {
6785 gdb_run_cmd
6786 gdb_expect {
6787 -re ".*Breakpoint .*main .*$gdb_prompt $"\
6788 {pass "rerun to main" ; return 0}
6789 -re "$gdb_prompt $"\
6790 {fail "rerun to main" ; return 0}
6791 timeout {fail "(timeout) rerun to main" ; return 0}
6792 }
6793 } else {
6794 send_gdb "run\n"
6795 gdb_expect {
6796 -re "The program .* has been started already.*y or n. $" {
6797 send_gdb "y\n" answer
6798 exp_continue
6799 }
6800 -re "Starting program.*$gdb_prompt $"\
6801 {pass "rerun to main" ; return 0}
6802 -re "$gdb_prompt $"\
6803 {fail "rerun to main" ; return 0}
6804 timeout {fail "(timeout) rerun to main" ; return 0}
6805 }
6806 }
6807 }
6808
6809 # Return true if EXECUTABLE contains a .gdb_index or .debug_names index section.
6810
6811 proc exec_has_index_section { executable } {
6812 set readelf_program [gdb_find_readelf]
6813 set res [catch {exec $readelf_program -S $executable \
6814 | grep -E "\.gdb_index|\.debug_names" }]
6815 if { $res == 0 } {
6816 return 1
6817 }
6818 return 0
6819 }
6820
6821 # Return list with major and minor version of readelf, or an empty list.
6822 gdb_caching_proc readelf_version {
6823 set readelf_program [gdb_find_readelf]
6824 set res [catch {exec $readelf_program --version} output]
6825 if { $res != 0 } {
6826 return [list]
6827 }
6828 set lines [split $output \n]
6829 set line [lindex $lines 0]
6830 set res [regexp {[ \t]+([0-9]+)[.]([0-9]+)[^ \t]*$} \
6831 $line dummy major minor]
6832 if { $res != 1 } {
6833 return [list]
6834 }
6835 return [list $major $minor]
6836 }
6837
6838 # Return 1 if readelf prints the PIE flag, 0 if is doesn't, and -1 if unknown.
6839 proc readelf_prints_pie { } {
6840 set version [readelf_version]
6841 if { [llength $version] == 0 } {
6842 return -1
6843 }
6844 set major [lindex $version 0]
6845 set minor [lindex $version 1]
6846 # It would be better to construct a PIE executable and test if the PIE
6847 # flag is printed by readelf, but we cannot reliably construct a PIE
6848 # executable if the multilib_flags dictate otherwise
6849 # (--target_board=unix/-no-pie/-fno-PIE).
6850 return [version_at_least $major $minor 2 26]
6851 }
6852
6853 # Return 1 if EXECUTABLE is a Position Independent Executable, 0 if it is not,
6854 # and -1 if unknown.
6855
6856 proc exec_is_pie { executable } {
6857 set res [readelf_prints_pie]
6858 if { $res != 1 } {
6859 return -1
6860 }
6861 set readelf_program [gdb_find_readelf]
6862 # We're not testing readelf -d | grep "FLAGS_1.*Flags:.*PIE"
6863 # because the PIE flag is not set by all versions of gold, see PR
6864 # binutils/26039.
6865 set res [catch {exec $readelf_program -h $executable} output]
6866 if { $res != 0 } {
6867 return -1
6868 }
6869 set res [regexp -line {^[ \t]*Type:[ \t]*DYN \((Position-Independent Executable|Shared object) file\)$} \
6870 $output]
6871 if { $res == 1 } {
6872 return 1
6873 }
6874 return 0
6875 }
6876
6877 # Return true if a test should be skipped due to lack of floating
6878 # point support or GDB can't fetch the contents from floating point
6879 # registers.
6880
6881 gdb_caching_proc gdb_skip_float_test {
6882 if [target_info exists gdb,skip_float_tests] {
6883 return 1
6884 }
6885
6886 # There is an ARM kernel ptrace bug that hardware VFP registers
6887 # are not updated after GDB ptrace set VFP registers. The bug
6888 # was introduced by kernel commit 8130b9d7b9d858aa04ce67805e8951e3cb6e9b2f
6889 # in 2012 and is fixed in e2dfb4b880146bfd4b6aa8e138c0205407cebbaf
6890 # in May 2016. In other words, kernels older than 4.6.3, 4.4.14,
6891 # 4.1.27, 3.18.36, and 3.14.73 have this bug.
6892 # This kernel bug is detected by check how does GDB change the
6893 # program result by changing one VFP register.
6894 if { [istarget "arm*-*-linux*"] } {
6895
6896 set compile_flags {debug nowarnings }
6897
6898 # Set up, compile, and execute a test program having VFP
6899 # operations.
6900 set src [standard_temp_file arm_vfp[pid].c]
6901 set exe [standard_temp_file arm_vfp[pid].x]
6902
6903 gdb_produce_source $src {
6904 int main() {
6905 double d = 4.0;
6906 int ret;
6907
6908 asm ("vldr d0, [%0]" : : "r" (&d));
6909 asm ("vldr d1, [%0]" : : "r" (&d));
6910 asm (".global break_here\n"
6911 "break_here:");
6912 asm ("vcmp.f64 d0, d1\n"
6913 "vmrs APSR_nzcv, fpscr\n"
6914 "bne L_value_different\n"
6915 "movs %0, #0\n"
6916 "b L_end\n"
6917 "L_value_different:\n"
6918 "movs %0, #1\n"
6919 "L_end:\n" : "=r" (ret) :);
6920
6921 /* Return $d0 != $d1. */
6922 return ret;
6923 }
6924 }
6925
6926 verbose "compiling testfile $src" 2
6927 set lines [gdb_compile $src $exe executable $compile_flags]
6928 file delete $src
6929
6930 if {![string match "" $lines]} {
6931 verbose "testfile compilation failed, returning 1" 2
6932 return 0
6933 }
6934
6935 # No error message, compilation succeeded so now run it via gdb.
6936 # Run the test up to 5 times to detect whether ptrace can
6937 # correctly update VFP registers or not.
6938 set skip_vfp_test 0
6939 for {set i 0} {$i < 5} {incr i} {
6940 global gdb_prompt srcdir subdir
6941
6942 gdb_exit
6943 gdb_start
6944 gdb_reinitialize_dir $srcdir/$subdir
6945 gdb_load "$exe"
6946
6947 runto_main
6948 gdb_test "break *break_here"
6949 gdb_continue_to_breakpoint "break_here"
6950
6951 # Modify $d0 to a different value, so the exit code should
6952 # be 1.
6953 gdb_test "set \$d0 = 5.0"
6954
6955 set test "continue to exit"
6956 gdb_test_multiple "continue" "$test" {
6957 -re "exited with code 01.*$gdb_prompt $" {
6958 }
6959 -re "exited normally.*$gdb_prompt $" {
6960 # However, the exit code is 0. That means something
6961 # wrong in setting VFP registers.
6962 set skip_vfp_test 1
6963 break
6964 }
6965 }
6966 }
6967
6968 gdb_exit
6969 remote_file build delete $exe
6970
6971 return $skip_vfp_test
6972 }
6973 return 0
6974 }
6975
6976 # Print a message and return true if a test should be skipped
6977 # due to lack of stdio support.
6978
6979 proc gdb_skip_stdio_test { msg } {
6980 if [target_info exists gdb,noinferiorio] {
6981 verbose "Skipping test '$msg': no inferior i/o."
6982 return 1
6983 }
6984 return 0
6985 }
6986
6987 proc gdb_skip_bogus_test { msg } {
6988 return 0
6989 }
6990
6991 # Return true if a test should be skipped due to lack of XML support
6992 # in the host GDB.
6993 # NOTE: This must be called while gdb is *not* running.
6994
6995 gdb_caching_proc gdb_skip_xml_test {
6996 global gdb_spawn_id
6997 global gdb_prompt
6998 global srcdir
6999
7000 if { [info exists gdb_spawn_id] } {
7001 error "GDB must not be running in gdb_skip_xml_tests."
7002 }
7003
7004 set xml_file [gdb_remote_download host "${srcdir}/gdb.xml/trivial.xml"]
7005
7006 gdb_start
7007 set xml_missing 0
7008 gdb_test_multiple "set tdesc filename $xml_file" "" {
7009 -re ".*XML support was disabled at compile time.*$gdb_prompt $" {
7010 set xml_missing 1
7011 }
7012 -re ".*$gdb_prompt $" { }
7013 }
7014 gdb_exit
7015 return $xml_missing
7016 }
7017
7018 # Return true if argv[0] is available.
7019
7020 gdb_caching_proc gdb_has_argv0 {
7021 set result 0
7022
7023 # Compile and execute a test program to check whether argv[0] is available.
7024 gdb_simple_compile has_argv0 {
7025 int main (int argc, char **argv) {
7026 return 0;
7027 }
7028 } executable
7029
7030
7031 # Helper proc.
7032 proc gdb_has_argv0_1 { exe } {
7033 global srcdir subdir
7034 global gdb_prompt hex
7035
7036 gdb_exit
7037 gdb_start
7038 gdb_reinitialize_dir $srcdir/$subdir
7039 gdb_load "$exe"
7040
7041 # Set breakpoint on main.
7042 gdb_test_multiple "break -q main" "break -q main" {
7043 -re "Breakpoint.*${gdb_prompt} $" {
7044 }
7045 -re "${gdb_prompt} $" {
7046 return 0
7047 }
7048 }
7049
7050 # Run to main.
7051 gdb_run_cmd
7052 gdb_test_multiple "" "run to main" {
7053 -re "Breakpoint.*${gdb_prompt} $" {
7054 }
7055 -re "${gdb_prompt} $" {
7056 return 0
7057 }
7058 }
7059
7060 set old_elements "200"
7061 set test "show print elements"
7062 gdb_test_multiple $test $test {
7063 -re "Limit on string chars or array elements to print is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
7064 set old_elements $expect_out(1,string)
7065 }
7066 }
7067 set old_repeats "200"
7068 set test "show print repeats"
7069 gdb_test_multiple $test $test {
7070 -re "Threshold for repeated print elements is (\[^\r\n\]+)\\.\r\n$gdb_prompt $" {
7071 set old_repeats $expect_out(1,string)
7072 }
7073 }
7074 gdb_test_no_output "set print elements unlimited" ""
7075 gdb_test_no_output "set print repeats unlimited" ""
7076
7077 set retval 0
7078 # Check whether argc is 1.
7079 gdb_test_multiple "p argc" "p argc" {
7080 -re " = 1\r\n${gdb_prompt} $" {
7081
7082 gdb_test_multiple "p argv\[0\]" "p argv\[0\]" {
7083 -re " = $hex \".*[file tail $exe]\"\r\n${gdb_prompt} $" {
7084 set retval 1
7085 }
7086 -re "${gdb_prompt} $" {
7087 }
7088 }
7089 }
7090 -re "${gdb_prompt} $" {
7091 }
7092 }
7093
7094 gdb_test_no_output "set print elements $old_elements" ""
7095 gdb_test_no_output "set print repeats $old_repeats" ""
7096
7097 return $retval
7098 }
7099
7100 set result [gdb_has_argv0_1 $obj]
7101
7102 gdb_exit
7103 file delete $obj
7104
7105 if { !$result
7106 && ([istarget *-*-linux*]
7107 || [istarget *-*-freebsd*] || [istarget *-*-kfreebsd*]
7108 || [istarget *-*-netbsd*] || [istarget *-*-knetbsd*]
7109 || [istarget *-*-openbsd*]
7110 || [istarget *-*-darwin*]
7111 || [istarget *-*-solaris*]
7112 || [istarget *-*-aix*]
7113 || [istarget *-*-gnu*]
7114 || [istarget *-*-cygwin*] || [istarget *-*-mingw32*]
7115 || [istarget *-*-*djgpp*] || [istarget *-*-go32*]
7116 || [istarget *-wince-pe] || [istarget *-*-mingw32ce*]
7117 || [istarget *-*-osf*]
7118 || [istarget *-*-dicos*]
7119 || [istarget *-*-nto*]
7120 || [istarget *-*-*vms*]
7121 || [istarget *-*-lynx*178]) } {
7122 fail "argv\[0\] should be available on this target"
7123 }
7124
7125 return $result
7126 }
7127
7128 # Note: the procedure gdb_gnu_strip_debug will produce an executable called
7129 # ${binfile}.dbglnk, which is just like the executable ($binfile) but without
7130 # the debuginfo. Instead $binfile has a .gnu_debuglink section which contains
7131 # the name of a debuginfo only file. This file will be stored in the same
7132 # subdirectory.
7133
7134 # Functions for separate debug info testing
7135
7136 # starting with an executable:
7137 # foo --> original executable
7138
7139 # at the end of the process we have:
7140 # foo.stripped --> foo w/o debug info
7141 # foo.debug --> foo's debug info
7142 # foo --> like foo, but with a new .gnu_debuglink section pointing to foo.debug.
7143
7144 # Fetch the build id from the file.
7145 # Returns "" if there is none.
7146
7147 proc get_build_id { filename } {
7148 if { ([istarget "*-*-mingw*"]
7149 || [istarget *-*-cygwin*]) } {
7150 set objdump_program [gdb_find_objdump]
7151 set result [catch {set data [exec $objdump_program -p $filename | grep signature | cut "-d " -f4]} output]
7152 verbose "result is $result"
7153 verbose "output is $output"
7154 if {$result == 1} {
7155 return ""
7156 }
7157 return $data
7158 } else {
7159 set tmp [standard_output_file "${filename}-tmp"]
7160 set objcopy_program [gdb_find_objcopy]
7161 set result [catch "exec $objcopy_program -j .note.gnu.build-id -O binary $filename $tmp" output]
7162 verbose "result is $result"
7163 verbose "output is $output"
7164 if {$result == 1} {
7165 return ""
7166 }
7167 set fi [open $tmp]
7168 fconfigure $fi -translation binary
7169 # Skip the NOTE header.
7170 read $fi 16
7171 set data [read $fi]
7172 close $fi
7173 file delete $tmp
7174 if {![string compare $data ""]} {
7175 return ""
7176 }
7177 # Convert it to hex.
7178 binary scan $data H* data
7179 return $data
7180 }
7181 }
7182
7183 # Return the build-id hex string (usually 160 bits as 40 hex characters)
7184 # converted to the form: .build-id/ab/cdef1234...89.debug
7185 # Return "" if no build-id found.
7186 proc build_id_debug_filename_get { filename } {
7187 set data [get_build_id $filename]
7188 if { $data == "" } {
7189 return ""
7190 }
7191 regsub {^..} $data {\0/} data
7192 return ".build-id/${data}.debug"
7193 }
7194
7195 # Create stripped files for DEST, replacing it. If ARGS is passed, it is a
7196 # list of optional flags. The only currently supported flag is no-main,
7197 # which removes the symbol entry for main from the separate debug file.
7198 #
7199 # Function returns zero on success. Function will return non-zero failure code
7200 # on some targets not supporting separate debug info (such as i386-msdos).
7201
7202 proc gdb_gnu_strip_debug { dest args } {
7203
7204 # Use the first separate debug info file location searched by GDB so the
7205 # run cannot be broken by some stale file searched with higher precedence.
7206 set debug_file "${dest}.debug"
7207
7208 set strip_to_file_program [transform strip]
7209 set objcopy_program [gdb_find_objcopy]
7210
7211 set debug_link [file tail $debug_file]
7212 set stripped_file "${dest}.stripped"
7213
7214 # Get rid of the debug info, and store result in stripped_file
7215 # something like gdb/testsuite/gdb.base/blah.stripped.
7216 set result [catch "exec $strip_to_file_program --strip-debug ${dest} -o ${stripped_file}" output]
7217 verbose "result is $result"
7218 verbose "output is $output"
7219 if {$result == 1} {
7220 return 1
7221 }
7222
7223 # Workaround PR binutils/10802:
7224 # Preserve the 'x' bit also for PIEs (Position Independent Executables).
7225 set perm [file attributes ${dest} -permissions]
7226 file attributes ${stripped_file} -permissions $perm
7227
7228 # Get rid of everything but the debug info, and store result in debug_file
7229 # This will be in the .debug subdirectory, see above.
7230 set result [catch "exec $strip_to_file_program --only-keep-debug ${dest} -o ${debug_file}" output]
7231 verbose "result is $result"
7232 verbose "output is $output"
7233 if {$result == 1} {
7234 return 1
7235 }
7236
7237 # If no-main is passed, strip the symbol for main from the separate
7238 # file. This is to simulate the behavior of elfutils's eu-strip, which
7239 # leaves the symtab in the original file only. There's no way to get
7240 # objcopy or strip to remove the symbol table without also removing the
7241 # debugging sections, so this is as close as we can get.
7242 if { [llength $args] == 1 && [lindex $args 0] == "no-main" } {
7243 set result [catch "exec $objcopy_program -N main ${debug_file} ${debug_file}-tmp" output]
7244 verbose "result is $result"
7245 verbose "output is $output"
7246 if {$result == 1} {
7247 return 1
7248 }
7249 file delete "${debug_file}"
7250 file rename "${debug_file}-tmp" "${debug_file}"
7251 }
7252
7253 # Link the two previous output files together, adding the .gnu_debuglink
7254 # section to the stripped_file, containing a pointer to the debug_file,
7255 # save the new file in dest.
7256 # This will be the regular executable filename, in the usual location.
7257 set result [catch "exec $objcopy_program --add-gnu-debuglink=${debug_file} ${stripped_file} ${dest}" output]
7258 verbose "result is $result"
7259 verbose "output is $output"
7260 if {$result == 1} {
7261 return 1
7262 }
7263
7264 # Workaround PR binutils/10802:
7265 # Preserve the 'x' bit also for PIEs (Position Independent Executables).
7266 set perm [file attributes ${stripped_file} -permissions]
7267 file attributes ${dest} -permissions $perm
7268
7269 return 0
7270 }
7271
7272 # Test the output of GDB_COMMAND matches the pattern obtained
7273 # by concatenating all elements of EXPECTED_LINES. This makes
7274 # it possible to split otherwise very long string into pieces.
7275 # If third argument TESTNAME is not empty, it's used as the name of the
7276 # test to be printed on pass/fail.
7277 proc help_test_raw { gdb_command expected_lines {testname {}} } {
7278 set expected_output [join $expected_lines ""]
7279 if {$testname != {}} {
7280 gdb_test "${gdb_command}" "${expected_output}" $testname
7281 return
7282 }
7283
7284 gdb_test "${gdb_command}" "${expected_output}"
7285 }
7286
7287 # A regexp that matches the end of help CLASS|PREFIX_COMMAND
7288 set help_list_trailer {
7289 "Type \"apropos word\" to search for commands related to \"word\"\.[\r\n]+"
7290 "Type \"apropos -v word\" for full documentation of commands related to \"word\"\.[\r\n]+"
7291 "Command name abbreviations are allowed if unambiguous\."
7292 }
7293
7294 # Test the output of "help COMMAND_CLASS". EXPECTED_INITIAL_LINES
7295 # are regular expressions that should match the beginning of output,
7296 # before the list of commands in that class.
7297 # LIST_OF_COMMANDS are regular expressions that should match the
7298 # list of commands in that class. If empty, the command list will be
7299 # matched automatically. The presence of standard epilogue will be tested
7300 # automatically.
7301 # If last argument TESTNAME is not empty, it's used as the name of the
7302 # test to be printed on pass/fail.
7303 # Notice that the '[' and ']' characters don't need to be escaped for strings
7304 # wrapped in {} braces.
7305 proc test_class_help { command_class expected_initial_lines {list_of_commands {}} {testname {}} } {
7306 global help_list_trailer
7307 if {[llength $list_of_commands]>0} {
7308 set l_list_of_commands {"List of commands:[\r\n]+[\r\n]+"}
7309 set l_list_of_commands [concat $l_list_of_commands $list_of_commands]
7310 set l_list_of_commands [concat $l_list_of_commands {"[\r\n]+[\r\n]+"}]
7311 } else {
7312 set l_list_of_commands {"List of commands\:.*[\r\n]+"}
7313 }
7314 set l_stock_body {
7315 "Type \"help\" followed by command name for full documentation\.[\r\n]+"
7316 }
7317 set l_entire_body [concat $expected_initial_lines $l_list_of_commands \
7318 $l_stock_body $help_list_trailer]
7319
7320 help_test_raw "help ${command_class}" $l_entire_body $testname
7321 }
7322
7323 # Like test_class_help but specialised to test "help user-defined".
7324 proc test_user_defined_class_help { {list_of_commands {}} {testname {}} } {
7325 test_class_help "user-defined" {
7326 "User-defined commands\.[\r\n]+"
7327 "The commands in this class are those defined by the user\.[\r\n]+"
7328 "Use the \"define\" command to define a command\.[\r\n]+"
7329 } $list_of_commands $testname
7330 }
7331
7332
7333 # COMMAND_LIST should have either one element -- command to test, or
7334 # two elements -- abbreviated command to test, and full command the first
7335 # element is abbreviation of.
7336 # The command must be a prefix command. EXPECTED_INITIAL_LINES
7337 # are regular expressions that should match the beginning of output,
7338 # before the list of subcommands. The presence of
7339 # subcommand list and standard epilogue will be tested automatically.
7340 proc test_prefix_command_help { command_list expected_initial_lines args } {
7341 global help_list_trailer
7342 set command [lindex $command_list 0]
7343 if {[llength $command_list]>1} {
7344 set full_command [lindex $command_list 1]
7345 } else {
7346 set full_command $command
7347 }
7348 # Use 'list' and not just {} because we want variables to
7349 # be expanded in this list.
7350 set l_stock_body [list\
7351 "List of $full_command subcommands\:.*\[\r\n\]+"\
7352 "Type \"help $full_command\" followed by $full_command subcommand name for full documentation\.\[\r\n\]+"]
7353 set l_entire_body [concat $expected_initial_lines $l_stock_body $help_list_trailer]
7354 if {[llength $args]>0} {
7355 help_test_raw "help ${command}" $l_entire_body [lindex $args 0]
7356 } else {
7357 help_test_raw "help ${command}" $l_entire_body
7358 }
7359 }
7360
7361 # Build executable named EXECUTABLE from specifications that allow
7362 # different options to be passed to different sub-compilations.
7363 # TESTNAME is the name of the test; this is passed to 'untested' if
7364 # something fails.
7365 # OPTIONS is passed to the final link, using gdb_compile. If OPTIONS
7366 # contains the option "pthreads", then gdb_compile_pthreads is used.
7367 # ARGS is a flat list of source specifications, of the form:
7368 # { SOURCE1 OPTIONS1 [ SOURCE2 OPTIONS2 ]... }
7369 # Each SOURCE is compiled to an object file using its OPTIONS,
7370 # using gdb_compile.
7371 # Returns 0 on success, -1 on failure.
7372 proc build_executable_from_specs {testname executable options args} {
7373 global subdir
7374 global srcdir
7375
7376 set binfile [standard_output_file $executable]
7377
7378 set func gdb_compile
7379 set func_index [lsearch -regexp $options {^(pthreads|shlib|shlib_pthreads|openmp)$}]
7380 if {$func_index != -1} {
7381 set func "${func}_[lindex $options $func_index]"
7382 }
7383
7384 # gdb_compile_shlib and gdb_compile_shlib_pthreads do not use the 3rd
7385 # parameter. They also requires $sources while gdb_compile and
7386 # gdb_compile_pthreads require $objects. Moreover they ignore any options.
7387 if [string match gdb_compile_shlib* $func] {
7388 set sources_path {}
7389 foreach {s local_options} $args {
7390 if {[regexp "^/" "$s"]} {
7391 lappend sources_path "$s"
7392 } else {
7393 lappend sources_path "$srcdir/$subdir/$s"
7394 }
7395 }
7396 set ret [$func $sources_path "${binfile}" $options]
7397 } elseif {[lsearch -exact $options rust] != -1} {
7398 set sources_path {}
7399 foreach {s local_options} $args {
7400 if {[regexp "^/" "$s"]} {
7401 lappend sources_path "$s"
7402 } else {
7403 lappend sources_path "$srcdir/$subdir/$s"
7404 }
7405 }
7406 set ret [gdb_compile_rust $sources_path "${binfile}" $options]
7407 } else {
7408 set objects {}
7409 set i 0
7410 foreach {s local_options} $args {
7411 if {![regexp "^/" "$s"]} {
7412 set s "$srcdir/$subdir/$s"
7413 }
7414 if { [$func "${s}" "${binfile}${i}.o" object $local_options] != "" } {
7415 untested $testname
7416 return -1
7417 }
7418 lappend objects "${binfile}${i}.o"
7419 incr i
7420 }
7421 set ret [$func $objects "${binfile}" executable $options]
7422 }
7423 if { $ret != "" } {
7424 untested $testname
7425 return -1
7426 }
7427
7428 return 0
7429 }
7430
7431 # Build executable named EXECUTABLE, from SOURCES. If SOURCES are not
7432 # provided, uses $EXECUTABLE.c. The TESTNAME paramer is the name of test
7433 # to pass to untested, if something is wrong. OPTIONS are passed
7434 # to gdb_compile directly.
7435 proc build_executable { testname executable {sources ""} {options {debug}} } {
7436 if {[llength $sources]==0} {
7437 set sources ${executable}.c
7438 }
7439
7440 set arglist [list $testname $executable $options]
7441 foreach source $sources {
7442 lappend arglist $source $options
7443 }
7444
7445 return [eval build_executable_from_specs $arglist]
7446 }
7447
7448 # Starts fresh GDB binary and loads an optional executable into GDB.
7449 # Usage: clean_restart [executable]
7450 # EXECUTABLE is the basename of the binary.
7451 # Return -1 if starting gdb or loading the executable failed.
7452
7453 proc clean_restart { args } {
7454 global srcdir
7455 global subdir
7456 global errcnt
7457 global warncnt
7458
7459 if { [llength $args] > 1 } {
7460 error "bad number of args: [llength $args]"
7461 }
7462
7463 gdb_exit
7464
7465 # This is a clean restart, so reset error and warning count.
7466 set errcnt 0
7467 set warncnt 0
7468
7469 # We'd like to do:
7470 # if { [gdb_start] == -1 } {
7471 # return -1
7472 # }
7473 # but gdb_start is a ${tool}_start proc, which doesn't have a defined
7474 # return value. So instead, we test for errcnt.
7475 gdb_start
7476 if { $errcnt > 0 } {
7477 return -1
7478 }
7479
7480 gdb_reinitialize_dir $srcdir/$subdir
7481
7482 if { [llength $args] >= 1 } {
7483 set executable [lindex $args 0]
7484 set binfile [standard_output_file ${executable}]
7485 return [gdb_load ${binfile}]
7486 }
7487
7488 return 0
7489 }
7490
7491 # Prepares for testing by calling build_executable_full, then
7492 # clean_restart.
7493 # TESTNAME is the name of the test.
7494 # Each element in ARGS is a list of the form
7495 # { EXECUTABLE OPTIONS SOURCE_SPEC... }
7496 # These are passed to build_executable_from_specs, which see.
7497 # The last EXECUTABLE is passed to clean_restart.
7498 # Returns 0 on success, non-zero on failure.
7499 proc prepare_for_testing_full {testname args} {
7500 foreach spec $args {
7501 if {[eval build_executable_from_specs [list $testname] $spec] == -1} {
7502 return -1
7503 }
7504 set executable [lindex $spec 0]
7505 }
7506 clean_restart $executable
7507 return 0
7508 }
7509
7510 # Prepares for testing, by calling build_executable, and then clean_restart.
7511 # Please refer to build_executable for parameter description.
7512 proc prepare_for_testing { testname executable {sources ""} {options {debug}}} {
7513
7514 if {[build_executable $testname $executable $sources $options] == -1} {
7515 return -1
7516 }
7517 clean_restart $executable
7518
7519 return 0
7520 }
7521
7522 # Retrieve the value of EXP in the inferior, represented in format
7523 # specified in FMT (using "printFMT"). DEFAULT is used as fallback if
7524 # print fails. TEST is the test message to use. It can be omitted,
7525 # in which case a test message is built from EXP.
7526
7527 proc get_valueof { fmt exp default {test ""} } {
7528 global gdb_prompt
7529
7530 if {$test == "" } {
7531 set test "get valueof \"${exp}\""
7532 }
7533
7534 set val ${default}
7535 gdb_test_multiple "print${fmt} ${exp}" "$test" {
7536 -re "\\$\[0-9\]* = (\[^\r\n\]*)\[\r\n\]*$gdb_prompt $" {
7537 set val $expect_out(1,string)
7538 pass "$test"
7539 }
7540 timeout {
7541 fail "$test (timeout)"
7542 }
7543 }
7544 return ${val}
7545 }
7546
7547 # Retrieve the value of local var EXP in the inferior. DEFAULT is used as
7548 # fallback if print fails. TEST is the test message to use. It can be
7549 # omitted, in which case a test message is built from EXP.
7550
7551 proc get_local_valueof { exp default {test ""} } {
7552 global gdb_prompt
7553
7554 if {$test == "" } {
7555 set test "get local valueof \"${exp}\""
7556 }
7557
7558 set val ${default}
7559 gdb_test_multiple "info locals ${exp}" "$test" {
7560 -re "$exp = (\[^\r\n\]*)\[\r\n\]*$gdb_prompt $" {
7561 set val $expect_out(1,string)
7562 pass "$test"
7563 }
7564 timeout {
7565 fail "$test (timeout)"
7566 }
7567 }
7568 return ${val}
7569 }
7570
7571 # Retrieve the value of EXP in the inferior, as a signed decimal value
7572 # (using "print /d"). DEFAULT is used as fallback if print fails.
7573 # TEST is the test message to use. It can be omitted, in which case
7574 # a test message is built from EXP.
7575
7576 proc get_integer_valueof { exp default {test ""} } {
7577 global gdb_prompt
7578
7579 if {$test == ""} {
7580 set test "get integer valueof \"${exp}\""
7581 }
7582
7583 set val ${default}
7584 gdb_test_multiple "print /d ${exp}" "$test" {
7585 -re "\\$\[0-9\]* = (\[-\]*\[0-9\]*).*$gdb_prompt $" {
7586 set val $expect_out(1,string)
7587 pass "$test"
7588 }
7589 timeout {
7590 fail "$test (timeout)"
7591 }
7592 }
7593 return ${val}
7594 }
7595
7596 # Retrieve the value of EXP in the inferior, as an hexadecimal value
7597 # (using "print /x"). DEFAULT is used as fallback if print fails.
7598 # TEST is the test message to use. It can be omitted, in which case
7599 # a test message is built from EXP.
7600
7601 proc get_hexadecimal_valueof { exp default {test ""} } {
7602 global gdb_prompt
7603
7604 if {$test == ""} {
7605 set test "get hexadecimal valueof \"${exp}\""
7606 }
7607
7608 set val ${default}
7609 gdb_test_multiple "print /x ${exp}" $test {
7610 -re "\\$\[0-9\]* = (0x\[0-9a-zA-Z\]+).*$gdb_prompt $" {
7611 set val $expect_out(1,string)
7612 pass "$test"
7613 }
7614 }
7615 return ${val}
7616 }
7617
7618 # Retrieve the size of TYPE in the inferior, as a decimal value. DEFAULT
7619 # is used as fallback if print fails. TEST is the test message to use.
7620 # It can be omitted, in which case a test message is 'sizeof (TYPE)'.
7621
7622 proc get_sizeof { type default {test ""} } {
7623 return [get_integer_valueof "sizeof (${type})" $default $test]
7624 }
7625
7626 proc get_target_charset { } {
7627 global gdb_prompt
7628
7629 gdb_test_multiple "show target-charset" "" {
7630 -re "The target character set is \"auto; currently (\[^\"\]*)\".*$gdb_prompt $" {
7631 return $expect_out(1,string)
7632 }
7633 -re "The target character set is \"(\[^\"\]*)\".*$gdb_prompt $" {
7634 return $expect_out(1,string)
7635 }
7636 }
7637
7638 # Pick a reasonable default.
7639 warning "Unable to read target-charset."
7640 return "UTF-8"
7641 }
7642
7643 # Get the address of VAR.
7644
7645 proc get_var_address { var } {
7646 global gdb_prompt hex
7647
7648 # Match output like:
7649 # $1 = (int *) 0x0
7650 # $5 = (int (*)()) 0
7651 # $6 = (int (*)()) 0x24 <function_bar>
7652
7653 gdb_test_multiple "print &${var}" "get address of ${var}" {
7654 -re "\\\$\[0-9\]+ = \\(.*\\) (0|$hex)( <${var}>)?\[\r\n\]+${gdb_prompt} $"
7655 {
7656 pass "get address of ${var}"
7657 if { $expect_out(1,string) == "0" } {
7658 return "0x0"
7659 } else {
7660 return $expect_out(1,string)
7661 }
7662 }
7663 }
7664 return ""
7665 }
7666
7667 # Return the frame number for the currently selected frame
7668 proc get_current_frame_number {{test_name ""}} {
7669 global gdb_prompt
7670
7671 if { $test_name == "" } {
7672 set test_name "get current frame number"
7673 }
7674 set frame_num -1
7675 gdb_test_multiple "frame" $test_name {
7676 -re "#(\[0-9\]+) .*$gdb_prompt $" {
7677 set frame_num $expect_out(1,string)
7678 }
7679 }
7680 return $frame_num
7681 }
7682
7683 # Get the current value for remotetimeout and return it.
7684 proc get_remotetimeout { } {
7685 global gdb_prompt
7686 global decimal
7687
7688 gdb_test_multiple "show remotetimeout" "" {
7689 -re "Timeout limit to wait for target to respond is ($decimal).*$gdb_prompt $" {
7690 return $expect_out(1,string)
7691 }
7692 }
7693
7694 # Pick the default that gdb uses
7695 warning "Unable to read remotetimeout"
7696 return 300
7697 }
7698
7699 # Set the remotetimeout to the specified timeout. Nothing is returned.
7700 proc set_remotetimeout { timeout } {
7701 global gdb_prompt
7702
7703 gdb_test_multiple "set remotetimeout $timeout" "" {
7704 -re "$gdb_prompt $" {
7705 verbose "Set remotetimeout to $timeout\n"
7706 }
7707 }
7708 }
7709
7710 # Get the target's current endianness and return it.
7711 proc get_endianness { } {
7712 global gdb_prompt
7713
7714 gdb_test_multiple "show endian" "determine endianness" {
7715 -re ".* (little|big) endian.*\r\n$gdb_prompt $" {
7716 # Pass silently.
7717 return $expect_out(1,string)
7718 }
7719 }
7720 return "little"
7721 }
7722
7723 # Get the target's default endianness and return it.
7724 gdb_caching_proc target_endianness {
7725 global gdb_prompt
7726
7727 set me "target_endianness"
7728
7729 set src { int main() { return 0; } }
7730 if {![gdb_simple_compile $me $src executable]} {
7731 return 0
7732 }
7733
7734 clean_restart $obj
7735 if ![runto_main] {
7736 return 0
7737 }
7738 set res [get_endianness]
7739
7740 gdb_exit
7741 remote_file build delete $obj
7742
7743 return $res
7744 }
7745
7746 # ROOT and FULL are file names. Returns the relative path from ROOT
7747 # to FULL. Note that FULL must be in a subdirectory of ROOT.
7748 # For example, given ROOT = /usr/bin and FULL = /usr/bin/ls, this
7749 # will return "ls".
7750
7751 proc relative_filename {root full} {
7752 set root_split [file split $root]
7753 set full_split [file split $full]
7754
7755 set len [llength $root_split]
7756
7757 if {[eval file join $root_split]
7758 != [eval file join [lrange $full_split 0 [expr {$len - 1}]]]} {
7759 error "$full not a subdir of $root"
7760 }
7761
7762 return [eval file join [lrange $full_split $len end]]
7763 }
7764
7765 # If GDB_PARALLEL exists, then set up the parallel-mode directories.
7766 if {[info exists GDB_PARALLEL]} {
7767 if {[is_remote host]} {
7768 unset GDB_PARALLEL
7769 } else {
7770 file mkdir \
7771 [make_gdb_parallel_path outputs] \
7772 [make_gdb_parallel_path temp] \
7773 [make_gdb_parallel_path cache]
7774 }
7775 }
7776
7777 # Set the inferior's cwd to the output directory, in order to have it
7778 # dump core there. This must be called before the inferior is
7779 # started.
7780
7781 proc set_inferior_cwd_to_output_dir {} {
7782 # Note this sets the inferior's cwd ("set cwd"), not GDB's ("cd").
7783 # If GDB crashes, we want its core dump in gdb/testsuite/, not in
7784 # the testcase's dir, so we can detect the unexpected core at the
7785 # end of the test run.
7786 if {![is_remote host]} {
7787 set output_dir [standard_output_file ""]
7788 gdb_test_no_output "set cwd $output_dir" \
7789 "set inferior cwd to test directory"
7790 }
7791 }
7792
7793 # Get the inferior's PID.
7794
7795 proc get_inferior_pid {} {
7796 set pid -1
7797 gdb_test_multiple "inferior" "get inferior pid" {
7798 -re "process (\[0-9\]*).*$::gdb_prompt $" {
7799 set pid $expect_out(1,string)
7800 pass $gdb_test_name
7801 }
7802 }
7803 return $pid
7804 }
7805
7806 # Find the kernel-produced core file dumped for the current testfile
7807 # program. PID was the inferior's pid, saved before the inferior
7808 # exited with a signal, or -1 if not known. If not on a remote host,
7809 # this assumes the core was generated in the output directory.
7810 # Returns the name of the core dump, or empty string if not found.
7811
7812 proc find_core_file {pid} {
7813 # For non-remote hosts, since cores are assumed to be in the
7814 # output dir, which we control, we use a laxer "core.*" glob. For
7815 # remote hosts, as we don't know whether the dir is being reused
7816 # for parallel runs, we use stricter names with no globs. It is
7817 # not clear whether this is really important, but it preserves
7818 # status quo ante.
7819 set files {}
7820 if {![is_remote host]} {
7821 lappend files core.*
7822 } elseif {$pid != -1} {
7823 lappend files core.$pid
7824 }
7825 lappend files ${::testfile}.core
7826 lappend files core
7827
7828 foreach file $files {
7829 if {![is_remote host]} {
7830 set names [glob -nocomplain [standard_output_file $file]]
7831 if {[llength $names] == 1} {
7832 return [lindex $names 0]
7833 }
7834 } else {
7835 if {[remote_file host exists $file]} {
7836 return $file
7837 }
7838 }
7839 }
7840 return ""
7841 }
7842
7843 # Check for production of a core file and remove it. PID is the
7844 # inferior's pid or -1 if not known. TEST is the test's message.
7845
7846 proc remove_core {pid {test ""}} {
7847 if {$test == ""} {
7848 set test "cleanup core file"
7849 }
7850
7851 set file [find_core_file $pid]
7852 if {$file != ""} {
7853 remote_file host delete $file
7854 pass "$test (removed)"
7855 } else {
7856 pass "$test (not found)"
7857 }
7858 }
7859
7860 proc core_find {binfile {deletefiles {}} {arg ""}} {
7861 global objdir subdir
7862
7863 set destcore "$binfile.core"
7864 file delete $destcore
7865
7866 # Create a core file named "$destcore" rather than just "core", to
7867 # avoid problems with sys admin types that like to regularly prune all
7868 # files named "core" from the system.
7869 #
7870 # Arbitrarily try setting the core size limit to "unlimited" since
7871 # this does not hurt on systems where the command does not work and
7872 # allows us to generate a core on systems where it does.
7873 #
7874 # Some systems append "core" to the name of the program; others append
7875 # the name of the program to "core"; still others (like Linux, as of
7876 # May 2003) create cores named "core.PID". In the latter case, we
7877 # could have many core files lying around, and it may be difficult to
7878 # tell which one is ours, so let's run the program in a subdirectory.
7879 set found 0
7880 set coredir [standard_output_file coredir.[getpid]]
7881 file mkdir $coredir
7882 catch "system \"(cd ${coredir}; ulimit -c unlimited; ${binfile} ${arg}; true) >/dev/null 2>&1\""
7883 # remote_exec host "${binfile}"
7884 foreach i "${coredir}/core ${coredir}/core.coremaker.c ${binfile}.core" {
7885 if [remote_file build exists $i] {
7886 remote_exec build "mv $i $destcore"
7887 set found 1
7888 }
7889 }
7890 # Check for "core.PID", "core.EXEC.PID.HOST.TIME", etc. It's fine
7891 # to use a glob here as we're looking inside a directory we
7892 # created. Also, this procedure only works on non-remote hosts.
7893 if { $found == 0 } {
7894 set names [glob -nocomplain -directory $coredir core.*]
7895 if {[llength $names] == 1} {
7896 set corefile [file join $coredir [lindex $names 0]]
7897 remote_exec build "mv $corefile $destcore"
7898 set found 1
7899 }
7900 }
7901 if { $found == 0 } {
7902 # The braindamaged HPUX shell quits after the ulimit -c above
7903 # without executing ${binfile}. So we try again without the
7904 # ulimit here if we didn't find a core file above.
7905 # Oh, I should mention that any "braindamaged" non-Unix system has
7906 # the same problem. I like the cd bit too, it's really neat'n stuff.
7907 catch "system \"(cd ${objdir}/${subdir}; ${binfile}; true) >/dev/null 2>&1\""
7908 foreach i "${objdir}/${subdir}/core ${objdir}/${subdir}/core.coremaker.c ${binfile}.core" {
7909 if [remote_file build exists $i] {
7910 remote_exec build "mv $i $destcore"
7911 set found 1
7912 }
7913 }
7914 }
7915
7916 # Try to clean up after ourselves.
7917 foreach deletefile $deletefiles {
7918 remote_file build delete [file join $coredir $deletefile]
7919 }
7920 remote_exec build "rmdir $coredir"
7921
7922 if { $found == 0 } {
7923 warning "can't generate a core file - core tests suppressed - check ulimit -c"
7924 return ""
7925 }
7926 return $destcore
7927 }
7928
7929 # gdb_target_symbol_prefix compiles a test program and then examines
7930 # the output from objdump to determine the prefix (such as underscore)
7931 # for linker symbol prefixes.
7932
7933 gdb_caching_proc gdb_target_symbol_prefix {
7934 # Compile a simple test program...
7935 set src { int main() { return 0; } }
7936 if {![gdb_simple_compile target_symbol_prefix $src executable]} {
7937 return 0
7938 }
7939
7940 set prefix ""
7941
7942 set objdump_program [gdb_find_objdump]
7943 set result [catch "exec $objdump_program --syms $obj" output]
7944
7945 if { $result == 0 \
7946 && ![regexp -lineanchor \
7947 { ([^ a-zA-Z0-9]*)main$} $output dummy prefix] } {
7948 verbose "gdb_target_symbol_prefix: Could not find main in objdump output; returning null prefix" 2
7949 }
7950
7951 file delete $obj
7952
7953 return $prefix
7954 }
7955
7956 # Return 1 if target supports scheduler locking, otherwise return 0.
7957
7958 gdb_caching_proc target_supports_scheduler_locking {
7959 global gdb_prompt
7960
7961 set me "gdb_target_supports_scheduler_locking"
7962
7963 set src { int main() { return 0; } }
7964 if {![gdb_simple_compile $me $src executable]} {
7965 return 0
7966 }
7967
7968 clean_restart $obj
7969 if ![runto_main] {
7970 return 0
7971 }
7972
7973 set supports_schedule_locking -1
7974 set current_schedule_locking_mode ""
7975
7976 set test "reading current scheduler-locking mode"
7977 gdb_test_multiple "show scheduler-locking" $test {
7978 -re "Mode for locking scheduler during execution is \"(\[\^\"\]*)\".*$gdb_prompt" {
7979 set current_schedule_locking_mode $expect_out(1,string)
7980 }
7981 -re "$gdb_prompt $" {
7982 set supports_schedule_locking 0
7983 }
7984 timeout {
7985 set supports_schedule_locking 0
7986 }
7987 }
7988
7989 if { $supports_schedule_locking == -1 } {
7990 set test "checking for scheduler-locking support"
7991 gdb_test_multiple "set scheduler-locking $current_schedule_locking_mode" $test {
7992 -re "Target '\[^'\]+' cannot support this command\..*$gdb_prompt $" {
7993 set supports_schedule_locking 0
7994 }
7995 -re "$gdb_prompt $" {
7996 set supports_schedule_locking 1
7997 }
7998 timeout {
7999 set supports_schedule_locking 0
8000 }
8001 }
8002 }
8003
8004 if { $supports_schedule_locking == -1 } {
8005 set supports_schedule_locking 0
8006 }
8007
8008 gdb_exit
8009 remote_file build delete $obj
8010 verbose "$me: returning $supports_schedule_locking" 2
8011 return $supports_schedule_locking
8012 }
8013
8014 # Return 1 if compiler supports use of nested functions. Otherwise,
8015 # return 0.
8016
8017 gdb_caching_proc support_nested_function_tests {
8018 # Compile a test program containing a nested function
8019 return [gdb_can_simple_compile nested_func {
8020 int main () {
8021 int foo () {
8022 return 0;
8023 }
8024 return foo ();
8025 }
8026 } executable]
8027 }
8028
8029 # gdb_target_symbol returns the provided symbol with the correct prefix
8030 # prepended. (See gdb_target_symbol_prefix, above.)
8031
8032 proc gdb_target_symbol { symbol } {
8033 set prefix [gdb_target_symbol_prefix]
8034 return "${prefix}${symbol}"
8035 }
8036
8037 # gdb_target_symbol_prefix_flags_asm returns a string that can be
8038 # added to gdb_compile options to define the C-preprocessor macro
8039 # SYMBOL_PREFIX with a value that can be prepended to symbols
8040 # for targets which require a prefix, such as underscore.
8041 #
8042 # This version (_asm) defines the prefix without double quotes
8043 # surrounding the prefix. It is used to define the macro
8044 # SYMBOL_PREFIX for assembly language files. Another version, below,
8045 # is used for symbols in inline assembler in C/C++ files.
8046 #
8047 # The lack of quotes in this version (_asm) makes it possible to
8048 # define supporting macros in the .S file. (The version which
8049 # uses quotes for the prefix won't work for such files since it's
8050 # impossible to define a quote-stripping macro in C.)
8051 #
8052 # It's possible to use this version (_asm) for C/C++ source files too,
8053 # but a string is usually required in such files; providing a version
8054 # (no _asm) which encloses the prefix with double quotes makes it
8055 # somewhat easier to define the supporting macros in the test case.
8056
8057 proc gdb_target_symbol_prefix_flags_asm {} {
8058 set prefix [gdb_target_symbol_prefix]
8059 if {$prefix ne ""} {
8060 return "additional_flags=-DSYMBOL_PREFIX=$prefix"
8061 } else {
8062 return "";
8063 }
8064 }
8065
8066 # gdb_target_symbol_prefix_flags returns the same string as
8067 # gdb_target_symbol_prefix_flags_asm, above, but with the prefix
8068 # enclosed in double quotes if there is a prefix.
8069 #
8070 # See the comment for gdb_target_symbol_prefix_flags_asm for an
8071 # extended discussion.
8072
8073 proc gdb_target_symbol_prefix_flags {} {
8074 set prefix [gdb_target_symbol_prefix]
8075 if {$prefix ne ""} {
8076 return "additional_flags=-DSYMBOL_PREFIX=\"$prefix\""
8077 } else {
8078 return "";
8079 }
8080 }
8081
8082 # A wrapper for 'remote_exec host' that passes or fails a test.
8083 # Returns 0 if all went well, nonzero on failure.
8084 # TEST is the name of the test, other arguments are as for remote_exec.
8085
8086 proc run_on_host { test program args } {
8087 verbose -log "run_on_host: $program $args"
8088 # remote_exec doesn't work properly if the output is set but the
8089 # input is the empty string -- so replace an empty input with
8090 # /dev/null.
8091 if {[llength $args] > 1 && [lindex $args 1] == ""} {
8092 set args [lreplace $args 1 1 "/dev/null"]
8093 }
8094 set result [eval remote_exec host [list $program] $args]
8095 verbose "result is $result"
8096 set status [lindex $result 0]
8097 set output [lindex $result 1]
8098 if {$status == 0} {
8099 pass $test
8100 return 0
8101 } else {
8102 verbose -log "run_on_host failed: $output"
8103 if { $output == "spawn failed" } {
8104 unsupported $test
8105 } else {
8106 fail $test
8107 }
8108 return -1
8109 }
8110 }
8111
8112 # Return non-zero if "board_info debug_flags" mentions Fission.
8113 # http://gcc.gnu.org/wiki/DebugFission
8114 # Fission doesn't support everything yet.
8115 # This supports working around bug 15954.
8116
8117 proc using_fission { } {
8118 set debug_flags [board_info [target_info name] debug_flags]
8119 return [regexp -- "-gsplit-dwarf" $debug_flags]
8120 }
8121
8122 # Search LISTNAME in uplevel LEVEL caller and set variables according to the
8123 # list of valid options with prefix PREFIX described by ARGSET.
8124 #
8125 # The first member of each one- or two-element list in ARGSET defines the
8126 # name of a variable that will be added to the caller's scope.
8127 #
8128 # If only one element is given to describe an option, it the value is
8129 # 0 if the option is not present in (the caller's) ARGS or 1 if
8130 # it is.
8131 #
8132 # If two elements are given, the second element is the default value of
8133 # the variable. This is then overwritten if the option exists in ARGS.
8134 # If EVAL, then subst is called on the value, which allows variables
8135 # to be used.
8136 #
8137 # Any parse_args elements in (the caller's) ARGS will be removed, leaving
8138 # any optional components.
8139 #
8140 # Example:
8141 # proc myproc {foo args} {
8142 # parse_list args 1 {{bar} {baz "abc"} {qux}} "-" false
8143 # # ...
8144 # }
8145 # myproc ABC -bar -baz DEF peanut butter
8146 # will define the following variables in myproc:
8147 # foo (=ABC), bar (=1), baz (=DEF), and qux (=0)
8148 # args will be the list {peanut butter}
8149
8150 proc parse_list { level listname argset prefix eval } {
8151 upvar $level $listname args
8152
8153 foreach argument $argset {
8154 if {[llength $argument] == 1} {
8155 # Normalize argument, strip leading/trailing whitespace.
8156 # Allows us to treat {foo} and { foo } the same.
8157 set argument [string trim $argument]
8158
8159 # No default specified, so we assume that we should set
8160 # the value to 1 if the arg is present and 0 if it's not.
8161 # It is assumed that no value is given with the argument.
8162 set pattern "$prefix$argument"
8163 set result [lsearch -exact $args $pattern]
8164
8165 if {$result != -1} {
8166 set value 1
8167 set args [lreplace $args $result $result]
8168 } else {
8169 set value 0
8170 }
8171 uplevel $level [list set $argument $value]
8172 } elseif {[llength $argument] == 2} {
8173 # There are two items in the argument. The second is a
8174 # default value to use if the item is not present.
8175 # Otherwise, the variable is set to whatever is provided
8176 # after the item in the args.
8177 set arg [lindex $argument 0]
8178 set pattern "$prefix[lindex $arg 0]"
8179 set result [lsearch -exact $args $pattern]
8180
8181 if {$result != -1} {
8182 set value [lindex $args [expr $result+1]]
8183 if { $eval } {
8184 set value [uplevel [expr $level + 1] [list subst $value]]
8185 }
8186 set args [lreplace $args $result [expr $result+1]]
8187 } else {
8188 set value [lindex $argument 1]
8189 if { $eval } {
8190 set value [uplevel $level [list subst $value]]
8191 }
8192 }
8193 uplevel $level [list set $arg $value]
8194 } else {
8195 error "Badly formatted argument \"$argument\" in argument set"
8196 }
8197 }
8198 }
8199
8200 # Search the caller's args variable and set variables according to the list of
8201 # valid options described by ARGSET.
8202
8203 proc parse_args { argset } {
8204 parse_list 2 args $argset "-" false
8205
8206 # The remaining args should be checked to see that they match the
8207 # number of items expected to be passed into the procedure...
8208 }
8209
8210 # Process the caller's options variable and set variables according
8211 # to the list of valid options described by OPTIONSET.
8212
8213 proc parse_options { optionset } {
8214 parse_list 2 options $optionset "" true
8215
8216 # Require no remaining options.
8217 upvar 1 options options
8218 if { [llength $options] != 0 } {
8219 error "Options left unparsed: $options"
8220 }
8221 }
8222
8223 # Capture the output of COMMAND in a string ignoring PREFIX (a regexp);
8224 # return that string.
8225
8226 proc capture_command_output { command prefix } {
8227 global gdb_prompt
8228 global expect_out
8229
8230 set test "capture_command_output for $command"
8231
8232 set output_string ""
8233 gdb_test_multiple $command $test {
8234 -re "^(\[^\r\n\]+\r\n)" {
8235 if { ![string equal $output_string ""] } {
8236 set output_string [join [list $output_string $expect_out(1,string)] ""]
8237 } else {
8238 set output_string $expect_out(1,string)
8239 }
8240 exp_continue
8241 }
8242
8243 -re "^$gdb_prompt $" {
8244 }
8245 }
8246
8247 # Strip the command.
8248 set command_re [string_to_regexp ${command}]
8249 set output_string [regsub ^$command_re\r\n $output_string ""]
8250
8251 # Strip the prefix.
8252 if { $prefix != "" } {
8253 set output_string [regsub ^$prefix $output_string ""]
8254 }
8255
8256 # Strip a trailing newline.
8257 set output_string [regsub "\r\n$" $output_string ""]
8258
8259 return $output_string
8260 }
8261
8262 # A convenience function that joins all the arguments together, with a
8263 # regexp that matches exactly one end of line in between each argument.
8264 # This function is ideal to write the expected output of a GDB command
8265 # that generates more than a couple of lines, as this allows us to write
8266 # each line as a separate string, which is easier to read by a human
8267 # being.
8268
8269 proc multi_line { args } {
8270 if { [llength $args] == 1 } {
8271 set hint "forgot {*} before list argument?"
8272 error "multi_line called with one argument ($hint)"
8273 }
8274 return [join $args "\r\n"]
8275 }
8276
8277 # Similar to the above, but while multi_line is meant to be used to
8278 # match GDB output, this one is meant to be used to build strings to
8279 # send as GDB input.
8280
8281 proc multi_line_input { args } {
8282 return [join $args "\n"]
8283 }
8284
8285 # Return how many newlines there are in the given string.
8286
8287 proc count_newlines { string } {
8288 return [regexp -all "\n" $string]
8289 }
8290
8291 # Return the version of the DejaGnu framework.
8292 #
8293 # The return value is a list containing the major, minor and patch version
8294 # numbers. If the version does not contain a minor or patch number, they will
8295 # be set to 0. For example:
8296 #
8297 # 1.6 -> {1 6 0}
8298 # 1.6.1 -> {1 6 1}
8299 # 2 -> {2 0 0}
8300
8301 proc dejagnu_version { } {
8302 # The frame_version variable is defined by DejaGnu, in runtest.exp.
8303 global frame_version
8304
8305 verbose -log "DejaGnu version: $frame_version"
8306 verbose -log "Expect version: [exp_version]"
8307 verbose -log "Tcl version: [info tclversion]"
8308
8309 set dg_ver [split $frame_version .]
8310
8311 while { [llength $dg_ver] < 3 } {
8312 lappend dg_ver 0
8313 }
8314
8315 return $dg_ver
8316 }
8317
8318 # Define user-defined command COMMAND using the COMMAND_LIST as the
8319 # command's definition. The terminating "end" is added automatically.
8320
8321 proc gdb_define_cmd {command command_list} {
8322 global gdb_prompt
8323
8324 set input [multi_line_input {*}$command_list "end"]
8325 set test "define $command"
8326
8327 gdb_test_multiple "define $command" $test {
8328 -re "End with" {
8329 gdb_test_multiple $input $test {
8330 -re "\r\n$gdb_prompt " {
8331 }
8332 }
8333 }
8334 }
8335 }
8336
8337 # Override the 'cd' builtin with a version that ensures that the
8338 # log file keeps pointing at the same file. We need this because
8339 # unfortunately the path to the log file is recorded using an
8340 # relative path name, and, we sometimes need to close/reopen the log
8341 # after changing the current directory. See get_compiler_info.
8342
8343 rename cd builtin_cd
8344
8345 proc cd { dir } {
8346
8347 # Get the existing log file flags.
8348 set log_file_info [log_file -info]
8349
8350 # Split the flags into args and file name.
8351 set log_file_flags ""
8352 set log_file_file ""
8353 foreach arg [ split "$log_file_info" " "] {
8354 if [string match "-*" $arg] {
8355 lappend log_file_flags $arg
8356 } else {
8357 lappend log_file_file $arg
8358 }
8359 }
8360
8361 # If there was an existing file, ensure it is an absolute path, and then
8362 # reset logging.
8363 if { $log_file_file != "" } {
8364 set log_file_file [file normalize $log_file_file]
8365 log_file
8366 log_file $log_file_flags "$log_file_file"
8367 }
8368
8369 # Call the builtin version of cd.
8370 builtin_cd $dir
8371 }
8372
8373 # Return a list of all languages supported by GDB, suitable for use in
8374 # 'set language NAME'. This doesn't include either the 'local' or
8375 # 'auto' keywords.
8376 proc gdb_supported_languages {} {
8377 return [list c objective-c c++ d go fortran modula-2 asm pascal \
8378 opencl rust minimal ada]
8379 }
8380
8381 # Check if debugging is enabled for gdb.
8382
8383 proc gdb_debug_enabled { } {
8384 global gdbdebug
8385
8386 # If not already read, get the debug setting from environment or board setting.
8387 if {![info exists gdbdebug]} {
8388 global env
8389 if [info exists env(GDB_DEBUG)] {
8390 set gdbdebug $env(GDB_DEBUG)
8391 } elseif [target_info exists gdb,debug] {
8392 set gdbdebug [target_info gdb,debug]
8393 } else {
8394 return 0
8395 }
8396 }
8397
8398 # Ensure it not empty.
8399 return [expr { $gdbdebug != "" }]
8400 }
8401
8402 # Turn on debugging if enabled, or reset if already on.
8403
8404 proc gdb_debug_init { } {
8405
8406 global gdb_prompt
8407
8408 if ![gdb_debug_enabled] {
8409 return;
8410 }
8411
8412 # First ensure logging is off.
8413 send_gdb "set logging enabled off\n"
8414
8415 set debugfile [standard_output_file gdb.debug]
8416 send_gdb "set logging file $debugfile\n"
8417
8418 send_gdb "set logging debugredirect\n"
8419
8420 global gdbdebug
8421 foreach entry [split $gdbdebug ,] {
8422 send_gdb "set debug $entry 1\n"
8423 }
8424
8425 # Now that everything is set, enable logging.
8426 send_gdb "set logging enabled on\n"
8427 gdb_expect 10 {
8428 -re "Copying output to $debugfile.*Redirecting debug output to $debugfile.*$gdb_prompt $" {}
8429 timeout { warning "Couldn't set logging file" }
8430 }
8431 }
8432
8433 # Check if debugging is enabled for gdbserver.
8434
8435 proc gdbserver_debug_enabled { } {
8436 # Always disabled for GDB only setups.
8437 return 0
8438 }
8439
8440 # Open the file for logging gdb input
8441
8442 proc gdb_stdin_log_init { } {
8443 gdb_persistent_global in_file
8444
8445 if {[info exists in_file]} {
8446 # Close existing file.
8447 catch "close $in_file"
8448 }
8449
8450 set logfile [standard_output_file_with_gdb_instance gdb.in]
8451 set in_file [open $logfile w]
8452 }
8453
8454 # Write to the file for logging gdb input.
8455 # TYPE can be one of the following:
8456 # "standard" : Default. Standard message written to the log
8457 # "answer" : Answer to a question (eg "Y"). Not written the log.
8458 # "optional" : Optional message. Not written to the log.
8459
8460 proc gdb_stdin_log_write { message {type standard} } {
8461
8462 global in_file
8463 if {![info exists in_file]} {
8464 return
8465 }
8466
8467 # Check message types.
8468 switch -regexp -- $type {
8469 "answer" {
8470 return
8471 }
8472 "optional" {
8473 return
8474 }
8475 }
8476
8477 # Write to the log and make sure the output is there, even in case
8478 # of crash.
8479 puts -nonewline $in_file "$message"
8480 flush $in_file
8481 }
8482
8483 # Write the command line used to invocate gdb to the cmd file.
8484
8485 proc gdb_write_cmd_file { cmdline } {
8486 set logfile [standard_output_file_with_gdb_instance gdb.cmd]
8487 set cmd_file [open $logfile w]
8488 puts $cmd_file $cmdline
8489 catch "close $cmd_file"
8490 }
8491
8492 # Compare contents of FILE to string STR. Pass with MSG if equal, otherwise
8493 # fail with MSG.
8494
8495 proc cmp_file_string { file str msg } {
8496 if { ![file exists $file]} {
8497 fail "$msg"
8498 return
8499 }
8500
8501 set caught_error [catch {
8502 set fp [open "$file" r]
8503 set file_contents [read $fp]
8504 close $fp
8505 } error_message]
8506 if {$caught_error} {
8507 error "$error_message"
8508 fail "$msg"
8509 return
8510 }
8511
8512 if { $file_contents == $str } {
8513 pass "$msg"
8514 } else {
8515 fail "$msg"
8516 }
8517 }
8518
8519 # Compare FILE1 and FILE2 as binary files. Return 0 if the files are
8520 # equal, otherwise, return non-zero.
8521
8522 proc cmp_binary_files { file1 file2 } {
8523 set fd1 [open $file1]
8524 fconfigure $fd1 -translation binary
8525 set fd2 [open $file2]
8526 fconfigure $fd2 -translation binary
8527
8528 set blk_size 1024
8529 while {true} {
8530 set blk1 [read $fd1 $blk_size]
8531 set blk2 [read $fd2 $blk_size]
8532 set diff [string compare $blk1 $blk2]
8533 if {$diff != 0 || [eof $fd1] || [eof $fd2]} {
8534 close $fd1
8535 close $fd2
8536 return $diff
8537 }
8538 }
8539 }
8540
8541 # Does the compiler support CTF debug output using '-gctf' compiler
8542 # flag? If not then we should skip these tests. We should also
8543 # skip them if libctf was explicitly disabled.
8544
8545 gdb_caching_proc skip_ctf_tests {
8546 global enable_libctf
8547
8548 if {$enable_libctf eq "no"} {
8549 return 1
8550 }
8551
8552 set can_ctf [gdb_can_simple_compile ctfdebug {
8553 int main () {
8554 return 0;
8555 }
8556 } executable "additional_flags=-gctf"]
8557
8558 return [expr {!$can_ctf}]
8559 }
8560
8561 # Return 1 if compiler supports -gstatement-frontiers. Otherwise,
8562 # return 0.
8563
8564 gdb_caching_proc supports_statement_frontiers {
8565 return [gdb_can_simple_compile supports_statement_frontiers {
8566 int main () {
8567 return 0;
8568 }
8569 } executable "additional_flags=-gstatement-frontiers"]
8570 }
8571
8572 # Return 1 if compiler supports -mmpx -fcheck-pointer-bounds. Otherwise,
8573 # return 0.
8574
8575 gdb_caching_proc supports_mpx_check_pointer_bounds {
8576 set flags "additional_flags=-mmpx additional_flags=-fcheck-pointer-bounds"
8577 return [gdb_can_simple_compile supports_mpx_check_pointer_bounds {
8578 int main () {
8579 return 0;
8580 }
8581 } executable $flags]
8582 }
8583
8584 # Return 1 if compiler supports -fcf-protection=. Otherwise,
8585 # return 0.
8586
8587 gdb_caching_proc supports_fcf_protection {
8588 return [gdb_can_simple_compile supports_fcf_protection {
8589 int main () {
8590 return 0;
8591 }
8592 } executable "additional_flags=-fcf-protection=full"]
8593 }
8594
8595 # Return true if symbols were read in using -readnow. Otherwise,
8596 # return false.
8597
8598 proc readnow { } {
8599 return [expr {[lsearch -exact $::GDBFLAGS -readnow] != -1
8600 || [lsearch -exact $::GDBFLAGS --readnow] != -1}]
8601 }
8602
8603 # Return index name if symbols were read in using an index.
8604 # Otherwise, return "".
8605
8606 proc have_index { objfile } {
8607
8608 set res ""
8609 set cmd "maint print objfiles $objfile"
8610 gdb_test_multiple $cmd "" -lbl {
8611 -re "\r\n.gdb_index: faked for \"readnow\"" {
8612 set res ""
8613 exp_continue
8614 }
8615 -re "\r\n.gdb_index:" {
8616 set res "gdb_index"
8617 exp_continue
8618 }
8619 -re "\r\n.debug_names:" {
8620 set res "debug_names"
8621 exp_continue
8622 }
8623 -re -wrap "" {
8624 # We don't care about any other input.
8625 }
8626 }
8627
8628 return $res
8629 }
8630
8631 # Return 1 if partial symbols are available. Otherwise, return 0.
8632
8633 proc psymtabs_p { } {
8634 global gdb_prompt
8635
8636 set cmd "maint info psymtab"
8637 gdb_test_multiple $cmd "" {
8638 -re "$cmd\r\n$gdb_prompt $" {
8639 return 0
8640 }
8641 -re -wrap "" {
8642 return 1
8643 }
8644 }
8645
8646 return 0
8647 }
8648
8649 # Verify that partial symtab expansion for $filename has state $readin.
8650
8651 proc verify_psymtab_expanded { filename readin } {
8652 global gdb_prompt
8653
8654 set cmd "maint info psymtab"
8655 set test "$cmd: $filename: $readin"
8656 set re [multi_line \
8657 " \{ psymtab \[^\r\n\]*$filename\[^\r\n\]*" \
8658 " readin $readin" \
8659 ".*"]
8660
8661 gdb_test_multiple $cmd $test {
8662 -re "$cmd\r\n$gdb_prompt $" {
8663 unsupported $gdb_test_name
8664 }
8665 -re -wrap $re {
8666 pass $gdb_test_name
8667 }
8668 }
8669 }
8670
8671 # Add a .gdb_index section to PROGRAM.
8672 # PROGRAM is assumed to be the output of standard_output_file.
8673 # Returns the 0 if there is a failure, otherwise 1.
8674 #
8675 # STYLE controls which style of index to add, if needed. The empty
8676 # string (the default) means .gdb_index; "-dwarf-5" means .debug_names.
8677
8678 proc add_gdb_index { program {style ""} } {
8679 global srcdir GDB env
8680 set contrib_dir "$srcdir/../contrib"
8681 set env(GDB) [append_gdb_data_directory_option $GDB]
8682 set result [catch "exec $contrib_dir/gdb-add-index.sh $style $program" output]
8683 if { $result != 0 } {
8684 verbose -log "result is $result"
8685 verbose -log "output is $output"
8686 return 0
8687 }
8688
8689 return 1
8690 }
8691
8692 # Add a .gdb_index section to PROGRAM, unless it alread has an index
8693 # (.gdb_index/.debug_names). Gdb doesn't support building an index from a
8694 # program already using one. Return 1 if a .gdb_index was added, return 0
8695 # if it already contained an index, and -1 if an error occurred.
8696 #
8697 # STYLE controls which style of index to add, if needed. The empty
8698 # string (the default) means .gdb_index; "-dwarf-5" means .debug_names.
8699
8700 proc ensure_gdb_index { binfile {style ""} } {
8701 global decimal
8702
8703 set testfile [file tail $binfile]
8704 set test "check if index present"
8705 set has_index 0
8706 set has_readnow 0
8707 gdb_test_multiple "mt print objfiles ${testfile}" $test -lbl {
8708 -re "\r\n\\.gdb_index: version ${decimal}(?=\r\n)" {
8709 set has_index 1
8710 gdb_test_lines "" $gdb_test_name ".*"
8711 }
8712 -re "\r\n\\.debug_names: exists(?=\r\n)" {
8713 set has_index 1
8714 gdb_test_lines "" $gdb_test_name ".*"
8715 }
8716 -re "\r\n(Cooked index in use|Psymtabs)(?=\r\n)" {
8717 gdb_test_lines "" $gdb_test_name ".*"
8718 }
8719 -re ".gdb_index: faked for \"readnow\"" {
8720 set has_readnow 1
8721 gdb_test_lines "" $gdb_test_name ".*"
8722 }
8723 -re -wrap "" {
8724 fail $gdb_test_name
8725 }
8726 }
8727
8728 if { $has_index } {
8729 return 0
8730 }
8731
8732 if { $has_readnow } {
8733 return -1
8734 }
8735
8736 if { [add_gdb_index $binfile $style] == "1" } {
8737 return 1
8738 }
8739
8740 return -1
8741 }
8742
8743 # Return 1 if executable contains .debug_types section. Otherwise, return 0.
8744
8745 proc debug_types { } {
8746 global hex
8747
8748 set cmd "maint info sections"
8749 gdb_test_multiple $cmd "" {
8750 -re -wrap "at $hex: .debug_types.*" {
8751 return 1
8752 }
8753 -re -wrap "" {
8754 return 0
8755 }
8756 }
8757
8758 return 0
8759 }
8760
8761 # Return the addresses in the line table for FILE for which is_stmt is true.
8762
8763 proc is_stmt_addresses { file } {
8764 global decimal
8765 global hex
8766
8767 set is_stmt [list]
8768
8769 gdb_test_multiple "maint info line-table $file" "" {
8770 -re "\r\n$decimal\[ \t\]+$decimal\[ \t\]+($hex)\[ \t\]+Y\[^\r\n\]*" {
8771 lappend is_stmt $expect_out(1,string)
8772 exp_continue
8773 }
8774 -re -wrap "" {
8775 }
8776 }
8777
8778 return $is_stmt
8779 }
8780
8781 # Return 1 if hex number VAL is an element of HEXLIST.
8782
8783 proc hex_in_list { val hexlist } {
8784 # Normalize val by removing 0x prefix, and leading zeros.
8785 set val [regsub ^0x $val ""]
8786 set val [regsub ^0+ $val "0"]
8787
8788 set re 0x0*$val
8789 set index [lsearch -regexp $hexlist $re]
8790 return [expr $index != -1]
8791 }
8792
8793 # Override proc NAME to proc OVERRIDE for the duration of the execution of
8794 # BODY.
8795
8796 proc with_override { name override body } {
8797 # Implementation note: It's possible to implement the override using
8798 # rename, like this:
8799 # rename $name save_$name
8800 # rename $override $name
8801 # set code [catch {uplevel 1 $body} result]
8802 # rename $name $override
8803 # rename save_$name $name
8804 # but there are two issues here:
8805 # - the save_$name might clash with an existing proc
8806 # - the override is no longer available under its original name during
8807 # the override
8808 # So, we use this more elaborate but cleaner mechanism.
8809
8810 # Save the old proc, if it exists.
8811 if { [info procs $name] != "" } {
8812 set old_args [info args $name]
8813 set old_body [info body $name]
8814 set existed true
8815 } else {
8816 set existed false
8817 }
8818
8819 # Install the override.
8820 set new_args [info args $override]
8821 set new_body [info body $override]
8822 eval proc $name {$new_args} {$new_body}
8823
8824 # Execute body.
8825 set code [catch {uplevel 1 $body} result]
8826
8827 # Restore old proc if it existed on entry, else delete it.
8828 if { $existed } {
8829 eval proc $name {$old_args} {$old_body}
8830 } else {
8831 rename $name ""
8832 }
8833
8834 # Return as appropriate.
8835 if { $code == 1 } {
8836 global errorInfo errorCode
8837 return -code error -errorinfo $errorInfo -errorcode $errorCode $result
8838 } elseif { $code > 1 } {
8839 return -code $code $result
8840 }
8841
8842 return $result
8843 }
8844
8845 # Setup tuiterm.exp environment. To be used in test-cases instead of
8846 # "load_lib tuiterm.exp". Calls initialization function and schedules
8847 # finalization function.
8848 proc tuiterm_env { } {
8849 load_lib tuiterm.exp
8850 }
8851
8852 # Dejagnu has a version of note, but usage is not allowed outside of dejagnu.
8853 # Define a local version.
8854 proc gdb_note { message } {
8855 verbose -- "NOTE: $message" 0
8856 }
8857
8858 # Return 1 if compiler supports -fuse-ld=gold, otherwise return 0.
8859 gdb_caching_proc have_fuse_ld_gold {
8860 set me "have_fuse_ld_gold"
8861 set flags "additional_flags=-fuse-ld=gold"
8862 set src { int main() { return 0; } }
8863 return [gdb_simple_compile $me $src executable $flags]
8864 }
8865
8866 # Return 1 if compiler supports fvar-tracking, otherwise return 0.
8867 gdb_caching_proc have_fvar_tracking {
8868 set me "have_fvar_tracking"
8869 set flags "additional_flags=-fvar-tracking"
8870 set src { int main() { return 0; } }
8871 return [gdb_simple_compile $me $src executable $flags]
8872 }
8873
8874 # Return 1 if linker supports -Ttext-segment, otherwise return 0.
8875 gdb_caching_proc linker_supports_Ttext_segment_flag {
8876 set me "linker_supports_Ttext_segment_flag"
8877 set flags ldflags="-Wl,-Ttext-segment=0x7000000"
8878 set src { int main() { return 0; } }
8879 return [gdb_simple_compile $me $src executable $flags]
8880 }
8881
8882 # Return 1 if linker supports -Ttext, otherwise return 0.
8883 gdb_caching_proc linker_supports_Ttext_flag {
8884 set me "linker_supports_Ttext_flag"
8885 set flags ldflags="-Wl,-Ttext=0x7000000"
8886 set src { int main() { return 0; } }
8887 return [gdb_simple_compile $me $src executable $flags]
8888 }
8889
8890 # Return 1 if linker supports --image-base, otherwise 0.
8891 gdb_caching_proc linker_supports_image_base_flag {
8892 set me "linker_supports_image_base_flag"
8893 set flags ldflags="-Wl,--image-base=0x7000000"
8894 set src { int main() { return 0; } }
8895 return [gdb_simple_compile $me $src executable $flags]
8896 }
8897
8898
8899 # Return 1 if compiler supports scalar_storage_order attribute, otherwise
8900 # return 0.
8901 gdb_caching_proc supports_scalar_storage_order_attribute {
8902 set me "supports_scalar_storage_order_attribute"
8903 set src {
8904 #include <string.h>
8905 struct sle {
8906 int v;
8907 } __attribute__((scalar_storage_order("little-endian")));
8908 struct sbe {
8909 int v;
8910 } __attribute__((scalar_storage_order("big-endian")));
8911 struct sle sle;
8912 struct sbe sbe;
8913 int main () {
8914 sle.v = sbe.v = 0x11223344;
8915 int same = memcmp (&sle, &sbe, sizeof (int)) == 0;
8916 int sso = !same;
8917 return sso;
8918 }
8919 }
8920 if { ![gdb_simple_compile $me $src executable ""] } {
8921 return 0
8922 }
8923
8924 set result [remote_exec target $obj]
8925 set status [lindex $result 0]
8926 set output [lindex $result 1]
8927 if { $output != "" } {
8928 return 0
8929 }
8930
8931 return $status
8932 }
8933
8934 # Return 1 if compiler supports __GNUC__, otherwise return 0.
8935 gdb_caching_proc supports_gnuc {
8936 set me "supports_gnuc"
8937 set src {
8938 #ifndef __GNUC__
8939 #error "No gnuc"
8940 #endif
8941 }
8942 return [gdb_simple_compile $me $src object ""]
8943 }
8944
8945 # Return 1 if target supports mpx, otherwise return 0.
8946 gdb_caching_proc have_mpx {
8947 global srcdir
8948
8949 set me "have_mpx"
8950 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
8951 verbose "$me: target does not support mpx, returning 0" 2
8952 return 0
8953 }
8954
8955 # Compile a test program.
8956 set src {
8957 #include "nat/x86-cpuid.h"
8958
8959 int main() {
8960 unsigned int eax, ebx, ecx, edx;
8961
8962 if (!__get_cpuid (1, &eax, &ebx, &ecx, &edx))
8963 return 0;
8964
8965 if ((ecx & bit_OSXSAVE) == bit_OSXSAVE)
8966 {
8967 if (__get_cpuid_max (0, (void *)0) < 7)
8968 return 0;
8969
8970 __cpuid_count (7, 0, eax, ebx, ecx, edx);
8971
8972 if ((ebx & bit_MPX) == bit_MPX)
8973 return 1;
8974
8975 }
8976 return 0;
8977 }
8978 }
8979 set compile_flags "incdir=${srcdir}/.."
8980 if {![gdb_simple_compile $me $src executable $compile_flags]} {
8981 return 0
8982 }
8983
8984 set result [remote_exec target $obj]
8985 set status [lindex $result 0]
8986 set output [lindex $result 1]
8987 if { $output != "" } {
8988 set status 0
8989 }
8990
8991 remote_file build delete $obj
8992
8993 if { $status == 0 } {
8994 verbose "$me: returning $status" 2
8995 return $status
8996 }
8997
8998 # Compile program with -mmpx -fcheck-pointer-bounds, try to trigger
8999 # 'No MPX support', in other words, see if kernel supports mpx.
9000 set src { int main (void) { return 0; } }
9001 set comp_flags {}
9002 append comp_flags " additional_flags=-mmpx"
9003 append comp_flags " additional_flags=-fcheck-pointer-bounds"
9004 if {![gdb_simple_compile $me-2 $src executable $comp_flags]} {
9005 return 0
9006 }
9007
9008 set result [remote_exec target $obj]
9009 set status [lindex $result 0]
9010 set output [lindex $result 1]
9011 set status [expr ($status == 0) \
9012 && ![regexp "^No MPX support\r?\n" $output]]
9013
9014 remote_file build delete $obj
9015
9016 verbose "$me: returning $status" 2
9017 return $status
9018 }
9019
9020 # Return 1 if target supports avx, otherwise return 0.
9021 gdb_caching_proc have_avx {
9022 global srcdir
9023
9024 set me "have_avx"
9025 if { ![istarget "i?86-*-*"] && ![istarget "x86_64-*-*"] } {
9026 verbose "$me: target does not support avx, returning 0" 2
9027 return 0
9028 }
9029
9030 # Compile a test program.
9031 set src {
9032 #include "nat/x86-cpuid.h"
9033
9034 int main() {
9035 unsigned int eax, ebx, ecx, edx;
9036
9037 if (!x86_cpuid (1, &eax, &ebx, &ecx, &edx))
9038 return 0;
9039
9040 if ((ecx & (bit_AVX | bit_OSXSAVE)) == (bit_AVX | bit_OSXSAVE))
9041 return 1;
9042 else
9043 return 0;
9044 }
9045 }
9046 set compile_flags "incdir=${srcdir}/.."
9047 if {![gdb_simple_compile $me $src executable $compile_flags]} {
9048 return 0
9049 }
9050
9051 set result [remote_exec target $obj]
9052 set status [lindex $result 0]
9053 set output [lindex $result 1]
9054 if { $output != "" } {
9055 set status 0
9056 }
9057
9058 remote_file build delete $obj
9059
9060 verbose "$me: returning $status" 2
9061 return $status
9062 }
9063
9064 # Called as
9065 # - require ARG...
9066 #
9067 # ARG can either be a name, or of the form !NAME.
9068 #
9069 # Each name is a proc to evaluate in the caller's context. It returns
9070 # a boolean, and a "!" means to invert the result. If this is
9071 # nonzero, all is well. If it is zero, an "untested" is emitted and
9072 # this proc causes the caller to return.
9073
9074 proc require { args } {
9075 foreach arg $args {
9076 if {[string index $arg 0] == "!"} {
9077 set ok 0
9078 set fn [string range $arg 1 end]
9079 } else {
9080 set ok 1
9081 set fn $arg
9082 }
9083 if {$ok != !![uplevel 1 $fn]} {
9084 untested "require failed: $arg"
9085 return -code return 0
9086 }
9087 }
9088 }
9089
9090 # Wait up to ::TIMEOUT seconds for file PATH to exist on the target system.
9091 # Return 1 if it does exist, 0 otherwise.
9092
9093 proc target_file_exists_with_timeout { path } {
9094 for {set i 0} {$i < $::timeout} {incr i} {
9095 if { [remote_file target exists $path] } {
9096 return 1
9097 }
9098
9099 sleep 1
9100 }
9101
9102 return 0
9103 }
9104
9105 gdb_caching_proc has_hw_wp_support {
9106 # Power 9, proc rev 2.2 does not support HW watchpoints due to HW bug.
9107 # Need to use a runtime test to determine if the Power processor has
9108 # support for HW watchpoints.
9109 global srcdir subdir gdb_prompt inferior_exited_re
9110
9111 set me "has_hw_wp_support"
9112
9113 global gdb_spawn_id
9114 if { [info exists gdb_spawn_id] } {
9115 error "$me called with running gdb instance"
9116 }
9117
9118 set compile_flags {debug nowarnings quiet}
9119
9120 # Compile a test program to test if HW watchpoints are supported
9121 set src {
9122 int main (void) {
9123 volatile int local;
9124 local = 1;
9125 if (local == 1)
9126 return 1;
9127 return 0;
9128 }
9129 }
9130
9131 if {![gdb_simple_compile $me $src executable $compile_flags]} {
9132 return 0
9133 }
9134
9135 gdb_start
9136 gdb_reinitialize_dir $srcdir/$subdir
9137 gdb_load "$obj"
9138
9139 if ![runto_main] {
9140 gdb_exit
9141 remote_file build delete $obj
9142
9143 set has_hw_wp_support 0
9144 return $has_hw_wp_support
9145 }
9146
9147 # The goal is to determine if HW watchpoints are available in general.
9148 # Use "watch" and then check if gdb responds with hardware watch point.
9149 set test "watch local"
9150
9151 gdb_test_multiple $test "Check for HW watchpoint support" {
9152 -re ".*Hardware watchpoint.*" {
9153 # HW watchpoint supported by platform
9154 verbose -log "\n$me: Hardware watchpoint detected"
9155 set has_hw_wp_support 1
9156 }
9157 -re ".*$gdb_prompt $" {
9158 set has_hw_wp_support 0
9159 verbose -log "\n$me: Default, hardware watchpoint not deteced"
9160 }
9161 }
9162
9163 gdb_exit
9164 remote_file build delete $obj
9165
9166 verbose "$me: returning $has_hw_wp_support" 2
9167 return $has_hw_wp_support
9168 }
9169
9170 # Return a list of all the accepted values of the set command
9171 # "SET_CMD SET_ARG".
9172 # For example get_set_option_choices "set architecture" "i386".
9173
9174 proc get_set_option_choices { set_cmd {set_arg ""} } {
9175 set values {}
9176
9177 if { $set_arg == "" } {
9178 # Add trailing space to signal that we need completion of the choices,
9179 # not of set_cmd itself.
9180 set cmd "complete $set_cmd "
9181 } else {
9182 set cmd "complete $set_cmd $set_arg"
9183 }
9184
9185 # Set test name without trailing space.
9186 set test [string trim $cmd]
9187
9188 with_set max-completions unlimited {
9189 gdb_test_multiple $cmd $test {
9190 -re "^[string_to_regexp $cmd]\r\n" {
9191 exp_continue
9192 }
9193
9194 -re "^$set_cmd (\[^\r\n\]+)\r\n" {
9195 lappend values $expect_out(1,string)
9196 exp_continue
9197 }
9198
9199 -re "^$::gdb_prompt $" {
9200 pass $gdb_test_name
9201 }
9202 }
9203 }
9204
9205 return $values
9206 }
9207
9208 # Return the compiler that can generate 32-bit ARM executables. Used
9209 # when testing biarch support on Aarch64. If ARM_CC_FOR_TARGET is
9210 # set, use that. If not, try a few common compiler names, making sure
9211 # that the executable they produce can run.
9212
9213 gdb_caching_proc arm_cc_for_target {
9214 if {[info exists ::ARM_CC_FOR_TARGET]} {
9215 # If the user specified the compiler explicitly, then don't
9216 # check whether the resulting binary runs outside GDB. Assume
9217 # that it does, and if it turns out it doesn't, then the user
9218 # should get loud FAILs, instead of UNSUPPORTED.
9219 return $::ARM_CC_FOR_TARGET
9220 }
9221
9222 # Fallback to a few common compiler names. Also confirm the
9223 # produced binary actually runs on the system before declaring
9224 # we've found the right compiler.
9225
9226 if [istarget "*-linux*-*"] {
9227 set compilers {
9228 arm-linux-gnueabi-gcc
9229 arm-none-linux-gnueabi-gcc
9230 arm-linux-gnueabihf-gcc
9231 }
9232 } else {
9233 set compilers {}
9234 }
9235
9236 foreach compiler $compilers {
9237 if {![is_remote host] && [which $compiler] == 0} {
9238 # Avoid "default_target_compile: Can't find
9239 # $compiler." warning issued from gdb_compile.
9240 continue
9241 }
9242
9243 set src { int main() { return 0; } }
9244 if {[gdb_simple_compile aarch64-32bit \
9245 $src \
9246 executable [list compiler=$compiler]]} {
9247
9248 set result [remote_exec target $obj]
9249 set status [lindex $result 0]
9250 set output [lindex $result 1]
9251
9252 file delete $obj
9253
9254 if { $output == "" && $status == 0} {
9255 return $compiler
9256 }
9257 }
9258 }
9259
9260 return ""
9261 }
9262
9263 # Step until the pattern REGEXP is found. Step at most
9264 # MAX_STEPS times, but stop stepping once REGEXP is found.
9265 #
9266 # If REGEXP is found then a single pass is emitted, otherwise, after
9267 # MAX_STEPS steps, a single fail is emitted.
9268 #
9269 # TEST_NAME is the name used in the pass/fail calls.
9270
9271 proc gdb_step_until { regexp {test_name ""} {max_steps 10} } {
9272 if { $test_name == "" } {
9273 set test_name "stepping until regexp"
9274 }
9275
9276 set count 0
9277 gdb_test_multiple "step" "$test_name" {
9278 -re "$regexp\r\n$::gdb_prompt $" {
9279 pass $test_name
9280 }
9281 -re ".*$::gdb_prompt $" {
9282 if {$count < $max_steps} {
9283 incr count
9284 send_gdb "step\n"
9285 exp_continue
9286 } else {
9287 fail $test_name
9288 }
9289 }
9290 }
9291 }
9292
9293 # Check if the compiler emits epilogue information associated
9294 # with the closing brace or with the last statement line.
9295 #
9296 # This proc restarts GDB
9297 #
9298 # Returns True if it is associated with the closing brace,
9299 # False if it is the last statement
9300 gdb_caching_proc have_epilogue_line_info {
9301
9302 set main {
9303 int
9304 main ()
9305 {
9306 return 0;
9307 }
9308 }
9309 if {![gdb_simple_compile "simple_program" $main]} {
9310 return False
9311 }
9312
9313 clean_restart $obj
9314
9315 gdb_test_multiple "info line 6" "epilogue test" {
9316 -re -wrap ".*starts at address.*and ends at.*" {
9317 return True
9318 }
9319 -re -wrap ".*" {
9320 return False
9321 }
9322 }
9323 }
9324
9325 # Decompress file BZ2, and return it.
9326
9327 proc decompress_bz2 { bz2 } {
9328 set copy [standard_output_file [file tail $bz2]]
9329 set copy [remote_download build $bz2 $copy]
9330 if { $copy == "" } {
9331 return $copy
9332 }
9333
9334 set res [remote_exec build "bzip2" "-df $copy"]
9335 if { [lindex $res 0] == -1 } {
9336 return ""
9337 }
9338
9339 set copy [regsub {.bz2$} $copy ""]
9340 if { ![remote_file build exists $copy] } {
9341 return ""
9342 }
9343
9344 return $copy
9345 }
9346
9347 # Return 1 if the output of "ldd FILE" contains regexp DEP, 0 if it doesn't,
9348 # and -1 if there was a problem running the command.
9349
9350 proc has_dependency { file dep } {
9351 set ldd [gdb_find_ldd]
9352 set command "$ldd $file"
9353 set result [remote_exec host $command]
9354 set status [lindex $result 0]
9355 set output [lindex $result 1]
9356 verbose -log "status of $command is $status"
9357 verbose -log "output of $command is $output"
9358 if { $status != 0 || $output == "" } {
9359 return -1
9360 }
9361 return [regexp $dep $output]
9362 }
9363
9364 # Always load compatibility stuff.
9365 load_lib future.exp