Code cleanup of the treatment of display expressions.
[kdbg.git] / kdbg / debugger.cpp
blob94fe1419003f2ade591a144ae4afe5648a7ac3ac
1 /*
2 * Copyright Johannes Sixt
3 * This file is licensed under the GNU General Public License Version 2.
4 * See the file COPYING in the toplevel directory of the source directory.
5 */
7 #include "debugger.h"
8 #include "dbgdriver.h"
9 #include "pgmargs.h"
10 #include "typetable.h"
11 #include "exprwnd.h"
12 #include "pgmsettings.h"
13 #include "programconfig.h"
14 #include "valarray.h"
15 #include <qregexp.h>
16 #include <qfileinfo.h>
17 #include <qlistbox.h>
18 #include <qstringlist.h>
19 #include <kapp.h>
20 #include <kconfig.h>
21 #include <klocale.h> /* i18n */
22 #include <kmessagebox.h>
23 #include <ctype.h>
24 #include <stdlib.h> /* strtol, atoi */
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h> /* sleep(3) */
27 #endif
28 #include "mydebug.h"
31 KDebugger::KDebugger(QWidget* parent,
32 ExprWnd* localVars,
33 ExprWnd* watchVars,
34 QListBox* backtrace) :
35 QObject(parent, "debugger"),
36 m_ttyLevel(ttyFull),
37 m_memoryFormat(MDTword | MDThex),
38 m_haveExecutable(false),
39 m_programActive(false),
40 m_programRunning(false),
41 m_sharedLibsListed(false),
42 m_typeTable(0),
43 m_programConfig(0),
44 m_d(0),
45 m_localVariables(*localVars),
46 m_watchVariables(*watchVars),
47 m_btWindow(*backtrace)
49 m_envVars.setAutoDelete(true);
50 m_brkpts.setAutoDelete(true);
52 connect(&m_localVariables, SIGNAL(expanded(QListViewItem*)),
53 SLOT(slotExpanding(QListViewItem*)));
54 connect(&m_watchVariables, SIGNAL(expanded(QListViewItem*)),
55 SLOT(slotExpanding(QListViewItem*)));
56 connect(&m_localVariables, SIGNAL(editValueCommitted(VarTree*, const QString&)),
57 SLOT(slotValueEdited(VarTree*, const QString&)));
58 connect(&m_watchVariables, SIGNAL(editValueCommitted(VarTree*, const QString&)),
59 SLOT(slotValueEdited(VarTree*, const QString&)));
61 connect(&m_btWindow, SIGNAL(highlighted(int)), SLOT(gotoFrame(int)));
63 emit updateUI();
66 KDebugger::~KDebugger()
68 if (m_programConfig != 0) {
69 saveProgramSettings();
70 m_programConfig->sync();
71 delete m_programConfig;
74 delete m_typeTable;
78 void KDebugger::saveSettings(KConfig* /*config*/)
82 void KDebugger::restoreSettings(KConfig* /*config*/)
87 //////////////////////////////////////////////////////////////////////
88 // external interface
90 const char GeneralGroup[] = "General";
91 const char DebuggerCmdStr[] = "DebuggerCmdStr";
92 const char TTYLevelEntry[] = "TTYLevel";
93 const char KDebugger::DriverNameEntry[] = "DriverName";
95 bool KDebugger::debugProgram(const QString& name,
96 DebuggerDriver* driver)
98 if (m_d != 0 && m_d->isRunning())
100 QApplication::setOverrideCursor(waitCursor);
102 stopDriver();
104 QApplication::restoreOverrideCursor();
106 if (m_d->isRunning() || m_haveExecutable) {
107 /* timed out! We can't really do anything useful now */
108 TRACE("timed out while waiting for gdb to die!");
109 return false;
111 delete m_d;
112 m_d = 0;
115 // wire up the driver
116 connect(driver, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)),
117 this, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)));
118 connect(driver, SIGNAL(processExited(KProcess*)), SLOT(gdbExited(KProcess*)));
119 connect(driver, SIGNAL(commandReceived(CmdQueueItem*,const char*)),
120 SLOT(parse(CmdQueueItem*,const char*)));
121 connect(driver, SIGNAL(wroteStdin(KProcess*)), SIGNAL(updateUI()));
122 connect(driver, SIGNAL(inferiorRunning()), SLOT(slotInferiorRunning()));
123 connect(driver, SIGNAL(enterIdleState()), SLOT(backgroundUpdate()));
124 connect(driver, SIGNAL(enterIdleState()), SIGNAL(updateUI()));
125 connect(&m_localVariables, SIGNAL(removingItem(VarTree*)),
126 driver, SLOT(dequeueCmdByVar(VarTree*)));
127 connect(&m_watchVariables, SIGNAL(removingItem(VarTree*)),
128 driver, SLOT(dequeueCmdByVar(VarTree*)));
130 // create the program settings object
131 openProgramConfig(name);
133 // get debugger command from per-program settings
134 if (m_programConfig != 0) {
135 m_programConfig->setGroup(GeneralGroup);
136 m_debuggerCmd = readDebuggerCmd();
137 // get terminal emulation level
138 m_ttyLevel = TTYLevel(m_programConfig->readNumEntry(TTYLevelEntry, ttyFull));
140 // the rest is read in later in the handler of DCexecutable
142 m_d = driver;
144 if (!startDriver()) {
145 TRACE("startDriver failed");
146 m_d = 0;
147 return false;
150 TRACE("before file cmd");
151 m_d->executeCmd(DCexecutable, name);
152 m_executable = name;
154 // set remote target
155 if (!m_remoteDevice.isEmpty()) {
156 m_d->executeCmd(DCtargetremote, m_remoteDevice);
157 m_d->queueCmd(DCbt, DebuggerDriver::QMoverride);
158 m_d->queueCmd(DCframe, 0, DebuggerDriver::QMnormal);
159 m_programActive = true;
160 m_haveExecutable = true;
163 // create a type table
164 m_typeTable = new ProgramTypeTable;
165 m_sharedLibsListed = false;
167 emit updateUI();
169 return true;
172 void KDebugger::shutdown()
174 // shut down debugger driver
175 if (m_d != 0 && m_d->isRunning())
177 stopDriver();
181 void KDebugger::useCoreFile(QString corefile, bool batch)
183 m_corefile = corefile;
184 if (!batch) {
185 CmdQueueItem* cmd = loadCoreFile();
186 cmd->m_byUser = true;
190 void KDebugger::setAttachPid(const QString& pid)
192 m_attachedPid = pid;
195 void KDebugger::programRun()
197 if (!isReady())
198 return;
200 // when program is active, but not a core file, continue
201 // otherwise run the program
202 if (m_programActive && m_corefile.isEmpty()) {
203 // gdb command: continue
204 m_d->executeCmd(DCcont, true);
205 } else {
206 // gdb command: run
207 m_d->executeCmd(DCrun, true);
208 m_corefile = QString();
209 m_programActive = true;
211 m_programRunning = true;
214 void KDebugger::attachProgram(const QString& pid)
216 if (!isReady())
217 return;
219 m_attachedPid = pid;
220 TRACE("Attaching to " + m_attachedPid);
221 m_d->executeCmd(DCattach, m_attachedPid);
222 m_programActive = true;
223 m_programRunning = true;
226 void KDebugger::programRunAgain()
228 if (canSingleStep()) {
229 m_d->executeCmd(DCrun, true);
230 m_corefile = QString();
231 m_programRunning = true;
235 void KDebugger::programStep()
237 if (canSingleStep()) {
238 m_d->executeCmd(DCstep, true);
239 m_programRunning = true;
243 void KDebugger::programNext()
245 if (canSingleStep()) {
246 m_d->executeCmd(DCnext, true);
247 m_programRunning = true;
251 void KDebugger::programStepi()
253 if (canSingleStep()) {
254 m_d->executeCmd(DCstepi, true);
255 m_programRunning = true;
259 void KDebugger::programNexti()
261 if (canSingleStep()) {
262 m_d->executeCmd(DCnexti, true);
263 m_programRunning = true;
267 void KDebugger::programFinish()
269 if (canSingleStep()) {
270 m_d->executeCmd(DCfinish, true);
271 m_programRunning = true;
275 void KDebugger::programKill()
277 if (haveExecutable() && isProgramActive()) {
278 if (m_programRunning) {
279 m_d->interruptInferior();
281 // this is an emergency command; flush queues
282 m_d->flushCommands(true);
283 m_d->executeCmd(DCkill, true);
287 bool KDebugger::runUntil(const QString& fileName, int lineNo)
289 if (isReady() && m_programActive && !m_programRunning) {
290 // strip off directory part of file name
291 QString file = fileName;
292 int offset = file.findRev("/");
293 if (offset >= 0) {
294 file.remove(0, offset+1);
296 m_d->executeCmd(DCuntil, file, lineNo, true);
297 m_programRunning = true;
298 return true;
299 } else {
300 return false;
304 void KDebugger::programBreak()
306 if (m_haveExecutable && m_programRunning) {
307 m_d->interruptInferior();
311 void KDebugger::programArgs(QWidget* parent)
313 if (m_haveExecutable) {
314 QStringList allOptions = m_d->boolOptionList();
315 PgmArgs dlg(parent, m_executable, m_envVars, allOptions);
316 dlg.setArgs(m_programArgs);
317 dlg.setWd(m_programWD);
318 dlg.setOptions(m_boolOptions);
319 if (dlg.exec()) {
320 updateProgEnvironment(dlg.args(), dlg.wd(),
321 dlg.envVars(), dlg.options());
326 void KDebugger::programSettings(QWidget* parent)
328 if (!m_haveExecutable)
329 return;
331 ProgramSettings dlg(parent, m_executable);
333 dlg.m_chooseDriver.setDebuggerCmd(m_debuggerCmd);
334 dlg.m_output.setTTYLevel(m_ttyLevel);
336 if (dlg.exec() == QDialog::Accepted)
338 m_debuggerCmd = dlg.m_chooseDriver.debuggerCmd();
339 m_ttyLevel = TTYLevel(dlg.m_output.ttyLevel());
343 bool KDebugger::setBreakpoint(QString file, int lineNo,
344 const DbgAddr& address, bool temporary)
346 if (!isReady()) {
347 return false;
350 Breakpoint* bp = breakpointByFilePos(file, lineNo, address);
351 if (bp == 0)
354 * No such breakpoint, so set a new one. If we have an address, we
355 * set the breakpoint exactly there. Otherwise we use the file name
356 * plus line no.
358 Breakpoint* bp = new Breakpoint;
359 bp->temporary = temporary;
361 if (address.isEmpty())
363 bp->fileName = file;
364 bp->lineNo = lineNo;
366 else
368 bp->address = address;
370 setBreakpoint(bp, false);
372 else
375 * If the breakpoint is disabled, enable it; if it's enabled,
376 * delete that breakpoint.
378 if (bp->enabled) {
379 deleteBreakpoint(bp);
380 } else {
381 enableDisableBreakpoint(bp);
384 return true;
387 void KDebugger::setBreakpoint(Breakpoint* bp, bool queueOnly)
389 CmdQueueItem* cmd;
390 if (!bp->text.isEmpty())
393 * The breakpoint was set using the text box in the breakpoint
394 * list. This is the only way in which watchpoints are set.
396 if (bp->type == Breakpoint::watchpoint) {
397 cmd = m_d->executeCmd(DCwatchpoint, bp->text);
398 } else {
399 cmd = m_d->executeCmd(DCbreaktext, bp->text);
402 else if (bp->address.isEmpty())
404 // strip off directory part of file name
405 QString file = bp->fileName;
406 int offset = file.findRev("/");
407 if (offset >= 0) {
408 file.remove(0, offset+1);
410 if (queueOnly) {
411 cmd = m_d->queueCmd(bp->temporary ? DCtbreakline : DCbreakline,
412 file, bp->lineNo, DebuggerDriver::QMoverride);
413 } else {
414 cmd = m_d->executeCmd(bp->temporary ? DCtbreakline : DCbreakline,
415 file, bp->lineNo);
418 else
420 if (queueOnly) {
421 cmd = m_d->queueCmd(bp->temporary ? DCtbreakaddr : DCbreakaddr,
422 bp->address.asString(), DebuggerDriver::QMoverride);
423 } else {
424 cmd = m_d->executeCmd(bp->temporary ? DCtbreakaddr : DCbreakaddr,
425 bp->address.asString());
428 cmd->m_brkpt = bp; // used in newBreakpoint()
431 bool KDebugger::enableDisableBreakpoint(QString file, int lineNo,
432 const DbgAddr& address)
434 Breakpoint* bp = breakpointByFilePos(file, lineNo, address);
435 return bp == 0 || enableDisableBreakpoint(bp);
438 bool KDebugger::enableDisableBreakpoint(Breakpoint* bp)
441 * Toggle enabled/disabled state.
443 * The driver is not bothered if we are modifying an orphaned
444 * breakpoint.
446 if (!bp->isOrphaned()) {
447 if (!canChangeBreakpoints()) {
448 return false;
450 m_d->executeCmd(bp->enabled ? DCdisable : DCenable, bp->id);
451 } else {
452 bp->enabled = !bp->enabled;
453 emit breakpointsChanged();
455 return true;
458 bool KDebugger::conditionalBreakpoint(Breakpoint* bp,
459 const QString& condition,
460 int ignoreCount)
463 * Change the condition and ignore count.
465 * The driver is not bothered if we are removing an orphaned
466 * breakpoint.
469 if (!bp->isOrphaned()) {
470 if (!canChangeBreakpoints()) {
471 return false;
474 bool changed = false;
476 if (bp->condition != condition) {
477 // change condition
478 m_d->executeCmd(DCcondition, condition, bp->id);
479 changed = true;
481 if (bp->ignoreCount != ignoreCount) {
482 // change ignore count
483 m_d->executeCmd(DCignore, bp->id, ignoreCount);
484 changed = true;
486 if (changed) {
487 // get the changes
488 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverride);
490 } else {
491 bp->condition = condition;
492 bp->ignoreCount = ignoreCount;
493 emit breakpointsChanged();
495 return true;
498 bool KDebugger::deleteBreakpoint(Breakpoint* bp)
501 * Remove the breakpoint.
503 * The driver is not bothered if we are removing an orphaned
504 * breakpoint.
506 if (!bp->isOrphaned()) {
507 if (!canChangeBreakpoints()) {
508 return false;
510 m_d->executeCmd(DCdelete, bp->id);
511 } else {
512 // move the last entry to bp's slot and shorten the list
513 int i = m_brkpts.findRef(bp);
514 m_brkpts.insert(i, m_brkpts.take(m_brkpts.size()-1));
515 m_brkpts.resize(m_brkpts.size()-1);
516 emit breakpointsChanged();
518 return false;
521 bool KDebugger::canSingleStep()
523 return isReady() && m_programActive && !m_programRunning;
526 bool KDebugger::canChangeBreakpoints()
528 return isReady() && !m_programRunning;
531 bool KDebugger::canStart()
533 return isReady() && !m_programActive;
536 bool KDebugger::isReady() const
538 return m_haveExecutable &&
539 m_d != 0 && m_d->canExecuteImmediately();
542 bool KDebugger::isIdle() const
544 return m_d == 0 || m_d->isIdle();
548 //////////////////////////////////////////////////////////
549 // debugger driver
551 bool KDebugger::startDriver()
553 emit debuggerStarting(); /* must set m_inferiorTerminal */
556 * If the per-program command string is empty, use the global setting
557 * (which might also be empty, in which case the driver uses its
558 * default).
560 m_explicitKill = false;
561 if (!m_d->startup(m_debuggerCmd)) {
562 return false;
566 * If we have an output terminal, we use it. Otherwise we will run the
567 * program with input and output redirected to /dev/null. Other
568 * redirections are also necessary depending on the tty emulation
569 * level.
571 int redirect = RDNstdin|RDNstdout|RDNstderr; /* redirect everything */
572 if (!m_inferiorTerminal.isEmpty()) {
573 switch (m_ttyLevel) {
574 default:
575 case ttyNone:
576 // redirect everything
577 break;
578 case ttySimpleOutputOnly:
579 redirect = RDNstdin;
580 break;
581 case ttyFull:
582 redirect = 0;
583 break;
586 m_d->executeCmd(DCtty, m_inferiorTerminal, redirect);
588 return true;
591 void KDebugger::stopDriver()
593 m_explicitKill = true;
595 if (m_attachedPid.isEmpty()) {
596 m_d->terminate();
597 } else {
598 m_d->detachAndTerminate();
602 * We MUST wait until the slot gdbExited() has been called. But to
603 * avoid a deadlock, we wait only for some certain maximum time. Should
604 * this timeout be reached, the only reasonable thing one could do then
605 * is exiting kdbg.
607 kapp->processEvents(1000); /* ideally, this will already shut it down */
608 int maxTime = 20; /* about 20 seconds */
609 while (m_haveExecutable && maxTime > 0) {
610 // give gdb time to die (and send a SIGCLD)
611 ::sleep(1);
612 --maxTime;
613 kapp->processEvents(1000);
617 void KDebugger::gdbExited(KProcess*)
620 * Save settings, but only if gdb has already processed "info line
621 * main", otherwise we would save an empty config file, because it
622 * isn't read in until then!
624 if (m_programConfig != 0) {
625 if (m_haveExecutable) {
626 saveProgramSettings();
627 m_programConfig->sync();
629 delete m_programConfig;
630 m_programConfig = 0;
633 // erase types
634 delete m_typeTable;
635 m_typeTable = 0;
637 if (m_explicitKill) {
638 TRACE(m_d->driverName() + " exited normally");
639 } else {
640 QString msg = i18n("%1 exited unexpectedly.\n"
641 "Restart the session (e.g. with File|Executable).");
642 KMessageBox::error(parentWidget(), msg.arg(m_d->driverName()));
645 // reset state
646 m_haveExecutable = false;
647 m_executable = "";
648 m_programActive = false;
649 m_programRunning = false;
650 m_explicitKill = false;
651 m_debuggerCmd = QString(); /* use global setting at next start! */
652 m_attachedPid = QString(); /* we are no longer attached to a process */
653 m_ttyLevel = ttyFull;
654 m_brkpts.clear();
656 // erase PC
657 emit updatePC(QString(), -1, DbgAddr(), 0);
660 QString KDebugger::getConfigForExe(const QString& name)
662 QFileInfo fi(name);
663 QString pgmConfigFile = fi.dirPath(true);
664 if (!pgmConfigFile.isEmpty()) {
665 pgmConfigFile += '/';
667 pgmConfigFile += ".kdbgrc." + fi.fileName();
668 TRACE("program config file = " + pgmConfigFile);
669 return pgmConfigFile;
672 void KDebugger::openProgramConfig(const QString& name)
674 ASSERT(m_programConfig == 0);
676 QString pgmConfigFile = getConfigForExe(name);
678 m_programConfig = new ProgramConfig(pgmConfigFile);
681 const char EnvironmentGroup[] = "Environment";
682 const char WatchGroup[] = "Watches";
683 const char FileVersion[] = "FileVersion";
684 const char ProgramArgs[] = "ProgramArgs";
685 const char WorkingDirectory[] = "WorkingDirectory";
686 const char OptionsSelected[] = "OptionsSelected";
687 const char Variable[] = "Var%d";
688 const char Value[] = "Value%d";
689 const char ExprFmt[] = "Expr%d";
691 void KDebugger::saveProgramSettings()
693 ASSERT(m_programConfig != 0);
694 m_programConfig->setGroup(GeneralGroup);
695 m_programConfig->writeEntry(FileVersion, 1);
696 m_programConfig->writeEntry(ProgramArgs, m_programArgs);
697 m_programConfig->writeEntry(WorkingDirectory, m_programWD);
698 m_programConfig->writeEntry(OptionsSelected, m_boolOptions);
699 m_programConfig->writeEntry(DebuggerCmdStr, m_debuggerCmd);
700 m_programConfig->writeEntry(TTYLevelEntry, int(m_ttyLevel));
701 QString driverName;
702 if (m_d != 0)
703 driverName = m_d->driverName();
704 m_programConfig->writeEntry(DriverNameEntry, driverName);
706 // write environment variables
707 m_programConfig->deleteGroup(EnvironmentGroup);
708 m_programConfig->setGroup(EnvironmentGroup);
709 QDictIterator<EnvVar> it = m_envVars;
710 EnvVar* var;
711 QString varName;
712 QString varValue;
713 for (int i = 0; (var = it) != 0; ++it, ++i) {
714 varName.sprintf(Variable, i);
715 varValue.sprintf(Value, i);
716 m_programConfig->writeEntry(varName, it.currentKey());
717 m_programConfig->writeEntry(varValue, var->value);
720 saveBreakpoints(m_programConfig);
722 // watch expressions
723 // first get rid of whatever was in this group
724 m_programConfig->deleteGroup(WatchGroup);
725 // then start a new group
726 m_programConfig->setGroup(WatchGroup);
727 VarTree* item = m_watchVariables.firstChild();
728 int watchNum = 0;
729 for (; item != 0; item = item->nextSibling(), ++watchNum) {
730 varName.sprintf(ExprFmt, watchNum);
731 m_programConfig->writeEntry(varName, item->getText());
734 // give others a chance
735 emit saveProgramSpecific(m_programConfig);
738 void KDebugger::restoreProgramSettings()
740 ASSERT(m_programConfig != 0);
741 m_programConfig->setGroup(GeneralGroup);
743 * We ignore file version for now we will use it in the future to
744 * distinguish different versions of this configuration file.
746 // m_debuggerCmd has been read in already
747 // m_ttyLevel has been read in already
748 QString pgmArgs = m_programConfig->readEntry(ProgramArgs);
749 QString pgmWd = m_programConfig->readEntry(WorkingDirectory);
750 QStringList boolOptions = m_programConfig->readListEntry(OptionsSelected);
751 m_boolOptions = QStringList();
753 // read environment variables
754 m_programConfig->setGroup(EnvironmentGroup);
755 m_envVars.clear();
756 QDict<EnvVar> pgmVars;
757 EnvVar* var;
758 QString varName;
759 QString varValue;
760 for (int i = 0;; ++i) {
761 varName.sprintf(Variable, i);
762 varValue.sprintf(Value, i);
763 if (!m_programConfig->hasKey(varName)) {
764 /* entry not present, assume that we've hit them all */
765 break;
767 QString name = m_programConfig->readEntry(varName);
768 if (name.isEmpty()) {
769 // skip empty names
770 continue;
772 var = new EnvVar;
773 var->value = m_programConfig->readEntry(varValue);
774 var->status = EnvVar::EVnew;
775 pgmVars.insert(name, var);
778 updateProgEnvironment(pgmArgs, pgmWd, pgmVars, boolOptions);
780 restoreBreakpoints(m_programConfig);
782 // watch expressions
783 m_programConfig->setGroup(WatchGroup);
784 m_watchVariables.clear();
785 for (int i = 0;; ++i) {
786 varName.sprintf(ExprFmt, i);
787 if (!m_programConfig->hasKey(varName)) {
788 /* entry not present, assume that we've hit them all */
789 break;
791 QString expr = m_programConfig->readEntry(varName);
792 if (expr.isEmpty()) {
793 // skip empty expressions
794 continue;
796 addWatch(expr);
799 // give others a chance
800 emit restoreProgramSpecific(m_programConfig);
804 * Reads the debugger command line from the program settings. The config
805 * group must have been set by the caller.
807 QString KDebugger::readDebuggerCmd()
809 QString debuggerCmd = m_programConfig->readEntry(DebuggerCmdStr);
811 // always let the user confirm the debugger cmd if we are root
812 if (::geteuid() == 0)
814 if (!debuggerCmd.isEmpty()) {
815 QString msg = i18n(
816 "The settings for this program specify "
817 "the following debugger command:\n%1\n"
818 "Shall this command be used?");
819 if (KMessageBox::warningYesNo(parentWidget(), msg.arg(debuggerCmd))
820 != KMessageBox::Yes)
822 // don't use it
823 debuggerCmd = QString();
827 return debuggerCmd;
831 * Breakpoints are saved one per group.
833 const char BPGroup[] = "Breakpoint %d";
834 const char File[] = "File";
835 const char Line[] = "Line";
836 const char Text[] = "Text";
837 const char Address[] = "Address";
838 const char Temporary[] = "Temporary";
839 const char Enabled[] = "Enabled";
840 const char Condition[] = "Condition";
842 void KDebugger::saveBreakpoints(ProgramConfig* config)
844 QString groupName;
845 int i = 0;
846 for (uint j = 0; j < m_brkpts.size(); j++) {
847 Breakpoint* bp = m_brkpts[j];
848 if (bp->type == Breakpoint::watchpoint)
849 continue; /* don't save watchpoints */
850 groupName.sprintf(BPGroup, i++);
852 /* remove remmants */
853 config->deleteGroup(groupName);
855 config->setGroup(groupName);
856 if (!bp->text.isEmpty()) {
858 * The breakpoint was set using the text box in the breakpoint
859 * list. We do not save the location by filename+line number,
860 * but instead honor what the user typed (a function name, for
861 * example, which could move between sessions).
863 config->writeEntry(Text, bp->text);
864 } else if (!bp->fileName.isEmpty()) {
865 config->writeEntry(File, bp->fileName);
866 config->writeEntry(Line, bp->lineNo);
868 * Addresses are hardly correct across sessions, so we don't
869 * save it.
871 } else {
872 config->writeEntry(Address, bp->address.asString());
874 config->writeEntry(Temporary, bp->temporary);
875 config->writeEntry(Enabled, bp->enabled);
876 if (!bp->condition.isEmpty())
877 config->writeEntry(Condition, bp->condition);
878 // we do not save the ignore count
880 // delete remaining groups
881 // we recognize that a group is present if there is an Enabled entry
882 for (;; i++) {
883 groupName.sprintf(BPGroup, i);
884 config->setGroup(groupName);
885 if (!config->hasKey(Enabled)) {
886 /* group not present, assume that we've hit them all */
887 break;
889 config->deleteGroup(groupName);
893 void KDebugger::restoreBreakpoints(ProgramConfig* config)
895 QString groupName;
897 * We recognize the end of the list if there is no Enabled entry
898 * present.
900 for (int i = 0;; i++) {
901 groupName.sprintf(BPGroup, i);
902 config->setGroup(groupName);
903 if (!config->hasKey(Enabled)) {
904 /* group not present, assume that we've hit them all */
905 break;
907 Breakpoint* bp = new Breakpoint;
908 bp->fileName = config->readEntry(File);
909 bp->lineNo = config->readNumEntry(Line, -1);
910 bp->text = config->readEntry(Text);
911 bp->address = config->readEntry(Address);
912 // check consistency
913 if ((bp->fileName.isEmpty() || bp->lineNo < 0) &&
914 bp->text.isEmpty() &&
915 bp->address.isEmpty())
917 delete bp;
918 continue;
920 bp->enabled = config->readBoolEntry(Enabled, true);
921 bp->temporary = config->readBoolEntry(Temporary, false);
922 bp->condition = config->readEntry(Condition);
925 * Add the breakpoint.
927 setBreakpoint(bp, false);
928 // the new breakpoint is disabled or conditionalized later
929 // in newBreakpoint()
931 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverride);
935 // parse output of command cmd
936 void KDebugger::parse(CmdQueueItem* cmd, const char* output)
938 ASSERT(cmd != 0); /* queue mustn't be empty */
940 TRACE(QString(__PRETTY_FUNCTION__) + " parsing " + output);
942 switch (cmd->m_cmd) {
943 case DCtargetremote:
944 // the output (if any) is uninteresting
945 case DCsetargs:
946 case DCtty:
947 // there is no output
948 case DCsetenv:
949 case DCunsetenv:
950 case DCsetoption:
951 /* if value is empty, we see output, but we don't care */
952 break;
953 case DCcd:
954 /* display gdb's message in the status bar */
955 m_d->parseChangeWD(output, m_statusMessage);
956 emit updateStatusMessage();
957 break;
958 case DCinitialize:
959 break;
960 case DCexecutable:
961 if (m_d->parseChangeExecutable(output, m_statusMessage))
963 // success; restore breakpoints etc.
964 if (m_programConfig != 0) {
965 restoreProgramSettings();
967 // load file containing main() or core file
968 if (!m_corefile.isEmpty())
970 // load core file
971 loadCoreFile();
973 else if (!m_attachedPid.isEmpty())
975 m_d->queueCmd(DCattach, m_attachedPid, DebuggerDriver::QMoverride);
976 m_programActive = true;
977 m_programRunning = true;
979 else if (!m_remoteDevice.isEmpty())
981 // handled elsewhere
983 else
985 m_d->queueCmd(DCinfolinemain, DebuggerDriver::QMnormal);
987 if (!m_statusMessage.isEmpty())
988 emit updateStatusMessage();
989 } else {
990 QString msg = m_d->driverName() + ": " + m_statusMessage;
991 KMessageBox::sorry(parentWidget(), msg);
992 m_executable = "";
993 m_corefile = ""; /* don't process core file */
994 m_haveExecutable = false;
996 break;
997 case DCcorefile:
998 // in any event we have an executable at this point
999 m_haveExecutable = true;
1000 if (m_d->parseCoreFile(output)) {
1001 // loading a core is like stopping at a breakpoint
1002 m_programActive = true;
1003 handleRunCommands(output);
1004 // do not reset m_corefile
1005 } else {
1006 // report error
1007 QString msg = m_d->driverName() + ": " + QString(output);
1008 KMessageBox::sorry(parentWidget(), msg);
1010 // if core file was loaded from command line, revert to info line main
1011 if (!cmd->m_byUser) {
1012 m_d->queueCmd(DCinfolinemain, DebuggerDriver::QMnormal);
1014 m_corefile = QString(); /* core file not available any more */
1016 break;
1017 case DCinfolinemain:
1018 // ignore the output, marked file info follows
1019 m_haveExecutable = true;
1020 break;
1021 case DCinfolocals:
1022 // parse local variables
1023 if (output[0] != '\0') {
1024 handleLocals(output);
1026 break;
1027 case DCinforegisters:
1028 handleRegisters(output);
1029 break;
1030 case DCexamine:
1031 handleMemoryDump(output);
1032 break;
1033 case DCinfoline:
1034 handleInfoLine(cmd, output);
1035 break;
1036 case DCdisassemble:
1037 handleDisassemble(cmd, output);
1038 break;
1039 case DCframe:
1040 handleFrameChange(output);
1041 updateAllExprs();
1042 break;
1043 case DCbt:
1044 handleBacktrace(output);
1045 updateAllExprs();
1046 break;
1047 case DCprint:
1048 handlePrint(cmd, output);
1049 break;
1050 case DCprintDeref:
1051 handlePrintDeref(cmd, output);
1052 break;
1053 case DCattach:
1054 m_haveExecutable = true;
1055 // fall through
1056 case DCrun:
1057 case DCcont:
1058 case DCstep:
1059 case DCstepi:
1060 case DCnext:
1061 case DCnexti:
1062 case DCfinish:
1063 case DCuntil:
1064 case DCthread:
1065 handleRunCommands(output);
1066 break;
1067 case DCkill:
1068 m_programRunning = m_programActive = false;
1069 // erase PC
1070 emit updatePC(QString(), -1, DbgAddr(), 0);
1071 break;
1072 case DCbreaktext:
1073 case DCbreakline:
1074 case DCtbreakline:
1075 case DCbreakaddr:
1076 case DCtbreakaddr:
1077 case DCwatchpoint:
1078 newBreakpoint(cmd, output);
1079 // fall through
1080 case DCdelete:
1081 case DCenable:
1082 case DCdisable:
1083 // these commands need immediate response
1084 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverrideMoreEqual);
1085 break;
1086 case DCinfobreak:
1087 // note: this handler must not enqueue a command, since
1088 // DCinfobreak is used at various different places.
1089 updateBreakList(output);
1090 break;
1091 case DCfindType:
1092 handleFindType(cmd, output);
1093 break;
1094 case DCprintStruct:
1095 case DCprintQStringStruct:
1096 case DCprintWChar:
1097 handlePrintStruct(cmd, output);
1098 break;
1099 case DCinfosharedlib:
1100 handleSharedLibs(output);
1101 break;
1102 case DCcondition:
1103 case DCignore:
1104 // we are not interested in the output
1105 break;
1106 case DCinfothreads:
1107 handleThreadList(output);
1108 break;
1109 case DCsetpc:
1110 handleSetPC(output);
1111 break;
1112 case DCsetvariable:
1113 handleSetVariable(cmd, output);
1114 break;
1118 void KDebugger::backgroundUpdate()
1121 * If there are still expressions that need to be updated, then do so.
1123 if (m_programActive)
1124 evalExpressions();
1127 void KDebugger::handleRunCommands(const char* output)
1129 uint flags = m_d->parseProgramStopped(output, m_statusMessage);
1130 emit updateStatusMessage();
1132 m_programActive = flags & DebuggerDriver::SFprogramActive;
1134 // refresh files if necessary
1135 if (flags & DebuggerDriver::SFrefreshSource) {
1136 TRACE("re-reading files");
1137 emit executableUpdated();
1141 * Try to set any orphaned breakpoints now.
1143 for (int i = m_brkpts.size()-1; i >= 0; i--) {
1144 if (m_brkpts[i]->isOrphaned()) {
1145 TRACE("re-trying brkpt loc: "+m_brkpts[i]->location+
1146 " file: "+m_brkpts[i]->fileName+
1147 QString().sprintf(" line: %d", m_brkpts[i]->lineNo));
1148 setBreakpoint(m_brkpts[i], true);
1149 flags |= DebuggerDriver::SFrefreshBreak;
1154 * If we stopped at a breakpoint, we must update the breakpoint list
1155 * because the hit count changes. Also, if the breakpoint was temporary
1156 * it would go away now.
1158 if ((flags & (DebuggerDriver::SFrefreshBreak|DebuggerDriver::SFrefreshSource)) ||
1159 stopMayChangeBreakList())
1161 m_d->queueCmd(DCinfobreak, DebuggerDriver::QMoverride);
1165 * If we haven't listed the shared libraries yet, do so. We must do
1166 * this before we emit any commands that list variables, since the type
1167 * libraries depend on the shared libraries.
1169 if (!m_sharedLibsListed) {
1170 // must be a high-priority command!
1171 m_d->executeCmd(DCinfosharedlib);
1174 // get the backtrace if the program is running
1175 if (m_programActive) {
1176 m_d->queueCmd(DCbt, DebuggerDriver::QMoverride);
1177 } else {
1178 // program finished: erase PC
1179 emit updatePC(QString(), -1, DbgAddr(), 0);
1180 // dequeue any commands in the queues
1181 m_d->flushCommands();
1184 /* Update threads list */
1185 if (m_programActive && (flags & DebuggerDriver::SFrefreshThreads)) {
1186 m_d->queueCmd(DCinfothreads, DebuggerDriver::QMoverride);
1189 m_programRunning = false;
1190 emit programStopped();
1193 void KDebugger::slotInferiorRunning()
1195 m_programRunning = true;
1198 void KDebugger::updateAllExprs()
1200 if (!m_programActive)
1201 return;
1203 // retrieve local variables
1204 m_d->queueCmd(DCinfolocals, DebuggerDriver::QMoverride);
1206 // retrieve registers
1207 m_d->queueCmd(DCinforegisters, DebuggerDriver::QMoverride);
1209 // get new memory dump
1210 if (!m_memoryExpression.isEmpty()) {
1211 queueMemoryDump(false);
1214 // update watch expressions
1215 VarTree* item = m_watchVariables.firstChild();
1216 for (; item != 0; item = item->nextSibling()) {
1217 m_watchEvalExpr.push_back(item->getText());
1221 void KDebugger::updateProgEnvironment(const QString& args, const QString& wd,
1222 const QDict<EnvVar>& newVars,
1223 const QStringList& newOptions)
1225 m_programArgs = args;
1226 m_d->executeCmd(DCsetargs, m_programArgs);
1227 TRACE("new pgm args: " + m_programArgs + "\n");
1229 m_programWD = wd.stripWhiteSpace();
1230 if (!m_programWD.isEmpty()) {
1231 m_d->executeCmd(DCcd, m_programWD);
1232 TRACE("new wd: " + m_programWD + "\n");
1235 // update environment variables
1236 QDictIterator<EnvVar> it = newVars;
1237 EnvVar* val;
1238 for (; (val = it) != 0; ++it) {
1239 QString var = it.currentKey();
1240 switch (val->status) {
1241 case EnvVar::EVnew:
1242 m_envVars.insert(var, val);
1243 // fall thru
1244 case EnvVar::EVdirty:
1245 // the value must be in our list
1246 ASSERT(m_envVars[var] == val);
1247 // update value
1248 m_d->executeCmd(DCsetenv, var, val->value);
1249 break;
1250 case EnvVar::EVdeleted:
1251 // must be in our list
1252 ASSERT(m_envVars[var] == val);
1253 // delete value
1254 m_d->executeCmd(DCunsetenv, var);
1255 m_envVars.remove(var);
1256 break;
1257 default:
1258 ASSERT(false);
1259 case EnvVar::EVclean:
1260 // variable not changed
1261 break;
1265 // update options
1266 QStringList::ConstIterator oi;
1267 for (oi = newOptions.begin(); oi != newOptions.end(); ++oi)
1269 if (m_boolOptions.findIndex(*oi) < 0) {
1270 // the options is currently not set, so set it
1271 m_d->executeCmd(DCsetoption, *oi, 1);
1272 } else {
1273 // option is set, no action required, but move it to the end
1274 m_boolOptions.remove(*oi);
1276 m_boolOptions.append(*oi);
1279 * Now all options that should be set are at the end of m_boolOptions.
1280 * If some options need to be unset, they are at the front of the list.
1281 * Here we unset and remove them.
1283 while (m_boolOptions.count() > newOptions.count()) {
1284 m_d->executeCmd(DCsetoption, m_boolOptions.first(), 0);
1285 m_boolOptions.remove(m_boolOptions.begin());
1289 void KDebugger::handleLocals(const char* output)
1291 // retrieve old list of local variables
1292 QStrList oldVars;
1293 m_localVariables.exprList(oldVars);
1296 * Get local variables.
1298 QList<ExprValue> newVars;
1299 parseLocals(output, newVars);
1302 * Clear any old VarTree item pointers, so that later we don't access
1303 * dangling pointers.
1305 m_localVariables.clearPendingUpdates();
1308 * Match old variables against new ones.
1310 for (const char* n = oldVars.first(); n != 0; n = oldVars.next()) {
1311 // lookup this variable in the list of new variables
1312 ExprValue* v = newVars.first();
1313 while (v != 0 && v->m_name != n) {
1314 v = newVars.next();
1316 if (v == 0) {
1317 // old variable not in the new variables
1318 TRACE(QString("old var deleted: ") + n);
1319 VarTree* v = m_localVariables.topLevelExprByName(n);
1320 if (v != 0) {
1321 m_localVariables.removeExpr(v);
1323 } else {
1324 // variable in both old and new lists: update
1325 TRACE(QString("update var: ") + n);
1326 m_localVariables.updateExpr(newVars.current(), *m_typeTable);
1327 // remove the new variable from the list
1328 newVars.remove();
1329 delete v;
1332 // insert all remaining new variables
1333 while (!newVars.isEmpty())
1335 ExprValue* v = newVars.take(0);
1336 TRACE("new var: " + v->m_name);
1337 m_localVariables.insertExpr(v, *m_typeTable);
1338 delete v;
1342 void KDebugger::parseLocals(const char* output, QList<ExprValue>& newVars)
1344 QList<ExprValue> vars;
1345 m_d->parseLocals(output, vars);
1347 QString origName; /* used in renaming variables */
1348 while (vars.count() > 0)
1350 ExprValue* variable = vars.take(0);
1352 * When gdb prints local variables, those from the innermost block
1353 * come first. We run through the list of already parsed variables
1354 * to find duplicates (ie. variables that hide local variables from
1355 * a surrounding block). We keep the name of the inner variable, but
1356 * rename those from the outer block so that, when the value is
1357 * updated in the window, the value of the variable that is
1358 * _visible_ changes the color!
1360 int block = 0;
1361 origName = variable->m_name;
1362 for (ExprValue* v = newVars.first(); v != 0; v = newVars.next()) {
1363 if (variable->m_name == v->m_name) {
1364 // we found a duplicate, change name
1365 block++;
1366 QString newName = origName + " (" + QString().setNum(block) + ")";
1367 variable->m_name = newName;
1370 newVars.append(variable);
1374 bool KDebugger::handlePrint(CmdQueueItem* cmd, const char* output)
1376 ASSERT(cmd->m_expr != 0);
1378 ExprValue* variable = m_d->parsePrintExpr(output, true);
1379 if (variable == 0)
1380 return false;
1382 // set expression "name"
1383 variable->m_name = cmd->m_expr->getText();
1386 TRACE("update expr: " + cmd->m_expr->getText());
1387 cmd->m_exprWnd->updateExpr(cmd->m_expr, variable, *m_typeTable);
1388 delete variable;
1391 evalExpressions(); /* enqueue dereferenced pointers */
1393 return true;
1396 bool KDebugger::handlePrintDeref(CmdQueueItem* cmd, const char* output)
1398 ASSERT(cmd->m_expr != 0);
1400 ExprValue* variable = m_d->parsePrintExpr(output, true);
1401 if (variable == 0)
1402 return false;
1404 // set expression "name"
1405 variable->m_name = cmd->m_expr->getText();
1409 * We must insert a dummy parent, because otherwise variable's value
1410 * would overwrite cmd->m_expr's value.
1412 ExprValue* dummyParent = new ExprValue(variable->m_name, VarTree::NKplain);
1413 dummyParent->m_varKind = VarTree::VKdummy;
1414 // the name of the parsed variable is the address of the pointer
1415 QString addr = "*" + cmd->m_expr->value();
1416 variable->m_name = addr;
1417 variable->m_nameKind = VarTree::NKaddress;
1419 dummyParent->m_child = variable;
1420 // expand the first level for convenience
1421 variable->m_initiallyExpanded = true;
1422 TRACE("update ptr: " + cmd->m_expr->getText());
1423 cmd->m_exprWnd->updateExpr(cmd->m_expr, dummyParent, *m_typeTable);
1424 delete dummyParent;
1427 evalExpressions(); /* enqueue dereferenced pointers */
1429 return true;
1432 // parse the output of bt
1433 void KDebugger::handleBacktrace(const char* output)
1435 // reduce flicker
1436 m_btWindow.setAutoUpdate(false);
1438 m_btWindow.clear();
1440 QList<StackFrame> stack;
1441 m_d->parseBackTrace(output, stack);
1443 if (stack.count() > 0) {
1444 StackFrame* frm = stack.take(0);
1445 // first frame must set PC
1446 // note: frm->lineNo is zero-based
1447 emit updatePC(frm->fileName, frm->lineNo, frm->address, frm->frameNo);
1449 do {
1450 QString func;
1451 if (frm->var != 0)
1452 func = frm->var->m_name;
1453 else
1454 func = frm->fileName + ":" + QString().setNum(frm->lineNo+1);
1455 m_btWindow.insertItem(func);
1456 TRACE("frame " + func + " (" + frm->fileName + ":" +
1457 QString().setNum(frm->lineNo+1) + ")");
1458 delete frm;
1460 while ((frm = stack.take()) != 0);
1463 m_btWindow.setAutoUpdate(true);
1464 m_btWindow.repaint();
1467 void KDebugger::gotoFrame(int frame)
1469 m_d->executeCmd(DCframe, frame);
1472 void KDebugger::handleFrameChange(const char* output)
1474 QString fileName;
1475 int frameNo;
1476 int lineNo;
1477 DbgAddr address;
1478 if (m_d->parseFrameChange(output, frameNo, fileName, lineNo, address)) {
1479 /* lineNo can be negative here if we can't find a file name */
1480 emit updatePC(fileName, lineNo, address, frameNo);
1481 } else {
1482 emit updatePC(fileName, -1, address, frameNo);
1486 void KDebugger::evalExpressions()
1488 // evaluate expressions in the following order:
1489 // watch expressions
1490 // pointers in local variables
1491 // pointers in watch expressions
1492 // types in local variables
1493 // types in watch expressions
1494 // struct members in local variables
1495 // struct members in watch expressions
1496 VarTree* exprItem = 0;
1497 if (!m_watchEvalExpr.empty())
1499 QString expr = m_watchEvalExpr.front();
1500 m_watchEvalExpr.pop_front();
1501 exprItem = m_watchVariables.topLevelExprByName(expr);
1503 if (exprItem != 0) {
1504 CmdQueueItem* cmd = m_d->queueCmd(DCprint, exprItem->getText(), DebuggerDriver::QMoverride);
1505 // remember which expr this was
1506 cmd->m_expr = exprItem;
1507 cmd->m_exprWnd = &m_watchVariables;
1508 } else {
1509 ExprWnd* wnd;
1510 #define POINTER(widget) \
1511 wnd = &widget; \
1512 exprItem = widget.nextUpdatePtr(); \
1513 if (exprItem != 0) goto pointer
1514 #define STRUCT(widget) \
1515 wnd = &widget; \
1516 exprItem = widget.nextUpdateStruct(); \
1517 if (exprItem != 0) goto ustruct
1518 #define TYPE(widget) \
1519 wnd = &widget; \
1520 exprItem = widget.nextUpdateType(); \
1521 if (exprItem != 0) goto type
1522 repeat:
1523 POINTER(m_localVariables);
1524 POINTER(m_watchVariables);
1525 STRUCT(m_localVariables);
1526 STRUCT(m_watchVariables);
1527 TYPE(m_localVariables);
1528 TYPE(m_watchVariables);
1529 #undef POINTER
1530 #undef STRUCT
1531 #undef TYPE
1532 return;
1534 pointer:
1535 // we have an expression to send
1536 dereferencePointer(wnd, exprItem, false);
1537 return;
1539 ustruct:
1540 // paranoia
1541 if (exprItem->m_type == 0 || exprItem->m_type == TypeInfo::unknownType())
1542 goto repeat;
1543 evalInitialStructExpression(exprItem, wnd, false);
1544 return;
1546 type:
1548 * Sometimes a VarTree gets registered twice for a type update. So
1549 * it may happen that it has already been updated. Hence, we ignore
1550 * it here and go on to the next task.
1552 if (exprItem->m_type != 0)
1553 goto repeat;
1554 determineType(wnd, exprItem);
1558 void KDebugger::dereferencePointer(ExprWnd* wnd, VarTree* exprItem,
1559 bool immediate)
1561 ASSERT(exprItem->m_varKind == VarTree::VKpointer);
1563 QString expr = exprItem->computeExpr();
1564 TRACE("dereferencing pointer: " + expr);
1565 CmdQueueItem* cmd;
1566 if (immediate) {
1567 cmd = m_d->queueCmd(DCprintDeref, expr, DebuggerDriver::QMoverrideMoreEqual);
1568 } else {
1569 cmd = m_d->queueCmd(DCprintDeref, expr, DebuggerDriver::QMoverride);
1571 // remember which expr this was
1572 cmd->m_expr = exprItem;
1573 cmd->m_exprWnd = wnd;
1576 void KDebugger::determineType(ExprWnd* wnd, VarTree* exprItem)
1578 ASSERT(exprItem->m_varKind == VarTree::VKstruct);
1580 QString expr = exprItem->computeExpr();
1581 TRACE("get type of: " + expr);
1582 CmdQueueItem* cmd;
1583 cmd = m_d->queueCmd(DCfindType, expr, DebuggerDriver::QMoverride);
1585 // remember which expr this was
1586 cmd->m_expr = exprItem;
1587 cmd->m_exprWnd = wnd;
1590 void KDebugger::handleFindType(CmdQueueItem* cmd, const char* output)
1592 QString type;
1593 if (m_d->parseFindType(output, type))
1595 ASSERT(cmd != 0 && cmd->m_expr != 0);
1597 TypeInfo* info = m_typeTable->lookup(type);
1599 if (info == 0) {
1601 * We've asked gdb for the type of the expression in
1602 * cmd->m_expr, but it returned a name we don't know. The base
1603 * class (and member) types have been checked already (at the
1604 * time when we parsed that particular expression). Now it's
1605 * time to derive the type from the base classes as a last
1606 * resort.
1608 info = cmd->m_expr->inferTypeFromBaseClass();
1609 // if we found a type through this method, register an alias
1610 if (info != 0) {
1611 TRACE("infered alias: " + type);
1612 m_typeTable->registerAlias(type, info);
1615 if (info == 0) {
1616 TRACE("unknown type "+type);
1617 cmd->m_expr->m_type = TypeInfo::unknownType();
1618 } else {
1619 cmd->m_expr->m_type = info;
1620 /* since this node has a new type, we get its value immediately */
1621 evalInitialStructExpression(cmd->m_expr, cmd->m_exprWnd, false);
1622 return;
1626 evalExpressions(); /* queue more of them */
1629 void KDebugger::handlePrintStruct(CmdQueueItem* cmd, const char* output)
1631 VarTree* var = cmd->m_expr;
1632 ASSERT(var != 0);
1633 ASSERT(var->m_varKind == VarTree::VKstruct);
1635 ExprValue* partExpr;
1636 if (cmd->m_cmd == DCprintQStringStruct) {
1637 partExpr = m_d->parseQCharArray(output, false, m_typeTable->qCharIsShort());
1638 } else if (cmd->m_cmd == DCprintWChar) {
1639 partExpr = m_d->parseQCharArray(output, false, true);
1640 } else {
1641 partExpr = m_d->parsePrintExpr(output, false);
1643 bool errorValue =
1644 partExpr == 0 ||
1645 /* we only allow simple values at the moment */
1646 partExpr->m_child != 0;
1648 QString partValue;
1649 if (errorValue)
1651 partValue = "?""?""?"; // 2 question marks in a row would be a trigraph
1652 } else {
1653 partValue = partExpr->m_value;
1655 delete partExpr;
1656 partExpr = 0;
1659 * Updating a struct value works like this: var->m_partialValue holds
1660 * the value that we have gathered so far (it's been initialized with
1661 * var->m_type->m_displayString[0] earlier). Each time we arrive here,
1662 * we append the printed result followed by the next
1663 * var->m_type->m_displayString to var->m_partialValue.
1665 * If the expression we just evaluated was a guard expression, and it
1666 * resulted in an error, we must not evaluate the real expression, but
1667 * go on to the next index. (We must still add the question marks to
1668 * the value).
1670 * Next, if this was the length expression, we still have not seen the
1671 * real expression, but the length of a QString.
1673 ASSERT(var->m_exprIndex >= 0 && var->m_exprIndex <= typeInfoMaxExpr);
1675 if (errorValue || !var->m_exprIndexUseGuard)
1677 // add current partValue (which might be the question marks)
1678 var->m_partialValue += partValue;
1679 var->m_exprIndex++; /* next part */
1680 var->m_exprIndexUseGuard = true;
1681 var->m_partialValue += var->m_type->m_displayString[var->m_exprIndex];
1683 else
1685 // this was a guard expression that succeeded
1686 // go for the real expression
1687 var->m_exprIndexUseGuard = false;
1690 /* go for more sub-expressions if needed */
1691 if (var->m_exprIndex < var->m_type->m_numExprs) {
1692 /* queue a new print command with quite high priority */
1693 evalStructExpression(var, cmd->m_exprWnd, true);
1694 return;
1697 cmd->m_exprWnd->updateStructValue(var);
1699 evalExpressions(); /* enqueue dereferenced pointers */
1702 /* queues the first printStruct command for a struct */
1703 void KDebugger::evalInitialStructExpression(VarTree* var, ExprWnd* wnd, bool immediate)
1705 var->m_exprIndex = 0;
1706 if (var->m_type != TypeInfo::wchartType())
1708 var->m_exprIndexUseGuard = true;
1709 var->m_partialValue = var->m_type->m_displayString[0];
1710 evalStructExpression(var, wnd, immediate);
1712 else
1714 var->m_exprIndexUseGuard = false;
1715 QString expr = var->computeExpr();
1716 CmdQueueItem* cmd = m_d->queueCmd(DCprintWChar, expr,
1717 immediate ? DebuggerDriver::QMoverrideMoreEqual
1718 : DebuggerDriver::QMoverride);
1719 // remember which expression this was
1720 cmd->m_expr = var;
1721 cmd->m_exprWnd = wnd;
1725 /* queues a printStruct command; var must have been initialized correctly */
1726 void KDebugger::evalStructExpression(VarTree* var, ExprWnd* wnd, bool immediate)
1728 QString base = var->computeExpr();
1729 QString expr;
1730 if (var->m_exprIndexUseGuard) {
1731 expr = var->m_type->m_guardStrings[var->m_exprIndex];
1732 if (expr.isEmpty()) {
1733 // no guard, omit it and go to expression
1734 var->m_exprIndexUseGuard = false;
1737 if (!var->m_exprIndexUseGuard) {
1738 expr = var->m_type->m_exprStrings[var->m_exprIndex];
1741 expr.replace("%s", base);
1743 DbgCommand dbgCmd = DCprintStruct;
1744 // check if this is a QString::Data
1745 if (expr.left(15) == "/QString::Data ")
1747 if (m_typeTable->parseQt2QStrings())
1749 expr = expr.mid(15, expr.length()); /* strip off /QString::Data */
1750 dbgCmd = DCprintQStringStruct;
1751 } else {
1753 * This should not happen: the type libraries should be set up
1754 * in a way that this can't happen. If this happens
1755 * nevertheless it means that, eg., kdecore was loaded but qt2
1756 * was not (only qt2 enables the QString feature).
1758 // TODO: remove this "print"; queue the next printStruct instead
1759 expr = "*0";
1762 TRACE("evalStruct: " + expr + (var->m_exprIndexUseGuard ? " // guard" : " // real"));
1763 CmdQueueItem* cmd = m_d->queueCmd(dbgCmd, expr,
1764 immediate ? DebuggerDriver::QMoverrideMoreEqual
1765 : DebuggerDriver::QMnormal);
1767 // remember which expression this was
1768 cmd->m_expr = var;
1769 cmd->m_exprWnd = wnd;
1772 void KDebugger::handleSharedLibs(const char* output)
1774 // delete all known libraries
1775 m_sharedLibs.clear();
1777 // parse the table of shared libraries
1778 m_d->parseSharedLibs(output, m_sharedLibs);
1779 m_sharedLibsListed = true;
1781 // get type libraries
1782 m_typeTable->loadLibTypes(m_sharedLibs);
1784 // hand over the QString data cmd
1785 m_d->setPrintQStringDataCmd(m_typeTable->printQStringDataCmd());
1788 CmdQueueItem* KDebugger::loadCoreFile()
1790 return m_d->queueCmd(DCcorefile, m_corefile, DebuggerDriver::QMoverride);
1793 void KDebugger::slotExpanding(QListViewItem* item)
1795 VarTree* exprItem = static_cast<VarTree*>(item);
1796 if (exprItem->m_varKind != VarTree::VKpointer) {
1797 return;
1799 ExprWnd* wnd = static_cast<ExprWnd*>(item->listView());
1800 dereferencePointer(wnd, exprItem, true);
1803 // add the expression in the edit field to the watch expressions
1804 void KDebugger::addWatch(const QString& t)
1806 QString expr = t.stripWhiteSpace();
1807 // don't add a watched expression again
1808 if (expr.isEmpty() || m_watchVariables.topLevelExprByName(expr) != 0)
1809 return;
1810 ExprValue e(expr, VarTree::NKplain);
1811 m_watchVariables.insertExpr(&e, *m_typeTable);
1813 // if we are boring ourselves, send down the command
1814 if (m_programActive) {
1815 m_watchEvalExpr.push_back(expr);
1816 if (m_d->isIdle()) {
1817 evalExpressions();
1822 // delete a toplevel watch expression
1823 void KDebugger::slotDeleteWatch()
1825 // delete only allowed while debugger is idle; or else we might delete
1826 // the very expression the debugger is currently working on...
1827 if (m_d == 0 || !m_d->isIdle())
1828 return;
1830 VarTree* item = m_watchVariables.currentItem();
1831 if (item == 0 || !item->isToplevelExpr())
1832 return;
1834 // remove the variable from the list to evaluate
1835 QStringList::iterator i = m_watchEvalExpr.find(item->getText());
1836 if (i != m_watchEvalExpr.end()) {
1837 m_watchEvalExpr.erase(i);
1839 m_watchVariables.removeExpr(item);
1840 // item is invalid at this point!
1843 void KDebugger::handleRegisters(const char* output)
1845 QList<RegisterInfo> regs;
1846 m_d->parseRegisters(output, regs);
1848 emit registersChanged(regs);
1850 // delete them all
1851 regs.setAutoDelete(true);
1855 * The output of the DCbreak* commands has more accurate information about
1856 * the file and the line number.
1858 * All newly set breakpoints are inserted in the m_brkpts, even those that
1859 * were not set sucessfully. The unsuccessful breakpoints ("orphaned
1860 * breakpoints") are assigned negative ids, and they are tried to set later
1861 * when the program stops again at a breakpoint.
1863 void KDebugger::newBreakpoint(CmdQueueItem* cmd, const char* output)
1865 Breakpoint* bp = cmd->m_brkpt;
1866 assert(bp != 0);
1867 if (bp == 0)
1868 return;
1870 // if this is a new breakpoint, put it in the list
1871 bool isNew = !m_brkpts.contains(bp);
1872 if (isNew) {
1873 assert(bp->id == 0);
1874 int n = m_brkpts.size();
1875 m_brkpts.resize(n+1);
1876 m_brkpts.insert(n, bp);
1879 // parse the output to determine success or failure
1880 int id;
1881 QString file;
1882 int lineNo;
1883 QString address;
1884 if (!m_d->parseBreakpoint(output, id, file, lineNo, address))
1887 * Failure, the breakpoint could not be set. If this is a new
1888 * breakpoint, assign it a negative id. We look for the minimal id
1889 * of all breakpoints (that are already in the list) to get the new
1890 * id.
1892 if (isNew)
1894 assert(bp->id == 0);
1895 for (int i = m_brkpts.size()-2; i >= 0; i--) {
1896 if (m_brkpts[i]->id < bp->id) {
1897 bp->id = m_brkpts[i]->id;
1898 break;
1901 --bp->id;
1903 return;
1906 // The breakpoint was successfully set.
1907 if (bp->id <= 0)
1909 // this is a new or orphaned breakpoint:
1910 // set the remaining properties
1911 if (!cmd->m_brkpt->enabled) {
1912 m_d->executeCmd(DCdisable, id);
1914 if (!cmd->m_brkpt->condition.isEmpty()) {
1915 m_d->executeCmd(DCcondition, cmd->m_brkpt->condition, id);
1919 bp->id = id;
1920 bp->fileName = file;
1921 bp->lineNo = lineNo;
1922 if (!address.isEmpty())
1923 bp->address = address;
1926 void KDebugger::updateBreakList(const char* output)
1928 // get the new list
1929 QList<Breakpoint> brks;
1930 brks.setAutoDelete(false);
1931 m_d->parseBreakList(output, brks);
1933 // merge new information into existing breakpoints
1935 for (int i = m_brkpts.size()-1; i >= 0; i--) // decrement!
1937 // skip orphaned breakpoints
1938 if (m_brkpts[i]->id < 0)
1939 continue;
1941 for (Breakpoint* bp = brks.first(); bp != 0; bp = brks.next())
1943 if (bp->id == m_brkpts[i]->id) {
1944 // keep accurate location
1945 // except that xsldbg doesn't have a location in
1946 // the old breakpoint if it's just been set
1947 bp->text = m_brkpts[i]->text;
1948 if (!m_brkpts[i]->fileName.isEmpty()) {
1949 bp->fileName = m_brkpts[i]->fileName;
1950 bp->lineNo = m_brkpts[i]->lineNo;
1952 m_brkpts.insert(i, bp); // old object is deleted
1953 goto stillAlive;
1957 * If we get here, this breakpoint is no longer present.
1959 * To delete the breakpoint at i, we place the last breakpoint in
1960 * the list into the slot i. This will delete the old object at i.
1961 * Then we shorten the list by one.
1963 m_brkpts.insert(i, m_brkpts.take(m_brkpts.size()-1));
1964 m_brkpts.resize(m_brkpts.size()-1);
1965 TRACE(QString().sprintf("deleted brkpt %d, have now %d brkpts", i, m_brkpts.size()));
1967 stillAlive:;
1970 // brks may contain new breakpoints not already in m_brkpts
1971 for (const Breakpoint* bp = brks.first(); bp != 0; bp = brks.next())
1973 bool found = false;
1974 for (uint i = 0; i < m_brkpts.size(); i++) {
1975 if (bp->id == m_brkpts[i]->id) {
1976 found = true;
1977 break;
1980 if (!found){
1981 int n = m_brkpts.size();
1982 m_brkpts.resize(n+1);
1983 m_brkpts.insert(n, bp);
1987 emit breakpointsChanged();
1990 // look if there is at least one temporary breakpoint
1991 // or a watchpoint
1992 bool KDebugger::stopMayChangeBreakList() const
1994 for (int i = m_brkpts.size()-1; i >= 0; i--) {
1995 Breakpoint* bp = m_brkpts[i];
1996 if (bp->temporary || bp->type == Breakpoint::watchpoint)
1997 return true;
1999 return false;
2002 Breakpoint* KDebugger::breakpointByFilePos(QString file, int lineNo,
2003 const DbgAddr& address)
2005 // look for exact file name match
2006 int i;
2007 for (i = m_brkpts.size()-1; i >= 0; i--) {
2008 if (m_brkpts[i]->lineNo == lineNo &&
2009 m_brkpts[i]->fileName == file &&
2010 (address.isEmpty() || m_brkpts[i]->address == address))
2012 return m_brkpts[i];
2015 // not found, so try basename
2016 // strip off directory part of file name
2017 int offset = file.findRev("/");
2018 file.remove(0, offset+1);
2020 for (i = m_brkpts.size()-1; i >= 0; i--) {
2021 // get base name of breakpoint's file
2022 QString basename = m_brkpts[i]->fileName;
2023 int offset = basename.findRev("/");
2024 if (offset >= 0) {
2025 basename.remove(0, offset+1);
2028 if (m_brkpts[i]->lineNo == lineNo &&
2029 basename == file &&
2030 (address.isEmpty() || m_brkpts[i]->address == address))
2032 return m_brkpts[i];
2036 // not found
2037 return 0;
2040 Breakpoint* KDebugger::breakpointById(int id)
2042 for (int i = m_brkpts.size()-1; i >= 0; i--)
2044 if (m_brkpts[i]->id == id) {
2045 return m_brkpts[i];
2048 // not found
2049 return 0;
2052 void KDebugger::slotValuePopup(const QString& expr)
2054 // search the local variables for a match
2055 VarTree* v = m_localVariables.topLevelExprByName(expr);
2056 if (v == 0) {
2057 // not found, check watch expressions
2058 v = m_watchVariables.topLevelExprByName(expr);
2059 if (v == 0) {
2060 // try a member of 'this'
2061 v = m_localVariables.topLevelExprByName("this");
2062 if (v != 0)
2063 v = ExprWnd::ptrMemberByName(v, expr);
2064 if (v == 0) {
2065 // nothing found; do nothing
2066 return;
2071 // construct the tip
2072 QString tip = v->getText() + " = ";
2073 if (!v->value().isEmpty())
2075 tip += v->value();
2077 else
2079 // no value: we use some hint
2080 switch (v->m_varKind) {
2081 case VarTree::VKstruct:
2082 tip += "{...}";
2083 break;
2084 case VarTree::VKarray:
2085 tip += "[...]";
2086 break;
2087 default:
2088 tip += "?""?""?"; // 2 question marks in a row would be a trigraph
2089 break;
2092 emit valuePopup(tip);
2095 void KDebugger::slotDisassemble(const QString& fileName, int lineNo)
2097 if (m_haveExecutable) {
2098 CmdQueueItem* cmd = m_d->queueCmd(DCinfoline, fileName, lineNo,
2099 DebuggerDriver::QMoverrideMoreEqual);
2100 cmd->m_fileName = fileName;
2101 cmd->m_lineNo = lineNo;
2105 void KDebugger::handleInfoLine(CmdQueueItem* cmd, const char* output)
2107 QString addrFrom, addrTo;
2108 if (cmd->m_lineNo >= 0) {
2109 // disassemble
2110 if (m_d->parseInfoLine(output, addrFrom, addrTo)) {
2111 // got the address range, now get the real code
2112 CmdQueueItem* c = m_d->queueCmd(DCdisassemble, addrFrom, addrTo,
2113 DebuggerDriver::QMoverrideMoreEqual);
2114 c->m_fileName = cmd->m_fileName;
2115 c->m_lineNo = cmd->m_lineNo;
2116 } else {
2117 // no code
2118 QList<DisassembledCode> empty;
2119 emit disassembled(cmd->m_fileName, cmd->m_lineNo, empty);
2121 } else {
2122 // set program counter
2123 if (m_d->parseInfoLine(output, addrFrom, addrTo)) {
2124 // move the program counter to the start address
2125 m_d->executeCmd(DCsetpc, addrFrom);
2130 void KDebugger::handleDisassemble(CmdQueueItem* cmd, const char* output)
2132 QList<DisassembledCode> code;
2133 code.setAutoDelete(true);
2134 m_d->parseDisassemble(output, code);
2135 emit disassembled(cmd->m_fileName, cmd->m_lineNo, code);
2138 void KDebugger::handleThreadList(const char* output)
2140 QList<ThreadInfo> threads;
2141 threads.setAutoDelete(true);
2142 m_d->parseThreadList(output, threads);
2143 emit threadsChanged(threads);
2146 void KDebugger::setThread(int id)
2148 m_d->queueCmd(DCthread, id, DebuggerDriver::QMoverrideMoreEqual);
2151 void KDebugger::setMemoryExpression(const QString& memexpr)
2153 m_memoryExpression = memexpr;
2155 // queue the new expression
2156 if (!m_memoryExpression.isEmpty() &&
2157 isProgramActive() &&
2158 !isProgramRunning())
2160 queueMemoryDump(true);
2164 void KDebugger::queueMemoryDump(bool immediate)
2166 m_d->queueCmd(DCexamine, m_memoryExpression, m_memoryFormat,
2167 immediate ? DebuggerDriver::QMoverrideMoreEqual :
2168 DebuggerDriver::QMoverride);
2171 void KDebugger::handleMemoryDump(const char* output)
2173 QList<MemoryDump> memdump;
2174 memdump.setAutoDelete(true);
2175 QString msg = m_d->parseMemoryDump(output, memdump);
2176 emit memoryDumpChanged(msg, memdump);
2179 void KDebugger::setProgramCounter(const QString& file, int line, const DbgAddr& addr)
2181 if (addr.isEmpty()) {
2182 // find address of the specified line
2183 CmdQueueItem* cmd = m_d->executeCmd(DCinfoline, file, line);
2184 cmd->m_lineNo = -1; /* indicates "Set PC" UI command */
2185 } else {
2186 // move the program counter to that address
2187 m_d->executeCmd(DCsetpc, addr.asString());
2191 void KDebugger::handleSetPC(const char* /*output*/)
2193 // TODO: handle errors
2195 // now go to the top-most frame
2196 // this also modifies the program counter indicator in the UI
2197 gotoFrame(0);
2200 void KDebugger::slotValueEdited(VarTree* expr, const QString& text)
2202 if (text.simplifyWhiteSpace().isEmpty())
2203 return; /* no text entered: ignore request */
2205 ExprWnd* wnd = static_cast<ExprWnd*>(expr->listView());
2206 TRACE(QString().sprintf("Changing %s to ",
2207 wnd->name()) + text);
2209 // determine the lvalue to edit
2210 QString lvalue = expr->computeExpr();
2211 CmdQueueItem* cmd = m_d->executeCmd(DCsetvariable, lvalue, text);
2212 cmd->m_expr = expr;
2213 cmd->m_exprWnd = wnd;
2216 void KDebugger::handleSetVariable(CmdQueueItem* cmd, const char* output)
2218 QString msg = m_d->parseSetVariable(output);
2219 if (!msg.isEmpty())
2221 // there was an error; display it in the status bar
2222 m_statusMessage = msg;
2223 emit updateStatusMessage();
2224 return;
2227 // get the new value
2228 QString expr = cmd->m_expr->computeExpr();
2229 CmdQueueItem* printCmd =
2230 m_d->queueCmd(DCprint, expr, DebuggerDriver::QMoverrideMoreEqual);
2231 printCmd->m_expr = cmd->m_expr;
2232 printCmd->m_exprWnd = cmd->m_exprWnd;
2236 #include "debugger.moc"