File: debugger.cpp

package info (click to toggle)
kdbg 1.2.4-2
  • links: PTS
  • area: main
  • in suites: woody
  • size: 2,504 kB
  • ctags: 1,945
  • sloc: cpp: 15,961; sh: 8,183; makefile: 481; perl: 71; ansic: 16
file content (1943 lines) | stat: -rw-r--r-- 51,088 bytes parent folder | download
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
// $Id: debugger.cpp,v 1.106.2.1 2002/01/01 17:01:51 jsixt Exp $

// Copyright by Johannes Sixt
// This file is under GPL, the GNU General Public Licence

#include "debugger.h"
#include "dbgdriver.h"
#include "pgmargs.h"
#include "typetable.h"
#include "exprwnd.h"
#include "pgmsettings.h"
#include "valarray.h"
#include <qregexp.h>
#include <qfileinfo.h>
#include <qlistbox.h>
#include <kapp.h>
#include <ksimpleconfig.h>
#include <kconfig.h>
#if QT_VERSION >= 200
#include <klocale.h>			/* i18n */
#include <kmessagebox.h>
#else
#include <kmsgbox.h>
#endif
#include <ctype.h>
#include <stdlib.h>			/* strtol, atoi */
#ifdef HAVE_UNISTD_H
#include <unistd.h>			/* sleep(3) */
#endif
#include "mydebug.h"


KDebugger::KDebugger(QWidget* parent,
		     ExprWnd* localVars,
		     ExprWnd* watchVars,
		     QListBox* backtrace,
		     DebuggerDriver* driver
		     ) :
	QObject(parent, "debugger"),
	m_ttyLevel(ttyFull),
	m_memoryFormat(MDTword | MDThex),
	m_haveExecutable(false),
	m_programActive(false),
	m_programRunning(false),
	m_sharedLibsListed(false),
	m_typeTable(0),
	m_programConfig(0),
	m_d(driver),
	m_localVariables(*localVars),
	m_watchVariables(*watchVars),
	m_btWindow(*backtrace),
	m_animationTimer(this),
	m_animationInterval(0)
{
    m_envVars.setAutoDelete(true);

    connect(&m_localVariables, SIGNAL(expanding(KTreeViewItem*,bool&)),
	    SLOT(slotLocalsExpanding(KTreeViewItem*,bool&)));
    connect(&m_watchVariables, SIGNAL(expanding(KTreeViewItem*,bool&)),
	    SLOT(slotWatchExpanding(KTreeViewItem*,bool&)));

    connect(&m_btWindow, SIGNAL(highlighted(int)), SLOT(gotoFrame(int)));

    connect(m_d, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)),
	    this, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)));

    // debugger process
    connect(m_d, SIGNAL(processExited(KProcess*)), SLOT(gdbExited(KProcess*)));
    connect(m_d, SIGNAL(commandReceived(CmdQueueItem*,const char*)),
	    SLOT(parse(CmdQueueItem*,const char*)));
    connect(m_d, SIGNAL(wroteStdin(KProcess*)), SIGNAL(updateUI()));
    connect(m_d, SIGNAL(inferiorRunning()), SLOT(slotInferiorRunning()));
    connect(m_d, SIGNAL(enterIdleState()), SLOT(backgroundUpdate()));
    connect(m_d, SIGNAL(enterIdleState()), SIGNAL(updateUI()));

    // animation
    connect(&m_animationTimer, SIGNAL(timeout()), SIGNAL(animationTimeout()));
    // special update of animation
    connect(this, SIGNAL(updateUI()), SLOT(slotUpdateAnimation()));

    emit updateUI();
}

KDebugger::~KDebugger()
{
    if (m_programConfig != 0) {
	saveProgramSettings();
	m_programConfig->sync();
	delete m_programConfig;
    }
    // delete breakpoint objects
    for (int i = m_brkpts.size()-1; i >= 0; i--) {
	delete m_brkpts[i];
    }

    delete m_typeTable;
}


void KDebugger::saveSettings(KConfig* /*config*/)
{
}

void KDebugger::restoreSettings(KConfig* /*config*/)
{
}


//////////////////////////////////////////////////////////////////////
// external interface

const char GeneralGroup[] = "General";
const char DebuggerCmdStr[] = "DebuggerCmdStr";
const char TTYLevelEntry[] = "TTYLevel";

bool KDebugger::debugProgram(const QString& name)
{
    if (m_d->isRunning())
    {
	QApplication::setOverrideCursor(waitCursor);

	stopDriver();

	QApplication::restoreOverrideCursor();

	if (m_d->isRunning() || m_haveExecutable) {
	    /* timed out! We can't really do anything useful now */
	    TRACE("timed out while waiting for gdb to die!");
	    return false;
	}
    }

    // create the program settings object
    openProgramConfig(name);

    // get debugger command from per-program settings
    if (m_programConfig != 0) {
	m_programConfig->setGroup(GeneralGroup);
	m_debuggerCmd = m_programConfig->readEntry(DebuggerCmdStr);
	// get terminal emulation level
	m_ttyLevel = TTYLevel(m_programConfig->readNumEntry(TTYLevelEntry, ttyFull));
    }
    // the rest is read in later in the handler of DCexecutable

    if (!startDriver()) {
	TRACE("startDriver failed");
	return false;
    }

    TRACE("before file cmd");
    m_d->executeCmd(DCexecutable, name);
    m_executable = name;

    // set remote target
    if (!m_remoteDevice.isEmpty()) {
	m_d->executeCmd(DCtargetremote, m_remoteDevice);
	m_d->queueCmd(DCbt, DebuggerDriver::QMoverride);
	m_d->queueCmd(DCframe, 0, DebuggerDriver::QMnormal);
	m_programActive = true;
	m_haveExecutable = true;
    }

    // create a type table
    m_typeTable = new ProgramTypeTable;
    m_sharedLibsListed = false;

    emit updateUI();

    return true;
}

void KDebugger::shutdown()
{
    // shut down debugger driver
    if (m_d->isRunning())
    {
	stopDriver();
    }
}

void KDebugger::useCoreFile(QString corefile, bool batch)
{
    m_corefile = corefile;
    if (!batch) {
	CmdQueueItem* cmd = loadCoreFile();
	cmd->m_byUser = true;
    }
}

void KDebugger::programRun()
{
    if (!isReady())
	return;

    // when program is active, but not a core file, continue
    // otherwise run the program
    if (m_programActive && m_corefile.isEmpty()) {
	// gdb command: continue
	m_d->executeCmd(DCcont, true);
    } else {
	// gdb command: run
	m_d->executeCmd(DCrun, true);
	m_corefile = QString();
	m_programActive = true;
    }
    m_programRunning = true;
}

void KDebugger::attachProgram(const QString& pid)
{
    if (!isReady())
	return;

    m_attachedPid = pid;
    TRACE("Attaching to " + m_attachedPid);
    m_d->executeCmd(DCattach, m_attachedPid);
    m_programActive = true;
    m_programRunning = true;
}

void KDebugger::programRunAgain()
{
    if (canSingleStep()) {
	m_d->executeCmd(DCrun, true);
	m_corefile = QString();
	m_programRunning = true;
    }
}

void KDebugger::programStep(bool byInsn)
{
    if (canSingleStep()) {
	m_d->executeCmd(byInsn ? DCstepi : DCstep, true);
	m_programRunning = true;
    }
}

