aboutsummaryrefslogtreecommitdiff
path: root/gdb/testsuite/lib/mi-support.exp
blob: dd6c41ace1b48bd9081039e316ba133a037c8af4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
# Copyright 1999-2015 Free Software Foundation, Inc.

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# This file was based on a file written by Fred Fish. (fnf@cygnus.com)

# Test setup routines that work with the MI interpreter.

load_lib gdb-utils.exp

# The variable mi_gdb_prompt is a regexp which matches the gdb mi prompt.
# Set it if it is not already set.
global mi_gdb_prompt
if ![info exists mi_gdb_prompt] then {
    set mi_gdb_prompt "\[(\]gdb\[)\] \r\n"
}

global mi_inferior_tty_name

set MIFLAGS "-i=mi"

set thread_selected_re "=thread-selected,id=\"\[0-9\]+\"\r\n"
set gdbindex_warning_re "&\"warning: Skipping \[^\r\n\]+ \.gdb_index section in \[^\r\n\]+\"\r\n(?:&\"\\\\n\"\r\n)?"
set library_loaded_re "=library-loaded\[^\n\]+\"\r\n(?:$gdbindex_warning_re)?"
set breakpoint_re "=(?:breakpoint-created|breakpoint-deleted)\[^\n\]+\"\r\n"

#
# mi_gdb_exit -- exit the GDB, killing the target program if necessary
#
proc mi_gdb_exit {} {
    catch mi_uncatched_gdb_exit
}

proc mi_uncatched_gdb_exit {} {
    global GDB
    global INTERNAL_GDBFLAGS GDBFLAGS
    global verbose
    global gdb_spawn_id
    global gdb_prompt
    global mi_gdb_prompt
    global MIFLAGS

    gdb_stop_suppressing_tests

    if { [info procs sid_exit] != "" } {
	sid_exit
    }

    if ![info exists gdb_spawn_id] {
	return
    }

    verbose "Quitting $GDB $INTERNAL_GDBFLAGS $GDBFLAGS $MIFLAGS"

    if { [is_remote host] && [board_info host exists fileid] } {
	send_gdb "999-gdb-exit\n"
	gdb_expect 10 {
	    -re "y or n" {
		send_gdb "y\n"
		exp_continue
	    }
	    -re "Undefined command.*$gdb_prompt $" {
		send_gdb "quit\n"
		exp_continue
	    }
	    -re "DOSEXIT code" { }
	    default { }
	}
    }

    if ![is_remote host] {
	remote_close host
    }
    unset gdb_spawn_id
}

#
# default_mi_gdb_start [INFERIOR_PTY] -- start gdb running, default procedure
#
# INFERIOR_PTY should be set to separate-inferior-tty to have the inferior work 
# with it's own PTY. If set to same-inferior-tty, the inferior shares GDB's PTY. 
# The default value is same-inferior-tty.
#
# When running over NFS, particularly if running many simultaneous
# tests on different hosts all using the same server, things can
# get really slow.  Give gdb at least 3 minutes to start up.
#
proc default_mi_gdb_start { args } {
    global verbose use_gdb_stub
    global GDB
    global INTERNAL_GDBFLAGS GDBFLAGS
    global gdb_prompt
    global mi_gdb_prompt
    global timeout
    global gdb_spawn_id inferior_spawn_id
    global MIFLAGS

    gdb_stop_suppressing_tests
    set inferior_pty no-tty

    # Set the default value, it may be overriden later by specific testfile.
    set use_gdb_stub [target_info exists use_gdb_stub]

    if { [llength $args] == 1} {
	set inferior_pty [lindex $args 0]
    }

    set separate_inferior_pty [string match $inferior_pty separate-inferior-tty]

    # Start SID.
    if { [info procs sid_start] != "" } {
	verbose "Spawning SID"
	sid_start
    }

    verbose "Spawning $GDB $INTERNAL_GDBFLAGS $GDBFLAGS $MIFLAGS"

    if [info exists gdb_spawn_id] {
	return 0
    }

    if ![is_remote host] {
	if { [which $GDB] == 0 } then {
	    perror "$GDB does not exist."
	    exit 1
	}
    }

    set res [remote_spawn host "$GDB $INTERNAL_GDBFLAGS $GDBFLAGS $MIFLAGS [host_info gdb_opts]"]
    if { $res < 0 || $res == "" } {
	perror "Spawning $GDB failed."
	return 1
    }
    gdb_expect {
	-re "~\"GNU.*\r\n~\".*$mi_gdb_prompt$" {
	    # We have a new format mi startup prompt.  If we are
	    # running mi1, then this is an error as we should be
	    # using the old-style prompt.
	    if { $MIFLAGS == "-i=mi1" } {
		perror "(mi startup) Got unexpected new mi prompt."
		remote_close host
		return -1
	    }
	    verbose "GDB initialized."
	}
	-re "\[^~\].*$mi_gdb_prompt$" {
	    # We have an old format mi startup prompt.  If we are
	    # not running mi1, then this is an error as we should be
	    # using the new-style prompt.
	    if { $MIFLAGS != "-i=mi1" } {
		perror "(mi startup) Got unexpected old mi prompt."
		remote_close host
		return -1
	    }
	    verbose "GDB initialized."
	}
	-re ".*unrecognized option.*for a complete list of options." {
	    untested "Skip mi tests (not compiled with mi support)."
	    remote_close host
	    return -1
	}
	-re ".*Interpreter `mi' unrecognized." {
	    untested "Skip mi tests (not compiled with mi support)."
	    remote_close host
	    return -1
	}
	timeout {
	    perror "(timeout) GDB never initialized after 10 seconds."
	    remote_close host
	    return -1
	}
    }
    set gdb_spawn_id $res

    # FIXME: mi output does not go through pagers, so these can be removed.
    # force the height to "unlimited", so no pagers get used
    send_gdb "100-gdb-set height 0\n"
    gdb_expect 10 {
	-re ".*100-gdb-set height 0\r\n100\\\^done\r\n$mi_gdb_prompt$" {
	    verbose "Setting height to 0." 2
	}
	timeout {
	    warning "Couldn't set the height to 0"
	}
    }
    # force the width to "unlimited", so no wraparound occurs
    send_gdb "101-gdb-set width 0\n"
    gdb_expect 10 {
	-re ".*101-gdb-set width 0\r\n101\\\^done\r\n$mi_gdb_prompt$" {
	    verbose "Setting width to 0." 2
	}
	timeout {
	    warning "Couldn't set the width to 0."
	}
    }

    # Create the new PTY for the inferior process.
    if { $separate_inferior_pty } {
	spawn -pty
	global mi_inferior_tty_name
	set inferior_spawn_id $spawn_id
	set mi_inferior_tty_name $spawn_out(slave,name)

	send_gdb "102-inferior-tty-set $mi_inferior_tty_name\n"
	gdb_expect 10 {
	    -re ".*102\\\^done\r\n$mi_gdb_prompt$" {
		verbose "redirect inferior output to new terminal device."
	    }
	    timeout {
		warning "Couldn't redirect inferior output." 2
	    }
	}
    }

    if {![info exists inferior_spawn_id]} {
	set inferior_spawn_id $gdb_spawn_id
    }

    mi_detect_async

    return 0
}

#
# Overridable function. You can override this function in your
# baseboard file.
#
proc mi_gdb_start { args } {
  return [default_mi_gdb_start $args]
}

# Many of the tests depend on setting breakpoints at various places and
# running until that breakpoint is reached.  At times, we want to start
# with a clean-slate with respect to breakpoints, so this utility proc 
# lets us do this without duplicating this code everywhere.
#

proc mi_delete_breakpoints {} {
    global mi_gdb_prompt

# FIXME: The mi operation won't accept a prompt back and will use the 'all' arg
    send_gdb "102-break-delete\n"
    gdb_expect 30 {
	 -re "Delete all breakpoints.*y or n.*$" {
	    send_gdb "y\n"
	    exp_continue
	 }
	 -re "102-break-delete\r\n102\\\^done\r\n$mi_gdb_prompt$" {
	     # This happens if there were no breakpoints
	 }
	 timeout { perror "Delete all breakpoints in mi_delete_breakpoints (timeout)" ; return }
    }

# The correct output is not "No breakpoints or watchpoints." but an
# empty BreakpointTable. Also, a query is not acceptable with mi.
    send_gdb "103-break-list\n"
    gdb_expect 30 {
	 -re "103-break-list\r\n103\\\^done,BreakpointTable=\{\}\r\n$mi_gdb_prompt$" {}
	 -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$" {}
	 -re "103-break-list\r\n103\\\^doneNo breakpoints or watchpoints.\r\n\r\n$mi_gdb_prompt$" {warning "Unexpected console text received"}
	 -re "$mi_gdb_prompt$" { perror "Breakpoints not deleted" ; return }
	 -re "Delete all breakpoints.*or n.*$" {
	    warning "Unexpected prompt for breakpoints deletion"
	    send_gdb "y\n"
	    exp_continue
	}
	 timeout { perror "-break-list (timeout)" ; return }
    }
}

