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