void KDebugger::programNext(bool byInsn)
{
    if (canSingleStep()) {
	m_d->executeCmd(byInsn ? DCnexti : DCnext, true);
	m_programRunning = true;
    }
}

void KDebugger::programFinish()
{
    if (canSingleStep()) {
	m_d->executeCmd(DCfinish, true);
	m_programRunning = true;
    }
}

void KDebugger::programKill()
{
    if (haveExecutable() && isProgramActive()) {
	if (m_programRunning) {
	    m_d->interruptInferior();
	}
	// this is an emergency command; flush queues
	m_d->flushCommands(true);
	m_d->executeCmd(DCkill, true);
    }
}

bool KDebugger::runUntil(const QString& fileName, int lineNo)
{
    if (isReady() && m_programActive && !m_programRunning) {
	// strip off directory part of file name
	QString file = fileName;
#if QT_VERSION < 200
	file.detach();
#endif
	int offset = file.findRev("/");
	if (offset >= 0) {
	    file.remove(0, offset+1);
	}
	m_d->executeCmd(DCuntil, file, lineNo, true);
	m_programRunning = true;
	return true;
    } else {
	return false;
    }
}

void KDebugger::programBreak()
{
    if (m_haveExecutable && m_programRunning) {
	m_d->interruptInferior();
    }
}

void KDebugger::programArgs(QWidget* parent)
{
    if (m_haveExecutable) {
	PgmArgs dlg(parent, m_executable, m_envVars);
	dlg.setArgs(m_programArgs);
	dlg.setWd(m_programWD);
	if (dlg.exec()) {
	    updateProgEnvironment(dlg.args(), dlg.wd(), dlg.envVars());
	}
    }
}

void KDebugger::programSettings(QWidget* parent)
{
    if (!m_haveExecutable)
	return;

    ProgramSettings dlg(parent, m_executable);

    dlg.m_chooseDriver.setDebuggerCmd(m_debuggerCmd);
    dlg.m_output.setTTYLevel(m_ttyLevel);

    if (dlg.exec() == QDialog::Accepted)
    {
	m_debuggerCmd = dlg.m_chooseDriver.debuggerCmd();
	m_ttyLevel = TTYLevel(dlg.m_output.ttyLevel());
    }
}

bool KDebugger::setBreakpoint(QString file, int lineNo,
			      const DbgAddr& address, bool temporary)
{
    if (!isReady()) {
	return false;
    }

    Breakpoint* bp = breakpointByFilePos(file, lineNo, address);
    if (bp == 0)
    {
	/*
	 * No such breakpoint, so set a new one. If we have an address, we
	 * set the breakpoint exactly there. Otherwise we use the file name
	 * plus line no.
	 */
	if (address.isEmpty())
	{
	    // strip off directory part of file name
#if QT_VERSION < 200
	    file.detach();
#endif
	    int offset = file.findRev("/");
	    if (offset >= 0) {
		file.remove(0, offset+1);
	    }
	    m_d->executeCmd(temporary ? DCtbreakline : DCbreakline,
			    file, lineNo);
	}
	else
	{
	    m_d->executeCmd(temporary ? DCtbreakaddr : DCbreakaddr,
			    address.asString());
	}
    }
    else
    {
	/*
	 * If the breakpoint is disabled, enable it; if it's enabled,
	 * delete that breakpoint.
	 */
	if (bp->enabled) {
	    m_d->executeCmd(DCdelete, bp->id);
	} else {
	    m_d->executeCmd(DCenable, bp->id);
	}
    }
    return true;
}

bool KDebugger::enableDisableBreakpoint(QString file, int lineNo,
					const DbgAddr& address)
{
    if (!isReady()) {
	return false;
    }

    Breakpoint* bp = breakpointByFilePos(file, lineNo, address);
    if (bp == 0)
	return true;

    // toggle enabled/disabled state
    if (bp->enabled) {
	m_d->executeCmd(DCdisable, bp->id);
    } else {
	m_d->executeCmd(DCenable, bp->id);
    }
    return true;
}

bool KDebugger::canSingleStep()
{
    return isReady() && m_programActive && !m_programRunning;
}

bool KDebugger::canChangeBreakpoints()
{
    return isReady() && !m_programRunning;
}

bool KDebugger::isReady() const 
{
    return m_haveExecutable &&
	m_d->canExecuteImmediately();
}

bool KDebugger::isIdle() const
{
    return m_d->isIdle();
}


//////////////////////////////////////////////////////////
// debugger driver

bool KDebugger::startDriver()
{
    emit debuggerStarting();		/* must set m_inferiorTerminal */

    /*
     * If the per-program command string is empty, use the global setting
     * (which might also be empty, in which case the driver uses its
     * default).
     */
    QString debuggerCmd = m_debuggerCmd.isEmpty()  ?
	m_generalDebuggerCmd  :  m_debuggerCmd;
    m_explicitKill = false;
    if (!m_d->startup(debuggerCmd)) {
	return false;
    }

    /*
     * If we have an output terminal, we use it. Otherwise we will run the
     * program with input and output redirected to /dev/null. Other
     * redirections are also necessary depending on the tty emulation
     * level.
     */
    int redirect = RDNstdin|RDNstdout|RDNstderr;	/* redirect everything */
    if (!m_inferiorTerminal.isEmpty()) {
	switch (m_ttyLevel) {
	default:
	case ttyNone:
	    // redirect everything
	    break;
	case ttySimpleOutputOnly:
	    redirect = RDNstdin;
	    break;
	case ttyFull:
	    redirect = 0;
	    break;
	}
    }
    m_d->executeCmd(DCtty, m_inferiorTerminal, redirect);

    return true;
}

void KDebugger::stopDriver()
{
    m_explicitKill = true;

    if (m_attachedPid.isEmpty()) {
	m_d->terminate();
    } else {
	m_d->detachAndTerminate();
    }

    /*
     * We MUST wait until the slot gdbExited() has been called. But to
     * avoid a deadlock, we wait only for some certain maximum time. Should
     * this timeout be reached, the only reasonable thing one could do then
     * is exiting kdbg.
     */
    kapp->processEvents(1000);		/* ideally, this will already shut it down */
    int maxTime = 20;			/* about 20 seconds */
    while (m_haveExecutable && maxTime > 0) {
	// give gdb time to die (and send a SIGCLD)
	::sleep(1);
	--maxTime;
	kapp->processEvents(1000);
    }
}

void KDebugger::gdbExited(KProcess*)
{
    /*
     * Save settings, but only if gdb has already processed "info line
     * main", otherwise we would save an empty config file, because it
     * isn't read in until then!
     */
    if (m_programConfig != 0) {
	if (m_haveExecutable) {
	    saveProgramSettings();
	    m_programConfig->sync();
	}
	delete m_programConfig;
	m_programConfig = 0;
    }

    // erase types
    delete m_typeTable;
    m_typeTable = 0;

    if (m_explicitKill) {
	TRACE("gdb exited normally");
    } else {
	QString msg = i18n("gdb exited unexpectedly.\n"
			   "Restart the session (e.g. with File|Executable).");
#if QT_VERSION < 200
	KMsgBox::message(parentWidget(), kapp->appName(), msg, KMsgBox::EXCLAMATION);
#else
	KMessageBox::error(parentWidget(), msg);
#endif
    }

    // reset state
    m_haveExecutable = false;
    m_executable = "";
    m_programActive = false;
    m_programRunning = false;
    m_explicitKill = false;
    m_debuggerCmd = QString();		/* use global setting at next start! */
    m_attachedPid = QString();		/* we are no longer attached to a process */
    m_ttyLevel = ttyFull;

    // stop gear wheel and erase PC
    stopAnimation();
    emit updatePC(QString(), -1, DbgAddr(), 0);
}