proc mi_gdb_reinitialize_dir { subdir } {
    global mi_gdb_prompt
    global MIFLAGS

    global suppress_flag
    if { $suppress_flag } {
	return
    }

    if [is_remote host] {
	return ""
    }

    if { $MIFLAGS == "-i=mi1" } {
      send_gdb "104-environment-directory\n"
      gdb_expect 60 {
	-re ".*Reinitialize source path to empty.*y or n. " {
	    warning "Got confirmation prompt for dir reinitialization."
	    send_gdb "y\n"
	    gdb_expect 60 {
		-re "$mi_gdb_prompt$" {}
		timeout {error "Dir reinitialization failed (timeout)"}
	    }
	}
	-re "$mi_gdb_prompt$" {}
	  timeout {error "Dir reinitialization failed (timeout)"}
      }
    } else {
	send_gdb "104-environment-directory -r\n"
	gdb_expect 60 {
	    -re "104\\\^done,source-path=.*\r\n$mi_gdb_prompt$" {}
	    -re "$mi_gdb_prompt$" {}
	    timeout {error "Dir reinitialization failed (timeout)"}
      }
    }

    send_gdb "105-environment-directory $subdir\n"
    gdb_expect 60 {
	-re "Source directories searched.*$mi_gdb_prompt$" {
	    verbose "Dir set to $subdir"
	}
	-re "105\\\^done.*\r\n$mi_gdb_prompt$" {
	    # FIXME: We return just the prompt for now.
	    verbose "Dir set to $subdir"
	    # perror "Dir \"$subdir\" failed."
	}
    }
}

# Send GDB the "target" command.
# FIXME: Some of these patterns are not appropriate for MI.  Based on
# config/monitor.exp:gdb_target_command.
proc mi_gdb_target_cmd { targetname serialport } {
    global mi_gdb_prompt

    set serialport_re [string_to_regexp $serialport]
    for {set i 1} {$i <= 3} {incr i} {
	send_gdb "47-target-select $targetname $serialport\n"
	gdb_expect 60 {
	    -re "47\\^connected.*$mi_gdb_prompt" {
		verbose "Set target to $targetname"
		return 0
	    }
	    -re "unknown host.*$mi_gdb_prompt" {
		verbose "Couldn't look up $serialport"
	    }
	    -re "Couldn't establish connection to remote.*$mi_gdb_prompt$" {
		verbose "Connection failed"
	    }
	    -re "Remote MIPS debugging.*$mi_gdb_prompt$" {
		verbose "Set target to $targetname"
		return 0
	    }
	    -re "Remote debugging using .*$serialport_re.*$mi_gdb_prompt$" {
		verbose "Set target to $targetname"
		return 0
	    }
	    -re "Remote target $targetname connected to.*$mi_gdb_prompt$" {
		verbose "Set target to $targetname"
		return 0
	    }
	    -re "Connected to.*$mi_gdb_prompt$" {
		verbose "Set target to $targetname"
		return 0
	    }
	    -re "Ending remote.*$mi_gdb_prompt$" { }
	    -re "Connection refused.*$mi_gdb_prompt$" {
		verbose "Connection refused by remote target.  Pausing, and trying again."
		sleep 5
		continue
	    }
	    -re "Non-stop mode requested, but remote does not support non-stop.*$mi_gdb_prompt" {
		unsupported "Non-stop mode not supported"
		return 1
	    }
	    -re "Timeout reading from remote system.*$mi_gdb_prompt$" {
		verbose "Got timeout error from gdb."
	    }
	    timeout {
		send_gdb ""
		break
	    }
	}
    }
    return 1
}

#
# load a file into the debugger (file command only).
# return a -1 if anything goes wrong.
#
proc mi_gdb_file_cmd { arg } {
    global verbose
    global loadpath
    global loadfile
    global GDB
    global mi_gdb_prompt
    global last_loaded_file
    upvar timeout timeout

    set last_loaded_file $arg

    if [is_remote host] {
	set arg [remote_download host $arg]
	if { $arg == "" } {
	    error "download failed"
	    return -1
	}
    }

# FIXME: Several of these patterns are only acceptable for console
# output.  Queries are an error for mi.
    send_gdb "105-file-exec-and-symbols $arg\n"
    gdb_expect 120 {
	-re "Reading symbols from.*done.*$mi_gdb_prompt$" {
	    verbose "\t\tLoaded $arg into the $GDB"
	    return 0
	}
	-re "has no symbol-table.*$mi_gdb_prompt$" {
	    perror "$arg wasn't compiled with \"-g\""
	    return -1
	}
	-re "Load new symbol table from \".*\".*y or n. $" {
	    send_gdb "y\n"
	    gdb_expect 120 {
		-re "Reading symbols from.*done.*$mi_gdb_prompt$" {
		    verbose "\t\tLoaded $arg with new symbol table into $GDB"
		    # All OK
		}
		timeout {
		    perror "(timeout) Couldn't load $arg, other program already loaded."
		    return -1
		}
	    }
	}
	-re "No such file or directory.*$mi_gdb_prompt$" {
	    perror "($arg) No such file or directory\n"
	    return -1
	}
	-re "105-file-exec-and-symbols .*\r\n105\\\^done\r\n$mi_gdb_prompt$" {
	    # We (MI) are just giving the prompt back for now, instead of giving
	    # some acknowledgement.
	    return 0
	}
	timeout {
	    perror "couldn't load $arg into $GDB (timed out)."
	    return -1
	}
	eof {
	    # This is an attempt to detect a core dump, but seems not to
	    # work.  Perhaps we need to match .* followed by eof, in which
	    # gdb_expect does not seem to have a way to do that.
	    perror "couldn't load $arg into $GDB (end of file)."
	    return -1
	}
    }
}

#
# connect to the target and download a file, if necessary.
# return a -1 if anything goes wrong.
#
proc mi_gdb_target_load { } {
    global verbose
    global loadpath
    global loadfile
    global GDB
    global mi_gdb_prompt

    if [target_info exists gdb_load_timeout] {
	set loadtimeout [target_info gdb_load_timeout]
    } else {
	set loadtimeout 1600
    }

    if { [info procs gdbserver_gdb_load] != "" } {
	mi_gdb_test "kill" ".*" ""
	if { [catch gdbserver_gdb_load res] == 1 } {
	    perror $res
	    return -1
	}
	set protocol [lindex $res 0]
	set gdbport [lindex $res 1]

	if { [mi_gdb_target_cmd $protocol $gdbport] != 0 } {
	    return -1
	}
    } elseif { [info procs send_target_sid] != "" } {
	# For SID, things get complex
	send_gdb "kill\n"
	gdb_expect 10 {
	    -re ".*$mi_gdb_prompt$"
	}
	send_target_sid
	gdb_expect $loadtimeout {
	    -re "\\^done.*$mi_gdb_prompt$" {
	    }
	    timeout {
		perror "Unable to connect to SID target (timeout)"
		return -1
	    }
	}
	send_gdb "48-target-download\n"
	gdb_expect $loadtimeout {
	    -re "48\\^done.*$mi_gdb_prompt$" {
	    }
	    timeout {
		perror "Unable to download to SID target (timeout)"
		return -1
	    }
	}
    } elseif { [target_info protocol] == "sim" } {
	# For the simulator, just connect to it directly.
	send_gdb "47-target-select sim\n"
	gdb_expect $loadtimeout {
	    -re "47\\^connected.*$mi_gdb_prompt$" {
	    }
	    timeout {
		perror "Unable to select sim target (timeout)"
		return -1
	    }
	}
	send_gdb "48-target-download\n"
	gdb_expect $loadtimeout {
	    -re "48\\^done.*$mi_gdb_prompt$" {
	    }
	    timeout {
		perror "Unable to download to sim target (timeout)"
		return -1
	    }
	}
    } elseif { [target_info gdb_protocol] == "remote" } {
	# remote targets
	if { [mi_gdb_target_cmd "remote" [target_info netport]] != 0 } {
	    perror "Unable to connect to remote target"
	    return -1
	}
	send_gdb "48-target-download\n"
	gdb_expect $loadtimeout {
	    -re "48\\^done.*$mi_gdb_prompt$" {
	    }
	    timeout {
		perror "Unable to download to remote target (timeout)"
		return -1
	    }
	}
    }
    return 0
}

#
# load a file into the debugger.
# return a -1 if anything goes wrong.
#
proc mi_gdb_load { arg } {
    if { $arg != "" } {
	return [mi_gdb_file_cmd $arg]
    }
    return 0
}

