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