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