# mi_gdb_test COMMAND PATTERN MESSAGE [IPATTERN] -- send a command to gdb; 
#   test the result.
#
# COMMAND is the command to execute, send to GDB with send_gdb.  If
#   this is the null string no command is sent.
# PATTERN is the pattern to match for a PASS, and must NOT include
#   the \r\n sequence immediately before the gdb prompt.
# MESSAGE is the message to be printed.  (If this is the empty string,
#   then sometimes we don't call pass or fail at all; I don't
#   understand this at all.)
# IPATTERN is the pattern to match for the inferior's output.  This parameter
#   is optional.  If present, it will produce a PASS if the match is
#   successful, and a FAIL if unsuccessful.
#
# Returns:
#    1 if the test failed,
#    0 if the test passes,
#   -1 if there was an internal error.
#
proc mi_gdb_test { args } {
    global verbose
    global mi_gdb_prompt
    global GDB expect_out
    global inferior_exited_re async
    upvar timeout timeout

    set command [lindex $args 0]
    set pattern [lindex $args 1]
    set message [lindex $args 2]

    if [llength $args]==4 {
	set ipattern [lindex $args 3]
    }

    if [llength $args]==5 {
	set question_string [lindex $args 3]
	set response_string [lindex $args 4]
    } else {
	set question_string "^FOOBAR$"
    }

    if $verbose>2 then {
	send_user "Sending \"$command\" to gdb\n"
	send_user "Looking to match \"$pattern\"\n"
	send_user "Message is \"$message\"\n"
    }

    set result -1
    set string "${command}\n"
    set string_regex [string_to_regexp $command]

    if { $command != "" } {
	while { "$string" != "" } {
	    set foo [string first "\n" "$string"]
	    set len [string length "$string"]
	    if { $foo < [expr $len - 1] } {
		set str [string range "$string" 0 $foo]
		if { [send_gdb "$str"] != "" } {
		    global suppress_flag

		    if { ! $suppress_flag } {
			perror "Couldn't send $command to GDB."
		    }
		    fail "$message"
		    return $result
		}
		gdb_expect 2 {
		    -re "\[\r\n\]" { }
		    timeout { }
		}
		set string [string range "$string" [expr $foo + 1] end]
	    } else {
		break
	    }
	}
	if { "$string" != "" } {
	    if { [send_gdb "$string"] != "" } {
		global suppress_flag

		if { ! $suppress_flag } {
		    perror "Couldn't send $command to GDB."
		}
		fail "$message"
		return $result
	    }
	}
    }

    if [info exists timeout] {
	set tmt $timeout
    } else {
	global timeout
	if [info exists timeout] {
	    set tmt $timeout
	} else {
	    set tmt 60
	}
    }
    if {$async} {
	# With $prompt_re "" there may come arbitrary asynchronous response
	# from the previous command, before or after $string_regex.
	set string_regex ".*"
    }
    verbose -log "Expecting: ^($string_regex\[\r\n\]+)?($pattern\[\r\n\]+$mi_gdb_prompt\[ \]*)"
    gdb_expect $tmt {
	 -re "\\*\\*\\* DOSEXIT code.*" {
	     if { $message != "" } {
		 fail "$message"
	     }
	     gdb_suppress_entire_file "GDB died"
	     return -1
	 }
	 -re "Ending remote debugging.*$mi_gdb_prompt\[ \]*$" {
	    if ![isnative] then {
		warning "Can`t communicate to remote target."
	    }
	    gdb_exit
	    gdb_start
	    set result -1
	}
	 -re "^($string_regex\[\r\n\]+)?($pattern\[\r\n\]+$mi_gdb_prompt\[ \]*)" {
	    # At this point, $expect_out(1,string) is the MI input command.
	    # and $expect_out(2,string) is the MI output command.
	    # If $expect_out(1,string) is "", then there was no MI input command here.

	    # NOTE, there is no trailing anchor because with GDB/MI, 
	    # asynchronous responses can happen at any point, causing more 
	    # data to be available.  Normally an anchor is used to make 
	    # sure the end of the output is matched, however, $mi_gdb_prompt 
	    # is just as good of an anchor since mi_gdb_test is meant to 
	    # match a single mi output command.  If a second GDB/MI output 
	    # response is sent, it will be in the buffer for the next 
	    # time mi_gdb_test is called.
	    if ![string match "" $message] then {
		pass "$message"
	    }
	    set result 0
	}
	 -re "(${question_string})$" {
	    send_gdb "$response_string\n"
	    exp_continue
	}
	 -re "Undefined.* command:.*$mi_gdb_prompt\[ \]*$" {
	    perror "Undefined command \"$command\"."
	     fail "$message"
	    set result 1
	}
	 -re "Ambiguous command.*$mi_gdb_prompt\[ \]*$" {
	    perror "\"$command\" is not a unique command name."
	     fail "$message"
	    set result 1
	}
	 -re "$inferior_exited_re with code \[0-9\]+.*$mi_gdb_prompt\[ \]*$" {
	    if ![string match "" $message] then {
		set errmsg "$message (the program exited)"
	    } else {
		set errmsg "$command (the program exited)"
	    }
	    fail "$errmsg"
	    return -1
	}
	 -re "The program is not being run.*$mi_gdb_prompt\[ \]*$" {
	    if ![string match "" $message] then {
		set errmsg "$message (the program is no longer running)"
	    } else {
		set errmsg "$command (the program is no longer running)"
	    }
	    fail "$errmsg"
	    return -1
	}
	 -re ".*$mi_gdb_prompt\[ \]*$" {
	    if ![string match "" $message] then {
		fail "$message"
	    }
	    set result 1
	}
	 "<return>" {
	    send_gdb "\n"
	    perror "Window too small."
	     fail "$message"
	}
	 -re "\\(y or n\\) " {
	    send_gdb "n\n"
	    perror "Got interactive prompt."
	     fail "$message"
	}
	 eof {
	     perror "Process no longer exists"
	     if { $message != "" } {
		 fail "$message"
	     }
	     return -1
	}
	 full_buffer {
	    perror "internal buffer is full."
	     fail "$message"
	}
	timeout	{
	    if ![string match "" $message] then {
		fail "$message (timeout)"
	    }
	    set result 1
	}
    }

    # If the GDB output matched, compare the inferior output.
    if { $result == 0 } {
	if [ info exists ipattern ] {
	    if { ![target_info exists gdb,noinferiorio] } {
		global gdb_spawn_id inferior_spawn_id

		set sid "$inferior_spawn_id $gdb_spawn_id"
		gdb_expect {
		    -i "$sid" -re "$ipattern" {
			pass "$message inferior output"
		    }
		    timeout {
			fail "$message inferior output (timeout)"
			set result 1
		    }
		}
	    } else {
		unsupported "$message inferior output"
	    }
	}
    }

    return $result
}

# Collect output sent to the console output stream until UNTIL is
# seen.  UNTIL is a regular expression.  MESSAGE is the message to be
# printed in case of timeout.

proc mi_gdb_expect_cli_output {until message} {

    set output ""
    gdb_expect {
	-re "~\"(\[^\r\n\]+)\"\r\n" {
	    append output $expect_out(1,string)
	    exp_continue
	}
	-notransfer -re "$until" {
	    # Done
	}
	timeout {
	    fail "$message (timeout)"
	    return ""
	}
    }

    return $output
}

#
# MI run command.  (A modified version of gdb_run_cmd)
#

# In patterns, the newline sequence ``\r\n'' is matched explicitly as
# ``.*$'' could swallow up output that we attempt to match elsewhere.

# Send the command to run the test program.
#
# If USE_MI_COMMAND is true, the "-exec-run" command is used.
# Otherwise, the "run" (CLI) command is used.  If the global USE_GDB_STUB is
# true, -exec-continue and continue are used instead of their run counterparts.
#
# ARGS is passed as argument to the command used to run the test program.
# Beware that arguments to "-exec-run" do not have the same semantics as
# arguments to the "run" command, so USE_MI_COMMAND influences the meaning
# of ARGS.  If USE_MI_COMMAND is true, they are arguments to -exec-run.
# If USE_MI_COMMAND is false, they are effectively arguments passed
# to the test program.  If the global USE_GDB_STUB is true, ARGS is not used.
proc mi_run_cmd_full {use_mi_command args} {
    global suppress_flag
    if { $suppress_flag } {
	return -1
    }
    global mi_gdb_prompt use_gdb_stub
    global thread_selected_re
    global library_loaded_re

    if {$use_mi_command} {
	set run_prefix "220-exec-"
	set run_match "220"
    } else {
	set run_prefix ""
	set run_match ""
    }

    foreach command [gdb_init_commands] {
	send_gdb "$command\n"
	gdb_expect 30 {
	    -re "$mi_gdb_prompt$" { }
	    default {
		perror "gdb_init_command for target failed"
		return -1
	    }
	}
    }

    if { [mi_gdb_target_load] < 0 } {
	return -1
    }

    if $use_gdb_stub {
	if [target_info exists gdb,do_reload_on_run] {
	    send_gdb "${run_prefix}continue\n"
	    gdb_expect 60 {
		-re "${run_match}\\^running\[\r\n\]+\\*running,thread-id=\"\[^\"\]+\"\r\n$mi_gdb_prompt" {}
		-re "${run_match}\\^error.*$mi_gdb_prompt" {return -1}
		default {}
	    }
	    return 0
	}

	if [target_info exists gdb,start_symbol] {
	    set start [target_info gdb,start_symbol]
	} else {
	    set start "start"
	}

	# HACK: Should either use 000-jump or fix the target code
	# to better handle RUN.
	send_gdb  "jump *$start\n"
	warning "Using CLI jump command, expect run-to-main FAIL"
	return 0
    }

    send_gdb "${run_prefix}run $args\n"
    gdb_expect {
	-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}" {
	}
	-re "\\^error,msg=\"The target does not support running in non-stop mode.\"" {
	    unsupported "Non-stop mode not supported"
	    return -1
	}
	timeout {
	    perror "Unable to start target"
	    return -1
	}
    }
    # NOTE: Shortly after this there will be a ``000*stopped,...(gdb)''

    return 0
}

# A wrapper for mi_run_cmd_full which uses -exec-run and
# -exec-continue, as appropriate.  ARGS are passed verbatim to
# mi_run_cmd_full.
proc mi_run_cmd {args} {
    return [eval mi_run_cmd_full 1 $args]
}

# A wrapper for mi_run_cmd_full which uses the CLI commands 'run' and
# 'continue', as appropriate.  ARGS are passed verbatim to
# mi_run_cmd_full.
proc mi_run_with_cli {args} {
    return [eval mi_run_cmd_full 0 $args]
}

#
# Just like run-to-main but works with the MI interface
#

proc mi_run_to_main { } {
    global suppress_flag
    if { $suppress_flag } {
	return -1
    }

    global srcdir
    global subdir
    global binfile
    global srcfile

    mi_delete_breakpoints
    mi_gdb_reinitialize_dir $srcdir/$subdir
    mi_gdb_load ${binfile}

    mi_runto main
}


# Just like gdb's "runto" proc, it will run the target to a given
# function.  The big difference here between mi_runto and mi_execute_to
# is that mi_execute_to must have the inferior running already.  This
# proc will (like gdb's runto) (re)start the inferior, too.
#
# FUNC is the linespec of the place to stop (it inserts a breakpoint here).
# It returns:
#   -1  if test suppressed, failed, timedout
#    0  if test passed