void KDebugger::openProgramConfig(const QString& name)
{
    ASSERT(m_programConfig == 0);

    QFileInfo fi(name);
    QString pgmConfigFile = fi.dirPath(true);
    if (!pgmConfigFile.isEmpty()) {
	pgmConfigFile += '/';
    }
    pgmConfigFile += ".kdbgrc." + fi.fileName();
    TRACE("program config file = " + pgmConfigFile);
    // check whether we can write to the file
    QFile file(pgmConfigFile);
    bool readonly = true;
    bool openit = true;
    if (file.open(IO_ReadWrite)) {	/* don't truncate! */
	readonly = false;
	// the file exists now
    } else if (!file.open(IO_ReadOnly)) {
	/* file does not exist and cannot be created: don't use it */
	openit = false;
    }
    if (openit) {
	m_programConfig = new KSimpleConfig(pgmConfigFile, readonly);
    }
}

const char EnvironmentGroup[] = "Environment";
const char WatchGroup[] = "Watches";
const char FileVersion[] = "FileVersion";
const char ProgramArgs[] = "ProgramArgs";
const char WorkingDirectory[] = "WorkingDirectory";
const char Variable[] = "Var%d";
const char Value[] = "Value%d";
const char ExprFmt[] = "Expr%d";

void KDebugger::saveProgramSettings()
{
    ASSERT(m_programConfig != 0);
    m_programConfig->setGroup(GeneralGroup);
    m_programConfig->writeEntry(FileVersion, 1);
    m_programConfig->writeEntry(ProgramArgs, m_programArgs);
    m_programConfig->writeEntry(WorkingDirectory, m_programWD);
    m_programConfig->writeEntry(DebuggerCmdStr, m_debuggerCmd);
    m_programConfig->writeEntry(TTYLevelEntry, int(m_ttyLevel));

    // write environment variables
    m_programConfig->deleteGroup(EnvironmentGroup);
    m_programConfig->setGroup(EnvironmentGroup);
    QDictIterator<EnvVar> it = m_envVars;
    EnvVar* var;
    QString varName;
    QString varValue;
    for (int i = 0; (var = it) != 0; ++it, ++i) {
	varName.sprintf(Variable, i);
	varValue.sprintf(Value, i);
	m_programConfig->writeEntry(varName, it.currentKey());
	m_programConfig->writeEntry(varValue, var->value);
    }

    saveBreakpoints(m_programConfig);

    // watch expressions
    // first get rid of whatever was in this group
    m_programConfig->deleteGroup(WatchGroup);
    // then start a new group
    m_programConfig->setGroup(WatchGroup);
    KTreeViewItem* item = m_watchVariables.itemAt(0);
    int watchNum = 0;
    for (; item != 0; item = item->getSibling(), ++watchNum) {
	varName.sprintf(ExprFmt, watchNum);
	m_programConfig->writeEntry(varName, item->getText());
    }

    // give others a chance
    emit saveProgramSpecific(m_programConfig);
}

void KDebugger::restoreProgramSettings()
{
    ASSERT(m_programConfig != 0);
    m_programConfig->setGroup(GeneralGroup);
    /*
     * We ignore file version for now we will use it in the future to
     * distinguish different versions of this configuration file.
     */
    m_debuggerCmd = m_programConfig->readEntry(DebuggerCmdStr);
    // m_ttyLevel has been read in already
    QString pgmArgs = m_programConfig->readEntry(ProgramArgs);
    QString pgmWd = m_programConfig->readEntry(WorkingDirectory);

    // read environment variables
    m_programConfig->setGroup(EnvironmentGroup);
    m_envVars.clear();
    QDict<EnvVar> pgmVars;
    EnvVar* var;
    QString varName;
    QString varValue;
    for (int i = 0;; ++i) {
	varName.sprintf(Variable, i);
	varValue.sprintf(Value, i);
	if (!m_programConfig->hasKey(varName)) {
	    /* entry not present, assume that we've hit them all */
	    break;
	}
	QString name = m_programConfig->readEntry(varName);
	if (name.isEmpty()) {
	    // skip empty names
	    continue;
	}
	var = new EnvVar;
	var->value = m_programConfig->readEntry(varValue);
	var->status = EnvVar::EVnew;
	pgmVars.insert(name, var);
    }

    updateProgEnvironment(pgmArgs, pgmWd, pgmVars);

    restoreBreakpoints(m_programConfig);

    // watch expressions
    m_programConfig->setGroup(WatchGroup);
    m_watchVariables.clear();
    for (int i = 0;; ++i) {
	varName.sprintf(ExprFmt, i);
	if (!m_programConfig->hasKey(varName)) {
	    /* entry not present, assume that we've hit them all */
	    break;
	}
	QString expr = m_programConfig->readEntry(varName);
	if (expr.isEmpty()) {
	    // skip empty expressions
	    continue;
	}
	addWatch(expr);
    }

    // give others a chance
    emit restoreProgramSpecific(m_programConfig);
}

/*
 * Breakpoints are saved one per group.
 */
const char BPGroup[] = "Breakpoint %d";
const char File[] = "File";
const char Line[] = "Line";
const char Address[] = "Address";
const char Temporary[] = "Temporary";
const char Enabled[] = "Enabled";
const char Condition[] = "Condition";

void KDebugger::saveBreakpoints(KSimpleConfig* config)
{
    QString groupName;
    int i = 0;
    for (uint j = 0; j < m_brkpts.size(); j++) {
	Breakpoint* bp = m_brkpts[j];
	if (bp->type == Breakpoint::watchpoint)
	    continue;			/* don't save watchpoints */
	groupName.sprintf(BPGroup, i++);
	config->setGroup(groupName);
	if (!bp->fileName.isEmpty()) {
	    config->writeEntry(File, bp->fileName);
	    config->writeEntry(Line, bp->lineNo);
	    /*
	     * Addresses are hardly correct across sessions, so we remove
	     * it since we have a file name and line number.
	     */
	    config->deleteEntry(Address, false);
	} else {
	    config->writeEntry(Address, bp->address.asString());
	    /* remove remmants */
	    config->deleteEntry(File, false);
	    config->deleteEntry(Line, false);
	}
	config->writeEntry(Temporary, bp->temporary);
	config->writeEntry(Enabled, bp->enabled);
	if (bp->condition.isEmpty())
	    config->deleteEntry(Condition, false);
	else
	    config->writeEntry(Condition, bp->condition);
	// we do not save the ignore count
    }
    // delete remaining groups
    // we recognize that a group is present if there is an Enabled entry
    for (;; i++) {
	groupName.sprintf(BPGroup, i);
	config->setGroup(groupName);
	if (!config->hasKey(Enabled)) {
	    /* group not present, assume that we've hit them all */
	    break;
	}
	config->deleteGroup(groupName);
    }
}

