Yet another strange gdb message is parsed.
[kdbg.git] / kdbg / debugger.cpp
blob3308351ef5f4923d2535df07d0c41827d978a887
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 "programconfig.h"
13 #include "valarray.h"
14 #include <qregexp.h>
15 #include <qfileinfo.h>
16 #include <qlistbox.h>
17 #include <qstringlist.h>
18 #include <kapp.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)
48 m_envVars.setAutoDelete(true);
49 m_brkpts.setAutoDelete(true);
51 connect(&m_localVariables, SIGNAL(expanding(KTreeViewItem*,bool&)),
52 SLOT(slotLocalsExpanding(KTreeViewItem*,bool&)));
53 connect(&m_watchVariables, SIGNAL(expanding(KTreeViewItem*,bool&)),
54 SLOT(slotWatchExpanding(KTreeViewItem*,bool&)));
55 connect(&m_localVariables, SIGNAL(editValueCommitted(int, const QString&)),
56 SLOT(slotValueEdited(int, const QString&)));
57 connect(&m_watchVariables, SIGNAL(editValueCommitted(int, const QString&)),
58 SLOT(slotValueEdited(int, const QString&)));
60 connect(&m_btWindow, SIGNAL(highlighted(int)), SLOT(gotoFrame(int)));
62 emit updateUI();
65 KDebugger::~KDebugger()
67 if (m_programConfig != 0) {
68 saveProgramSettings();
69 m_programConfig->sync();
70 delete m_programConfig;
73 delete m_typeTable;
77 void KDebugger::saveSettings(KConfig* /*config*/)
81 void KDebugger::restoreSettings(KConfig* /*config*/)
86 //////////////////////////////////////////////////////////////////////
87 // external interface
89 const char GeneralGroup[] = "General";
90 const char DebuggerCmdStr[] = "DebuggerCmdStr";
91 const char TTYLevelEntry[] = "TTYLevel";
92 const char KDebugger::DriverNameEntry[] = "DriverName";
94 bool KDebugger::debugProgram(const QString& name,
95 DebuggerDriver* driver)
97 if (m_d != 0 && m_d->isRunning())
99 QApplication::setOverrideCursor(waitCursor);
101 stopDriver();
103 QApplication::restoreOverrideCursor();
105 if (m_d->isRunning() || m_haveExecutable) {
106 /* timed out! We can't really do anything useful now */
107 TRACE("timed out while waiting for gdb to die!");
108 return false;
110 delete m_d;
111 m_d = 0;
114 // wire up the driver
115 connect(driver, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)),
116 this, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)));
117 connect(driver, SIGNAL(processExited(KProcess*)), SLOT(gdbExited(KProcess*)));
118 connect(driver, SIGNAL(commandReceived(CmdQueueItem*,const char*)),
119 SLOT(parse(CmdQueueItem*,const char*)));
120 connect(driver, SIGNAL(wroteStdin(KProcess*)), SIGNAL(updateUI()));
121 connect(driver, SIGNAL(inferiorRunning()), SLOT(slotInferiorRunning()));
122 connect(driver, SIGNAL(enterIdleState()), SLOT(backgroundUpdate()));
123 connect(driver, SIGNAL(enterIdleState()), SIGNAL(updateUI()));
125 // create the program settings object
126 openProgramConfig(name);
128 // get debugger command from per-program settings
129 if (m_programConfig != 0) {
130 m_programConfig->setGroup(GeneralGroup);
131 m_debuggerCmd = readDebuggerCmd();
132 // get terminal emulation level
133 m_ttyLevel = TTYLevel(m_programConfig->readNumEntry(TTYLevelEntry, ttyFull));
135 // the rest is read in later in the handler of DCexecutable
137 m_d = driver;
139 if (!startDriver()) {
140 TRACE("startDriver failed");
141 m_d = 0;
142 return false;
145 TRACE("before file cmd");
146 m_d->executeCmd(DCexecutable, name);
147 m_executable = name;
149 // set remote target
150 if (!m_remoteDevice.isEmpty()) {
151 m_d->executeCmd(DCtargetremote, m_remoteDevice);
152 m_d->queueCmd(DCbt, DebuggerDriver::QMoverride);
153 m_d->queueCmd(DCframe, 0, DebuggerDriver::QMnormal);
154 m_programActive = true;
155 m_haveExecutable = true;
158 // create a type table
159 m_typeTable = new ProgramTypeTable;
160 m_sharedLibsListed = false;
162 emit updateUI();
164 return true;
167 void KDebugger::shutdown()
169 // shut down debugger driver
170 if (m_d != 0 && m_d->isRunning())
172 stopDriver();
176 void KDebugger::useCoreFile(QString corefile, bool batch)
178 m_corefile = corefile;
179 if (!batch) {
180 CmdQueueItem* cmd = loadCoreFile();
181 cmd->m_byUser = true;
185 void KDebugger::setAttachPid(const QString& pid)
187 m_attachedPid = pid;
190 void KDebugger::programRun()
192 if (!isReady())
193 return;
195 // when program is active, but not a core file, continue
196 // otherwise run the program
197 if (m_programActive && m_corefile.isEmpty()) {
198 // gdb command: continue
199 m_d->executeCmd(DCcont, true);
200 } else {
201 // gdb command: run
202 m_d->executeCmd(DCrun, true);
203 m_corefile = QString();
204 m_programActive = true;
206 m_programRunning = true;
209 void KDebugger::attachProgram(const QString& pid)
211 if (!isReady())
212 return;
214 m_attachedPid = pid;
215 TRACE("Attaching to " + m_attachedPid);
216 m_d->executeCmd(DCattach, m_attachedPid);
217 m_programActive = true;
218 m_programRunning = true;
221 void KDebugger::programRunAgain()
223 if (canSingleStep()) {
224 m_d->executeCmd(DCrun, true);
225 m_corefile = QString();
226 m_programRunning = true;
230 void KDebugger::programStep()
232 if (canSingleStep()) {
233 m_d->executeCmd(DCstep, true);
234 m_programRunning = true;
238 void KDebugger::programNext()
240 if (canSingleStep()) {
241 m_d->executeCmd(DCnext, true);
242 m_programRunning = true;
246 void KDebugger::programStepi()
248 if (canSingleStep()) {
249 m_d->executeCmd(DCstepi, true);
250 m_programRunning = true;
254 void KDebugger::programNexti()
256 if (canSingleStep()) {
257 m_d->executeCmd(DCnexti, true);
258 m_programRunning = true;
262 void KDebugger::programFinish()
264 if (canSingleStep()) {
265 m_d->executeCmd(DCfinish, true);
266 m_programRunning = true;
270 void KDebugger::programKill()
272 if (haveExecutable() && isProgramActive()) {
273 if (m_programRunning) {
274 m_d->interruptInferior();
276 // this is an emergency command; flush queues
277 m_d->flushCommands(true);
278 m_d->executeCmd(DCkill, true);
282 bool KDebugger::runUntil(const QString& fileName, int lineNo)
284 if (isReady() && m_programActive && !m_programRunning) {
285 // strip off directory part of file name
286 QString file = fileName;
287 int offset = file.findRev("/");
288 if (offset >= 0) {
289 file.remove(0, offset+1);
291 m_d->executeCmd(DCuntil, file, lineNo, true);
292 m_programRunning = true;
293 return true;
294 } else {
295 return false;
299 void KDebugger::programBreak()
301 if (m_haveExecutable && m_programRunning) {
302 m_d->interruptInferior();
306 void KDebugger::programArgs(QWidget* parent)
308 if (m_haveExecutable) {
309 QStringList allOptions = m_d->boolOptionList();
310 PgmArgs dlg(parent, m_executable, m_envVars, allOptions);
311 dlg.setArgs(m_programArgs);
312 dlg.setWd(m_programWD);
313 dlg.setOptions(m_boolOptions);
314 if (dlg.exec()) {
315 updateProgEnvironment(dlg.args(), dlg.wd(),
316 dlg.envVars(), dlg.options());
321 void KDebugger::programSettings(QWidget* parent)
323 if (!m_haveExecutable)
324 return;
326 ProgramSettings dlg(parent, m_executable);
328 dlg.m_chooseDriver.setDebuggerCmd(m_debuggerCmd);
329 dlg.m_output.setTTYLevel(m_ttyLevel);
331 if (dlg.exec() == QDialog::Accepted)
333 m_debuggerCmd = dlg.m_chooseDriver.debuggerCmd();
334 m_ttyLevel = TTYLevel(dlg.m_output.ttyLevel());
338 bool KDebugger::setBreakpoint(QString file, int lineNo,
339 const DbgAddr& address, bool temporary)
341 if (!isReady()) {
342 return false;
345 Breakpoint* bp = breakpointByFilePos(file, lineNo, address);
346 if (bp == 0)
349 * No such breakpoint, so set a new one. If we have an address, we
350 * set the breakpoint exactly there. Otherwise we use the file name
351 * plus line no.
353 Breakpoint* bp = new Breakpoint;
354 bp->temporary = temporary;
356 if (address.isEmpty())
358 bp->fileName = file;
359 bp->lineNo = lineNo;
361 else
363 bp->address = address;
365 setBreakpoint(bp, false);
367 else
370 * If the breakpoint is disabled, enable it; if it's enabled,
371 * delete that breakpoint.
373 if (bp->enabled) {
374 deleteBreakpoint(bp);
375 } else {
376 enableDisableBreakpoint(bp);
379 return true;
382 void KDebugger::setBreakpoint(Breakpoint* bp, bool queueOnly)
384 CmdQueueItem* cmd;
385 if (!bp->text.isEmpty())
388 * The breakpoint was set using the text box in the breakpoint
389 * list. This is the only way in which watchpoints are set.
391 if (bp->type == Breakpoint::watchpoint) {
392 cmd = m_d->executeCmd(DCwatchpoint, bp->text);
393 } else {
394 cmd = m_d->executeCmd(DCbreaktext, bp->text);
397 else if (bp->address.isEmpty())
399 // strip off directory part of file name
400 QString file = bp->fileName;
401 int offset = file.findRev("/");
402 if (offset >= 0) {
403 file.remove(0, offset+1);
405 if (queueOnly) {
406 cmd = m_d->queueCmd(bp->temporary ? DCtbreakline : DCbreakline,
407 file, bp->lineNo, DebuggerDriver::QMoverride);
408 } else {
409 cmd = m_d->executeCmd(bp->temporary ? DCtbreakline : DCbreakline,
410 file, bp->lineNo);
413 else
415 if (queueOnly) {
416 cmd = m_d->queueCmd(bp->temporary ? DCtbreakaddr : DCbreakaddr,
417 bp->address.asString(), DebuggerDriver::QMoverride);
418 } else {
419 cmd = m_d->executeCmd(bp->temporary ? DCtbreakaddr : DCbreakaddr,
420 bp->address.asString());
423 cmd->m_brkpt = bp; // used in newBreakpoint()
426 bool KDebugger::enableDisableBreakpoint(QString file, int lineNo,
427 const DbgAddr& address)
429 Breakpoint* bp = breakpointByFilePos(file, lineNo, address);
430 return bp == 0 || enableDisableBreakpoint(bp);
433 bool KDebugger::enableDisableBreakpoint(Breakpoint* bp)
436 * Toggle enabled/disabled state.
438 * The driver is not bothered if we are modifying an orphaned
439 * breakpoint.
441 if (!bp->isOrphaned()) {
442 if (!canChangeBreakpoints()) {
443 return false;
445 m_d->executeCmd(bp->enabled ? DCdisable : DCenable, bp->id);
446 } else {
447 bp->enabled = !bp->enabled;
448 emit breakpointsChanged();
450 return true;
453 bool KDebugger::conditionalBreakpoint(Breakpoint* bp,
454 const QString& condition,
455 int ignoreCount)
458 * Change the condition and ignore count.
460 * The driver is not bothered if we are removing an orphaned
461 * breakpoint.
464 if (!bp->isOrphaned()) {
465 if (!canChangeBreakpoints()) {
466 return false;
469 bool changed = false;
471 if (bp->condition != condition) {
472 // change condition
473 m_d->executeCmd(DCcondition, condition, bp->id);
474 changed = true;
476 if (bp->ignoreCount != ignoreCount) {
477 // change ignore count
478 m_d->executeCmd(DCignore, bp->id, ignoreCount);
479 changed = true;
481 if (changed) {
482 // get the changes
483 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverride);
485 } else {
486 bp->condition = condition;
487 bp->ignoreCount = ignoreCount;
488 emit breakpointsChanged();
490 return true;
493 bool KDebugger::deleteBreakpoint(Breakpoint* bp)
496 * Remove the breakpoint.
498 * The driver is not bothered if we are removing an orphaned
499 * breakpoint.
501 if (!bp->isOrphaned()) {
502 if (!canChangeBreakpoints()) {
503 return false;
505 m_d->executeCmd(DCdelete, bp->id);
506 } else {
507 // move the last entry to bp's slot and shorten the list
508 int i = m_brkpts.findRef(bp);
509 m_brkpts.insert(i, m_brkpts.take(m_brkpts.size()-1));
510 m_brkpts.resize(m_brkpts.size()-1);
511 emit breakpointsChanged();
513 return false;
516 bool KDebugger::canSingleStep()
518 return isReady() && m_programActive && !m_programRunning;
521 bool KDebugger::canChangeBreakpoints()
523 return isReady() && !m_programRunning;
526 bool KDebugger::isReady() const
528 return m_haveExecutable &&
529 m_d != 0 && m_d->canExecuteImmediately();
532 bool KDebugger::isIdle() const
534 return m_d == 0 || m_d->isIdle();
538 //////////////////////////////////////////////////////////
539 // debugger driver
541 bool KDebugger::startDriver()
543 emit debuggerStarting(); /* must set m_inferiorTerminal */
546 * If the per-program command string is empty, use the global setting
547 * (which might also be empty, in which case the driver uses its
548 * default).
550 m_explicitKill = false;
551 if (!m_d->startup(m_debuggerCmd)) {
552 return false;
556 * If we have an output terminal, we use it. Otherwise we will run the
557 * program with input and output redirected to /dev/null. Other
558 * redirections are also necessary depending on the tty emulation
559 * level.
561 int redirect = RDNstdin|RDNstdout|RDNstderr; /* redirect everything */
562 if (!m_inferiorTerminal.isEmpty()) {
563 switch (m_ttyLevel) {
564 default:
565 case ttyNone:
566 // redirect everything
567 break;
568 case ttySimpleOutputOnly:
569 redirect = RDNstdin;
570 break;
571 case ttyFull:
572 redirect = 0;
573 break;
576 m_d->executeCmd(DCtty, m_inferiorTerminal, redirect);
578 return true;
581 void KDebugger::stopDriver()
583 m_explicitKill = true;
585 if (m_attachedPid.isEmpty()) {
586 m_d->terminate();
587 } else {
588 m_d->detachAndTerminate();
592 * We MUST wait until the slot gdbExited() has been called. But to
593 * avoid a deadlock, we wait only for some certain maximum time. Should
594 * this timeout be reached, the only reasonable thing one could do then
595 * is exiting kdbg.
597 kapp->processEvents(1000); /* ideally, this will already shut it down */
598 int maxTime = 20; /* about 20 seconds */
599 while (m_haveExecutable && maxTime > 0) {
600 // give gdb time to die (and send a SIGCLD)
601 ::sleep(1);
602 --maxTime;
603 kapp->processEvents(1000);
607 void KDebugger::gdbExited(KProcess*)
610 * Save settings, but only if gdb has already processed "info line
611 * main", otherwise we would save an empty config file, because it
612 * isn't read in until then!
614 if (m_programConfig != 0) {
615 if (m_haveExecutable) {
616 saveProgramSettings();
617 m_programConfig->sync();
619 delete m_programConfig;
620 m_programConfig = 0;
623 // erase types
624 delete m_typeTable;
625 m_typeTable = 0;
627 if (m_explicitKill) {
628 TRACE(m_d->driverName() + " exited normally");
629 } else {
630 QString msg = i18n("%1 exited unexpectedly.\n"
631 "Restart the session (e.g. with File|Executable).");
632 KMessageBox::error(parentWidget(), msg.arg(m_d->driverName()));
635 // reset state
636 m_haveExecutable = false;
637 m_executable = "";
638 m_programActive = false;
639 m_programRunning = false;
640 m_explicitKill = false;
641 m_debuggerCmd = QString(); /* use global setting at next start! */
642 m_attachedPid = QString(); /* we are no longer attached to a process */
643 m_ttyLevel = ttyFull;
644 m_brkpts.clear();
646 // erase PC
647 emit updatePC(QString(), -1, DbgAddr(), 0);
650 QString KDebugger::getConfigForExe(const QString& name)
652 QFileInfo fi(name);
653 QString pgmConfigFile = fi.dirPath(true);
654 if (!pgmConfigFile.isEmpty()) {
655 pgmConfigFile += '/';
657 pgmConfigFile += ".kdbgrc." + fi.fileName();
658 TRACE("program config file = " + pgmConfigFile);
659 return pgmConfigFile;
662 void KDebugger::openProgramConfig(const QString& name)
664 ASSERT(m_programConfig == 0);
666 QString pgmConfigFile = getConfigForExe(name);
668 m_programConfig = new ProgramConfig(pgmConfigFile);
671 const char EnvironmentGroup[] = "Environment";
672 const char WatchGroup[] = "Watches";
673 const char FileVersion[] = "FileVersion";
674 const char ProgramArgs[] = "ProgramArgs";
675 const char WorkingDirectory[] = "WorkingDirectory";
676 const char OptionsSelected[] = "OptionsSelected";
677 const char Variable[] = "Var%d";
678 const char Value[] = "Value%d";
679 const char ExprFmt[] = "Expr%d";
681 void KDebugger::saveProgramSettings()
683 ASSERT(m_programConfig != 0);
684 m_programConfig->setGroup(GeneralGroup);
685 m_programConfig->writeEntry(FileVersion, 1);
686 m_programConfig->writeEntry(ProgramArgs, m_programArgs);
687 m_programConfig->writeEntry(WorkingDirectory, m_programWD);
688 m_programConfig->writeEntry(OptionsSelected, m_boolOptions);
689 m_programConfig->writeEntry(DebuggerCmdStr, m_debuggerCmd);
690 m_programConfig->writeEntry(TTYLevelEntry, int(m_ttyLevel));
691 QString driverName;
692 if (m_d != 0)
693 driverName = m_d->driverName();
694 m_programConfig->writeEntry(DriverNameEntry, driverName);
696 // write environment variables
697 m_programConfig->deleteGroup(EnvironmentGroup);
698 m_programConfig->setGroup(EnvironmentGroup);
699 QDictIterator<EnvVar> it = m_envVars;
700 EnvVar* var;
701 QString varName;
702 QString varValue;
703 for (int i = 0; (var = it) != 0; ++it, ++i) {
704 varName.sprintf(Variable, i);
705 varValue.sprintf(Value, i);
706 m_programConfig->writeEntry(varName, it.currentKey());
707 m_programConfig->writeEntry(varValue, var->value);
710 saveBreakpoints(m_programConfig);
712 // watch expressions
713 // first get rid of whatever was in this group
714 m_programConfig->deleteGroup(WatchGroup);
715 // then start a new group
716 m_programConfig->setGroup(WatchGroup);
717 KTreeViewItem* item = m_watchVariables.itemAt(0);
718 int watchNum = 0;
719 for (; item != 0; item = item->getSibling(), ++watchNum) {
720 varName.sprintf(ExprFmt, watchNum);
721 m_programConfig->writeEntry(varName, item->getText());
724 // give others a chance
725 emit saveProgramSpecific(m_programConfig);
728 void KDebugger::restoreProgramSettings()
730 ASSERT(m_programConfig != 0);
731 m_programConfig->setGroup(GeneralGroup);
733 * We ignore file version for now we will use it in the future to
734 * distinguish different versions of this configuration file.
736 // m_debuggerCmd has been read in already
737 // m_ttyLevel has been read in already
738 QString pgmArgs = m_programConfig->readEntry(ProgramArgs);
739 QString pgmWd = m_programConfig->readEntry(WorkingDirectory);
740 QStringList boolOptions = m_programConfig->readListEntry(OptionsSelected);
741 m_boolOptions = QStringList();
743 // read environment variables
744 m_programConfig->setGroup(EnvironmentGroup);
745 m_envVars.clear();
746 QDict<EnvVar> pgmVars;
747 EnvVar* var;
748 QString varName;
749 QString varValue;
750 for (int i = 0;; ++i) {
751 varName.sprintf(Variable, i);
752 varValue.sprintf(Value, i);
753 if (!m_programConfig->hasKey(varName)) {
754 /* entry not present, assume that we've hit them all */
755 break;
757 QString name = m_programConfig->readEntry(varName);
758 if (name.isEmpty()) {
759 // skip empty names
760 continue;
762 var = new EnvVar;
763 var->value = m_programConfig->readEntry(varValue);
764 var->status = EnvVar::EVnew;
765 pgmVars.insert(name, var);
768 updateProgEnvironment(pgmArgs, pgmWd, pgmVars, boolOptions);
770 restoreBreakpoints(m_programConfig);
772 // watch expressions
773 m_programConfig->setGroup(WatchGroup);
774 m_watchVariables.clear();
775 for (int i = 0;; ++i) {
776 varName.sprintf(ExprFmt, i);
777 if (!m_programConfig->hasKey(varName)) {
778 /* entry not present, assume that we've hit them all */
779 break;
781 QString expr = m_programConfig->readEntry(varName);
782 if (expr.isEmpty()) {
783 // skip empty expressions
784 continue;
786 addWatch(expr);
789 // give others a chance
790 emit restoreProgramSpecific(m_programConfig);
794 * Reads the debugger command line from the program settings. The config
795 * group must have been set by the caller.
797 QString KDebugger::readDebuggerCmd()
799 QString debuggerCmd = m_programConfig->readEntry(DebuggerCmdStr);
801 // always let the user confirm the debugger cmd if we are root
802 if (::geteuid() == 0)
804 if (!debuggerCmd.isEmpty()) {
805 QString msg = i18n(
806 "The settings for this program specify "
807 "the following debugger command:\n%1\n"
808 "Shall this command be used?");
809 if (KMessageBox::warningYesNo(parentWidget(), msg.arg(debuggerCmd))
810 != KMessageBox::Yes)
812 // don't use it
813 debuggerCmd = QString();
817 return debuggerCmd;
821 * Breakpoints are saved one per group.
823 const char BPGroup[] = "Breakpoint %d";
824 const char File[] = "File";
825 const char Line[] = "Line";
826 const char Text[] = "Text";
827 const char Address[] = "Address";
828 const char Temporary[] = "Temporary";
829 const char Enabled[] = "Enabled";
830 const char Condition[] = "Condition";
832 void KDebugger::saveBreakpoints(ProgramConfig* config)
834 QString groupName;
835 int i = 0;
836 for (uint j = 0; j < m_brkpts.size(); j++) {
837 Breakpoint* bp = m_brkpts[j];
838 if (bp->type == Breakpoint::watchpoint)
839 continue; /* don't save watchpoints */
840 groupName.sprintf(BPGroup, i++);
842 /* remove remmants */
843 config->deleteGroup(groupName);
845 config->setGroup(groupName);
846 if (!bp->text.isEmpty()) {
848 * The breakpoint was set using the text box in the breakpoint
849 * list. We do not save the location by filename+line number,
850 * but instead honor what the user typed (a function name, for
851 * example, which could move between sessions).
853 config->writeEntry(Text, bp->text);
854 } else if (!bp->fileName.isEmpty()) {
855 config->writeEntry(File, bp->fileName);
856 config->writeEntry(Line, bp->lineNo);
858 * Addresses are hardly correct across sessions, so we don't
859 * save it.
861 } else {
862 config->writeEntry(Address, bp->address.asString());
864 config->writeEntry(Temporary, bp->temporary);
865 config->writeEntry(Enabled, bp->enabled);
866 if (!bp->condition.isEmpty())
867 config->writeEntry(Condition, bp->condition);
868 // we do not save the ignore count
870 // delete remaining groups
871 // we recognize that a group is present if there is an Enabled entry
872 for (;; i++) {
873 groupName.sprintf(BPGroup, i);
874 config->setGroup(groupName);
875 if (!config->hasKey(Enabled)) {
876 /* group not present, assume that we've hit them all */
877 break;
879 config->deleteGroup(groupName);
883 void KDebugger::restoreBreakpoints(ProgramConfig* config)
885 QString groupName;
887 * We recognize the end of the list if there is no Enabled entry
888 * present.
890 for (int i = 0;; i++) {
891 groupName.sprintf(BPGroup, i);
892 config->setGroup(groupName);
893 if (!config->hasKey(Enabled)) {
894 /* group not present, assume that we've hit them all */
895 break;
897 Breakpoint* bp = new Breakpoint;
898 bp->fileName = config->readEntry(File);
899 bp->lineNo = config->readNumEntry(Line, -1);
900 bp->text = config->readEntry(Text);
901 bp->address = config->readEntry(Address);
902 // check consistency
903 if ((bp->fileName.isEmpty() || bp->lineNo < 0) &&
904 bp->text.isEmpty() &&
905 bp->address.isEmpty())
907 delete bp;
908 continue;
910 bp->enabled = config->readBoolEntry(Enabled, true);
911 bp->temporary = config->readBoolEntry(Temporary, false);
912 bp->condition = config->readEntry(Condition);
915 * Add the breakpoint.
917 setBreakpoint(bp, false);
918 // the new breakpoint is disabled or conditionalized later
919 // in newBreakpoint()
921 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverride);
925 // parse output of command cmd
926 void KDebugger::parse(CmdQueueItem* cmd, const char* output)
928 ASSERT(cmd != 0); /* queue mustn't be empty */
930 TRACE(QString(__PRETTY_FUNCTION__) + " parsing " + output);
932 switch (cmd->m_cmd) {
933 case DCtargetremote:
934 // the output (if any) is uninteresting
935 case DCsetargs:
936 case DCtty:
937 // there is no output
938 case DCsetenv:
939 case DCunsetenv:
940 case DCsetoption:
941 /* if value is empty, we see output, but we don't care */
942 break;
943 case DCcd:
944 /* display gdb's message in the status bar */
945 m_d->parseChangeWD(output, m_statusMessage);
946 emit updateStatusMessage();
947 break;
948 case DCinitialize:
949 break;
950 case DCexecutable:
951 if (m_d->parseChangeExecutable(output, m_statusMessage))
953 // success; restore breakpoints etc.
954 if (m_programConfig != 0) {
955 restoreProgramSettings();
957 // load file containing main() or core file
958 if (!m_corefile.isEmpty())
960 // load core file
961 loadCoreFile();
963 else if (!m_attachedPid.isEmpty())
965 m_d->queueCmd(DCattach, m_attachedPid, DebuggerDriver::QMoverride);
966 m_programActive = true;
967 m_programRunning = true;
969 else if (!m_remoteDevice.isEmpty())
971 // handled elsewhere
973 else
975 m_d->queueCmd(DCinfolinemain, DebuggerDriver::QMnormal);
977 if (!m_statusMessage.isEmpty())
978 emit updateStatusMessage();
979 } else {
980 QString msg = m_d->driverName() + ": " + m_statusMessage;
981 KMessageBox::sorry(parentWidget(), msg);
982 m_executable = "";
983 m_corefile = ""; /* don't process core file */
984 m_haveExecutable = false;
986 break;
987 case DCcorefile:
988 // in any event we have an executable at this point
989 m_haveExecutable = true;
990 if (m_d->parseCoreFile(output)) {
991 // loading a core is like stopping at a breakpoint
992 m_programActive = true;
993 handleRunCommands(output);
994 // do not reset m_corefile
995 } else {
996 // report error
997 QString msg = m_d->driverName() + ": " + QString(output);
998 KMessageBox::sorry(parentWidget(), msg);
1000 // if core file was loaded from command line, revert to info line main
1001 if (!cmd->m_byUser) {
1002 m_d->queueCmd(DCinfolinemain, DebuggerDriver::QMnormal);
1004 m_corefile = QString(); /* core file not available any more */
1006 break;
1007 case DCinfolinemain:
1008 // ignore the output, marked file info follows
1009 m_haveExecutable = true;
1010 break;
1011 case DCinfolocals:
1012 // parse local variables
1013 if (output[0] != '\0') {
1014 handleLocals(output);
1016 break;
1017 case DCinforegisters:
1018 handleRegisters(output);
1019 break;
1020 case DCexamine:
1021 handleMemoryDump(output);
1022 break;
1023 case DCinfoline:
1024 handleInfoLine(cmd, output);
1025 break;
1026 case DCdisassemble:
1027 handleDisassemble(cmd, output);
1028 break;
1029 case DCframe:
1030 handleFrameChange(output);
1031 updateAllExprs();
1032 break;
1033 case DCbt:
1034 handleBacktrace(output);
1035 updateAllExprs();
1036 break;
1037 case DCprint:
1038 handlePrint(cmd, output);
1039 break;
1040 case DCprintDeref:
1041 handlePrintDeref(cmd, output);
1042 break;
1043 case DCattach:
1044 m_haveExecutable = true;
1045 // fall through
1046 case DCrun:
1047 case DCcont:
1048 case DCstep:
1049 case DCstepi:
1050 case DCnext:
1051 case DCnexti:
1052 case DCfinish:
1053 case DCuntil:
1054 case DCthread:
1055 handleRunCommands(output);
1056 break;
1057 case DCkill:
1058 m_programRunning = m_programActive = false;
1059 // erase PC
1060 emit updatePC(QString(), -1, DbgAddr(), 0);
1061 break;
1062 case DCbreaktext:
1063 case DCbreakline:
1064 case DCtbreakline:
1065 case DCbreakaddr:
1066 case DCtbreakaddr:
1067 case DCwatchpoint:
1068 newBreakpoint(cmd, output);
1069 // fall through
1070 case DCdelete:
1071 case DCenable:
1072 case DCdisable:
1073 // these commands need immediate response
1074 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverrideMoreEqual);
1075 break;
1076 case DCinfobreak:
1077 // note: this handler must not enqueue a command, since
1078 // DCinfobreak is used at various different places.
1079 updateBreakList(output);
1080 break;
1081 case DCfindType:
1082 handleFindType(cmd, output);
1083 break;
1084 case DCprintStruct:
1085 case DCprintQStringStruct:
1086 handlePrintStruct(cmd, output);
1087 break;
1088 case DCinfosharedlib:
1089 handleSharedLibs(output);
1090 break;
1091 case DCcondition:
1092 case DCignore:
1093 // we are not interested in the output
1094 break;
1095 case DCinfothreads:
1096 handleThreadList(output);
1097 break;
1098 case DCsetpc:
1099 handleSetPC(output);
1100 break;
1101 case DCsetvariable:
1102 handleSetVariable(cmd, output);
1103 break;
1107 void KDebugger::backgroundUpdate()
1110 * If there are still expressions that need to be updated, then do so.
1112 if (m_programActive)
1113 evalExpressions();
1116 void KDebugger::handleRunCommands(const char* output)
1118 uint flags = m_d->parseProgramStopped(output, m_statusMessage);
1119 emit updateStatusMessage();
1121 m_programActive = flags & DebuggerDriver::SFprogramActive;
1123 // refresh files if necessary
1124 if (flags & DebuggerDriver::SFrefreshSource) {
1125 TRACE("re-reading files");
1126 emit executableUpdated();
1130 * Try to set any orphaned breakpoints now.
1132 for (int i = m_brkpts.size()-1; i >= 0; i--) {
1133 if (m_brkpts[i]->isOrphaned()) {
1134 TRACE("re-trying brkpt loc: "+m_brkpts[i]->location+
1135 " file: "+m_brkpts[i]->fileName+
1136 QString().sprintf(" line: %d", m_brkpts[i]->lineNo));
1137 setBreakpoint(m_brkpts[i], true);
1138 flags |= DebuggerDriver::SFrefreshBreak;
1143 * If we stopped at a breakpoint, we must update the breakpoint list
1144 * because the hit count changes. Also, if the breakpoint was temporary
1145 * it would go away now.
1147 if ((flags & (DebuggerDriver::SFrefreshBreak|DebuggerDriver::SFrefreshSource)) ||
1148 stopMayChangeBreakList())
1150 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverride);
1154 * If we haven't listed the shared libraries yet, do so. We must do
1155 * this before we emit any commands that list variables, since the type
1156 * libraries depend on the shared libraries.
1158 if (!m_sharedLibsListed) {
1159 // must be a high-priority command!
1160 m_d->executeCmd(DCinfosharedlib);
1163 // get the backtrace if the program is running
1164 if (m_programActive) {
1165 m_d->queueCmd(DCbt, DebuggerDriver::QMoverride);
1166 } else {
1167 // program finished: erase PC
1168 emit updatePC(QString(), -1, DbgAddr(), 0);
1169 // dequeue any commands in the queues
1170 m_d->flushCommands();
1173 /* Update threads list */
1174 if (m_programActive && (flags & DebuggerDriver::SFrefreshThreads)) {
1175 m_d->queueCmd(DCinfothreads, DebuggerDriver::QMoverride);
1178 m_programRunning = false;
1179 emit programStopped();
1182 void KDebugger::slotInferiorRunning()
1184 m_programRunning = true;
1187 void KDebugger::updateAllExprs()
1189 if (!m_programActive)
1190 return;
1192 // retrieve local variables
1193 m_d->queueCmd(DCinfolocals, DebuggerDriver::QMoverride);
1195 // retrieve registers
1196 m_d->queueCmd(DCinforegisters, DebuggerDriver::QMoverride);
1198 // get new memory dump
1199 if (!m_memoryExpression.isEmpty()) {
1200 queueMemoryDump(false);
1203 // update watch expressions
1204 KTreeViewItem* item = m_watchVariables.itemAt(0);
1205 for (; item != 0; item = item->getSibling()) {
1206 m_watchEvalExpr.append(static_cast<VarTree*>(item));
1210 void KDebugger::updateProgEnvironment(const QString& args, const QString& wd,
1211 const QDict<EnvVar>& newVars,
1212 const QStringList& newOptions)
1214 m_programArgs = args;
1215 m_d->executeCmd(DCsetargs, m_programArgs);
1216 TRACE("new pgm args: " + m_programArgs + "\n");
1218 m_programWD = wd.stripWhiteSpace();
1219 if (!m_programWD.isEmpty()) {
1220 m_d->executeCmd(DCcd, m_programWD);
1221 TRACE("new wd: " + m_programWD + "\n");
1224 // update environment variables
1225 QDictIterator<EnvVar> it = newVars;
1226 EnvVar* val;
1227 for (; (val = it) != 0; ++it) {
1228 QString var = it.currentKey();
1229 switch (val->status) {
1230 case EnvVar::EVnew:
1231 m_envVars.insert(var, val);
1232 // fall thru
1233 case EnvVar::EVdirty:
1234 // the value must be in our list
1235 ASSERT(m_envVars[var] == val);
1236 // update value
1237 m_d->executeCmd(DCsetenv, var, val->value);
1238 break;
1239 case EnvVar::EVdeleted:
1240 // must be in our list
1241 ASSERT(m_envVars[var] == val);
1242 // delete value
1243 m_d->executeCmd(DCunsetenv, var);
1244 m_envVars.remove(var);
1245 break;
1246 default:
1247 ASSERT(false);
1248 case EnvVar::EVclean:
1249 // variable not changed
1250 break;
1254 // update options
1255 QStringList::ConstIterator oi;
1256 for (oi = newOptions.begin(); oi != newOptions.end(); ++oi)
1258 if (m_boolOptions.findIndex(*oi) < 0) {
1259 // the options is currently not set, so set it
1260 m_d->executeCmd(DCsetoption, *oi, 1);
1261 } else {
1262 // option is set, no action required, but move it to the end
1263 m_boolOptions.remove(*oi);
1265 m_boolOptions.append(*oi);
1268 * Now all options that should be set are at the end of m_boolOptions.
1269 * If some options need to be unset, they are at the front of the list.
1270 * Here we unset and remove them.
1272 while (m_boolOptions.count() > newOptions.count()) {
1273 m_d->executeCmd(DCsetoption, m_boolOptions.first(), 0);
1274 m_boolOptions.remove(m_boolOptions.begin());
1278 void KDebugger::handleLocals(const char* output)
1280 // retrieve old list of local variables
1281 QStrList oldVars;
1282 m_localVariables.exprList(oldVars);
1285 * Get local variables.
1287 QList<VarTree> newVars;
1288 parseLocals(output, newVars);
1291 * Clear any old VarTree item pointers, so that later we don't access
1292 * dangling pointers.
1294 m_localVariables.clearPendingUpdates();
1296 // reduce flicker
1297 bool autoU = m_localVariables.autoUpdate();
1298 m_localVariables.setAutoUpdate(false);
1299 bool repaintNeeded = false;
1302 * Match old variables against new ones.
1304 for (const char* n = oldVars.first(); n != 0; n = oldVars.next()) {
1305 // lookup this variable in the list of new variables
1306 VarTree* v = newVars.first();
1307 while (v != 0 && strcmp(v->getText(), n) != 0) {
1308 v = newVars.next();
1310 if (v == 0) {
1311 // old variable not in the new variables
1312 TRACE(QString("old var deleted: ") + n);
1313 v = m_localVariables.topLevelExprByName(n);
1314 removeExpr(&m_localVariables, v);
1315 if (v != 0) repaintNeeded = true;
1316 } else {
1317 // variable in both old and new lists: update
1318 TRACE(QString("update var: ") + n);
1319 m_localVariables.updateExpr(newVars.current());
1320 // remove the new variable from the list
1321 newVars.remove();
1322 delete v;
1323 repaintNeeded = true;
1326 // insert all remaining new variables
1327 for (VarTree* v = newVars.first(); v != 0; v = newVars.next()) {
1328 TRACE("new var: " + v->getText());
1329 m_localVariables.insertExpr(v);
1330 repaintNeeded = true;
1333 // repaint
1334 m_localVariables.setAutoUpdate(autoU);
1335 if (repaintNeeded && autoU && m_localVariables.isVisible())
1336 m_localVariables.repaint();
1339 void KDebugger::parseLocals(const char* output, QList<VarTree>& newVars)
1341 QList<VarTree> vars;
1342 m_d->parseLocals(output, vars);
1344 QString origName; /* used in renaming variables */
1345 while (vars.count() > 0)
1347 VarTree* variable = vars.take(0);
1348 // get some types
1349 variable->inferTypesOfChildren(*m_typeTable);
1351 * When gdb prints local variables, those from the innermost block
1352 * come first. We run through the list of already parsed variables
1353 * to find duplicates (ie. variables that hide local variables from
1354 * a surrounding block). We keep the name of the inner variable, but
1355 * rename those from the outer block so that, when the value is
1356 * updated in the window, the value of the variable that is
1357 * _visible_ changes the color!
1359 int block = 0;
1360 origName = variable->getText();
1361 for (VarTree* v = newVars.first(); v != 0; v = newVars.next()) {
1362 if (variable->getText() == v->getText()) {
1363 // we found a duplicate, change name
1364 block++;
1365 QString newName = origName + " (" + QString().setNum(block) + ")";
1366 variable->setText(newName);
1369 newVars.append(variable);
1373 bool KDebugger::handlePrint(CmdQueueItem* cmd, const char* output)
1375 ASSERT(cmd->m_expr != 0);
1377 VarTree* variable = parseExpr(output, true);
1378 if (variable == 0)
1379 return false;
1381 // set expression "name"
1382 variable->setText(cmd->m_expr->getText());
1385 TRACE("update expr: " + cmd->m_expr->getText());
1386 cmd->m_exprWnd->updateExpr(cmd->m_expr, variable);
1387 delete variable;
1390 evalExpressions(); /* enqueue dereferenced pointers */
1392 return true;
1395 bool KDebugger::handlePrintDeref(CmdQueueItem* cmd, const char* output)
1397 ASSERT(cmd->m_expr != 0);
1399 VarTree* variable = parseExpr(output, true);
1400 if (variable == 0)
1401 return false;
1403 // set expression "name"
1404 variable->setText(cmd->m_expr->getText());
1408 * We must insert a dummy parent, because otherwise variable's value
1409 * would overwrite cmd->m_expr's value.
1411 VarTree* dummyParent = new VarTree(variable->getText(), VarTree::NKplain);
1412 dummyParent->m_varKind = VarTree::VKdummy;
1413 // the name of the parsed variable is the address of the pointer
1414 QString addr = "*" + cmd->m_expr->m_value;
1415 variable->setText(addr);
1416 variable->m_nameKind = VarTree::NKaddress;
1418 dummyParent->appendChild(variable);
1419 dummyParent->setDeleteChildren(true);
1420 // expand the first level for convenience
1421 variable->setExpanded(true);
1422 TRACE("update ptr: " + cmd->m_expr->getText());
1423 cmd->m_exprWnd->updateExpr(cmd->m_expr, dummyParent);
1424 delete dummyParent;
1427 evalExpressions(); /* enqueue dereferenced pointers */
1429 return true;
1432 VarTree* KDebugger::parseExpr(const char* output, bool wantErrorValue)
1434 VarTree* variable;
1436 // check for error conditions
1437 bool goodValue = m_d->parsePrintExpr(output, wantErrorValue, variable);
1439 if (variable != 0 && goodValue)
1441 // get some types
1442 variable->inferTypesOfChildren(*m_typeTable);
1444 return variable;
1447 // parse the output of bt
1448 void KDebugger::handleBacktrace(const char* output)
1450 // reduce flicker
1451 m_btWindow.setAutoUpdate(false);
1453 m_btWindow.clear();
1455 QList<StackFrame> stack;
1456 m_d->parseBackTrace(output, stack);
1458 if (stack.count() > 0) {
1459 StackFrame* frm = stack.take(0);
1460 // first frame must set PC
1461 // note: frm->lineNo is zero-based
1462 emit updatePC(frm->fileName, frm->lineNo, frm->address, frm->frameNo);
1464 do {
1465 QString func;
1466 if (frm->var != 0)
1467 func = frm->var->getText();
1468 else
1469 func = frm->fileName + ":" + QString().setNum(frm->lineNo+1);
1470 m_btWindow.insertItem(func);
1471 TRACE("frame " + func + " (" + frm->fileName + ":" +
1472 QString().setNum(frm->lineNo+1) + ")");
1473 delete frm;
1475 while ((frm = stack.take()) != 0);
1478 m_btWindow.setAutoUpdate(true);
1479 m_btWindow.repaint();
1482 void KDebugger::gotoFrame(int frame)
1484 m_d->executeCmd(DCframe, frame);
1487 void KDebugger::handleFrameChange(const char* output)
1489 QString fileName;
1490 int frameNo;
1491 int lineNo;
1492 DbgAddr address;
1493 if (m_d->parseFrameChange(output, frameNo, fileName, lineNo, address)) {
1494 /* lineNo can be negative here if we can't find a file name */
1495 emit updatePC(fileName, lineNo, address, frameNo);
1496 } else {
1497 emit updatePC(fileName, -1, address, frameNo);
1501 void KDebugger::evalExpressions()
1503 // evaluate expressions in the following order:
1504 // watch expressions
1505 // pointers in local variables
1506 // pointers in watch expressions
1507 // types in local variables
1508 // types in watch expressions
1509 // pointers in 'this'
1510 // types in 'this'
1512 VarTree* exprItem = m_watchEvalExpr.first();
1513 if (exprItem != 0) {
1514 m_watchEvalExpr.remove();
1515 QString expr = exprItem->computeExpr();
1516 TRACE("watch expr: " + expr);
1517 CmdQueueItem* cmd = m_d->queueCmd(DCprint, expr, DebuggerDriver::QMoverride);
1518 // remember which expr this was
1519 cmd->m_expr = exprItem;
1520 cmd->m_exprWnd = &m_watchVariables;
1521 } else {
1522 ExprWnd* wnd;
1523 VarTree* exprItem;
1524 #define POINTER(widget) \
1525 wnd = &widget; \
1526 exprItem = widget.nextUpdatePtr(); \
1527 if (exprItem != 0) goto pointer
1528 #define STRUCT(widget) \
1529 wnd = &widget; \
1530 exprItem = widget.nextUpdateStruct(); \
1531 if (exprItem != 0) goto ustruct
1532 #define TYPE(widget) \
1533 wnd = &widget; \
1534 exprItem = widget.nextUpdateType(); \
1535 if (exprItem != 0) goto type
1536 repeat:
1537 POINTER(m_localVariables);
1538 POINTER(m_watchVariables);
1539 STRUCT(m_localVariables);
1540 STRUCT(m_watchVariables);
1541 TYPE(m_localVariables);
1542 TYPE(m_watchVariables);
1543 #undef POINTER
1544 #undef STRUCT
1545 #undef TYPE
1546 return;
1548 pointer:
1549 // we have an expression to send
1550 dereferencePointer(wnd, exprItem, false);
1551 return;
1553 ustruct:
1554 // paranoia
1555 if (exprItem->m_type == 0 || exprItem->m_type == TypeInfo::unknownType())
1556 goto repeat;
1557 evalInitialStructExpression(exprItem, wnd, false);
1558 return;
1560 type:
1562 * Sometimes a VarTree gets registered twice for a type update. So
1563 * it may happen that it has already been updated. Hence, we ignore
1564 * it here and go on to the next task.
1566 if (exprItem->m_type != 0)
1567 goto repeat;
1568 determineType(wnd, exprItem);
1572 void KDebugger::dereferencePointer(ExprWnd* wnd, VarTree* exprItem,
1573 bool immediate)
1575 ASSERT(exprItem->m_varKind == VarTree::VKpointer);
1577 QString expr = exprItem->computeExpr();
1578 TRACE("dereferencing pointer: " + expr);
1579 CmdQueueItem* cmd;
1580 if (immediate) {
1581 cmd = m_d->queueCmd(DCprintDeref, expr, DebuggerDriver::QMoverrideMoreEqual);
1582 } else {
1583 cmd = m_d->queueCmd(DCprintDeref, expr, DebuggerDriver::QMoverride);
1585 // remember which expr this was
1586 cmd->m_expr = exprItem;
1587 cmd->m_exprWnd = wnd;
1590 void KDebugger::determineType(ExprWnd* wnd, VarTree* exprItem)
1592 ASSERT(exprItem->m_varKind == VarTree::VKstruct);
1594 QString expr = exprItem->computeExpr();
1595 TRACE("get type of: " + expr);
1596 CmdQueueItem* cmd;
1597 cmd = m_d->queueCmd(DCfindType, expr, DebuggerDriver::QMoverride);
1599 // remember which expr this was
1600 cmd->m_expr = exprItem;
1601 cmd->m_exprWnd = wnd;
1604 void KDebugger::handleFindType(CmdQueueItem* cmd, const char* output)
1606 QString type;
1607 if (m_d->parseFindType(output, type))
1609 ASSERT(cmd != 0 && cmd->m_expr != 0);
1611 TypeInfo* info = m_typeTable->lookup(type);
1613 if (info == 0) {
1615 * We've asked gdb for the type of the expression in
1616 * cmd->m_expr, but it returned a name we don't know. The base
1617 * class (and member) types have been checked already (at the
1618 * time when we parsed that particular expression). Now it's
1619 * time to derive the type from the base classes as a last
1620 * resort.
1622 info = cmd->m_expr->inferTypeFromBaseClass();
1623 // if we found a type through this method, register an alias
1624 if (info != 0) {
1625 TRACE("infered alias: " + type);
1626 m_typeTable->registerAlias(type, info);
1629 if (info == 0) {
1630 TRACE("unknown type");
1631 cmd->m_expr->m_type = TypeInfo::unknownType();
1632 } else {
1633 cmd->m_expr->m_type = info;
1634 /* since this node has a new type, we get its value immediately */
1635 evalInitialStructExpression(cmd->m_expr, cmd->m_exprWnd, false);
1636 return;
1640 evalExpressions(); /* queue more of them */
1643 void KDebugger::handlePrintStruct(CmdQueueItem* cmd, const char* output)
1645 VarTree* var = cmd->m_expr;
1646 ASSERT(var != 0);
1647 ASSERT(var->m_varKind == VarTree::VKstruct);
1649 VarTree* partExpr;
1650 if (cmd->m_cmd != DCprintQStringStruct) {
1651 partExpr = parseExpr(output, false);
1652 } else {
1653 partExpr = m_d->parseQCharArray(output, false, m_typeTable->qCharIsShort());
1655 bool errorValue =
1656 partExpr == 0 ||
1657 /* we only allow simple values at the moment */
1658 partExpr->childCount() != 0;
1660 QString partValue;
1661 if (errorValue)
1663 partValue = "?""?""?"; // 2 question marks in a row would be a trigraph
1664 } else {
1665 partValue = partExpr->m_value;
1667 delete partExpr;
1668 partExpr = 0;
1671 * Updating a struct value works like this: var->m_partialValue holds
1672 * the value that we have gathered so far (it's been initialized with
1673 * var->m_type->m_displayString[0] earlier). Each time we arrive here,
1674 * we append the printed result followed by the next
1675 * var->m_type->m_displayString to var->m_partialValue.
1677 * If the expression we just evaluated was a guard expression, and it
1678 * resulted in an error, we must not evaluate the real expression, but
1679 * go on to the next index. (We must still add the question marks to
1680 * the value).
1682 * Next, if this was the length expression, we still have not seen the
1683 * real expression, but the length of a QString.
1685 ASSERT(var->m_exprIndex >= 0 && var->m_exprIndex <= typeInfoMaxExpr);
1687 if (errorValue || !var->m_exprIndexUseGuard)
1689 // add current partValue (which might be the question marks)
1690 var->m_partialValue += partValue;
1691 var->m_exprIndex++; /* next part */
1692 var->m_exprIndexUseGuard = true;
1693 var->m_partialValue += var->m_type->m_displayString[var->m_exprIndex];
1695 else
1697 // this was a guard expression that succeeded
1698 // go for the real expression
1699 var->m_exprIndexUseGuard = false;
1702 /* go for more sub-expressions if needed */
1703 if (var->m_exprIndex < var->m_type->m_numExprs) {
1704 /* queue a new print command with quite high priority */
1705 evalStructExpression(var, cmd->m_exprWnd, true);
1706 return;
1709 cmd->m_exprWnd->updateStructValue(var);
1711 evalExpressions(); /* enqueue dereferenced pointers */
1714 /* queues the first printStruct command for a struct */
1715 void KDebugger::evalInitialStructExpression(VarTree* var, ExprWnd* wnd, bool immediate)
1717 var->m_exprIndex = 0;
1718 var->m_exprIndexUseGuard = true;
1719 var->m_partialValue = var->m_type->m_displayString[0];
1720 evalStructExpression(var, wnd, immediate);
1723 /* queues a printStruct command; var must have been initialized correctly */
1724 void KDebugger::evalStructExpression(VarTree* var, ExprWnd* wnd, bool immediate)
1726 QString base = var->computeExpr();
1727 QString exprFmt;
1728 if (var->m_exprIndexUseGuard) {
1729 exprFmt = var->m_type->m_guardStrings[var->m_exprIndex];
1730 if (exprFmt.isEmpty()) {
1731 // no guard, omit it and go to expression
1732 var->m_exprIndexUseGuard = false;
1735 if (!var->m_exprIndexUseGuard) {
1736 exprFmt = var->m_type->m_exprStrings[var->m_exprIndex];
1739 SIZED_QString(expr, exprFmt.length() + base.length() + 10);
1740 expr.sprintf(exprFmt, base.data());
1742 DbgCommand dbgCmd = DCprintStruct;
1743 // check if this is a QString::Data
1744 if (strncmp(expr, "/QString::Data ", 15) == 0)
1746 if (m_typeTable->parseQt2QStrings())
1748 expr = expr.mid(15, expr.length()); /* strip off /QString::Data */
1749 dbgCmd = DCprintQStringStruct;
1750 } else {
1752 * This should not happen: the type libraries should be set up
1753 * in a way that this can't happen. If this happens
1754 * nevertheless it means that, eg., kdecore was loaded but qt2
1755 * was not (only qt2 enables the QString feature).
1757 // TODO: remove this "print"; queue the next printStruct instead
1758 expr = "*0";
1760 } else {
1761 expr = expr;
1763 TRACE("evalStruct: " + expr + (var->m_exprIndexUseGuard ? " // guard" : " // real"));
1764 CmdQueueItem* cmd = m_d->queueCmd(dbgCmd, expr,
1765 immediate ? DebuggerDriver::QMoverrideMoreEqual
1766 : DebuggerDriver::QMnormal);
1768 // remember which expression this was
1769 cmd->m_expr = var;
1770 cmd->m_exprWnd = wnd;
1773 /* removes expression from window */
1774 void KDebugger::removeExpr(ExprWnd* wnd, VarTree* var)
1776 if (var == 0)
1777 return;
1779 // must remove any references to var from command queues
1780 m_d->dequeueCmdByVar(var);
1782 wnd->removeExpr(var);
1785 void KDebugger::handleSharedLibs(const char* output)
1787 // delete all known libraries
1788 m_sharedLibs.clear();
1790 // parse the table of shared libraries
1791 m_d->parseSharedLibs(output, m_sharedLibs);
1792 m_sharedLibsListed = true;
1794 // get type libraries
1795 m_typeTable->loadLibTypes(m_sharedLibs);
1797 // hand over the QString data cmd
1798 m_d->setPrintQStringDataCmd(m_typeTable->printQStringDataCmd());
1801 CmdQueueItem* KDebugger::loadCoreFile()
1803 return m_d->queueCmd(DCcorefile, m_corefile, DebuggerDriver::QMoverride);
1806 void KDebugger::slotLocalsExpanding(KTreeViewItem* item, bool& allow)
1808 exprExpandingHelper(&m_localVariables, item, allow);
1811 void KDebugger::slotWatchExpanding(KTreeViewItem* item, bool& allow)
1813 exprExpandingHelper(&m_watchVariables, item, allow);
1816 void KDebugger::exprExpandingHelper(ExprWnd* wnd, KTreeViewItem* item, bool&)
1818 VarTree* exprItem = static_cast<VarTree*>(item);
1819 if (exprItem->m_varKind != VarTree::VKpointer) {
1820 return;
1822 dereferencePointer(wnd, exprItem, true);
1825 // add the expression in the edit field to the watch expressions
1826 void KDebugger::addWatch(const QString& t)
1828 QString expr = t.stripWhiteSpace();
1829 if (expr.isEmpty())
1830 return;
1831 VarTree* exprItem = new VarTree(expr, VarTree::NKplain);
1832 m_watchVariables.insertExpr(exprItem);
1834 // if we are boring ourselves, send down the command
1835 if (m_programActive) {
1836 m_watchEvalExpr.append(exprItem);
1837 if (m_d->isIdle()) {
1838 evalExpressions();
1843 // delete a toplevel watch expression
1844 void KDebugger::slotDeleteWatch()
1846 // delete only allowed while debugger is idle; or else we might delete
1847 // the very expression the debugger is currently working on...
1848 if (!m_d->isIdle())
1849 return;
1851 int index = m_watchVariables.currentItem();
1852 if (index < 0)
1853 return;
1855 VarTree* item = static_cast<VarTree*>(m_watchVariables.itemAt(index));
1856 if (!item->isToplevelExpr())
1857 return;
1859 // remove the variable from the list to evaluate
1860 if (m_watchEvalExpr.findRef(item) >= 0) {
1861 m_watchEvalExpr.remove();
1863 removeExpr(&m_watchVariables, item);
1864 // item is invalid at this point!
1867 void KDebugger::handleRegisters(const char* output)
1869 QList<RegisterInfo> regs;
1870 m_d->parseRegisters(output, regs);
1872 emit registersChanged(regs);
1874 // delete them all
1875 regs.setAutoDelete(true);
1879 * The output of the DCbreak* commands has more accurate information about
1880 * the file and the line number.
1882 * All newly set breakpoints are inserted in the m_brkpts, even those that
1883 * were not set sucessfully. The unsuccessful breakpoints ("orphaned
1884 * breakpoints") are assigned negative ids, and they are tried to set later
1885 * when the program stops again at a breakpoint.
1887 void KDebugger::newBreakpoint(CmdQueueItem* cmd, const char* output)
1889 Breakpoint* bp = cmd->m_brkpt;
1890 assert(bp != 0);
1891 if (bp == 0)
1892 return;
1894 // if this is a new breakpoint, put it in the list
1895 bool isNew = !m_brkpts.contains(bp);
1896 if (isNew) {
1897 assert(bp->id == 0);
1898 int n = m_brkpts.size();
1899 m_brkpts.resize(n+1);
1900 m_brkpts.insert(n, bp);
1903 // parse the output to determine success or failure
1904 int id;
1905 QString file;
1906 int lineNo;
1907 QString address;
1908 if (!m_d->parseBreakpoint(output, id, file, lineNo, address))
1911 * Failure, the breakpoint could not be set. If this is a new
1912 * breakpoint, assign it a negative id. We look for the minimal id
1913 * of all breakpoints (that are already in the list) to get the new
1914 * id.
1916 if (isNew)
1918 assert(bp->id == 0);
1919 for (int i = m_brkpts.size()-2; i >= 0; i--) {
1920 if (m_brkpts[i]->id < bp->id) {
1921 bp->id = m_brkpts[i]->id;
1922 break;
1925 --bp->id;
1927 return;
1930 // The breakpoint was successfully set.
1931 if (bp->id <= 0)
1933 // this is a new or orphaned breakpoint:
1934 // set the remaining properties
1935 if (!cmd->m_brkpt->enabled) {
1936 m_d->executeCmd(DCdisable, id);
1938 if (!cmd->m_brkpt->condition.isEmpty()) {
1939 m_d->executeCmd(DCcondition, cmd->m_brkpt->condition, id);
1943 bp->id = id;
1944 bp->fileName = file;
1945 bp->lineNo = lineNo;
1946 if (!address.isEmpty())
1947 bp->address = address;
1950 void KDebugger::updateBreakList(const char* output)
1952 // get the new list
1953 QList<Breakpoint> brks;
1954 brks.setAutoDelete(false);
1955 m_d->parseBreakList(output, brks);
1957 // merge new information into existing breakpoints
1959 for (int i = m_brkpts.size()-1; i >= 0; i--) // decrement!
1961 // skip orphaned breakpoints
1962 if (m_brkpts[i]->id < 0)
1963 continue;
1965 for (Breakpoint* bp = brks.first(); bp != 0; bp = brks.next())
1967 if (bp->id == m_brkpts[i]->id) {
1968 // keep accurate location
1969 // except that xsldbg doesn't have a location in
1970 // the old breakpoint if it's just been set
1971 bp->text = m_brkpts[i]->text;
1972 if (!m_brkpts[i]->fileName.isEmpty()) {
1973 bp->fileName = m_brkpts[i]->fileName;
1974 bp->lineNo = m_brkpts[i]->lineNo;
1976 m_brkpts.insert(i, bp); // old object is deleted
1977 goto stillAlive;
1981 * If we get here, this breakpoint is no longer present.
1983 * To delete the breakpoint at i, we place the last breakpoint in
1984 * the list into the slot i. This will delete the old object at i.
1985 * Then we shorten the list by one.
1987 m_brkpts.insert(i, m_brkpts.take(m_brkpts.size()-1));
1988 m_brkpts.resize(m_brkpts.size()-1);
1989 TRACE(QString().sprintf("deleted brkpt %d, have now %d brkpts", i, m_brkpts.size()));
1991 stillAlive:;
1994 // brks may contain new breakpoints not already in m_brkpts
1995 for (const Breakpoint* bp = brks.first(); bp != 0; bp = brks.next())
1997 bool found = false;
1998 for (uint i = 0; i < m_brkpts.size(); i++) {
1999 if (bp->id == m_brkpts[i]->id) {
2000 found = true;
2001 break;
2004 if (!found){
2005 int n = m_brkpts.size();
2006 m_brkpts.resize(n+1);
2007 m_brkpts.insert(n, bp);
2011 emit breakpointsChanged();
2014 // look if there is at least one temporary breakpoint
2015 // or a watchpoint
2016 bool KDebugger::stopMayChangeBreakList() const
2018 for (int i = m_brkpts.size()-1; i >= 0; i--) {
2019 Breakpoint* bp = m_brkpts[i];
2020 if (bp->temporary || bp->type == Breakpoint::watchpoint)
2021 return true;
2023 return false;
2026 Breakpoint* KDebugger::breakpointByFilePos(QString file, int lineNo,
2027 const DbgAddr& address)
2029 // look for exact file name match
2030 int i;
2031 for (i = m_brkpts.size()-1; i >= 0; i--) {
2032 if (m_brkpts[i]->lineNo == lineNo &&
2033 m_brkpts[i]->fileName == file &&
2034 (address.isEmpty() || m_brkpts[i]->address == address))
2036 return m_brkpts[i];
2039 // not found, so try basename
2040 // strip off directory part of file name
2041 int offset = file.findRev("/");
2042 file.remove(0, offset+1);
2044 for (i = m_brkpts.size()-1; i >= 0; i--) {
2045 // get base name of breakpoint's file
2046 QString basename = m_brkpts[i]->fileName;
2047 int offset = basename.findRev("/");
2048 if (offset >= 0) {
2049 basename.remove(0, offset+1);
2052 if (m_brkpts[i]->lineNo == lineNo &&
2053 basename == file &&
2054 (address.isEmpty() || m_brkpts[i]->address == address))
2056 return m_brkpts[i];
2060 // not found
2061 return 0;
2064 Breakpoint* KDebugger::breakpointById(int id)
2066 for (int i = m_brkpts.size()-1; i >= 0; i--)
2068 if (m_brkpts[i]->id == id) {
2069 return m_brkpts[i];
2072 // not found
2073 return 0;
2076 void KDebugger::slotValuePopup(const QString& expr)
2078 // search the local variables for a match
2079 VarTree* v = m_localVariables.topLevelExprByName(expr);
2080 if (v == 0) {
2081 // not found, check watch expressions
2082 v = m_watchVariables.topLevelExprByName(expr);
2083 if (v == 0) {
2084 // nothing found; do nothing
2085 return;
2089 // construct the tip
2090 QString tip = v->getText() + " = ";
2091 if (!v->m_value.isEmpty())
2093 tip += v->m_value;
2095 else
2097 // no value: we use some hint
2098 switch (v->m_varKind) {
2099 case VarTree::VKstruct:
2100 tip += "{...}";
2101 break;
2102 case VarTree::VKarray:
2103 tip += "[...]";
2104 break;
2105 default:
2106 tip += "?""?""?"; // 2 question marks in a row would be a trigraph
2107 break;
2110 emit valuePopup(tip);
2113 void KDebugger::slotDisassemble(const QString& fileName, int lineNo)
2115 CmdQueueItem* cmd = m_d->queueCmd(DCinfoline, fileName, lineNo,
2116 DebuggerDriver::QMoverrideMoreEqual);
2117 cmd->m_fileName = fileName;
2118 cmd->m_lineNo = lineNo;
2121 void KDebugger::handleInfoLine(CmdQueueItem* cmd, const char* output)
2123 QString addrFrom, addrTo;
2124 if (cmd->m_lineNo >= 0) {
2125 // disassemble
2126 if (m_d->parseInfoLine(output, addrFrom, addrTo)) {
2127 // got the address range, now get the real code
2128 CmdQueueItem* c = m_d->queueCmd(DCdisassemble, addrFrom, addrTo,
2129 DebuggerDriver::QMoverrideMoreEqual);
2130 c->m_fileName = cmd->m_fileName;
2131 c->m_lineNo = cmd->m_lineNo;
2132 } else {
2133 // no code
2134 QList<DisassembledCode> empty;
2135 emit disassembled(cmd->m_fileName, cmd->m_lineNo, empty);
2137 } else {
2138 // set program counter
2139 if (m_d->parseInfoLine(output, addrFrom, addrTo)) {
2140 // move the program counter to the start address
2141 m_d->executeCmd(DCsetpc, addrFrom);
2146 void KDebugger::handleDisassemble(CmdQueueItem* cmd, const char* output)
2148 QList<DisassembledCode> code;
2149 code.setAutoDelete(true);
2150 m_d->parseDisassemble(output, code);
2151 emit disassembled(cmd->m_fileName, cmd->m_lineNo, code);
2154 void KDebugger::handleThreadList(const char* output)
2156 QList<ThreadInfo> threads;
2157 threads.setAutoDelete(true);
2158 m_d->parseThreadList(output, threads);
2159 emit threadsChanged(threads);
2162 void KDebugger::setThread(int id)
2164 m_d->queueCmd(DCthread, id, DebuggerDriver::QMoverrideMoreEqual);
2167 void KDebugger::setMemoryExpression(const QString& memexpr)
2169 m_memoryExpression = memexpr;
2171 // queue the new expression
2172 if (!m_memoryExpression.isEmpty() &&
2173 isProgramActive() &&
2174 !isProgramRunning())
2176 queueMemoryDump(true);
2180 void KDebugger::queueMemoryDump(bool immediate)
2182 m_d->queueCmd(DCexamine, m_memoryExpression, m_memoryFormat,
2183 immediate ? DebuggerDriver::QMoverrideMoreEqual :
2184 DebuggerDriver::QMoverride);
2187 void KDebugger::handleMemoryDump(const char* output)
2189 QList<MemoryDump> memdump;
2190 memdump.setAutoDelete(true);
2191 QString msg = m_d->parseMemoryDump(output, memdump);
2192 emit memoryDumpChanged(msg, memdump);
2195 void KDebugger::setProgramCounter(const QString& file, int line, const DbgAddr& addr)
2197 if (addr.isEmpty()) {
2198 // find address of the specified line
2199 CmdQueueItem* cmd = m_d->executeCmd(DCinfoline, file, line);
2200 cmd->m_lineNo = -1; /* indicates "Set PC" UI command */
2201 } else {
2202 // move the program counter to that address
2203 m_d->executeCmd(DCsetpc, addr.asString());
2207 void KDebugger::handleSetPC(const char* /*output*/)
2209 // TODO: handle errors
2211 // now go to the top-most frame
2212 // this also modifies the program counter indicator in the UI
2213 gotoFrame(0);
2216 void KDebugger::slotValueEdited(int row, const QString& text)
2218 if (text.simplifyWhiteSpace().isEmpty())
2219 return; /* no text entered: ignore request */
2221 ASSERT(sender()->inherits("ExprWnd"));
2222 ExprWnd* wnd = const_cast<ExprWnd*>(static_cast<const ExprWnd*>(sender()));
2223 TRACE(QString().sprintf("Changing %s at row %d to ",
2224 wnd->name(), row) + text);
2226 // determine the lvalue to edit
2227 VarTree* expr = static_cast<VarTree*>(wnd->itemAt(row));
2228 QString lvalue = expr->computeExpr();
2229 CmdQueueItem* cmd = m_d->executeCmd(DCsetvariable, lvalue, text);
2230 cmd->m_expr = expr;
2231 cmd->m_exprWnd = wnd;
2234 void KDebugger::handleSetVariable(CmdQueueItem* cmd, const char* output)
2236 QString msg = m_d->parseSetVariable(output);
2237 if (!msg.isEmpty())
2239 // there was an error; display it in the status bar
2240 m_statusMessage = msg;
2241 emit updateStatusMessage();
2242 return;
2245 // get the new value
2246 QString expr = cmd->m_expr->computeExpr();
2247 CmdQueueItem* printCmd =
2248 m_d->queueCmd(DCprint, expr, DebuggerDriver::QMoverrideMoreEqual);
2249 printCmd->m_expr = cmd->m_expr;
2250 printCmd->m_exprWnd = cmd->m_exprWnd;
2254 #include "debugger.moc"