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