xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/testsuite/lib/mi-support.exp (revision 8b657b0747480f8989760d71343d6dd33f8d4cf9)
1# Copyright 1999-2023 Free Software Foundation, Inc.
2
3# This program is free software; you can redistribute it and/or modify
4# it under the terms of the GNU General Public License as published by
5# the Free Software Foundation; either version 3 of the License, or
6# (at your option) any later version.
7#
8# This program is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11# GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License
14# along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16# This file was based on a file written by Fred Fish. (fnf@cygnus.com)
17
18# Test setup routines that work with the MI interpreter.
19
20load_lib gdb-utils.exp
21
22# The variable mi_gdb_prompt is a regexp which matches the gdb mi prompt.
23# Set it if it is not already set.
24global mi_gdb_prompt
25if {![info exists mi_gdb_prompt]} {
26    set mi_gdb_prompt "\[(\]gdb\[)\] \r\n"
27}
28
29global mi_inferior_tty_name
30
31# Always points to GDB's main UI spawn ID, even when testing with MI
32# running on a secondary UI.
33global gdb_main_spawn_id
34
35# Points to the spawn id of the MI channel.  When testing with MI
36# running as the primary/main UI, this is the same as
37# gdb_main_spawn_id, but will be different when testing with MI
38# running on a secondary UI.
39global mi_spawn_id
40
41set MIFLAGS "-i=mi"
42
43set thread_selected_re "=thread-selected,id=\"\[0-9\]+\"\r\n"
44set gdbindex_warning_re "&\"warning: Skipping \[^\r\n\]+ \.gdb_index section in \[^\r\n\]+\"\r\n(?:&\"\\\\n\"\r\n)?"
45set library_loaded_re "=library-loaded\[^\n\]+\"\r\n(?:$gdbindex_warning_re)?"
46set breakpoint_re "=(?:breakpoint-created|breakpoint-deleted)\[^\n\]+\"\r\n"
47
48#
49# mi_gdb_exit -- exit the GDB, killing the target program if necessary
50#
51proc mi_gdb_exit {} {
52    catch mi_uncatched_gdb_exit
53}
54
55proc mi_uncatched_gdb_exit {} {
56    global GDB
57    global INTERNAL_GDBFLAGS GDBFLAGS
58    global gdb_spawn_id gdb_main_spawn_id
59    global mi_spawn_id inferior_spawn_id
60    global gdb_prompt
61    global mi_gdb_prompt
62    global MIFLAGS
63
64    if { [info procs sid_exit] != "" } {
65	sid_exit
66    }
67
68    if ![info exists gdb_spawn_id] {
69	return
70    }
71
72    verbose "Quitting $GDB $INTERNAL_GDBFLAGS $GDBFLAGS $MIFLAGS"
73
74    if { [is_remote host] && [board_info host exists fileid] } {
75	send_gdb "999-gdb-exit\n"
76	gdb_expect 10 {
77	    -re "y or n" {
78		send_gdb "y\n"
79		exp_continue
80	    }
81	    -re "Undefined command.*$gdb_prompt $" {
82		send_gdb "quit\n"
83		exp_continue
84	    }
85	    -re "DOSEXIT code" { }
86	    -re "\r\n999\\^exit\r\n" { }
87	}
88    }
89
90    # Switch back to the main spawn id, so that remote_close below
91    # closes it, and not a secondary channel.  Closing a secondary
92    # channel does not make GDB exit.
93    if {$gdb_spawn_id != $gdb_main_spawn_id} {
94	switch_gdb_spawn_id $gdb_main_spawn_id
95    }
96
97    # Close secondary MI channel, if there's one.
98    if {$mi_spawn_id != $gdb_main_spawn_id} {
99	close -i $mi_spawn_id
100    }
101
102    if ![is_remote host] {
103	remote_close host
104    }
105    unset gdb_spawn_id
106    unset gdb_main_spawn_id
107    unset mi_spawn_id
108    unset inferior_spawn_id
109}
110
111# Create the PTY for the inferior process and tell GDB about it.
112
113proc mi_create_inferior_pty {} {
114    global mi_gdb_prompt
115    global inferior_spawn_id
116    global mi_inferior_tty_name
117
118    spawn -pty
119    set inferior_spawn_id $spawn_id
120    set tty_name $spawn_out(slave,name)
121    set mi_inferior_tty_name $tty_name
122
123    send_gdb "102-inferior-tty-set $tty_name\n"
124    gdb_expect 10 {
125	-re ".*102\\\^done\r\n$mi_gdb_prompt$" {
126	    verbose "redirect inferior output to new terminal device."
127	}
128	timeout {
129	    warning "Couldn't redirect inferior output." 2
130	}
131    }
132}
133
134#
135# Like default_mi_gdb_start below, but the MI is created as a separate
136# ui in a new tty.  The global MI_SPAWN_ID is updated to point at the
137# new tty created for the MI interface.  The global GDB_MAIN_SPAWN_ID
138# is updated to the current value of the global GDB_SPAWN_ID.
139#
140proc mi_gdb_start_separate_mi_tty { { flags {} } } {
141    global gdb_prompt mi_gdb_prompt
142    global timeout
143    global gdb_spawn_id gdb_main_spawn_id mi_spawn_id
144    global inferior_spawn_id
145
146    set separate_inferior_pty 0
147
148    foreach flag $flags {
149	if {$flag == "separate-inferior-tty"} {
150	    set separate_inferior_pty 1
151	}
152    }
153
154    gdb_start
155
156    # Create the new PTY for the MI UI.
157    spawn -pty
158    set mi_spawn_id $spawn_id
159    set mi_tty_name $spawn_out(slave,name)
160    gdb_test_multiple "new-ui mi $mi_tty_name" "new-ui" {
161	-re "New UI allocated\r\n$gdb_prompt $" {
162	}
163    }
164
165    # Switch to the MI channel.
166    set gdb_main_spawn_id $gdb_spawn_id
167    switch_gdb_spawn_id $mi_spawn_id
168
169    # Consume pending output and MI prompt.
170    gdb_expect {
171	-re "$mi_gdb_prompt$" {
172	}
173	default {
174	    perror "MI channel failed"
175	    remote_close host
176	    return -1
177	}
178    }
179
180    if {$separate_inferior_pty} {
181	mi_create_inferior_pty
182    }
183
184    mi_detect_async
185
186    return 0
187}
188
189#
190# default_mi_gdb_start [FLAGS] -- start gdb running, default procedure
191#
192# FLAGS is a list of flags, each flag is a string.
193#
194# If "separate-inferior-tty" is specified, the inferior works with
195# it's own PTY.
196#
197# If "separate-mi-tty" is specified, the gdb starts in CLI mode, with
198# MI running on a secondary UI, on its own tty.
199#
200# When running over NFS, particularly if running many simultaneous
201# tests on different hosts all using the same server, things can
202# get really slow.  Give gdb at least 3 minutes to start up.
203#
204proc default_mi_gdb_start { { flags {} } } {
205    global use_gdb_stub
206    global GDB
207    global INTERNAL_GDBFLAGS GDBFLAGS
208    global gdb_prompt
209    global mi_gdb_prompt
210    global timeout
211    global gdb_spawn_id gdb_main_spawn_id inferior_spawn_id mi_spawn_id
212    global MIFLAGS
213    global FORCE_SEPARATE_MI_TTY
214
215    # Keep track of the number of times GDB has been launched.
216    global gdb_instances
217    incr gdb_instances
218
219    gdb_stdin_log_init
220
221    if {[info exists FORCE_SEPARATE_MI_TTY]} {
222	set separate_mi_pty $FORCE_SEPARATE_MI_TTY
223    } else {
224	set separate_mi_pty 0
225    }
226
227    set separate_inferior_pty 0
228
229    foreach flag $flags {
230	if {$flag == "separate-mi-tty"} {
231	    set separate_mi_pty 1
232	} elseif {$flag == "separate-inferior-tty"} {
233	    set separate_inferior_pty 1
234	}
235    }
236
237    if {$separate_mi_pty} {
238	return [mi_gdb_start_separate_mi_tty $flags]
239    }
240
241    set inferior_pty no-tty
242
243    # Set the default value, it may be overriden later by specific testfile.
244    set use_gdb_stub [target_info exists use_gdb_stub]
245
246    # Start SID.
247    if { [info procs sid_start] != "" } {
248	verbose "Spawning SID"
249	sid_start
250    }
251
252    if [info exists gdb_spawn_id] {
253	return 0
254    }
255
256    save_vars { GDBFLAGS } {
257	append GDBFLAGS " $MIFLAGS"
258
259	set res [gdb_spawn]
260	if { $res != 0} {
261	    return $res
262	}
263    }
264
265    gdb_expect {
266	-re "~\"GNU.*\r\n~\".*$mi_gdb_prompt$" {
267	    # We have a new format mi startup prompt.  If we are
268	    # running mi1, then this is an error as we should be
269	    # using the old-style prompt.
270	    if { $MIFLAGS == "-i=mi1" } {
271		perror "(mi startup) Got unexpected new mi prompt."
272		remote_close host
273		unset gdb_spawn_id
274		return -1
275	    }
276	    verbose "GDB initialized."
277	}
278	-re "\[^~\].*$mi_gdb_prompt$" {
279	    # We have an old format mi startup prompt.  If we are
280	    # not running mi1, then this is an error as we should be
281	    # using the new-style prompt.
282	    if { $MIFLAGS != "-i=mi1" } {
283		perror "(mi startup) Got unexpected old mi prompt."
284		remote_close host
285		unset gdb_spawn_id
286		return -1
287	    }
288	    verbose "GDB initialized."
289	}
290	-re ".*unrecognized option.*for a complete list of options." {
291	    untested "skip mi tests (not compiled with mi support)."
292	    remote_close host
293	    unset gdb_spawn_id
294	    return -1
295	}
296	-re ".*Interpreter `mi' unrecognized." {
297	    untested "skip mi tests (not compiled with mi support)."
298	    remote_close host
299	    unset gdb_spawn_id
300	    return -1
301	}
302	timeout {
303	    perror "(timeout) GDB never initialized after 10 seconds."
304	    remote_close host
305	    unset gdb_spawn_id
306	    return -1
307	}
308    }
309    set gdb_main_spawn_id $gdb_spawn_id
310    set mi_spawn_id $gdb_spawn_id
311
312    # FIXME: mi output does not go through pagers, so these can be removed.
313    # force the height to "unlimited", so no pagers get used
314    send_gdb "100-gdb-set height 0\n"
315    gdb_expect 10 {
316	-re ".*100-gdb-set height 0\r\n100\\\^done\r\n$mi_gdb_prompt$" {
317	    verbose "Setting height to 0." 2
318	}
319	timeout {
320	    warning "Couldn't set the height to 0"
321	}
322    }
323    # force the width to "unlimited", so no wraparound occurs
324    send_gdb "101-gdb-set width 0\n"
325    gdb_expect 10 {
326	-re ".*101-gdb-set width 0\r\n101\\\^done\r\n$mi_gdb_prompt$" {
327	    verbose "Setting width to 0." 2
328	}
329	timeout {
330	    warning "Couldn't set the width to 0."
331	}
332    }
333
334    if { $separate_inferior_pty } {
335	mi_create_inferior_pty
336    }
337
338    if {![info exists inferior_spawn_id]} {
339	set inferior_spawn_id $gdb_spawn_id
340    }
341
342    mi_detect_async
343
344    return 0
345}
346
347#
348# Overridable function. You can override this function in your
349# baseboard file.
350#
351proc mi_gdb_start { args } {
352  return [eval default_mi_gdb_start $args]
353}
354
355# Many of the tests depend on setting breakpoints at various places and
356# running until that breakpoint is reached.  At times, we want to start
357# with a clean-slate with respect to breakpoints, so this utility proc
358# lets us do this without duplicating this code everywhere.
359#
360
361proc mi_delete_breakpoints {} {
362    global mi_gdb_prompt
363
364# FIXME: The mi operation won't accept a prompt back and will use the 'all' arg
365    send_gdb "102-break-delete\n"
366    gdb_expect 30 {
367	 -re "Delete all breakpoints.*y or n.*$" {
368	    send_gdb "y\n"
369	    exp_continue
370	 }
371	 -re "102-break-delete\r\n102\\\^done\r\n$mi_gdb_prompt$" {
372	     # This happens if there were no breakpoints
373	 }
374	 timeout { perror "Delete all breakpoints in mi_delete_breakpoints (timeout)" ; return }
375    }
376
377# The correct output is not "No breakpoints or watchpoints." but an
378# empty BreakpointTable. Also, a query is not acceptable with mi.
379    send_gdb "103-break-list\n"
380    gdb_expect 30 {
381	 -re "103-break-list\r\n103\\\^done,BreakpointTable=\{\}\r\n$mi_gdb_prompt$" {}
382	 -re "103-break-list\r\n103\\\^done,BreakpointTable=\{nr_rows=\".\",nr_cols=\".\",hdr=\\\[\{width=\".*\",alignment=\".*\",col_name=\"number\",colhdr=\"Num\"\}.*colhdr=\"Type\".*colhdr=\"Disp\".*colhdr=\"Enb\".*colhdr=\"Address\".*colhdr=\"What\".*\\\],body=\\\[\\\]\}\r\n$mi_gdb_prompt$" {}
383	 -re "103-break-list\r\n103\\\^doneNo breakpoints or watchpoints.\r\n\r\n$mi_gdb_prompt$" {warning "Unexpected console text received"}
384	 -re "$mi_gdb_prompt$" { perror "Breakpoints not deleted" ; return }
385	 -re "Delete all breakpoints.*or n.*$" {
386	    warning "Unexpected prompt for breakpoints deletion"
387	    send_gdb "y\n"
388	    exp_continue
389	}
390	 timeout { perror "-break-list (timeout)" ; return }
391    }
392}
393
394proc mi_gdb_reinitialize_dir { subdir } {
395    global mi_gdb_prompt
396    global MIFLAGS
397
398    if [is_remote host] {
399	return ""
400    }
401
402    if { $MIFLAGS == "-i=mi1" } {
403      send_gdb "104-environment-directory\n"
404      gdb_expect 60 {
405	-re ".*Reinitialize source path to empty.*y or n. " {
406	    warning "Got confirmation prompt for dir reinitialization."
407	    send_gdb "y\n"
408	    gdb_expect 60 {
409		-re "$mi_gdb_prompt$" {}
410		timeout {error "Dir reinitialization failed (timeout)"}
411	    }
412	}
413	-re "$mi_gdb_prompt$" {}
414	  timeout {error "Dir reinitialization failed (timeout)"}
415      }
416    } else {
417	send_gdb "104-environment-directory -r\n"
418	gdb_expect 60 {
419	    -re "104\\\^done,source-path=.*\r\n$mi_gdb_prompt$" {}
420	    -re "$mi_gdb_prompt$" {}
421	    timeout {error "Dir reinitialization failed (timeout)"}
422      }
423    }
424
425    send_gdb "105-environment-directory $subdir\n"
426    gdb_expect 60 {
427	-re "Source directories searched.*$mi_gdb_prompt$" {
428	    verbose "Dir set to $subdir"
429	}
430	-re "105\\\^done.*\r\n$mi_gdb_prompt$" {
431	    # FIXME: We return just the prompt for now.
432	    verbose "Dir set to $subdir"
433	    # perror "Dir \"$subdir\" failed."
434	}
435    }
436}
437
438# Send GDB the "target" command.
439# FIXME: Some of these patterns are not appropriate for MI.  Based on
440# config/monitor.exp:gdb_target_command.
441proc mi_gdb_target_cmd { targetname serialport } {
442    global mi_gdb_prompt
443
444    set serialport_re [string_to_regexp $serialport]
445    for {set i 1} {$i <= 3} {incr i} {
446	send_gdb "47-target-select $targetname $serialport\n"
447	gdb_expect 60 {
448	    -re "47\\^connected.*$mi_gdb_prompt" {
449		verbose "Set target to $targetname"
450		return 0
451	    }
452	    -re "unknown host.*$mi_gdb_prompt" {
453		verbose "Couldn't look up $serialport"
454	    }
455	    -re "Couldn't establish connection to remote.*$mi_gdb_prompt$" {
456		verbose "Connection failed"
457	    }
458	    -re "Remote MIPS debugging.*$mi_gdb_prompt$" {
459		verbose "Set target to $targetname"
460		return 0
461	    }
462	    -re "Remote debugging using .*$serialport_re.*$mi_gdb_prompt$" {
463		verbose "Set target to $targetname"
464		return 0
465	    }
466	    -re "Remote target $targetname connected to.*$mi_gdb_prompt$" {
467		verbose "Set target to $targetname"
468		return 0
469	    }
470	    -re "Connected to.*$mi_gdb_prompt$" {
471		verbose "Set target to $targetname"
472		return 0
473	    }
474	    -re "Ending remote.*$mi_gdb_prompt$" { }
475	    -re "Connection refused.*$mi_gdb_prompt$" {
476		verbose "Connection refused by remote target.  Pausing, and trying again."
477		sleep 5
478		continue
479	    }
480	    -re "Non-stop mode requested, but remote does not support non-stop.*$mi_gdb_prompt" {
481		unsupported "non-stop mode not supported"
482		return 1
483	    }
484	    -re "Timeout reading from remote system.*$mi_gdb_prompt$" {
485		verbose "Got timeout error from gdb."
486	    }
487	    timeout {
488		send_gdb ""
489		break
490	    }
491	}
492    }
493    return 1
494}
495
496#
497# load a file into the debugger (file command only).
498# return a -1 if anything goes wrong.
499#
500proc mi_gdb_file_cmd { arg } {
501    global loadpath
502    global loadfile
503    global GDB
504    global mi_gdb_prompt
505    global last_loaded_file
506    upvar timeout timeout
507
508    # GCC for Windows target may create foo.exe given "-o foo".
509    if { ![file exists $arg] && [file exists "$arg.exe"] } {
510	set arg "$arg.exe"
511    }
512
513    set last_loaded_file $arg
514
515    if [is_remote host] {
516	set arg [remote_download host $arg]
517	if { $arg == "" } {
518	    error "download failed"
519	    return -1
520	}
521    }
522
523# FIXME: Several of these patterns are only acceptable for console
524# output.  Queries are an error for mi.
525    send_gdb "105-file-exec-and-symbols $arg\n"
526    gdb_expect 120 {
527	-re "Reading symbols from.*$mi_gdb_prompt$" {
528	    verbose "\t\tLoaded $arg into the $GDB"
529	    return 0
530	}
531	-re "has no symbol-table.*$mi_gdb_prompt$" {
532	    perror "$arg wasn't compiled with \"-g\""
533	    return -1
534	}
535	-re "Load new symbol table from \".*\".*y or n. $" {
536	    send_gdb "y\n"
537	    gdb_expect 120 {
538		-re "Reading symbols from.*$mi_gdb_prompt$" {
539		    verbose "\t\tLoaded $arg with new symbol table into $GDB"
540		    # All OK
541		}
542		timeout {
543		    perror "(timeout) Couldn't load $arg, other program already loaded."
544		    return -1
545		}
546	    }
547	}
548	-re "No such file or directory.*$mi_gdb_prompt$" {
549	    perror "($arg) No such file or directory\n"
550	    return -1
551	}
552	-re "105-file-exec-and-symbols .*\r\n105\\\^done\r\n$mi_gdb_prompt$" {
553	    # We (MI) are just giving the prompt back for now, instead of giving
554	    # some acknowledgement.
555	    return 0
556	}
557	timeout {
558	    perror "couldn't load $arg into $GDB (timed out)."
559	    return -1
560	}
561	eof {
562	    # This is an attempt to detect a core dump, but seems not to
563	    # work.  Perhaps we need to match .* followed by eof, in which
564	    # gdb_expect does not seem to have a way to do that.
565	    perror "couldn't load $arg into $GDB (end of file)."
566	    return -1
567	}
568    }
569}
570
571#
572# connect to the target and download a file, if necessary.
573# return a -1 if anything goes wrong.
574#
575proc mi_gdb_target_load { } {
576    global loadpath
577    global loadfile
578    global GDB
579    global mi_gdb_prompt
580
581    if [target_info exists gdb_load_timeout] {
582	set loadtimeout [target_info gdb_load_timeout]
583    } else {
584	set loadtimeout 1600
585    }
586
587    if { [info procs gdbserver_gdb_load] != "" } {
588	mi_gdb_test "kill" ".*" ""
589	if { [catch gdbserver_gdb_load res] == 1 } {
590	    perror $res
591	    return -1
592	}
593	set protocol [lindex $res 0]
594	set gdbport [lindex $res 1]
595
596	if { [mi_gdb_target_cmd $protocol $gdbport] != 0 } {
597	    return -1
598	}
599    } elseif { [info procs send_target_sid] != "" } {
600	# For SID, things get complex
601	send_gdb "kill\n"
602	gdb_expect 10 {
603	    -re ".*$mi_gdb_prompt$"
604	}
605	send_target_sid
606	gdb_expect $loadtimeout {
607	    -re "\\^done.*$mi_gdb_prompt$" {
608	    }
609	    timeout {
610		perror "Unable to connect to SID target (timeout)"
611		return -1
612	    }
613	}
614	send_gdb "48-target-download\n"
615	gdb_expect $loadtimeout {
616	    -re "48\\^done.*$mi_gdb_prompt$" {
617	    }
618	    timeout {
619		perror "Unable to download to SID target (timeout)"
620		return -1
621	    }
622	}
623    } elseif { [target_info protocol] == "sim" } {
624	set target_sim_options "[board_info target gdb,target_sim_options]"
625	# For the simulator, just connect to it directly.
626	send_gdb "47-target-select sim $target_sim_options\n"
627	gdb_expect $loadtimeout {
628	    -re "47\\^connected.*$mi_gdb_prompt$" {
629	    }
630	    timeout {
631		perror "Unable to select sim target (timeout)"
632		return -1
633	    }
634	}
635	send_gdb "48-target-download\n"
636	gdb_expect $loadtimeout {
637	    -re "48\\^done.*$mi_gdb_prompt$" {
638	    }
639	    timeout {
640		perror "Unable to download to sim target (timeout)"
641		return -1
642	    }
643	}
644    } elseif { [target_info gdb_protocol] == "remote" } {
645	# remote targets
646	if { [mi_gdb_target_cmd "remote" [target_info netport]] != 0 } {
647	    perror "Unable to connect to remote target"
648	    return -1
649	}
650	send_gdb "48-target-download\n"
651	gdb_expect $loadtimeout {
652	    -re "48\\^done.*$mi_gdb_prompt$" {
653	    }
654	    timeout {
655		perror "Unable to download to remote target (timeout)"
656		return -1
657	    }
658	}
659    }
660    return 0
661}
662
663#
664# load a file into the debugger.
665# return a -1 if anything goes wrong.
666#
667proc mi_gdb_load { arg } {
668    if { $arg != "" } {
669	return [mi_gdb_file_cmd $arg]
670    }
671    return 0
672}
673
674# Return true if symbols were read in using -readnow.  Otherwise,
675# return false.
676
677proc mi_readnow { args } {
678    # Just defer to gdb.exp.
679    return [readnow]
680}
681
682# mi_gdb_test COMMAND [PATTERN [MESSAGE [IPATTERN]]] -- send a command to gdb;
683#   test the result.
684#
685# COMMAND is the command to execute, send to GDB with send_gdb.  If
686#   this is the null string no command is sent.
687# PATTERN is the pattern to match for a PASS, and must NOT include
688#   the \r\n sequence immediately before the gdb prompt.
689#   If not specified, .* is used.
690# MESSAGE is the message to be printed.  (If this is the empty string,
691#   then sometimes we don't call pass or fail at all; I don't
692#   understand this at all.)
693#   If not specified, COMMAND is used.
694# IPATTERN is the pattern to match for the inferior's output.  This parameter
695#   is optional.  If present, it will produce a PASS if the match is
696#   successful, and a FAIL if unsuccessful.
697#
698# Returns:
699#    1 if the test failed,
700#    0 if the test passes,
701#   -1 if there was an internal error.
702#
703proc mi_gdb_test { args } {
704    global verbose
705    global mi_gdb_prompt
706    global GDB expect_out
707    global inferior_exited_re async
708    upvar timeout timeout
709
710    if {[llength $args] >= 1} {
711	set command [lindex $args 0]
712    } else {
713	error "Not enough arguments in mi_gdb_test"
714    }
715
716    if {[llength $args] >= 2} {
717	set pattern [lindex $args 1]
718    } else {
719	set pattern ".*"
720    }
721
722    if {[llength $args] >= 3} {
723	set message [lindex $args 2]
724    } else {
725	set message $command
726    }
727
728    if [llength $args]==4 {
729	set ipattern [lindex $args 3]
730    }
731
732    if [llength $args]==5 {
733	set question_string [lindex $args 3]
734	set response_string [lindex $args 4]
735    } else {
736	set question_string "^FOOBAR$"
737    }
738
739    if { [llength $args] >= 6 } {
740	error "Too many arguments in mi_gdb_test"
741    }
742
743    if {$verbose > 2} {
744	send_user "Sending \"$command\" to gdb\n"
745	send_user "Looking to match \"$pattern\"\n"
746	send_user "Message is \"$message\"\n"
747    }
748
749    set result -1
750    set string "${command}\n"
751    set string_regex [string_to_regexp $command]
752
753    if { $command != "" } {
754	while { "$string" != "" } {
755	    set foo [string first "\n" "$string"]
756	    set len [string length "$string"]
757	    if { $foo < [expr $len - 1] } {
758		set str [string range "$string" 0 $foo]
759		if { [send_gdb "$str"] != "" } {
760		    perror "Couldn't send $command to GDB."
761		}
762		gdb_expect 2 {
763		    -re "\[\r\n\]" { }
764		    timeout { }
765		}
766		set string [string range "$string" [expr $foo + 1] end]
767	    } else {
768		break
769	    }
770	}
771	if { "$string" != "" } {
772	    if { [send_gdb "$string"] != "" } {
773		perror "Couldn't send $command to GDB."
774	    }
775	}
776    }
777
778    if [info exists timeout] {
779	set tmt $timeout
780    } else {
781	global timeout
782	if [info exists timeout] {
783	    set tmt $timeout
784	} else {
785	    set tmt 60
786	}
787    }
788    if {$async} {
789	# With $prompt_re "" there may come arbitrary asynchronous response
790	# from the previous command, before or after $string_regex.
791	set string_regex ".*"
792    }
793    verbose -log "Expecting: ^($string_regex\[\r\n\]+)?($pattern\[\r\n\]+$mi_gdb_prompt\[ \]*)"
794    gdb_expect $tmt {
795	 -re "\\*\\*\\* DOSEXIT code.*" {
796	     if { $message != "" } {
797		 fail "$message"
798	     }
799	     return -1
800	 }
801	 -re "Ending remote debugging.*$mi_gdb_prompt\[ \]*$" {
802	    if {![isnative]} {
803		warning "Can`t communicate to remote target."
804	    }
805	    gdb_exit
806	    gdb_start
807	    set result -1
808	}
809	 -re "^($string_regex\[\r\n\]+)?($pattern\[\r\n\]+$mi_gdb_prompt\[ \]*)" {
810	    # At this point, $expect_out(1,string) is the MI input command.
811	    # and $expect_out(2,string) is the MI output command.
812	    # If $expect_out(1,string) is "", then there was no MI input command here.
813
814	    # NOTE, there is no trailing anchor because with GDB/MI,
815	    # asynchronous responses can happen at any point, causing more
816	    # data to be available.  Normally an anchor is used to make
817	    # sure the end of the output is matched, however, $mi_gdb_prompt
818	    # is just as good of an anchor since mi_gdb_test is meant to
819	    # match a single mi output command.  If a second GDB/MI output
820	    # response is sent, it will be in the buffer for the next
821	    # time mi_gdb_test is called.
822	    if {![string match "" $message]} {
823		pass "$message"
824	    }
825	    set result 0
826	}
827	 -re "(${question_string})$" {
828	    send_gdb "$response_string\n"
829	    exp_continue
830	}
831	 -re "Undefined.* command:.*$mi_gdb_prompt\[ \]*$" {
832	    perror "Undefined command \"$command\"."
833	     fail "$message"
834	    set result 1
835	}
836	 -re "Ambiguous command.*$mi_gdb_prompt\[ \]*$" {
837	    perror "\"$command\" is not a unique command name."
838	     fail "$message"
839	    set result 1
840	}
841	 -re "$inferior_exited_re with code \[0-9\]+.*$mi_gdb_prompt\[ \]*$" {
842	    if {![string match "" $message]} {
843		set errmsg "$message (the program exited)"
844	    } else {
845		set errmsg "$command (the program exited)"
846	    }
847	    fail "$errmsg"
848	    return -1
849	}
850	 -re "The program is not being run.*$mi_gdb_prompt\[ \]*$" {
851	    if {![string match "" $message]} {
852		set errmsg "$message (the program is no longer running)"
853	    } else {
854		set errmsg "$command (the program is no longer running)"
855	    }
856	    fail "$errmsg"
857	    return -1
858	}
859	 -re ".*$mi_gdb_prompt\[ \]*$" {
860	    if {![string match "" $message]} {
861		fail "$message (unexpected output)"
862	    }
863	    set result 1
864	}
865	 "<return>" {
866	    send_gdb "\n"
867	    perror "Window too small."
868	     fail "$message"
869	}
870	 eof {
871	     perror "Process no longer exists"
872	     if { $message != "" } {
873		 fail "$message"
874	     }
875	     return -1
876	}
877	 full_buffer {
878	    perror "internal buffer is full."
879	     fail "$message"
880	}
881	timeout	{
882	    if {![string match "" $message]} {
883		fail "$message (timeout)"
884	    }
885	    set result 1
886	}
887    }
888
889    # If the GDB output matched, compare the inferior output.
890    if { $result == 0 } {
891	if [ info exists ipattern ] {
892	    if { ![target_info exists gdb,noinferiorio] } {
893		global gdb_spawn_id inferior_spawn_id
894
895		set sid "$inferior_spawn_id $gdb_spawn_id"
896		gdb_expect {
897		    -i "$sid" -re "$ipattern" {
898			pass "$message inferior output"
899		    }
900		    timeout {
901			fail "$message inferior output (timeout)"
902			set result 1
903		    }
904		}
905	    } else {
906		unsupported "$message inferior output"
907	    }
908	}
909    }
910
911    return $result
912}
913
914# Collect output sent to the console output stream until UNTIL is
915# seen.  UNTIL is a regular expression.  MESSAGE is the message to be
916# printed in case of timeout.
917
918proc mi_gdb_expect_cli_output {until message} {
919
920    set output ""
921    gdb_expect {
922	-re "~\"(\[^\r\n\]+)\"\r\n" {
923	    append output $expect_out(1,string)
924	    exp_continue
925	}
926	-notransfer -re "$until" {
927	    # Done
928	}
929	timeout {
930	    fail "$message (timeout)"
931	    return ""
932	}
933    }
934
935    return $output
936}
937
938#
939# MI run command.  (A modified version of gdb_run_cmd)
940#
941
942# In patterns, the newline sequence ``\r\n'' is matched explicitly as
943# ``.*$'' could swallow up output that we attempt to match elsewhere.
944
945# Send the command to run the test program.
946#
947# If USE_MI_COMMAND is true, the "-exec-run" command is used.
948# Otherwise, the "run" (CLI) command is used.  If the global USE_GDB_STUB is
949# true, -exec-continue and continue are used instead of their run counterparts.
950#
951# ARGS is passed as argument to the command used to run the test program.
952# Beware that arguments to "-exec-run" do not have the same semantics as
953# arguments to the "run" command, so USE_MI_COMMAND influences the meaning
954# of ARGS.  If USE_MI_COMMAND is true, they are arguments to -exec-run.
955# If USE_MI_COMMAND is false, they are effectively arguments passed
956# to the test program.  If the global USE_GDB_STUB is true, ARGS is not used.
957proc mi_run_cmd_full {use_mi_command args} {
958    global mi_gdb_prompt use_gdb_stub
959    global thread_selected_re
960    global library_loaded_re
961
962    if {$use_mi_command} {
963	set run_prefix "220-exec-"
964	set run_match "220"
965    } else {
966	set run_prefix ""
967	set run_match ""
968    }
969
970    foreach command [gdb_init_commands] {
971	send_gdb "$command\n"
972	gdb_expect 30 {
973	    -re "$mi_gdb_prompt$" { }
974	    default {
975		unresolved "gdb_init_command for target failed"
976		return -1
977	    }
978	}
979    }
980
981    if { [mi_gdb_target_load] < 0 } {
982	return -1
983    }
984
985    if $use_gdb_stub {
986	if [target_info exists gdb,do_reload_on_run] {
987	    send_gdb "${run_prefix}continue\n"
988	    gdb_expect 60 {
989		-re "${run_match}\\^running\[\r\n\]+\\*running,thread-id=\"\[^\"\]+\"\r\n$mi_gdb_prompt" {}
990		-re "${run_match}\\^error.*$mi_gdb_prompt" {return -1}
991		default {}
992	    }
993	    return 0
994	}
995
996	if [target_info exists gdb,start_symbol] {
997	    set start [target_info gdb,start_symbol]
998	} else {
999	    set start "start"
1000	}
1001
1002	# HACK: Should either use 000-jump or fix the target code
1003	# to better handle RUN.
1004	send_gdb  "jump *$start\n"
1005	warning "Using CLI jump command, expect run-to-main FAIL"
1006	gdb_expect {
1007	    -re "&\"jump \\*${start}\\\\n\"\[\r\n\]+~\"Continuing at 0x\[0-9A-Fa-f\]+\.\\\\n\"\[\r\n\]+\\^running\[\r\n\]+\\*running,thread-id=\"\[^\"\]+\"\[\r\n\]+${mi_gdb_prompt}" {}
1008	    timeout {
1009		unresolved "unable to start target"
1010		return -1
1011	    }
1012	}
1013	return 0
1014    }
1015
1016    send_gdb "${run_prefix}run $args\n"
1017    gdb_expect {
1018	-re "${run_match}\\^running\r\n(\\*running,thread-id=\"\[^\"\]+\"\r\n|=thread-created,id=\"1\",group-id=\"\[0-9\]+\"\r\n)*(${library_loaded_re})*(${thread_selected_re})?${mi_gdb_prompt}" {
1019	}
1020	-re "\\^error,msg=\"The target does not support running in non-stop mode.\"" {
1021	    unsupported "non-stop mode not supported"
1022	    return -1
1023	}
1024	timeout {
1025	    unresolved "unable to start target"
1026	    return -1
1027	}
1028    }
1029    # NOTE: Shortly after this there will be a ``000*stopped,...(gdb)''
1030
1031    return 0
1032}
1033
1034# A wrapper for mi_run_cmd_full which uses -exec-run and
1035# -exec-continue, as appropriate.  ARGS are passed verbatim to
1036# mi_run_cmd_full.
1037proc mi_run_cmd {args} {
1038    return [eval mi_run_cmd_full 1 $args]
1039}
1040
1041# A wrapper for mi_run_cmd_full which uses the CLI commands 'run' and
1042# 'continue', as appropriate.  ARGS are passed verbatim to
1043# mi_run_cmd_full.
1044proc mi_run_with_cli {args} {
1045    return [eval mi_run_cmd_full 0 $args]
1046}
1047
1048# Starts fresh GDB binary and loads an optional executable into GDB.
1049# Usage: mi_clean_restart [executable]
1050# EXECUTABLE is the basename of the binary.
1051# Return -1 if starting gdb or loading the executable failed.
1052
1053proc mi_clean_restart { args } {
1054    global srcdir
1055    global subdir
1056    global errcnt
1057    global warncnt
1058
1059    if { [llength $args] > 1 } {
1060	error "bad number of args: [llength $args]"
1061    }
1062
1063    gdb_exit
1064
1065    # This is a clean restart, so reset error and warning count.
1066    set errcnt 0
1067    set warncnt 0
1068
1069    if {[mi_gdb_start]} {
1070	return -1
1071    }
1072
1073    mi_gdb_reinitialize_dir $srcdir/$subdir
1074
1075    if { [llength $args] >= 1 } {
1076	set executable [lindex $args 0]
1077	set binfile [standard_output_file ${executable}]
1078	return [mi_gdb_load ${binfile}]
1079    }
1080
1081    return 0
1082}
1083
1084# Just like gdb's "runto" proc, it will run the target to a given
1085# function.  The big difference here between mi_runto and mi_execute_to
1086# is that mi_execute_to must have the inferior running already.  This
1087# proc will (like gdb's runto) (re)start the inferior, too.
1088#
1089# FUNC is the linespec of the place to stop (it inserts a breakpoint here).
1090# It returns:
1091#   -1  if failed, timedout
1092#    0  if test passed
1093#
1094# Supported options:
1095#
1096#  -qualified -- pass --qualified to -break-insert
1097#  -pending   -- pass -f to -break-insert to create a pending
1098#                breakpoint.
1099
1100proc mi_runto_helper {func run_or_continue args} {
1101  global mi_gdb_prompt expect_out
1102  global hex decimal fullname_syntax
1103
1104  parse_args {{qualified} {pending}}
1105
1106  set test "mi runto $func"
1107  if {$pending} {
1108      set bp [mi_make_breakpoint_pending -type breakpoint -disp del]
1109  } else {
1110      set bp [mi_make_breakpoint -type breakpoint -disp del \
1111		  -func $func\(\\\(.*\\\)\)?]
1112  }
1113  set extra_opts ""
1114  set extra_output ""
1115  if {$qualified} {
1116      lappend extra_opts "--qualified"
1117  }
1118  if {$pending} {
1119      lappend extra_opts "-f"
1120      # MI prints "Function FUNC not defined", "No line NNN in current
1121      # file.", etc. to the CLI stream.
1122      set extra_output "&\"\[^\r\n\]+\"\r\n"
1123  }
1124  mi_gdb_test "200-break-insert [join $extra_opts " "] -t $func" "${extra_output}200\\^done,$bp" \
1125      "breakpoint at $func"
1126
1127  if {$run_or_continue == "run"} {
1128      if { [mi_run_cmd] < 0 } {
1129	  return -1
1130      }
1131  } else {
1132      mi_send_resuming_command "exec-continue" "$test"
1133  }
1134
1135  mi_expect_stop "breakpoint-hit" $func ".*" ".*" "\[0-9\]+" { "" "disp=\"del\"" } $test
1136}
1137
1138proc mi_runto {func args} {
1139    return [mi_runto_helper $func "run" {*}$args]
1140}
1141
1142# Just like runto_main but works with the MI interface.
1143
1144proc mi_runto_main {} {
1145    return [mi_runto_helper "main" "run" -qualified]
1146}
1147
1148# Next to the next statement
1149# For return values, see mi_execute_to_helper
1150
1151proc mi_next { test } {
1152  return [mi_next_to {.*} {.*} {.*} {.*} $test]
1153}
1154
1155
1156# Step to the next statement
1157# For return values, see mi_execute_to_helper
1158
1159proc mi_step { test } {
1160  return [mi_step_to {.*} {.*} {.*} {.*} $test]
1161}
1162
1163set async "unknown"
1164
1165proc mi_detect_async {} {
1166    global async
1167    global mi_gdb_prompt
1168
1169    send_gdb "show mi-async\n"
1170
1171    gdb_expect {
1172	-re "asynchronous mode is on...*$mi_gdb_prompt$" {
1173	    set async 1
1174	}
1175	-re ".*$mi_gdb_prompt$" {
1176	    set async 0
1177	}
1178	timeout {
1179	    set async 0
1180	}
1181    }
1182    return $async
1183}
1184
1185# Wait for MI *stopped notification to appear.
1186# The REASON, FUNC, ARGS, FILE and LINE are regular expressions
1187# to match against whatever is output in *stopped.  FILE may also match
1188# filename of a file without debug info.  ARGS should not include [] the
1189# list of argument is enclosed in, and other regular expressions should
1190# not include quotes.
1191# EXTRA can be a list of one, two or three elements.
1192# The first element is the regular expression
1193# for output expected right after *stopped, and before GDB prompt.
1194# The third element is the regular expression for the locno
1195# right after bkptno field.  The locno regex should not include
1196# the comma separating it from the following fields.
1197#
1198# When we fail to match output at all, -1 is returned.  If FILE does
1199# match and the target system has no debug info for FILE return 0.
1200# Otherwise, the line at which we stop is returned.  This is useful when
1201# exact line is not possible to specify for some reason -- one can pass
1202# the .* or "\[0-9\]*" regexps for line, and then check the line
1203# programmatically.
1204#
1205# Do not pass .* for any argument if you are expecting more than one stop.
1206proc mi_expect_stop { reason func args file line extra test } {
1207
1208    global mi_gdb_prompt
1209    global hex
1210    global decimal
1211    global fullname_syntax
1212    global async
1213    global thread_selected_re
1214    global breakpoint_re
1215
1216    set any "\[^\n\]*"
1217
1218    set after_stopped ""
1219    set after_reason ""
1220    set locno ""
1221    if { [llength $extra] == 3 } {
1222	set after_stopped [lindex $extra 0]
1223	set after_reason [lindex $extra 1]
1224	set after_reason "${after_reason},"
1225	set locno [lindex $extra 2]
1226	set locno "${locno},"
1227    } elseif { [llength $extra] == 2 } {
1228	set after_stopped [lindex $extra 0]
1229	set after_reason [lindex $extra 1]
1230	set after_reason "${after_reason},"
1231    } elseif { [llength $extra] == 1 } {
1232	set after_stopped [lindex $extra 0]
1233    }
1234
1235    if {$async} {
1236	set prompt_re ""
1237    } else {
1238	set prompt_re "$mi_gdb_prompt$"
1239    }
1240
1241    if { $reason == "really-no-reason" } {
1242	gdb_expect {
1243	    -re "\\*stopped\r\n$prompt_re" {
1244		pass "$test"
1245	    }
1246	    timeout {
1247		fail "$test (timeout)"
1248	    }
1249	}
1250	return
1251    }
1252
1253    if { $reason == "exited-normally" } {
1254
1255	gdb_expect {
1256	    -re "\\*stopped,reason=\"exited-normally\"\r\n$prompt_re" {
1257		pass "$test"
1258	    }
1259	    -re ".*$mi_gdb_prompt$" {fail "continue to end (2)"}
1260	    timeout {
1261		fail "$test (timeout)"
1262	    }
1263	}
1264	return
1265    }
1266    if { $reason == "exited" } {
1267	gdb_expect {
1268	    -re "\\*stopped,reason=\"exited\",exit-code=\"\[0-7\]+\"\r\n$prompt_re" {
1269		pass "$test"
1270	    }
1271	    -re ".*$mi_gdb_prompt$" {
1272		fail "$test (inferior not stopped)"
1273	    }
1274	    timeout {
1275		fail "$test (timeout)"
1276	    }
1277	}
1278	return
1279    }
1280
1281    if { $reason == "solib-event" } {
1282	set pattern "\\*stopped,reason=\"solib-event\",thread-id=\"$decimal\",stopped-threads=$any\r\n($thread_selected_re|$breakpoint_re)*$prompt_re"
1283	verbose -log "mi_expect_stop: expecting: $pattern"
1284	gdb_expect {
1285	    -re "$pattern" {
1286		pass "$test"
1287	    }
1288	    timeout {
1289		fail "$test (timeout)"
1290	    }
1291	}
1292	return
1293    }
1294
1295    set args "\\\[$args\\\]"
1296
1297    set bn ""
1298    set ebn ""
1299    if { $reason == "breakpoint-hit" } {
1300	set bn {bkptno="[0-9]+",}
1301	set bn "${bn}${locno}"
1302    } elseif { $reason == "solib-event" } {
1303	set bn ".*"
1304    } elseif { $reason == "exception-caught" } {
1305	set ebn {bkptno="[0-9]+",}
1306	set ebn "${ebn}${locno}"
1307	set bn ".*"
1308	set reason "breakpoint-hit"
1309    }
1310
1311    set r ""
1312    if { $reason != "" } {
1313	set r "reason=\"$reason\","
1314    }
1315
1316
1317    set a $after_reason
1318
1319    verbose -log "mi_expect_stop: expecting: \\*stopped,${ebn}${r}${a}${bn}frame=\{addr=\"$hex\",func=\"$func\",args=$args,(?:file=\"$any$file\",fullname=\"${fullname_syntax}$file\",line=\"$line\",arch=\"$any\"|from=\"$file\")\}$after_stopped,thread-id=\"$decimal\",stopped-threads=$any\r\n($thread_selected_re|$breakpoint_re)*$prompt_re"
1320
1321    gdb_expect {
1322	-re "\\*stopped,${ebn}${r}${a}${bn}frame=\{addr=\"$hex\",func=\"$func\",args=$args,(?:file=\"$any$file\",fullname=\"${fullname_syntax}$file\",line=\"($line)\",arch=\"$any\"|from=\"$file\")\}$after_stopped,thread-id=\"$decimal\",stopped-threads=$any\r\n($thread_selected_re|$breakpoint_re)*$prompt_re" {
1323	    pass "$test"
1324	    if {[array names expect_out "2,string"] != ""} {
1325		return $expect_out(2,string)
1326	    }
1327	    # No debug info available but $file does match.
1328	    return 0
1329	}
1330	-re "\\*stopped,${ebn}${r}${a}${bn}frame=\{addr=\"$hex\",func=\"$any\",args=\[\\\[\{\]$any\[\\\]\}\],file=\"$any\",fullname=\"${fullname_syntax}$any\",line=\"\[0-9\]*\",arch=\"$any\"\}$after_stopped,thread-id=\"$decimal\",stopped-threads=$any\r\n($thread_selected_re|$breakpoint_re)*$prompt_re" {
1331	    verbose -log "got $expect_out(buffer)"
1332	    fail "$test (stopped at wrong place)"
1333	    return -1
1334	}
1335	-re ".*\r\n$mi_gdb_prompt$" {
1336	    verbose -log "got $expect_out(buffer)"
1337	    fail "$test (unknown output after running)"
1338	    return -1
1339	}
1340	timeout {
1341	    fail "$test (timeout)"
1342	    return -1
1343	}
1344    }
1345}
1346
1347# Wait for MI *stopped notification related to an interrupt request to
1348# appear.
1349proc mi_expect_interrupt { test } {
1350    global mi_gdb_prompt
1351    global decimal
1352    global async
1353
1354    if {$async} {
1355	set prompt_re ""
1356    } else {
1357	set prompt_re "$mi_gdb_prompt"
1358    }
1359
1360    set r_nonstop "reason=\"signal-received\",signal-name=\"0\",signal-meaning=\"Signal 0\""
1361    set r_allstop "reason=\"signal-received\",signal-name=\"SIGINT\",signal-meaning=\"Interrupt\""
1362    set r "(${r_nonstop}|${r_allstop})"
1363    set any "\[^\n\]*"
1364
1365    # A signal can land anywhere, just ignore the location
1366    verbose -log "mi_expect_interrupt: expecting: \\*stopped,${r}$any\r\n$prompt_re"
1367    gdb_expect {
1368	-re "\\*stopped,${r}$any\r\n$prompt_re" {
1369	    pass "$test"
1370	    return 0
1371	}
1372	-re ".*\r\n$mi_gdb_prompt" {
1373	    verbose -log "got $expect_out(buffer)"
1374	    fail "$test (unknown output after running)"
1375	    return -1
1376	}
1377	timeout {
1378	    fail "$test (timeout)"
1379	    return -1
1380	}
1381    }
1382}
1383
1384# cmd should not include the number or newline (i.e. "exec-step 3", not
1385# "220-exec-step 3\n"
1386
1387# Can not match -re ".*\r\n${mi_gdb_prompt}", because of false positives
1388# after the first prompt is printed.
1389
1390proc mi_execute_to { cmd reason func args file line extra test } {
1391    mi_send_resuming_command "$cmd" "$test"
1392    set r [mi_expect_stop $reason $func $args $file $line $extra $test]
1393    return $r
1394}
1395
1396proc mi_next_to { func args file line test } {
1397    mi_execute_to "exec-next" "end-stepping-range" "$func" "$args" \
1398	"$file" "$line" "" "$test"
1399}
1400
1401proc mi_step_to { func args file line test } {
1402    mi_execute_to "exec-step" "end-stepping-range" "$func" "$args" \
1403	"$file" "$line" "" "$test"
1404}
1405
1406proc mi_finish_to { func args file line result ret test } {
1407    mi_execute_to "exec-finish" "function-finished" "$func" "$args" \
1408	"$file" "$line" \
1409	",gdb-result-var=\"$result\",return-value=\"$ret\"" \
1410	"$test"
1411}
1412
1413proc mi_continue_to {func} {
1414    mi_runto_helper $func "continue"
1415}
1416
1417proc mi0_execute_to { cmd reason func args file line extra test } {
1418    mi_execute_to_helper "$cmd" "$reason" "$func" "\{$args\}" \
1419	"$file" "$line" "$extra" "$test"
1420}
1421
1422proc mi0_next_to { func args file line test } {
1423    mi0_execute_to "exec-next" "end-stepping-range" "$func" "$args" \
1424	"$file" "$line" "" "$test"
1425}
1426
1427proc mi0_step_to { func args file line test } {
1428    mi0_execute_to "exec-step" "end-stepping-range" "$func" "$args" \
1429	"$file" "$line" "" "$test"
1430}
1431
1432proc mi0_finish_to { func args file line result ret test } {
1433    mi0_execute_to "exec-finish" "function-finished" "$func" "$args" \
1434	"$file" "$line" \
1435	",gdb-result-var=\"$result\",return-value=\"$ret\"" \
1436	"$test"
1437}
1438
1439proc mi0_continue_to { bkptno func args file line test } {
1440    mi0_execute_to "exec-continue" "breakpoint-hit\",bkptno=\"$bkptno" \
1441	"$func" "$args" "$file" "$line" "" "$test"
1442}
1443
1444# Creates a breakpoint and checks the reported fields are as expected.
1445# This procedure takes the same options as mi_make_breakpoint and
1446# returns the breakpoint regexp from that procedure.
1447
1448proc mi_create_breakpoint {location test args} {
1449    set bp [eval mi_make_breakpoint $args]
1450    mi_gdb_test "222-break-insert $location" "222\\^done,$bp" $test
1451    return $bp
1452}
1453
1454# Like mi_create_breakpoint, but creates a breakpoint with multiple
1455# locations using mi_make_breakpoint_multi instead.
1456
1457proc mi_create_breakpoint_multi {location test args} {
1458    set bp [eval mi_make_breakpoint_multi $args]
1459    mi_gdb_test "222-break-insert $location" "222\\^done,$bp" $test
1460    return $bp
1461}
1462
1463# Creates varobj named NAME for EXPRESSION.
1464# Name cannot be "-".
1465proc mi_create_varobj { name expression testname } {
1466    mi_gdb_test "-var-create $name * $expression" \
1467	"\\^done,name=\"$name\",numchild=\"\[0-9\]+\",value=\".*\",type=.*,has_more=\"0\"" \
1468	$testname
1469}
1470
1471proc mi_create_floating_varobj { name expression testname } {
1472    mi_gdb_test "-var-create $name @ $expression" \
1473	"\\^done,name=\"$name\",numchild=\"\(-1\|\[0-9\]+\)\",value=\".*\",type=.*" \
1474	$testname
1475}
1476
1477
1478# Same as mi_create_varobj, but also checks the reported type
1479# of the varobj.
1480proc mi_create_varobj_checked { name expression type testname } {
1481    mi_gdb_test "-var-create $name * $expression" \
1482	"\\^done,name=\"$name\",numchild=\"\[0-9\]+\",value=\".*\",type=\"$type\".*" \
1483	$testname
1484}
1485
1486# Same as mi_create_floating_varobj, but assumes the test is creating
1487# a dynamic varobj that has children, so the value must be "{...}".
1488# The "has_more" attribute is checked.
1489proc mi_create_dynamic_varobj {name expression has_more testname} {
1490    mi_gdb_test "-var-create $name @ $expression" \
1491	"\\^done,name=\"$name\",numchild=\"0\",value=\"{\\.\\.\\.}\",type=.*,has_more=\"${has_more}\"" \
1492	$testname
1493}
1494
1495# Deletes the specified NAME.
1496proc mi_delete_varobj { name testname } {
1497    mi_gdb_test "-var-delete $name" \
1498	"\\^done,ndeleted=.*" \
1499	$testname
1500}
1501
1502# Updates varobj named NAME and checks that all varobjs in EXPECTED
1503# are reported as updated, and no other varobj is updated.
1504# Assumes that no varobj is out of scope and that no varobj changes
1505# types.
1506proc mi_varobj_update { name expected testname } {
1507    set er "\\^done,changelist=\\\["
1508    set first 1
1509    foreach item $expected {
1510	set v "{name=\"$item\",in_scope=\"true\",type_changed=\"false\",has_more=\".\"}"
1511	if {$first == 1} {
1512	    set er "$er$v"
1513	    set first 0
1514	} else {
1515	    set er "$er,$v"
1516	}
1517    }
1518    set er "$er\\\]"
1519
1520    verbose -log "Expecting: $er" 2
1521    mi_gdb_test "-var-update $name" $er $testname
1522}
1523
1524proc mi_varobj_update_with_child_type_change { name child_name new_type new_children testname } {
1525    set v "{name=\"$child_name\",in_scope=\"true\",type_changed=\"true\",new_type=\"$new_type\",new_num_children=\"$new_children\",has_more=\".\"}"
1526    set er "\\^done,changelist=\\\[$v\\\]"
1527    verbose -log "Expecting: $er"
1528    mi_gdb_test "-var-update $name" $er $testname
1529}
1530
1531proc mi_varobj_update_with_type_change { name new_type new_children testname } {
1532    mi_varobj_update_with_child_type_change $name $name $new_type $new_children $testname
1533}
1534
1535# A helper that turns a key/value list into a regular expression
1536# matching some MI output.
1537proc mi_varobj_update_kv_helper {list} {
1538    set first 1
1539    set rx ""
1540    foreach {key value} $list {
1541	if {!$first} {
1542	    append rx ,
1543	}
1544	set first 0
1545	if {$key == "new_children"} {
1546	    append rx "$key=\\\[$value\\\]"
1547	} else {
1548	    append rx "$key=\"$value\""
1549	}
1550    }
1551    return $rx
1552}
1553
1554# A helper for mi_varobj_update_dynamic that computes a match
1555# expression given a child list.
1556proc mi_varobj_update_dynamic_helper {children} {
1557    set crx ""
1558
1559    set first 1
1560    foreach child $children {
1561	if {!$first} {
1562	    append crx ,
1563	}
1564	set first 0
1565	append crx "{"
1566	append crx [mi_varobj_update_kv_helper $child]
1567	append crx "}"
1568    }
1569
1570    return $crx
1571}
1572
1573# Update a dynamic varobj named NAME.  CHILDREN is a list of children
1574# that have been updated; NEW_CHILDREN is a list of children that were
1575# added to the primary varobj.  Each child is a list of key/value
1576# pairs that are expected.  SELF is a key/value list holding
1577# information about the varobj itself.  TESTNAME is the name of the
1578# test.
1579proc mi_varobj_update_dynamic {name testname self children new_children} {
1580    if {[llength $new_children]} {
1581	set newrx [mi_varobj_update_dynamic_helper $new_children]
1582	lappend self new_children $newrx
1583    }
1584    set selfrx [mi_varobj_update_kv_helper $self]
1585    set crx [mi_varobj_update_dynamic_helper $children]
1586
1587    set er "\\^done,changelist=\\\[\{name=\"$name\",in_scope=\"true\""
1588    append er ",$selfrx\}"
1589    if {"$crx" != ""} {
1590	append er ",$crx"
1591    }
1592    append er "\\\]"
1593
1594    verbose -log "Expecting: $er"
1595    mi_gdb_test "-var-update $name" $er $testname
1596}
1597
1598proc mi_check_varobj_value { name value testname } {
1599
1600    mi_gdb_test "-var-evaluate-expression $name" \
1601	"\\^done,value=\"$value\"" \
1602	$testname
1603}
1604
1605# Helper proc which constructs a child regexp for
1606# mi_list_varobj_children and mi_varobj_update_dynamic.
1607proc mi_child_regexp {children add_child} {
1608    set children_exp {}
1609
1610    if {$add_child} {
1611	set pre "child="
1612    } else {
1613	set pre ""
1614    }
1615
1616    foreach item $children {
1617
1618	set name [lindex $item 0]
1619	set exp [lindex $item  1]
1620	set numchild [lindex $item 2]
1621	if {[llength $item] == 5} {
1622	    set type [lindex $item 3]
1623	    set value [lindex $item 4]
1624
1625	    lappend children_exp\
1626		"$pre{name=\"$name\",exp=\"$exp\",numchild=\"$numchild\",value=\"$value\",type=\"$type\"(,thread-id=\"\[0-9\]+\")?}"
1627	} elseif {[llength $item] == 4} {
1628	    set type [lindex $item 3]
1629
1630	    lappend children_exp\
1631		"$pre{name=\"$name\",exp=\"$exp\",numchild=\"$numchild\",type=\"$type\"(,thread-id=\"\[0-9\]+\")?}"
1632	} else {
1633	    lappend children_exp\
1634		"$pre{name=\"$name\",exp=\"$exp\",numchild=\"$numchild\"(,thread-id=\"\[0-9\]+\")?}"
1635	}
1636    }
1637    return [join $children_exp ","]
1638}
1639
1640# Check the results of the:
1641#
1642#   -var-list-children VARNAME
1643#
1644# command.  The CHILDREN parement should be a list of lists.
1645# Each inner list can have either 3 or 4 elements, describing
1646# fields that gdb is expected to report for child variable object,
1647# in the following order
1648#
1649#   - Name
1650#   - Expression
1651#   - Number of children
1652#   - Type
1653#
1654# If inner list has 3 elements, the gdb is expected to output no
1655# type for a child and no value.
1656#
1657# If the inner list has 4 elements, gdb output is expected to
1658# have no value.
1659#
1660proc mi_list_varobj_children { varname children testname } {
1661    mi_list_varobj_children_range $varname "" "" [llength $children] $children \
1662      $testname
1663}
1664
1665# Like mi_list_varobj_children, but sets a subrange.  NUMCHILDREN is
1666# the total number of children.
1667proc mi_list_varobj_children_range {varname from to numchildren children testname} {
1668    set options ""
1669    if {[llength $varname] == 2} {
1670	set options [lindex $varname 1]
1671	set varname [lindex $varname 0]
1672    }
1673
1674    set children_exp_j [mi_child_regexp $children 1]
1675    if {$numchildren} {
1676	set expected "\\^done,numchild=\".*\",children=\\\[$children_exp_j.*\\\]"
1677    } {
1678	set expected "\\^done,numchild=\"0\""
1679    }
1680
1681    if {"$to" == ""} {
1682	append expected ",has_more=\"0\""
1683    } elseif {$to >= 0 && $numchildren > $to} {
1684	append expected ",has_more=\"1\""
1685    } else {
1686	append expected ",has_more=\"0\""
1687    }
1688
1689    verbose -log "Expecting: $expected"
1690
1691    mi_gdb_test "-var-list-children $options $varname $from $to" \
1692      $expected $testname
1693}
1694
1695# Verifies that variable object VARNAME has NUMBER children,
1696# where each one is named $VARNAME.<index-of-child> and has type TYPE.
1697proc mi_list_array_varobj_children { varname number type testname } {
1698    mi_list_array_varobj_children_with_index $varname $number 0 $type $testname
1699}
1700
1701# Same as mi_list_array_varobj_children, but allowing to pass a start index
1702# for an array.
1703proc mi_list_array_varobj_children_with_index { varname number start_index \
1704  type testname } {
1705    set t {}
1706    set index $start_index
1707    for {set i 0} {$i < $number} {incr i} {
1708	lappend t [list $varname.$index $index 0 $type]
1709	incr index
1710    }
1711    mi_list_varobj_children $varname $t $testname
1712}
1713
1714# A list of two-element lists.  First element of each list is
1715# a Tcl statement, and the second element is the line
1716# number of source C file where the statement originates.
1717set mi_autotest_data ""
1718# The name of the source file for autotesting.
1719set mi_autotest_source ""
1720
1721# Prepares for running inline tests in FILENAME.
1722# See comments for mi_run_inline_test for detailed
1723# explanation of the idea and syntax.
1724proc mi_prepare_inline_tests { filename } {
1725
1726    global srcdir
1727    global subdir
1728    global mi_autotest_source
1729    global mi_autotest_data
1730
1731    set mi_autotest_data {}
1732
1733    set mi_autotest_source $filename
1734
1735    if {![regexp "^/" "$filename"]} {
1736	set filename "$srcdir/$subdir/$filename"
1737    }
1738
1739    set chan [open $filename]
1740    set content [read $chan]
1741    set line_number 1
1742    while {1} {
1743	set start [string first "/*:" $content]
1744	if {$start != -1} {
1745	    set end [string first ":*/" $content]
1746	    if {$end == -1} {
1747		error "Unterminated special comment in $filename"
1748	    }
1749
1750	    set prefix [string range $content 0 $start]
1751	    set prefix_newlines [count_newlines $prefix]
1752
1753	    set line_number [expr $line_number+$prefix_newlines]
1754	    set comment_line $line_number
1755
1756	    set comment [string range $content [expr $start+3] [expr $end-1]]
1757
1758	    set comment_newlines [count_newlines $comment]
1759	    set line_number [expr $line_number+$comment_newlines]
1760
1761	    set comment [string trim $comment]
1762	    set content [string range $content [expr $end+3] \
1763			     [string length $content]]
1764	    lappend mi_autotest_data [list $comment $comment_line]
1765	} else {
1766	    break
1767	}
1768    }
1769    close $chan
1770}
1771
1772# Helper to mi_run_inline_test below.
1773# Return the list of all (statement,line_number) lists
1774# that comprise TESTCASE.  The begin and end markers
1775# are not included.
1776proc mi_get_inline_test {testcase} {
1777
1778    global mi_gdb_prompt
1779    global mi_autotest_data
1780    global mi_autotest_source
1781
1782    set result {}
1783
1784    set seen_begin 0
1785    set seen_end 0
1786    foreach l $mi_autotest_data {
1787
1788	set comment [lindex $l 0]
1789
1790	if {$comment == "BEGIN: $testcase"} {
1791	    set seen_begin 1
1792	} elseif {$comment == "END: $testcase"} {
1793	    set seen_end 1
1794	    break
1795	} elseif {$seen_begin==1} {
1796	    lappend result $l
1797	}
1798    }
1799
1800    if {$seen_begin == 0} {
1801	error "Autotest $testcase not found"
1802    }
1803
1804    if {$seen_begin == 1 && $seen_end == 0} {
1805	error "Missing end marker for test $testcase"
1806    }
1807
1808    return $result
1809}
1810
1811# Sets temporary breakpoint at LOCATION.
1812proc mi_tbreak {location test} {
1813
1814    global mi_gdb_prompt
1815
1816    mi_gdb_test "-break-insert -t $location" \
1817	{\^done,bkpt=.*} \
1818	$test
1819}
1820
1821# Send COMMAND that must be a command that resumes
1822# the inferior (run/continue/next/etc) and consumes
1823# the "^running" output from it.
1824proc mi_send_resuming_command_raw {command test} {
1825
1826    global mi_gdb_prompt
1827    global thread_selected_re
1828    global library_loaded_re
1829
1830    send_gdb "$command\n"
1831    gdb_expect {
1832	-re "\\^running\r\n\\*running,thread-id=\"\[^\"\]+\"\r\n($library_loaded_re)*($thread_selected_re)?${mi_gdb_prompt}" {
1833	    # Note that lack of 'pass' call here -- this works around limitation
1834	    # in DejaGNU xfail mechanism. mi-until.exp has this:
1835	    #
1836	    #     setup_kfail gdb/2104 "*-*-*"
1837	    #     mi_execute_to ...
1838	    #
1839	    # and mi_execute_to uses mi_send_resuming_command.  If we use 'pass' here,
1840	    # it will reset kfail, so when the actual test fails, it will be flagged
1841	    # as real failure.
1842	    return 0
1843	}
1844	-re "\\^error,msg=\"Displaced stepping is only supported in ARM mode\".*" {
1845	    unsupported "$test (Thumb mode)"
1846	    return -1
1847	}
1848	-re "\\^error,msg=.*" {
1849	    fail "$test (MI error)"
1850	    return -1
1851	}
1852	-re ".*${mi_gdb_prompt}" {
1853	    fail "$test (failed to resume)"
1854	    return -1
1855	}
1856	timeout {
1857	    fail "$test"
1858	    return -1
1859	}
1860    }
1861}
1862
1863proc mi_send_resuming_command {command test} {
1864    mi_send_resuming_command_raw -$command $test
1865}
1866
1867# Helper to mi_run_inline_test below.
1868# Sets a temporary breakpoint at LOCATION and runs
1869# the program using COMMAND.  When the program is stopped
1870# returns the line at which it.  Returns -1 if line cannot
1871# be determined.
1872# Does not check that the line is the same as requested.
1873# The caller can check itself if required.
1874proc_with_prefix mi_continue_to_line {location test} {
1875    with_test_prefix $test {
1876	mi_tbreak $location "set temporary breakpoint"
1877	mi_send_resuming_command "exec-continue" "continue to breakpoint"
1878	return [mi_get_stop_line]
1879    }
1880}
1881
1882# Wait until gdb prints the current line.
1883proc mi_get_stop_line {} {
1884
1885  global mi_gdb_prompt
1886  global async
1887
1888  if {$async} {
1889      set prompt_re ""
1890  } else {
1891      set prompt_re "$mi_gdb_prompt$"
1892  }
1893
1894  gdb_expect {
1895      -re ".*line=\"(\[0-9\]*)\".*\r\n$prompt_re" {
1896	  return $expect_out(1,string)
1897      }
1898      -re ".*$mi_gdb_prompt" {
1899	  fail "wait for stop (unexpected output)"
1900      }
1901      timeout {
1902	  fail "wait for stop (timeout)"
1903      }
1904  }
1905}
1906
1907# Run a MI test embedded in comments in a C file.
1908# The C file should contain special comments in the following
1909# three forms:
1910#
1911#    /*: BEGIN: testname :*/
1912#    /*:  <Tcl statements> :*/
1913#    /*: END: testname :*/
1914#
1915# This procedure find the begin and end marker for the requested
1916# test. Then, a temporary breakpoint is set at the begin
1917# marker and the program is run (from start).
1918#
1919# After that, for each special comment between the begin and end
1920# marker, the Tcl statements are executed.  It is assumed that
1921# for each comment, the immediately preceding line is executable
1922# C statement.  Then, gdb will be single-stepped until that
1923# preceding C statement is executed, and after that the
1924# Tcl statements in the comment will be executed.
1925#
1926# For example:
1927#
1928#     /*: BEGIN: assignment-test :*/
1929#     v = 10;
1930#     /*: <Tcl code to check that 'v' is indeed 10 :*/
1931#     /*: END: assignment-test :*/
1932#
1933# The mi_prepare_inline_tests function should be called before
1934# calling this function.  A given C file can contain several
1935# inline tests.  The names of the tests must be unique within one
1936# C file.
1937#
1938proc mi_run_inline_test { testcase } {
1939
1940    global mi_gdb_prompt
1941    global hex
1942    global decimal
1943    global fullname_syntax
1944    global mi_autotest_source
1945
1946    set commands [mi_get_inline_test $testcase]
1947
1948    set first 1
1949    set line_now 1
1950
1951    foreach c $commands {
1952	set statements [lindex $c 0]
1953	set line [lindex $c 1]
1954	set line [expr $line-1]
1955
1956	# We want gdb to be stopped at the expression immediately
1957	# before the comment.  If this is the first comment, the
1958	# program is either not started yet or is in some random place,
1959	# so we run it.  For further comments, we might be already
1960	# standing at the right line. If not continue till the
1961	# right line.
1962
1963	if {$first==1} {
1964	    # Start the program afresh.
1965	    mi_tbreak "$mi_autotest_source:$line" "set temporary breakpoint"
1966	    if { [mi_run_cmd] < 0 } {
1967		return -1
1968	    }
1969	    set line_now [mi_get_stop_line]
1970	    set first 0
1971	} elseif {$line_now!=$line} {
1972	    set line_now [mi_continue_to_line "$mi_autotest_source:$line" "continue to $line"]
1973	}
1974
1975	if {$line_now!=$line} {
1976	    fail "$testcase: go to line $line"
1977	}
1978
1979	# We're not at the statement right above the comment.
1980	# Execute that statement so that the comment can test
1981	# the state after the statement is executed.
1982
1983	# Single-step past the line.
1984	if { [mi_send_resuming_command "exec-next" "$testcase: step over $line"] != 0 } {
1985	    return -1
1986	}
1987	set line_now [mi_get_stop_line]
1988
1989	# We probably want to use 'uplevel' so that statements
1990	# have direct access to global variables that the
1991	# main 'exp' file has set up.  But it's not yet clear,
1992	# will need more experience to be sure.
1993	eval $statements
1994    }
1995
1996    return 0
1997}
1998
1999proc get_mi_thread_list {name} {
2000  global expect_out
2001
2002  # MI will return a list of thread ids:
2003  #
2004  # -thread-list-ids
2005  # ^done,thread-ids=[thread-id="1",thread-id="2",...],number-of-threads="N"
2006  # (gdb)
2007  mi_gdb_test "-thread-list-ids" \
2008    {.*\^done,thread-ids={(thread-id="[0-9]+"(,)?)+},current-thread-id="[0-9]+",number-of-threads="[0-9]+"} \
2009    "-thread_list_ids ($name)"
2010
2011  set output {}
2012  if {[info exists expect_out(buffer)]} {
2013    set output $expect_out(buffer)
2014  }
2015
2016  set thread_list {}
2017  if {![regexp {thread-ids=\{(thread-id="[0-9]+"(,)?)*\}} $output threads]} {
2018    fail "finding threads in MI output ($name)"
2019  } else {
2020    pass "finding threads in MI output ($name)"
2021
2022    # Make list of console threads
2023    set start [expr {[string first \{ $threads] + 1}]
2024    set end   [expr {[string first \} $threads] - 1}]
2025    set threads [string range $threads $start $end]
2026    foreach thread [split $threads ,] {
2027      if {[scan $thread {thread-id="%d"} num]} {
2028	lappend thread_list $num
2029      }
2030    }
2031  }
2032
2033  return $thread_list
2034}
2035
2036# Check that MI and the console know of the same threads.
2037# Appends NAME to all test names.
2038proc check_mi_and_console_threads {name} {
2039  global expect_out
2040
2041  mi_gdb_test "-thread-list-ids" \
2042    {.*\^done,thread-ids={(thread-id="[0-9]+"(,)*)+},current-thread-id="[0-9]+",number-of-threads="[0-9]+"} \
2043    "-thread-list-ids ($name)"
2044  set mi_output {}
2045  if {[info exists expect_out(buffer)]} {
2046    set mi_output $expect_out(buffer)
2047  }
2048
2049  # GDB will return a list of thread ids and some more info:
2050  #
2051  # (gdb)
2052  # -interpreter-exec console "info threads"
2053  # ~"  4 Thread 2051 (LWP 7734)  0x401166b1 in __libc_nanosleep () at __libc_nanosleep:-1"
2054  # ~"  3 Thread 1026 (LWP 7733)   () at __libc_nanosleep:-1"
2055  # ~"  2 Thread 2049 (LWP 7732)  0x401411f8 in __poll (fds=0x804bb24, nfds=1, timeout=2000) at ../sysdeps/unix/sysv/linux/poll.c:63"
2056  # ~"* 1 Thread 1024 (LWP 7731)  main (argc=1, argv=0xbfffdd94) at ../../../src/gdb/testsuite/gdb.mi/pthreads.c:160"
2057  # FIXME: kseitz/2002-09-05: Don't use the hack-cli method.
2058  mi_gdb_test "info threads" \
2059    {.*(~".*"[\r\n]*)+.*} \
2060    "info threads ($name)"
2061  set console_output {}
2062  if {[info exists expect_out(buffer)]} {
2063    set console_output $expect_out(buffer)
2064  }
2065
2066  # Make a list of all known threads to console (gdb's thread IDs)
2067  set console_thread_list {}
2068  foreach line [split $console_output \n] {
2069    if {[string index $line 0] == "~"} {
2070      # This is a line from the console; trim off "~", " ", "*", and "\""
2071      set line [string trim $line ~\ \"\*]
2072      if {[scan $line "%d" id] == 1} {
2073	lappend console_thread_list $id
2074      }
2075    }
2076  }
2077
2078  # Now find the result string from MI
2079  set mi_result ""
2080  foreach line [split $mi_output \n] {
2081    if {[string range $line 0 4] == "^done"} {
2082      set mi_result $line
2083    }
2084  }
2085  if {$mi_result == ""} {
2086    fail "finding MI result string ($name)"
2087  } else {
2088    pass "finding MI result string ($name)"
2089  }
2090
2091  # Finally, extract the thread ids and compare them to the console
2092  set num_mi_threads_str ""
2093  if {![regexp {number-of-threads="[0-9]+"} $mi_result num_mi_threads_str]} {
2094    fail "finding number of threads in MI output ($name)"
2095  } else {
2096    pass "finding number of threads in MI output ($name)"
2097
2098    # Extract the number of threads from the MI result
2099    if {![scan $num_mi_threads_str {number-of-threads="%d"} num_mi_threads]} {
2100      fail "got number of threads from MI ($name)"
2101    } else {
2102      pass "got number of threads from MI ($name)"
2103
2104      # Check if MI and console have same number of threads
2105      if {$num_mi_threads != [llength $console_thread_list]} {
2106	fail "console and MI have same number of threads ($name)"
2107      } else {
2108	pass "console and MI have same number of threads ($name)"
2109
2110	# Get MI thread list
2111	set mi_thread_list [get_mi_thread_list $name]
2112
2113	# Check if MI and console have the same threads
2114	set fails 0
2115	foreach ct [lsort $console_thread_list] mt [lsort $mi_thread_list] {
2116	  if {$ct != $mt} {
2117	    incr fails
2118	  }
2119	}
2120	if {$fails > 0} {
2121	  fail "MI and console have same threads ($name)"
2122
2123	  # Send a list of failures to the log
2124	  send_log "Console has thread ids: $console_thread_list\n"
2125	  send_log "MI has thread ids: $mi_thread_list\n"
2126	} else {
2127	  pass "MI and console have same threads ($name)"
2128	}
2129      }
2130    }
2131  }
2132}
2133
2134# Download shared libraries to the target.
2135proc mi_load_shlibs { args } {
2136    foreach file $args {
2137	gdb_remote_download target [shlib_target_file $file]
2138    }
2139
2140    if {[is_remote target]} {
2141	# If the target is remote, we need to tell gdb where to find the
2142	# libraries.
2143	#
2144	# We could set this even when not testing remotely, but a user
2145	# generally won't set it unless necessary.  In order to make the tests
2146	# more like the real-life scenarios, we don't set it for local testing.
2147	mi_gdb_test "set solib-search-path [file dirname [lindex $args 0]]" "\^done" ""
2148    }
2149}
2150
2151proc mi_check_thread_states { states test } {
2152    global expect_out
2153    set pattern ".*\\^done,threads=\\\["
2154    foreach s $states {
2155	set pattern "${pattern}(.*)state=\"$s\""
2156    }
2157    set pattern "${pattern}(,core=\"\[0-9\]*\")?\\\}\\\].*"
2158
2159    verbose -log "expecting: $pattern"
2160    mi_gdb_test "-thread-info" $pattern $test
2161}
2162
2163# Return a list of MI features supported by this gdb.
2164proc mi_get_features {} {
2165    global expect_out mi_gdb_prompt
2166
2167    send_gdb "-list-features\n"
2168
2169    gdb_expect {
2170	-re "\\^done,features=\\\[(.*)\\\]\r\n$mi_gdb_prompt$" {
2171	    regsub -all -- \" $expect_out(1,string) "" features
2172	    return [split $features ,]
2173	}
2174	-re ".*\r\n$mi_gdb_prompt$" {
2175	    verbose -log "got $expect_out(buffer)"
2176	    return ""
2177	}
2178	timeout {
2179	    verbose -log "timeout in mi_gdb_prompt"
2180	    return ""
2181	}
2182    }
2183}
2184
2185# Variable Object Trees
2186#
2187# Yet another way to check varobjs. Pass mi_walk_varobj_tree a "list" of
2188# variables (not unlike the actual source code definition), and it will
2189# automagically test the children for you (by default).
2190#
2191# Example:
2192#
2193# source code:
2194# struct bar {
2195#   union {
2196#     int integer;
2197#     void *ptr;
2198#   };
2199#   const int *iPtr;
2200# };
2201#
2202# class foo {
2203# public:
2204#   int a;
2205#   struct {
2206#     int b;
2207#     struct bar *c;
2208#   };
2209# };
2210#
2211# foo *f = new foo (); <-- break here
2212#
2213# We want to check all the children of "f".
2214#
2215# Translate the above structures into the following tree:
2216#
2217# set tree {
2218#   foo f {
2219#     {} public {
2220#       int a {}
2221#       anonymous struct {
2222#         {} public {
2223#           int b {}
2224#           {bar *} c {
2225#             {} public {
2226#               anonymous union {
2227#                 {} public {
2228#                   int integer {}
2229#                   {void *} ptr {}
2230#                 }
2231#               }
2232#               {const int *} iPtr {
2233#                 {const int} {*iPtr} {}
2234#               }
2235#             }
2236#           }
2237#         }
2238#       }
2239#     }
2240#   }
2241# }
2242#
2243# mi_walk_varobj_tree c++ $tree
2244#
2245# If you'd prefer to walk the tree using your own callback,
2246# simply pass the name of the callback to mi_walk_varobj_tree.
2247#
2248# This callback should take one argument, the name of the variable
2249# to process.  This name is the name of a global array holding the
2250# variable's properties (object name, type, etc).
2251#
2252# An example callback:
2253#
2254# proc my_callback {var} {
2255#   upvar #0 $var varobj
2256#
2257#   puts "my_callback: called on varobj $varobj(obj_name)"
2258# }
2259#
2260# The arrays created for each variable object contain the following
2261# members:
2262#
2263# obj_name     - the object name for accessing this variable via MI
2264# display_name - the display name for this variable (exp="display_name" in
2265#                the output of -var-list-children)
2266# type         - the type of this variable (type="type" in the output
2267#                of -var-list-children, or the special tag "anonymous"
2268# path_expr    - the "-var-info-path-expression" for this variable
2269#                NOTE: This member cannot be used reliably with typedefs.
2270#                Use with caution!
2271#                See notes inside get_path_expr for more.
2272# parent       - the variable name of the parent varobj
2273# children     - a list of children variable names (which are the
2274#                names Tcl arrays, not object names)
2275#
2276# For each variable object, an array containing the above fields will
2277# be created under the root node (conveniently called, "root").  For example,
2278# a variable object with handle "OBJ.public.0_anonymous.a" will have
2279# a corresponding global Tcl variable named "root.OBJ.public.0_anonymous.a".
2280#
2281# Note that right now, this mechanism cannot be used for recursive data
2282# structures like linked lists.
2283
2284namespace eval ::varobj_tree {
2285  # An index which is appended to root varobjs to ensure uniqueness.
2286  variable _root_idx 0
2287
2288  # A procedure to help with debuggging varobj trees.
2289  # VARIABLE_NAME is the name of the variable to dump.
2290  # CMD, if present, is the name of the callback to output the contstructed
2291  #   strings. By default, it uses expect's "send_log" command.
2292  # TERM, if present, is a terminating character. By default it is the newline.
2293  #
2294  # To output to the terminal (not the expect log), use
2295  # mi_varobj_tree_dump_variable my_variable puts ""
2296
2297  proc mi_varobj_tree_dump_variable {variable_name {cmd send_log} {term "\n"}} {
2298    upvar #0 $variable_name varobj
2299
2300    eval "$cmd \"VAR = $variable_name$term\""
2301
2302    # Explicitly encode the array indices, since outputting them
2303    # in some logical order is better than what "array names" might
2304    # return.
2305    foreach idx {obj_name parent display_name type path_expr} {
2306      eval "$cmd \"\t$idx = $varobj($idx)$term\""
2307    }
2308
2309    # Output children
2310    set num [llength $varobj(children)]
2311    eval "$cmd \"\tnum_children = $num$term\""
2312    if {$num > 0} {
2313      eval "$cmd \"\tchildren = $varobj(children)$term\""
2314    }
2315  }
2316
2317  # The default callback used by mi_walk_varobj_tree.  This callback
2318  # simply checks all of VAR's children.  It specifically does not test
2319  # path expressions, since that is very problematic.
2320  #
2321  # This procedure may be used in custom callbacks.
2322  proc test_children_callback {variable_name} {
2323    upvar #0 $variable_name varobj
2324
2325    if {[llength $varobj(children)] > 0} {
2326      # Construct the list of children the way mi_list_varobj_children
2327      # expects to get it:
2328      # { {obj_name display_name num_children type} ... }
2329      set children_list {}
2330      foreach child $varobj(children) {
2331	upvar #0 $child c
2332	set clist [list [string_to_regexp $c(obj_name)] \
2333		       [string_to_regexp $c(display_name)] \
2334		       [llength $c(children)]]
2335	if {[string length $c(type)] > 0} {
2336	  lappend clist [string_to_regexp $c(type)]
2337	}
2338	lappend children_list $clist
2339      }
2340
2341      mi_list_varobj_children $varobj(obj_name) $children_list \
2342	  "VT: list children of $varobj(obj_name)"
2343    }
2344  }
2345
2346  # Set the properties of the varobj represented by
2347  # PARENT_VARIABLE - the name of the parent's variable
2348  # OBJNAME         - the MI object name of this variable
2349  # DISP_NAME       - the display name of this variable
2350  # TYPE            - the type of this variable
2351  # PATH            - the path expression for this variable
2352  # CHILDREN        - a list of the variable's children
2353  proc create_varobj {parent_variable objname disp_name \
2354			  type path children} {
2355    upvar #0 $parent_variable parent
2356
2357    set var_name "root.$objname"
2358    global $var_name
2359    array set $var_name [list obj_name $objname]
2360    array set $var_name [list display_name $disp_name]
2361    array set $var_name [list type $type]
2362    array set $var_name [list path_expr $path]
2363    array set $var_name [list parent "$parent_variable"]
2364    array set $var_name [list children \
2365			     [get_tree_children $var_name $children]]
2366    return $var_name
2367  }
2368
2369  # Should VARIABLE be used in path expressions?  The CPLUS_FAKE_CHILD
2370  # varobjs and anonymous structs/unions are not used for path expressions.
2371  proc is_path_expr_parent {variable} {
2372    upvar #0 $variable varobj
2373
2374    # If the varobj's type is "", it is a CPLUS_FAKE_CHILD.
2375    # If the tail of the varobj's object name is "%d_anonymous",
2376    # then it represents an anonymous struct or union.
2377    if {[string length $varobj(type)] == 0 \
2378	    || [regexp {[0-9]+_anonymous$} $varobj(obj_name)]} {
2379      return false
2380    }
2381
2382    return true
2383  }
2384
2385  # Return the path expression for the variable named NAME in
2386  # parent varobj whose variable name is given by PARENT_VARIABLE.
2387  proc get_path_expr {parent_variable name type} {
2388    upvar #0 $parent_variable parent
2389    upvar #0 $parent_variable path_parent
2390
2391    # If TYPE is "", this is one of the CPLUS_FAKE_CHILD varobjs,
2392    # which has no path expression.  Likewsise for anonymous structs
2393    # and unions.
2394    if {[string length $type] == 0 \
2395	    || [string compare $type "anonymous"] == 0} {
2396      return ""
2397    }
2398
2399    # Find the path parent variable.
2400    while {![is_path_expr_parent $parent_variable]} {
2401      set parent_variable $path_parent(parent)
2402      upvar #0 $parent_variable path_parent
2403    }
2404
2405    # This is where things get difficult.  We do not actually know
2406    # the real type for variables defined via typedefs, so we don't actually
2407    # know whether the parent is a structure/union or not.
2408    #
2409    # So we assume everything that isn't a simple type is a compound type.
2410    set stars ""
2411    regexp {\*+} $parent(type) stars
2412    set is_compound 1
2413    if {[string index $name 0] == "*"} {
2414      set is_compound 0
2415    }
2416
2417    if {[string index $parent(type) end] == "\]"} {
2418      # Parent is an array.
2419      return "($path_parent(path_expr))\[$name\]"
2420    } elseif {$is_compound} {
2421      # Parent is a structure or union or a pointer to one.
2422      if {[string length $stars]} {
2423	set join "->"
2424      } else {
2425	set join "."
2426      }
2427
2428      global root
2429
2430      # To make matters even more hideous, varobj.c has slightly different
2431      # path expressions for C and C++.
2432      set path_expr "($path_parent(path_expr))$join$name"
2433      if {[string compare -nocase $root(language) "c"] == 0} {
2434	return $path_expr
2435      } else {
2436	return "($path_expr)"
2437      }
2438    } else {
2439      # Parent is a pointer.
2440      return "*($path_parent(path_expr))"
2441    }
2442  }
2443
2444  # Process the CHILDREN (a list of varobj_tree elements) of the variable
2445  # given by PARENT_VARIABLE.  Returns a list of children variables.
2446  proc get_tree_children {parent_variable children} {
2447    upvar #0 $parent_variable parent
2448
2449    set field_idx 0
2450    set children_list {}
2451    foreach {type name children} $children {
2452      if {[string compare $parent_variable "root"] == 0} {
2453	# Root variable
2454	variable _root_idx
2455	incr _root_idx
2456	set objname "$name$_root_idx"
2457	set disp_name "$name"
2458	set path_expr "$name"
2459      } elseif {[string compare $type "anonymous"] == 0} {
2460	# Special case: anonymous types.  In this case, NAME will either be
2461	# "struct" or "union".
2462	set objname "$parent(obj_name).${field_idx}_anonymous"
2463	set disp_name "<anonymous $name>"
2464	set path_expr ""
2465	set type "$name {...}"
2466      } else {
2467	set objname "$parent(obj_name).$name"
2468	set disp_name $name
2469	set path_expr [get_path_expr $parent_variable $name $type]
2470      }
2471
2472      lappend children_list [create_varobj $parent_variable $objname \
2473				 $disp_name $type $path_expr $children]
2474      incr field_idx
2475    }
2476
2477    return $children_list
2478  }
2479
2480  # The main procedure to call the given CALLBACK on the elements of the
2481  # given varobj TREE.  See detailed explanation above.
2482  proc walk_tree {language tree callback} {
2483    global root
2484    variable _root_idx
2485
2486    if {[llength $tree] < 3} {
2487      error "tree does not contain enough elements"
2488    }
2489
2490    set _root_idx 0
2491
2492    # Create root node and process the tree.
2493    array set root [list language $language]
2494    array set root [list obj_name "root"]
2495    array set root [list display_name "root"]
2496    array set root [list type "root"]
2497    array set root [list path_expr "root"]
2498    array set root [list parent "root"]
2499    array set root [list children [get_tree_children root $tree]]
2500
2501    # Walk the tree
2502    set all_nodes $root(children); # a stack of nodes
2503    while {[llength $all_nodes] > 0} {
2504      # "Pop" the name of the global variable containing this varobj's
2505      # information from the stack of nodes.
2506      set var_name [lindex $all_nodes 0]
2507      set all_nodes [lreplace $all_nodes 0 0]
2508
2509      # Bring the global named in VAR_NAME into scope as the local variable
2510      # VAROBJ.
2511      upvar #0 $var_name varobj
2512
2513      # Append any children of VAROBJ to the list of nodes to walk.
2514      if {[llength $varobj(children)] > 0} {
2515	set all_nodes [concat $all_nodes $varobj(children)]
2516      }
2517
2518      # If this is a root variable, create the variable object for it.
2519      if {[string compare $varobj(parent) "root"] == 0} {
2520	mi_create_varobj $varobj(obj_name) $varobj(display_name) \
2521	    "VT: create root varobj for $varobj(display_name)"
2522      }
2523
2524      # Now call the callback for VAROBJ.
2525      uplevel #0 $callback $var_name
2526    }
2527  }
2528}
2529
2530# The default varobj tree callback, which simply tests -var-list-children.
2531proc mi_varobj_tree_test_children_callback {variable} {
2532  ::varobj_tree::test_children_callback $variable
2533}
2534
2535# Walk the variable object tree given by TREE, calling the specified
2536# CALLBACK.  By default this uses mi_varobj_tree_test_children_callback.
2537proc mi_walk_varobj_tree {language tree \
2538			      {callback \
2539				   mi_varobj_tree_test_children_callback}} {
2540  ::varobj_tree::walk_tree $language $tree $callback
2541}
2542
2543# Build a list of key-value pairs given by the list ATTR_LIST.  Flatten
2544# this list using the optional JOINER, a comma by default.
2545#
2546# The list must contain an even number of elements, which are the key-value
2547# pairs.  Each value will be surrounded by quotes, according to the grammar,
2548# except if the value starts with \[ or \{, when the quotes will be omitted.
2549#
2550# Example: mi_build_kv_pairs {a b c d e f g \[.*\]}
2551# returns a=\"b\",c=\"d\",e=\"f\",g=\[.*\]
2552proc mi_build_kv_pairs {attr_list {joiner ,}} {
2553    set l {}
2554    foreach {var value} $attr_list {
2555	if {[string range $value 0 1] == "\\\["
2556	    || [string range $value 0 1] == "\\\{"} {
2557	    lappend l "$var=$value"
2558	} else {
2559	    lappend l "$var=\"$value\""
2560	}
2561    }
2562    return "[join $l $joiner]"
2563}
2564
2565# Construct a breakpoint location regexp.  This may be used along with
2566# mi_make_breakpoint_multi to test the output of -break-insert,
2567# -dprintf-insert, or -break-info with breapoints with multiple
2568# locations.
2569#
2570# All arguments for the breakpoint location may be specified using the
2571# options number, enabled, addr, func, file, fullname, line and
2572# thread-groups.
2573#
2574# Example: mi_make_breakpoint_loc -number 2.1 -file ".*/myfile.c" -line 3
2575# will return the breakpoint location:
2576# {number="2.1",enabled=".*",addr=".*",func=".*",
2577#       file=".*/myfile.c",fullname=".*",line="3",thread-groups=\[.*\]}
2578
2579proc mi_make_breakpoint_loc {args} {
2580    parse_args {{number .*} {enabled .*} {addr .*}
2581	{func .*} {file .*} {fullname .*} {line .*}
2582	{thread-groups \\\[.*\\\]}}
2583
2584    set attr_list {}
2585    foreach attr [list number enabled addr func file \
2586		      fullname line thread-groups] {
2587	lappend attr_list $attr [set $attr]
2588    }
2589
2590    return "{[mi_build_kv_pairs $attr_list]}"
2591}
2592
2593# Bits shared between mi_make_breakpoint and mi_make_breakpoint_multi.
2594
2595proc mi_make_breakpoint_1 {attr_list cond evaluated-by times \
2596			   ignore script original-location} {
2597    set result "bkpt=\\\{[mi_build_kv_pairs $attr_list]"
2598
2599    # There are always exceptions.
2600
2601    # If COND is not preset, do not output it.
2602    if {[string length $cond] > 0} {
2603	append result ","
2604	append result [mi_build_kv_pairs [list "cond" $cond]]
2605
2606	# When running on a remote, GDB may output who is evaluating
2607	# breakpoint conditions.
2608	if {[string length ${evaluated-by}] > 0} {
2609	    append result [mi_build_kv_pairs \
2610			       [list "evaluated-by" ${evaluated-by}]]
2611	} else {
2612	    append result {(,evaluated-by=".*")?}
2613	}
2614    }
2615
2616    append result ","
2617    append result [mi_build_kv_pairs [list "times" $times]]
2618
2619    # If SCRIPT and IGNORE are not present, do not output them.
2620    if {$ignore != 0} {
2621	append result ","
2622	append result [mi_build_kv_pairs [list "ignore" $ignore]]
2623	append result ","
2624    }
2625    if {[string length $script] > 0} {
2626	append result ","
2627	append result [mi_build_kv_pairs [list "script" $script]]
2628	append result ","
2629    } else {
2630	# Allow anything up until the next "official"/required attribute.
2631	# This pattern skips over script/ignore if matches on those
2632	# were not specifically required by the caller.
2633	append result ".*"
2634    }
2635    append result [mi_build_kv_pairs \
2636		       [list "original-location" ${original-location}]]
2637
2638    return $result
2639}
2640
2641
2642# Construct a breakpoint regexp, for a breakpoint with multiple
2643# locations.  This may be used to test the output of -break-insert,
2644# -dprintf-insert, or -break-info with breakpoints with multiple
2645# locations.
2646#
2647# All arguments for the breakpoint may be specified using the options
2648# number, type, disp, enabled, func, cond, evaluated-by, times,
2649# ignore, script and locations.
2650#
2651# Only if -script and -ignore are given will they appear in the output.
2652# Otherwise, this procedure will skip them using ".*".
2653#
2654# Example: mi_make_breakpoint_multi -number 2 -locations "$loc"
2655# will return the breakpoint:
2656# bkpt={number="2",type=".*",disp=".*",enabled=".*",addr="<MULTIPLE>",
2657#       times="0".*original-location=".*",locations=$loc}
2658#
2659# You can construct the list of locations with mi_make_breakpoint_loc.
2660
2661proc mi_make_breakpoint_multi {args} {
2662    parse_args {{number .*} {type .*} {disp .*} {enabled .*}
2663	{times .*} {ignore 0}
2664	{script ""} {original-location .*} {cond ""} {evaluated-by ""}
2665	{locations .*}}
2666
2667    set attr_list {}
2668    foreach attr [list number type disp enabled] {
2669	lappend attr_list $attr [set $attr]
2670    }
2671
2672    lappend attr_list "addr" "<MULTIPLE>"
2673
2674    set result [mi_make_breakpoint_1 \
2675		    $attr_list $cond ${evaluated-by} $times \
2676		    $ignore $script ${original-location}]
2677
2678    append result ","
2679    append result [mi_build_kv_pairs [list "locations" $locations]]
2680
2681    append result "\\\}"
2682    return $result
2683}
2684
2685# Construct a breakpoint regexp, for a pending breakpoint.  This may
2686# be used to test the output of -break-insert, -dprintf-insert, or
2687# -break-info for pending breakpoints.
2688#
2689# Arguments for the breakpoint may be specified using the options
2690# number, type, disp, enabled, pending.
2691#
2692# Example: mi_make_breakpoint_pending -number 2 -pending func
2693# will return the breakpoint:
2694# bkpt={number="2",type=".*",disp=".*",enabled=".*",addr="<PENDING>",
2695#       pending="func", times="0".*original-location=".*"}
2696
2697proc mi_make_breakpoint_pending {args} {
2698    parse_args {{number .*} {type .*} {disp .*} {enabled .*}
2699	{pending .*} {original-location .*}}
2700
2701    set attr_list {}
2702    foreach attr [list number type disp enabled] {
2703	lappend attr_list $attr [set $attr]
2704    }
2705
2706    lappend attr_list "addr" "<PENDING>"
2707
2708    foreach attr [list pending] {
2709	lappend attr_list $attr [set $attr]
2710    }
2711
2712    set ignore 0
2713    set times 0
2714    set script ""
2715    set cond ""
2716    set evaluated-by ""
2717
2718    set result [mi_make_breakpoint_1 \
2719		    $attr_list $cond ${evaluated-by} $times \
2720		    $ignore $script ${original-location}]
2721
2722    append result "\\\}"
2723    return $result
2724}
2725
2726# Construct a breakpoint regexp.  This may be used to test the output of
2727# -break-insert, -dprintf-insert, or -break-info.
2728#
2729# All arguments for the breakpoint may be specified using the options
2730# number, type, disp, enabled, addr, func, file, fullanme, line,
2731# thread-groups, cond, evaluated-by, times, ignore, script,
2732# and original-location.
2733#
2734# Only if -script and -ignore are given will they appear in the output.
2735# Otherwise, this procedure will skip them using ".*".
2736#
2737# Example: mi_make_breakpoint -number 2 -file ".*/myfile.c" -line 3
2738# will return the breakpoint:
2739# bkpt={number="2",type=".*",disp=".*",enabled=".*",addr=".*",func=".*",
2740#       file=".*/myfile.c",fullname=".*",line="3",thread-groups=\[.*\],
2741#       times="0".*original-location=".*"}
2742
2743proc mi_make_breakpoint {args} {
2744    parse_args {{number .*} {type .*} {disp .*} {enabled .*} {addr .*}
2745	{func .*} {file .*} {fullname .*} {line .*}
2746	{thread-groups \\\[.*\\\]} {times .*} {ignore 0}
2747	{script ""} {original-location .*} {cond ""} {evaluated-by ""}}
2748
2749    set attr_list {}
2750    foreach attr [list number type disp enabled addr func file \
2751		      fullname line thread-groups] {
2752	lappend attr_list $attr [set $attr]
2753    }
2754
2755    set result [mi_make_breakpoint_1 \
2756		    $attr_list $cond ${evaluated-by} $times \
2757		    $ignore $script ${original-location}]
2758
2759    append result "\\\}"
2760    return $result
2761}
2762
2763# Build a breakpoint table regexp given the list of breakpoints in `bp_list',
2764# constructed by mi_make_breakpoint.
2765#
2766# Example:  Construct a breakpoint table where the only attributes we
2767# test for are the existence of three breakpoints numbered 1, 2, and 3.
2768#
2769# set bps {}
2770# lappend bps [mi_make_breakpoint -number 1]
2771# lappend bps [mi_make_breakpoint -number 2]
2772# lappned bps [mi_make_breakpoint -number 3]
2773# mi_make_breakpoint_table $bps
2774# will return (abbreviated for clarity):
2775# BreakpointTable={nr_rows="3",nr_cols="6",hdr=[{width=".*",...} ...],
2776#   body=[bkpt={number="1",...},bkpt={number="2",...},bkpt={number="3",...}]}
2777
2778proc mi_make_breakpoint_table {bp_list} {
2779    # Build header -- assume a standard header for all breakpoint tables.
2780    set hl {}
2781    foreach {nm hdr} [list number Num type Type disp Disp enabled Enb \
2782			  addr Address what What] {
2783	# The elements here are the MI table headers, which have the
2784	# format:
2785	# {width="7",alignment="-1",col_name="number",colhdr="Num"}
2786	lappend hl "{[mi_build_kv_pairs [list width .* alignment .* \
2787				       col_name $nm colhdr $hdr]]}"
2788    }
2789    set header "hdr=\\\[[join $hl ,]\\\]"
2790
2791    # The caller has implicitly supplied the number of columns and rows.
2792    set nc [llength $hl]
2793    set nr [llength $bp_list]
2794
2795    # Build body -- mi_make_breakpoint has done most of the work.
2796    set body "body=\\\[[join $bp_list ,]\\\]"
2797
2798    # Assemble the final regexp.
2799    return "BreakpointTable={nr_rows=\"$nr\",nr_cols=\"$nc\",$header,$body}"
2800}
2801
2802# Return a 1 for configurations that do not support Python scripting.
2803# Note: This also sets various globals that specify which version of Python
2804# is in use.  See skip_python_tests_prompt.
2805
2806proc mi_skip_python_tests {} {
2807    global mi_gdb_prompt
2808    return [skip_python_tests_prompt "$mi_gdb_prompt$"]
2809}
2810
2811# As skip_libstdcxx_probe_tests_prompt, with mi_gdb_prompt.
2812
2813proc mi_skip_libstdcxx_probe_tests {} {
2814    global mi_gdb_prompt
2815    return [skip_libstdcxx_probe_tests_prompt "$mi_gdb_prompt$"]
2816}
2817
2818# Check whether we're testing with the remote or extended-remote
2819# targets.
2820
2821proc mi_is_target_remote {} {
2822    global mi_gdb_prompt
2823
2824    return [gdb_is_target_remote_prompt "$mi_gdb_prompt"]
2825}
2826
2827# Retrieve the value of EXP in the inferior, represented in format
2828# specified in FMT (using "printFMT").  DEFAULT is used as fallback if
2829# print fails.  TEST is the test message to use.  It can be omitted,
2830# in which case a test message is built from EXP.
2831#
2832# This is an MI version of gdb_valueof.
2833
2834proc mi_get_valueof { fmt exp default {test ""} } {
2835    global mi_gdb_prompt
2836
2837    if {$test == "" } {
2838	set test "get valueof \"${exp}\""
2839    }
2840
2841    set val ${default}
2842    gdb_test_multiple "print${fmt} ${exp}" "$test" -prompt "$::mi_gdb_prompt$" {
2843	-re "~\"\\$\[0-9\]* = (\[^\r\n\]*)\\\\n\"\r\n\\^done\r\n$mi_gdb_prompt$" {
2844	    set val $expect_out(1,string)
2845	    pass "$test"
2846	}
2847	timeout {
2848	    fail "$test (timeout)"
2849	}
2850    }
2851    return ${val}
2852}
2853