aboutsummaryrefslogtreecommitdiffstats
path: root/lisp/progmodes/gdb-ui.el
blob: 3c1251ba59b04e2a2c72fd045c3709185ef8911e (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
;;; gdb-ui.el --- User Interface for running GDB

;; Author: Nick Roberts <[email protected]>
;; Maintainer: FSF
;; Keywords: unix, tools

;; Copyright (C) 2002, 2003, 2004, 2005  Free Software Foundation, Inc.

;; This file is part of GNU Emacs.

;; GNU Emacs 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 2, or (at your option)
;; any later version.

;; GNU Emacs 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 GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Commentary:

;; This mode acts as a graphical user interface to GDB.  You can interact with
;; GDB through the GUD buffer in the usual way, but there are also further
;; buffers which control the execution and describe the state of your program.
;; It separates the input/output of your program from that of GDB, if
;; required, and watches expressions in the speedbar.  It also uses features of
;; Emacs 21 such as the fringe/display margin for breakpoints, and the toolbar
;; (see the GDB Graphical Interface section in the Emacs info manual).

;; By default, M-x gdb will start the debugger. However, if you have customised
;; gud-gdb-command-name, then start it with M-x gdba.

;; This file has evolved from gdba.el that was included with GDB 5.0 and
;; written by Tom Lord and Jim Kingdon.  It uses GDB's annotation interface.
;; You don't need to know about annotations to use this mode as a debugger,
;; but if you are interested developing the mode itself, then see the
;; Annotations section in the GDB info manual.
;;
;; GDB developers plan to make the annotation interface obsolete.  A new
;; interface called GDB/MI (machine interface) has been designed to replace
;; it.  Some GDB/MI commands are used in this file through the CLI command
;; 'interpreter mi <mi-command>'.  A file called gdb-mi.el is included with
;; GDB (6.2 onwards) that uses GDB/MI as the primary interface to GDB.  It is
;; still under development and is part of a process to migrate Emacs from
;; annotations to GDB/MI.
;;
;; Known Bugs:
;;
;; TODO:
;; 1) Use MI command -data-read-memory for memory window.
;; 2) Highlight changed register values (use MI commands
;;    -data-list-register-values and -data-list-changed-registers instead
;;    of 'info registers'.
;; 3) Use tree-widget.el instead of the speedbar for watch-expressions?
;; 4) Mark breakpoint locations on scroll-bar of source buffer?
;; 5) After release of 22.1 use '-var-list-children --all-values'
;;    and '-stack-list-locals 2' which need GDB 6.1 onwards.

;;; Code:

