Simplified updateBreakList(); reverted m_brkpts.count() to m_brkpts.size().
[kdbg.git] / kdbg / debugger.cpp
bloba48b6b6272965a6c6af8c5927f91ea08993fe6de
1 // $Id$
3 // Copyright by Johannes Sixt
4 // This file is under GPL, the GNU General Public Licence
6 #include "debugger.h"
7 #include "dbgdriver.h"
8 #include "pgmargs.h"
9 #include "typetable.h"
10 #include "exprwnd.h"
11 #include "pgmsettings.h"
12 #include "valarray.h"
13 #include <qregexp.h>
14 #include <qfileinfo.h>
15 #include <qlistbox.h>
16 #include <qstringlist.h>
17 #include <kapp.h>
18 #include <ksimpleconfig.h>
19 #include <kconfig.h>
20 #include <klocale.h> /* i18n */
21 #include <kmessagebox.h>
22 #include <ctype.h>
23 #include <stdlib.h> /* strtol, atoi */
24 #ifdef HAVE_UNISTD_H
25 #include <unistd.h> /* sleep(3) */
26 #endif
27 #include "mydebug.h"
30 KDebugger::KDebugger(QWidget* parent,
31 ExprWnd* localVars,
32 ExprWnd* watchVars,
33 QListBox* backtrace) :
34 QObject(parent, "debugger"),
35 m_ttyLevel(ttyFull),
36 m_memoryFormat(MDTword | MDThex),
37 m_haveExecutable(false),
38 m_programActive(false),
39 m_programRunning(false),
40 m_sharedLibsListed(false),
41 m_typeTable(0),
42 m_programConfig(0),
43 m_d(0),
44 m_localVariables(*localVars),
45 m_watchVariables(*watchVars),
46 m_btWindow(*backtrace),
47 m_animationTimer(this),
48 m_animationInterval(0)
50 m_envVars.setAutoDelete(true);
51 m_brkpts.setAutoDelete(true);
53 connect(&m_localVariables, SIGNAL(expanding(KTreeViewItem*,bool&)),
54 SLOT(slotLocalsExpanding(KTreeViewItem*,bool&)));
55 connect(&m_watchVariables, SIGNAL(expanding(KTreeViewItem*,bool&)),
56 SLOT(slotWatchExpanding(KTreeViewItem*,bool&)));
58 connect(&m_btWindow, SIGNAL(highlighted(int)), SLOT(gotoFrame(int)));
60 // animation
61 connect(&m_animationTimer, SIGNAL(timeout()), SIGNAL(animationTimeout()));
62 // special update of animation
63 connect(this, SIGNAL(updateUI()), SLOT(slotUpdateAnimation()));
65 emit updateUI();
68 KDebugger::~KDebugger()
70 if (m_programConfig != 0) {
71 saveProgramSettings();
72 m_programConfig->sync();
73 delete m_programConfig;
76 delete m_typeTable;
80 void KDebugger::saveSettings(KConfig* /*config*/)
84 void KDebugger::restoreSettings(KConfig* /*config*/)
89 //////////////////////////////////////////////////////////////////////
90 // external interface
92 const char GeneralGroup[] = "General";
93 const char DebuggerCmdStr[] = "DebuggerCmdStr";
94 const char TTYLevelEntry[] = "TTYLevel";
95 const char KDebugger::DriverNameEntry[] = "DriverName";
97 bool KDebugger::debugProgram(const QString& name,
98 DebuggerDriver* driver)
100 if (m_d != 0 && m_d->isRunning())
102 QApplication::setOverrideCursor(waitCursor);
104 stopDriver();
106 QApplication::restoreOverrideCursor();
108 if (m_d->isRunning() || m_haveExecutable) {
109 /* timed out! We can't really do anything useful now */
110 TRACE("timed out while waiting for gdb to die!");
111 return false;
113 delete m_d;
114 m_d = 0;
117 // wire up the driver
118 connect(driver, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)),
119 this, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)));
120 connect(driver, SIGNAL(processExited(KProcess*)), SLOT(gdbExited(KProcess*)));
121 connect(driver, SIGNAL(commandReceived(CmdQueueItem*,const char*)),
122 SLOT(parse(CmdQueueItem*,const char*)));
123 connect(driver, SIGNAL(wroteStdin(KProcess*)), SIGNAL(updateUI()));
124 connect(driver, SIGNAL(inferiorRunning()), SLOT(slotInferiorRunning()));
125 connect(driver, SIGNAL(enterIdleState()), SLOT(backgroundUpdate()));
126 connect(driver, SIGNAL(enterIdleState()), SIGNAL(updateUI()));
128 // create the program settings object
129 openProgramConfig(name);
131 // get debugger command from per-program settings
132 if (m_programConfig != 0) {
133 m_programConfig->setGroup(GeneralGroup);
134 m_debuggerCmd = m_programConfig->readEntry(DebuggerCmdStr);
135 // get terminal emulation level
136 m_ttyLevel = TTYLevel(m_programConfig->readNumEntry(TTYLevelEntry, ttyFull));
138 // the rest is read in later in the handler of DCexecutable
140 m_d = driver;
142 if (!startDriver()) {
143 TRACE("startDriver failed");
144 m_d = 0;
145 return false;
148 TRACE("before file cmd");
149 m_d->executeCmd(DCexecutable, name);
150 m_executable = name;
152 // set remote target
153 if (!m_remoteDevice.isEmpty()) {
154 m_d->executeCmd(DCtargetremote, m_remoteDevice);
155 m_d->queueCmd(DCbt, DebuggerDriver::QMoverride);
156 m_d->queueCmd(DCframe, 0, DebuggerDriver::QMnormal);
157 m_programActive = true;
158 m_haveExecutable = true;
161 // create a type table
162 m_typeTable = new ProgramTypeTable;
163 m_sharedLibsListed = false;
165 emit updateUI();
167 return true;
170 void KDebugger::shutdown()
172 // shut down debugger driver
173 if (m_d != 0 && m_d->isRunning())
175 stopDriver();
179 void KDebugger::useCoreFile(QString corefile, bool batch)
181 m_corefile = corefile;
182 if (!batch) {
183 CmdQueueItem* cmd = loadCoreFile();
184 cmd->m_byUser = true;
188 void KDebugger::programRun()
190 if (!isReady())
191 return;
193 // when program is active, but not a core file, continue
194 // otherwise run the program
195 if (m_programActive && m_corefile.isEmpty()) {
196 // gdb command: continue
197 m_d->executeCmd(DCcont, true);
198 } else {
199 // gdb command: run
200 m_d->executeCmd(DCrun, true);
201 m_corefile = QString();
202 m_programActive = true;
204 m_programRunning = true;
207 void KDebugger::attachProgram(const QString& pid)
209 if (!isReady())
210 return;
212 m_attachedPid = pid;
213 TRACE("Attaching to " + m_attachedPid);
214 m_d->executeCmd(DCattach, m_attachedPid);
215 m_programActive = true;
216 m_programRunning = true;
219 void KDebugger::programRunAgain()
221 if (canSingleStep()) {
222 m_d->executeCmd(DCrun, true);
223 m_corefile = QString();
224 m_programRunning = true;
228 void KDebugger::programStep()
230 if (canSingleStep()) {
231 m_d->executeCmd(DCstep, true);
232 m_programRunning = true;
236 void KDebugger::programNext()
238 if (canSingleStep()) {
239 m_d->executeCmd(DCnext, true);
240 m_programRunning = true;
244 void KDebugger::programStepi()
246 if (canSingleStep()) {
247 m_d->executeCmd(DCstepi, true);
248 m_programRunning = true;
252 void KDebugger::programNexti()
254 if (canSingleStep()) {
255 m_d->executeCmd(DCnexti, true);
256 m_programRunning = true;
260 void KDebugger::programFinish()
262 if (canSingleStep()) {
263 m_d->executeCmd(DCfinish, true);
264 m_programRunning = true;
268 void KDebugger::programKill()
270 if (haveExecutable() && isProgramActive()) {
271 if (m_programRunning) {
272 m_d->interruptInferior();
274 // this is an emergency command; flush queues
275 m_d->flushCommands(true);
276 m_d->executeCmd(DCkill, true);
280 bool KDebugger::runUntil(const QString& fileName, int lineNo)
282 if (isReady() && m_programActive && !m_programRunning) {
283 // strip off directory part of file name
284 QString file = fileName;
285 int offset = file.findRev("/");
286 if (offset >= 0) {
287 file.remove(0, offset+1);
289 m_d->executeCmd(DCuntil, file, lineNo, true);
290 m_programRunning = true;
291 return true;
292 } else {
293 return false;
297 void KDebugger::programBreak()
299 if (m_haveExecutable && m_programRunning) {
300 m_d->interruptInferior();
304 void KDebugger::programArgs(QWidget* parent)
306 if (m_haveExecutable) {
307 QStringList allOptions = m_d->boolOptionList();
308 PgmArgs dlg(parent, m_executable, m_envVars, allOptions);
309 dlg.setArgs(m_programArgs);
310 dlg.setWd(m_programWD);
311 dlg.setOptions(m_boolOptions);
312 if (dlg.exec()) {
313 updateProgEnvironment(dlg.args(), dlg.wd(),
314 dlg.envVars(), dlg.options());
319 void KDebugger::programSettings(QWidget* parent)
321 if (!m_haveExecutable)
322 return;
324 ProgramSettings dlg(parent, m_executable);
326 dlg.m_chooseDriver.setDebuggerCmd(m_debuggerCmd);
327 dlg.m_output.setTTYLevel(m_ttyLevel);
329 if (dlg.exec() == QDialog::Accepted)
331 m_debuggerCmd = dlg.m_chooseDriver.debuggerCmd();
332 m_ttyLevel = TTYLevel(dlg.m_output.ttyLevel());
336 bool KDebugger::setBreakpoint(QString file, int lineNo,
337 const DbgAddr& address, bool temporary)
339 if (!isReady()) {
340 return false;
343 Breakpoint* bp = breakpointByFilePos(file, lineNo, address);
344 if (bp == 0)
347 * No such breakpoint, so set a new one. If we have an address, we
348 * set the breakpoint exactly there. Otherwise we use the file name
349 * plus line no.
351 if (address.isEmpty())
353 // strip off directory part of file name
354 int offset = file.findRev("/");
355 if (offset >= 0) {
356 file.remove(0, offset+1);
358 m_d->executeCmd(temporary ? DCtbreakline : DCbreakline,
359 file, lineNo);
361 else
363 m_d->executeCmd(temporary ? DCtbreakaddr : DCbreakaddr,
364 address.asString());
367 else
370 * If the breakpoint is disabled, enable it; if it's enabled,
371 * delete that breakpoint.
373 if (bp->enabled) {
374 m_d->executeCmd(DCdelete, bp->id);
375 } else {
376 m_d->executeCmd(DCenable, bp->id);
379 return true;
382 bool KDebugger::enableDisableBreakpoint(QString file, int lineNo,
383 const DbgAddr& address)
385 if (!isReady()) {
386 return false;
389 Breakpoint* bp = breakpointByFilePos(file, lineNo, address);
390 if (bp == 0)
391 return true;
393 // toggle enabled/disabled state
394 if (bp->enabled) {
395 m_d->executeCmd(DCdisable, bp->id);
396 } else {
397 m_d->executeCmd(DCenable, bp->id);
399 return true;
402 bool KDebugger::canSingleStep()
404 return isReady() && m_programActive && !m_programRunning;
407 bool KDebugger::canChangeBreakpoints()
409 return isReady() && !m_programRunning;
412 bool KDebugger::isReady() const
414 return m_haveExecutable &&
415 m_d != 0 && m_d->canExecuteImmediately();
418 bool KDebugger::isIdle() const
420 return m_d == 0 || m_d->isIdle();
424 //////////////////////////////////////////////////////////
425 // debugger driver
427 bool KDebugger::startDriver()
429 emit debuggerStarting(); /* must set m_inferiorTerminal */
432 * If the per-program command string is empty, use the global setting
433 * (which might also be empty, in which case the driver uses its
434 * default).
436 m_explicitKill = false;
437 if (!m_d->startup(m_debuggerCmd)) {
438 return false;
442 * If we have an output terminal, we use it. Otherwise we will run the
443 * program with input and output redirected to /dev/null. Other
444 * redirections are also necessary depending on the tty emulation
445 * level.
447 int redirect = RDNstdin|RDNstdout|RDNstderr; /* redirect everything */
448 if (!m_inferiorTerminal.isEmpty()) {
449 switch (m_ttyLevel) {
450 default:
451 case ttyNone:
452 // redirect everything
453 break;
454 case ttySimpleOutputOnly:
455 redirect = RDNstdin;
456 break;
457 case ttyFull:
458 redirect = 0;
459 break;
462 m_d->executeCmd(DCtty, m_inferiorTerminal, redirect);
464 return true;
467 void KDebugger::stopDriver()
469 m_explicitKill = true;
471 if (m_attachedPid.isEmpty()) {
472 m_d->terminate();
473 } else {
474 m_d->detachAndTerminate();
478 * We MUST wait until the slot gdbExited() has been called. But to
479 * avoid a deadlock, we wait only for some certain maximum time. Should
480 * this timeout be reached, the only reasonable thing one could do then
481 * is exiting kdbg.
483 kapp->processEvents(1000); /* ideally, this will already shut it down */
484 int maxTime = 20; /* about 20 seconds */
485 while (m_haveExecutable && maxTime > 0) {
486 // give gdb time to die (and send a SIGCLD)
487 ::sleep(1);
488 --maxTime;
489 kapp->processEvents(1000);
493 void KDebugger::gdbExited(KProcess*)
496 * Save settings, but only if gdb has already processed "info line
497 * main", otherwise we would save an empty config file, because it
498 * isn't read in until then!
500 if (m_programConfig != 0) {
501 if (m_haveExecutable) {
502 saveProgramSettings();
503 m_programConfig->sync();
505 delete m_programConfig;
506 m_programConfig = 0;
509 // erase types
510 delete m_typeTable;
511 m_typeTable = 0;
513 if (m_explicitKill) {
514 TRACE(m_d->driverName() + " exited normally");
515 } else {
516 QString msg = i18n("%1 exited unexpectedly.\n"
517 "Restart the session (e.g. with File|Executable).");
518 KMessageBox::error(parentWidget(), msg.arg(m_d->driverName()));
521 // reset state
522 m_haveExecutable = false;
523 m_executable = "";
524 m_programActive = false;
525 m_programRunning = false;
526 m_explicitKill = false;
527 m_debuggerCmd = QString(); /* use global setting at next start! */
528 m_attachedPid = QString(); /* we are no longer attached to a process */
529 m_ttyLevel = ttyFull;
530 m_brkpts.clear();
532 // stop gear wheel and erase PC
533 stopAnimation();
534 emit updatePC(QString(), -1, DbgAddr(), 0);
537 QString KDebugger::getConfigForExe(const QString& name)
539 QFileInfo fi(name);
540 QString pgmConfigFile = fi.dirPath(true);
541 if (!pgmConfigFile.isEmpty()) {
542 pgmConfigFile += '/';
544 pgmConfigFile += ".kdbgrc." + fi.fileName();
545 TRACE("program config file = " + pgmConfigFile);
546 return pgmConfigFile;
549 void KDebugger::openProgramConfig(const QString& name)
551 ASSERT(m_programConfig == 0);
553 QString pgmConfigFile = getConfigForExe(name);
554 // check whether we can write to the file
555 QFile file(pgmConfigFile);
556 bool readonly = true;
557 bool openit = true;
558 if (file.open(IO_ReadWrite)) { /* don't truncate! */
559 readonly = false;
560 // the file exists now
561 } else if (!file.open(IO_ReadOnly)) {
562 /* file does not exist and cannot be created: don't use it */
563 openit = false;
565 if (openit) {
566 m_programConfig = new KSimpleConfig(pgmConfigFile, readonly);
570 const char EnvironmentGroup[] = "Environment";
571 const char WatchGroup[] = "Watches";
572 const char FileVersion[] = "FileVersion";
573 const char ProgramArgs[] = "ProgramArgs";
574 const char WorkingDirectory[] = "WorkingDirectory";
575 const char OptionsSelected[] = "OptionsSelected";
576 const char Variable[] = "Var%d";
577 const char Value[] = "Value%d";
578 const char ExprFmt[] = "Expr%d";
580 void KDebugger::saveProgramSettings()
582 ASSERT(m_programConfig != 0);
583 m_programConfig->setGroup(GeneralGroup);
584 m_programConfig->writeEntry(FileVersion, 1);
585 m_programConfig->writeEntry(ProgramArgs, m_programArgs);
586 m_programConfig->writeEntry(WorkingDirectory, m_programWD);
587 m_programConfig->writeEntry(OptionsSelected, m_boolOptions);
588 m_programConfig->writeEntry(DebuggerCmdStr, m_debuggerCmd);
589 m_programConfig->writeEntry(TTYLevelEntry, int(m_ttyLevel));
590 QString driverName;
591 if (m_d != 0)
592 driverName = m_d->driverName();
593 m_programConfig->writeEntry(DriverNameEntry, driverName);
595 // write environment variables
596 m_programConfig->deleteGroup(EnvironmentGroup);
597 m_programConfig->setGroup(EnvironmentGroup);
598 QDictIterator<EnvVar> it = m_envVars;
599 EnvVar* var;
600 QString varName;
601 QString varValue;
602 for (int i = 0; (var = it) != 0; ++it, ++i) {
603 varName.sprintf(Variable, i);
604 varValue.sprintf(Value, i);
605 m_programConfig->writeEntry(varName, it.currentKey());
606 m_programConfig->writeEntry(varValue, var->value);
609 saveBreakpoints(m_programConfig);
611 // watch expressions
612 // first get rid of whatever was in this group
613 m_programConfig->deleteGroup(WatchGroup);
614 // then start a new group
615 m_programConfig->setGroup(WatchGroup);
616 KTreeViewItem* item = m_watchVariables.itemAt(0);
617 int watchNum = 0;
618 for (; item != 0; item = item->getSibling(), ++watchNum) {
619 varName.sprintf(ExprFmt, watchNum);
620 m_programConfig->writeEntry(varName, item->getText());
623 // give others a chance
624 emit saveProgramSpecific(m_programConfig);
627 void KDebugger::restoreProgramSettings()
629 ASSERT(m_programConfig != 0);
630 m_programConfig->setGroup(GeneralGroup);
632 * We ignore file version for now we will use it in the future to
633 * distinguish different versions of this configuration file.
635 m_debuggerCmd = m_programConfig->readEntry(DebuggerCmdStr);
636 // m_ttyLevel has been read in already
637 QString pgmArgs = m_programConfig->readEntry(ProgramArgs);
638 QString pgmWd = m_programConfig->readEntry(WorkingDirectory);
639 QStringList boolOptions = m_programConfig->readListEntry(OptionsSelected);
640 m_boolOptions = QStringList();
642 // read environment variables
643 m_programConfig->setGroup(EnvironmentGroup);
644 m_envVars.clear();
645 QDict<EnvVar> pgmVars;
646 EnvVar* var;
647 QString varName;
648 QString varValue;
649 for (int i = 0;; ++i) {
650 varName.sprintf(Variable, i);
651 varValue.sprintf(Value, i);
652 if (!m_programConfig->hasKey(varName)) {
653 /* entry not present, assume that we've hit them all */
654 break;
656 QString name = m_programConfig->readEntry(varName);
657 if (name.isEmpty()) {
658 // skip empty names
659 continue;
661 var = new EnvVar;
662 var->value = m_programConfig->readEntry(varValue);
663 var->status = EnvVar::EVnew;
664 pgmVars.insert(name, var);
667 updateProgEnvironment(pgmArgs, pgmWd, pgmVars, boolOptions);
669 restoreBreakpoints(m_programConfig);
671 // watch expressions
672 m_programConfig->setGroup(WatchGroup);
673 m_watchVariables.clear();
674 for (int i = 0;; ++i) {
675 varName.sprintf(ExprFmt, i);
676 if (!m_programConfig->hasKey(varName)) {
677 /* entry not present, assume that we've hit them all */
678 break;
680 QString expr = m_programConfig->readEntry(varName);
681 if (expr.isEmpty()) {
682 // skip empty expressions
683 continue;
685 addWatch(expr);
688 // give others a chance
689 emit restoreProgramSpecific(m_programConfig);
693 * Breakpoints are saved one per group.
695 const char BPGroup[] = "Breakpoint %d";
696 const char File[] = "File";
697 const char Line[] = "Line";
698 const char Address[] = "Address";
699 const char Temporary[] = "Temporary";
700 const char Enabled[] = "Enabled";
701 const char Condition[] = "Condition";
703 void KDebugger::saveBreakpoints(KSimpleConfig* config)
705 QString groupName;
706 int i = 0;
707 for (uint j = 0; j < m_brkpts.size(); j++) {
708 Breakpoint* bp = m_brkpts[j];
709 if (bp->type == Breakpoint::watchpoint)
710 continue; /* don't save watchpoints */
711 groupName.sprintf(BPGroup, i++);
712 config->setGroup(groupName);
713 if (!bp->fileName.isEmpty()) {
714 config->writeEntry(File, bp->fileName);
715 config->writeEntry(Line, bp->lineNo);
717 * Addresses are hardly correct across sessions, so we remove
718 * it since we have a file name and line number.
720 config->deleteEntry(Address, false);
721 } else {
722 config->writeEntry(Address, bp->address.asString());
723 /* remove remmants */
724 config->deleteEntry(File, false);
725 config->deleteEntry(Line, false);
727 config->writeEntry(Temporary, bp->temporary);
728 config->writeEntry(Enabled, bp->enabled);
729 if (bp->condition.isEmpty())
730 config->deleteEntry(Condition, false);
731 else
732 config->writeEntry(Condition, bp->condition);
733 // we do not save the ignore count
735 // delete remaining groups
736 // we recognize that a group is present if there is an Enabled entry
737 for (;; i++) {
738 groupName.sprintf(BPGroup, i);
739 config->setGroup(groupName);
740 if (!config->hasKey(Enabled)) {
741 /* group not present, assume that we've hit them all */
742 break;
744 config->deleteGroup(groupName);
748 void KDebugger::restoreBreakpoints(KSimpleConfig* config)
750 QString groupName;
752 * We recognize the end of the list if there is no Enabled entry
753 * present.
755 for (int i = 0;; i++) {
756 groupName.sprintf(BPGroup, i);
757 config->setGroup(groupName);
758 if (!config->hasKey(Enabled)) {
759 /* group not present, assume that we've hit them all */
760 break;
762 Breakpoint* bp = new Breakpoint;
763 bp->fileName = config->readEntry(File);
764 bp->lineNo = config->readNumEntry(Line, -1);
765 bp->address = config->readEntry(Address);
766 if ((bp->fileName.isEmpty() || bp->lineNo < 0) && bp->address.isEmpty()) {
767 delete bp;
768 continue;
770 bp->enabled = config->readBoolEntry(Enabled, true);
771 bp->temporary = config->readBoolEntry(Temporary, false);
772 bp->condition = config->readEntry(Condition);
775 * Add the breakpoint.
777 CmdQueueItem* cmd;
778 if (!bp->fileName.isEmpty()) {
779 cmd = m_d->executeCmd(bp->temporary ? DCtbreakline : DCbreakline,
780 bp->fileName, bp->lineNo);
781 } else {
782 cmd = m_d->executeCmd(bp->temporary ? DCtbreakaddr : DCbreakaddr,
783 bp->address.asString());
785 // the new breakpoint is disabled or conditionalized later
786 // in newBreakpoint() using this reference:
787 cmd->m_brkpt = bp;
789 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverride);
793 // parse output of command cmd
794 void KDebugger::parse(CmdQueueItem* cmd, const char* output)
796 ASSERT(cmd != 0); /* queue mustn't be empty */
798 TRACE(QString(__PRETTY_FUNCTION__) + " parsing " + output);
800 switch (cmd->m_cmd) {
801 case DCtargetremote:
802 // the output (if any) is uninteresting
803 case DCsetargs:
804 case DCtty:
805 // there is no output
806 case DCsetenv:
807 case DCunsetenv:
808 case DCsetoption:
809 /* if value is empty, we see output, but we don't care */
810 break;
811 case DCcd:
812 /* display gdb's message in the status bar */
813 m_d->parseChangeWD(output, m_statusMessage);
814 emit updateStatusMessage();
815 break;
816 case DCinitialize:
817 break;
818 case DCexecutable:
819 if (m_d->parseChangeExecutable(output, m_statusMessage))
821 // success; restore breakpoints etc.
822 if (m_programConfig != 0) {
823 restoreProgramSettings();
825 // load file containing main() or core file
826 if (m_corefile.isEmpty()) {
827 if (m_remoteDevice.isEmpty())
828 m_d->queueCmd(DCinfolinemain, DebuggerDriver::QMnormal);
829 } else {
830 // load core file
831 loadCoreFile();
833 if (!m_statusMessage.isEmpty())
834 emit updateStatusMessage();
835 } else {
836 QString msg = m_d->driverName() + ": " + m_statusMessage;
837 KMessageBox::sorry(parentWidget(), msg);
838 m_executable = "";
839 m_corefile = ""; /* don't process core file */
840 m_haveExecutable = false;
842 break;
843 case DCcorefile:
844 // in any event we have an executable at this point
845 m_haveExecutable = true;
846 if (m_d->parseCoreFile(output)) {
847 // loading a core is like stopping at a breakpoint
848 m_programActive = true;
849 handleRunCommands(output);
850 // do not reset m_corefile
851 } else {
852 // report error
853 QString msg = m_d->driverName() + ": " + QString(output);
854 KMessageBox::sorry(parentWidget(), msg);
856 // if core file was loaded from command line, revert to info line main
857 if (!cmd->m_byUser) {
858 m_d->queueCmd(DCinfolinemain, DebuggerDriver::QMnormal);
860 m_corefile = QString(); /* core file not available any more */
862 break;
863 case DCinfolinemain:
864 // ignore the output, marked file info follows
865 m_haveExecutable = true;
866 break;
867 case DCinfolocals:
868 // parse local variables
869 if (output[0] != '\0') {
870 handleLocals(output);
872 break;
873 case DCinforegisters:
874 handleRegisters(output);
875 break;
876 case DCexamine:
877 handleMemoryDump(output);
878 break;
879 case DCinfoline:
880 handleInfoLine(cmd, output);
881 break;
882 case DCdisassemble:
883 handleDisassemble(cmd, output);
884 break;
885 case DCframe:
886 handleFrameChange(output);
887 updateAllExprs();
888 break;
889 case DCbt:
890 handleBacktrace(output);
891 updateAllExprs();
892 break;
893 case DCprint:
894 handlePrint(cmd, output);
895 break;
896 case DCattach:
897 case DCrun:
898 case DCcont:
899 case DCstep:
900 case DCstepi:
901 case DCnext:
902 case DCnexti:
903 case DCfinish:
904 case DCuntil:
905 case DCthread:
906 handleRunCommands(output);
907 break;
908 case DCkill:
909 m_programRunning = m_programActive = false;
910 // erase PC
911 emit updatePC(QString(), -1, DbgAddr(), 0);
912 break;
913 case DCbreaktext:
914 case DCbreakline:
915 case DCtbreakline:
916 case DCbreakaddr:
917 case DCtbreakaddr:
918 case DCwatchpoint:
919 newBreakpoint(cmd, output);
920 // fall through
921 case DCdelete:
922 case DCenable:
923 case DCdisable:
924 // these commands need immediate response
925 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverrideMoreEqual);
926 break;
927 case DCinfobreak:
928 // note: this handler must not enqueue a command, since
929 // DCinfobreak is used at various different places.
930 updateBreakList(output);
931 emit lineItemsChanged();
932 break;
933 case DCfindType:
934 handleFindType(cmd, output);
935 break;
936 case DCprintStruct:
937 case DCprintQStringStruct:
938 handlePrintStruct(cmd, output);
939 break;
940 case DCinfosharedlib:
941 handleSharedLibs(output);
942 break;
943 case DCcondition:
944 case DCignore:
945 // we are not interested in the output
946 break;
947 case DCinfothreads:
948 handleThreadList(output);
949 break;
950 case DCsetpc:
951 handleSetPC(output);
952 break;
956 void KDebugger::backgroundUpdate()
959 * If there are still expressions that need to be updated, then do so.
961 if (m_programActive)
962 evalExpressions();
965 void KDebugger::handleRunCommands(const char* output)
967 uint flags = m_d->parseProgramStopped(output, m_statusMessage);
968 emit updateStatusMessage();
970 m_programActive = flags & DebuggerDriver::SFprogramActive;
972 // refresh files if necessary
973 if (flags & DebuggerDriver::SFrefreshSource) {
974 TRACE("re-reading files");
975 emit executableUpdated();
979 * If we stopped at a breakpoint, we must update the breakpoint list
980 * because the hit count changes. Also, if the breakpoint was temporary
981 * it would go away now.
983 if ((flags & (DebuggerDriver::SFrefreshBreak|DebuggerDriver::SFrefreshSource)) ||
984 stopMayChangeBreakList())
986 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverride);
990 * If we haven't listed the shared libraries yet, do so. We must do
991 * this before we emit any commands that list variables, since the type
992 * libraries depend on the shared libraries.
994 if (!m_sharedLibsListed) {
995 // must be a high-priority command!
996 m_d->executeCmd(DCinfosharedlib);
999 // get the backtrace if the program is running
1000 if (m_programActive) {
1001 m_d->queueCmd(DCbt, DebuggerDriver::QMoverride);
1002 } else {
1003 // program finished: erase PC
1004 emit updatePC(QString(), -1, DbgAddr(), 0);
1005 // dequeue any commands in the queues
1006 m_d->flushCommands();
1009 /* Update threads list */
1010 if (flags & DebuggerDriver::SFrefreshThreads) {
1011 m_d->queueCmd(DCinfothreads, DebuggerDriver::QMoverride);
1014 m_programRunning = false;
1015 emit programStopped();
1018 void KDebugger::slotInferiorRunning()
1020 m_programRunning = true;
1023 void KDebugger::updateAllExprs()
1025 if (!m_programActive)
1026 return;
1028 // retrieve local variables
1029 m_d->queueCmd(DCinfolocals, DebuggerDriver::QMoverride);
1031 // retrieve registers
1032 m_d->queueCmd(DCinforegisters, DebuggerDriver::QMoverride);
1034 // get new memory dump
1035 if (!m_memoryExpression.isEmpty()) {
1036 queueMemoryDump(false);
1039 // update watch expressions
1040 KTreeViewItem* item = m_watchVariables.itemAt(0);
1041 for (; item != 0; item = item->getSibling()) {
1042 m_watchEvalExpr.append(static_cast<VarTree*>(item));
1046 void KDebugger::updateProgEnvironment(const QString& args, const QString& wd,
1047 const QDict<EnvVar>& newVars,
1048 const QStringList& newOptions)
1050 m_programArgs = args;
1051 m_d->executeCmd(DCsetargs, m_programArgs);
1052 TRACE("new pgm args: " + m_programArgs + "\n");
1054 m_programWD = wd.stripWhiteSpace();
1055 if (!m_programWD.isEmpty()) {
1056 m_d->executeCmd(DCcd, m_programWD);
1057 TRACE("new wd: " + m_programWD + "\n");
1060 // update environment variables
1061 QDictIterator<EnvVar> it = newVars;
1062 EnvVar* val;
1063 for (; (val = it) != 0; ++it) {
1064 QString var = it.currentKey();
1065 switch (val->status) {
1066 case EnvVar::EVnew:
1067 m_envVars.insert(var, val);
1068 // fall thru
1069 case EnvVar::EVdirty:
1070 // the value must be in our list
1071 ASSERT(m_envVars[var] == val);
1072 // update value
1073 m_d->executeCmd(DCsetenv, var, val->value);
1074 break;
1075 case EnvVar::EVdeleted:
1076 // must be in our list
1077 ASSERT(m_envVars[var] == val);
1078 // delete value
1079 m_d->executeCmd(DCunsetenv, var);
1080 m_envVars.remove(var);
1081 break;
1082 default:
1083 ASSERT(false);
1084 case EnvVar::EVclean:
1085 // variable not changed
1086 break;
1090 // update options
1091 QStringList::ConstIterator oi;
1092 for (oi = newOptions.begin(); oi != newOptions.end(); ++oi)
1094 if (m_boolOptions.findIndex(*oi) < 0) {
1095 // the options is currently not set, so set it
1096 m_d->executeCmd(DCsetoption, *oi, 1);
1097 } else {
1098 // option is set, no action required, but move it to the end
1099 m_boolOptions.remove(*oi);
1101 m_boolOptions.append(*oi);
1104 * Now all options that should be set are at the end of m_boolOptions.
1105 * If some options need to be unset, they are at the front of the list.
1106 * Here we unset and remove them.
1108 while (m_boolOptions.count() > newOptions.count()) {
1109 m_d->executeCmd(DCsetoption, m_boolOptions.first(), 0);
1110 m_boolOptions.remove(m_boolOptions.begin());
1114 void KDebugger::handleLocals(const char* output)
1116 // retrieve old list of local variables
1117 QStrList oldVars;
1118 m_localVariables.exprList(oldVars);
1121 * Get local variables.
1123 QList<VarTree> newVars;
1124 parseLocals(output, newVars);
1127 * Clear any old VarTree item pointers, so that later we don't access
1128 * dangling pointers.
1130 m_localVariables.clearPendingUpdates();
1132 // reduce flicker
1133 bool autoU = m_localVariables.autoUpdate();
1134 m_localVariables.setAutoUpdate(false);
1135 bool repaintNeeded = false;
1138 * Match old variables against new ones.
1140 for (const char* n = oldVars.first(); n != 0; n = oldVars.next()) {
1141 // lookup this variable in the list of new variables
1142 VarTree* v = newVars.first();
1143 while (v != 0 && strcmp(v->getText(), n) != 0) {
1144 v = newVars.next();
1146 if (v == 0) {
1147 // old variable not in the new variables
1148 TRACE(QString("old var deleted: ") + n);
1149 v = m_localVariables.topLevelExprByName(n);
1150 removeExpr(&m_localVariables, v);
1151 if (v != 0) repaintNeeded = true;
1152 } else {
1153 // variable in both old and new lists: update
1154 TRACE(QString("update var: ") + n);
1155 m_localVariables.updateExpr(newVars.current());
1156 // remove the new variable from the list
1157 newVars.remove();
1158 delete v;
1159 repaintNeeded = true;
1162 // insert all remaining new variables
1163 for (VarTree* v = newVars.first(); v != 0; v = newVars.next()) {
1164 TRACE("new var: " + v->getText());
1165 m_localVariables.insertExpr(v);
1166 repaintNeeded = true;
1169 // repaint
1170 m_localVariables.setAutoUpdate(autoU);
1171 if (repaintNeeded && autoU && m_localVariables.isVisible())
1172 m_localVariables.repaint();
1175 void KDebugger::parseLocals(const char* output, QList<VarTree>& newVars)
1177 QList<VarTree> vars;
1178 m_d->parseLocals(output, vars);
1180 QString origName; /* used in renaming variables */
1181 while (vars.count() > 0)
1183 VarTree* variable = vars.take(0);
1184 // get some types
1185 variable->inferTypesOfChildren(*m_typeTable);
1187 * When gdb prints local variables, those from the innermost block
1188 * come first. We run through the list of already parsed variables
1189 * to find duplicates (ie. variables that hide local variables from
1190 * a surrounding block). We keep the name of the inner variable, but
1191 * rename those from the outer block so that, when the value is
1192 * updated in the window, the value of the variable that is
1193 * _visible_ changes the color!
1195 int block = 0;
1196 origName = variable->getText();
1197 for (VarTree* v = newVars.first(); v != 0; v = newVars.next()) {
1198 if (variable->getText() == v->getText()) {
1199 // we found a duplicate, change name
1200 block++;
1201 QString newName = origName + " (" + QString().setNum(block) + ")";
1202 variable->setText(newName);
1205 newVars.append(variable);
1209 bool KDebugger::handlePrint(CmdQueueItem* cmd, const char* output)
1211 ASSERT(cmd->m_expr != 0);
1213 VarTree* variable = parseExpr(output, true);
1214 if (variable == 0)
1215 return false;
1217 // set expression "name"
1218 variable->setText(cmd->m_expr->getText());
1220 if (cmd->m_expr->m_varKind == VarTree::VKpointer) {
1222 * We must insert a dummy parent, because otherwise variable's value
1223 * would overwrite cmd->m_expr's value.
1225 VarTree* dummyParent = new VarTree(variable->getText(), VarTree::NKplain);
1226 dummyParent->m_varKind = VarTree::VKdummy;
1227 // the name of the parsed variable is the address of the pointer
1228 QString addr = "*" + cmd->m_expr->m_value;
1229 variable->setText(addr);
1230 variable->m_nameKind = VarTree::NKaddress;
1232 dummyParent->appendChild(variable);
1233 dummyParent->setDeleteChildren(true);
1234 // expand the first level for convenience
1235 variable->setExpanded(true);
1236 TRACE("update ptr: " + cmd->m_expr->getText());
1237 cmd->m_exprWnd->updateExpr(cmd->m_expr, dummyParent);
1238 delete dummyParent;
1239 } else {
1240 TRACE("update expr: " + cmd->m_expr->getText());
1241 cmd->m_exprWnd->updateExpr(cmd->m_expr, variable);
1242 delete variable;
1245 evalExpressions(); /* enqueue dereferenced pointers */
1247 return true;
1250 VarTree* KDebugger::parseExpr(const char* output, bool wantErrorValue)
1252 VarTree* variable;
1254 // check for error conditions
1255 bool goodValue = m_d->parsePrintExpr(output, wantErrorValue, variable);
1257 if (variable != 0 && goodValue)
1259 // get some types
1260 variable->inferTypesOfChildren(*m_typeTable);
1262 return variable;
1265 // parse the output of bt
1266 void KDebugger::handleBacktrace(const char* output)
1268 // reduce flicker
1269 m_btWindow.setAutoUpdate(false);
1271 m_btWindow.clear();
1273 QList<StackFrame> stack;
1274 m_d->parseBackTrace(output, stack);
1276 if (stack.count() > 0) {
1277 StackFrame* frm = stack.take(0);
1278 // first frame must set PC
1279 // note: frm->lineNo is zero-based
1280 emit updatePC(frm->fileName, frm->lineNo, frm->address, frm->frameNo);
1282 do {
1283 QString func;
1284 if (frm->var != 0)
1285 func = frm->var->getText();
1286 else
1287 func = frm->fileName + ":" + QString().setNum(frm->lineNo+1);
1288 m_btWindow.insertItem(func);
1289 TRACE("frame " + func + " (" + frm->fileName + ":" +
1290 QString().setNum(frm->lineNo+1) + ")");
1291 delete frm;
1293 while ((frm = stack.take()) != 0);
1296 m_btWindow.setAutoUpdate(true);
1297 m_btWindow.repaint();
1300 void KDebugger::gotoFrame(int frame)
1302 m_d->executeCmd(DCframe, frame);
1305 void KDebugger::handleFrameChange(const char* output)
1307 QString fileName;
1308 int frameNo;
1309 int lineNo;
1310 DbgAddr address;
1311 if (m_d->parseFrameChange(output, frameNo, fileName, lineNo, address)) {
1312 /* lineNo can be negative here if we can't find a file name */
1313 emit updatePC(fileName, lineNo, address, frameNo);
1314 } else {
1315 emit updatePC(fileName, -1, address, frameNo);
1319 void KDebugger::evalExpressions()
1321 // evaluate expressions in the following order:
1322 // watch expressions
1323 // pointers in local variables
1324 // pointers in watch expressions
1325 // types in local variables
1326 // types in watch expressions
1327 // pointers in 'this'
1328 // types in 'this'
1330 VarTree* exprItem = m_watchEvalExpr.first();
1331 if (exprItem != 0) {
1332 m_watchEvalExpr.remove();
1333 QString expr = exprItem->computeExpr();
1334 TRACE("watch expr: " + expr);
1335 CmdQueueItem* cmd = m_d->queueCmd(DCprint, expr, DebuggerDriver::QMoverride);
1336 // remember which expr this was
1337 cmd->m_expr = exprItem;
1338 cmd->m_exprWnd = &m_watchVariables;
1339 } else {
1340 ExprWnd* wnd;
1341 VarTree* exprItem;
1342 #define POINTER(widget) \
1343 wnd = &widget; \
1344 exprItem = widget.nextUpdatePtr(); \
1345 if (exprItem != 0) goto pointer
1346 #define STRUCT(widget) \
1347 wnd = &widget; \
1348 exprItem = widget.nextUpdateStruct(); \
1349 if (exprItem != 0) goto ustruct
1350 #define TYPE(widget) \
1351 wnd = &widget; \
1352 exprItem = widget.nextUpdateType(); \
1353 if (exprItem != 0) goto type
1354 repeat:
1355 POINTER(m_localVariables);
1356 POINTER(m_watchVariables);
1357 STRUCT(m_localVariables);
1358 STRUCT(m_watchVariables);
1359 TYPE(m_localVariables);
1360 TYPE(m_watchVariables);
1361 #undef POINTER
1362 #undef STRUCT
1363 #undef TYPE
1364 return;
1366 pointer:
1367 // we have an expression to send
1368 dereferencePointer(wnd, exprItem, false);
1369 return;
1371 ustruct:
1372 // paranoia
1373 if (exprItem->m_type == 0 || exprItem->m_type == TypeInfo::unknownType())
1374 goto repeat;
1375 evalInitialStructExpression(exprItem, wnd, false);
1376 return;
1378 type:
1380 * Sometimes a VarTree gets registered twice for a type update. So
1381 * it may happen that it has already been updated. Hence, we ignore
1382 * it here and go on to the next task.
1384 if (exprItem->m_type != 0)
1385 goto repeat;
1386 determineType(wnd, exprItem);
1390 void KDebugger::dereferencePointer(ExprWnd* wnd, VarTree* exprItem,
1391 bool immediate)
1393 ASSERT(exprItem->m_varKind == VarTree::VKpointer);
1395 QString expr = exprItem->computeExpr();
1396 TRACE("dereferencing pointer: " + expr);
1397 QString queueExpr = "*(" + expr + ")";
1398 CmdQueueItem* cmd;
1399 if (immediate) {
1400 cmd = m_d->queueCmd(DCprint, queueExpr, DebuggerDriver::QMoverrideMoreEqual);
1401 } else {
1402 cmd = m_d->queueCmd(DCprint, queueExpr, DebuggerDriver::QMoverride);
1404 // remember which expr this was
1405 cmd->m_expr = exprItem;
1406 cmd->m_exprWnd = wnd;
1409 void KDebugger::determineType(ExprWnd* wnd, VarTree* exprItem)
1411 ASSERT(exprItem->m_varKind == VarTree::VKstruct);
1413 QString expr = exprItem->computeExpr();
1414 TRACE("get type of: " + expr);
1415 CmdQueueItem* cmd;
1416 cmd = m_d->queueCmd(DCfindType, expr, DebuggerDriver::QMoverride);
1418 // remember which expr this was
1419 cmd->m_expr = exprItem;
1420 cmd->m_exprWnd = wnd;
1423 void KDebugger::handleFindType(CmdQueueItem* cmd, const char* output)
1425 QString type;
1426 if (m_d->parseFindType(output, type))
1428 ASSERT(cmd != 0 && cmd->m_expr != 0);
1430 TypeInfo* info = m_typeTable->lookup(type);
1432 if (info == 0) {
1434 * We've asked gdb for the type of the expression in
1435 * cmd->m_expr, but it returned a name we don't know. The base
1436 * class (and member) types have been checked already (at the
1437 * time when we parsed that particular expression). Now it's
1438 * time to derive the type from the base classes as a last
1439 * resort.
1441 info = cmd->m_expr->inferTypeFromBaseClass();
1442 // if we found a type through this method, register an alias
1443 if (info != 0) {
1444 TRACE("infered alias: " + type);
1445 m_typeTable->registerAlias(type, info);
1448 if (info == 0) {
1449 TRACE("unknown type");
1450 cmd->m_expr->m_type = TypeInfo::unknownType();
1451 } else {
1452 cmd->m_expr->m_type = info;
1453 /* since this node has a new type, we get its value immediately */
1454 evalInitialStructExpression(cmd->m_expr, cmd->m_exprWnd, false);
1455 return;
1459 evalExpressions(); /* queue more of them */
1462 void KDebugger::handlePrintStruct(CmdQueueItem* cmd, const char* output)
1464 VarTree* var = cmd->m_expr;
1465 ASSERT(var != 0);
1466 ASSERT(var->m_varKind == VarTree::VKstruct);
1468 VarTree* partExpr;
1469 if (cmd->m_cmd != DCprintQStringStruct) {
1470 partExpr = parseExpr(output, false);
1471 } else {
1472 partExpr = m_d->parseQCharArray(output, false, m_typeTable->qCharIsShort());
1474 bool errorValue =
1475 partExpr == 0 ||
1476 /* we only allow simple values at the moment */
1477 partExpr->childCount() != 0;
1479 QString partValue;
1480 if (errorValue)
1482 partValue = "?""?""?"; // 2 question marks in a row would be a trigraph
1483 } else {
1484 partValue = partExpr->m_value;
1486 delete partExpr;
1487 partExpr = 0;
1490 * Updating a struct value works like this: var->m_partialValue holds
1491 * the value that we have gathered so far (it's been initialized with
1492 * var->m_type->m_displayString[0] earlier). Each time we arrive here,
1493 * we append the printed result followed by the next
1494 * var->m_type->m_displayString to var->m_partialValue.
1496 * If the expression we just evaluated was a guard expression, and it
1497 * resulted in an error, we must not evaluate the real expression, but
1498 * go on to the next index. (We must still add the question marks to
1499 * the value).
1501 * Next, if this was the length expression, we still have not seen the
1502 * real expression, but the length of a QString.
1504 ASSERT(var->m_exprIndex >= 0 && var->m_exprIndex <= typeInfoMaxExpr);
1506 if (errorValue || !var->m_exprIndexUseGuard)
1508 // add current partValue (which might be the question marks)
1509 var->m_partialValue += partValue;
1510 var->m_exprIndex++; /* next part */
1511 var->m_exprIndexUseGuard = true;
1512 var->m_partialValue += var->m_type->m_displayString[var->m_exprIndex];
1514 else
1516 // this was a guard expression that succeeded
1517 // go for the real expression
1518 var->m_exprIndexUseGuard = false;
1521 /* go for more sub-expressions if needed */
1522 if (var->m_exprIndex < var->m_type->m_numExprs) {
1523 /* queue a new print command with quite high priority */
1524 evalStructExpression(var, cmd->m_exprWnd, true);
1525 return;
1528 cmd->m_exprWnd->updateStructValue(var);
1530 evalExpressions(); /* enqueue dereferenced pointers */
1533 /* queues the first printStruct command for a struct */
1534 void KDebugger::evalInitialStructExpression(VarTree* var, ExprWnd* wnd, bool immediate)
1536 var->m_exprIndex = 0;
1537 var->m_exprIndexUseGuard = true;
1538 var->m_partialValue = var->m_type->m_displayString[0];
1539 evalStructExpression(var, wnd, immediate);
1542 /* queues a printStruct command; var must have been initialized correctly */
1543 void KDebugger::evalStructExpression(VarTree* var, ExprWnd* wnd, bool immediate)
1545 QString base = var->computeExpr();
1546 QString exprFmt;
1547 if (var->m_exprIndexUseGuard) {
1548 exprFmt = var->m_type->m_guardStrings[var->m_exprIndex];
1549 if (exprFmt.isEmpty()) {
1550 // no guard, omit it and go to expression
1551 var->m_exprIndexUseGuard = false;
1554 if (!var->m_exprIndexUseGuard) {
1555 exprFmt = var->m_type->m_exprStrings[var->m_exprIndex];
1558 SIZED_QString(expr, exprFmt.length() + base.length() + 10);
1559 expr.sprintf(exprFmt, base.data());
1561 DbgCommand dbgCmd = DCprintStruct;
1562 // check if this is a QString::Data
1563 if (strncmp(expr, "/QString::Data ", 15) == 0)
1565 if (m_typeTable->parseQt2QStrings())
1567 expr = expr.mid(15, expr.length()); /* strip off /QString::Data */
1568 dbgCmd = DCprintQStringStruct;
1569 } else {
1571 * This should not happen: the type libraries should be set up
1572 * in a way that this can't happen. If this happens
1573 * nevertheless it means that, eg., kdecore was loaded but qt2
1574 * was not (only qt2 enables the QString feature).
1576 // TODO: remove this "print"; queue the next printStruct instead
1577 expr = "*0";
1579 } else {
1580 expr = expr;
1582 TRACE("evalStruct: " + expr + (var->m_exprIndexUseGuard ? " // guard" : " // real"));
1583 CmdQueueItem* cmd = m_d->queueCmd(dbgCmd, expr,
1584 immediate ? DebuggerDriver::QMoverrideMoreEqual
1585 : DebuggerDriver::QMnormal);
1587 // remember which expression this was
1588 cmd->m_expr = var;
1589 cmd->m_exprWnd = wnd;
1592 /* removes expression from window */
1593 void KDebugger::removeExpr(ExprWnd* wnd, VarTree* var)
1595 if (var == 0)
1596 return;
1598 // must remove any references to var from command queues
1599 m_d->dequeueCmdByVar(var);
1601 wnd->removeExpr(var);
1604 void KDebugger::handleSharedLibs(const char* output)
1606 // delete all known libraries
1607 m_sharedLibs.clear();
1609 // parse the table of shared libraries
1610 m_d->parseSharedLibs(output, m_sharedLibs);
1611 m_sharedLibsListed = true;
1613 // get type libraries
1614 m_typeTable->loadLibTypes(m_sharedLibs);
1617 CmdQueueItem* KDebugger::loadCoreFile()
1619 return m_d->queueCmd(DCcorefile, m_corefile, DebuggerDriver::QMoverride);
1622 void KDebugger::slotLocalsExpanding(KTreeViewItem* item, bool& allow)
1624 exprExpandingHelper(&m_localVariables, item, allow);
1627 void KDebugger::slotWatchExpanding(KTreeViewItem* item, bool& allow)
1629 exprExpandingHelper(&m_watchVariables, item, allow);
1632 void KDebugger::exprExpandingHelper(ExprWnd* wnd, KTreeViewItem* item, bool&)
1634 VarTree* exprItem = static_cast<VarTree*>(item);
1635 if (exprItem->m_varKind != VarTree::VKpointer) {
1636 return;
1638 dereferencePointer(wnd, exprItem, true);
1641 // add the expression in the edit field to the watch expressions
1642 void KDebugger::addWatch(const QString& t)
1644 QString expr = t.stripWhiteSpace();
1645 if (expr.isEmpty())
1646 return;
1647 VarTree* exprItem = new VarTree(expr, VarTree::NKplain);
1648 m_watchVariables.insertExpr(exprItem);
1650 // if we are boring ourselves, send down the command
1651 if (m_programActive) {
1652 m_watchEvalExpr.append(exprItem);
1653 if (m_d->isIdle()) {
1654 evalExpressions();
1659 // delete a toplevel watch expression
1660 void KDebugger::slotDeleteWatch()
1662 // delete only allowed while debugger is idle; or else we might delete
1663 // the very expression the debugger is currently working on...
1664 if (!m_d->isIdle())
1665 return;
1667 int index = m_watchVariables.currentItem();
1668 if (index < 0)
1669 return;
1671 VarTree* item = static_cast<VarTree*>(m_watchVariables.itemAt(index));
1672 if (!item->isToplevelExpr())
1673 return;
1675 // remove the variable from the list to evaluate
1676 if (m_watchEvalExpr.findRef(item) >= 0) {
1677 m_watchEvalExpr.remove();
1679 removeExpr(&m_watchVariables, item);
1680 // item is invalid at this point!
1683 void KDebugger::startAnimation(bool fast)
1685 int interval = fast ? 50 : 150;
1686 if (!m_animationTimer.isActive()) {
1687 m_animationTimer.start(interval);
1688 } else if (m_animationInterval != interval) {
1689 m_animationTimer.changeInterval(interval);
1691 m_animationInterval = interval;
1694 void KDebugger::stopAnimation()
1696 if (m_animationTimer.isActive()) {
1697 m_animationTimer.stop();
1698 m_animationInterval = 0;
1702 void KDebugger::slotUpdateAnimation()
1704 if (isIdle()) {
1705 stopAnimation();
1706 } else {
1708 * Slow animation while program is stopped (i.e. while variables
1709 * are displayed)
1711 bool slow = isReady() && m_programActive && !m_programRunning;
1712 startAnimation(!slow);
1716 void KDebugger::handleRegisters(const char* output)
1718 QList<RegisterInfo> regs;
1719 m_d->parseRegisters(output, regs);
1721 emit registersChanged(regs);
1723 // delete them all
1724 regs.setAutoDelete(true);
1728 * The output of the DCbreak* commands has more accurate information about
1729 * the file and the line number.
1731 void KDebugger::newBreakpoint(CmdQueueItem* cmd, const char* output)
1733 int id;
1734 QString file;
1735 int lineNo;
1736 QString address;
1737 if (!m_d->parseBreakpoint(output, id, file, lineNo, address))
1739 delete cmd->m_brkpt;
1740 return;
1743 // is this a breakpoint restored from the settings?
1744 if (cmd->m_brkpt != 0)
1746 // yes, add it
1747 cmd->m_brkpt->id = id;
1749 int n = m_brkpts.size();
1750 m_brkpts.resize(n+1);
1751 m_brkpts.insert(n, cmd->m_brkpt);
1753 // set the remaining properties
1754 if (!cmd->m_brkpt->enabled) {
1755 m_d->executeCmd(DCdisable, id);
1757 if (!cmd->m_brkpt->condition.isEmpty()) {
1758 m_d->executeCmd(DCcondition, cmd->m_brkpt->condition, id);
1762 // see if it is new
1763 for (int i = m_brkpts.size()-1; i >= 0; i--) {
1764 if (m_brkpts[i]->id == id) {
1765 // not new; update
1766 m_brkpts[i]->fileName = file;
1767 m_brkpts[i]->lineNo = lineNo;
1768 if (!address.isEmpty())
1769 m_brkpts[i]->address = address;
1770 return;
1773 // yes, new
1774 Breakpoint* bp = new Breakpoint;
1775 bp->id = id;
1776 bp->fileName = file;
1777 bp->lineNo = lineNo;
1778 bp->address = address;
1779 int n = m_brkpts.size();
1780 m_brkpts.resize(n+1);
1781 m_brkpts.insert(n, bp);
1784 void KDebugger::updateBreakList(const char* output)
1786 // get the new list
1787 QList<Breakpoint> brks;
1788 brks.setAutoDelete(false);
1789 m_d->parseBreakList(output, brks);
1791 // merge new information into existing breakpoints
1793 for (int i = m_brkpts.size()-1; i >= 0; i--) // decrement!
1795 for (Breakpoint* bp = brks.first(); bp != 0; bp = brks.next())
1797 if (bp->id == m_brkpts[i]->id) {
1798 // keep accurate location
1799 bp->fileName = m_brkpts[i]->fileName;
1800 bp->lineNo = m_brkpts[i]->lineNo;
1801 m_brkpts.insert(i, bp); // old object is deleted
1802 goto stillAlive;
1806 * If we get here, this breakpoint is no longer present.
1808 * To delete the breakpoint at i, we place the last breakpoint in
1809 * the list into the slot i. This will delete the old object at i.
1810 * Then we shorten the list by one.
1812 m_brkpts.insert(i, m_brkpts.take(m_brkpts.size()-1));
1813 m_brkpts.resize(m_brkpts.size()-1);
1814 TRACE(QString().sprintf("deleted brkpt %d, have now %d brkpts", i, m_brkpts.size()));
1816 stillAlive:;
1819 emit breakpointsChanged();
1822 // look if there is at least one temporary breakpoint
1823 // or a watchpoint
1824 bool KDebugger::stopMayChangeBreakList() const
1826 for (int i = m_brkpts.size()-1; i >= 0; i--) {
1827 Breakpoint* bp = m_brkpts[i];
1828 if (bp->temporary || bp->type == Breakpoint::watchpoint)
1829 return true;
1831 return false;
1834 Breakpoint* KDebugger::breakpointByFilePos(QString file, int lineNo,
1835 const DbgAddr& address)
1837 // look for exact file name match
1838 int i;
1839 for (i = m_brkpts.size()-1; i >= 0; i--) {
1840 if (m_brkpts[i]->lineNo == lineNo &&
1841 m_brkpts[i]->fileName == file &&
1842 (address.isEmpty() || m_brkpts[i]->address == address))
1844 return m_brkpts[i];
1847 // not found, so try basename
1848 // strip off directory part of file name
1849 int offset = file.findRev("/");
1850 file.remove(0, offset+1);
1852 for (i = m_brkpts.size()-1; i >= 0; i--) {
1853 // get base name of breakpoint's file
1854 QString basename = m_brkpts[i]->fileName;
1855 int offset = basename.findRev("/");
1856 if (offset >= 0) {
1857 basename.remove(0, offset+1);
1860 if (m_brkpts[i]->lineNo == lineNo &&
1861 basename == file &&
1862 (address.isEmpty() || m_brkpts[i]->address == address))
1864 return m_brkpts[i];
1868 // not found
1869 return 0;
1872 void KDebugger::slotValuePopup(const QString& expr)
1874 // search the local variables for a match
1875 VarTree* v = m_localVariables.topLevelExprByName(expr);
1876 if (v == 0) {
1877 // not found, check watch expressions
1878 v = m_watchVariables.topLevelExprByName(expr);
1879 if (v == 0) {
1880 // nothing found; do nothing
1881 return;
1885 // construct the tip
1886 QString tip = v->getText() + " = ";
1887 if (!v->m_value.isEmpty())
1889 tip += v->m_value;
1891 else
1893 // no value: we use some hint
1894 switch (v->m_varKind) {
1895 case VarTree::VKstruct:
1896 tip += "{...}";
1897 break;
1898 case VarTree::VKarray:
1899 tip += "[...]";
1900 break;
1901 default:
1902 tip += "?""?""?"; // 2 question marks in a row would be a trigraph
1903 break;
1906 emit valuePopup(tip);
1909 void KDebugger::slotDisassemble(const QString& fileName, int lineNo)
1911 CmdQueueItem* cmd = m_d->queueCmd(DCinfoline, fileName, lineNo,
1912 DebuggerDriver::QMoverrideMoreEqual);
1913 cmd->m_fileName = fileName;
1914 cmd->m_lineNo = lineNo;
1917 void KDebugger::handleInfoLine(CmdQueueItem* cmd, const char* output)
1919 QString addrFrom, addrTo;
1920 if (cmd->m_lineNo >= 0) {
1921 // disassemble
1922 if (m_d->parseInfoLine(output, addrFrom, addrTo)) {
1923 // got the address range, now get the real code
1924 CmdQueueItem* c = m_d->queueCmd(DCdisassemble, addrFrom, addrTo,
1925 DebuggerDriver::QMoverrideMoreEqual);
1926 c->m_fileName = cmd->m_fileName;
1927 c->m_lineNo = cmd->m_lineNo;
1928 } else {
1929 // no code
1930 QList<DisassembledCode> empty;
1931 emit disassembled(cmd->m_fileName, cmd->m_lineNo, empty);
1933 } else {
1934 // set program counter
1935 if (m_d->parseInfoLine(output, addrFrom, addrTo)) {
1936 // move the program counter to the start address
1937 m_d->executeCmd(DCsetpc, addrFrom);
1942 void KDebugger::handleDisassemble(CmdQueueItem* cmd, const char* output)
1944 QList<DisassembledCode> code;
1945 code.setAutoDelete(true);
1946 m_d->parseDisassemble(output, code);
1947 emit disassembled(cmd->m_fileName, cmd->m_lineNo, code);
1950 void KDebugger::handleThreadList(const char* output)
1952 QList<ThreadInfo> threads;
1953 threads.setAutoDelete(true);
1954 m_d->parseThreadList(output, threads);
1955 emit threadsChanged(threads);
1958 void KDebugger::setThread(int id)
1960 m_d->queueCmd(DCthread, id, DebuggerDriver::QMoverrideMoreEqual);
1963 void KDebugger::setMemoryExpression(const QString& memexpr)
1965 m_memoryExpression = memexpr;
1967 // queue the new expression
1968 if (!m_memoryExpression.isEmpty() &&
1969 isProgramActive() &&
1970 !isProgramRunning())
1972 queueMemoryDump(true);
1976 void KDebugger::queueMemoryDump(bool immediate)
1978 m_d->queueCmd(DCexamine, m_memoryExpression, m_memoryFormat,
1979 immediate ? DebuggerDriver::QMoverrideMoreEqual :
1980 DebuggerDriver::QMoverride);
1983 void KDebugger::handleMemoryDump(const char* output)
1985 QList<MemoryDump> memdump;
1986 memdump.setAutoDelete(true);
1987 QString msg = m_d->parseMemoryDump(output, memdump);
1988 emit memoryDumpChanged(msg, memdump);
1991 void KDebugger::setProgramCounter(const QString& file, int line, const DbgAddr& addr)
1993 if (addr.isEmpty()) {
1994 // find address of the specified line
1995 CmdQueueItem* cmd = m_d->executeCmd(DCinfoline, file, line);
1996 cmd->m_lineNo = -1; /* indicates "Set PC" UI command */
1997 } else {
1998 // move the program counter to that address
1999 m_d->executeCmd(DCsetpc, addr.asString());
2003 void KDebugger::handleSetPC(const char* /*output*/)
2005 // TODO: handle errors
2007 // now go to the top-most frame
2008 // this also modifies the program counter indicator in the UI
2009 gotoFrame(0);
2013 #include "debugger.moc"