void KDebugger::restoreBreakpoints(KSimpleConfig* config)
{
    QString groupName;
    QString fileName;
    QString address;
    int lineNo;
    bool enabled, temporary;
    QString condition;
    /*
     * We recognize the end of the list if there is no Enabled entry
     * present.
     */
    for (int i = 0;; i++) {
	groupName.sprintf(BPGroup, i);
	config->setGroup(groupName);
	if (!config->hasKey(Enabled)) {
	    /* group not present, assume that we've hit them all */
	    break;
	}
	fileName = config->readEntry(File);
	lineNo = config->readNumEntry(Line, -1);
	address = config->readEntry(Address);
	if ((fileName.isEmpty() || lineNo < 0) && address.isEmpty())
	    continue;
	enabled = config->readBoolEntry(Enabled, true);
	temporary = config->readBoolEntry(Temporary, false);
	condition = config->readEntry(Condition);
	/*
	 * Add the breakpoint. We assume that we have started a new
	 * instance of gdb, because we assign the breakpoint ids ourselves,
	 * starting with 1. Then we use this id to disable the breakpoint,
	 * if necessary. If this assignment of ids doesn't work, (maybe
	 * because this isn't a fresh gdb at all), we disable the wrong
	 * breakpoint! Oh well... for now it works.
	 */
	if (!fileName.isEmpty()) {
	    m_d->executeCmd(temporary ? DCtbreakline : DCbreakline,
			    fileName, lineNo);
	} else {
	    m_d->executeCmd(temporary ? DCtbreakaddr : DCbreakaddr,
			    address);
	}
	if (!enabled) {
	    m_d->executeCmd(DCdisable, i+1);
	}
	if (!condition.isEmpty()) {
	    m_d->executeCmd(DCcondition, condition, i+1);
	}
    }
    m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverride);
}


// parse output of command cmd
void KDebugger::parse(CmdQueueItem* cmd, const char* output)
{
    ASSERT(cmd != 0);			/* queue mustn't be empty */

    TRACE(QString(__PRETTY_FUNCTION__) + " parsing " + output);

    switch (cmd->m_cmd) {
    case DCtargetremote:
	// the output (if any) is uninteresting
    case DCsetargs:
    case DCtty:
	// there is no output
    case DCsetenv:
    case DCunsetenv:
	/* if value is empty, we see output, but we don't care */
	break;
    case DCcd:
	/* display gdb's message in the status bar */
	m_d->parseChangeWD(output, m_statusMessage);
	emit updateStatusMessage();
	break;
    case DCinitialize:
	break;
    case DCexecutable:
	if (m_d->parseChangeExecutable(output, m_statusMessage))
	{
	    // success; restore breakpoints etc.
	    if (m_programConfig != 0) {
		restoreProgramSettings();
	    }
	    // load file containing main() or core file
	    if (m_corefile.isEmpty()) {
		if (m_remoteDevice.isEmpty())
		    m_d->queueCmd(DCinfolinemain, DebuggerDriver::QMnormal);
	    } else {
		// load core file
		loadCoreFile();
	    }
	    if (!m_statusMessage.isEmpty())
		emit updateStatusMessage();
	} else {
	    QString msg = "gdb: " + m_statusMessage;
#if QT_VERSION < 200
	    KMsgBox::message(parentWidget(), kapp->appName(), msg,
			     KMsgBox::STOP, i18n("OK"));
#else
	    KMessageBox::sorry(parentWidget(), msg);
#endif
	    m_executable = "";
	    m_corefile = "";		/* don't process core file */
	    m_haveExecutable = false;
	}
	break;
    case DCcorefile:
	// in any event we have an executable at this point
	m_haveExecutable = true;
	if (m_d->parseCoreFile(output)) {
	    // loading a core is like stopping at a breakpoint
	    m_programActive = true;
	    handleRunCommands(output);
	    // do not reset m_corefile
	} else {
	    // report error
	    QString msg = m_d->driverName() + ": " + QString(output);
#if QT_VERSION < 200
	    KMsgBox::message(parentWidget(), kapp->appName(), msg,
			     KMsgBox::EXCLAMATION, i18n("OK"));
#else
	    KMessageBox::sorry(parentWidget(), msg);
#endif
	    // if core file was loaded from command line, revert to info line main
	    if (!cmd->m_byUser) {
		m_d->queueCmd(DCinfolinemain, DebuggerDriver::QMnormal);
	    }
	    m_corefile = QString();	/* core file not available any more */
	}
	break;
    case DCinfolinemain:
	// ignore the output, marked file info follows
	m_haveExecutable = true;
	break;
    case DCinfolocals:
	// parse local variables
	if (output[0] != '\0') {
	    handleLocals(output);
	}
	break;
    case DCinforegisters:
	handleRegisters(output);
	break;
    case DCexamine:
	handleMemoryDump(output);
	break;
    case DCinfoline:
	handleInfoLine(cmd, output);
	break;
    case DCdisassemble:
	handleDisassemble(cmd, output);
	break;
    case DCframe:
	handleFrameChange(output);
	updateAllExprs();
	break;
    case DCbt:
	handleBacktrace(output);
	updateAllExprs();
	break;
    case DCprint:
	handlePrint(cmd, output);
	break;
    case DCattach:
    case DCrun:
    case DCcont:
    case DCstep:
    case DCstepi:
    case DCnext:
    case DCnexti:
    case DCfinish:
    case DCuntil:
    case DCthread:
	handleRunCommands(output);
	break;
    case DCkill:
	m_programRunning = m_programActive = false;
	// erase PC
	emit updatePC(QString(), -1, DbgAddr(), 0);
	break;
    case DCbreaktext:
    case DCbreakline:
    case DCtbreakline:
    case DCbreakaddr:
    case DCtbreakaddr:
    case DCwatchpoint:
	newBreakpoint(output);
	// fall through
    case DCdelete:
    case DCenable:
    case DCdisable:
	// these commands need immediate response
	m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverrideMoreEqual);
	break;
    case DCinfobreak:
	// note: this handler must not enqueue a command, since
	// DCinfobreak is used at various different places.
	updateBreakList(output);
	emit lineItemsChanged();
	break;
    case DCfindType:
	handleFindType(cmd, output);
	break;
    case DCprintStruct:
    case DCprintQStringStruct:
	handlePrintStruct(cmd, output);
	break;
    case DCinfosharedlib:
	handleSharedLibs(output);
	break;
    case DCcondition:
    case DCignore:
	// we are not interested in the output
	break;
    case DCinfothreads:
	handleThreadList(output);
	break;
    }
}

void KDebugger::backgroundUpdate()
{
    /*
     * If there are still expressions that need to be updated, then do so.
     */
    if (m_programActive)
	evalExpressions();
}

void KDebugger::handleRunCommands(const char* output)
{
    uint flags = m_d->parseProgramStopped(output, m_statusMessage);
    emit updateStatusMessage();

    m_programActive = flags & DebuggerDriver::SFprogramActive;

    // refresh files if necessary
    if (flags & DebuggerDriver::SFrefreshSource) {
	TRACE("re-reading files");
	emit executableUpdated();
    }

    /*
     * If we stopped at a breakpoint, we must update the breakpoint list
     * because the hit count changes. Also, if the breakpoint was temporary
     * it would go away now.
     */
    if ((flags & (DebuggerDriver::SFrefreshBreak|DebuggerDriver::SFrefreshSource)) ||
	stopMayChangeBreakList())
    {
	m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverride);
    }

    /*
     * If we haven't listed the shared libraries yet, do so. We must do
     * this before we emit any commands that list variables, since the type
     * libraries depend on the shared libraries.
     */
    if (!m_sharedLibsListed) {
	// must be a high-priority command!
	m_d->executeCmd(DCinfosharedlib);
    }

    // get the backtrace if the program is running
    if (m_programActive) {
	m_d->queueCmd(DCbt, DebuggerDriver::QMoverride);
    } else {
	// program finished: erase PC
	emit updatePC(QString(), -1, DbgAddr(), 0);
	// dequeue any commands in the queues
	m_d->flushCommands();
    }

    /* Update threads list */
    if (flags & DebuggerDriver::SFrefreshThreads) {
	m_d->queueCmd(DCinfothreads, DebuggerDriver::QMoverride);
    }

    m_programRunning = false;
    emit programStopped();
}