proc mi_runto_helper {func run_or_continue} {
  global suppress_flag
  if { $suppress_flag } {
    return -1
  }

  global mi_gdb_prompt expect_out
  global hex decimal fullname_syntax

  set test "mi runto $func"
  set bp [mi_make_breakpoint -type breakpoint -disp del \
	      -func $func\(\\\(.*\\\)\)?]
  mi_gdb_test "200-break-insert -t $func" "200\\^done,$bp" \
      "breakpoint at $func"

  if {$run_or_continue == "run"} {
      if { [mi_run_cmd] < 0 } {
	  return -1
      }
  } else {
      mi_send_resuming_command "exec-continue" "$test"
  }

  mi_expect_stop "breakpoint-hit" $func ".*" ".*" "\[0-9\]+" { "" "disp=\"del\"" } $test
}

proc mi_runto {func} {
    return [mi_runto_helper $func "run"]
}

# Next to the next statement
# For return values, see mi_execute_to_helper

proc mi_next { test } {
  return [mi_next_to {.*} {.*} {.*} {.*} $test]
}


# Step to the next statement
# For return values, see mi_execute_to_helper

proc mi_step { test } {
  return [mi_step_to {.*} {.*} {.*} {.*} $test]
}

set async "unknown"

proc mi_detect_async {} {
    global async
    global mi_gdb_prompt

    send_gdb "show mi-async\n"

    gdb_expect {
	-re "asynchronous mode is on...*$mi_gdb_prompt$" {
	    set async 1
	}
	-re ".*$mi_gdb_prompt$" {
	    set async 0
	}
	timeout {
	    set async 0
	}
    }
    return $async
}

# Wait for MI *stopped notification to appear.
# The REASON, FUNC, ARGS, FILE and LINE are regular expressions
# to match against whatever is output in *stopped.  FILE may also match
# filename of a file without debug info.  ARGS should not include [] the
# list of argument is enclosed in, and other regular expressions should
# not include quotes.
# If EXTRA is a list of one element, it's the regular expression
# for output expected right after *stopped, and before GDB prompt.
# If EXTRA is a list of two elements, the first element is for
# output right after *stopped, and the second element is output
# right after reason field.  The regex after reason should not include
# the comma separating it from the following fields.
#
# When we fail to match output at all, -1 is returned.  If FILE does
# match and the target system has no debug info for FILE return 0.
# Otherwise, the line at which we stop is returned.  This is useful when
# exact line is not possible to specify for some reason -- one can pass
# the .* or "\[0-9\]*" regexps for line, and then check the line
# programmatically.
#
# Do not pass .* for any argument if you are expecting more than one stop.
proc mi_expect_stop { reason func args file line extra test } {

    global mi_gdb_prompt
    global hex
    global decimal
    global fullname_syntax
    global async
    global thread_selected_re
    global breakpoint_re

    set any "\[^\n\]*"

    set after_stopped ""
    set after_reason ""
    if { [llength $extra] == 2 } {
	set after_stopped [lindex $extra 0]
	set after_reason [lindex $extra 1]
	set after_reason "${after_reason},"
    } elseif { [llength $extra] == 1 } {
	set after_stopped [lindex $extra 0]
    }

    if {$async} {
	set prompt_re ""
    } else {
	set prompt_re "$mi_gdb_prompt$"
    }

    if { $reason == "really-no-reason" } {
	gdb_expect {
	    -re "\\*stopped\r\n$prompt_re" {
		pass "$test"
	    }
	    timeout {
		fail "$test (timeout)"
	    }
	}
	return
    }

    if { $reason == "exited-normally" } {

	gdb_expect {
	    -re "\\*stopped,reason=\"exited-normally\"\r\n$prompt_re" {
		pass "$test"
	    }
	    -re ".*$mi_gdb_prompt$" {fail "continue to end (2)"}
	    timeout {
		fail "$test (timeout)"
	    }
	}
	return
    }
    if { $reason == "exited" } {
	gdb_expect {
	    -re "\\*stopped,reason=\"exited\",exit-code=\"\[0-7\]+\"\r\n$prompt_re" {
		pass "$test"
	    }
	    -re ".*$mi_gdb_prompt$" {
		fail "$test (inferior not stopped)"
	    }
	    timeout {
		fail "$test (timeout)"
	    }
	}
	return
    }

    if { $reason == "solib-event" } {
	set pattern "\\*stopped,reason=\"solib-event\",thread-id=\"$decimal\",stopped-threads=$any\r\n($thread_selected_re|$breakpoint_re)*$prompt_re"
	verbose -log "mi_expect_stop: expecting: $pattern"
	gdb_expect {
	    -re "$pattern" {
		pass "$test"
	    }
	    timeout {
		fail "$test (timeout)"
	    }
	}
	return
    }

    set args "\\\[$args\\\]"

    set bn ""
    if { $reason == "breakpoint-hit" } {
	set bn {bkptno="[0-9]+",}
    } elseif { $reason == "solib-event" } {
	set bn ".*"
    }

    set r ""
    if { $reason != "" } {
	set r "reason=\"$reason\","
    }


    set a $after_reason

    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"
    gdb_expect {
	-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" {
	    pass "$test"
	    if {[array names expect_out "2,string"] != ""} {
		return $expect_out(2,string)
	    }
	    # No debug info available but $file does match.
	    return 0
	}
	-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" {
	    verbose -log "got $expect_out(buffer)"
	    fail "$test (stopped at wrong place)"
	    return -1
	}
	-re ".*\r\n$mi_gdb_prompt$" {
	    verbose -log "got $expect_out(buffer)"
	    fail "$test (unknown output after running)"
	    return -1
	}
	timeout {
	    fail "$test (timeout)"
	    return -1
	}
    }
}

# Wait for MI *stopped notification related to an interrupt request to
# appear.
proc mi_expect_interrupt { test } {
    global mi_gdb_prompt
    global decimal
    global async

    if {$async} {
	set prompt_re ""
    } else {
	set prompt_re "$mi_gdb_prompt$"
    }

    set r_nonstop "reason=\"signal-received\",signal-name=\"0\",signal-meaning=\"Signal 0\""
    set r_allstop "reason=\"signal-received\",signal-name=\"SIGINT\",signal-meaning=\"Interrupt\""
    set r "(${r_nonstop}|${r_allstop})"
    set any "\[^\n\]*"

    # A signal can land anywhere, just ignore the location
    verbose -log "mi_expect_interrupt: expecting: \\*stopped,${r}$any\r\n$prompt_re"
    gdb_expect {
	-re "\\*stopped,${r}$any\r\n$prompt_re" {
	    pass "$test"
	    return 0
	}
	-re ".*\r\n$mi_gdb_prompt$" {
	    verbose -log "got $expect_out(buffer)"
	    fail "$test (unknown output after running)"
	    return -1
	}
	timeout {
	    fail "$test (timeout)"
	    return -1
	}
    }
}

# cmd should not include the number or newline (i.e. "exec-step 3", not
# "220-exec-step 3\n"

# Can not match -re ".*\r\n${mi_gdb_prompt}", because of false positives
# after the first prompt is printed.

proc mi_execute_to { cmd reason func args file line extra test } {
    global suppress_flag
    if { $suppress_flag } {
	return -1
    }

    mi_send_resuming_command "$cmd" "$test"
    set r [mi_expect_stop $reason $func $args $file $line $extra $test]
    return $r
}

proc mi_next_to { func args file line test } {
    mi_execute_to "exec-next" "end-stepping-range" "$func" "$args" \
	"$file" "$line" "" "$test"
}

proc mi_step_to { func args file line test } {
    mi_execute_to "exec-step" "end-stepping-range" "$func" "$args" \
	"$file" "$line" "" "$test"
}

proc mi_finish_to { func args file line result ret test } {
    mi_execute_to "exec-finish" "function-finished" "$func" "$args" \
	"$file" "$line" \
	",gdb-result-var=\"$result\",return-value=\"$ret\"" \
	"$test"
}

proc mi_continue_to {func} {
    mi_runto_helper $func "continue"
}

proc mi0_execute_to { cmd reason func args file line extra test } {
    mi_execute_to_helper "$cmd" "$reason" "$func" "\{$args\}" \
	"$file" "$line" "$extra" "$test"
}

proc mi0_next_to { func args file line test } {
    mi0_execute_to "exec-next" "end-stepping-range" "$func" "$args" \
	"$file" "$line" "" "$test"
}

proc mi0_step_to { func args file line test } {
    mi0_execute_to "exec-step" "end-stepping-range" "$func" "$args" \
	"$file" "$line" "" "$test"
}

proc mi0_finish_to { func args file line result ret test } {
    mi0_execute_to "exec-finish" "function-finished" "$func" "$args" \
	"$file" "$line" \
	",gdb-result-var=\"$result\",return-value=\"$ret\"" \
	"$test"
}

proc mi0_continue_to { bkptno func args file line test } {
    mi0_execute_to "exec-continue" "breakpoint-hit\",bkptno=\"$bkptno" \
	"$func" "$args" "$file" "$line" "" "$test"
}

# Creates a breakpoint and checks the reported fields are as expected.
# This procedure takes the same options as mi_make_breakpoint and
# returns the breakpoint regexp from that procedure.

proc mi_create_breakpoint {location test args} {
    set bp [eval mi_make_breakpoint $args]
    mi_gdb_test "222-break-insert $location" "222\\^done,$bp" $test
    return $bp
}

# Creates varobj named NAME for EXPRESSION.
# Name cannot be "-".
proc mi_create_varobj { name expression testname } {
    mi_gdb_test "-var-create $name * $expression" \
	"\\^done,name=\"$name\",numchild=\"\[0-9\]+\",value=\".*\",type=.*,has_more=\"0\"" \
	$testname
}

