Removed compatibility code for Qt 1.x (!).
[kdbg.git] / kdbg / debugger.cpp
blob39c2b5b48fa6ac32aff27b18d9429f0d11241216
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::canStart()
528 return isReady() && !m_programActive;
531 bool KDebugger::isReady() const
533 return m_haveExecutable &&
534 m_d != 0 && m_d->canExecuteImmediately();
537 bool KDebugger::isIdle() const
539 return m_d == 0 || m_d->isIdle();
543 //////////////////////////////////////////////////////////
544 // debugger driver
546 bool KDebugger::startDriver()
548 emit debuggerStarting(); /* must set m_inferiorTerminal */
551 * If the per-program command string is empty, use the global setting
552 * (which might also be empty, in which case the driver uses its
553 * default).
555 m_explicitKill = false;
556 if (!m_d->startup(m_debuggerCmd)) {
557 return false;
561 * If we have an output terminal, we use it. Otherwise we will run the
562 * program with input and output redirected to /dev/null. Other
563 * redirections are also necessary depending on the tty emulation
564 * level.
566 int redirect = RDNstdin|RDNstdout|RDNstderr; /* redirect everything */
567 if (!m_inferiorTerminal.isEmpty()) {
568 switch (m_ttyLevel) {
569 default:
570 case ttyNone:
571 // redirect everything
572 break;
573 case ttySimpleOutputOnly:
574 redirect = RDNstdin;
575 break;
576 case ttyFull:
577 redirect = 0;
578 break;
581 m_d->executeCmd(DCtty, m_inferiorTerminal, redirect);
583 return true;
586 void KDebugger::stopDriver()
588 m_explicitKill = true;
590 if (m_attachedPid.isEmpty()) {
591 m_d->terminate();
592 } else {
593 m_d->detachAndTerminate();
597 * We MUST wait until the slot gdbExited() has been called. But to
598 * avoid a deadlock, we wait only for some certain maximum time. Should
599 * this timeout be reached, the only reasonable thing one could do then
600 * is exiting kdbg.
602 kapp->processEvents(1000); /* ideally, this will already shut it down */
603 int maxTime = 20; /* about 20 seconds */
604 while (m_haveExecutable && maxTime > 0) {
605 // give gdb time to die (and send a SIGCLD)
606 ::sleep(1);
607 --maxTime;
608 kapp->processEvents(1000);
612 void KDebugger::gdbExited(KProcess*)
615 * Save settings, but only if gdb has already processed "info line
616 * main", otherwise we would save an empty config file, because it
617 * isn't read in until then!
619 if (m_programConfig != 0) {
620 if (m_haveExecutable) {
621 saveProgramSettings();
622 m_programConfig->sync();
624 delete m_programConfig;
625 m_programConfig = 0;
628 // erase types
629 delete m_typeTable;
630 m_typeTable = 0;
632 if (m_explicitKill) {
633 TRACE(m_d->driverName() + " exited normally");
634 } else {
635 QString msg = i18n("%1 exited unexpectedly.\n"
636 "Restart the session (e.g. with File|Executable).");
637 KMessageBox::error(parentWidget(), msg.arg(m_d->driverName()));
640 // reset state
641 m_haveExecutable = false;
642 m_executable = "";
643 m_programActive = false;
644 m_programRunning = false;
645 m_explicitKill = false;
646 m_debuggerCmd = QString(); /* use global setting at next start! */
647 m_attachedPid = QString(); /* we are no longer attached to a process */
648 m_ttyLevel = ttyFull;
649 m_brkpts.clear();
651 // erase PC
652 emit updatePC(QString(), -1, DbgAddr(), 0);
655 QString KDebugger::getConfigForExe(const QString& name)
657 QFileInfo fi(name);
658 QString pgmConfigFile = fi.dirPath(true);
659 if (!pgmConfigFile.isEmpty()) {
660 pgmConfigFile += '/';
662 pgmConfigFile += ".kdbgrc." + fi.fileName();
663 TRACE("program config file = " + pgmConfigFile);
664 return pgmConfigFile;
667 void KDebugger::openProgramConfig(const QString& name)
669 ASSERT(m_programConfig == 0);
671 QString pgmConfigFile = getConfigForExe(name);
673 m_programConfig = new ProgramConfig(pgmConfigFile);
676 const char EnvironmentGroup[] = "Environment";
677 const char WatchGroup[] = "Watches";
678 const char FileVersion[] = "FileVersion";
679 const char ProgramArgs[] = "ProgramArgs";
680 const char WorkingDirectory[] = "WorkingDirectory";
681 const char OptionsSelected[] = "OptionsSelected";
682 const char Variable[] = "Var%d";
683 const char Value[] = "Value%d";
684 const char ExprFmt[] = "Expr%d";
686 void KDebugger::saveProgramSettings()
688 ASSERT(m_programConfig != 0);
689 m_programConfig->setGroup(GeneralGroup);
690 m_programConfig->writeEntry(FileVersion, 1);
691 m_programConfig->writeEntry(ProgramArgs, m_programArgs);
692 m_programConfig->writeEntry(WorkingDirectory, m_programWD);
693 m_programConfig->writeEntry(OptionsSelected, m_boolOptions);
694 m_programConfig->writeEntry(DebuggerCmdStr, m_debuggerCmd);
695 m_programConfig->writeEntry(TTYLevelEntry, int(m_ttyLevel));
696 QString driverName;
697 if (m_d != 0)
698 driverName = m_d->driverName();
699 m_programConfig->writeEntry(DriverNameEntry, driverName);
701 // write environment variables
702 m_programConfig->deleteGroup(EnvironmentGroup);
703 m_programConfig->setGroup(EnvironmentGroup);
704 QDictIterator<EnvVar> it = m_envVars;
705 EnvVar* var;
706 QString varName;
707 QString varValue;
708 for (int i = 0; (var = it) != 0; ++it, ++i) {
709 varName.sprintf(Variable, i);
710 varValue.sprintf(Value, i);
711 m_programConfig->writeEntry(varName, it.currentKey());
712 m_programConfig->writeEntry(varValue, var->value);
715 saveBreakpoints(m_programConfig);
717 // watch expressions
718 // first get rid of whatever was in this group
719 m_programConfig->deleteGroup(WatchGroup);
720 // then start a new group
721 m_programConfig->setGroup(WatchGroup);
722 KTreeViewItem* item = m_watchVariables.itemAt(0);
723 int watchNum = 0;
724 for (; item != 0; item = item->getSibling(), ++watchNum) {
725 varName.sprintf(ExprFmt, watchNum);
726 m_programConfig->writeEntry(varName, item->getText());
729 // give others a chance
730 emit saveProgramSpecific(m_programConfig);
733 void KDebugger::restoreProgramSettings()
735 ASSERT(m_programConfig != 0);
736 m_programConfig->setGroup(GeneralGroup);
738 * We ignore file version for now we will use it in the future to
739 * distinguish different versions of this configuration file.
741 // m_debuggerCmd has been read in already
742 // m_ttyLevel has been read in already
743 QString pgmArgs = m_programConfig->readEntry(ProgramArgs);
744 QString pgmWd = m_programConfig->readEntry(WorkingDirectory);
745 QStringList boolOptions = m_programConfig->readListEntry(OptionsSelected);
746 m_boolOptions = QStringList();
748 // read environment variables
749 m_programConfig->setGroup(EnvironmentGroup);
750 m_envVars.clear();
751 QDict<EnvVar> pgmVars;
752 EnvVar* var;
753 QString varName;
754 QString varValue;
755 for (int i = 0;; ++i) {
756 varName.sprintf(Variable, i);
757 varValue.sprintf(Value, i);
758 if (!m_programConfig->hasKey(varName)) {
759 /* entry not present, assume that we've hit them all */
760 break;
762 QString name = m_programConfig->readEntry(varName);
763 if (name.isEmpty()) {
764 // skip empty names
765 continue;
767 var = new EnvVar;
768 var->value = m_programConfig->readEntry(varValue);
769 var->status = EnvVar::EVnew;
770 pgmVars.insert(name, var);
773 updateProgEnvironment(pgmArgs, pgmWd, pgmVars, boolOptions);
775 restoreBreakpoints(m_programConfig);
777 // watch expressions
778 m_programConfig->setGroup(WatchGroup);
779 m_watchVariables.clear();
780 for (int i = 0;; ++i) {
781 varName.sprintf(ExprFmt, i);
782 if (!m_programConfig->hasKey(varName)) {
783 /* entry not present, assume that we've hit them all */
784 break;
786 QString expr = m_programConfig->readEntry(varName);
787 if (expr.isEmpty()) {
788 // skip empty expressions
789 continue;
791 addWatch(expr);
794 // give others a chance
795 emit restoreProgramSpecific(m_programConfig);
799 * Reads the debugger command line from the program settings. The config
800 * group must have been set by the caller.
802 QString KDebugger::readDebuggerCmd()
804 QString debuggerCmd = m_programConfig->readEntry(DebuggerCmdStr);
806 // always let the user confirm the debugger cmd if we are root
807 if (::geteuid() == 0)
809 if (!debuggerCmd.isEmpty()) {
810 QString msg = i18n(
811 "The settings for this program specify "
812 "the following debugger command:\n%1\n"
813 "Shall this command be used?");
814 if (KMessageBox::warningYesNo(parentWidget(), msg.arg(debuggerCmd))
815 != KMessageBox::Yes)
817 // don't use it
818 debuggerCmd = QString();
822 return debuggerCmd;
826 * Breakpoints are saved one per group.
828 const char BPGroup[] = "Breakpoint %d";
829 const char File[] = "File";
830 const char Line[] = "Line";
831 const char Text[] = "Text";
832 const char Address[] = "Address";
833 const char Temporary[] = "Temporary";
834 const char Enabled[] = "Enabled";
835 const char Condition[] = "Condition";
837 void KDebugger::saveBreakpoints(ProgramConfig* config)
839 QString groupName;
840 int i = 0;
841 for (uint j = 0; j < m_brkpts.size(); j++) {
842 Breakpoint* bp = m_brkpts[j];
843 if (bp->type == Breakpoint::watchpoint)
844 continue; /* don't save watchpoints */
845 groupName.sprintf(BPGroup, i++);
847 /* remove remmants */
848 config->deleteGroup(groupName);
850 config->setGroup(groupName);
851 if (!bp->text.isEmpty()) {
853 * The breakpoint was set using the text box in the breakpoint
854 * list. We do not save the location by filename+line number,
855 * but instead honor what the user typed (a function name, for
856 * example, which could move between sessions).
858 config->writeEntry(Text, bp->text);
859 } else if (!bp->fileName.isEmpty()) {
860 config->writeEntry(File, bp->fileName);
861 config->writeEntry(Line, bp->lineNo);
863 * Addresses are hardly correct across sessions, so we don't
864 * save it.
866 } else {
867 config->writeEntry(Address, bp->address.asString());
869 config->writeEntry(Temporary, bp->temporary);
870 config->writeEntry(Enabled, bp->enabled);
871 if (!bp->condition.isEmpty())
872 config->writeEntry(Condition, bp->condition);
873 // we do not save the ignore count
875 // delete remaining groups
876 // we recognize that a group is present if there is an Enabled entry
877 for (;; i++) {
878 groupName.sprintf(BPGroup, i);
879 config->setGroup(groupName);
880 if (!config->hasKey(Enabled)) {
881 /* group not present, assume that we've hit them all */
882 break;
884 config->deleteGroup(groupName);
888 void KDebugger::restoreBreakpoints(ProgramConfig* config)
890 QString groupName;
892 * We recognize the end of the list if there is no Enabled entry
893 * present.
895 for (int i = 0;; i++) {
896 groupName.sprintf(BPGroup, i);
897 config->setGroup(groupName);
898 if (!config->hasKey(Enabled)) {
899 /* group not present, assume that we've hit them all */
900 break;
902 Breakpoint* bp = new Breakpoint;
903 bp->fileName = config->readEntry(File);
904 bp->lineNo = config->readNumEntry(Line, -1);
905 bp->text = config->readEntry(Text);
906 bp->address = config->readEntry(Address);
907 // check consistency
908 if ((bp->fileName.isEmpty() || bp->lineNo < 0) &&
909 bp->text.isEmpty() &&
910 bp->address.isEmpty())
912 delete bp;
913 continue;
915 bp->enabled = config->readBoolEntry(Enabled, true);
916 bp->temporary = config->readBoolEntry(Temporary, false);
917 bp->condition = config->readEntry(Condition);
920 * Add the breakpoint.
922 setBreakpoint(bp, false);
923 // the new breakpoint is disabled or conditionalized later
924 // in newBreakpoint()
926 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverride);
930 // parse output of command cmd
931 void KDebugger::parse(CmdQueueItem* cmd, const char* output)
933 ASSERT(cmd != 0); /* queue mustn't be empty */
935 TRACE(QString(__PRETTY_FUNCTION__) + " parsing " + output);
937 switch (cmd->m_cmd) {
938 case DCtargetremote:
939 // the output (if any) is uninteresting
940 case DCsetargs:
941 case DCtty:
942 // there is no output
943 case DCsetenv:
944 case DCunsetenv:
945 case DCsetoption:
946 /* if value is empty, we see output, but we don't care */
947 break;
948 case DCcd:
949 /* display gdb's message in the status bar */
950 m_d->parseChangeWD(output, m_statusMessage);
951 emit updateStatusMessage();
952 break;
953 case DCinitialize:
954 break;
955 case DCexecutable:
956 if (m_d->parseChangeExecutable(output, m_statusMessage))
958 // success; restore breakpoints etc.
959 if (m_programConfig != 0) {
960 restoreProgramSettings();
962 // load file containing main() or core file
963 if (!m_corefile.isEmpty())
965 // load core file
966 loadCoreFile();
968 else if (!m_attachedPid.isEmpty())
970 m_d->queueCmd(DCattach, m_attachedPid, DebuggerDriver::QMoverride);
971 m_programActive = true;
972 m_programRunning = true;
974 else if (!m_remoteDevice.isEmpty())
976 // handled elsewhere
978 else
980 m_d->queueCmd(DCinfolinemain, DebuggerDriver::QMnormal);
982 if (!m_statusMessage.isEmpty())
983 emit updateStatusMessage();
984 } else {
985 QString msg = m_d->driverName() + ": " + m_statusMessage;
986 KMessageBox::sorry(parentWidget(), msg);
987 m_executable = "";
988 m_corefile = ""; /* don't process core file */
989 m_haveExecutable = false;
991 break;
992 case DCcorefile:
993 // in any event we have an executable at this point
994 m_haveExecutable = true;
995 if (m_d->parseCoreFile(output)) {
996 // loading a core is like stopping at a breakpoint
997 m_programActive = true;
998 handleRunCommands(output);
999 // do not reset m_corefile
1000 } else {
1001 // report error
1002 QString msg = m_d->driverName() + ": " + QString(output);
1003 KMessageBox::sorry(parentWidget(), msg);
1005 // if core file was loaded from command line, revert to info line main
1006 if (!cmd->m_byUser) {
1007 m_d->queueCmd(DCinfolinemain, DebuggerDriver::QMnormal);
1009 m_corefile = QString(); /* core file not available any more */
1011 break;
1012 case DCinfolinemain:
1013 // ignore the output, marked file info follows
1014 m_haveExecutable = true;
1015 break;
1016 case DCinfolocals:
1017 // parse local variables
1018 if (output[0] != '\0') {
1019 handleLocals(output);
1021 break;
1022 case DCinforegisters:
1023 handleRegisters(output);
1024 break;
1025 case DCexamine:
1026 handleMemoryDump(output);
1027 break;
1028 case DCinfoline:
1029 handleInfoLine(cmd, output);
1030 break;
1031 case DCdisassemble:
1032 handleDisassemble(cmd, output);
1033 break;
1034 case DCframe:
1035 handleFrameChange(output);
1036 updateAllExprs();
1037 break;
1038 case DCbt:
1039 handleBacktrace(output);
1040 updateAllExprs();
1041 break;
1042 case DCprint:
1043 handlePrint(cmd, output);
1044 break;
1045 case DCprintDeref:
1046 handlePrintDeref(cmd, output);
1047 break;
1048 case DCattach:
1049 m_haveExecutable = true;
1050 // fall through
1051 case DCrun:
1052 case DCcont:
1053 case DCstep:
1054 case DCstepi:
1055 case DCnext:
1056 case DCnexti:
1057 case DCfinish:
1058 case DCuntil:
1059 case DCthread:
1060 handleRunCommands(output);
1061 break;
1062 case DCkill:
1063 m_programRunning = m_programActive = false;
1064 // erase PC
1065 emit updatePC(QString(), -1, DbgAddr(), 0);
1066 break;
1067 case DCbreaktext:
1068 case DCbreakline:
1069 case DCtbreakline:
1070 case DCbreakaddr:
1071 case DCtbreakaddr:
1072 case DCwatchpoint:
1073 newBreakpoint(cmd, output);
1074 // fall through
1075 case DCdelete:
1076 case DCenable:
1077 case DCdisable:
1078 // these commands need immediate response
1079 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverrideMoreEqual);
1080 break;
1081 case DCinfobreak:
1082 // note: this handler must not enqueue a command, since
1083 // DCinfobreak is used at various different places.
1084 updateBreakList(output);
1085 break;
1086 case DCfindType:
1087 handleFindType(cmd, output);
1088 break;
1089 case DCprintStruct:
1090 case DCprintQStringStruct:
1091 handlePrintStruct(cmd, output);
1092 break;
1093 case DCinfosharedlib:
1094 handleSharedLibs(output);
1095 break;
1096 case DCcondition:
1097 case DCignore:
1098 // we are not interested in the output
1099 break;
1100 case DCinfothreads:
1101 handleThreadList(output);
1102 break;
1103 case DCsetpc:
1104 handleSetPC(output);
1105 break;
1106 case DCsetvariable:
1107 handleSetVariable(cmd, output);
1108 break;
1112 void KDebugger::backgroundUpdate()
1115 * If there are still expressions that need to be updated, then do so.
1117 if (m_programActive)
1118 evalExpressions();
1121 void KDebugger::handleRunCommands(const char* output)
1123 uint flags = m_d->parseProgramStopped(output, m_statusMessage);
1124 emit updateStatusMessage();
1126 m_programActive = flags & DebuggerDriver::SFprogramActive;
1128 // refresh files if necessary
1129 if (flags & DebuggerDriver::SFrefreshSource) {
1130 TRACE("re-reading files");
1131 emit executableUpdated();
1135 * Try to set any orphaned breakpoints now.
1137 for (int i = m_brkpts.size()-1; i >= 0; i--) {
1138 if (m_brkpts[i]->isOrphaned()) {
1139 TRACE("re-trying brkpt loc: "+m_brkpts[i]->location+
1140 " file: "+m_brkpts[i]->fileName+
1141 QString().sprintf(" line: %d", m_brkpts[i]->lineNo));
1142 setBreakpoint(m_brkpts[i], true);
1143 flags |= DebuggerDriver::SFrefreshBreak;
1148 * If we stopped at a breakpoint, we must update the breakpoint list
1149 * because the hit count changes. Also, if the breakpoint was temporary
1150 * it would go away now.
1152 if ((flags & (DebuggerDriver::SFrefreshBreak|DebuggerDriver::SFrefreshSource)) ||
1153 stopMayChangeBreakList())
1155 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverride);
1159 * If we haven't listed the shared libraries yet, do so. We must do
1160 * this before we emit any commands that list variables, since the type
1161 * libraries depend on the shared libraries.
1163 if (!m_sharedLibsListed) {
1164 // must be a high-priority command!
1165 m_d->executeCmd(DCinfosharedlib);
1168 // get the backtrace if the program is running
1169 if (m_programActive) {
1170 m_d->queueCmd(DCbt, DebuggerDriver::QMoverride);
1171 } else {
1172 // program finished: erase PC
1173 emit updatePC(QString(), -1, DbgAddr(), 0);
1174 // dequeue any commands in the queues
1175 m_d->flushCommands();
1178 /* Update threads list */
1179 if (m_programActive && (flags & DebuggerDriver::SFrefreshThreads)) {
1180 m_d->queueCmd(DCinfothreads, DebuggerDriver::QMoverride);
1183 m_programRunning = false;
1184 emit programStopped();
1187 void KDebugger::slotInferiorRunning()
1189 m_programRunning = true;
1192 void KDebugger::updateAllExprs()
1194 if (!m_programActive)
1195 return;
1197 // retrieve local variables
1198 m_d->queueCmd(DCinfolocals, DebuggerDriver::QMoverride);
1200 // retrieve registers
1201 m_d->queueCmd(DCinforegisters, DebuggerDriver::QMoverride);
1203 // get new memory dump
1204 if (!m_memoryExpression.isEmpty()) {
1205 queueMemoryDump(false);
1208 // update watch expressions
1209 KTreeViewItem* item = m_watchVariables.itemAt(0);
1210 for (; item != 0; item = item->getSibling()) {
1211 m_watchEvalExpr.append(static_cast<VarTree*>(item));
1215 void KDebugger::updateProgEnvironment(const QString& args, const QString& wd,
1216 const QDict<EnvVar>& newVars,
1217 const QStringList& newOptions)
1219 m_programArgs = args;
1220 m_d->executeCmd(DCsetargs, m_programArgs);
1221 TRACE("new pgm args: " + m_programArgs + "\n");
1223 m_programWD = wd.stripWhiteSpace();
1224 if (!m_programWD.isEmpty()) {
1225 m_d->executeCmd(DCcd, m_programWD);
1226 TRACE("new wd: " + m_programWD + "\n");
1229 // update environment variables
1230 QDictIterator<EnvVar> it = newVars;
1231 EnvVar* val;
1232 for (; (val = it) != 0; ++it) {
1233 QString var = it.currentKey();
1234 switch (val->status) {
1235 case EnvVar::EVnew:
1236 m_envVars.insert(var, val);
1237 // fall thru
1238 case EnvVar::EVdirty:
1239 // the value must be in our list
1240 ASSERT(m_envVars[var] == val);
1241 // update value
1242 m_d->executeCmd(DCsetenv, var, val->value);
1243 break;
1244 case EnvVar::EVdeleted:
1245 // must be in our list
1246 ASSERT(m_envVars[var] == val);
1247 // delete value
1248 m_d->executeCmd(DCunsetenv, var);
1249 m_envVars.remove(var);
1250 break;
1251 default:
1252 ASSERT(false);
1253 case EnvVar::EVclean:
1254 // variable not changed
1255 break;
1259 // update options
1260 QStringList::ConstIterator oi;
1261 for (oi = newOptions.begin(); oi != newOptions.end(); ++oi)
1263 if (m_boolOptions.findIndex(*oi) < 0) {
1264 // the options is currently not set, so set it
1265 m_d->executeCmd(DCsetoption, *oi, 1);
1266 } else {
1267 // option is set, no action required, but move it to the end
1268 m_boolOptions.remove(*oi);
1270 m_boolOptions.append(*oi);
1273 * Now all options that should be set are at the end of m_boolOptions.
1274 * If some options need to be unset, they are at the front of the list.
1275 * Here we unset and remove them.
1277 while (m_boolOptions.count() > newOptions.count()) {
1278 m_d->executeCmd(DCsetoption, m_boolOptions.first(), 0);
1279 m_boolOptions.remove(m_boolOptions.begin());
1283 void KDebugger::handleLocals(const char* output)
1285 // retrieve old list of local variables
1286 QStrList oldVars;
1287 m_localVariables.exprList(oldVars);
1290 * Get local variables.
1292 QList<VarTree> newVars;
1293 parseLocals(output, newVars);
1296 * Clear any old VarTree item pointers, so that later we don't access
1297 * dangling pointers.
1299 m_localVariables.clearPendingUpdates();
1301 // reduce flicker
1302 bool autoU = m_localVariables.autoUpdate();
1303 m_localVariables.setAutoUpdate(false);
1304 bool repaintNeeded = false;
1307 * Match old variables against new ones.
1309 for (const char* n = oldVars.first(); n != 0; n = oldVars.next()) {
1310 // lookup this variable in the list of new variables
1311 VarTree* v = newVars.first();
1312 while (v != 0 && strcmp(v->getText(), n) != 0) {
1313 v = newVars.next();
1315 if (v == 0) {
1316 // old variable not in the new variables
1317 TRACE(QString("old var deleted: ") + n);
1318 v = m_localVariables.topLevelExprByName(n);
1319 removeExpr(&m_localVariables, v);
1320 if (v != 0) repaintNeeded = true;
1321 } else {
1322 // variable in both old and new lists: update
1323 TRACE(QString("update var: ") + n);
1324 m_localVariables.updateExpr(newVars.current());
1325 // remove the new variable from the list
1326 newVars.remove();
1327 delete v;
1328 repaintNeeded = true;
1331 // insert all remaining new variables
1332 for (VarTree* v = newVars.first(); v != 0; v = newVars.next()) {
1333 TRACE("new var: " + v->getText());
1334 m_localVariables.insertExpr(v);
1335 repaintNeeded = true;
1338 // repaint
1339 m_localVariables.setAutoUpdate(autoU);
1340 if (repaintNeeded && autoU && m_localVariables.isVisible())
1341 m_localVariables.repaint();
1344 void KDebugger::parseLocals(const char* output, QList<VarTree>& newVars)
1346 QList<VarTree> vars;
1347 m_d->parseLocals(output, vars);
1349 QString origName; /* used in renaming variables */
1350 while (vars.count() > 0)
1352 VarTree* variable = vars.take(0);
1353 // get some types
1354 variable->inferTypesOfChildren(*m_typeTable);
1356 * When gdb prints local variables, those from the innermost block
1357 * come first. We run through the list of already parsed variables
1358 * to find duplicates (ie. variables that hide local variables from
1359 * a surrounding block). We keep the name of the inner variable, but
1360 * rename those from the outer block so that, when the value is
1361 * updated in the window, the value of the variable that is
1362 * _visible_ changes the color!
1364 int block = 0;
1365 origName = variable->getText();
1366 for (VarTree* v = newVars.first(); v != 0; v = newVars.next()) {
1367 if (variable->getText() == v->getText()) {
1368 // we found a duplicate, change name
1369 block++;
1370 QString newName = origName + " (" + QString().setNum(block) + ")";
1371 variable->setText(newName);
1374 newVars.append(variable);
1378 bool KDebugger::handlePrint(CmdQueueItem* cmd, const char* output)
1380 ASSERT(cmd->m_expr != 0);
1382 VarTree* variable = parseExpr(output, true);
1383 if (variable == 0)
1384 return false;
1386 // set expression "name"
1387 variable->setText(cmd->m_expr->getText());
1390 TRACE("update expr: " + cmd->m_expr->getText());
1391 cmd->m_exprWnd->updateExpr(cmd->m_expr, variable);
1392 delete variable;
1395 evalExpressions(); /* enqueue dereferenced pointers */
1397 return true;
1400 bool KDebugger::handlePrintDeref(CmdQueueItem* cmd, const char* output)
1402 ASSERT(cmd->m_expr != 0);
1404 VarTree* variable = parseExpr(output, true);
1405 if (variable == 0)
1406 return false;
1408 // set expression "name"
1409 variable->setText(cmd->m_expr->getText());
1413 * We must insert a dummy parent, because otherwise variable's value
1414 * would overwrite cmd->m_expr's value.
1416 VarTree* dummyParent = new VarTree(variable->getText(), VarTree::NKplain);
1417 dummyParent->m_varKind = VarTree::VKdummy;
1418 // the name of the parsed variable is the address of the pointer
1419 QString addr = "*" + cmd->m_expr->m_value;
1420 variable->setText(addr);
1421 variable->m_nameKind = VarTree::NKaddress;
1423 dummyParent->appendChild(variable);
1424 dummyParent->setDeleteChildren(true);
1425 // expand the first level for convenience
1426 variable->setExpanded(true);
1427 TRACE("update ptr: " + cmd->m_expr->getText());
1428 cmd->m_exprWnd->updateExpr(cmd->m_expr, dummyParent);
1429 delete dummyParent;
1432 evalExpressions(); /* enqueue dereferenced pointers */
1434 return true;
1437 VarTree* KDebugger::parseExpr(const char* output, bool wantErrorValue)
1439 VarTree* variable;
1441 // check for error conditions
1442 bool goodValue = m_d->parsePrintExpr(output, wantErrorValue, variable);
1444 if (variable != 0 && goodValue)
1446 // get some types
1447 variable->inferTypesOfChildren(*m_typeTable);
1449 return variable;
1452 // parse the output of bt
1453 void KDebugger::handleBacktrace(const char* output)
1455 // reduce flicker
1456 m_btWindow.setAutoUpdate(false);
1458 m_btWindow.clear();
1460 QList<StackFrame> stack;
1461 m_d->parseBackTrace(output, stack);
1463 if (stack.count() > 0) {
1464 StackFrame* frm = stack.take(0);
1465 // first frame must set PC
1466 // note: frm->lineNo is zero-based
1467 emit updatePC(frm->fileName, frm->lineNo, frm->address, frm->frameNo);
1469 do {
1470 QString func;
1471 if (frm->var != 0)
1472 func = frm->var->getText();
1473 else
1474 func = frm->fileName + ":" + QString().setNum(frm->lineNo+1);
1475 m_btWindow.insertItem(func);
1476 TRACE("frame " + func + " (" + frm->fileName + ":" +
1477 QString().setNum(frm->lineNo+1) + ")");
1478 delete frm;
1480 while ((frm = stack.take()) != 0);
1483 m_btWindow.setAutoUpdate(true);
1484 m_btWindow.repaint();
1487 void KDebugger::gotoFrame(int frame)
1489 m_d->executeCmd(DCframe, frame);
1492 void KDebugger::handleFrameChange(const char* output)
1494 QString fileName;
1495 int frameNo;
1496 int lineNo;
1497 DbgAddr address;
1498 if (m_d->parseFrameChange(output, frameNo, fileName, lineNo, address)) {
1499 /* lineNo can be negative here if we can't find a file name */
1500 emit updatePC(fileName, lineNo, address, frameNo);
1501 } else {
1502 emit updatePC(fileName, -1, address, frameNo);
1506 void KDebugger::evalExpressions()
1508 // evaluate expressions in the following order:
1509 // watch expressions
1510 // pointers in local variables
1511 // pointers in watch expressions
1512 // types in local variables
1513 // types in watch expressions
1514 // pointers in 'this'
1515 // types in 'this'
1517 VarTree* exprItem = m_watchEvalExpr.first();
1518 if (exprItem != 0) {
1519 m_watchEvalExpr.remove();
1520 QString expr = exprItem->computeExpr();
1521 TRACE("watch expr: " + expr);
1522 CmdQueueItem* cmd = m_d->queueCmd(DCprint, expr, DebuggerDriver::QMoverride);
1523 // remember which expr this was
1524 cmd->m_expr = exprItem;
1525 cmd->m_exprWnd = &m_watchVariables;
1526 } else {
1527 ExprWnd* wnd;
1528 VarTree* exprItem;
1529 #define POINTER(widget) \
1530 wnd = &widget; \
1531 exprItem = widget.nextUpdatePtr(); \
1532 if (exprItem != 0) goto pointer
1533 #define STRUCT(widget) \
1534 wnd = &widget; \
1535 exprItem = widget.nextUpdateStruct(); \
1536 if (exprItem != 0) goto ustruct
1537 #define TYPE(widget) \
1538 wnd = &widget; \
1539 exprItem = widget.nextUpdateType(); \
1540 if (exprItem != 0) goto type
1541 repeat:
1542 POINTER(m_localVariables);
1543 POINTER(m_watchVariables);
1544 STRUCT(m_localVariables);
1545 STRUCT(m_watchVariables);
1546 TYPE(m_localVariables);
1547 TYPE(m_watchVariables);
1548 #undef POINTER
1549 #undef STRUCT
1550 #undef TYPE
1551 return;
1553 pointer:
1554 // we have an expression to send
1555 dereferencePointer(wnd, exprItem, false);
1556 return;
1558 ustruct:
1559 // paranoia
1560 if (exprItem->m_type == 0 || exprItem->m_type == TypeInfo::unknownType())
1561 goto repeat;
1562 evalInitialStructExpression(exprItem, wnd, false);
1563 return;
1565 type:
1567 * Sometimes a VarTree gets registered twice for a type update. So
1568 * it may happen that it has already been updated. Hence, we ignore
1569 * it here and go on to the next task.
1571 if (exprItem->m_type != 0)
1572 goto repeat;
1573 determineType(wnd, exprItem);
1577 void KDebugger::dereferencePointer(ExprWnd* wnd, VarTree* exprItem,
1578 bool immediate)
1580 ASSERT(exprItem->m_varKind == VarTree::VKpointer);
1582 QString expr = exprItem->computeExpr();
1583 TRACE("dereferencing pointer: " + expr);
1584 CmdQueueItem* cmd;
1585 if (immediate) {
1586 cmd = m_d->queueCmd(DCprintDeref, expr, DebuggerDriver::QMoverrideMoreEqual);
1587 } else {
1588 cmd = m_d->queueCmd(DCprintDeref, expr, DebuggerDriver::QMoverride);
1590 // remember which expr this was
1591 cmd->m_expr = exprItem;
1592 cmd->m_exprWnd = wnd;
1595 void KDebugger::determineType(ExprWnd* wnd, VarTree* exprItem)
1597 ASSERT(exprItem->m_varKind == VarTree::VKstruct);
1599 QString expr = exprItem->computeExpr();
1600 TRACE("get type of: " + expr);
1601 CmdQueueItem* cmd;
1602 cmd = m_d->queueCmd(DCfindType, expr, DebuggerDriver::QMoverride);
1604 // remember which expr this was
1605 cmd->m_expr = exprItem;
1606 cmd->m_exprWnd = wnd;
1609 void KDebugger::handleFindType(CmdQueueItem* cmd, const char* output)
1611 QString type;
1612 if (m_d->parseFindType(output, type))
1614 ASSERT(cmd != 0 && cmd->m_expr != 0);
1616 TypeInfo* info = m_typeTable->lookup(type);
1618 if (info == 0) {
1620 * We've asked gdb for the type of the expression in
1621 * cmd->m_expr, but it returned a name we don't know. The base
1622 * class (and member) types have been checked already (at the
1623 * time when we parsed that particular expression). Now it's
1624 * time to derive the type from the base classes as a last
1625 * resort.
1627 info = cmd->m_expr->inferTypeFromBaseClass();
1628 // if we found a type through this method, register an alias
1629 if (info != 0) {
1630 TRACE("infered alias: " + type);
1631 m_typeTable->registerAlias(type, info);
1634 if (info == 0) {
1635 TRACE("unknown type");
1636 cmd->m_expr->m_type = TypeInfo::unknownType();
1637 } else {
1638 cmd->m_expr->m_type = info;
1639 /* since this node has a new type, we get its value immediately */
1640 evalInitialStructExpression(cmd->m_expr, cmd->m_exprWnd, false);
1641 return;
1645 evalExpressions(); /* queue more of them */
1648 void KDebugger::handlePrintStruct(CmdQueueItem* cmd, const char* output)
1650 VarTree* var = cmd->m_expr;
1651 ASSERT(var != 0);
1652 ASSERT(var->m_varKind == VarTree::VKstruct);
1654 VarTree* partExpr;
1655 if (cmd->m_cmd != DCprintQStringStruct) {
1656 partExpr = parseExpr(output, false);
1657 } else {
1658 partExpr = m_d->parseQCharArray(output, false, m_typeTable->qCharIsShort());
1660 bool errorValue =
1661 partExpr == 0 ||
1662 /* we only allow simple values at the moment */
1663 partExpr->childCount() != 0;
1665 QString partValue;
1666 if (errorValue)
1668 partValue = "?""?""?"; // 2 question marks in a row would be a trigraph
1669 } else {
1670 partValue = partExpr->m_value;
1672 delete partExpr;
1673 partExpr = 0;
1676 * Updating a struct value works like this: var->m_partialValue holds
1677 * the value that we have gathered so far (it's been initialized with
1678 * var->m_type->m_displayString[0] earlier). Each time we arrive here,
1679 * we append the printed result followed by the next
1680 * var->m_type->m_displayString to var->m_partialValue.
1682 * If the expression we just evaluated was a guard expression, and it
1683 * resulted in an error, we must not evaluate the real expression, but
1684 * go on to the next index. (We must still add the question marks to
1685 * the value).
1687 * Next, if this was the length expression, we still have not seen the
1688 * real expression, but the length of a QString.
1690 ASSERT(var->m_exprIndex >= 0 && var->m_exprIndex <= typeInfoMaxExpr);
1692 if (errorValue || !var->m_exprIndexUseGuard)
1694 // add current partValue (which might be the question marks)
1695 var->m_partialValue += partValue;
1696 var->m_exprIndex++; /* next part */
1697 var->m_exprIndexUseGuard = true;
1698 var->m_partialValue += var->m_type->m_displayString[var->m_exprIndex];
1700 else
1702 // this was a guard expression that succeeded
1703 // go for the real expression
1704 var->m_exprIndexUseGuard = false;
1707 /* go for more sub-expressions if needed */
1708 if (var->m_exprIndex < var->m_type->m_numExprs) {
1709 /* queue a new print command with quite high priority */
1710 evalStructExpression(var, cmd->m_exprWnd, true);
1711 return;
1714 cmd->m_exprWnd->updateStructValue(var);
1716 evalExpressions(); /* enqueue dereferenced pointers */
1719 /* queues the first printStruct command for a struct */
1720 void KDebugger::evalInitialStructExpression(VarTree* var, ExprWnd* wnd, bool immediate)
1722 var->m_exprIndex = 0;
1723 var->m_exprIndexUseGuard = true;
1724 var->m_partialValue = var->m_type->m_displayString[0];
1725 evalStructExpression(var, wnd, immediate);
1728 /* queues a printStruct command; var must have been initialized correctly */
1729 void KDebugger::evalStructExpression(VarTree* var, ExprWnd* wnd, bool immediate)
1731 QString base = var->computeExpr();
1732 QString exprFmt;
1733 if (var->m_exprIndexUseGuard) {
1734 exprFmt = var->m_type->m_guardStrings[var->m_exprIndex];
1735 if (exprFmt.isEmpty()) {
1736 // no guard, omit it and go to expression
1737 var->m_exprIndexUseGuard = false;
1740 if (!var->m_exprIndexUseGuard) {
1741 exprFmt = var->m_type->m_exprStrings[var->m_exprIndex];
1744 QString expr;
1745 expr.sprintf(exprFmt, base.data());
1747 DbgCommand dbgCmd = DCprintStruct;
1748 // check if this is a QString::Data
1749 if (strncmp(expr, "/QString::Data ", 15) == 0)
1751 if (m_typeTable->parseQt2QStrings())
1753 expr = expr.mid(15, expr.length()); /* strip off /QString::Data */
1754 dbgCmd = DCprintQStringStruct;
1755 } else {
1757 * This should not happen: the type libraries should be set up
1758 * in a way that this can't happen. If this happens
1759 * nevertheless it means that, eg., kdecore was loaded but qt2
1760 * was not (only qt2 enables the QString feature).
1762 // TODO: remove this "print"; queue the next printStruct instead
1763 expr = "*0";
1765 } else {
1766 expr = expr;
1768 TRACE("evalStruct: " + expr + (var->m_exprIndexUseGuard ? " // guard" : " // real"));
1769 CmdQueueItem* cmd = m_d->queueCmd(dbgCmd, expr,
1770 immediate ? DebuggerDriver::QMoverrideMoreEqual
1771 : DebuggerDriver::QMnormal);
1773 // remember which expression this was
1774 cmd->m_expr = var;
1775 cmd->m_exprWnd = wnd;
1778 /* removes expression from window */
1779 void KDebugger::removeExpr(ExprWnd* wnd, VarTree* var)
1781 if (var == 0)
1782 return;
1784 // must remove any references to var from command queues
1785 m_d->dequeueCmdByVar(var);
1787 wnd->removeExpr(var);
1790 void KDebugger::handleSharedLibs(const char* output)
1792 // delete all known libraries
1793 m_sharedLibs.clear();
1795 // parse the table of shared libraries
1796 m_d->parseSharedLibs(output, m_sharedLibs);
1797 m_sharedLibsListed = true;
1799 // get type libraries
1800 m_typeTable->loadLibTypes(m_sharedLibs);
1802 // hand over the QString data cmd
1803 m_d->setPrintQStringDataCmd(m_typeTable->printQStringDataCmd());
1806 CmdQueueItem* KDebugger::loadCoreFile()
1808 return m_d->queueCmd(DCcorefile, m_corefile, DebuggerDriver::QMoverride);
1811 void KDebugger::slotLocalsExpanding(KTreeViewItem* item, bool& allow)
1813 exprExpandingHelper(&m_localVariables, item, allow);
1816 void KDebugger::slotWatchExpanding(KTreeViewItem* item, bool& allow)
1818 exprExpandingHelper(&m_watchVariables, item, allow);
1821 void KDebugger::exprExpandingHelper(ExprWnd* wnd, KTreeViewItem* item, bool&)
1823 VarTree* exprItem = static_cast<VarTree*>(item);
1824 if (exprItem->m_varKind != VarTree::VKpointer) {
1825 return;
1827 dereferencePointer(wnd, exprItem, true);
1830 // add the expression in the edit field to the watch expressions
1831 void KDebugger::addWatch(const QString& t)
1833 QString expr = t.stripWhiteSpace();
1834 if (expr.isEmpty())
1835 return;
1836 VarTree* exprItem = new VarTree(expr, VarTree::NKplain);
1837 m_watchVariables.insertExpr(exprItem);
1839 // if we are boring ourselves, send down the command
1840 if (m_programActive) {
1841 m_watchEvalExpr.append(exprItem);
1842 if (m_d->isIdle()) {
1843 evalExpressions();
1848 // delete a toplevel watch expression
1849 void KDebugger::slotDeleteWatch()
1851 // delete only allowed while debugger is idle; or else we might delete
1852 // the very expression the debugger is currently working on...
1853 if (!m_d->isIdle())
1854 return;
1856 int index = m_watchVariables.currentItem();
1857 if (index < 0)
1858 return;
1860 VarTree* item = static_cast<VarTree*>(m_watchVariables.itemAt(index));
1861 if (!item->isToplevelExpr())
1862 return;
1864 // remove the variable from the list to evaluate
1865 if (m_watchEvalExpr.findRef(item) >= 0) {
1866 m_watchEvalExpr.remove();
1868 removeExpr(&m_watchVariables, item);
1869 // item is invalid at this point!
1872 void KDebugger::handleRegisters(const char* output)
1874 QList<RegisterInfo> regs;
1875 m_d->parseRegisters(output, regs);
1877 emit registersChanged(regs);
1879 // delete them all
1880 regs.setAutoDelete(true);
1884 * The output of the DCbreak* commands has more accurate information about
1885 * the file and the line number.
1887 * All newly set breakpoints are inserted in the m_brkpts, even those that
1888 * were not set sucessfully. The unsuccessful breakpoints ("orphaned
1889 * breakpoints") are assigned negative ids, and they are tried to set later
1890 * when the program stops again at a breakpoint.
1892 void KDebugger::newBreakpoint(CmdQueueItem* cmd, const char* output)
1894 Breakpoint* bp = cmd->m_brkpt;
1895 assert(bp != 0);
1896 if (bp == 0)
1897 return;
1899 // if this is a new breakpoint, put it in the list
1900 bool isNew = !m_brkpts.contains(bp);
1901 if (isNew) {
1902 assert(bp->id == 0);
1903 int n = m_brkpts.size();
1904 m_brkpts.resize(n+1);
1905 m_brkpts.insert(n, bp);
1908 // parse the output to determine success or failure
1909 int id;
1910 QString file;
1911 int lineNo;
1912 QString address;
1913 if (!m_d->parseBreakpoint(output, id, file, lineNo, address))
1916 * Failure, the breakpoint could not be set. If this is a new
1917 * breakpoint, assign it a negative id. We look for the minimal id
1918 * of all breakpoints (that are already in the list) to get the new
1919 * id.
1921 if (isNew)
1923 assert(bp->id == 0);
1924 for (int i = m_brkpts.size()-2; i >= 0; i--) {
1925 if (m_brkpts[i]->id < bp->id) {
1926 bp->id = m_brkpts[i]->id;
1927 break;
1930 --bp->id;
1932 return;
1935 // The breakpoint was successfully set.
1936 if (bp->id <= 0)
1938 // this is a new or orphaned breakpoint:
1939 // set the remaining properties
1940 if (!cmd->m_brkpt->enabled) {
1941 m_d->executeCmd(DCdisable, id);
1943 if (!cmd->m_brkpt->condition.isEmpty()) {
1944 m_d->executeCmd(DCcondition, cmd->m_brkpt->condition, id);
1948 bp->id = id;
1949 bp->fileName = file;
1950 bp->lineNo = lineNo;
1951 if (!address.isEmpty())
1952 bp->address = address;
1955 void KDebugger::updateBreakList(const char* output)
1957 // get the new list
1958 QList<Breakpoint> brks;
1959 brks.setAutoDelete(false);
1960 m_d->parseBreakList(output, brks);
1962 // merge new information into existing breakpoints
1964 for (int i = m_brkpts.size()-1; i >= 0; i--) // decrement!
1966 // skip orphaned breakpoints
1967 if (m_brkpts[i]->id < 0)
1968 continue;
1970 for (Breakpoint* bp = brks.first(); bp != 0; bp = brks.next())
1972 if (bp->id == m_brkpts[i]->id) {
1973 // keep accurate location
1974 // except that xsldbg doesn't have a location in
1975 // the old breakpoint if it's just been set
1976 bp->text = m_brkpts[i]->text;
1977 if (!m_brkpts[i]->fileName.isEmpty()) {
1978 bp->fileName = m_brkpts[i]->fileName;
1979 bp->lineNo = m_brkpts[i]->lineNo;
1981 m_brkpts.insert(i, bp); // old object is deleted
1982 goto stillAlive;
1986 * If we get here, this breakpoint is no longer present.
1988 * To delete the breakpoint at i, we place the last breakpoint in
1989 * the list into the slot i. This will delete the old object at i.
1990 * Then we shorten the list by one.
1992 m_brkpts.insert(i, m_brkpts.take(m_brkpts.size()-1));
1993 m_brkpts.resize(m_brkpts.size()-1);
1994 TRACE(QString().sprintf("deleted brkpt %d, have now %d brkpts", i, m_brkpts.size()));
1996 stillAlive:;
1999 // brks may contain new breakpoints not already in m_brkpts
2000 for (const Breakpoint* bp = brks.first(); bp != 0; bp = brks.next())
2002 bool found = false;
2003 for (uint i = 0; i < m_brkpts.size(); i++) {
2004 if (bp->id == m_brkpts[i]->id) {
2005 found = true;
2006 break;
2009 if (!found){
2010 int n = m_brkpts.size();
2011 m_brkpts.resize(n+1);
2012 m_brkpts.insert(n, bp);
2016 emit breakpointsChanged();
2019 // look if there is at least one temporary breakpoint
2020 // or a watchpoint
2021 bool KDebugger::stopMayChangeBreakList() const
2023 for (int i = m_brkpts.size()-1; i >= 0; i--) {
2024 Breakpoint* bp = m_brkpts[i];
2025 if (bp->temporary || bp->type == Breakpoint::watchpoint)
2026 return true;
2028 return false;
2031 Breakpoint* KDebugger::breakpointByFilePos(QString file, int lineNo,
2032 const DbgAddr& address)
2034 // look for exact file name match
2035 int i;
2036 for (i = m_brkpts.size()-1; i >= 0; i--) {
2037 if (m_brkpts[i]->lineNo == lineNo &&
2038 m_brkpts[i]->fileName == file &&
2039 (address.isEmpty() || m_brkpts[i]->address == address))
2041 return m_brkpts[i];
2044 // not found, so try basename
2045 // strip off directory part of file name
2046 int offset = file.findRev("/");
2047 file.remove(0, offset+1);
2049 for (i = m_brkpts.size()-1; i >= 0; i--) {
2050 // get base name of breakpoint's file
2051 QString basename = m_brkpts[i]->fileName;
2052 int offset = basename.findRev("/");
2053 if (offset >= 0) {
2054 basename.remove(0, offset+1);
2057 if (m_brkpts[i]->lineNo == lineNo &&
2058 basename == file &&
2059 (address.isEmpty() || m_brkpts[i]->address == address))
2061 return m_brkpts[i];
2065 // not found
2066 return 0;
2069 Breakpoint* KDebugger::breakpointById(int id)
2071 for (int i = m_brkpts.size()-1; i >= 0; i--)
2073 if (m_brkpts[i]->id == id) {
2074 return m_brkpts[i];
2077 // not found
2078 return 0;
2081 void KDebugger::slotValuePopup(const QString& expr)
2083 // search the local variables for a match
2084 VarTree* v = m_localVariables.topLevelExprByName(expr);
2085 if (v == 0) {
2086 // not found, check watch expressions
2087 v = m_watchVariables.topLevelExprByName(expr);
2088 if (v == 0) {
2089 // nothing found; do nothing
2090 return;
2094 // construct the tip
2095 QString tip = v->getText() + " = ";
2096 if (!v->m_value.isEmpty())
2098 tip += v->m_value;
2100 else
2102 // no value: we use some hint
2103 switch (v->m_varKind) {
2104 case VarTree::VKstruct:
2105 tip += "{...}";
2106 break;
2107 case VarTree::VKarray:
2108 tip += "[...]";
2109 break;
2110 default:
2111 tip += "?""?""?"; // 2 question marks in a row would be a trigraph
2112 break;
2115 emit valuePopup(tip);
2118 void KDebugger::slotDisassemble(const QString& fileName, int lineNo)
2120 CmdQueueItem* cmd = m_d->queueCmd(DCinfoline, fileName, lineNo,
2121 DebuggerDriver::QMoverrideMoreEqual);
2122 cmd->m_fileName = fileName;
2123 cmd->m_lineNo = lineNo;
2126 void KDebugger::handleInfoLine(CmdQueueItem* cmd, const char* output)
2128 QString addrFrom, addrTo;
2129 if (cmd->m_lineNo >= 0) {
2130 // disassemble
2131 if (m_d->parseInfoLine(output, addrFrom, addrTo)) {
2132 // got the address range, now get the real code
2133 CmdQueueItem* c = m_d->queueCmd(DCdisassemble, addrFrom, addrTo,
2134 DebuggerDriver::QMoverrideMoreEqual);
2135 c->m_fileName = cmd->m_fileName;
2136 c->m_lineNo = cmd->m_lineNo;
2137 } else {
2138 // no code
2139 QList<DisassembledCode> empty;
2140 emit disassembled(cmd->m_fileName, cmd->m_lineNo, empty);
2142 } else {
2143 // set program counter
2144 if (m_d->parseInfoLine(output, addrFrom, addrTo)) {
2145 // move the program counter to the start address
2146 m_d->executeCmd(DCsetpc, addrFrom);
2151 void KDebugger::handleDisassemble(CmdQueueItem* cmd, const char* output)
2153 QList<DisassembledCode> code;
2154 code.setAutoDelete(true);
2155 m_d->parseDisassemble(output, code);
2156 emit disassembled(cmd->m_fileName, cmd->m_lineNo, code);
2159 void KDebugger::handleThreadList(const char* output)
2161 QList<ThreadInfo> threads;
2162 threads.setAutoDelete(true);
2163 m_d->parseThreadList(output, threads);
2164 emit threadsChanged(threads);
2167 void KDebugger::setThread(int id)
2169 m_d->queueCmd(DCthread, id, DebuggerDriver::QMoverrideMoreEqual);
2172 void KDebugger::setMemoryExpression(const QString& memexpr)
2174 m_memoryExpression = memexpr;
2176 // queue the new expression
2177 if (!m_memoryExpression.isEmpty() &&
2178 isProgramActive() &&
2179 !isProgramRunning())
2181 queueMemoryDump(true);
2185 void KDebugger::queueMemoryDump(bool immediate)
2187 m_d->queueCmd(DCexamine, m_memoryExpression, m_memoryFormat,
2188 immediate ? DebuggerDriver::QMoverrideMoreEqual :
2189 DebuggerDriver::QMoverride);
2192 void KDebugger::handleMemoryDump(const char* output)
2194 QList<MemoryDump> memdump;
2195 memdump.setAutoDelete(true);
2196 QString msg = m_d->parseMemoryDump(output, memdump);
2197 emit memoryDumpChanged(msg, memdump);
2200 void KDebugger::setProgramCounter(const QString& file, int line, const DbgAddr& addr)
2202 if (addr.isEmpty()) {
2203 // find address of the specified line
2204 CmdQueueItem* cmd = m_d->executeCmd(DCinfoline, file, line);
2205 cmd->m_lineNo = -1; /* indicates "Set PC" UI command */
2206 } else {
2207 // move the program counter to that address
2208 m_d->executeCmd(DCsetpc, addr.asString());
2212 void KDebugger::handleSetPC(const char* /*output*/)
2214 // TODO: handle errors
2216 // now go to the top-most frame
2217 // this also modifies the program counter indicator in the UI
2218 gotoFrame(0);
2221 void KDebugger::slotValueEdited(int row, const QString& text)
2223 if (text.simplifyWhiteSpace().isEmpty())
2224 return; /* no text entered: ignore request */
2226 ASSERT(sender()->inherits("ExprWnd"));
2227 ExprWnd* wnd = const_cast<ExprWnd*>(static_cast<const ExprWnd*>(sender()));
2228 TRACE(QString().sprintf("Changing %s at row %d to ",
2229 wnd->name(), row) + text);
2231 // determine the lvalue to edit
2232 VarTree* expr = static_cast<VarTree*>(wnd->itemAt(row));
2233 QString lvalue = expr->computeExpr();
2234 CmdQueueItem* cmd = m_d->executeCmd(DCsetvariable, lvalue, text);
2235 cmd->m_expr = expr;
2236 cmd->m_exprWnd = wnd;
2239 void KDebugger::handleSetVariable(CmdQueueItem* cmd, const char* output)
2241 QString msg = m_d->parseSetVariable(output);
2242 if (!msg.isEmpty())
2244 // there was an error; display it in the status bar
2245 m_statusMessage = msg;
2246 emit updateStatusMessage();
2247 return;
2250 // get the new value
2251 QString expr = cmd->m_expr->computeExpr();
2252 CmdQueueItem* printCmd =
2253 m_d->queueCmd(DCprint, expr, DebuggerDriver::QMoverrideMoreEqual);
2254 printCmd->m_expr = cmd->m_expr;
2255 printCmd->m_exprWnd = cmd->m_exprWnd;
2259 #include "debugger.moc"