void KDebugger::slotInferiorRunning()
{
    m_programRunning = true;
}

void KDebugger::updateAllExprs()
{
    if (!m_programActive)
	return;

    // retrieve local variables
    m_d->queueCmd(DCinfolocals, DebuggerDriver::QMoverride);

    // retrieve registers
    m_d->queueCmd(DCinforegisters, DebuggerDriver::QMoverride);

    // get new memory dump
    if (!m_memoryExpression.isEmpty()) {
	queueMemoryDump(false);
    }

    // update watch expressions
    KTreeViewItem* item = m_watchVariables.itemAt(0);
    for (; item != 0; item = item->getSibling()) {
	m_watchEvalExpr.append(static_cast<VarTree*>(item));
    }
}

void KDebugger::updateProgEnvironment(const QString& args, const QString& wd,
				      const QDict<EnvVar>& newVars)
{
    m_programArgs = args;
    m_d->executeCmd(DCsetargs, m_programArgs);
    TRACE("new pgm args: " + m_programArgs + "\n");

    m_programWD = wd.stripWhiteSpace();
    if (!m_programWD.isEmpty()) {
	m_d->executeCmd(DCcd, m_programWD);
	TRACE("new wd: " + m_programWD + "\n");
    }

    QDictIterator<EnvVar> it = newVars;
    EnvVar* val;
    for (; (val = it) != 0; ++it) {
	QString var = it.currentKey();
	switch (val->status) {
	case EnvVar::EVnew:
	    m_envVars.insert(var, val);
	    // fall thru
	case EnvVar::EVdirty:
	    // the value must be in our list
	    ASSERT(m_envVars[var] == val);
	    // update value
	    m_d->executeCmd(DCsetenv, var, val->value);
	    break;
	case EnvVar::EVdeleted:
	    // must be in our list
	    ASSERT(m_envVars[var] == val);
	    // delete value
	    m_d->executeCmd(DCunsetenv, var);
	    m_envVars.remove(var);
	    break;
	default:
	    ASSERT(false);
	case EnvVar::EVclean:
	    // variable not changed
	    break;
	}
    }
}

void KDebugger::handleLocals(const char* output)
{
    // retrieve old list of local variables
    QStrList oldVars;
    m_localVariables.exprList(oldVars);

    /*
     *  Get local variables.
     */
    QList<VarTree> newVars;
    parseLocals(output, newVars);

    /*
     * Clear any old VarTree item pointers, so that later we don't access
     * dangling pointers.
     */
    m_localVariables.clearPendingUpdates();

    // reduce flicker
    bool autoU = m_localVariables.autoUpdate();
    m_localVariables.setAutoUpdate(false);
    bool repaintNeeded = false;

    /*
     * Match old variables against new ones.
     */
    for (const char* n = oldVars.first(); n != 0; n = oldVars.next()) {
	// lookup this variable in the list of new variables
	VarTree* v = newVars.first();
	while (v != 0 && strcmp(v->getText(), n) != 0) {
	    v = newVars.next();
	}
	if (v == 0) {
	    // old variable not in the new variables
	    TRACE(QString("old var deleted: ") + n);
	    v = m_localVariables.topLevelExprByName(n);
	    removeExpr(&m_localVariables, v);
	    if (v != 0) repaintNeeded = true;
	} else {
	    // variable in both old and new lists: update
	    TRACE(QString("update var: ") + n);
	    m_localVariables.updateExpr(newVars.current());
	    // remove the new variable from the list
	    newVars.remove();
	    delete v;
#if QT_VERSION >= 200
	    repaintNeeded = true;
#endif
	}
    }
    // insert all remaining new variables
    for (VarTree* v = newVars.first(); v != 0; v = newVars.next()) {
	TRACE("new var: " + v->getText());
	m_localVariables.insertExpr(v);
	repaintNeeded = true;
    }

    // repaint
    m_localVariables.setAutoUpdate(autoU);
    if (repaintNeeded && autoU && m_localVariables.isVisible())
	m_localVariables.repaint();
}

void KDebugger::parseLocals(const char* output, QList<VarTree>& newVars)
{
    QList<VarTree> vars;
    m_d->parseLocals(output, vars);

    QString origName;			/* used in renaming variables */
    while (vars.count() > 0)
    {
	VarTree* variable = vars.take(0);
	// get some types
	variable->inferTypesOfChildren(*m_typeTable);
	/*
	 * When gdb prints local variables, those from the innermost block
	 * come first. We run through the list of already parsed variables
	 * to find duplicates (ie. variables that hide local variables from
	 * a surrounding block). We keep the name of the inner variable, but
	 * rename those from the outer block so that, when the value is
	 * updated in the window, the value of the variable that is
	 * _visible_ changes the color!
	 */
	int block = 0;
	origName = variable->getText();
	for (VarTree* v = newVars.first(); v != 0; v = newVars.next()) {
	    if (variable->getText() == v->getText()) {
		// we found a duplicate, change name
		block++;
		QString newName = origName + " (" + QString().setNum(block) + ")";
		variable->setText(newName);
	    }
	}
	newVars.append(variable);
    }
}

bool KDebugger::handlePrint(CmdQueueItem* cmd, const char* output)
{
    ASSERT(cmd->m_expr != 0);

    VarTree* variable = parseExpr(output, true);
    if (variable == 0)
	return false;

    // set expression "name"
    variable->setText(cmd->m_expr->getText());

    if (cmd->m_expr->m_varKind == VarTree::VKpointer) {
	/*
	 * We must insert a dummy parent, because otherwise variable's value
	 * would overwrite cmd->m_expr's value.
	 */
	VarTree* dummyParent = new VarTree(variable->getText(), VarTree::NKplain);
	dummyParent->m_varKind = VarTree::VKdummy;
	// the name of the parsed variable is the address of the pointer
	QString addr = "*" + cmd->m_expr->m_value;
	variable->setText(addr);
	variable->m_nameKind = VarTree::NKaddress;

	dummyParent->appendChild(variable);
	dummyParent->setDeleteChildren(true);
	TRACE("update ptr: " + cmd->m_expr->getText());
	cmd->m_exprWnd->updateExpr(cmd->m_expr, dummyParent);
	delete dummyParent;
    } else {
	TRACE("update expr: " + cmd->m_expr->getText());
	cmd->m_exprWnd->updateExpr(cmd->m_expr, variable);
	delete variable;
    }

    evalExpressions();			/* enqueue dereferenced pointers */

    return true;
}