proc mi_create_floating_varobj { name expression testname } {
    mi_gdb_test "-var-create $name @ $expression" \
	"\\^done,name=\"$name\",numchild=\"\(-1\|\[0-9\]+\)\",value=\".*\",type=.*" \
	$testname
}


# Same as mi_create_varobj, but also checks the reported type
# of the varobj.
proc mi_create_varobj_checked { name expression type testname } {
    mi_gdb_test "-var-create $name * $expression" \
	"\\^done,name=\"$name\",numchild=\"\[0-9\]+\",value=\".*\",type=\"$type\".*" \
	$testname
}

# Same as mi_create_floating_varobj, but assumes the test is creating
# a dynamic varobj that has children, so the value must be "{...}".
# The "has_more" attribute is checked.
proc mi_create_dynamic_varobj {name expression has_more testname} {
    mi_gdb_test "-var-create $name @ $expression" \
	"\\^done,name=\"$name\",numchild=\"0\",value=\"{\\.\\.\\.}\",type=.*,has_more=\"${has_more}\"" \
	$testname
}

# Deletes the specified NAME.
proc mi_delete_varobj { name testname } {
    mi_gdb_test "-var-delete $name" \
	"\\^done,ndeleted=.*" \
	$testname
}

# Updates varobj named NAME and checks that all varobjs in EXPECTED
# are reported as updated, and no other varobj is updated.
# Assumes that no varobj is out of scope and that no varobj changes
# types.
proc mi_varobj_update { name expected testname } {
    set er "\\^done,changelist=\\\["
    set first 1
    foreach item $expected {
	set v "{name=\"$item\",in_scope=\"true\",type_changed=\"false\",has_more=\".\"}"
	if {$first == 1} {
	    set er "$er$v"
	    set first 0
	} else {
	    set er "$er,$v"
	}
    }
    set er "$er\\\]"

    verbose -log "Expecting: $er" 2
    mi_gdb_test "-var-update $name" $er $testname
}

proc mi_varobj_update_with_child_type_change { name child_name new_type new_children testname } {
    set v "{name=\"$child_name\",in_scope=\"true\",type_changed=\"true\",new_type=\"$new_type\",new_num_children=\"$new_children\",has_more=\".\"}"
    set er "\\^done,changelist=\\\[$v\\\]"
    verbose -log "Expecting: $er"
    mi_gdb_test "-var-update $name" $er $testname
}

proc mi_varobj_update_with_type_change { name new_type new_children testname } {
    mi_varobj_update_with_child_type_change $name $name $new_type $new_children $testname
}

# A helper that turns a key/value list into a regular expression
# matching some MI output.
proc mi_varobj_update_kv_helper {list} {
    set first 1
    set rx ""
    foreach {key value} $list {
	if {!$first} {
	    append rx ,
	}
	set first 0
	if {$key == "new_children"} {
	    append rx "$key=\\\[$value\\\]"
	} else {
	    append rx "$key=\"$value\""
	}
    }
    return $rx
}

# A helper for mi_varobj_update_dynamic that computes a match
# expression given a child list.
proc mi_varobj_update_dynamic_helper {children} {
    set crx ""

    set first 1
    foreach child $children {
	if {!$first} {
	    append crx ,
	}
	set first 0
	append crx "{"
	append crx [mi_varobj_update_kv_helper $child]
	append crx "}"
    }

    return $crx
}

# Update a dynamic varobj named NAME.  CHILDREN is a list of children
# that have been updated; NEW_CHILDREN is a list of children that were
# added to the primary varobj.  Each child is a list of key/value
# pairs that are expected.  SELF is a key/value list holding
# information about the varobj itself.  TESTNAME is the name of the
# test.
proc mi_varobj_update_dynamic {name testname self children new_children} {
    if {[llength $new_children]} {
	set newrx [mi_varobj_update_dynamic_helper $new_children]
	lappend self new_children $newrx
    }
    set selfrx [mi_varobj_update_kv_helper $self]
    set crx [mi_varobj_update_dynamic_helper $children]

    set er "\\^done,changelist=\\\[\{name=\"$name\",in_scope=\"true\""
    append er ",$selfrx\}"
    if {"$crx" != ""} {
	append er ",$crx"
    }
    append er "\\\]"

    verbose -log "Expecting: $er"
    mi_gdb_test "-var-update $name" $er $testname
}

proc mi_check_varobj_value { name value testname } {

    mi_gdb_test "-var-evaluate-expression $name" \
	"\\^done,value=\"$value\"" \
	$testname
}

# Helper proc which constructs a child regexp for
# mi_list_varobj_children and mi_varobj_update_dynamic.
proc mi_child_regexp {children add_child} {
    set children_exp {}

    if {$add_child} {
	set pre "child="
    } else {
	set pre ""
    }

    foreach item $children {

	set name [lindex $item 0]
	set exp [lindex $item  1]
	set numchild [lindex $item 2]
	if {[llength $item] == 5} {
	    set type [lindex $item 3]
	    set value [lindex $item 4]

	    lappend children_exp\
		"$pre{name=\"$name\",exp=\"$exp\",numchild=\"$numchild\",value=\"$value\",type=\"$type\"(,thread-id=\"\[0-9\]+\")?}"
	} elseif {[llength $item] == 4} {
	    set type [lindex $item 3]

	    lappend children_exp\
		"$pre{name=\"$name\",exp=\"$exp\",numchild=\"$numchild\",type=\"$type\"(,thread-id=\"\[0-9\]+\")?}"
	} else {
	    lappend children_exp\
		"$pre{name=\"$name\",exp=\"$exp\",numchild=\"$numchild\"(,thread-id=\"\[0-9\]+\")?}"
	}
    }
    return [join $children_exp ","]
}

# Check the results of the:
#
#   -var-list-children VARNAME
#
# command.  The CHILDREN parement should be a list of lists.
# Each inner list can have either 3 or 4 elements, describing
# fields that gdb is expected to report for child variable object,
# in the following order
#
#   - Name
#   - Expression
#   - Number of children
#   - Type
#
# If inner list has 3 elements, the gdb is expected to output no
# type for a child and no value.
#
# If the inner list has 4 elements, gdb output is expected to
# have no value.
#
proc mi_list_varobj_children { varname children testname } {
    mi_list_varobj_children_range $varname "" "" [llength $children] $children \
      $testname
}

# Like mi_list_varobj_children, but sets a subrange.  NUMCHILDREN is
# the total number of children.
proc mi_list_varobj_children_range {varname from to numchildren children testname} {
    set options ""
    if {[llength $varname] == 2} {
	set options [lindex $varname 1]
	set varname [lindex $varname 0]
    }

    set children_exp_j [mi_child_regexp $children 1]
    if {$numchildren} {
	set expected "\\^done,numchild=\".*\",children=\\\[$children_exp_j.*\\\]"
    } {
	set expected "\\^done,numchild=\"0\""
    }

    if {"$to" == ""} {
	append expected ",has_more=\"0\""
    } elseif {$to >= 0 && $numchildren > $to} {
	append expected ",has_more=\"1\""
    } else {
	append expected ",has_more=\"0\""
    }

    verbose -log "Expecting: $expected"

    mi_gdb_test "-var-list-children $options $varname $from $to" \
      $expected $testname
}

# Verifies that variable object VARNAME has NUMBER children,
# where each one is named $VARNAME.<index-of-child> and has type TYPE.
proc mi_list_array_varobj_children { varname number type testname } {
    mi_list_array_varobj_children_with_index $varname $number 0 $type $testname
}

# Same as mi_list_array_varobj_children, but allowing to pass a start index
# for an array.
proc mi_list_array_varobj_children_with_index { varname number start_index \
  type testname } {
    set t {}
    set index $start_index
    for {set i 0} {$i < $number} {incr i} {
	lappend t [list $varname.$index $index 0 $type]
	incr index
    }
    mi_list_varobj_children $varname $t $testname
}

# A list of two-element lists.  First element of each list is
# a Tcl statement, and the second element is the line
# number of source C file where the statement originates.
set mi_autotest_data ""
# The name of the source file for autotesting.
set mi_autotest_source ""

proc count_newlines { string } {
    return [regexp -all "\n" $string]
}

# Prepares for running inline tests in FILENAME.
# See comments for mi_run_inline_test for detailed
# explanation of the idea and syntax.
proc mi_prepare_inline_tests { filename } {

    global srcdir
    global subdir
    global mi_autotest_source
    global mi_autotest_data

    set mi_autotest_data {}

    set mi_autotest_source $filename

    if { ! [regexp "^/" "$filename"] } then {
	set filename "$srcdir/$subdir/$filename"
    }

    set chan [open $filename]
    set content [read $chan]
    set line_number 1
    while {1} {
	set start [string first "/*:" $content]
	if {$start != -1} {
	    set end [string first ":*/" $content]
	    if {$end == -1} {
		error "Unterminated special comment in $filename"
	    }

	    set prefix [string range $content 0 $start]
	    set prefix_newlines [count_newlines $prefix]

	    set line_number [expr $line_number+$prefix_newlines]
	    set comment_line $line_number

	    set comment [string range $content [expr $start+3] [expr $end-1]]

	    set comment_newlines [count_newlines $comment]
	    set line_number [expr $line_number+$comment_newlines]

	    set comment [string trim $comment]
	    set content [string range $content [expr $end+3] \
			     [string length $content]]
	    lappend mi_autotest_data [list $comment $comment_line]
	} else {
	    break
	}
    }
    close $chan
}