(require 'gud)

(defvar gdb-current-address "main" "Initialisation for Assembler buffer.")
(defvar gdb-previous-address nil)
(defvar gdb-memory-address "main")
(defvar gdb-previous-frame nil)
(defvar gdb-current-frame nil)
(defvar gdb-current-stack-level nil)
(defvar gdb-current-language nil)
(defvar gdb-var-list nil "List of variables in watch window.")
(defvar gdb-var-changed nil "Non-nil means that gdb-var-list has changed.")
(defvar gdb-buffer-type nil)
(defvar gdb-overlay-arrow-position nil)
(defvar gdb-server-prefix nil)
(defvar gdb-flush-pending-output nil)
(defvar gdb-location-list nil "List of directories for source files.")
(defvar gdb-find-file-unhook nil)

(defvar gdb-buffer-type nil
  "One of the symbols bound in `gdb-buffer-rules'.")

(defvar gdb-input-queue ()
  "A list of gdb command objects.")

(defvar gdb-prompting nil
  "True when gdb is idle with no pending input.")

(defvar gdb-output-sink 'user
  "The disposition of the output of the current gdb command.
Possible values are these symbols:

    `user' -- gdb output should be copied to the GUD buffer
              for the user to see.

    `inferior' -- gdb output should be copied to the inferior-io buffer

    `pre-emacs' -- output should be ignored util the post-prompt
                   annotation is received.  Then the output-sink
		   becomes:...
    `emacs' -- output should be collected in the partial-output-buffer
	       for subsequent processing by a command.  This is the
	       disposition of output generated by commands that
	       gdb mode sends to gdb on its own behalf.
    `post-emacs' -- ignore output until the prompt annotation is
		    received, then go to USER disposition.

gdba (gdb-ui.el) uses all five values,  gdbmi (gdb-mi.el) only two
\(`user' and `emacs').")

(defvar gdb-current-item nil
  "The most recent command item sent to gdb.")

(defvar gdb-pending-triggers '()
  "A list of trigger functions that have run later than their output
handlers.")

;; end of gdb variables

;;;###autoload
(defun gdba (command-line)
  "Run gdb on program FILE in buffer *gud-FILE*.
The directory containing FILE becomes the initial working directory
and source-file directory for your debugger.

If `gdb-many-windows' is nil (the default value) then gdb just
pops up the GUD buffer unless `gdb-show-main' is t. In this case
it starts with two windows: one displaying the GUD buffer and the
other with the source file with the main routine of the inferior.

If `gdb-many-windows' is t, regardless of the value of
`gdb-show-main', the layout below will appear unless
`gdb-use-inferior-io-buffer' is nil when the source buffer
occupies the full width of the frame.  Keybindings are given in
relevant buffer.

Watch expressions appear in the speedbar/slowbar.

The following commands help control operation :

`gdb-many-windows'    - Toggle the number of windows gdb uses.
`gdb-restore-windows' - To restore the window layout.

See Info node `(emacs)GDB Graphical Interface' for a more
detailed description of this mode.


---------------------------------------------------------------------
                               GDB Toolbar
---------------------------------------------------------------------
 GUD buffer (I/O of GDB)          | Locals buffer
                                  |
                                  |
                                  |
---------------------------------------------------------------------
 Source buffer                    | Input/Output (of inferior) buffer
                                  | (comint-mode)
                                  |
                                  |
                                  |
                                  |
                                  |
                                  |
---------------------------------------------------------------------
 Stack buffer                     | Breakpoints buffer
 RET      gdb-frames-select       | SPC    gdb-toggle-breakpoint
                                  | RET    gdb-goto-breakpoint
                                  |   d    gdb-delete-breakpoint
---------------------------------------------------------------------"
  ;;
  (interactive (list (gud-query-cmdline 'gdba)))
  ;;
  ;; Let's start with a basic gud-gdb buffer and then modify it a bit.
  (gdb command-line)
  (gdb-ann3))

(defvar gdb-debug-log nil)

(defcustom gdb-enable-debug-log nil
  "Non-nil means record the process input and output in `gdb-debug-log'."
  :type 'boolean
  :group 'gud
  :version "22.1")

(defcustom gdb-use-inferior-io-buffer nil
  "Non-nil means display output from the inferior in a separate buffer."
  :type 'boolean
  :group 'gud
  :version "22.1")

(defun gdb-set-gud-minor-mode (buffer)
  "Set gud-minor-mode from find-file if appropriate."
  (goto-char (point-min))
  (unless (search-forward "No source file named " nil t)
    (condition-case nil
	(gdb-enqueue-input
	 (list (concat gdb-server-prefix "info source\n")
	       `(lambda () (gdb-set-gud-minor-mode-1 ,buffer))))
      (error (setq gdb-find-file-unhook t)))))

(defun gdb-set-gud-minor-mode-1 (buffer)
  (goto-char (point-min))
  (if (and (search-forward "Located in " nil t)
	   (looking-at "\\S-*")
	   (string-equal (buffer-file-name buffer)
			 (match-string 0)))
      (with-current-buffer buffer
	(set (make-local-variable 'gud-minor-mode) 'gdba)
	(set (make-local-variable 'tool-bar-map) gud-tool-bar-map))))

(defun gdb-set-gud-minor-mode-existing-buffers ()
  (dolist (buffer (buffer-list))
    (let ((file (buffer-file-name buffer)))
      (if file
	(progn
	  (gdb-enqueue-input
	   (list (concat gdb-server-prefix "list "
			 (file-name-nondirectory file) ":1\n")
		 `(lambda () (gdb-set-gud-minor-mode ,buffer)))))))))

(defun gdb-ann3 ()
  (setq gdb-debug-log nil)
  (set (make-local-variable 'gud-minor-mode) 'gdba)
  (set (make-local-variable 'gud-marker-filter) 'gud-gdba-marker-filter)
  ;;
  (gud-def gud-break (if (not (string-equal mode-name "Machine"))
			 (gud-call "break %f:%l" arg)
		       (save-excursion
			 (beginning-of-line)
			 (forward-char 2)
			 (gud-call "break *%a" arg)))
	   "\C-b" "Set breakpoint at current line or address.")
  ;;
  (gud-def gud-remove (if (not (string-equal mode-name "Machine"))
			  (gud-call "clear %f:%l" arg)
			(save-excursion
			  (beginning-of-line)
			  (forward-char 2)
			  (gud-call "clear *%a" arg)))
	   "\C-d" "Remove breakpoint at current line or address.")
  ;;
  (gud-def gud-until  (if (not (string-equal mode-name "Machine"))
			  (gud-call "until %f:%l" arg)
			(save-excursion
			  (beginning-of-line)
			  (forward-char 2)
			  (gud-call "until *%a" arg)))
	   "\C-u" "Continue to current line or address.")

  (define-key gud-minor-mode-map [left-margin mouse-1]
    'gdb-mouse-set-clear-breakpoint)
  (define-key gud-minor-mode-map [left-fringe mouse-1]
    'gdb-mouse-set-clear-breakpoint)
  (define-key gud-minor-mode-map [left-margin mouse-3]
    'gdb-mouse-toggle-breakpoint)
;  (define-key gud-minor-mode-map [left-fringe mouse-3]
;    'gdb-mouse-toggle-breakpoint)

  (setq comint-input-sender 'gdb-send)
  ;;
  ;; (re-)initialize
  (setq gdb-current-address "main")
  (setq gdb-previous-address nil)
  (setq gdb-memory-address "main")
  (setq gdb-previous-frame nil)
  (setq gdb-current-frame nil)
  (setq gdb-current-stack-level nil)
  (setq gdb-var-list nil)
  (setq gdb-var-changed nil)
  (setq gdb-first-prompt nil)
  (setq gdb-prompting nil)
  (setq gdb-input-queue nil)
  (setq gdb-current-item nil)
  (setq gdb-pending-triggers nil)
  (setq gdb-output-sink 'user)
  (setq gdb-server-prefix "server ")
  (setq gdb-flush-pending-output nil)
  (setq gdb-location-list nil)
  (setq gdb-find-file-unhook nil)
  ;;
  (setq gdb-buffer-type 'gdba)
  ;;
  (if gdb-use-inferior-io-buffer (gdb-clear-inferior-io))
  ;;
  (if (eq window-system 'w32)
      (gdb-enqueue-input (list "set new-console off\n" 'ignore)))
  (gdb-enqueue-input (list "set height 0\n" 'ignore))
  (gdb-enqueue-input (list "set width 0\n" 'ignore))
  ;; find source file and compilation directory here
  (gdb-enqueue-input (list "server list main\n"   'ignore))   ; C program
  (gdb-enqueue-input (list "server list MAIN__\n" 'ignore))   ; Fortran program
  (gdb-enqueue-input (list "server info source\n" 'gdb-source-info))
  ;;
  (gdb-set-gud-minor-mode-existing-buffers)
  (run-hooks 'gdba-mode-hook))

(defcustom gdb-use-colon-colon-notation nil
  "If non-nil use FUN::VAR format to display variables in the speedbar." ;
  :type 'boolean
  :group 'gud
  :version "22.1")

(defun gud-watch ()
  "Watch expression at point."
  (interactive)
  (require 'tooltip)
  (let ((expr (tooltip-identifier-from-point (point))))
    (if (and (string-equal gdb-current-language "c")
	     gdb-use-colon-colon-notation gdb-current-frame)
	(setq expr (concat gdb-current-frame "::" expr)))
    (catch 'already-watched
      (dolist (var gdb-var-list)
	(if (string-equal expr (car var)) (throw 'already-watched nil)))
      (set-text-properties 0 (length expr) nil expr)
      (gdb-enqueue-input
       (list
	(if (eq gud-minor-mode 'gdba)
	    (concat "server interpreter mi \"-var-create - * "  expr "\"\n")
	  (concat"-var-create - * "  expr "\n"))
	     `(lambda () (gdb-var-create-handler ,expr))))))
  (select-window (get-buffer-window gud-comint-buffer 0)))

(defconst gdb-var-create-regexp
  "name=\"\\(.*?\\)\",numchild=\"\\(.*?\\)\",type=\"\\(.*?\\)\"")

(defun gdb-var-create-handler (expr)
  (with-current-buffer (gdb-get-create-buffer 'gdb-partial-output-buffer)
    (goto-char (point-min))
    (if (re-search-forward gdb-var-create-regexp nil t)
	(let ((var (list expr
			 (match-string 1)
			 (match-string 2)
			 (match-string 3)
			 nil nil)))
	  (push var gdb-var-list)
	  (speedbar 1)
	  (if (equal (nth 2 var) "0")
	      (gdb-enqueue-input
	       (list (concat "server interpreter mi \"-var-evaluate-expression "
			     (nth 1 var) "\"\n")
		     `(lambda () (gdb-var-evaluate-expression-handler
				  ,(nth 1 var) nil))))
	    (setq gdb-var-changed t)))
      (if (re-search-forward "Undefined command" nil t)
	  (message "Watching expressions requires gdb 6.0 onwards")
	(message "No symbol %s in current context." expr)))))

(defun gdb-var-evaluate-expression-handler (varnum changed)
  (with-current-buffer (gdb-get-create-buffer 'gdb-partial-output-buffer)
    (goto-char (point-min))
    (re-search-forward ".*value=\"\\(.*?\\)\"" nil t)
    (catch 'var-found
      (let ((num 0))
	(dolist (var gdb-var-list)
	  (if (string-equal varnum (cadr var))
	      (progn
		(if changed (setcar (nthcdr 5 var) t))
		(setcar (nthcdr 4 var) (match-string 1))
		(setcar (nthcdr num gdb-var-list) var)
		(throw 'var-found nil)))
	  (setq num (+ num 1))))))
  (setq gdb-var-changed t))

(defun gdb-var-list-children (varnum)
  (gdb-enqueue-input
   (list (concat "server interpreter mi \"-var-list-children "  varnum "\"\n")
	     `(lambda () (gdb-var-list-children-handler ,varnum)))))

(defconst gdb-var-list-children-regexp
  "name=\"\\(.*?\\)\",exp=\"\\(.*?\\)\",numchild=\"\\(.*?\\)\"")

(defun gdb-var-list-children-handler (varnum)
  (with-current-buffer (gdb-get-create-buffer 'gdb-partial-output-buffer)
    (goto-char (point-min))
    (let ((var-list nil))
     (catch 'child-already-watched
       (dolist (var gdb-var-list)
	 (if (string-equal varnum (cadr var))
	     (progn
	       (push var var-list)
	       (while (re-search-forward gdb-var-list-children-regexp nil t)
		 (let ((varchild (list (match-string 2)
				       (match-string 1)
				       (match-string 3)
				       nil nil nil)))
		   (if (looking-at ",type=\"\\(.*?\\)\"")
		       (setcar (nthcdr 3 varchild) (match-string 1)))
		   (dolist (var1 gdb-var-list)
		     (if (string-equal (cadr var1) (cadr varchild))
			 (throw 'child-already-watched nil)))
		   (push varchild var-list)
		   (if (equal (nth 2 varchild) "0")
		       (gdb-enqueue-input
			(list
			 (concat
			  "server interpreter mi \"-var-evaluate-expression "
				 (nth 1 varchild) "\"\n")
			 `(lambda () (gdb-var-evaluate-expression-handler
				      ,(nth 1 varchild) nil))))))))
	   (push var var-list)))
       (setq gdb-var-list (nreverse var-list))))))

(defun gdb-var-update ()
  (if (not (member 'gdb-var-update gdb-pending-triggers))
      (progn
	(gdb-enqueue-input
	 (list
	  (if (with-current-buffer gud-comint-buffer (eq gud-minor-mode 'gdba))
	      "server interpreter mi \"-var-update *\"\n"
	    "-var-update *\n")
				 'gdb-var-update-handler))
	(push 'gdb-var-update gdb-pending-triggers))))

(defconst gdb-var-update-regexp "name=\"\\(.*?\\)\"")

(defun gdb-var-update-handler ()
  (with-current-buffer (gdb-get-create-buffer 'gdb-partial-output-buffer)
    (goto-char (point-min))
    (while (re-search-forward gdb-var-update-regexp nil t)
	(let ((varnum (match-string 1)))
	  (gdb-enqueue-input
	   (list
	    (if (with-current-buffer gud-comint-buffer (eq gud-minor-mode 'gdba))
		(concat "server interpreter mi \"-var-evaluate-expression "
			varnum "\"\n")
	      (concat "-var-evaluate-expression " varnum "\n"))
		     `(lambda () (gdb-var-evaluate-expression-handler
				  ,varnum t)))))))
  (setq gdb-pending-triggers
   (delq 'gdb-var-update gdb-pending-triggers))
  (when (and (boundp 'speedbar-frame) (frame-live-p speedbar-frame))
    ;; dummy command to update speedbar at right time
    (gdb-enqueue-input (list "server pwd\n" 'gdb-speedbar-timer-fn))
    ;; keep gdb-pending-triggers non-nil till end
    (push 'gdb-speedbar-timer gdb-pending-triggers)))

(defun gdb-speedbar-timer-fn ()
  (setq gdb-pending-triggers
	(delq 'gdb-speedbar-timer gdb-pending-triggers))
  (with-current-buffer gud-comint-buffer
    (speedbar-timer-fn)))

(defun gdb-var-delete ()
  "Delete watched expression from the speedbar."
  (interactive)
  (if (with-current-buffer gud-comint-buffer (eq gud-minor-mode 'gdba))
      (let ((text (speedbar-line-text)))
	(string-match "\\(\\S-+\\)" text)
	(let* ((expr (match-string 1 text))
	       (var (assoc expr gdb-var-list))
	       (varnum (cadr var)))
	  (unless (string-match "\\." varnum)
	    (gdb-enqueue-input
	     (list
	      (if (with-current-buffer gud-comint-buffer
		    (eq gud-minor-mode 'gdba))
		  (concat "server interpreter mi \"-var-delete " varnum "\"\n")
		(concat "-var-delete " varnum "\n"))
		   'ignore))
	    (setq gdb-var-list (delq var gdb-var-list))
	    (dolist (varchild gdb-var-list)
	      (if (string-match (concat (nth 1 var) "\\.") (nth 1 varchild))
		  (setq gdb-var-list (delq varchild gdb-var-list))))
	    (setq gdb-var-changed t))))))

(defun gdb-edit-value (text token indent)
  "Assign a value to a variable displayed in the speedbar."
  (let* ((var (nth (- (count-lines (point-min) (point)) 2) gdb-var-list))
	 (varnum (cadr var)) (value))
    (setq value (read-string "New value: "))
    (gdb-enqueue-input
     (list
      (if (with-current-buffer gud-comint-buffer
	    (eq gud-minor-mode 'gdba))
	  (concat "server interpreter mi \"-var-assign " varnum " " value "\"\n")
	(concat "-var-assign " varnum " " value "\n"))
	   'ignore))))

(defcustom gdb-show-changed-values t
  "If non-nil highlight values that have recently changed in the speedbar.
The highlighting is done with `font-lock-warning-face'."
  :type 'boolean
  :group 'gud
  :version "22.1")

(defun gdb-speedbar-expand-node (text token indent)
  "Expand the node the user clicked on.
TEXT is the text of the button we clicked on, a + or - item.
TOKEN is data related to this node.
INDENT is the current indentation depth."
  (cond ((string-match "+" text)        ;expand this node
	 (if (with-current-buffer gud-comint-buffer (eq gud-minor-mode 'gdba))
	     (gdb-var-list-children token)
	   (gdbmi-var-list-children token)))
	((string-match "-" text)	;contract this node
	 (dolist (var gdb-var-list)
	   (if (string-match (concat token "\\.") (nth 1 var))
	       (setq gdb-var-list (delq var gdb-var-list))))
	 (setq gdb-var-changed t))))

(defun gdb-get-target-string ()
  (with-current-buffer gud-comint-buffer
    gud-target-name))


;;
;; gdb buffers.
;;
;; Each buffer has a TYPE -- a symbol that identifies the function
;; of that particular buffer.
;;
;; The usual gdb interaction buffer is given the type `gdba' and
;; is constructed specially.
;;
;; Others are constructed by gdb-get-create-buffer and
;; named according to the rules set forth in the gdb-buffer-rules-assoc

(defvar gdb-buffer-rules-assoc '())

(defun gdb-get-buffer (key)
  "Return the gdb buffer tagged with type KEY.
The key should be one of the cars in `gdb-buffer-rules-assoc'."
  (save-excursion
    (gdb-look-for-tagged-buffer key (buffer-list))))

(defun gdb-get-create-buffer (key)
  "Create a new gdb  buffer of the type specified by KEY.
The key should be one of the cars in `gdb-buffer-rules-assoc'."
  (or (gdb-get-buffer key)
      (let* ((rules (assoc key gdb-buffer-rules-assoc))
	     (name (funcall (gdb-rules-name-maker rules)))
	     (new (get-buffer-create name)))
	(with-current-buffer new
	  (let ((trigger))
	    (if (cdr (cdr rules))
		(setq trigger (funcall (car (cdr (cdr rules))))))
	    (set (make-local-variable 'gdb-buffer-type) key)
	    (set (make-local-variable 'gud-minor-mode)
		 (with-current-buffer gud-comint-buffer gud-minor-mode))
	    (set (make-local-variable 'tool-bar-map) gud-tool-bar-map)
	    (if trigger (funcall trigger)))
	  new))))

(defun gdb-rules-name-maker (rules) (car (cdr rules)))

(defun gdb-look-for-tagged-buffer (key bufs)
  (let ((retval nil))
    (while (and (not retval) bufs)
      (set-buffer (car bufs))
      (if (eq gdb-buffer-type key)
	  (setq retval (car bufs)))
      (setq bufs (cdr bufs)))
    retval))

;;
;; This assoc maps buffer type symbols to rules.  Each rule is a list of
;; at least one and possible more functions.  The functions have these
;; roles in defining a buffer type:
;;
;;     NAME - Return a name for this  buffer type.
;;
;; The remaining function(s) are optional:
;;
;;     MODE - called in a new buffer with no arguments, should establish
;;	      the proper mode for the buffer.
;;

(defun gdb-set-buffer-rules (buffer-type &rest rules)
  (let ((binding (assoc buffer-type gdb-buffer-rules-assoc)))
    (if binding
	(setcdr binding rules)
      (push (cons buffer-type rules)
	    gdb-buffer-rules-assoc))))

;; GUD buffers are an exception to the rules
(gdb-set-buffer-rules 'gdba 'error)

;;
;; Partial-output buffer : This accumulates output from a command executed on
;; behalf of emacs (rather than the user).
;;
(gdb-set-buffer-rules 'gdb-partial-output-buffer
		      'gdb-partial-output-name)

(defun gdb-partial-output-name ()
  (concat "*partial-output-"
	  (gdb-get-target-string)
	  "*"))


(gdb-set-buffer-rules 'gdb-inferior-io
		      'gdb-inferior-io-name
		      'gdb-inferior-io-mode)

(defun gdb-inferior-io-name ()
  (concat "*input/output of "
	  (gdb-get-target-string)
	  "*"))

(defvar gdb-inferior-io-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\C-c\C-c" 'gdb-inferior-io-interrupt)
    (define-key map "\C-c\C-z" 'gdb-inferior-io-stop)
    (define-key map "\C-c\C-\\" 'gdb-inferior-io-quit)
    (define-key map "\C-c\C-d" 'gdb-inferior-io-eof)
    map))

(define-derived-mode gdb-inferior-io-mode comint-mode "Inferior I/O"
  "Major mode for gdb inferior-io."
  :syntax-table nil :abbrev-table nil
  ;; We want to use comint because it has various nifty and familiar
  ;; features.  We don't need a process, but comint wants one, so create
  ;; a dummy one.
  (make-comint-in-buffer
   (substring (buffer-name) 1 (- (length (buffer-name)) 1))
   (current-buffer) "hexl")
  (setq comint-input-sender 'gdb-inferior-io-sender))

(defun gdb-inferior-io-sender (proc string)
  ;; PROC is the pseudo-process created to satisfy comint.
  (with-current-buffer (process-buffer proc)
    (setq proc (get-buffer-process gud-comint-buffer))
    (process-send-string proc string)
    (process-send-string proc "\n")))

(defun gdb-inferior-io-interrupt ()
  "Interrupt the program being debugged."
  (interactive)
  (interrupt-process
   (get-buffer-process gud-comint-buffer) comint-ptyp))

(defun gdb-inferior-io-quit ()
  "Send quit signal to the program being debugged."
  (interactive)
  (quit-process
   (get-buffer-process gud-comint-buffer) comint-ptyp))

(defun gdb-inferior-io-stop ()
  "Stop the program being debugged."
  (interactive)
  (stop-process
   (get-buffer-process gud-comint-buffer) comint-ptyp))

(defun gdb-inferior-io-eof ()
  "Send end-of-file to the program being debugged."
  (interactive)
  (process-send-eof
   (get-buffer-process gud-comint-buffer)))


;;
;; gdb communications
;;

;; INPUT: things sent to gdb
;;
;; The queues are lists.  Each element is either a string (indicating user or
;; user-like input) or a list of the form:
;;
;;    (INPUT-STRING  HANDLER-FN)
;;
;; The handler function will be called from the partial-output buffer when the
;; command completes.  This is the way to write commands which invoke gdb
;; commands autonomously.
;;
;; These lists are consumed tail first.
;;

(defun gdb-send (proc string)
  "A comint send filter for gdb.
This filter may simply queue input for a later time."
  (if gud-running
      (process-send-string proc (concat string "\n"))
    (gdb-enqueue-input (concat string "\n"))))

;; Note: Stuff enqueued here will be sent to the next prompt, even if it
;; is a query, or other non-top-level prompt.

(defun gdb-enqueue-input (item)
  (if gdb-prompting
      (progn
	(gdb-send-item item)
	(setq gdb-prompting nil))
    (push item gdb-input-queue)))

(defun gdb-dequeue-input ()
  (let ((queue gdb-input-queue))
    (and queue
	 (let ((last (car (last queue))))
	   (unless (nbutlast queue) (setq gdb-input-queue '()))
	   last))))

(defun gdb-send-item (item)
  (setq gdb-flush-pending-output nil)
  (if gdb-enable-debug-log (push (cons 'send item) gdb-debug-log))
  (setq gdb-current-item item)
  (with-current-buffer gud-comint-buffer
    (if (eq gud-minor-mode 'gdba)
	(if (stringp item)
	    (progn
	      (setq gdb-output-sink 'user)
	      (process-send-string (get-buffer-process gud-comint-buffer) item))
	  (progn
	    (gdb-clear-partial-output)
	    (setq gdb-output-sink 'pre-emacs)
	    (process-send-string (get-buffer-process gud-comint-buffer)
				 (car item))))
      ;; case: eq gud-minor-mode 'gdbmi
      (gdb-clear-partial-output)
      (setq gdb-output-sink 'emacs)
      (process-send-string (get-buffer-process gud-comint-buffer)
			   (car item)))))

;;
;; output -- things gdb prints to emacs
;;
;; GDB output is a stream interrupted by annotations.
;; Annotations can be recognized by their beginning
;; with \C-j\C-z\C-z<tag><opt>\C-j
;;
;; The tag is a string obeying symbol syntax.
;;
;; The optional part `<opt>' can be either the empty string
;; or a space followed by more data relating to the annotation.
;; For example, the SOURCE annotation is followed by a filename,
;; line number and various useless goo.  This data must not include
;; any newlines.
;;

(defcustom gud-gdba-command-name "gdb -annotate=3"
  "Default command to execute an executable under the GDB-UI debugger."
  :type 'string
  :group 'gud
  :version "22.1")

(defvar gdb-annotation-rules
  '(("pre-prompt" gdb-pre-prompt)
    ("prompt" gdb-prompt)
    ("commands" gdb-subprompt)
    ("overload-choice" gdb-subprompt)
    ("query" gdb-subprompt)
    ;; Need this prompt for GDB 6.1
    ("nquery" gdb-subprompt)
    ("prompt-for-continue" gdb-subprompt)
    ("post-prompt" gdb-post-prompt)
    ("source" gdb-source)
    ("starting" gdb-starting)
    ("exited" gdb-stopping)
    ("signalled" gdb-stopping)
    ("signal" gdb-stopping)
    ("breakpoint" gdb-stopping)
    ("watchpoint" gdb-stopping)
    ("frame-begin" gdb-frame-begin)
    ("stopped" gdb-stopped)
    ) "An assoc mapping annotation tags to functions which process them.")

(defun gdb-resync()
  (setq gdb-flush-pending-output t)
  (setq gud-running nil)
  (setq gdb-output-sink 'user)
  (setq gdb-input-queue nil)
  (setq gdb-pending-triggers nil)
  (setq gdb-prompting t))

(defconst gdb-source-spec-regexp
  "\\(.*\\):\\([0-9]*\\):[0-9]*:[a-z]*:\\(0x[a-f0-9]*\\)")

;; Do not use this except as an annotation handler.
(defun gdb-source (args)
  (string-match gdb-source-spec-regexp args)
  ;; Extract the frame position from the marker.
  (setq gud-last-frame
	(cons
	 (match-string 1 args)
	 (string-to-int (match-string 2 args))))
  (setq gdb-current-address (match-string 3 args))
  ;; cover for auto-display output which comes *before*
  ;; stopped annotation
  (if (eq gdb-output-sink 'inferior) (setq gdb-output-sink 'user)))

(defun gdb-pre-prompt (ignored)
  "An annotation handler for `pre-prompt'.
This terminates the collection of output from a previous command if that
happens to be in effect."
  (let ((sink gdb-output-sink))
    (cond
     ((eq sink 'user) t)
     ((eq sink 'emacs)
      (setq gdb-output-sink 'post-emacs))
     (t
      (gdb-resync)
      (error "Phase error in gdb-pre-prompt (got %s)" sink)))))

(defun gdb-prompt (ignored)
  "An annotation handler for `prompt'.
This sends the next command (if any) to gdb."
  (when gdb-first-prompt (gdb-ann3))
  (let ((sink gdb-output-sink))
    (cond
     ((eq sink 'user) t)
     ((eq sink 'post-emacs)
      (setq gdb-output-sink 'user)
      (let ((handler
	     (car (cdr gdb-current-item))))
	(with-current-buffer (gdb-get-create-buffer 'gdb-partial-output-buffer)
	  (funcall handler))))
     (t
      (gdb-resync)
      (error "Phase error in gdb-prompt (got %s)" sink))))
  (let ((input (gdb-dequeue-input)))
    (if input
	(gdb-send-item input)
      (progn
	(setq gdb-prompting t)
	(gud-display-frame)))))

(defun gdb-subprompt (ignored)
  "An annotation handler for non-top-level prompts."
  (setq gdb-prompting t))

(defun gdb-starting (ignored)
  "An annotation handler for `starting'.
This says that I/O for the subprocess is now the program being debugged,
not GDB."
  (let ((sink gdb-output-sink))
    (cond
     ((eq sink 'user)
      (progn
	(setq gud-running t)
	(if gdb-use-inferior-io-buffer
	    (setq gdb-output-sink 'inferior))))
     (t
      (gdb-resync)
      (error "Unexpected `starting' annotation")))))

(defun gdb-stopping (ignored)
  "An annotation handler for `exited' and other annotations.
They say that I/O for the subprocess is now GDB, not the program
being debugged."
  (if gdb-use-inferior-io-buffer
      (let ((sink gdb-output-sink))
	(cond
	 ((eq sink 'inferior)
	  (setq gdb-output-sink 'user))
	 (t
	  (gdb-resync)
	  (error "Unexpected stopping annotation"))))))

(defun gdb-frame-begin (ignored)
  (let ((sink gdb-output-sink))
    (cond
     ((eq sink 'inferior)
      (setq gdb-output-sink 'user))
     ((eq sink 'user) t)
     ((eq sink 'emacs) t)
     (t
      (gdb-resync)
      (error "Unexpected frame-begin annotation (%S)" sink)))))

(defun gdb-stopped (ignored)
  "An annotation handler for `stopped'.
It is just like `gdb-stopping', except that if we already set the output
sink to `user' in `gdb-stopping', that is fine."
  (setq gud-running nil)
  (let ((sink gdb-output-sink))
    (cond
     ((eq sink 'inferior)
      (setq gdb-output-sink 'user))
     ((eq sink 'user) t)
     (t
      (gdb-resync)
      (error "Unexpected stopped annotation")))))

(defun gdb-post-prompt (ignored)
  "An annotation handler for `post-prompt'.
This begins the collection of output from the current command if that
happens to be appropriate."
  (if (not gdb-pending-triggers)
      (progn
	(gdb-get-current-frame)
	(gdb-invalidate-frames)
	(gdb-invalidate-breakpoints)
	(gdb-invalidate-assembler)
	(gdb-invalidate-registers)
	(gdb-invalidate-memory)
	(gdb-invalidate-locals)
	(gdb-invalidate-threads)
	(unless (eq system-type 'darwin) ;Breaks on Darwin's GDB-5.3.
	  ;; FIXME: with GDB-6 on Darwin, this might very well work.
	  ;; only needed/used with speedbar/watch expressions
	  (when (and (boundp 'speedbar-frame) (frame-live-p speedbar-frame))
	    (setq gdb-var-changed t)    ; force update
	    (dolist (var gdb-var-list)
	      (setcar (nthcdr 5 var) nil))
	    (gdb-var-update)))))
  (let ((sink gdb-output-sink))
    (cond
     ((eq sink 'user) t)
     ((eq sink 'pre-emacs)
      (setq gdb-output-sink 'emacs))
     (t
      (gdb-resync)
      (error "Phase error in gdb-post-prompt (got %s)" sink)))))

(defun gud-gdba-marker-filter (string)
  "A gud marker filter for gdb.  Handle a burst of output from GDB."
  (if gdb-flush-pending-output
      nil
    (if gdb-enable-debug-log (push (cons 'recv string) gdb-debug-log))
    ;; Recall the left over gud-marker-acc from last time
    (setq gud-marker-acc (concat gud-marker-acc string))
    ;; Start accumulating output for the GUD buffer
    (let ((output ""))
      ;;
      ;; Process all the complete markers in this chunk.
      (while (string-match "\n\032\032\\(.*\\)\n" gud-marker-acc)
	(let ((annotation (match-string 1 gud-marker-acc)))
	  ;;
	  ;; Stuff prior to the match is just ordinary output.
	  ;; It is either concatenated to OUTPUT or directed
	  ;; elsewhere.
	  (setq output
		(gdb-concat-output
		 output
		 (substring gud-marker-acc 0 (match-beginning 0))))
	  ;;
	  ;; Take that stuff off the gud-marker-acc.
	  (setq gud-marker-acc (substring gud-marker-acc (match-end 0)))
	  ;;
	  ;; Parse the tag from the annotation, and maybe its arguments.
	  (string-match "\\(\\S-*\\) ?\\(.*\\)" annotation)
	  (let* ((annotation-type (match-string 1 annotation))
		 (annotation-arguments (match-string 2 annotation))
		 (annotation-rule (assoc annotation-type
					 gdb-annotation-rules)))
	    ;; Call the handler for this annotation.
	    (if annotation-rule
		(funcall (car (cdr annotation-rule))
			 annotation-arguments)
	      ;; Else the annotation is not recognized.  Ignore it silently,
	      ;; so that GDB can add new annotations without causing
	      ;; us to blow up.
	      ))))
      ;;
      ;; Does the remaining text end in a partial line?
      ;; If it does, then keep part of the gud-marker-acc until we get more.
      (if (string-match "\n\\'\\|\n\032\\'\\|\n\032\032.*\\'"
			gud-marker-acc)
	  (progn
	    ;; Everything before the potential marker start can be output.
	    (setq output
		  (gdb-concat-output output
				     (substring gud-marker-acc 0
						(match-beginning 0))))
	    ;;
	    ;; Everything after, we save, to combine with later input.
	    (setq gud-marker-acc (substring gud-marker-acc (match-beginning 0))))
	;;
	;; In case we know the gud-marker-acc contains no partial annotations:
	(progn
	  (setq output (gdb-concat-output output gud-marker-acc))
	  (setq gud-marker-acc "")))
      output)))

(defun gdb-concat-output (so-far new)
  (let ((sink gdb-output-sink))
    (cond
     ((eq sink 'user) (concat so-far new))
     ((or (eq sink 'pre-emacs) (eq sink 'post-emacs)) so-far)
     ((eq sink 'emacs)
      (gdb-append-to-partial-output new)
      so-far)
     ((eq sink 'inferior)
      (gdb-append-to-inferior-io new)
      so-far)
     (t
      (gdb-resync)
      (error "Bogon output sink %S" sink)))))

(defun gdb-append-to-partial-output (string)
  (with-current-buffer (gdb-get-create-buffer 'gdb-partial-output-buffer)
    (goto-char (point-max))
    (insert string)))

(defun gdb-clear-partial-output ()
  (with-current-buffer (gdb-get-create-buffer 'gdb-partial-output-buffer)
    (erase-buffer)))

(defun gdb-append-to-inferior-io (string)
  (with-current-buffer (gdb-get-create-buffer 'gdb-inferior-io)
    (goto-char (point-max))
    (insert-before-markers string))
  (if (not (string-equal string ""))
      (gdb-display-buffer (gdb-get-create-buffer 'gdb-inferior-io))))

(defun gdb-clear-inferior-io ()
  (with-current-buffer (gdb-get-create-buffer 'gdb-inferior-io)
    (erase-buffer)))


;; One trick is to have a command who's output is always available in a buffer
;; of it's own, and is always up to date.  We build several buffers of this
;; type.
;;
;; There are two aspects to this: gdb has to tell us when the output for that
;; command might have changed, and we have to be able to run the command
;; behind the user's back.
;;
;; The output phasing associated with the variable gdb-output-sink
;; help us to run commands behind the user's back.
;;
;; Below is the code for specificly managing buffers of output from one
;; command.
;;

;; The trigger function is suitable for use in the assoc GDB-ANNOTATION-RULES
;; It adds an input for the command we are tracking.  It should be the
;; annotation rule binding of whatever gdb sends to tell us this command
;; might have changed it's output.
;;
;; NAME is the function name.  DEMAND-PREDICATE tests if output is really needed.
;; GDB-COMMAND is a string of such.  OUTPUT-HANDLER is the function bound to the
;; input in the input queue (see comment about ``gdb communications'' above).

(defmacro def-gdb-auto-update-trigger (name demand-predicate gdb-command
					    output-handler)
  `(defun ,name (&optional ignored)
     (if (and (,demand-predicate)
	      (not (member ',name
			   gdb-pending-triggers)))
	 (progn
	   (gdb-enqueue-input
	    (list ,gdb-command ',output-handler))
	   (push ',name gdb-pending-triggers)))))

(defmacro def-gdb-auto-update-handler (name trigger buf-key custom-defun)
  `(defun ,name ()
     (setq gdb-pending-triggers
      (delq ',trigger
	    gdb-pending-triggers))
     (let ((buf (gdb-get-buffer ',buf-key)))
       (and buf
	    (with-current-buffer buf
	      (let ((p (point))
		    (buffer-read-only nil))
		(erase-buffer)
		(insert-buffer-substring (gdb-get-create-buffer
					  'gdb-partial-output-buffer))
		(goto-char p)))))
     ;; put customisation here
     (,custom-defun)))

(defmacro def-gdb-auto-updated-buffer (buffer-key trigger-name gdb-command
						  output-handler-name custom-defun)
  `(progn
     (def-gdb-auto-update-trigger ,trigger-name
       ;; The demand predicate:
       (lambda () (gdb-get-buffer ',buffer-key))
       ,gdb-command
       ,output-handler-name)
     (def-gdb-auto-update-handler ,output-handler-name
       ,trigger-name ,buffer-key ,custom-defun)))


;;
;; Breakpoint buffer : This displays the output of `info breakpoints'.
;;
(gdb-set-buffer-rules 'gdb-breakpoints-buffer
		      'gdb-breakpoints-buffer-name
		      'gdb-breakpoints-mode)

(def-gdb-auto-updated-buffer gdb-breakpoints-buffer
  ;; This defines the auto update rule for buffers of type
  ;; `gdb-breakpoints-buffer'.
  ;;
  ;; It defines a function to serve as the annotation handler that
  ;; handles the `foo-invalidated' message.  That function is called:
  gdb-invalidate-breakpoints
  ;;
  ;; To update the buffer, this command is sent to gdb.
  "server info breakpoints\n"
  ;;
  ;; This also defines a function to be the handler for the output
  ;; from the command above.  That function will copy the output into
  ;; the appropriately typed buffer.  That function will be called:
  gdb-info-breakpoints-handler
  ;; buffer specific functions
  gdb-info-breakpoints-custom)

(defconst breakpoint-xpm-data
  "/* XPM */
static char *magick[] = {
/* columns rows colors chars-per-pixel */
\"10 10 2 1\",
\"  c red\",
\"+ c None\",
/* pixels */
\"+++    +++\",
\"++      ++\",
\"+        +\",
\"          \",
\"          \",
\"          \",
\"          \",
\"+        +\",
\"++      ++\",
\"+++    +++\",
};"
  "XPM data used for breakpoint icon.")

(defconst breakpoint-enabled-pbm-data
  "P1
10 10\",
0 0 0 0 1 1 1 1 0 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 1 1 1 1 1 1 1 1 0 0
0 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 0
0 0 1 1 1 1 1 1 1 1 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 0 0 1 1 1 1 0 0 0 0"
  "PBM data used for enabled breakpoint icon.")

(defconst breakpoint-disabled-pbm-data
  "P1
10 10\",
0 0 1 0 1 0 1 0 0 0
0 1 0 1 0 1 0 1 0 0
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
0 0 1 0 1 0 1 0 1 0
0 0 0 1 0 1 0 1 0 0"
  "PBM data used for disabled breakpoint icon.")

(defvar breakpoint-enabled-icon nil
  "Icon for enabled breakpoint in display margin.")

(defvar breakpoint-disabled-icon nil
  "Icon for disabled breakpoint in display margin.")

;; Bitmap for breakpoint in fringe
(and (display-images-p)
     (define-fringe-bitmap 'breakpoint
       "\x3c\x7e\xff\xff\xff\xff\x7e\x3c"))

(defface breakpoint-enabled-bitmap-face
  '((t
     :inherit fringe
     :foreground "red"))
  "Face for enabled breakpoint icon in fringe."
  :group 'gud)

(defface breakpoint-disabled-bitmap-face
  '((t
     :inherit fringe
     :foreground "grey60"))
  "Face for disabled breakpoint icon in fringe."
  :group 'gud)


;;-put breakpoint icons in relevant margins (even those set in the GUD buffer)
(defun gdb-info-breakpoints-custom ()
  (let ((flag) (bptno))
    ;; remove all breakpoint-icons in source buffers but not assembler buffer
    (dolist (buffer (buffer-list))
      (with-current-buffer buffer
	(if (and (eq gud-minor-mode 'gdba)
		 (not (string-match "\\`\\*.+\\*\\'" (buffer-name))))
	    (gdb-remove-breakpoint-icons (point-min) (point-max)))))
    (with-current-buffer (gdb-get-buffer 'gdb-breakpoints-buffer)
      (save-excursion
	(goto-char (point-min))
	(while (< (point) (- (point-max) 1))
	  (forward-line 1)
	  (if (looking-at "[^\t].*breakpoint")
	      (progn
		(looking-at "\\([0-9]+\\)\\s-+\\S-+\\s-+\\S-+\\s-+\\(.\\)")
		(setq bptno (match-string 1))
		(setq flag (char-after (match-beginning 2)))
		(beginning-of-line)
		(if (re-search-forward " in .* at\\s-+" nil t)
		    (progn
		      (looking-at "\\(\\S-+\\):\\([0-9]+\\)")
		      (let ((line (match-string 2)) (buffer-read-only nil)
			    (file (match-string 1)))
			(add-text-properties (point-at-bol) (point-at-eol)
			 '(mouse-face highlight
			   help-echo "mouse-2, RET: visit breakpoint"))
			(unless (file-exists-p file)
			   (setq file (cdr (assoc bptno gdb-location-list))))
			(unless (string-equal file "File not found")
			  (if file
			      (with-current-buffer (find-file-noselect file)
				(set (make-local-variable 'gud-minor-mode)
				     'gdba)
				(set (make-local-variable 'tool-bar-map)
				     gud-tool-bar-map)
				;; only want one breakpoint icon at each location
				(save-excursion
				  (goto-line (string-to-number line))
				  (gdb-put-breakpoint-icon (eq flag ?y) bptno)))
			    (gdb-enqueue-input
			     (list (concat gdb-server-prefix "list "
					   (match-string-no-properties 1) ":1\n")
				   'ignore))
			    (gdb-enqueue-input
			     (list (concat gdb-server-prefix "info source\n")
				   `(lambda ()
				      (gdb-get-location
				       ,bptno ,line ,flag)))))))))))
	  (end-of-line)))))
  (if (gdb-get-buffer 'gdb-assembler-buffer) (gdb-assembler-custom)))

(defun gdb-mouse-set-clear-breakpoint (event)
  "Set/clear breakpoint in left fringe/margin with mouse click."
  (interactive "e")
  (mouse-minibuffer-check event)
  (let ((posn (event-end event)))
    (if (numberp (posn-point posn))
	(with-selected-window (posn-window posn)
	  (save-excursion
	    (goto-char (posn-point posn))
	    (if (or (posn-object posn)
		    (eq (car (fringe-bitmaps-at-pos (posn-point posn)))
			'breakpoint))
		(gud-remove nil)
	      (gud-break nil)))))))

(defun gdb-mouse-toggle-breakpoint (event)
  "Enable/disable breakpoint in left fringe/margin with mouse click."
  (interactive "e")
  (mouse-minibuffer-check event)
  (let ((posn (event-end event)))
    (if (numberp (posn-point posn))
	(with-selected-window (posn-window posn)
	  (save-excursion
	    (goto-char (posn-point posn))
	    (if
;		(or
		 (posn-object posn)
;		 (eq (car (fringe-bitmaps-at-pos (posn-point posn)))
;		     'breakpoint))
		(gdb-enqueue-input
		 (list
		  (let ((bptno (get-text-property
				0 'gdb-bptno (car (posn-string posn)))))
		    (concat
			    (if (get-text-property
				 0 'gdb-enabled (car (posn-string posn)))
				"disable "
			      "enable ")
			    bptno "\n")) 'ignore))))))))

(defun gdb-breakpoints-buffer-name ()
  (with-current-buffer gud-comint-buffer
    (concat "*breakpoints of " (gdb-get-target-string) "*")))

(defun gdb-display-breakpoints-buffer ()
  "Display status of user-settable breakpoints."
  (interactive)
  (gdb-display-buffer
   (gdb-get-create-buffer 'gdb-breakpoints-buffer)))

(defconst gdb-frame-parameters
  '((height . 14) (width . 80)
    (unsplittable . t)
    (tool-bar-lines . nil)
    (menu-bar-lines . nil)
    (minibuffer . nil)))

(defun gdb-frame-breakpoints-buffer ()
  "Display status of user-settable breakpoints in a new frame."
  (interactive)
  (let ((special-display-regexps (append special-display-regexps '(".*")))
	(special-display-frame-alist gdb-frame-parameters))
    (display-buffer (gdb-get-create-buffer 'gdb-breakpoints-buffer))))

(defvar gdb-breakpoints-mode-map
  (let ((map (make-sparse-keymap))
	(menu (make-sparse-keymap "Breakpoints")))
    (define-key menu [toggle] '("Toggle" . gdb-toggle-breakpoint))
    (define-key menu [delete] '("Delete" . gdb-delete-breakpoint))
    (define-key menu [goto] '("Goto"   . gdb-goto-breakpoint))

    (suppress-keymap map)
    (define-key map [menu-bar breakpoints] (cons "Breakpoints" menu))
    (define-key map " " 'gdb-toggle-breakpoint)
    (define-key map "d" 'gdb-delete-breakpoint)
    (define-key map "q" 'kill-this-buffer)
    (define-key map "\r" 'gdb-goto-breakpoint)
    (define-key map [mouse-2] 'gdb-goto-breakpoint)
    map))

(defun gdb-breakpoints-mode ()
  "Major mode for gdb breakpoints.

\\{gdb-breakpoints-mode-map}"
  (kill-all-local-variables)
  (setq major-mode 'gdb-breakpoints-mode)
  (setq mode-name "Breakpoints")
  (use-local-map gdb-breakpoints-mode-map)
  (setq buffer-read-only t)
  (run-mode-hooks 'gdb-breakpoints-mode-hook)
  (if (with-current-buffer gud-comint-buffer (eq gud-minor-mode 'gdba))
      'gdb-invalidate-breakpoints
    'gdbmi-invalidate-breakpoints))

(defun gdb-toggle-breakpoint ()
  "Enable/disable breakpoint at current line."
  (interactive)
  (save-excursion
    (beginning-of-line 1)
    (if (if (with-current-buffer gud-comint-buffer (eq gud-minor-mode 'gdba))
	    (looking-at "\\([0-9]+\\).*point\\s-*\\S-*\\s-*\\(.\\)")
	  (looking-at
      "\\([0-9]+\\)\\s-*\\S-*\\s-*\\S-*\\s-*\\(.\\)\\s-*\\S-*\\s-*\\S-*:[0-9]+"))
	(gdb-enqueue-input
	 (list
	  (concat gdb-server-prefix
		  (if (eq ?y (char-after (match-beginning 2)))
		      "disable "
		    "enable ")
		  (match-string 1) "\n") 'ignore))
      (error "Not recognized as break/watchpoint line"))))

(defun gdb-delete-breakpoint ()
  "Delete the breakpoint at current line."
  (interactive)
  (beginning-of-line 1)
  (if (if (with-current-buffer gud-comint-buffer (eq gud-minor-mode 'gdba))
	  (looking-at "\\([0-9]+\\).*point\\s-*\\S-*\\s-*\\(.\\)")
	(looking-at
	 "\\([0-9]+\\)\\s-*\\S-*\\s-*\\S-*\\s-*.\\s-*\\S-*\\s-*\\S-*:[0-9]+"))
      (gdb-enqueue-input
       (list
	(concat gdb-server-prefix "delete " (match-string 1) "\n") 'ignore))
    (error "Not recognized as break/watchpoint line")))

(defun gdb-goto-breakpoint (&optional event)
  "Display the breakpoint location specified at current line."
  (interactive (list last-input-event))
  (if event (mouse-set-point event))
  (save-excursion
    (beginning-of-line 1)
    (if (if (with-current-buffer gud-comint-buffer (eq gud-minor-mode 'gdba))
	    (looking-at "\\([0-9]+\\) .* in .* at\\s-+\\(\\S-*\\):\\([0-9]+\\)")
	  (looking-at
 "\\([0-9]+\\)\\s-*\\S-*\\s-*\\S-*\\s-*.\\s-*\\S-*\\s-*\\(\\S-*\\):\\([0-9]+\\)"))
	(let ((bptno (match-string 1))
	      (file  (match-string 2))
	      (line  (match-string 3)))
	  (save-selected-window
	    (let* ((buf (find-file-noselect (if (file-exists-p file)
						file
					      (cdr (assoc bptno gdb-location-list)))))
		   (window (display-buffer buf)))
	      (with-current-buffer buf
		(goto-line (string-to-number line))
		(set-window-point window (point))))))
      (error "Not recognized as break/watchpoint line"))))


;; Frames buffer.  This displays a perpetually correct bactracktrace
;; (from the command `where').
;;
;; Alas, if your stack is deep, it is costly.
;;
(gdb-set-buffer-rules 'gdb-stack-buffer
		      'gdb-stack-buffer-name
		      'gdb-frames-mode)

(def-gdb-auto-updated-buffer gdb-stack-buffer
  gdb-invalidate-frames
  "server where\n"
  gdb-info-frames-handler
  gdb-info-frames-custom)

(defun gdb-info-frames-custom ()
  (with-current-buffer (gdb-get-buffer 'gdb-stack-buffer)
    (save-excursion
      (let ((buffer-read-only nil))
	(goto-char (point-min))
	(while (< (point) (point-max))
	  (add-text-properties (point-at-bol) (point-at-eol)
			     '(mouse-face highlight
			       help-echo "mouse-2, RET: Select frame"))
	  (beginning-of-line)
	  (when (and (looking-at "^#\\([0-9]+\\)")
		     (equal (match-string 1) gdb-current-stack-level))
	    (put-text-property (point-at-bol) (point-at-eol)
			       'face '(:inverse-video t)))
	  (forward-line 1))))))

(defun gdb-stack-buffer-name ()
  (with-current-buffer gud-comint-buffer
    (concat "*stack frames of " (gdb-get-target-string) "*")))

(defun gdb-display-stack-buffer ()
  "Display backtrace of current stack."
  (interactive)
  (gdb-display-buffer
   (gdb-get-create-buffer 'gdb-stack-buffer)))

(defun gdb-frame-stack-buffer ()
  "Display backtrace of current stack in a new frame."
  (interactive)
  (let ((special-display-regexps (append special-display-regexps '(".*")))
	(special-display-frame-alist gdb-frame-parameters))
    (display-buffer (gdb-get-create-buffer 'gdb-stack-buffer))))

(defvar gdb-frames-mode-map
  (let ((map (make-sparse-keymap)))
    (suppress-keymap map)
    (define-key map "q" 'kill-this-buffer)
    (define-key map "\r" 'gdb-frames-select)
    (define-key map [mouse-2] 'gdb-frames-select)
    map))

(defun gdb-frames-mode ()
  "Major mode for gdb frames.

\\{gdb-frames-mode-map}"
  (kill-all-local-variables)
  (setq major-mode 'gdb-frames-mode)
  (setq mode-name "Frames")
  (setq buffer-read-only t)
  (use-local-map gdb-frames-mode-map)
  (font-lock-mode -1)
  (run-mode-hooks 'gdb-frames-mode-hook)
  (if (with-current-buffer gud-comint-buffer (eq gud-minor-mode 'gdba))
      'gdb-invalidate-frames
    'gdbmi-invalidate-frames))

(defun gdb-get-frame-number ()
  (save-excursion
    (let* ((pos (re-search-backward "^#*\\([0-9]*\\)" nil t))
	   (n (or (and pos (match-string-no-properties 1)) "0")))
      n)))

(defun gdb-frames-select (&optional event)
  "Select the frame and display the relevant source."
  (interactive (list last-input-event))
  (if event (mouse-set-point event))
  (gdb-enqueue-input
   (list (concat gdb-server-prefix "frame " (gdb-get-frame-number) "\n") 'ignore))
  (gud-display-frame))


;; Threads buffer.  This displays a selectable thread list.
;;
(gdb-set-buffer-rules 'gdb-threads-buffer
		      'gdb-threads-buffer-name
		      'gdb-threads-mode)

(def-gdb-auto-updated-buffer gdb-threads-buffer
  gdb-invalidate-threads
  (concat gdb-server-prefix "info threads\n")
  gdb-info-threads-handler
  gdb-info-threads-custom)

(defun gdb-info-threads-custom ()
  (with-current-buffer (gdb-get-buffer 'gdb-threads-buffer)
    (let ((buffer-read-only nil))
      (goto-char (point-min))
      (while (< (point) (point-max))
	(add-text-properties (point-at-bol) (point-at-eol)
			     '(mouse-face highlight
			       help-echo "mouse-2, RET: select thread"))
	(forward-line 1)))))

(defun gdb-threads-buffer-name ()
  (with-current-buffer gud-comint-buffer
    (concat "*threads of " (gdb-get-target-string) "*")))

(defun gdb-display-threads-buffer ()
  "Display IDs of currently known threads."
  (interactive)
  (gdb-display-buffer
   (gdb-get-create-buffer 'gdb-threads-buffer)))

(defun gdb-frame-threads-buffer ()
  "Display IDs of currently known threads in a new frame."
  (interactive)
  (let ((special-display-regexps (append special-display-regexps '(".*")))
	(special-display-frame-alist gdb-frame-parameters))
    (display-buffer (gdb-get-create-buffer 'gdb-threads-buffer))))

(defvar gdb-threads-mode-map
  (let ((map (make-sparse-keymap)))
    (suppress-keymap map)
    (define-key map "q" 'kill-this-buffer)
    (define-key map "\r" 'gdb-threads-select)
    (define-key map [mouse-2] 'gdb-threads-select)
    map))

(defun gdb-threads-mode ()
  "Major mode for gdb frames.

\\{gdb-threads-mode-map}"
  (kill-all-local-variables)
  (setq major-mode 'gdb-threads-mode)
  (setq mode-name "Threads")
  (setq buffer-read-only t)
  (use-local-map gdb-threads-mode-map)
  (run-mode-hooks 'gdb-threads-mode-hook)
  'gdb-invalidate-threads)

(defun gdb-get-thread-number ()
  (save-excursion
    (re-search-backward "^\\s-*\\([0-9]*\\)" nil t)
    (match-string-no-properties 1)))

(defun gdb-threads-select (&optional event)
  "Select the thread and display the relevant source."
  (interactive (list last-input-event))
  (if event (mouse-set-point event))
  (gdb-enqueue-input
   (list (concat "thread " (gdb-get-thread-number) "\n") 'ignore))
  (gud-display-frame))


;; Registers buffer.
;;
(gdb-set-buffer-rules 'gdb-registers-buffer
		      'gdb-registers-buffer-name
		      'gdb-registers-mode)

(def-gdb-auto-updated-buffer gdb-registers-buffer
  gdb-invalidate-registers
  (concat gdb-server-prefix "info registers\n")
  gdb-info-registers-handler
  gdb-info-registers-custom)

(defun gdb-info-registers-custom ())

(defvar gdb-registers-mode-map
  (let ((map (make-sparse-keymap)))
    (suppress-keymap map)
    (define-key map "q" 'kill-this-buffer)
     map))

(defun gdb-registers-mode ()
  "Major mode for gdb registers.

\\{gdb-registers-mode-map}"
  (kill-all-local-variables)
  (setq major-mode 'gdb-registers-mode)
  (setq mode-name "Registers")
  (setq buffer-read-only t)
  (use-local-map gdb-registers-mode-map)
  (run-mode-hooks 'gdb-registers-mode-hook)
  'gdb-invalidate-registers)

(defun gdb-registers-buffer-name ()
  (with-current-buffer gud-comint-buffer
    (concat "*registers of " (gdb-get-target-string) "*")))

(defun gdb-display-registers-buffer ()
  "Display integer register contents."
  (interactive)
  (gdb-display-buffer
   (gdb-get-create-buffer 'gdb-registers-buffer)))

(defun gdb-frame-registers-buffer ()
  "Display integer register contents in a new frame."
  (interactive)
  (let ((special-display-regexps (append special-display-regexps '(".*")))
	(special-display-frame-alist gdb-frame-parameters))
    (display-buffer (gdb-get-create-buffer 'gdb-registers-buffer))))

;; Memory buffer.
;;
(defcustom gdb-memory-repeat-count 32
  "Number of data items in memory window."
  :type 'integer
  :group 'gud
  :version "22.1")

(defcustom gdb-memory-format "x"
  "Display format of data items in memory window."
  :type '(choice (const :tag "Hexadecimal" "x")
	 	 (const :tag "Signed decimal" "d")
	 	 (const :tag "Unsigned decimal" "u")
		 (const :tag "Octal" "o")
		 (const :tag "Binary" "t"))
  :group 'gud
  :version "22.1")

(defcustom gdb-memory-unit "w"
  "Unit size of data items in memory window."
  :type '(choice (const :tag "Byte" "b")
		 (const :tag "Halfword" "h")
		 (const :tag "Word" "w")
		 (const :tag "Giant word" "g"))
  :group 'gud
  :version "22.1")

(gdb-set-buffer-rules 'gdb-memory-buffer
		      'gdb-memory-buffer-name
		      'gdb-memory-mode)

(def-gdb-auto-updated-buffer gdb-memory-buffer
  gdb-invalidate-memory
  (concat gdb-server-prefix "x/" (number-to-string gdb-memory-repeat-count)
	  gdb-memory-format gdb-memory-unit " " gdb-memory-address "\n")
  gdb-read-memory-handler
  gdb-read-memory-custom)

(defun gdb-read-memory-custom ())

(defvar gdb-memory-mode-map
  (let ((map (make-sparse-keymap)))
    (suppress-keymap map)
    (define-key map "q" 'kill-this-buffer)
     map))

(defun gdb-memory-set-address (event)
  "Set the start memory address."
  (interactive "e")
  (save-selected-window
    (select-window (posn-window (event-start event)))
    (let ((arg (read-from-minibuffer "Memory address: ")))
      (setq gdb-memory-address arg))
    (gdb-invalidate-memory)))

(defun gdb-memory-set-repeat-count (event)
  "Set the number of data items in memory window."
  (interactive "e")
  (save-selected-window
    (select-window (posn-window (event-start event)))
    (let* ((arg (read-from-minibuffer "Repeat count: "))
	  (count (string-to-int arg)))
      (if (< count 0)
	  (error "Non-negative numbers only")
	(customize-set-variable 'gdb-memory-repeat-count count)
	(gdb-invalidate-memory)))))

(defun gdb-memory-format-binary ()
  "Set the display format to binary."
  (interactive)
  (customize-set-variable 'gdb-memory-format "t")
  (gdb-invalidate-memory))

(defun gdb-memory-format-octal ()
  "Set the display format to octal."
  (interactive)
  (customize-set-variable 'gdb-memory-format "o")
  (gdb-invalidate-memory))

(defun gdb-memory-format-unsigned ()
  "Set the display format to unsigned decimal."
  (interactive)
  (customize-set-variable 'gdb-memory-format "u")
  (gdb-invalidate-memory))

(defun gdb-memory-format-signed ()
  "Set the display format to decimal."
  (interactive)
  (customize-set-variable 'gdb-memory-format "d")
  (gdb-invalidate-memory))

(defun gdb-memory-format-hexadecimal ()
  "Set the display format to hexadecimal."
  (interactive)
  (customize-set-variable 'gdb-memory-format "x")
  (gdb-invalidate-memory))

(defvar gdb-memory-format-keymap
  (let ((map (make-sparse-keymap)))
    (define-key map [header-line down-mouse-3] 'gdb-memory-format-menu-1)
    map)
 "Keymap to select format in the header line.")

(defvar gdb-memory-format-menu (make-sparse-keymap "Format")
 "Menu of display formats in the header line.")

(define-key gdb-memory-format-menu [binary]
  '(menu-item "Binary" gdb-memory-format-binary
	      :button (:radio . (equal gdb-memory-format "t"))))
(define-key gdb-memory-format-menu [octal]
  '(menu-item "Octal" gdb-memory-format-octal
	      :button (:radio . (equal gdb-memory-format "o"))))
(define-key gdb-memory-format-menu [unsigned]
  '(menu-item "Unsigned Decimal" gdb-memory-format-unsigned
	      :button (:radio . (equal gdb-memory-format "u"))))
(define-key gdb-memory-format-menu [signed]
  '(menu-item "Signed Decimal" gdb-memory-format-signed
	      :button (:radio . (equal gdb-memory-format "d"))))
(define-key gdb-memory-format-menu [hexadecimal]
  '(menu-item "Hexadecimal" gdb-memory-format-hexadecimal
	      :button (:radio . (equal gdb-memory-format "x"))))

(defun gdb-memory-format-menu (event)
  (interactive "@e")
  (x-popup-menu event gdb-memory-format-menu))

(defun gdb-memory-format-menu-1 (event)
  (interactive "e")
  (save-selected-window
    (select-window (posn-window (event-start event)))
    (let* ((selection (gdb-memory-format-menu event))
	   (binding (and selection (lookup-key gdb-memory-format-menu
					       (vector (car selection))))))
      (if binding (call-interactively binding)))))

(defun gdb-memory-unit-giant ()
  "Set the unit size to giant words (eight bytes)."
  (interactive)
  (customize-set-variable 'gdb-memory-unit "g")
  (gdb-invalidate-memory))

(defun gdb-memory-unit-word ()
  "Set the unit size to words (four bytes)."
  (interactive)
  (customize-set-variable 'gdb-memory-unit "w")
  (gdb-invalidate-memory))

(defun gdb-memory-unit-halfword ()
  "Set the unit size to halfwords (two bytes)."
  (interactive)
  (customize-set-variable 'gdb-memory-unit "h")
  (gdb-invalidate-memory))

(defun gdb-memory-unit-byte ()
  "Set the unit size to bytes."
  (interactive)
  (customize-set-variable 'gdb-memory-unit "b")
  (gdb-invalidate-memory))

(defvar gdb-memory-unit-keymap
  (let ((map (make-sparse-keymap)))
    (define-key map [header-line down-mouse-3] 'gdb-memory-unit-menu-1)
    map)
 "Keymap to select units in the header line.")

(defvar gdb-memory-unit-menu (make-sparse-keymap "Unit")
 "Menu of units in the header line.")

(define-key gdb-memory-unit-menu [giantwords]
  '(menu-item "Giant words" gdb-memory-unit-giant
	      :button (:radio . (equal gdb-memory-unit "g"))))
(define-key gdb-memory-unit-menu [words]
  '(menu-item "Words" gdb-memory-unit-word
	      :button (:radio . (equal gdb-memory-unit "w"))))
(define-key gdb-memory-unit-menu [halfwords]
  '(menu-item "Halfwords" gdb-memory-unit-halfword
	      :button (:radio . (equal gdb-memory-unit "h"))))
(define-key gdb-memory-unit-menu [bytes]
  '(menu-item "Bytes" gdb-memory-unit-byte
	      :button (:radio . (equal gdb-memory-unit "b"))))

(defun gdb-memory-unit-menu (event)
  (interactive "@e")
  (x-popup-menu event gdb-memory-unit-menu))

(defun gdb-memory-unit-menu-1 (event)
  (interactive "e")
  (save-selected-window
    (select-window (posn-window (event-start event)))
    (let* ((selection (gdb-memory-unit-menu event))
	   (binding (and selection (lookup-key gdb-memory-unit-menu
					       (vector (car selection))))))
      (if binding (call-interactively binding)))))

;;from make-mode-line-mouse-map
(defun gdb-make-header-line-mouse-map (mouse function) "\
Return a keymap with single entry for mouse key MOUSE on the header line.
MOUSE is defined to run function FUNCTION with no args in the buffer
corresponding to the mode line clicked."
  (let ((map (make-sparse-keymap)))
    (define-key map (vector 'header-line mouse) function)
    (define-key map (vector 'header-line 'down-mouse-1) 'ignore)
    map))

(defun gdb-memory-mode ()
  "Major mode for examining memory.

\\{gdb-memory-mode-map}"
  (kill-all-local-variables)
  (setq major-mode 'gdb-memory-mode)
  (setq mode-name "Memory")
  (setq buffer-read-only t)
  (use-local-map gdb-memory-mode-map)
  (setq header-line-format
	'(:eval
	  (concat
	   "Read address: "
	   (propertize gdb-memory-address
		       'face font-lock-warning-face
		       'help-echo (purecopy "mouse-1: Set memory address")
		       'local-map (purecopy (gdb-make-header-line-mouse-map
					     'mouse-1
					     #'gdb-memory-set-address)))
	   "  Repeat Count: "
	   (propertize (number-to-string gdb-memory-repeat-count)
		       'face font-lock-warning-face
		       'help-echo (purecopy "mouse-1: Set repeat count")
		       'local-map (purecopy (gdb-make-header-line-mouse-map
					     'mouse-1
					     #'gdb-memory-set-repeat-count)))
	   "  Display Format: "
	   (propertize gdb-memory-format
		       'face font-lock-warning-face
		       'help-echo (purecopy "mouse-3: Select display format")
		       'local-map gdb-memory-format-keymap)
	   "  Unit Size: "
	   (propertize gdb-memory-unit
		       'face font-lock-warning-face
		       'help-echo (purecopy "mouse-3: Select unit size")
		       'local-map gdb-memory-unit-keymap))))
  (run-mode-hooks 'gdb-memory-mode-hook)
  'gdb-invalidate-memory)

(defun gdb-memory-buffer-name ()
  (with-current-buffer gud-comint-buffer
    (concat "*memory of " (gdb-get-target-string) "*")))

(defun gdb-display-memory-buffer ()
  "Display memory contents."
  (interactive)
  (gdb-display-buffer
   (gdb-get-create-buffer 'gdb-memory-buffer)))

(defun gdb-frame-memory-buffer ()
  "Display memory contents in a new frame."
  (interactive)
  (let ((special-display-regexps (append special-display-regexps '(".*")))
	(special-display-frame-alist gdb-frame-parameters))
    (display-buffer (gdb-get-create-buffer 'gdb-memory-buffer))))


;; Locals buffer.
;;
(gdb-set-buffer-rules 'gdb-locals-buffer
		      'gdb-locals-buffer-name
		      'gdb-locals-mode)

(def-gdb-auto-updated-buffer gdb-locals-buffer
  gdb-invalidate-locals
  "server info locals\n"
  gdb-info-locals-handler
  gdb-info-locals-custom)

;; Abbreviate for arrays and structures.
;; These can be expanded using gud-display.
(defun gdb-info-locals-handler nil
  (setq gdb-pending-triggers (delq 'gdb-invalidate-locals
				  gdb-pending-triggers))
  (let ((buf (gdb-get-buffer 'gdb-partial-output-buffer)))
    (with-current-buffer buf
      (goto-char (point-min))
      (while (re-search-forward "^ .*\n" nil t)
	(replace-match "" nil nil))
      (goto-char (point-min))
      (while (re-search-forward "{[-0-9, {}\]*\n" nil t)
	(replace-match "(array);\n" nil nil))
      (goto-char (point-min))
      (while (re-search-forward "{.*=.*\n" nil t)
	(replace-match "(structure);\n" nil nil))))
  (let ((buf (gdb-get-buffer 'gdb-locals-buffer)))
    (and buf (with-current-buffer buf
	       (let ((p (point))
		     (buffer-read-only nil))
		 (delete-region (point-min) (point-max))
		 (insert-buffer-substring (gdb-get-create-buffer
					   'gdb-partial-output-buffer))
		 (goto-char p)))))
  (run-hooks 'gdb-info-locals-hook))

(defun gdb-info-locals-custom ()
  nil)

(defvar gdb-locals-mode-map
  (let ((map (make-sparse-keymap)))
    (suppress-keymap map)
    (define-key map "q" 'kill-this-buffer)
     map))

(defun gdb-locals-mode ()
  "Major mode for gdb locals.

\\{gdb-locals-mode-map}"
  (kill-all-local-variables)
  (setq major-mode 'gdb-locals-mode)
  (setq mode-name (concat "Locals:" gdb-current-frame))
  (setq buffer-read-only t)
  (use-local-map gdb-locals-mode-map)
  (run-mode-hooks 'gdb-locals-mode-hook)
  (if (with-current-buffer gud-comint-buffer (eq gud-minor-mode 'gdba))
      'gdb-invalidate-locals
    'gdbmi-invalidate-locals))

(defun gdb-locals-buffer-name ()
  (with-current-buffer gud-comint-buffer
    (concat "*locals of " (gdb-get-target-string) "*")))

(defun gdb-display-locals-buffer ()
  "Display local variables of current stack and their values."
  (interactive)
  (gdb-display-buffer
   (gdb-get-create-buffer 'gdb-locals-buffer)))

(defun gdb-frame-locals-buffer ()
  "Display local variables of current stack and their values in a new frame."
  (interactive)
  (let ((special-display-regexps (append special-display-regexps '(".*")))
	(special-display-frame-alist gdb-frame-parameters))
    (display-buffer (gdb-get-create-buffer 'gdb-locals-buffer))))


;;;; Window management
(defun gdb-display-buffer (buf &optional size)
  (let ((answer (get-buffer-window buf 0))
	(must-split nil))
    (if answer
	(display-buffer buf)		;Raise the frame if necessary.
      ;; The buffer is not yet displayed.
      (pop-to-buffer gud-comint-buffer)	;Select the right frame.
      (let ((window (get-lru-window)))
	(if window
	    (progn
	      (set-window-buffer window buf)
	      (setq answer window))
	  (setq must-split t)))
      (if must-split
	  (let* ((largest (get-largest-window))
		 (cur-size (window-height largest))
		 (new-size (and size (< size cur-size) (- cur-size size))))
	    (setq answer (split-window largest new-size))
	    (set-window-buffer answer buf)
	    (set-window-dedicated-p answer t)))
      answer)))


;;; Shared keymap initialization:

(let ((menu (make-sparse-keymap "GDB-Windows")))
  (define-key gud-menu-map [displays]
    `(menu-item "GDB-Windows" ,menu :visible (eq gud-minor-mode 'gdba)))
  (define-key menu [gdb] '("Gdb" . gdb-display-gdb-buffer))
  (define-key menu [threads] '("Threads" . gdb-display-threads-buffer))
  (define-key menu [memory] '("Memory" . gdb-display-memory-buffer))
  (define-key menu [assembler] '("Machine" . gdb-display-assembler-buffer))
  (define-key menu [registers] '("Registers" . gdb-display-registers-buffer))
  (define-key menu [locals] '("Locals" . gdb-display-locals-buffer))
  (define-key menu [frames] '("Stack" . gdb-display-stack-buffer))
  (define-key menu [breakpoints] '("Breakpoints" . gdb-display-breakpoints-buffer)))

(let ((menu (make-sparse-keymap "GDB-Frames")))
  (define-key gud-menu-map [frames]
    `(menu-item "GDB-Frames" ,menu :visible (eq gud-minor-mode 'gdba)))
  (define-key menu [gdb] '("Gdb" . gdb-frame-gdb-buffer))
  (define-key menu [threads] '("Threads" . gdb-frame-threads-buffer))
  (define-key menu [memory] '("Memory" . gdb-frame-memory-buffer))
  (define-key menu [assembler] '("Machine" . gdb-frame-assembler-buffer))
  (define-key menu [registers] '("Registers" . gdb-frame-registers-buffer))
  (define-key menu [locals] '("Locals" . gdb-frame-locals-buffer))
  (define-key menu [frames] '("Stack" . gdb-frame-stack-buffer))
  (define-key menu [breakpoints] '("Breakpoints" . gdb-frame-breakpoints-buffer)))

(let ((menu (make-sparse-keymap "GDB-UI")))
  (define-key gud-menu-map [ui]
    `(menu-item "GDB-UI" ,menu :visible (eq gud-minor-mode 'gdba)))
  (define-key menu [gdb-restore-windows]
    '("Restore Window Layout" . gdb-restore-windows))
  (define-key menu [gdb-many-windows]
    (menu-bar-make-toggle gdb-many-windows gdb-many-windows
     "Display Other Windows" "Many windows %s"
     "Toggle display of locals, stack and breakpoint information")))

(defun gdb-frame-gdb-buffer ()
  "Display GUD buffer in a new frame."
  (interactive)
  (select-frame (make-frame gdb-frame-parameters))
  (switch-to-buffer (gdb-get-create-buffer 'gdba))
  (set-window-dedicated-p (selected-window) t))

(defun gdb-display-gdb-buffer ()
  "Display GUD buffer."
  (interactive)
  (gdb-display-buffer
   (gdb-get-create-buffer 'gdba)))

(defvar gdb-main-file nil "Source file from which program execution begins.")

(defcustom gdb-show-main nil
  "Nil means don't display source file containing the main routine."
  :type 'boolean
  :group 'gud
  :version "22.1")

(defun gdb-set-window-buffer (name)
  (set-window-buffer (selected-window) (get-buffer name))
  (set-window-dedicated-p (selected-window) t))

(defun gdb-setup-windows ()
  "Layout the window pattern for gdb-many-windows."
  (gdb-display-locals-buffer)
  (gdb-display-stack-buffer)
  (delete-other-windows)
  (gdb-display-breakpoints-buffer)
  (delete-other-windows)
  ; Don't dedicate.
  (pop-to-buffer gud-comint-buffer)
  (split-window nil ( / ( * (window-height) 3) 4))
  (split-window nil ( / (window-height) 3))
  (split-window-horizontally)
  (other-window 1)
  (gdb-set-window-buffer (gdb-locals-buffer-name))
  (other-window 1)
  (switch-to-buffer
       (if gud-last-last-frame
	   (gud-find-file (car gud-last-last-frame))
	 (gud-find-file gdb-main-file)))
  (when gdb-use-inferior-io-buffer
    (split-window-horizontally)
    (other-window 1)
    (gdb-set-window-buffer (gdb-inferior-io-name)))
  (other-window 1)
  (gdb-set-window-buffer (gdb-stack-buffer-name))
  (split-window-horizontally)
  (other-window 1)
  (gdb-set-window-buffer (gdb-breakpoints-buffer-name))
  (other-window 1))

(defcustom gdb-many-windows nil
  "Nil means just pop up the GUD buffer unless `gdb-show-main' is t.
In this case it starts with two windows: one displaying the GUD
buffer and the other with the source file with the main routine
of the inferior.  Non-nil means display the layout shown for
`gdba'."
  :type 'boolean
  :group 'gud
  :version "22.1")

(defun gdb-many-windows (arg)
  "Toggle the number of windows in the basic arrangement."
  (interactive "P")
  (setq gdb-many-windows
	(if (null arg)
	    (not gdb-many-windows)
	  (> (prefix-numeric-value arg) 0)))
  (condition-case nil
      (gdb-restore-windows)
    (error nil)))

(defun gdb-restore-windows ()
  "Restore the basic arrangement of windows used by gdba.
This arrangement depends on the value of `gdb-many-windows'."
  (interactive)
  (pop-to-buffer gud-comint-buffer)	;Select the right window and frame.
    (delete-other-windows)
  (if gdb-many-windows
      (gdb-setup-windows)
    (split-window)
    (other-window 1)
    (switch-to-buffer
	 (if gud-last-last-frame
	     (gud-find-file (car gud-last-last-frame))
	   (gud-find-file gdb-main-file)))
    (other-window 1)))

(defun gdb-reset ()
  "Exit a debugging session cleanly.
Kills the gdb buffers and resets the source buffers."
  (dolist (buffer (buffer-list))
    (unless (eq buffer gud-comint-buffer)
      (with-current-buffer buffer
	(if (memq gud-minor-mode '(gdbmi gdba))
	    (if (string-match "\\`\\*.+\\*\\'" (buffer-name))
		(kill-buffer nil)
	      (gdb-remove-breakpoint-icons (point-min) (point-max) t)
	      (setq gud-minor-mode nil)
	      (kill-local-variable 'tool-bar-map)
	      (setq gud-running nil))))))
  (when (markerp gdb-overlay-arrow-position)
    (move-marker gdb-overlay-arrow-position nil)
    (setq gdb-overlay-arrow-position nil))
  (setq overlay-arrow-variable-list
	(delq 'gdb-overlay-arrow-position overlay-arrow-variable-list)))

(defun gdb-source-info ()
  "Find the source file where the program starts and displays it with related
buffers."
  (goto-char (point-min))
  (if (and (search-forward "Located in " nil t)
	   (looking-at "\\S-*"))
      (setq gdb-main-file (match-string 0)))
 (if gdb-many-windows
      (gdb-setup-windows)
   (gdb-get-create-buffer 'gdb-breakpoints-buffer)
   (if gdb-show-main
       (let ((pop-up-windows t))
	 (display-buffer (gud-find-file gdb-main-file))))))

(defun gdb-get-location (bptno line flag)
  "Find the directory containing the relevant source file.
Put in buffer and place breakpoint icon."
  (goto-char (point-min))
  (if (search-forward "Located in " nil t)
      (if (looking-at "\\S-*")
	  (push (cons bptno (match-string 0)) gdb-location-list))
    (gdb-resync)
    (push (cons bptno "File not found") gdb-location-list)
    (error "Cannot find source file for breakpoint location.
Add directory to search path for source files using the GDB command, dir."))
  (with-current-buffer
      (find-file-noselect (match-string 0))
    (save-current-buffer
      (set (make-local-variable 'gud-minor-mode) 'gdba)
      (set (make-local-variable 'tool-bar-map) gud-tool-bar-map))
    ;; only want one breakpoint icon at each location
    (save-excursion
      (goto-line (string-to-number line))
      (gdb-put-breakpoint-icon (eq flag ?y) bptno))))

(add-hook 'find-file-hook 'gdb-find-file-hook)

(defun gdb-find-file-hook ()
  (if (and (not gdb-find-file-unhook)
	   ;; in case gud or gdb-ui is just loaded
	   gud-comint-buffer
	   (buffer-name gud-comint-buffer)
	   (with-current-buffer gud-comint-buffer
	     (eq gud-minor-mode 'gdba)))
      (condition-case nil
	(gdb-enqueue-input
	 (list (concat gdb-server-prefix "list "
		       (file-name-nondirectory buffer-file-name)
		       ":1\n")
	       `(lambda () (gdb-set-gud-minor-mode ,(current-buffer)))))
	(error (setq gdb-find-file-unhook t)))))

;;from put-image
(defun gdb-put-string (putstring pos &optional dprop)
  "Put string PUTSTRING in front of POS in the current buffer.
PUTSTRING is displayed by putting an overlay into the current buffer with a
`before-string' STRING that has a `display' property whose value is
PUTSTRING."
  (let ((string (make-string 1 ?x))
	(buffer (current-buffer)))
    (setq putstring (copy-sequence putstring))
    (let ((overlay (make-overlay pos pos buffer))
	  (prop (or dprop
		    (list (list 'margin 'left-margin) putstring))))
      (put-text-property 0 (length string) 'display prop string)
      (overlay-put overlay 'put-break t)
      (overlay-put overlay 'before-string string))))

;;from remove-images
(defun gdb-remove-strings (start end &optional buffer)
  "Remove strings between START and END in BUFFER.
Remove only strings that were put in BUFFER with calls to `gdb-put-string'.
BUFFER nil or omitted means use the current buffer."
  (unless buffer
    (setq buffer (current-buffer)))
  (dolist (overlay (overlays-in start end))
	(when (overlay-get overlay 'put-break)
	  (delete-overlay overlay))))

(defun gdb-put-breakpoint-icon (enabled bptno)
  (let ((start (progn (beginning-of-line) (- (point) 1)))
	(end (progn (end-of-line) (+ (point) 1)))
	(putstring (if enabled "B" "b")))
    (add-text-properties
     0 1 '(help-echo "mouse-1: set/clear bkpt, mouse-3: enable/disable bkpt")
     putstring)
    (if enabled (add-text-properties
		 0 1 `(gdb-bptno ,bptno gdb-enabled t) putstring)
      (add-text-properties
       0 1 `(gdb-bptno ,bptno gdb-enabled nil) putstring))
    (gdb-remove-breakpoint-icons start end)
    (if (display-images-p)
	(if (>= (car (window-fringes)) 8)
	    (gdb-put-string
	     nil (1+ start)
	     `(left-fringe breakpoint
			   ,(if enabled
				'breakpoint-enabled-bitmap-face
			      'breakpoint-disabled-bitmap-face)))
	  (when (< left-margin-width 2)
	    (save-current-buffer
	      (setq left-margin-width 2)
	      (if (get-buffer-window (current-buffer) 0)
		  (set-window-margins
		   (get-buffer-window (current-buffer) 0)
		   left-margin-width right-margin-width))))
	  (put-image
	   (if enabled
	       (or breakpoint-enabled-icon
		   (setq breakpoint-enabled-icon
			 (find-image `((:type xpm :data
					      ,breakpoint-xpm-data
					      :ascent 100 :pointer hand)
				       (:type pbm :data
					      ,breakpoint-enabled-pbm-data
					      :ascent 100 :pointer hand)))))
	     (or breakpoint-disabled-icon
		 (setq breakpoint-disabled-icon
		       (find-image `((:type xpm :data
					    ,breakpoint-xpm-data
					    :conversion disabled
					    :ascent 100)
				     (:type pbm :data
					    ,breakpoint-disabled-pbm-data
					    :ascent 100))))))
	   (+ start 1)
	   putstring
	   'left-margin))
      (when (< left-margin-width 2)
	(save-current-buffer
	  (setq left-margin-width 2)
	  (if (get-buffer-window (current-buffer) 0)
	      (set-window-margins
	       (get-buffer-window (current-buffer) 0)
	       left-margin-width right-margin-width))))
      (gdb-put-string putstring (1+ start)))))

(defun gdb-remove-breakpoint-icons (start end &optional remove-margin)
  (gdb-remove-strings start end)
  (if (display-images-p)
      (remove-images start end))
  (when remove-margin
    (setq left-margin-width 0)
    (if (get-buffer-window (current-buffer) 0)
	(set-window-margins
	 (get-buffer-window (current-buffer) 0)
	 left-margin-width right-margin-width))))


;;
;; Assembler buffer.
;;
(gdb-set-buffer-rules 'gdb-assembler-buffer
		      'gdb-assembler-buffer-name
		      'gdb-assembler-mode)

(def-gdb-auto-updated-buffer gdb-assembler-buffer
  gdb-invalidate-assembler
  (concat gdb-server-prefix "disassemble " gdb-current-address "\n")
  gdb-assembler-handler
  gdb-assembler-custom)

(defun gdb-assembler-custom ()
  (let ((buffer (gdb-get-buffer 'gdb-assembler-buffer))
	(pos 1) (address) (flag) (bptno))
    (with-current-buffer buffer
      (if (not (equal gdb-current-address "main"))
	  (progn
	    (goto-char (point-min))
	    (if (re-search-forward gdb-current-address nil t)
		(progn
		  (setq pos (point))
		  (beginning-of-line)
		  (or gdb-overlay-arrow-position
		      (setq gdb-overlay-arrow-position (make-marker)))
		  (set-marker gdb-overlay-arrow-position
			      (point) (current-buffer))))))
      ;; remove all breakpoint-icons in assembler buffer before updating.
      (gdb-remove-breakpoint-icons (point-min) (point-max)))
    (with-current-buffer (gdb-get-buffer 'gdb-breakpoints-buffer)
      (goto-char (point-min))
      (while (< (point) (- (point-max) 1))
	(forward-line 1)
	(if (looking-at "[^\t].*breakpoint")
	    (progn
	      (looking-at
	       "\\([0-9]+\\)\\s-+\\S-+\\s-+\\S-+\\s-+\\(.\\)\\s-+0x\\(\\S-+\\)")
	      (setq bptno (match-string 1))
	      (setq flag (char-after (match-beginning 2)))
	      (setq address (match-string 3))
	      ;; remove leading 0s from output of info break.
	      (if (string-match "^0+\\(.*\\)" address)
		  (setq address (match-string 1 address)))
	      (with-current-buffer buffer
		  (goto-char (point-min))
		  (if (re-search-forward address nil t)
		      (gdb-put-breakpoint-icon (eq flag ?y) bptno)))))))
    (if (not (equal gdb-current-address "main"))
	(set-window-point (get-buffer-window buffer 0) pos))))

(defvar gdb-assembler-mode-map
  (let ((map (make-sparse-keymap)))
    (suppress-keymap map)
    (define-key map "q" 'kill-this-buffer)
     map))

(defvar gdb-assembler-font-lock-keywords
  '(;; <__function.name+n>
    ("<\\(\\(\\sw\\|[_.]\\)+\\)\\(\\+[0-9]+\\)?>"
     (1 font-lock-function-name-face))
    ;; 0xNNNNNNNN <__function.name+n>: opcode
    ("^0x[0-9a-f]+ \\(<\\(\\(\\sw\\|[_.]\\)+\\)\\+[0-9]+>\\)?:[ \t]+\\(\\sw+\\)"
     (4 font-lock-keyword-face))
    ;; %register(at least i386)
    ("%\\sw+" . font-lock-variable-name-face)
    ("^\\(Dump of assembler code for function\\) \\(.+\\):"
     (1 font-lock-comment-face)
     (2 font-lock-function-name-face))
    ("^\\(End of assembler dump\\.\\)" . font-lock-comment-face))
  "Font lock keywords used in `gdb-assembler-mode'.")

(defun gdb-assembler-mode ()
  "Major mode for viewing code assembler.

\\{gdb-assembler-mode-map}"
  (kill-all-local-variables)
  (setq major-mode 'gdb-assembler-mode)
  (setq mode-name "Machine")
  (setq gdb-overlay-arrow-position nil)
  (add-to-list 'overlay-arrow-variable-list 'gdb-overlay-arrow-position)
  (put 'gdb-overlay-arrow-position 'overlay-arrow-string "=>")
  (setq fringes-outside-margins t)
  (setq buffer-read-only t)
  (use-local-map gdb-assembler-mode-map)
  (gdb-invalidate-assembler)
  (set (make-local-variable 'font-lock-defaults)
       '(gdb-assembler-font-lock-keywords))
  (run-mode-hooks 'gdb-assembler-mode-hook)
  'gdb-invalidate-assembler)

(defun gdb-assembler-buffer-name ()
  (with-current-buffer gud-comint-buffer
    (concat "*Machine Code " (gdb-get-target-string) "*")))

(defun gdb-display-assembler-buffer ()
  "Display disassembly view."
  (interactive)
  (gdb-display-buffer
   (gdb-get-create-buffer 'gdb-assembler-buffer)))

(defun gdb-frame-assembler-buffer ()
  "Display disassembly view in a new frame."
  (interactive)
  (let ((special-display-regexps (append special-display-regexps '(".*")))
	(special-display-frame-alist gdb-frame-parameters))
    (display-buffer (gdb-get-create-buffer 'gdb-assembler-buffer))))

;; modified because if gdb-current-address has changed value a new command
;; must be enqueued to update the buffer with the new output
(defun gdb-invalidate-assembler (&optional ignored)
  (if (gdb-get-buffer 'gdb-assembler-buffer)
      (progn
	(unless (string-equal gdb-current-frame gdb-previous-frame)
	  (if (or (not (member 'gdb-invalidate-assembler
			       gdb-pending-triggers))
		  (not (string-equal gdb-current-address
				     gdb-previous-address)))
	  (progn
	    ;; take previous disassemble command off the queue
	    (with-current-buffer gud-comint-buffer
	      (let ((queue gdb-input-queue))
		(dolist (item queue)
		  (if (equal (cdr item) '(gdb-assembler-handler))
		      (setq gdb-input-queue
			    (delete item gdb-input-queue))))))
	    (gdb-enqueue-input
	     (list (concat gdb-server-prefix "disassemble " gdb-current-address "\n")
		   'gdb-assembler-handler))
	    (push 'gdb-invalidate-assembler gdb-pending-triggers)
	    (setq gdb-previous-address gdb-current-address)
	    (setq gdb-previous-frame gdb-current-frame)))))))

(defun gdb-get-current-frame ()
  (if (not (member 'gdb-get-current-frame gdb-pending-triggers))
      (progn
	(gdb-enqueue-input
	 (list (concat gdb-server-prefix "info frame\n") 'gdb-frame-handler))
	(push 'gdb-get-current-frame
	       gdb-pending-triggers))))

(defun gdb-frame-handler ()
  (setq gdb-pending-triggers
   (delq 'gdb-get-current-frame gdb-pending-triggers))
  (with-current-buffer (gdb-get-create-buffer 'gdb-partial-output-buffer)
    (goto-char (point-min))
    (if (looking-at "Stack level \\([0-9]+\\)")
	(setq gdb-current-stack-level (match-string 1)))
    (forward-line)
    (if (looking-at ".*=\\s-+0x\\(\\S-*\\)\\s-+in\\s-+\\(\\S-*?\\);? ")
	(progn
	  (setq gdb-current-frame (match-string 2))
	  (if (gdb-get-buffer 'gdb-locals-buffer)
	      (with-current-buffer (gdb-get-buffer 'gdb-locals-buffer)
		(setq mode-name (concat "Locals:" gdb-current-frame))))
	  (let ((address (match-string 1)))
	    ;; remove leading 0s from output of info frame command.
	    (if (string-match "^0+\\(.*\\)" address)
		(setq gdb-current-address
		      (concat "0x" (match-string 1 address)))
	      (setq gdb-current-address (concat "0x" address))))
	  (if (not (re-search-forward "(\\S-*:[0-9]*);" nil t))
		;;update with new frame for machine code if necessary
		(gdb-invalidate-assembler)))))
    (if (re-search-forward " source language \\(\\S-*\\)\." nil t)
	(setq gdb-current-language (match-string 1))))

(provide 'gdb-ui)

;; arch-tag: e9fb00c5-74ef-469f-a088-37384caae352
;;; gdb-ui.el ends here