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