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