VarTree* KDebugger::parseExpr(const char* output, bool wantErrorValue)
{
    VarTree* variable;

    // check for error conditions
    bool goodValue = m_d->parsePrintExpr(output, wantErrorValue, variable);

    if (variable != 0 && goodValue)
    {
	// get some types
	variable->inferTypesOfChildren(*m_typeTable);
    }
    return variable;
}

// parse the output of bt
void KDebugger::handleBacktrace(const char* output)
{
    // reduce flicker
    m_btWindow.setAutoUpdate(false);

    m_btWindow.clear();

    QList<StackFrame> stack;
    m_d->parseBackTrace(output, stack);

    if (stack.count() > 0) {
	StackFrame* frm = stack.take(0);
	// first frame must set PC
	// note: frm->lineNo is zero-based
	emit updatePC(frm->fileName, frm->lineNo, frm->address, frm->frameNo);

	do {
	    QString func;
	    if (frm->var != 0)
		func = frm->var->getText();
	    else
		func = frm->fileName + ":" + QString().setNum(frm->lineNo+1);
	    m_btWindow.insertItem(func);
	    TRACE("frame " + func + " (" + frm->fileName + ":" +
		  QString().setNum(frm->lineNo+1) + ")");
	    delete frm;
	}
	while ((frm = stack.take()) != 0);
    }

    m_btWindow.setAutoUpdate(true);
    m_btWindow.repaint();
}

void KDebugger::gotoFrame(int frame)
{
    m_d->executeCmd(DCframe, frame);
}

void KDebugger::handleFrameChange(const char* output)
{
    QString fileName;
    int frameNo;
    int lineNo;
    DbgAddr address;
    if (m_d->parseFrameChange(output, frameNo, fileName, lineNo, address)) {
	/* lineNo can be negative here if we can't find a file name */
	emit updatePC(fileName, lineNo, address, frameNo);
    } else {
	emit updatePC(fileName, -1, address, frameNo);
    }
}

void KDebugger::evalExpressions()
{
    // evaluate expressions in the following order:
    //   watch expressions
    //   pointers in local variables
    //   pointers in watch expressions
    //   types in local variables
    //   types in watch expressions
    //   pointers in 'this'
    //   types in 'this'
    
    VarTree* exprItem = m_watchEvalExpr.first();
    if (exprItem != 0) {
	m_watchEvalExpr.remove();
	QString expr = exprItem->computeExpr();
	TRACE("watch expr: " + expr);
	CmdQueueItem* cmd = m_d->queueCmd(DCprint, expr, DebuggerDriver::QMoverride);
	// remember which expr this was
	cmd->m_expr = exprItem;
	cmd->m_exprWnd = &m_watchVariables;
    } else {
	ExprWnd* wnd;
	VarTree* exprItem;
#define POINTER(widget) \
		wnd = &widget; \
		exprItem = widget.nextUpdatePtr(); \
		if (exprItem != 0) goto pointer
#define STRUCT(widget) \
		wnd = &widget; \
		exprItem = widget.nextUpdateStruct(); \
		if (exprItem != 0) goto ustruct
#define TYPE(widget) \
		wnd = &widget; \
		exprItem = widget.nextUpdateType(); \
		if (exprItem != 0) goto type
    repeat:
	POINTER(m_localVariables);
	POINTER(m_watchVariables);
	STRUCT(m_localVariables);
	STRUCT(m_watchVariables);
	TYPE(m_localVariables);
	TYPE(m_watchVariables);
#undef POINTER
#undef STRUCT
#undef TYPE
	return;

	pointer:
	// we have an expression to send
	dereferencePointer(wnd, exprItem, false);
	return;

	ustruct:
	// paranoia
	if (exprItem->m_type == 0 || exprItem->m_type == TypeInfo::unknownType())
	    goto repeat;
	evalInitialStructExpression(exprItem, wnd, false);
	return;

	type:
	/*
	 * Sometimes a VarTree gets registered twice for a type update. So
	 * it may happen that it has already been updated. Hence, we ignore
	 * it here and go on to the next task.
	 */
	if (exprItem->m_type != 0)
	    goto repeat;
	determineType(wnd, exprItem);
    }
}

void KDebugger::dereferencePointer(ExprWnd* wnd, VarTree* exprItem,
				   bool immediate)
{
    ASSERT(exprItem->m_varKind == VarTree::VKpointer);

    QString expr = exprItem->computeExpr();
    TRACE("dereferencing pointer: " + expr);
    QString queueExpr = "*(" + expr + ")";
    CmdQueueItem* cmd;
    if (immediate) {
	cmd = m_d->queueCmd(DCprint, queueExpr, DebuggerDriver::QMoverrideMoreEqual);
    } else {
	cmd = m_d->queueCmd(DCprint, queueExpr, DebuggerDriver::QMoverride);
    }
    // remember which expr this was
    cmd->m_expr = exprItem;
    cmd->m_exprWnd = wnd;
}

void KDebugger::determineType(ExprWnd* wnd, VarTree* exprItem)
{
    ASSERT(exprItem->m_varKind == VarTree::VKstruct);

    QString expr = exprItem->computeExpr();
    TRACE("get type of: " + expr);
    CmdQueueItem* cmd;
    cmd = m_d->queueCmd(DCfindType, expr, DebuggerDriver::QMoverride);

    // remember which expr this was
    cmd->m_expr = exprItem;
    cmd->m_exprWnd = wnd;
}

void KDebugger::handleFindType(CmdQueueItem* cmd, const char* output)
{
    QString type;
    if (m_d->parseFindType(output, type))
    {
	ASSERT(cmd != 0 && cmd->m_expr != 0);

	TypeInfo* info = m_typeTable->lookup(type);

	if (info == 0) {
	    /*
	     * We've asked gdb for the type of the expression in
	     * cmd->m_expr, but it returned a name we don't know. The base
	     * class (and member) types have been checked already (at the
	     * time when we parsed that particular expression). Now it's
	     * time to derive the type from the base classes as a last
	     * resort.
	     */
	    info = cmd->m_expr->inferTypeFromBaseClass();
	    // if we found a type through this method, register an alias
	    if (info != 0) {
		TRACE("infered alias: " + type);
		m_typeTable->registerAlias(type, info);
	    }
	}
	if (info == 0) {
	    TRACE("unknown type");
	    cmd->m_expr->m_type = TypeInfo::unknownType();
	} else {
	    cmd->m_expr->m_type = info;
	    /* since this node has a new type, we get its value immediately */
	    evalInitialStructExpression(cmd->m_expr, cmd->m_exprWnd, false);
	    return;
	}
    }

    evalExpressions();			/* queue more of them */
}

