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