1# Copyright 1999, 2000, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010, 2011
2# Free Software Foundation, Inc.
3
4# This program is free software; you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation; either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17# This file was based on a file written by Fred Fish. (fnf@cygnus.com)
18
19# Test setup routines that work with the MI interpreter.
20
21# The variable mi_gdb_prompt is a regexp which matches the gdb mi prompt.
22# Set it if it is not already set.
23global mi_gdb_prompt
24if ![info exists mi_gdb_prompt] then {
25    set mi_gdb_prompt "\[(\]gdb\[)\] \r\n"
26}
27
28global mi_inferior_spawn_id
29global mi_inferior_tty_name
30
31set MIFLAGS "-i=mi"
32
33set thread_selected_re "=thread-selected,id=\"\[0-9\]+\"\r\n"
34set library_loaded_re "=library-loaded\[^\n\]+\"\r\n"
35
36#
37# mi_gdb_exit -- exit the GDB, killing the target program if necessary
38#
39proc mi_gdb_exit {} {
40    catch mi_uncatched_gdb_exit
41}
42
43proc mi_uncatched_gdb_exit {} {
44    global GDB
45    global INTERNAL_GDBFLAGS GDBFLAGS
46    global verbose
47    global gdb_spawn_id;
48    global gdb_prompt
49    global mi_gdb_prompt
50    global MIFLAGS
51
52    gdb_stop_suppressing_tests;
53
54    if { [info procs sid_exit] != "" } {
55	sid_exit
56    }
57
58    if ![info exists gdb_spawn_id] {
59	return;
60    }
61
62    verbose "Quitting $GDB $INTERNAL_GDBFLAGS $GDBFLAGS $MIFLAGS"
63
64    if { [is_remote host] && [board_info host exists fileid] } {
65	send_gdb "999-gdb-exit\n";
66	gdb_expect 10 {
67	    -re "y or n" {
68		send_gdb "y\n";
69		exp_continue;
70	    }
71            -re "Undefined command.*$gdb_prompt $" {
72                send_gdb "quit\n"
73		exp_continue;
74            }
75	    -re "DOSEXIT code" { }
76	    default { }
77	}
78    }
79
80    if ![is_remote host] {
81	remote_close host;
82    }
83    unset gdb_spawn_id
84}
85
86#
87# default_mi_gdb_start [INFERIOR_PTY] -- start gdb running, default procedure
88#
89# INFERIOR_PTY should be set to separate-inferior-tty to have the inferior work
90# with it's own PTY. If set to same-inferior-tty, the inferior shares GDB's PTY.
91# The default value is same-inferior-tty.
92#
93# When running over NFS, particularly if running many simultaneous
94# tests on different hosts all using the same server, things can
95# get really slow.  Give gdb at least 3 minutes to start up.
96#
97proc default_mi_gdb_start { args } {
98    global verbose
99    global GDB
100    global INTERNAL_GDBFLAGS GDBFLAGS
101    global gdb_prompt
102    global mi_gdb_prompt
103    global timeout
104    global gdb_spawn_id;
105    global MIFLAGS
106
107    gdb_stop_suppressing_tests;
108    set inferior_pty no-tty
109
110    if { [llength $args] == 1} {
111	set inferior_pty [lindex $args 0]
112    }
113
114    set separate_inferior_pty [string match $inferior_pty separate-inferior-tty]
115
116    # Start SID.
117    if { [info procs sid_start] != "" } {
118	verbose "Spawning SID"
119	sid_start
120    }
121
122    verbose "Spawning $GDB $INTERNAL_GDBFLAGS $GDBFLAGS $MIFLAGS"
123
124    if [info exists gdb_spawn_id] {
125	return 0;
126    }
127
128    if ![is_remote host] {
129	if { [which $GDB] == 0 } then {
130	    perror "$GDB does not exist."
131	    exit 1
132	}
133    }
134
135    # Create the new PTY for the inferior process.
136    if { $separate_inferior_pty } {
137	spawn -pty
138	global mi_inferior_spawn_id
139	global mi_inferior_tty_name
140	set mi_inferior_spawn_id $spawn_id
141	set mi_inferior_tty_name $spawn_out(slave,name)
142    }
143
144    set res [remote_spawn host "$GDB $INTERNAL_GDBFLAGS $GDBFLAGS $MIFLAGS [host_info gdb_opts]"];
145    if { $res < 0 || $res == "" } {
146	perror "Spawning $GDB failed."
147	return 1;
148    }
149    gdb_expect {
150	-re "~\"GNU.*\r\n~\".*$mi_gdb_prompt$" {
151	    # We have a new format mi startup prompt.  If we are
152	    # running mi1, then this is an error as we should be
153	    # using the old-style prompt.
154	    if { $MIFLAGS == "-i=mi1" } {
155	        perror "(mi startup) Got unexpected new mi prompt."
156	        remote_close host;
157	        return -1;
158	    }
159	    verbose "GDB initialized."
160	}
161	-re "\[^~\].*$mi_gdb_prompt$" {
162	    # We have an old format mi startup prompt.  If we are
163	    # not running mi1, then this is an error as we should be
164	    # using the new-style prompt.
165	    if { $MIFLAGS != "-i=mi1" } {
166	        perror "(mi startup) Got unexpected old mi prompt."
167	        remote_close host;
168	        return -1;
169	    }
170	    verbose "GDB initialized."
171	}
172	-re ".*unrecognized option.*for a complete list of options." {
173	    untested "Skip mi tests (not compiled with mi support)."
174	    remote_close host;
175	    return -1;
176	}
177	-re ".*Interpreter `mi' unrecognized." {
178	    untested "Skip mi tests (not compiled with mi support)."
179	    remote_close host;
180	    return -1;
181	}
182	timeout {
183	    perror "(timeout) GDB never initialized after 10 seconds."
184	    remote_close host;
185	    return -1
186	}
187    }
188    set gdb_spawn_id -1;
189
190    # FIXME: mi output does not go through pagers, so these can be removed.
191    # force the height to "unlimited", so no pagers get used
192    send_gdb "100-gdb-set height 0\n"
193    gdb_expect 10 {
194	-re ".*100-gdb-set height 0\r\n100\\\^done\r\n$mi_gdb_prompt$" {
195	    verbose "Setting height to 0." 2
196	}
197	timeout {
198	    warning "Couldn't set the height to 0"
199	}
200    }
201    # force the width to "unlimited", so no wraparound occurs
202    send_gdb "101-gdb-set width 0\n"
203    gdb_expect 10 {
204	-re ".*101-gdb-set width 0\r\n101\\\^done\r\n$mi_gdb_prompt$" {
205	    verbose "Setting width to 0." 2
206	}
207	timeout {
208	    warning "Couldn't set the width to 0."
209	}
210    }
211    # If allowing the inferior to have its own PTY then assign the inferior
212    # its own terminal device here.
213    if { $separate_inferior_pty } {
214	send_gdb "102-inferior-tty-set $mi_inferior_tty_name\n"
215	gdb_expect 10 {
216	    -re ".*102\\\^done\r\n$mi_gdb_prompt$" {
217		verbose "redirect inferior output to new terminal device."
218	    }
219	    timeout {
220	    	warning "Couldn't redirect inferior output." 2
221	    }
222    	}
223    }
224
225    detect_async
226
227    return 0;
228}
229
230#
231# Overridable function. You can override this function in your
232# baseboard file.
233#
234proc mi_gdb_start { args } {
235  return [default_mi_gdb_start $args]
236}
237
238# Many of the tests depend on setting breakpoints at various places and
239# running until that breakpoint is reached.  At times, we want to start
240# with a clean-slate with respect to breakpoints, so this utility proc
241# lets us do this without duplicating this code everywhere.
242#
243
244proc mi_delete_breakpoints {} {
245    global mi_gdb_prompt
246
247# FIXME: The mi operation won't accept a prompt back and will use the 'all' arg
248    send_gdb "102-break-delete\n"
249    gdb_expect 30 {
250	 -re "Delete all breakpoints.*y or n.*$" {
251	    send_gdb "y\n";
252	    exp_continue
253         }
254	 -re "102-break-delete\r\n102\\\^done\r\n$mi_gdb_prompt$" {
255            # This happens if there were no breakpoints
256	 }
257	 timeout { perror "Delete all breakpoints in mi_delete_breakpoints (timeout)" ; return }
258    }
259
260# The correct output is not "No breakpoints or watchpoints." but an
261# empty BreakpointTable. Also, a query is not acceptable with mi.
262    send_gdb "103-break-list\n"
263    gdb_expect 30 {
264	 -re "103-break-list\r\n103\\\^done,BreakpointTable=\{\}\r\n$mi_gdb_prompt$" {}
265	 -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$" {}
266	 -re "103-break-list\r\n103\\\^doneNo breakpoints or watchpoints.\r\n\r\n$mi_gdb_prompt$" {warning "Unexpected console text received"}
267	 -re "$mi_gdb_prompt$" { perror "Breakpoints not deleted" ; return }
268	 -re "Delete all breakpoints.*or n.*$" {
269	    warning "Unexpected prompt for breakpoints deletion";
270	    send_gdb "y\n";
271	    exp_continue
272	}
273	 timeout { perror "-break-list (timeout)" ; return }
274    }
275}
276
277proc mi_gdb_reinitialize_dir { subdir } {
278    global mi_gdb_prompt
279    global MIFLAGS
280
281    global suppress_flag
282    if { $suppress_flag } {
283	return
284    }
285
286    if [is_remote host] {
287	return "";
288    }
289
290    if { $MIFLAGS == "-i=mi1" } {
291      send_gdb "104-environment-directory\n"
292      gdb_expect 60 {
293	-re ".*Reinitialize source path to empty.*y or n. " {
294            warning "Got confirmation prompt for dir reinitialization."
295	    send_gdb "y\n"
296	    gdb_expect 60 {
297		-re "$mi_gdb_prompt$" {}
298                timeout {error "Dir reinitialization failed (timeout)"}
299	    }
300	}
301	-re "$mi_gdb_prompt$" {}
302        timeout {error "Dir reinitialization failed (timeout)"}
303      }
304    } else {
305      send_gdb "104-environment-directory -r\n"
306      gdb_expect 60 {
307	-re "104\\\^done,source-path=.*\r\n$mi_gdb_prompt$" {}
308	-re "$mi_gdb_prompt$" {}
309        timeout {error "Dir reinitialization failed (timeout)"}
310      }
311    }
312
313    send_gdb "105-environment-directory $subdir\n"
314    gdb_expect 60 {
315	-re "Source directories searched.*$mi_gdb_prompt$" {
316	    verbose "Dir set to $subdir"
317	}
318	-re "105\\\^done.*\r\n$mi_gdb_prompt$" {
319            # FIXME: We return just the prompt for now.
320	    verbose "Dir set to $subdir"
321	    # perror "Dir \"$subdir\" failed."
322	}
323    }
324}
325
326# Send GDB the "target" command.
327# FIXME: Some of these patterns are not appropriate for MI.  Based on
328# config/monitor.exp:gdb_target_command.
329proc mi_gdb_target_cmd { targetname serialport } {
330    global mi_gdb_prompt
331
332    set serialport_re [string_to_regexp $serialport]
333    for {set i 1} {$i <= 3} {incr i} {
334	send_gdb "47-target-select $targetname $serialport\n"
335	gdb_expect 60 {
336	    -re "47\\^connected.*$mi_gdb_prompt" {
337		verbose "Set target to $targetname";
338		return 0;
339	    }
340	    -re "unknown host.*$mi_gdb_prompt" {
341	        verbose "Couldn't look up $serialport"
342	    }
343	    -re "Couldn't establish connection to remote.*$mi_gdb_prompt$" {
344		verbose "Connection failed";
345	    }
346	    -re "Remote MIPS debugging.*$mi_gdb_prompt$" {
347		verbose "Set target to $targetname";
348		return 0;
349	    }
350	    -re "Remote debugging using .*$serialport_re.*$mi_gdb_prompt$" {
351		verbose "Set target to $targetname";
352		return 0;
353	    }
354	    -re "Remote target $targetname connected to.*$mi_gdb_prompt$" {
355		verbose "Set target to $targetname";
356		return 0;
357	    }
358	    -re "Connected to.*$mi_gdb_prompt$" {
359		verbose "Set target to $targetname";
360		return 0;
361	    }
362	    -re "Ending remote.*$mi_gdb_prompt$" { }
363	    -re "Connection refused.*$mi_gdb_prompt$" {
364		verbose "Connection refused by remote target.  Pausing, and trying again."
365		sleep 5
366		continue
367	    }
368	    -re "Non-stop mode requested, but remote does not support non-stop.*$mi_gdb_prompt" {
369		unsupported "Non-stop mode not supported"
370		return 1
371	    }
372	    -re "Timeout reading from remote system.*$mi_gdb_prompt$" {
373		verbose "Got timeout error from gdb.";
374	    }
375	    timeout {
376		send_gdb "";
377		break
378	    }
379	}
380    }
381    return 1
382}
383
384#
385# load a file into the debugger (file command only).
386# return a -1 if anything goes wrong.
387#
388proc mi_gdb_file_cmd { arg } {
389    global verbose
390    global loadpath
391    global loadfile
392    global GDB
393    global mi_gdb_prompt
394    global last_loaded_file
395    upvar timeout timeout
396
397    set last_loaded_file $arg
398
399    if [is_remote host] {
400	set arg [remote_download host $arg];
401	if { $arg == "" } {
402	    error "download failed"
403	    return -1;
404	}
405    }
406
407# FIXME: Several of these patterns are only acceptable for console
408# output.  Queries are an error for mi.
409    send_gdb "105-file-exec-and-symbols $arg\n"
410    gdb_expect 120 {
411        -re "Reading symbols from.*done.*$mi_gdb_prompt$" {
412            verbose "\t\tLoaded $arg into the $GDB"
413            return 0
414        }
415        -re "has no symbol-table.*$mi_gdb_prompt$" {
416            perror "$arg wasn't compiled with \"-g\""
417            return -1
418        }
419        -re "Load new symbol table from \".*\".*y or n. $" {
420            send_gdb "y\n"
421            gdb_expect 120 {
422                -re "Reading symbols from.*done.*$mi_gdb_prompt$" {
423                    verbose "\t\tLoaded $arg with new symbol table into $GDB"
424                    # All OK
425                }
426                timeout {
427                    perror "(timeout) Couldn't load $arg, other program already loaded."
428                    return -1
429                }
430            }
431	}
432        -re "No such file or directory.*$mi_gdb_prompt$" {
433            perror "($arg) No such file or directory\n"
434            return -1
435        }
436        -re "105-file-exec-and-symbols .*\r\n105\\\^done\r\n$mi_gdb_prompt$" {
437            # We (MI) are just giving the prompt back for now, instead of giving
438	    # some acknowledgement.
439	    return 0
440	}
441        timeout {
442            perror "couldn't load $arg into $GDB (timed out)."
443            return -1
444        }
445	eof {
446            # This is an attempt to detect a core dump, but seems not to
447            # work.  Perhaps we need to match .* followed by eof, in which
448            # gdb_expect does not seem to have a way to do that.
449            perror "couldn't load $arg into $GDB (end of file)."
450            return -1
451        }
452    }
453}
454
455#
456# connect to the target and download a file, if necessary.
457# return a -1 if anything goes wrong.
458#
459proc mi_gdb_target_load { } {
460    global verbose
461    global loadpath
462    global loadfile
463    global GDB
464    global mi_gdb_prompt
465
466    if [target_info exists gdb_load_timeout] {
467	set loadtimeout [target_info gdb_load_timeout]
468    } else {
469	set loadtimeout 1600
470    }
471
472    if { [info procs gdbserver_gdb_load] != "" } {
473	mi_gdb_test "kill" ".*" ""
474	set res [gdbserver_gdb_load]
475	set protocol [lindex $res 0]
476	set gdbport [lindex $res 1]
477
478	if { [mi_gdb_target_cmd $protocol $gdbport] != 0 } {
479	    return -1
480	}
481    } elseif { [info procs send_target_sid] != "" } {
482	# For SID, things get complex
483	send_gdb "kill\n"
484	gdb_expect 10 {
485	    -re ".*$mi_gdb_prompt$"
486	}
487	send_target_sid
488	gdb_expect $loadtimeout {
489	    -re "\\^done.*$mi_gdb_prompt$" {
490	    }
491	    timeout {
492		perror "Unable to connect to SID target (timeout)"
493		return -1
494	    }
495	}
496	send_gdb "48-target-download\n"
497	gdb_expect $loadtimeout {
498	    -re "48\\^done.*$mi_gdb_prompt$" {
499	    }
500	    timeout {
501		perror "Unable to download to SID target (timeout)"
502		return -1
503	    }
504	}
505    } elseif { [target_info protocol] == "sim" } {
506	# For the simulator, just connect to it directly.
507	send_gdb "47-target-select sim\n"
508	gdb_expect $loadtimeout {
509	    -re "47\\^connected.*$mi_gdb_prompt$" {
510	    }
511	    timeout {
512		perror "Unable to select sim target (timeout)"
513		return -1
514	    }
515	}
516	send_gdb "48-target-download\n"
517	gdb_expect $loadtimeout {
518	    -re "48\\^done.*$mi_gdb_prompt$" {
519	    }
520	    timeout {
521		perror "Unable to download to sim target (timeout)"
522		return -1
523	    }
524	}
525    } elseif { [target_info gdb_protocol] == "remote" } {
526	# remote targets
527	if { [mi_gdb_target_cmd "remote" [target_info netport]] != 0 } {
528	    perror "Unable to connect to remote target"
529	    return -1
530	}
531	send_gdb "48-target-download\n"
532	gdb_expect $loadtimeout {
533	    -re "48\\^done.*$mi_gdb_prompt$" {
534	    }
535	    timeout {
536		perror "Unable to download to remote target (timeout)"
537		return -1
538	    }
539	}
540    }
541    return 0
542}
543
544#
545# load a file into the debugger.
546# return a -1 if anything goes wrong.
547#
548proc mi_gdb_load { arg } {
549    if { $arg != "" } {
550	return [mi_gdb_file_cmd $arg]
551    }
552    return 0
553}
554
555# mi_gdb_test COMMAND PATTERN MESSAGE [IPATTERN] -- send a command to gdb;
556#   test the result.
557#
558# COMMAND is the command to execute, send to GDB with send_gdb.  If
559#   this is the null string no command is sent.
560# PATTERN is the pattern to match for a PASS, and must NOT include
561#   the \r\n sequence immediately before the gdb prompt.
562# MESSAGE is the message to be printed.  (If this is the empty string,
563#   then sometimes we don't call pass or fail at all; I don't
564#   understand this at all.)
565# IPATTERN is the pattern to match for the inferior's output.  This parameter
566#   is optional.  If present, it will produce a PASS if the match is
567#   successful, and a FAIL if unsuccessful.
568#
569# Returns:
570#    1 if the test failed,
571#    0 if the test passes,
572#   -1 if there was an internal error.
573#
574proc mi_gdb_test { args } {
575    global verbose
576    global mi_gdb_prompt
577    global GDB expect_out
578    global inferior_exited_re
579    upvar timeout timeout
580
581    set command [lindex $args 0]
582    set pattern [lindex $args 1]
583    set message [lindex $args 2]
584
585    if [llength $args]==4 {
586	set ipattern [lindex $args 3]
587    }
588
589    if [llength $args]==5 {
590	set question_string [lindex $args 3];
591	set response_string [lindex $args 4];
592    } else {
593	set question_string "^FOOBAR$"
594    }
595
596    if $verbose>2 then {
597	send_user "Sending \"$command\" to gdb\n"
598	send_user "Looking to match \"$pattern\"\n"
599	send_user "Message is \"$message\"\n"
600    }
601
602    set result -1
603    set string "${command}\n";
604    set string_regex [string_to_regexp $command]
605
606    if { $command != "" } {
607	while { "$string" != "" } {
608	    set foo [string first "\n" "$string"];
609	    set len [string length "$string"];
610	    if { $foo < [expr $len - 1] } {
611		set str [string range "$string" 0 $foo];
612		if { [send_gdb "$str"] != "" } {
613		    global suppress_flag;
614
615		    if { ! $suppress_flag } {
616			perror "Couldn't send $command to GDB.";
617		    }
618		    fail "$message";
619		    return $result;
620		}
621		gdb_expect 2 {
622		    -re "\[\r\n\]" { }
623		    timeout { }
624		}
625		set string [string range "$string" [expr $foo + 1] end];
626	    } else {
627		break;
628	    }
629	}
630	if { "$string" != "" } {
631	    if { [send_gdb "$string"] != "" } {
632		global suppress_flag;
633
634		if { ! $suppress_flag } {
635		    perror "Couldn't send $command to GDB.";
636		}
637		fail "$message";
638		return $result;
639	    }
640	}
641    }
642
643    if [info exists timeout] {
644	set tmt $timeout;
645    } else {
646	global timeout;
647	if [info exists timeout] {
648	    set tmt $timeout;
649	} else {
650	    set tmt 60;
651	}
652    }
653    verbose -log "Expecting: ^($string_regex\[\r\n\]+)?($pattern\[\r\n\]+$mi_gdb_prompt\[ \]*)"
654    gdb_expect $tmt {
655	 -re "\\*\\*\\* DOSEXIT code.*" {
656	     if { $message != "" } {
657		 fail "$message";
658	     }
659	     gdb_suppress_entire_file "GDB died";
660	     return -1;
661	 }
662	 -re "Ending remote debugging.*$mi_gdb_prompt\[ \]*$" {
663	    if ![isnative] then {
664		warning "Can`t communicate to remote target."
665	    }
666	    gdb_exit
667	    gdb_start
668	    set result -1
669	}
670	 -re "^($string_regex\[\r\n\]+)?($pattern\[\r\n\]+$mi_gdb_prompt\[ \]*)" {
671	    # At this point, $expect_out(1,string) is the MI input command.
672	    # and $expect_out(2,string) is the MI output command.
673	    # If $expect_out(1,string) is "", then there was no MI input command here.
674
675	    # NOTE, there is no trailing anchor because with GDB/MI,
676	    # asynchronous responses can happen at any point, causing more
677	    # data to be available.  Normally an anchor is used to make
678	    # sure the end of the output is matched, however, $mi_gdb_prompt
679	    # is just as good of an anchor since mi_gdb_test is meant to
680	    # match a single mi output command.  If a second GDB/MI output
681	    # response is sent, it will be in the buffer for the next
682	    # time mi_gdb_test is called.
683	    if ![string match "" $message] then {
684		pass "$message"
685	    }
686	    set result 0
687	}
688	 -re "(${question_string})$" {
689	    send_gdb "$response_string\n";
690	    exp_continue;
691	}
692	 -re "Undefined.* command:.*$mi_gdb_prompt\[ \]*$" {
693	    perror "Undefined command \"$command\"."
694            fail "$message"
695	    set result 1
696	}
697	 -re "Ambiguous command.*$mi_gdb_prompt\[ \]*$" {
698	    perror "\"$command\" is not a unique command name."
699            fail "$message"
700	    set result 1
701	}
702	 -re "$inferior_exited_re with code \[0-9\]+.*$mi_gdb_prompt\[ \]*$" {
703	    if ![string match "" $message] then {
704		set errmsg "$message (the program exited)"
705	    } else {
706		set errmsg "$command (the program exited)"
707	    }
708	    fail "$errmsg"
709	    return -1
710	}
711	 -re "The program is not being run.*$mi_gdb_prompt\[ \]*$" {
712	    if ![string match "" $message] then {
713		set errmsg "$message (the program is no longer running)"
714	    } else {
715		set errmsg "$command (the program is no longer running)"
716	    }
717	    fail "$errmsg"
718	    return -1
719	}
720	 -re ".*$mi_gdb_prompt\[ \]*$" {
721	    if ![string match "" $message] then {
722		fail "$message"
723	    }
724	    set result 1
725	}
726	 "<return>" {
727	    send_gdb "\n"
728	    perror "Window too small."
729            fail "$message"
730	}
731	 -re "\\(y or n\\) " {
732	    send_gdb "n\n"
733	    perror "Got interactive prompt."
734            fail "$message"
735	}
736	 eof {
737	     perror "Process no longer exists"
738	     if { $message != "" } {
739		 fail "$message"
740	     }
741	     return -1
742	}
743	 full_buffer {
744	    perror "internal buffer is full."
745            fail "$message"
746	}
747	timeout	{
748	    if ![string match "" $message] then {
749		fail "$message (timeout)"
750	    }
751	    set result 1
752	}
753    }
754
755    # If the GDB output matched, compare the inferior output.
756    if { $result == 0 } {
757	if [ info exists ipattern ] {
758	    if { ![target_info exists gdb,noinferiorio] } {
759		global mi_inferior_spawn_id
760		expect {
761		    -i $mi_inferior_spawn_id -re "$ipattern" {
762			pass "$message inferior output"
763		    }
764		    timeout {
765			fail "$message inferior output (timeout)"
766			set result 1
767		    }
768		}
769	    } else {
770		unsupported "$message inferior output"
771	    }
772        }
773    }
774
775    return $result
776}
777
778#
779# MI run command.  (A modified version of gdb_run_cmd)
780#
781
782# In patterns, the newline sequence ``\r\n'' is matched explicitly as
783# ``.*$'' could swallow up output that we attempt to match elsewhere.
784
785proc mi_run_cmd {args} {
786    global suppress_flag
787    if { $suppress_flag } {
788	return -1
789    }
790    global mi_gdb_prompt
791    global thread_selected_re
792    global library_loaded_re
793
794    if [target_info exists gdb_init_command] {
795	send_gdb "[target_info gdb_init_command]\n";
796	gdb_expect 30 {
797	    -re "$mi_gdb_prompt$" { }
798	    default {
799		perror "gdb_init_command for target failed";
800		return -1;
801	    }
802	}
803    }
804
805    if { [mi_gdb_target_load] < 0 } {
806	return -1
807    }
808
809    if [target_info exists use_gdb_stub] {
810	if [target_info exists gdb,do_reload_on_run] {
811	    send_gdb "220-exec-continue\n";
812	    gdb_expect 60 {
813		-re "220\\^running\[\r\n\]+\\*running,thread-id=\"\[^\"\]+\"\r\n$mi_gdb_prompt" {}
814		default {}
815	    }
816	    return 0;
817	}
818
819	if [target_info exists gdb,start_symbol] {
820	    set start [target_info gdb,start_symbol];
821	} else {
822	    set start "start";
823	}
824
825	# HACK: Should either use 000-jump or fix the target code
826	# to better handle RUN.
827	send_gdb  "jump *$start\n"
828	warning "Using CLI jump command, expect run-to-main FAIL"
829	return 0
830    }
831
832    send_gdb "220-exec-run $args\n"
833    gdb_expect {
834	-re "220\\^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}" {
835	}
836	-re "\\^error,msg=\"The target does not support running in non-stop mode.\"" {
837	    unsupported "Non-stop mode not supported"
838	    return -1
839	}
840	timeout {
841	    perror "Unable to start target"
842	    return -1
843	}
844    }
845    # NOTE: Shortly after this there will be a ``000*stopped,...(gdb)''
846
847    return 0
848}
849
850#
851# Just like run-to-main but works with the MI interface
852#
853
854proc mi_run_to_main { } {
855    global suppress_flag
856    if { $suppress_flag } {
857	return -1
858    }
859
860    global srcdir
861    global subdir
862    global binfile
863    global srcfile
864
865    mi_delete_breakpoints
866    mi_gdb_reinitialize_dir $srcdir/$subdir
867    mi_gdb_load ${binfile}
868
869    mi_runto main
870}
871
872
873# Just like gdb's "runto" proc, it will run the target to a given
874# function.  The big difference here between mi_runto and mi_execute_to
875# is that mi_execute_to must have the inferior running already.  This
876# proc will (like gdb's runto) (re)start the inferior, too.
877#
878# FUNC is the linespec of the place to stop (it inserts a breakpoint here).
879# It returns:
880#   -1  if test suppressed, failed, timedout
881#    0  if test passed
882
883proc mi_runto_helper {func run_or_continue} {
884  global suppress_flag
885  if { $suppress_flag } {
886    return -1
887  }
888
889  global mi_gdb_prompt expect_out
890  global hex decimal fullname_syntax
891
892  set test "mi runto $func"
893  mi_gdb_test "200-break-insert -t $func" \
894    "200\\^done,bkpt=\{number=\"\[0-9\]+\",type=\"breakpoint\",disp=\"del\",enabled=\"y\",addr=\"$hex\",func=\"$func\(\\\(.*\\\)\)?\",file=\".*\",line=\"\[0-9\]*\",times=\"0\",original-location=\".*\"\}" \
895    "breakpoint at $func"
896
897  if {![regexp {number="[0-9]+"} $expect_out(buffer) str]
898      || ![scan $str {number="%d"} bkptno]} {
899    set bkptno {[0-9]+}
900  }
901
902  if {$run_or_continue == "run"} {
903      if { [mi_run_cmd] < 0 } {
904	  return -1
905      }
906  } else {
907      mi_send_resuming_command "exec-continue" "$test"
908  }
909
910  mi_expect_stop "breakpoint-hit" $func ".*" ".*" "\[0-9\]+" { "" "disp=\"del\"" } $test
911}
912
913proc mi_runto {func} {
914    return [mi_runto_helper $func "run"]
915}
916
917# Next to the next statement
918# For return values, see mi_execute_to_helper
919
920proc mi_next { test } {
921  return [mi_next_to {.*} {.*} {.*} {.*} $test]
922}
923
924
925# Step to the next statement
926# For return values, see mi_execute_to_helper
927
928proc mi_step { test } {
929  return [mi_step_to {.*} {.*} {.*} {.*} $test]
930}
931
932set async "unknown"
933
934proc detect_async {} {
935    global async
936    global mi_gdb_prompt
937
938    send_gdb "show target-async\n"
939
940    gdb_expect {
941        -re ".*Controlling the inferior in asynchronous mode is on...*$mi_gdb_prompt$" {
942            set async 1
943        }
944        -re ".*$mi_gdb_prompt$" {
945            set async 0
946        }
947        timeout {
948            set async 0
949        }
950    }
951    return $async
952}
953
954# Wait for MI *stopped notification to appear.
955# The REASON, FUNC, ARGS, FILE and LINE are regular expressions
956# to match against whatever is output in *stopped.  ARGS should
957# not include [] the list of argument is enclosed in, and other
958# regular expressions should not include quotes.
959# If EXTRA is a list of one element, it's the regular expression
960# for output expected right after *stopped, and before GDB prompt.
961# If EXTRA is a list of two elements, the first element is for
962# output right after *stopped, and the second element is output
963# right after reason field.  The regex after reason should not include
964# the comma separating it from the following fields.
965#
966# When we fail to match output at all, -1 is returned.  Otherwise,
967# the line at which we stop is returned.  This is useful when exact
968# line is not possible to specify for some reason -- one can pass
969# the .* or "\[0-9\]*" regexps for line, and then check the line
970# programmatically.
971#
972# Do not pass .* for any argument if you are expecting more than one stop.
973proc mi_expect_stop { reason func args file line extra test } {
974
975    global mi_gdb_prompt
976    global hex
977    global decimal
978    global fullname_syntax
979    global async
980    global thread_selected_re
981
982    set after_stopped ""
983    set after_reason ""
984    if { [llength $extra] == 2 } {
985        set after_stopped [lindex $extra 0]
986        set after_reason [lindex $extra 1]
987        set after_reason "${after_reason},"
988    } elseif { [llength $extra] == 1 } {
989        set after_stopped [lindex $extra 0]
990    }
991
992    if {$async} {
993        set prompt_re ""
994    } else {
995        set prompt_re "$mi_gdb_prompt$"
996    }
997
998    if { $reason == "really-no-reason" } {
999        gdb_expect {
1000          -re "\\*stopped\r\n$prompt_re" {
1001            pass "$test"
1002          }
1003          timeout {
1004              fail "$test (unknown output after running)"
1005          }
1006        }
1007        return
1008    }
1009
1010    if { $reason == "exited-normally" } {
1011
1012        gdb_expect {
1013          -re "\\*stopped,reason=\"exited-normally\"\r\n$prompt_re" {
1014            pass "$test"
1015          }
1016          -re ".*$mi_gdb_prompt$" {fail "continue to end (2)"}
1017          timeout {
1018              fail "$test (unknown output after running)"
1019          }
1020        }
1021        return
1022    }
1023
1024    set args "\\\[$args\\\]"
1025
1026    set bn ""
1027    if { $reason == "breakpoint-hit" } {
1028        set bn {bkptno="[0-9]+",}
1029    }
1030
1031    set r ""
1032    if { $reason != "" } {
1033        set r "reason=\"$reason\","
1034    }
1035
1036
1037    set a $after_reason
1038
1039    set any "\[^\n\]*"
1040
1041    verbose -log "mi_expect_stop: expecting: \\*stopped,${r}${a}${bn}frame=\{addr=\"$hex\",func=\"$func\",args=$args,file=\"$any$file\",fullname=\"${fullname_syntax}$file\",line=\"$line\"\}$after_stopped,thread-id=\"$decimal\",stopped-threads=$any\r\n($thread_selected_re)?$prompt_re"
1042    gdb_expect {
1043	-re "\\*stopped,${r}${a}${bn}frame=\{addr=\"$hex\",func=\"$func\",args=$args,file=\"$any$file\",fullname=\"${fullname_syntax}$file\",line=\"($line)\"\}$after_stopped,thread-id=\"$decimal\",stopped-threads=$any\r\n($thread_selected_re)?$prompt_re" {
1044	    pass "$test"
1045            return $expect_out(2,string)
1046	}
1047	-re "\\*stopped,${r}${a}${bn}frame=\{addr=\"$hex\",func=\"$any\",args=\[\\\[\{\]$any\[\\\]\}\],file=\"$any\",fullname=\"${fullname_syntax}$any\",line=\"\[0-9\]*\"\}$after_stopped,thread-id=\"$decimal\",stopped-threads=$any\r\n$prompt_re" {
1048            verbose -log "got $expect_out(buffer)"
1049	    fail "$test (stopped at wrong place)"
1050	    return -1
1051	}
1052	-re ".*\r\n$mi_gdb_prompt$" {
1053            verbose -log "got $expect_out(buffer)"
1054	    fail "$test (unknown output after running)"
1055	    return -1
1056	}
1057	timeout {
1058	    fail "$test (timeout)"
1059	    return -1
1060	}
1061    }
1062}
1063
1064# Wait for MI *stopped notification related to an interrupt request to
1065# appear.
1066proc mi_expect_interrupt { test } {
1067    global mi_gdb_prompt
1068    global decimal
1069    global async
1070
1071    if {$async} {
1072	set prompt_re ""
1073    } else {
1074	set prompt_re "$mi_gdb_prompt$"
1075    }
1076
1077    set r "reason=\"signal-received\",signal-name=\"0\",signal-meaning=\"Signal 0\""
1078
1079    set any "\[^\n\]*"
1080
1081    # A signal can land anywhere, just ignore the location
1082    verbose -log "mi_expect_interrupt: expecting: \\*stopped,${r}$any\r\n$prompt_re"
1083    gdb_expect {
1084	-re "\\*stopped,${r}$any\r\n$prompt_re" {
1085	    pass "$test"
1086	    return 0;
1087	}
1088	-re ".*\r\n$mi_gdb_prompt$" {
1089	    verbose -log "got $expect_out(buffer)"
1090	    fail "$test (unknown output after running)"
1091	    return -1
1092	}
1093	timeout {
1094	    fail "$test (timeout)"
1095	    return -1
1096	}
1097    }
1098}
1099
1100# cmd should not include the number or newline (i.e. "exec-step 3", not
1101# "220-exec-step 3\n"
1102
1103# Can not match -re ".*\r\n${mi_gdb_prompt}", because of false positives
1104# after the first prompt is printed.
1105
1106proc mi_execute_to { cmd reason func args file line extra test } {
1107    global suppress_flag
1108    if { $suppress_flag } {
1109	return -1
1110    }
1111
1112    mi_send_resuming_command "$cmd" "$test"
1113    set r [mi_expect_stop $reason $func $args $file $line $extra $test]
1114    return $r
1115}
1116
1117proc mi_next_to { func args file line test } {
1118    mi_execute_to "exec-next" "end-stepping-range" "$func" "$args" \
1119	"$file" "$line" "" "$test"
1120}
1121
1122proc mi_step_to { func args file line test } {
1123    mi_execute_to "exec-step" "end-stepping-range" "$func" "$args" \
1124	"$file" "$line" "" "$test"
1125}
1126
1127proc mi_finish_to { func args file line result ret test } {
1128    mi_execute_to "exec-finish" "function-finished" "$func" "$args" \
1129	"$file" "$line" \
1130	",gdb-result-var=\"$result\",return-value=\"$ret\"" \
1131	"$test"
1132}
1133
1134proc mi_continue_to {func} {
1135    mi_runto_helper $func "continue"
1136}
1137
1138proc mi0_execute_to { cmd reason func args file line extra test } {
1139    mi_execute_to_helper "$cmd" "$reason" "$func" "\{$args\}" \
1140	"$file" "$line" "$extra" "$test"
1141}
1142
1143proc mi0_next_to { func args file line test } {
1144    mi0_execute_to "exec-next" "end-stepping-range" "$func" "$args" \
1145	"$file" "$line" "" "$test"
1146}
1147
1148proc mi0_step_to { func args file line test } {
1149    mi0_execute_to "exec-step" "end-stepping-range" "$func" "$args" \
1150	"$file" "$line" "" "$test"
1151}
1152
1153proc mi0_finish_to { func args file line result ret test } {
1154    mi0_execute_to "exec-finish" "function-finished" "$func" "$args" \
1155	"$file" "$line" \
1156	",gdb-result-var=\"$result\",return-value=\"$ret\"" \
1157	"$test"
1158}
1159
1160proc mi0_continue_to { bkptno func args file line test } {
1161    mi0_execute_to "exec-continue" "breakpoint-hit\",bkptno=\"$bkptno" \
1162	"$func" "$args" "$file" "$line" "" "$test"
1163}
1164
1165# Creates a breakpoint and checks the reported fields are as expected
1166proc mi_create_breakpoint { location number disp func file line address test } {
1167    verbose -log "Expecting: 222\\^done,bkpt=\{number=\"$number\",type=\"breakpoint\",disp=\"$disp\",enabled=\"y\",addr=\"$address\",func=\"$func\",file=\"$file\",fullname=\".*\",line=\"$line\",times=\"0\",original-location=\".*\"\}"
1168    mi_gdb_test "222-break-insert $location" \
1169        "222\\^done,bkpt=\{number=\"$number\",type=\"breakpoint\",disp=\"$disp\",enabled=\"y\",addr=\"$address\",func=\"$func\",file=\"$file\",fullname=\".*\",line=\"$line\",times=\"0\",original-location=\".*\"\}" \
1170        $test
1171}
1172
1173proc mi_list_breakpoints { expected test } {
1174    set fullname ".*"
1175
1176    set body ""
1177    set first 1
1178
1179    foreach item $expected {
1180        if {$first == 0} {
1181            set body "$body,"
1182            set first 0
1183        }
1184        set number [lindex $item 0]
1185        set disp [lindex $item 1]
1186        set func [lindex $item 2]
1187        set file [lindex $item 3]
1188        set line [lindex $item 4]
1189        set address [lindex $item 5]
1190        set body "${body}bkpt=\{number=\"$number\",type=\"breakpoint\",disp=\"$disp\",enabled=\"y\",addr=\"$address\",func=\"$func\",file=\".*$file\",${fullname},line=\"$line\",times=\"0\",original-location=\".*\"\}"
1191        set first 0
1192    }
1193
1194    verbose -log "Expecting: 666\\\^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=\\\[$body\\\]\}"
1195    mi_gdb_test "666-break-list" \
1196        "666\\\^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=\\\[$body\\\]\}" \
1197        $test
1198}
1199
1200# Creates varobj named NAME for EXPRESSION.
1201# Name cannot be "-".
1202proc mi_create_varobj { name expression testname } {
1203    mi_gdb_test "-var-create $name * $expression" \
1204        "\\^done,name=\"$name\",numchild=\"\[0-9\]+\",value=\".*\",type=.*,has_more=\"0\"" \
1205        $testname
1206}
1207
1208proc mi_create_floating_varobj { name expression testname } {
1209    mi_gdb_test "-var-create $name @ $expression" \
1210        "\\^done,name=\"$name\",numchild=\"\(-1\|\[0-9\]+\)\",value=\".*\",type=.*" \
1211        $testname
1212}
1213
1214
1215# Same as mi_create_varobj, but also checks the reported type
1216# of the varobj.
1217proc mi_create_varobj_checked { name expression type testname } {
1218    mi_gdb_test "-var-create $name * $expression" \
1219        "\\^done,name=\"$name\",numchild=\"\[0-9\]+\",value=\".*\",type=\"$type\".*" \
1220        $testname
1221}
1222
1223# Same as mi_create_floating_varobj, but assumes the test is creating
1224# a dynamic varobj that has children, so the value must be "{...}".
1225proc mi_create_dynamic_varobj {name expression testname} {
1226    mi_gdb_test "-var-create $name @ $expression" \
1227        "\\^done,name=\"$name\",numchild=\"\(-1\|\[0-9\]+\)\",value=\"{\\.\\.\\.}\",type=.*" \
1228        $testname
1229}
1230
1231# Deletes the specified NAME.
1232proc mi_delete_varobj { name testname } {
1233    mi_gdb_test "-var-delete $name" \
1234        "\\^done,ndeleted=.*" \
1235        $testname
1236}
1237
1238# Updates varobj named NAME and checks that all varobjs in EXPECTED
1239# are reported as updated, and no other varobj is updated.
1240# Assumes that no varobj is out of scope and that no varobj changes
1241# types.
1242proc mi_varobj_update { name expected testname } {
1243    set er "\\^done,changelist=\\\["
1244    set first 1
1245    foreach item $expected {
1246        set v "{name=\"$item\",in_scope=\"true\",type_changed=\"false\",has_more=\".\"}"
1247        if {$first == 1} {
1248            set er "$er$v"
1249            set first 0
1250        } else {
1251            set er "$er,$v"
1252        }
1253    }
1254    set er "$er\\\]"
1255
1256    verbose -log "Expecting: $er" 2
1257    mi_gdb_test "-var-update $name" $er $testname
1258}
1259
1260proc mi_varobj_update_with_type_change { name new_type new_children testname } {
1261    set v "{name=\"$name\",in_scope=\"true\",type_changed=\"true\",new_type=\"$new_type\",new_num_children=\"$new_children\",has_more=\".\"}"
1262    set er "\\^done,changelist=\\\[$v\\\]"
1263    verbose -log "Expecting: $er"
1264    mi_gdb_test "-var-update $name" $er $testname
1265}
1266
1267# A helper that turns a key/value list into a regular expression
1268# matching some MI output.
1269proc mi_varobj_update_kv_helper {list} {
1270    set first 1
1271    set rx ""
1272    foreach {key value} $list {
1273	if {!$first} {
1274	    append rx ,
1275	}
1276	set first 0
1277	if {$key == "new_children"} {
1278	    append rx "$key=\\\[$value\\\]"
1279	} else {
1280	    append rx "$key=\"$value\""
1281	}
1282    }
1283    return $rx
1284}
1285
1286# A helper for mi_varobj_update_dynamic that computes a match
1287# expression given a child list.
1288proc mi_varobj_update_dynamic_helper {children} {
1289    set crx ""
1290
1291    set first 1
1292    foreach child $children {
1293	if {!$first} {
1294	    append crx ,
1295	}
1296	set first 0
1297	append crx "{"
1298	append crx [mi_varobj_update_kv_helper $child]
1299	append crx "}"
1300    }
1301
1302    return $crx
1303}
1304
1305# Update a dynamic varobj named NAME.  CHILDREN is a list of children
1306# that have been updated; NEW_CHILDREN is a list of children that were
1307# added to the primary varobj.  Each child is a list of key/value
1308# pairs that are expected.  SELF is a key/value list holding
1309# information about the varobj itself.  TESTNAME is the name of the
1310# test.
1311proc mi_varobj_update_dynamic {name testname self children new_children} {
1312    if {[llength $new_children]} {
1313	set newrx [mi_varobj_update_dynamic_helper $new_children]
1314	lappend self new_children $newrx
1315    }
1316    set selfrx [mi_varobj_update_kv_helper $self]
1317    set crx [mi_varobj_update_dynamic_helper $children]
1318
1319    set er "\\^done,changelist=\\\[\{name=\"$name\",in_scope=\"true\""
1320    append er ",$selfrx\}"
1321    if {"$crx" != ""} {
1322	append er ",$crx"
1323    }
1324    append er "\\\]"
1325
1326    verbose -log "Expecting: $er"
1327    mi_gdb_test "-var-update $name" $er $testname
1328}
1329
1330proc mi_check_varobj_value { name value testname } {
1331
1332    mi_gdb_test "-var-evaluate-expression $name" \
1333	"\\^done,value=\"$value\"" \
1334	$testname
1335}
1336
1337# Helper proc which constructs a child regexp for
1338# mi_list_varobj_children and mi_varobj_update_dynamic.
1339proc mi_child_regexp {children add_child} {
1340    set children_exp {}
1341    set whatever "\"\[^\"\]+\""
1342
1343    if {$add_child} {
1344	set pre "child="
1345    } else {
1346	set pre ""
1347    }
1348
1349    foreach item $children {
1350
1351        set name [lindex $item 0]
1352        set exp [lindex $item  1]
1353        set numchild [lindex $item 2]
1354        if {[llength $item] == 5} {
1355            set type [lindex $item 3]
1356            set value [lindex $item 4]
1357
1358            lappend children_exp\
1359                "$pre{name=\"$name\",exp=\"$exp\",numchild=\"$numchild\",value=\"$value\",type=\"$type\"\(,thread-id=\"\[0-9\]+\")?}"
1360        } elseif {[llength $item] == 4} {
1361            set type [lindex $item 3]
1362
1363            lappend children_exp\
1364                "$pre{name=\"$name\",exp=\"$exp\",numchild=\"$numchild\",type=\"$type\"\(,thread-id=\"\[0-9\]+\")?}"
1365        } else {
1366            lappend children_exp\
1367                "$pre{name=\"$name\",exp=\"$exp\",numchild=\"$numchild\"(,thread-id=\"\[0-9\]+\")?}"
1368        }
1369    }
1370    return [join $children_exp ","]
1371}
1372
1373# Check the results of the:
1374#
1375#   -var-list-children VARNAME
1376#
1377# command.  The CHILDREN parement should be a list of lists.
1378# Each inner list can have either 3 or 4 elements, describing
1379# fields that gdb is expected to report for child variable object,
1380# in the following order
1381#
1382#   - Name
1383#   - Expression
1384#   - Number of children
1385#   - Type
1386#
1387# If inner list has 3 elements, the gdb is expected to output no
1388# type for a child and no value.
1389#
1390# If the inner list has 4 elements, gdb output is expected to
1391# have no value.
1392#
1393proc mi_list_varobj_children { varname children testname } {
1394    mi_list_varobj_children_range $varname "" "" [llength $children] $children \
1395      $testname
1396}
1397
1398# Like mi_list_varobj_children, but sets a subrange.  NUMCHILDREN is
1399# the total number of children.
1400proc mi_list_varobj_children_range {varname from to numchildren children testname} {
1401    set options ""
1402    if {[llength $varname] == 2} {
1403        set options [lindex $varname 1]
1404        set varname [lindex $varname 0]
1405    }
1406
1407    set whatever "\"\[^\"\]+\""
1408
1409    set children_exp_j [mi_child_regexp $children 1]
1410    if {$numchildren} {
1411        set expected "\\^done,numchild=\".*\",children=\\\[$children_exp_j.*\\\]"
1412    } {
1413        set expected "\\^done,numchild=\"0\""
1414    }
1415
1416    if {"$to" == ""} {
1417        append expected ",has_more=\"0\""
1418    } elseif {$to >= 0 && $numchildren > $to} {
1419        append expected ",has_more=\"1\""
1420    } else {
1421        append expected ",has_more=\"0\""
1422    }
1423
1424    verbose -log "Expecting: $expected"
1425
1426    mi_gdb_test "-var-list-children $options $varname $from $to" \
1427      $expected $testname
1428}
1429
1430# Verifies that variable object VARNAME has NUMBER children,
1431# where each one is named $VARNAME.<index-of-child> and has type TYPE.
1432proc mi_list_array_varobj_children { varname number type testname } {
1433    set t {}
1434    for {set i 0} {$i < $number} {incr i} {
1435        lappend t [list $varname.$i $i 0 $type]
1436    }
1437    mi_list_varobj_children $varname $t $testname
1438}
1439
1440# A list of two-element lists.  First element of each list is
1441# a Tcl statement, and the second element is the line
1442# number of source C file where the statement originates.
1443set mi_autotest_data ""
1444# The name of the source file for autotesting.
1445set mi_autotest_source ""
1446
1447proc count_newlines { string } {
1448    return [regexp -all "\n" $string]
1449}
1450
1451# Prepares for running inline tests in FILENAME.
1452# See comments for mi_run_inline_test for detailed
1453# explanation of the idea and syntax.
1454proc mi_prepare_inline_tests { filename } {
1455
1456    global srcdir
1457    global subdir
1458    global mi_autotest_source
1459    global mi_autotest_data
1460
1461    set mi_autotest_data {}
1462
1463    set mi_autotest_source $filename
1464
1465    if { ! [regexp "^/" "$filename"] } then {
1466	set filename "$srcdir/$subdir/$filename"
1467    }
1468
1469    set chan [open $filename]
1470    set content [read $chan]
1471    set line_number 1
1472    while {1} {
1473        set start [string first "/*:" $content]
1474        if {$start != -1} {
1475            set end [string first ":*/" $content]
1476            if {$end == -1} {
1477                error "Unterminated special comment in $filename"
1478            }
1479
1480            set prefix [string range $content 0 $start]
1481            set prefix_newlines [count_newlines $prefix]
1482
1483            set line_number [expr $line_number+$prefix_newlines]
1484            set comment_line $line_number
1485
1486            set comment [string range $content [expr $start+3] [expr $end-1]]
1487
1488            set comment_newlines [count_newlines $comment]
1489            set line_number [expr $line_number+$comment_newlines]
1490
1491            set comment [string trim $comment]
1492            set content [string range $content [expr $end+3] \
1493                             [string length $content]]
1494            lappend mi_autotest_data [list $comment $comment_line]
1495        } else {
1496           break
1497        }
1498    }
1499    close $chan
1500}
1501
1502# Helper to mi_run_inline_test below.
1503# Return the list of all (statement,line_number) lists
1504# that comprise TESTCASE.  The begin and end markers
1505# are not included.
1506proc mi_get_inline_test {testcase} {
1507
1508    global mi_gdb_prompt
1509    global mi_autotest_data
1510    global mi_autotest_source
1511
1512    set result {}
1513
1514    set seen_begin 0
1515    set seen_end 0
1516    foreach l $mi_autotest_data {
1517
1518        set comment [lindex $l 0]
1519
1520        if {$comment == "BEGIN: $testcase"} {
1521            set seen_begin 1
1522        } elseif {$comment == "END: $testcase"} {
1523            set seen_end 1
1524            break
1525        } elseif {$seen_begin==1} {
1526            lappend result $l
1527        }
1528    }
1529
1530    if {$seen_begin == 0} {
1531        error "Autotest $testcase not found"
1532    }
1533
1534    if {$seen_begin == 1 && $seen_end == 0} {
1535        error "Missing end marker for test $testcase"
1536    }
1537
1538    return $result
1539}
1540
1541# Sets temporary breakpoint at LOCATION.
1542proc mi_tbreak {location} {
1543
1544    global mi_gdb_prompt
1545
1546    mi_gdb_test "-break-insert -t $location" \
1547        {\^done,bkpt=.*} \
1548        "run to $location (set breakpoint)"
1549}
1550
1551# Send COMMAND that must be a command that resumes
1552# the inferiour (run/continue/next/etc) and consumes
1553# the "^running" output from it.
1554proc mi_send_resuming_command_raw {command test} {
1555
1556    global mi_gdb_prompt
1557    global thread_selected_re
1558    global library_loaded_re
1559
1560    send_gdb "$command\n"
1561    gdb_expect {
1562        -re "\\^running\r\n\\*running,thread-id=\"\[^\"\]+\"\r\n($library_loaded_re)*($thread_selected_re)?${mi_gdb_prompt}" {
1563            # Note that lack of 'pass' call here -- this works around limitation
1564            # in DejaGNU xfail mechanism. mi-until.exp has this:
1565            #
1566            #     setup_kfail gdb/2104 "*-*-*"
1567            #     mi_execute_to ...
1568            #
1569            # and mi_execute_to uses mi_send_resuming_command.  If we use 'pass' here,
1570            # it will reset kfail, so when the actual test fails, it will be flagged
1571            # as real failure.
1572	    return 0
1573        }
1574        -re "\\^error,msg=\"Displaced stepping is only supported in ARM mode\".*" {
1575            unsupported "$test (Thumb mode)"
1576            return -1
1577        }
1578        -re "\\^error,msg=.*" {
1579            fail "$test (MI error)"
1580            return -1
1581        }
1582        -re ".*${mi_gdb_prompt}" {
1583            fail "$test (failed to resume)"
1584	    return -1
1585        }
1586        timeout {
1587	    fail "$test"
1588	    return -1
1589        }
1590    }
1591}
1592
1593proc mi_send_resuming_command {command test} {
1594    mi_send_resuming_command_raw -$command $test
1595}
1596
1597# Helper to mi_run_inline_test below.
1598# Sets a temporary breakpoint at LOCATION and runs
1599# the program using COMMAND.  When the program is stopped
1600# returns the line at which it.  Returns -1 if line cannot
1601# be determined.
1602# Does not check that the line is the same as requested.
1603# The caller can check itself if required.
1604proc mi_continue_to_line {location test} {
1605
1606    mi_tbreak $location
1607    mi_send_resuming_command "exec-continue" "run to $location (exec-continue)"
1608    return [mi_get_stop_line $test]
1609}
1610
1611# Wait until gdb prints the current line.
1612proc mi_get_stop_line {test} {
1613
1614  global mi_gdb_prompt
1615  global async
1616
1617  if {$async} {
1618      set prompt_re ""
1619  } else {
1620      set prompt_re "$mi_gdb_prompt$"
1621  }
1622
1623  gdb_expect {
1624      -re ".*line=\"(\[0-9\]*)\".*\r\n$prompt_re" {
1625          return $expect_out(1,string)
1626      }
1627      -re ".*$mi_gdb_prompt" {
1628          fail "wait for stop ($test)"
1629      }
1630      timeout {
1631          fail "wait for stop ($test)"
1632      }
1633  }
1634}
1635
1636# Run a MI test embedded in comments in a C file.
1637# The C file should contain special comments in the following
1638# three forms:
1639#
1640#    /*: BEGIN: testname :*/
1641#    /*:  <Tcl statements> :*/
1642#    /*: END: testname :*/
1643#
1644# This procedure find the begin and end marker for the requested
1645# test. Then, a temporary breakpoint is set at the begin
1646# marker and the program is run (from start).
1647#
1648# After that, for each special comment between the begin and end
1649# marker, the Tcl statements are executed.  It is assumed that
1650# for each comment, the immediately preceding line is executable
1651# C statement.  Then, gdb will be single-stepped until that
1652# preceding C statement is executed, and after that the
1653# Tcl statements in the comment will be executed.
1654#
1655# For example:
1656#
1657#     /*: BEGIN: assignment-test :*/
1658#     v = 10;
1659#     /*: <Tcl code to check that 'v' is indeed 10 :*/
1660#     /*: END: assignment-test :*/
1661#
1662# The mi_prepare_inline_tests function should be called before
1663# calling this function.  A given C file can contain several
1664# inline tests.  The names of the tests must be unique within one
1665# C file.
1666#
1667proc mi_run_inline_test { testcase } {
1668
1669    global mi_gdb_prompt
1670    global hex
1671    global decimal
1672    global fullname_syntax
1673    global mi_autotest_source
1674
1675    set commands [mi_get_inline_test $testcase]
1676
1677    set first 1
1678    set line_now 1
1679
1680    foreach c $commands {
1681        set statements [lindex $c 0]
1682        set line [lindex $c 1]
1683        set line [expr $line-1]
1684
1685        # We want gdb to be stopped at the expression immediately
1686        # before the comment.  If this is the first comment, the
1687        # program is either not started yet or is in some random place,
1688        # so we run it.  For further comments, we might be already
1689        # standing at the right line. If not continue till the
1690        # right line.
1691
1692        if {$first==1} {
1693            # Start the program afresh.
1694            mi_tbreak "$mi_autotest_source:$line"
1695            mi_run_cmd
1696            set line_now [mi_get_stop_line "$testcase: step to $line"]
1697            set first 0
1698        } elseif {$line_now!=$line} {
1699            set line_now [mi_continue_to_line "$mi_autotest_source:$line" "continue to $line"]
1700        }
1701
1702        if {$line_now!=$line} {
1703            fail "$testcase: go to line $line"
1704        }
1705
1706        # We're not at the statement right above the comment.
1707        # Execute that statement so that the comment can test
1708        # the state after the statement is executed.
1709
1710        # Single-step past the line.
1711        if { [mi_send_resuming_command "exec-next" "$testcase: step over $line"] != 0 } {
1712	    return -1
1713	}
1714	set line_now [mi_get_stop_line "$testcase: step over $line"]
1715
1716        # We probably want to use 'uplevel' so that statements
1717        # have direct access to global variables that the
1718        # main 'exp' file has set up.  But it's not yet clear,
1719        # will need more experience to be sure.
1720        eval $statements
1721    }
1722}
1723
1724proc get_mi_thread_list {name} {
1725  global expect_out
1726
1727  # MI will return a list of thread ids:
1728  #
1729  # -thread-list-ids
1730  # ^done,thread-ids=[thread-id="1",thread-id="2",...],number-of-threads="N"
1731  # (gdb)
1732  mi_gdb_test "-thread-list-ids" \
1733    {.*\^done,thread-ids={(thread-id="[0-9]+"(,)?)+},current-thread-id="[0-9]+",number-of-threads="[0-9]+"} \
1734    "-thread_list_ids ($name)"
1735
1736  set output {}
1737  if {[info exists expect_out(buffer)]} {
1738    set output $expect_out(buffer)
1739  }
1740
1741  set thread_list {}
1742  if {![regexp {thread-ids=\{(thread-id="[0-9]+"(,)?)*\}} $output threads]} {
1743    fail "finding threads in MI output ($name)"
1744  } else {
1745    pass "finding threads in MI output ($name)"
1746
1747    # Make list of console threads
1748    set start [expr {[string first \{ $threads] + 1}]
1749    set end   [expr {[string first \} $threads] - 1}]
1750    set threads [string range $threads $start $end]
1751    foreach thread [split $threads ,] {
1752      if {[scan $thread {thread-id="%d"} num]} {
1753	lappend thread_list $num
1754      }
1755    }
1756  }
1757
1758  return $thread_list
1759}
1760
1761# Check that MI and the console know of the same threads.
1762# Appends NAME to all test names.
1763proc check_mi_and_console_threads {name} {
1764  global expect_out
1765
1766  mi_gdb_test "-thread-list-ids" \
1767    {.*\^done,thread-ids={(thread-id="[0-9]+"(,)*)+},current-thread-id="[0-9]+",number-of-threads="[0-9]+"} \
1768    "-thread-list-ids ($name)"
1769  set mi_output {}
1770  if {[info exists expect_out(buffer)]} {
1771    set mi_output $expect_out(buffer)
1772  }
1773
1774  # GDB will return a list of thread ids and some more info:
1775  #
1776  # (gdb)
1777  # -interpreter-exec console "info threads"
1778  # ~"  4 Thread 2051 (LWP 7734)  0x401166b1 in __libc_nanosleep () at __libc_nanosleep:-1"
1779  # ~"  3 Thread 1026 (LWP 7733)   () at __libc_nanosleep:-1"
1780  # ~"  2 Thread 2049 (LWP 7732)  0x401411f8 in __poll (fds=0x804bb24, nfds=1, timeout=2000) at ../sysdeps/unix/sysv/linux/poll.c:63"
1781  # ~"* 1 Thread 1024 (LWP 7731)  main (argc=1, argv=0xbfffdd94) at ../../../src/gdb/testsuite/gdb.mi/pthreads.c:160"
1782  # FIXME: kseitz/2002-09-05: Don't use the hack-cli method.
1783  mi_gdb_test "info threads" \
1784    {.*(~".*"[\r\n]*)+.*} \
1785    "info threads ($name)"
1786  set console_output {}
1787  if {[info exists expect_out(buffer)]} {
1788    set console_output $expect_out(buffer)
1789  }
1790
1791  # Make a list of all known threads to console (gdb's thread IDs)
1792  set console_thread_list {}
1793  foreach line [split $console_output \n] {
1794    if {[string index $line 0] == "~"} {
1795      # This is a line from the console; trim off "~", " ", "*", and "\""
1796      set line [string trim $line ~\ \"\*]
1797      if {[scan $line "%d" id] == 1} {
1798	lappend console_thread_list $id
1799      }
1800    }
1801  }
1802
1803  # Now find the result string from MI
1804  set mi_result ""
1805  foreach line [split $mi_output \n] {
1806    if {[string range $line 0 4] == "^done"} {
1807      set mi_result $line
1808    }
1809  }
1810  if {$mi_result == ""} {
1811    fail "finding MI result string ($name)"
1812  } else {
1813    pass "finding MI result string ($name)"
1814  }
1815
1816  # Finally, extract the thread ids and compare them to the console
1817  set num_mi_threads_str ""
1818  if {![regexp {number-of-threads="[0-9]+"} $mi_result num_mi_threads_str]} {
1819    fail "finding number of threads in MI output ($name)"
1820  } else {
1821    pass "finding number of threads in MI output ($name)"
1822
1823    # Extract the number of threads from the MI result
1824    if {![scan $num_mi_threads_str {number-of-threads="%d"} num_mi_threads]} {
1825      fail "got number of threads from MI ($name)"
1826    } else {
1827      pass "got number of threads from MI ($name)"
1828
1829      # Check if MI and console have same number of threads
1830      if {$num_mi_threads != [llength $console_thread_list]} {
1831	fail "console and MI have same number of threads ($name)"
1832      } else {
1833	pass "console and MI have same number of threads ($name)"
1834
1835	# Get MI thread list
1836	set mi_thread_list [get_mi_thread_list $name]
1837
1838	# Check if MI and console have the same threads
1839	set fails 0
1840	foreach ct [lsort $console_thread_list] mt [lsort $mi_thread_list] {
1841	  if {$ct != $mt} {
1842	    incr fails
1843	  }
1844	}
1845	if {$fails > 0} {
1846	  fail "MI and console have same threads ($name)"
1847
1848	  # Send a list of failures to the log
1849	  send_log "Console has thread ids: $console_thread_list\n"
1850	  send_log "MI has thread ids: $mi_thread_list\n"
1851	} else {
1852	  pass "MI and console have same threads ($name)"
1853	}
1854      }
1855    }
1856  }
1857}
1858
1859# Download shared libraries to the target.
1860proc mi_load_shlibs { args } {
1861    if {![is_remote target]} {
1862	return
1863    }
1864
1865    foreach file $args {
1866	gdb_download [shlib_target_file $file]
1867    }
1868
1869    # Even if the target supplies full paths for shared libraries,
1870    # they may not be paths for this system.
1871    mi_gdb_test "set solib-search-path [file dirname [lindex $args 0]]" "\^done" ""
1872}
1873
1874proc mi_reverse_list { list } {
1875    if { [llength $list] <= 1 } {
1876	return $list
1877    }
1878    set tail [lrange $list 1 [llength $list]]
1879    set rtail [mi_reverse_list $tail]
1880    lappend rtail [lindex $list 0]
1881    return $rtail
1882}
1883
1884proc mi_check_thread_states { xstates test } {
1885    global expect_out
1886    set states [mi_reverse_list $xstates]
1887    set pattern ".*\\^done,threads=\\\["
1888    foreach s $states {
1889	set pattern "${pattern}(.*)state=\"$s\""
1890    }
1891    set pattern "${pattern}(,core=\"\[0-9\]*\")?\\\}\\\].*"
1892
1893    verbose -log "expecting: $pattern"
1894    mi_gdb_test "-thread-info" $pattern $test
1895}
1896
1897# Return a list of MI features supported by this gdb.
1898proc mi_get_features {} {
1899    global expect_out mi_gdb_prompt
1900
1901    send_gdb "-list-features\n"
1902
1903    gdb_expect {
1904	-re "\\^done,features=\\\[(.*)\\\]\r\n$mi_gdb_prompt$" {
1905	    regsub -all -- \" $expect_out(1,string) "" features
1906	    return [split $features ,]
1907	}
1908	-re ".*\r\n$mi_gdb_prompt$" {
1909	    verbose -log "got $expect_out(buffer)"
1910	    return ""
1911	}
1912	timeout {
1913	    verbose -log "timeout in mi_gdb_prompt"
1914	    return ""
1915	}
1916    }
1917}
1918