# Helper to mi_run_inline_test below.
# Return the list of all (statement,line_number) lists
# that comprise TESTCASE.  The begin and end markers
# are not included.
proc mi_get_inline_test {testcase} {

    global mi_gdb_prompt
    global mi_autotest_data
    global mi_autotest_source

    set result {}

    set seen_begin 0
    set seen_end 0
    foreach l $mi_autotest_data {

	set comment [lindex $l 0]

	if {$comment == "BEGIN: $testcase"} {
	    set seen_begin 1
	} elseif {$comment == "END: $testcase"} {
	    set seen_end 1
	    break
	} elseif {$seen_begin==1} {
	    lappend result $l
	}
    }

    if {$seen_begin == 0} {
	error "Autotest $testcase not found"
    }

    if {$seen_begin == 1 && $seen_end == 0} {
	error "Missing end marker for test $testcase"
    }

    return $result
}

# Sets temporary breakpoint at LOCATION.
proc mi_tbreak {location} {

    global mi_gdb_prompt

    mi_gdb_test "-break-insert -t $location" \
	{\^done,bkpt=.*} \
	"run to $location (set breakpoint)"
}

# Send COMMAND that must be a command that resumes
# the inferior (run/continue/next/etc) and consumes
# the "^running" output from it.
proc mi_send_resuming_command_raw {command test} {

    global mi_gdb_prompt
    global thread_selected_re
    global library_loaded_re

    send_gdb "$command\n"
    gdb_expect {
	-re "\\^running\r\n\\*running,thread-id=\"\[^\"\]+\"\r\n($library_loaded_re)*($thread_selected_re)?${mi_gdb_prompt}" {
	    # Note that lack of 'pass' call here -- this works around limitation
	    # in DejaGNU xfail mechanism. mi-until.exp has this:
	    #
	    #     setup_kfail gdb/2104 "*-*-*"
	    #     mi_execute_to ...
	    #
	    # and mi_execute_to uses mi_send_resuming_command.  If we use 'pass' here,
	    # it will reset kfail, so when the actual test fails, it will be flagged
	    # as real failure.
	    return 0
	}
	-re "\\^error,msg=\"Displaced stepping is only supported in ARM mode\".*" {
	    unsupported "$test (Thumb mode)"
	    return -1
	}
	-re "\\^error,msg=.*" {
	    fail "$test (MI error)"
	    return -1
	}
	-re ".*${mi_gdb_prompt}" {
	    fail "$test (failed to resume)"
	    return -1
	}
	timeout {
	    fail "$test"
	    return -1
	}
    }
}

proc mi_send_resuming_command {command test} {
    mi_send_resuming_command_raw -$command $test
}

# Helper to mi_run_inline_test below.
# Sets a temporary breakpoint at LOCATION and runs
# the program using COMMAND.  When the program is stopped
# returns the line at which it.  Returns -1 if line cannot
# be determined.
# Does not check that the line is the same as requested.
# The caller can check itself if required.
proc mi_continue_to_line {location test} {

    mi_tbreak $location
    mi_send_resuming_command "exec-continue" "run to $location (exec-continue)"
    return [mi_get_stop_line $test]
}

# Wait until gdb prints the current line.
proc mi_get_stop_line {test} {

  global mi_gdb_prompt
  global async

  if {$async} {
      set prompt_re ""
  } else {
      set prompt_re "$mi_gdb_prompt$"
  }

  gdb_expect {
      -re ".*line=\"(\[0-9\]*)\".*\r\n$prompt_re" {
	  return $expect_out(1,string)
      }
      -re ".*$mi_gdb_prompt" {
	  fail "wait for stop ($test)"
      }
      timeout {
	  fail "wait for stop ($test)"
      }
  }
}

# Run a MI test embedded in comments in a C file.
# The C file should contain special comments in the following
# three forms:
#
#    /*: BEGIN: testname :*/
#    /*:  <Tcl statements> :*/
#    /*: END: testname :*/
#
# This procedure find the begin and end marker for the requested
# test. Then, a temporary breakpoint is set at the begin
# marker and the program is run (from start).
#
# After that, for each special comment between the begin and end
# marker, the Tcl statements are executed.  It is assumed that
# for each comment, the immediately preceding line is executable
# C statement.  Then, gdb will be single-stepped until that
# preceding C statement is executed, and after that the
# Tcl statements in the comment will be executed.
#
# For example:
#
#     /*: BEGIN: assignment-test :*/
#     v = 10;
#     /*: <Tcl code to check that 'v' is indeed 10 :*/
#     /*: END: assignment-test :*/
#
# The mi_prepare_inline_tests function should be called before
# calling this function.  A given C file can contain several
# inline tests.  The names of the tests must be unique within one
# C file.
#
proc mi_run_inline_test { testcase } {

    global mi_gdb_prompt
    global hex
    global decimal
    global fullname_syntax
    global mi_autotest_source

    set commands [mi_get_inline_test $testcase]

    set first 1
    set line_now 1

    foreach c $commands {
	set statements [lindex $c 0]
	set line [lindex $c 1]
	set line [expr $line-1]

	# We want gdb to be stopped at the expression immediately
	# before the comment.  If this is the first comment, the
	# program is either not started yet or is in some random place,
	# so we run it.  For further comments, we might be already
	# standing at the right line. If not continue till the
	# right line.

	if {$first==1} {
	    # Start the program afresh.
	    mi_tbreak "$mi_autotest_source:$line"
	    mi_run_cmd
	    set line_now [mi_get_stop_line "$testcase: step to $line"]
	    set first 0
	} elseif {$line_now!=$line} {
	    set line_now [mi_continue_to_line "$mi_autotest_source:$line" "continue to $line"]
	}

	if {$line_now!=$line} {
	    fail "$testcase: go to line $line"
	}

	# We're not at the statement right above the comment.
	# Execute that statement so that the comment can test
	# the state after the statement is executed.

	# Single-step past the line.
	if { [mi_send_resuming_command "exec-next" "$testcase: step over $line"] != 0 } {
	    return -1
	}
	set line_now [mi_get_stop_line "$testcase: step over $line"]

	# We probably want to use 'uplevel' so that statements
	# have direct access to global variables that the
	# main 'exp' file has set up.  But it's not yet clear,
	# will need more experience to be sure.
	eval $statements
    }
}

proc get_mi_thread_list {name} {
  global expect_out

  # MI will return a list of thread ids:
  #
  # -thread-list-ids
  # ^done,thread-ids=[thread-id="1",thread-id="2",...],number-of-threads="N"
  # (gdb)
  mi_gdb_test "-thread-list-ids" \
    {.*\^done,thread-ids={(thread-id="[0-9]+"(,)?)+},current-thread-id="[0-9]+",number-of-threads="[0-9]+"} \
    "-thread_list_ids ($name)"

  set output {}
  if {[info exists expect_out(buffer)]} {
    set output $expect_out(buffer)
  }

  set thread_list {}
  if {![regexp {thread-ids=\{(thread-id="[0-9]+"(,)?)*\}} $output threads]} {
    fail "finding threads in MI output ($name)"
  } else {
    pass "finding threads in MI output ($name)"

    # Make list of console threads
    set start [expr {[string first \{ $threads] + 1}]
    set end   [expr {[string first \} $threads] - 1}]
    set threads [string range $threads $start $end]
    foreach thread [split $threads ,] {
      if {[scan $thread {thread-id="%d"} num]} {
	lappend thread_list $num
      }
    }
  }

  return $thread_list
}