void KDebugger::handlePrintStruct(CmdQueueItem* cmd, const char* output)
{
    VarTree* var = cmd->m_expr;
    ASSERT(var != 0);
    ASSERT(var->m_varKind == VarTree::VKstruct);

    VarTree* partExpr;
    if (cmd->m_cmd != DCprintQStringStruct) {
	partExpr = parseExpr(output, false);
    } else {
	partExpr = m_d->parseQCharArray(output, false, m_typeTable->qCharIsShort());
    }
    bool errorValue =
	partExpr == 0 ||
	/* we only allow simple values at the moment */
	partExpr->childCount() != 0;

    QString partValue;
    if (errorValue)
    {
	partValue = "?""?""?";	// 2 question marks in a row would be a trigraph
    } else {
	partValue = partExpr->m_value;
    }
    delete partExpr;
    partExpr = 0;

    /*
     * Updating a struct value works like this: var->m_partialValue holds
     * the value that we have gathered so far (it's been initialized with
     * var->m_type->m_displayString[0] earlier). Each time we arrive here,
     * we append the printed result followed by the next
     * var->m_type->m_displayString to var->m_partialValue.
     * 
     * If the expression we just evaluated was a guard expression, and it
     * resulted in an error, we must not evaluate the real expression, but
     * go on to the next index. (We must still add the question marks to
     * the value).
     * 
     * Next, if this was the length expression, we still have not seen the
     * real expression, but the length of a QString.
     */
    ASSERT(var->m_exprIndex >= 0 && var->m_exprIndex <= typeInfoMaxExpr);

    if (errorValue || !var->m_exprIndexUseGuard)
    {
	// add current partValue (which might be the question marks)
#if QT_VERSION < 200
	var->m_partialValue.detach();
#endif
	var->m_partialValue += partValue;
	var->m_exprIndex++;		/* next part */
	var->m_exprIndexUseGuard = true;
	var->m_partialValue += var->m_type->m_displayString[var->m_exprIndex];
    }
    else
    {
	// this was a guard expression that succeeded
	// go for the real expression
	var->m_exprIndexUseGuard = false;
    }

    /* go for more sub-expressions if needed */
    if (var->m_exprIndex < var->m_type->m_numExprs) {
	/* queue a new print command with quite high priority */
	evalStructExpression(var, cmd->m_exprWnd, true);
	return;
    }

    cmd->m_exprWnd->updateStructValue(var);

    evalExpressions();			/* enqueue dereferenced pointers */
}

/* queues the first printStruct command for a struct */
void KDebugger::evalInitialStructExpression(VarTree* var, ExprWnd* wnd, bool immediate)
{
    var->m_exprIndex = 0;
    var->m_exprIndexUseGuard = true;
    var->m_partialValue = var->m_type->m_displayString[0];
    evalStructExpression(var, wnd, immediate);
}

/* queues a printStruct command; var must have been initialized correctly */
void KDebugger::evalStructExpression(VarTree* var, ExprWnd* wnd, bool immediate)
{
    QString base = var->computeExpr();
    QString exprFmt;
    if (var->m_exprIndexUseGuard) {
	exprFmt = var->m_type->m_guardStrings[var->m_exprIndex];
	if (exprFmt.isEmpty()) {
	    // no guard, omit it and go to expression
	    var->m_exprIndexUseGuard = false;
	}
    }
    if (!var->m_exprIndexUseGuard) {
	exprFmt = var->m_type->m_exprStrings[var->m_exprIndex];
    }

    SIZED_QString(expr, exprFmt.length() + base.length() + 10);
    expr.sprintf(exprFmt, base.data());

    DbgCommand dbgCmd = DCprintStruct;
    // check if this is a QString::Data
    if (strncmp(expr, "/QString::Data ", 15) == 0)
    {
	if (m_typeTable->parseQt2QStrings())
	{
	    expr = expr.mid(15, expr.length());	/* strip off /QString::Data */
	    dbgCmd = DCprintQStringStruct;
	} else {
	    /*
	     * This should not happen: the type libraries should be set up
	     * in a way that this can't happen. If this happens
	     * nevertheless it means that, eg., kdecore was loaded but qt2
	     * was not (only qt2 enables the QString feature).
	     */
	    // TODO: remove this "print"; queue the next printStruct instead
	    expr = "*0";
	}
    } else {
	expr = expr;
    }
    TRACE("evalStruct: " + expr + (var->m_exprIndexUseGuard ? " // guard" : " // real"));
    CmdQueueItem* cmd = m_d->queueCmd(dbgCmd, expr,
				      immediate  ?  DebuggerDriver::QMoverrideMoreEqual
				      : DebuggerDriver::QMnormal);

    // remember which expression this was
    cmd->m_expr = var;
    cmd->m_exprWnd = wnd;
}

/* removes expression from window */
void KDebugger::removeExpr(ExprWnd* wnd, VarTree* var)
{
    if (var == 0)
	return;

    // must remove any references to var from command queues
    m_d->dequeueCmdByVar(var);

    wnd->removeExpr(var);
}

void KDebugger::handleSharedLibs(const char* output)
{
    // delete all known libraries
    m_sharedLibs.clear();

    // parse the table of shared libraries
    m_d->parseSharedLibs(output, m_sharedLibs);
    m_sharedLibsListed = true;

    // get type libraries
    m_typeTable->loadLibTypes(m_sharedLibs);
}

CmdQueueItem* KDebugger::loadCoreFile()
{
    return m_d->queueCmd(DCcorefile, m_corefile, DebuggerDriver::QMoverride);
}

void KDebugger::slotLocalsExpanding(KTreeViewItem* item, bool& allow)
{
    exprExpandingHelper(&m_localVariables, item, allow);
}

void KDebugger::slotWatchExpanding(KTreeViewItem* item, bool& allow)
{
    exprExpandingHelper(&m_watchVariables, item, allow);
}

void KDebugger::exprExpandingHelper(ExprWnd* wnd, KTreeViewItem* item, bool&)
{
    VarTree* exprItem = static_cast<VarTree*>(item);
    if (exprItem->m_varKind != VarTree::VKpointer) {
	return;
    }
    dereferencePointer(wnd, exprItem, true);
}

// add the expression in the edit field to the watch expressions
void KDebugger::addWatch(const QString& t)
{
    QString expr = t.stripWhiteSpace();
    if (expr.isEmpty())
	return;
    VarTree* exprItem = new VarTree(expr, VarTree::NKplain);
    m_watchVariables.insertExpr(exprItem);

    // if we are boring ourselves, send down the command
    if (m_programActive) {
	m_watchEvalExpr.append(exprItem);
	if (m_d->isIdle()) {
	    evalExpressions();
	}
    }
}

// delete a toplevel watch expression
void KDebugger::slotDeleteWatch()
{
    // delete only allowed while debugger is idle; or else we might delete
    // the very expression the debugger is currently working on...
    if (!m_d->isIdle())
	return;

    int index = m_watchVariables.currentItem();
    if (index < 0)
	return;
    
    VarTree* item = static_cast<VarTree*>(m_watchVariables.itemAt(index));
    if (!item->isToplevelExpr())
	return;

    // remove the variable from the list to evaluate
    if (m_watchEvalExpr.findRef(item) >= 0) {
	m_watchEvalExpr.remove();
    }
    removeExpr(&m_watchVariables, item);
    // item is invalid at this point!
}

void KDebugger::startAnimation(bool fast)
{
    int interval = fast ? 50 : 150;
    if (!m_animationTimer.isActive()) {
	m_animationTimer.start(interval);
    } else if (m_animationInterval != interval) {
	m_animationTimer.changeInterval(interval);
    }
    m_animationInterval = interval;
}

void KDebugger::stopAnimation()
{
    if (m_animationTimer.isActive()) {
	m_animationTimer.stop();
	m_animationInterval = 0;
    }
}

void KDebugger::slotUpdateAnimation()
{
    if (m_d->isIdle()) {
	stopAnimation();
    } else {
	/*
	 * Slow animation while program is stopped (i.e. while variables
	 * are displayed)
	 */
	bool slow = isReady() && m_programActive && !m_programRunning;
	startAnimation(!slow);
    }
}

