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