# Check that MI and the console know of the same threads.
# Appends NAME to all test names.
proc check_mi_and_console_threads {name} {
  global expect_out

  mi_gdb_test "-thread-list-ids" \
    {.*\^done,thread-ids={(thread-id="[0-9]+"(,)*)+},current-thread-id="[0-9]+",number-of-threads="[0-9]+"} \
    "-thread-list-ids ($name)"
  set mi_output {}
  if {[info exists expect_out(buffer)]} {
    set mi_output $expect_out(buffer)
  }

  # GDB will return a list of thread ids and some more info:
  #
  # (gdb) 
  # -interpreter-exec console "info threads"
  # ~"  4 Thread 2051 (LWP 7734)  0x401166b1 in __libc_nanosleep () at __libc_nanosleep:-1"
  # ~"  3 Thread 1026 (LWP 7733)   () at __libc_nanosleep:-1"
  # ~"  2 Thread 2049 (LWP 7732)  0x401411f8 in __poll (fds=0x804bb24, nfds=1, timeout=2000) at ../sysdeps/unix/sysv/linux/poll.c:63"
  # ~"* 1 Thread 1024 (LWP 7731)  main (argc=1, argv=0xbfffdd94) at ../../../src/gdb/testsuite/gdb.mi/pthreads.c:160"
  # FIXME: kseitz/2002-09-05: Don't use the hack-cli method.
  mi_gdb_test "info threads" \
    {.*(~".*"[\r\n]*)+.*} \
    "info threads ($name)"
  set console_output {}
  if {[info exists expect_out(buffer)]} {
    set console_output $expect_out(buffer)
  }

  # Make a list of all known threads to console (gdb's thread IDs)
  set console_thread_list {}
  foreach line [split $console_output \n] {
    if {[string index $line 0] == "~"} {
      # This is a line from the console; trim off "~", " ", "*", and "\""
      set line [string trim $line ~\ \"\*]
      if {[scan $line "%d" id] == 1} {
	lappend console_thread_list $id
      }
    }
  }

  # Now find the result string from MI
  set mi_result ""
  foreach line [split $mi_output \n] {
    if {[string range $line 0 4] == "^done"} {
      set mi_result $line
    }
  }
  if {$mi_result == ""} {
    fail "finding MI result string ($name)"
  } else {
    pass "finding MI result string ($name)"
  }

  # Finally, extract the thread ids and compare them to the console
  set num_mi_threads_str ""
  if {![regexp {number-of-threads="[0-9]+"} $mi_result num_mi_threads_str]} {
    fail "finding number of threads in MI output ($name)"
  } else {
    pass "finding number of threads in MI output ($name)"

    # Extract the number of threads from the MI result
    if {![scan $num_mi_threads_str {number-of-threads="%d"} num_mi_threads]} {
      fail "got number of threads from MI ($name)"
    } else {
      pass "got number of threads from MI ($name)"

      # Check if MI and console have same number of threads
      if {$num_mi_threads != [llength $console_thread_list]} {
	fail "console and MI have same number of threads ($name)"
      } else {
	pass "console and MI have same number of threads ($name)"

	# Get MI thread list
	set mi_thread_list [get_mi_thread_list $name]

	# Check if MI and console have the same threads
	set fails 0
	foreach ct [lsort $console_thread_list] mt [lsort $mi_thread_list] {
	  if {$ct != $mt} {
	    incr fails
	  }
	}
	if {$fails > 0} {
	  fail "MI and console have same threads ($name)"

	  # Send a list of failures to the log
	  send_log "Console has thread ids: $console_thread_list\n"
	  send_log "MI has thread ids: $mi_thread_list\n"
	} else {
	  pass "MI and console have same threads ($name)"
	}
      }
    }
  }
}

# Download shared libraries to the target.
proc mi_load_shlibs { args } {
    if {![is_remote target]} {
	return
    }

    foreach file $args {
	gdb_download [shlib_target_file $file]
    }

    # Even if the target supplies full paths for shared libraries,
    # they may not be paths for this system.
    mi_gdb_test "set solib-search-path [file dirname [lindex $args 0]]" "\^done" ""
}

proc mi_reverse_list { list } {
    if { [llength $list] <= 1 } {
	return $list
    }
    set tail [lrange $list 1 [llength $list]]
    set rtail [mi_reverse_list $tail]
    lappend rtail [lindex $list 0]
    return $rtail
}

proc mi_check_thread_states { xstates test } {
    global expect_out
    set states [mi_reverse_list $xstates]
    set pattern ".*\\^done,threads=\\\["
    foreach s $states {
	set pattern "${pattern}(.*)state=\"$s\""
    }
    set pattern "${pattern}(,core=\"\[0-9\]*\")?\\\}\\\].*"

    verbose -log "expecting: $pattern"
    mi_gdb_test "-thread-info" $pattern $test
}

# Return a list of MI features supported by this gdb.
proc mi_get_features {} {
    global expect_out mi_gdb_prompt

    send_gdb "-list-features\n"

    gdb_expect {
	-re "\\^done,features=\\\[(.*)\\\]\r\n$mi_gdb_prompt$" {
	    regsub -all -- \" $expect_out(1,string) "" features
	    return [split $features ,]
	}
	-re ".*\r\n$mi_gdb_prompt$" {
	    verbose -log "got $expect_out(buffer)"
	    return ""
	}
	timeout {
	    verbose -log "timeout in mi_gdb_prompt"
	    return ""
	}
    }
}

# Variable Object Trees
#
# Yet another way to check varobjs. Pass mi_walk_varobj_tree a "list" of
# variables (not unlike the actual source code definition), and it will
# automagically test the children for you (by default).
#
# Example:
#
# source code:
# struct bar {
#   union {
#     int integer;
#     void *ptr;
#   };
#   const int *iPtr;
# };
#
# class foo {
# public:
#   int a;
#   struct {
#     int b;
#     struct bar *c;
#   };
# };
#
# foo *f = new foo (); <-- break here
#
# We want to check all the children of "f".
#
# Translate the above structures into the following tree:
#
# set tree {
#   foo f {
#     {} public {
#       int a {}
#       anonymous struct {
#         {} public {
#           int b {}
#           {bar *} c {
#             {} public {
#               anonymous union {
#                 {} public {
#                   int integer {}
#                   {void *} ptr {}
#                 }
#               }
#               {const int *} iPtr {
#                 {const int} {*iPtr} {}
#               }
#             }
#           }
#         }
#       }
#     }
#   }
# }
#
# mi_walk_varobj_tree c++ $tree
#
# If you'd prefer to walk the tree using your own callback,
# simply pass the name of the callback to mi_walk_varobj_tree.
#
# This callback should take one argument, the name of the variable
# to process.  This name is the name of a global array holding the
# variable's properties (object name, type, etc).
#
# An example callback:
#
# proc my_callback {var} {
#   upvar #0 $var varobj
#
#   puts "my_callback: called on varobj $varobj(obj_name)"
# }
#
# The arrays created for each variable object contain the following
# members:
#
# obj_name     - the object name for accessing this variable via MI
# display_name - the display name for this variable (exp="display_name" in
#                the output of -var-list-children)
# type         - the type of this variable (type="type" in the output
#                of -var-list-children, or the special tag "anonymous"
# path_expr    - the "-var-info-path-expression" for this variable
#                NOTE: This member cannot be used reliably with typedefs.
#                Use with caution!
#                See notes inside get_path_expr for more.
# parent       - the variable name of the parent varobj
# children     - a list of children variable names (which are the
#                names Tcl arrays, not object names)
#
# For each variable object, an array containing the above fields will
# be created under the root node (conveniently called, "root").  For example,
# a variable object with handle "OBJ.public.0_anonymous.a" will have
# a corresponding global Tcl variable named "root.OBJ.public.0_anonymous.a".
#
# Note that right now, this mechanism cannot be used for recursive data
# structures like linked lists.

namespace eval ::varobj_tree {
  # An index which is appended to root varobjs to ensure uniqueness.
  variable _root_idx 0

  # A procedure to help with debuggging varobj trees.
  # VARIABLE_NAME is the name of the variable to dump.
  # CMD, if present, is the name of the callback to output the contstructed
  #   strings. By default, it uses expect's "send_log" command.
  # TERM, if present, is a terminating character. By default it is the newline.
  #
  # To output to the terminal (not the expect log), use
  # mi_varobj_tree_dump_variable my_variable puts ""

  proc mi_varobj_tree_dump_variable {variable_name {cmd send_log} {term "\n"}} {
    upvar #0 $variable_name varobj

    eval "$cmd \"VAR = $variable_name$term\""

    # Explicitly encode the array indices, since outputting them
    # in some logical order is better than what "array names" might
    # return.
    foreach idx {obj_name parent display_name type path_expr} {
      eval "$cmd \"\t$idx = $varobj($idx)$term\""
    }

    # Output children
    set num [llength $varobj(children)]
    eval "$cmd \"\tnum_children = $num$term\""
    if {$num > 0} {
      eval "$cmd \"\tchildren = $varobj(children)$term\""
    }
  }

  # The default callback used by mi_walk_varobj_tree.  This callback
  # simply checks all of VAR's children.  It specifically does not test
  # path expressions, since that is very problematic.
  #
  # This procedure may be used in custom callbacks.
  proc test_children_callback {variable_name} {
    upvar #0 $variable_name varobj

    if {[llength $varobj(children)] > 0} {
      # Construct the list of children the way mi_list_varobj_children
      # expects to get it:
      # { {obj_name display_name num_children type} ... }
      set children_list {}
      foreach child $varobj(children) {
	upvar #0 $child c
	set clist [list [string_to_regexp $c(obj_name)] \
		       [string_to_regexp $c(display_name)] \
		       [llength $c(children)]]
	if {[string length $c(type)] > 0} {
	  lappend clist [string_to_regexp $c(type)]
	}
	lappend children_list $clist
      }

      mi_list_varobj_children $varobj(obj_name) $children_list \
	  "VT: list children of $varobj(obj_name)"
    }
  }

  # Set the properties of the varobj represented by
  # PARENT_VARIABLE - the name of the parent's variable
  # OBJNAME         - the MI object name of this variable
  # DISP_NAME       - the display name of this variable
  # TYPE            - the type of this variable
  # PATH            - the path expression for this variable
  # CHILDREN        - a list of the variable's children
  proc create_varobj {parent_variable objname disp_name \
			  type path children} {
    upvar #0 $parent_variable parent

    set var_name "root.$objname"
    global $var_name
    array set $var_name [list obj_name $objname]
    array set $var_name [list display_name $disp_name]
    array set $var_name [list type $type]
    array set $var_name [list path_expr $path]
    array set $var_name [list parent "$parent_variable"]
    array set $var_name [list children \
			     [get_tree_children $var_name $children]]
    return $var_name
  }

  # Should VARIABLE be used in path expressions?  The CPLUS_FAKE_CHILD
  # varobjs and anonymous structs/unions are not used for path expressions.
  proc is_path_expr_parent {variable} {
    upvar #0 $variable varobj

    # If the varobj's type is "", it is a CPLUS_FAKE_CHILD.
    # If the tail of the varobj's object name is "%d_anonymous",
    # then it represents an anonymous struct or union.
    if {[string length $varobj(type)] == 0 \
	    || [regexp {[0-9]+_anonymous$} $varobj(obj_name)]} {
      return false
    }

    return true
  }

  # Return the path expression for the variable named NAME in
  # parent varobj whose variable name is given by PARENT_VARIABLE.
  proc get_path_expr {parent_variable name type} {
    upvar #0 $parent_variable parent
    upvar #0 $parent_variable path_parent

    # If TYPE is "", this is one of the CPLUS_FAKE_CHILD varobjs,
    # which has no path expression.  Likewsise for anonymous structs
    # and unions.
    if {[string length $type] == 0 \
	    || [string compare $type "anonymous"] == 0} {
      return ""
    }

    # Find the path parent variable.
    while {![is_path_expr_parent $parent_variable]} {
      set parent_variable $path_parent(parent)
      upvar #0 $parent_variable path_parent
    }

    # This is where things get difficult.  We do not actually know
    # the real type for variables defined via typedefs, so we don't actually
    # know whether the parent is a structure/union or not.
    #
    # So we assume everything that isn't a simple type is a compound type.
    set stars ""
    regexp {\*+} $parent(type) stars
    set is_compound 1
    if {[string index $name 0] == "*"} {
      set is_compound 0
    }

    if {[string index $parent(type) end] == "\]"} {
      # Parent is an array.
      return "($path_parent(path_expr))\[$name\]"
    } elseif {$is_compound} {
      # Parent is a structure or union or a pointer to one.
      if {[string length $stars]} {
	set join "->"
      } else {
	set join "."
      }

      global root

      # To make matters even more hideous, varobj.c has slightly different
      # path expressions for C and C++.
      set path_expr "($path_parent(path_expr))$join$name"
      if {[string compare -nocase $root(language) "c"] == 0} {
	return $path_expr
      } else {
	return "($path_expr)"
      }
    } else {
      # Parent is a pointer.
      return "*($path_parent(path_expr))"
    }
  }

  # Process the CHILDREN (a list of varobj_tree elements) of the variable
  # given by PARENT_VARIABLE.  Returns a list of children variables.
  proc get_tree_children {parent_variable children} {
    upvar #0 $parent_variable parent

    set field_idx 0
    set children_list {}
    foreach {type name children} $children {
      if {[string compare $parent_variable "root"] == 0} {
	# Root variable
	variable _root_idx
	incr _root_idx
	set objname "$name$_root_idx"
	set disp_name "$name"
	set path_expr "$name"
      } elseif {[string compare $type "anonymous"] == 0} {
	# Special case: anonymous types.  In this case, NAME will either be
	# "struct" or "union".
	set objname "$parent(obj_name).${field_idx}_anonymous"
	set disp_name "<anonymous $name>"
	set path_expr ""
	set type "$name {...}"
      } else {
	set objname "$parent(obj_name).$name"
	set disp_name $name
	set path_expr [get_path_expr $parent_variable $name $type]
      }

      lappend children_list [create_varobj $parent_variable $objname \
				 $disp_name $type $path_expr $children]
      incr field_idx
    }

    return $children_list
  }

  # The main procedure to call the given CALLBACK on the elements of the
  # given varobj TREE.  See detailed explanation above.
  proc walk_tree {language tree callback} {
    global root
    variable _root_idx

    if {[llength $tree] < 3} {
      error "tree does not contain enough elements"
    }

    set _root_idx 0

    # Create root node and process the tree.
    array set root [list language $language]
    array set root [list obj_name "root"]
    array set root [list display_name "root"]
    array set root [list type "root"]
    array set root [list path_expr "root"]
    array set root [list parent "root"]
    array set root [list children [get_tree_children root $tree]]

    # Walk the tree
    set all_nodes $root(children); # a stack of nodes
    while {[llength $all_nodes] > 0} {
      # "Pop" the name of the global variable containing this varobj's
      # information from the stack of nodes.
      set var_name [lindex $all_nodes 0]
      set all_nodes [lreplace $all_nodes 0 0]

      # Bring the global named in VAR_NAME into scope as the local variable
      # VAROBJ.
      upvar #0 $var_name varobj

      # Append any children of VAROBJ to the list of nodes to walk.
      if {[llength $varobj(children)] > 0} {
	set all_nodes [concat $all_nodes $varobj(children)]
      }

      # If this is a root variable, create the variable object for it.
      if {[string compare $varobj(parent) "root"] == 0} {
	mi_create_varobj $varobj(obj_name) $varobj(display_name) \
	    "VT: create root varobj for $varobj(display_name)"
      }

      # Now call the callback for VAROBJ.
      uplevel #0 $callback $var_name
    }
  }
}

# The default varobj tree callback, which simply tests -var-list-children.
proc mi_varobj_tree_test_children_callback {variable} {
  ::varobj_tree::test_children_callback $variable
}

# Walk the variable object tree given by TREE, calling the specified
# CALLBACK.  By default this uses mi_varobj_tree_test_children_callback.
proc mi_walk_varobj_tree {language tree \
			      {callback \
				   mi_varobj_tree_test_children_callback}} {
  ::varobj_tree::walk_tree $language $tree $callback
}

# Build a list of key-value pairs given by the list ATTR_LIST.  Flatten
# this list using the optional JOINER, a comma by default.
#
# The list must contain an even number of elements, which are the key-value
# pairs.  Each value will be surrounded by quotes, according to the grammar,
# except if the value starts with \[ or \{, when the quotes will be omitted.
#
# Example: mi_build_kv_pairs {a b c d e f g \[.*\]}
# returns a=\"b\",c=\"d\",e=\"f\",g=\[.*\]
proc mi_build_kv_pairs {attr_list {joiner ,}} {
    set l {}
    foreach {var value} $attr_list {
	if {[string range $value 0 1] == "\\\["
	    || [string range $value 0 1] == "\\\{"} {
	    lappend l "$var=$value"
	} else {
	    lappend l "$var=\"$value\""
	}
    }
    return "[join $l $joiner]"
}

# Construct a breakpoint regexp.  This may be used to test the output of
# -break-insert, -dprintf-insert, or -break-info.
#
# All arguments for the breakpoint may be specified using the options
# number, type, disp, enabled, addr, func, file, fullanme, line,
# thread-groups, cond, evaluated-by, times, ignore, script,
# and original-location.
#
# Only if -script and -ignore are given will they appear in the output.
# Otherwise, this procedure will skip them using ".*".
#
# Example: mi_make_breakpoint -number 2 -file ".*/myfile.c" -line 3
# will return the breakpoint:
# bkpt={number="2",type=".*",disp=".*",enabled=".*",addr=".*",func=".*",
#       file=".*/myfile.c",fullname=".*",line="3",thread-groups=\[.*\],
#       times="0".*original-location=".*"}

proc mi_make_breakpoint {args} {
    parse_args {{number .*} {type .*} {disp .*} {enabled .*} {addr .*}
	{func .*} {file .*} {fullname .*} {line .*}
	{thread-groups \\\[.*\\\]} {times .*} {ignore 0}
	{script ""} {original-location .*} {cond ""} {evaluated-by ""}}

    set attr_list {}
    foreach attr [list number type disp enabled addr func file \
		      fullname line thread-groups] {
	lappend attr_list $attr [set $attr]
    }

    set result "bkpt={[mi_build_kv_pairs $attr_list]"

    # There are always exceptions.

    # If COND is not preset, do not output it.
    if {[string length $cond] > 0} {
	append result ","
	append result [mi_build_kv_pairs [list "cond" $cond]]

	# When running on a remote, GDB may output who is evaluating
	# breakpoint conditions.
	if {[string length ${evaluated-by}] > 0} {
	    append result [mi_build_kv_pairs \
			       [list "evaluated-by" ${evaluated-by}]]
	} else {
	    append result {(,evaluated-by=".*")?}
	}
    }

    append result ","
    append result [mi_build_kv_pairs [list "times" $times]]

    # If SCRIPT and IGNORE are not present, do not output them.
    if {$ignore != 0} {
	append result ","
	append result [mi_build_kv_pairs [list "ignore" $ignore]]
	append result ","
    }
    if {[string length $script] > 0} {
	append result ","
	append result [mi_build_kv_pairs [list "script" $script]]
	append result ","
    } else {
	# Allow anything up until the next "official"/required attribute.
	# This pattern skips over script/ignore if matches on those
	# were not specifically required by the caller.
	append result ".*"
    }
    append result [mi_build_kv_pairs \
		       [list "original-location" ${original-location}]]
    append result "}"
    return $result
}

# Build a breakpoint table regexp given the list of breakpoints in `bp_list',
# constructed by mi_make_breakpoint.
#
# Example:  Construct a breakpoint table where the only attributes we
# test for are the existence of three breakpoints numbered 1, 2, and 3.
#
# set bps {}
# lappend bps [mi_make_breakpoint -number 1]
# lappend bps [mi_make_breakpoint -number 2]
# lappned bps [mi_make_breakpoint -number 3]
# mi_make_breakpoint_table $bps
# will return (abbreviated for clarity):
# BreakpointTable={nr_rows="3",nr_cols="6",hdr=[{width=".*",...} ...],
#   body=[bkpt={number="1",...},bkpt={number="2",...},bkpt={number="3",...}]}

proc mi_make_breakpoint_table {bp_list} {
    # Build header -- assume a standard header for all breakpoint tables.
    set hl {}
    foreach {nm hdr} [list number Num type Type disp Disp enabled Enb \
			  addr Address what What] {
	# The elements here are the MI table headers, which have the
	# format:
	# {width="7",alignment="-1",col_name="number",colhdr="Num"}
	lappend hl "{[mi_build_kv_pairs [list width .* alignment .* \
				       col_name $nm colhdr $hdr]]}"
    }
    set header "hdr=\\\[[join $hl ,]\\\]"

    # The caller has implicitly supplied the number of columns and rows.
    set nc [llength $hl]
    set nr [llength $bp_list]

    # Build body -- mi_make_breakpoint has done most of the work.
    set body "body=\\\[[join $bp_list ,]\\\]"

    # Assemble the final regexp.
    return "BreakpointTable={nr_rows=\"$nr\",nr_cols=\"$nc\",$header,$body}"
}

# Return a 1 for configurations that do not support Python scripting.
# Note: This also sets various globals that specify which version of Python
# is in use.  See skip_python_tests_prompt.

proc mi_skip_python_tests {} {
    global mi_gdb_prompt
    return [skip_python_tests_prompt "$mi_gdb_prompt$"]
}