void KDebugger::handleRegisters(const char* output)
{
    QList<RegisterInfo> regs;
    m_d->parseRegisters(output, regs);

    emit registersChanged(regs);

    // delete them all
    regs.setAutoDelete(true);
}

/*
 * The output of the DCbreak* commands has more accurate information about
 * the file and the line number.
 */
void KDebugger::newBreakpoint(const char* output)
{
    int id;
    QString file;
    int lineNo;
    if (!m_d->parseBreakpoint(output, id, file, lineNo))
	return;

    // see if it is new
    for (int i = m_brkpts.size()-1; i >= 0; i--) {
	if (m_brkpts[i]->id == id) {
	    // not new; update
	    m_brkpts[i]->fileName = file;
	    m_brkpts[i]->lineNo = lineNo;
	    return;
	}
    }
    // yes, new
    Breakpoint* bp = new Breakpoint;
    bp->id = id;
    bp->temporary = false;
    bp->enabled = true;
    bp->hitCount = 0;
    bp->ignoreCount = 0;
    bp->fileName = file;
    bp->lineNo = lineNo;
    int n = m_brkpts.size();
    m_brkpts.resize(n+1);
    m_brkpts[n] = bp;
}

void KDebugger::updateBreakList(const char* output)
{
    // get the new list
    QList<Breakpoint> brks;
    brks.setAutoDelete(false);
    m_d->parseBreakList(output, brks);

    // merge new information into existing breakpoints

    QArray<Breakpoint*> oldbrks = m_brkpts;

    // move parsed breakpoints into m_brkpts
    m_brkpts.detach();
    m_brkpts.resize(brks.count());
    int n = 0;
    for (Breakpoint* bp = brks.first(); bp != 0; bp = brks.next())
    {
	m_brkpts[n++] = bp;
    }

    // go through all old breakpoints
    for (int i = oldbrks.size()-1; i >= 0; i--) {
	// is this one still alive?
	for (int j = m_brkpts.size()-1; j >= 0; j--)
	{
	    if (m_brkpts[j]->id == oldbrks[i]->id) {
		// yes, it is
		// keep accurate location
		m_brkpts[j]->fileName = oldbrks[i]->fileName;
		m_brkpts[j]->lineNo = oldbrks[i]->lineNo;
		break;
	    }
	}
    }

    // delete old breakpoints
    for (int i = oldbrks.size()-1; i >= 0; i--) {
	delete oldbrks[i];
    }

    emit breakpointsChanged();
}

// look if there is at least one temporary breakpoint
// or a watchpoint
bool KDebugger::stopMayChangeBreakList() const
{
    for (int i = m_brkpts.size()-1; i >= 0; i--) {
	Breakpoint* bp = m_brkpts[i];
	if (bp->temporary || bp->type == Breakpoint::watchpoint)
	    return true;
    }
    return false;
}

Breakpoint* KDebugger::breakpointByFilePos(QString file, int lineNo,
					   const DbgAddr& address)
{
    // look for exact file name match
    int i;
    for (i = m_brkpts.size()-1; i >= 0; i--) {
	if (m_brkpts[i]->lineNo == lineNo &&
	    m_brkpts[i]->fileName == file &&
	    (address.isEmpty() || m_brkpts[i]->address == address))
	{
	    return m_brkpts[i];
	}
    }
    // not found, so try basename
    // strip off directory part of file name
    int offset = file.findRev("/");
#if QT_VERSION < 200
    file.detach();
#endif
    file.remove(0, offset+1);

    for (i = m_brkpts.size()-1; i >= 0; i--) {
	// get base name of breakpoint's file
	QString basename = m_brkpts[i]->fileName;
	int offset = basename.findRev("/");
	if (offset >= 0) {
#if QT_VERSION < 200
	    basename.detach();
#endif
	    basename.remove(0, offset+1);
	}

	if (m_brkpts[i]->lineNo == lineNo &&
	    basename == file &&
	    (address.isEmpty() || m_brkpts[i]->address == address))
	{
	    return m_brkpts[i];
	}
    }

    // not found
    return 0;
}

void KDebugger::slotValuePopup(const QString& expr)
{
    // search the local variables for a match
    VarTree* v = m_localVariables.topLevelExprByName(expr);
    if (v == 0) {
	// not found, check watch expressions
	v = m_watchVariables.topLevelExprByName(expr);
	if (v == 0) {
	    // nothing found; do nothing
	    return;
	}
    }

    // construct the tip
    QString tip = v->getText() + " = ";
    if (!v->m_value.isEmpty())
    {
	tip += v->m_value;
    }
    else
    {
	// no value: we use some hint
	switch (v->m_varKind) {
	case VarTree::VKstruct:
	    tip += "{...}";
	    break;
	case VarTree::VKarray:
	    tip += "[...]";
	    break;
	default:
	    tip += "?""?""?";	// 2 question marks in a row would be a trigraph
	    break;
	}
    }
    emit valuePopup(tip);
}

void KDebugger::slotDisassemble(const QString& fileName, int lineNo)
{
    CmdQueueItem* cmd = m_d->queueCmd(DCinfoline, fileName, lineNo,
				      DebuggerDriver::QMoverrideMoreEqual);
    cmd->m_fileName = fileName;
    cmd->m_lineNo = lineNo;
}

void KDebugger::handleInfoLine(CmdQueueItem* cmd, const char* output)
{
    QString addrFrom, addrTo;
    if (m_d->parseInfoLine(output, addrFrom, addrTo)) {
	// got the address range, now get the real code
	CmdQueueItem* c = m_d->queueCmd(DCdisassemble, addrFrom, addrTo,
					DebuggerDriver::QMoverrideMoreEqual);
	c->m_fileName = cmd->m_fileName;
	c->m_lineNo = cmd->m_lineNo;
    } else {
	// no code
	QList<DisassembledCode> empty;
	emit disassembled(cmd->m_fileName, cmd->m_lineNo, empty);
    }
}

void KDebugger::handleDisassemble(CmdQueueItem* cmd, const char* output)
{
    QList<DisassembledCode> code;
    code.setAutoDelete(true);
    m_d->parseDisassemble(output, code);
    emit disassembled(cmd->m_fileName, cmd->m_lineNo, code);
}

void KDebugger::handleThreadList(const char* output)
{
    QList<ThreadInfo> threads;
    threads.setAutoDelete(true);
    m_d->parseThreadList(output, threads);
    emit threadsChanged(threads);
}

void KDebugger::setThread(int id)
{
    m_d->queueCmd(DCthread, id, DebuggerDriver::QMoverrideMoreEqual);
}

void KDebugger::setMemoryExpression(const QString& memexpr)
{
    m_memoryExpression = memexpr;

    // queue the new expression
    if (!m_memoryExpression.isEmpty() &&
	isProgramActive() &&
	!isProgramRunning())
    {
	queueMemoryDump(true);
    }
}

void KDebugger::queueMemoryDump(bool immediate)
{
    m_d->queueCmd(DCexamine, m_memoryExpression, m_memoryFormat,
		  immediate ? DebuggerDriver::QMoverrideMoreEqual :
			      DebuggerDriver::QMoverride);
}

void KDebugger::handleMemoryDump(const char* output)
{
    QList<MemoryDump> memdump;
    memdump.setAutoDelete(true);
    QString msg = m_d->parseMemoryDump(output, memdump);
    emit memoryDumpChanged(msg, memdump);
}


#include "debugger.moc"