PageRenderTime 85ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 1ms

/src/plugins/debugger/gdb/gdbengine.cpp

https://bitbucket.org/kpozn/qt-creator-py-reborn
C++ | 5439 lines | 4438 code | 429 blank | 572 comment | 902 complexity | 456d16a2f4907e74a86b1b2081e849ef MD5 | raw file
Possible License(s): LGPL-2.1
  1. /**************************************************************************
  2. **
  3. ** This file is part of Qt Creator
  4. **
  5. ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
  6. **
  7. ** Contact: Nokia Corporation (qt-info@nokia.com)
  8. **
  9. **
  10. ** GNU Lesser General Public License Usage
  11. **
  12. ** This file may be used under the terms of the GNU Lesser General Public
  13. ** License version 2.1 as published by the Free Software Foundation and
  14. ** appearing in the file LICENSE.LGPL included in the packaging of this file.
  15. ** Please review the following information to ensure the GNU Lesser General
  16. ** Public License version 2.1 requirements will be met:
  17. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  18. **
  19. ** In addition, as a special exception, Nokia gives you certain additional
  20. ** rights. These rights are described in the Nokia Qt LGPL Exception
  21. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  22. **
  23. ** Other Usage
  24. **
  25. ** Alternatively, this file may be used in accordance with the terms and
  26. ** conditions contained in a signed written agreement between you and Nokia.
  27. **
  28. ** If you have questions regarding the use of this file, please contact
  29. ** Nokia at qt-info@nokia.com.
  30. **
  31. **************************************************************************/
  32. #define QT_NO_CAST_FROM_ASCII
  33. #include "gdbengine.h"
  34. #include "debuggerstartparameters.h"
  35. #include "debuggerinternalconstants.h"
  36. #include "disassemblerlines.h"
  37. #include "attachgdbadapter.h"
  38. #include "coregdbadapter.h"
  39. #include "localplaingdbadapter.h"
  40. #include "termgdbadapter.h"
  41. #include "remotegdbserveradapter.h"
  42. #include "remoteplaingdbadapter.h"
  43. #include "codagdbadapter.h"
  44. #include "debuggeractions.h"
  45. #include "debuggerconstants.h"
  46. #include "debuggercore.h"
  47. #include "debuggerplugin.h"
  48. #include "debuggerrunner.h"
  49. #include "debuggerstringutils.h"
  50. #include "debuggertooltipmanager.h"
  51. #include "disassembleragent.h"
  52. #include "gdbmi.h"
  53. #include "gdboptionspage.h"
  54. #include "memoryagent.h"
  55. #include "watchutils.h"
  56. #include "breakhandler.h"
  57. #include "moduleshandler.h"
  58. #include "registerhandler.h"
  59. #include "snapshothandler.h"
  60. #include "sourcefileshandler.h"
  61. #include "stackhandler.h"
  62. #include "threadshandler.h"
  63. #include "watchhandler.h"
  64. #include "debuggersourcepathmappingwidget.h"
  65. #include "hostutils.h"
  66. #include "logwindow.h"
  67. #include "procinterrupt.h"
  68. #include <coreplugin/icore.h>
  69. #include <coreplugin/idocument.h>
  70. #include <extensionsystem/pluginmanager.h>
  71. #include <projectexplorer/abi.h>
  72. #include <projectexplorer/projectexplorerconstants.h>
  73. #include <projectexplorer/taskhub.h>
  74. #include <projectexplorer/itaskhandler.h>
  75. #include <texteditor/itexteditor.h>
  76. #include <utils/elfreader.h>
  77. #include <utils/qtcassert.h>
  78. #include <utils/qtcprocess.h>
  79. #include <QCoreApplication>
  80. #include <QDebug>
  81. #include <QDir>
  82. #include <QDirIterator>
  83. #include <QFileInfo>
  84. #include <QMetaObject>
  85. #include <QTime>
  86. #include <QTimer>
  87. #include <QTemporaryFile>
  88. #include <QTextStream>
  89. #include <QAction>
  90. #include <QDialogButtonBox>
  91. #include <QLabel>
  92. #include <QMainWindow>
  93. #include <QMessageBox>
  94. #include <QPushButton>
  95. #ifdef Q_OS_UNIX
  96. #include <unistd.h>
  97. #include <dlfcn.h>
  98. #endif
  99. #include <ctype.h>
  100. using namespace ProjectExplorer;
  101. using namespace Utils;
  102. namespace Debugger {
  103. namespace Internal {
  104. class GdbToolTipContext : public DebuggerToolTipContext
  105. {
  106. public:
  107. GdbToolTipContext(const DebuggerToolTipContext &c) :
  108. DebuggerToolTipContext(c), editor(0) {}
  109. QPoint mousePosition;
  110. QString expression;
  111. Core::IEditor *editor;
  112. };
  113. enum { debugPending = 0 };
  114. #define PENDING_DEBUG(s) do { if (debugPending) qDebug() << s; } while (0)
  115. #define CB(callback) &GdbEngine::callback, STRINGIFY(callback)
  116. QByteArray GdbEngine::tooltipIName(const QString &exp)
  117. {
  118. return "tooltip." + exp.toLatin1().toHex();
  119. }
  120. static bool stateAcceptsGdbCommands(DebuggerState state)
  121. {
  122. switch (state) {
  123. case EngineSetupRequested:
  124. case EngineSetupOk:
  125. case EngineSetupFailed:
  126. case InferiorUnrunnable:
  127. case InferiorSetupRequested:
  128. case InferiorSetupFailed:
  129. case EngineRunRequested:
  130. case InferiorRunRequested:
  131. case InferiorRunOk:
  132. case InferiorStopRequested:
  133. case InferiorStopOk:
  134. case InferiorShutdownRequested:
  135. case EngineShutdownRequested:
  136. case InferiorShutdownOk:
  137. case InferiorShutdownFailed:
  138. return true;
  139. case DebuggerNotReady:
  140. case InferiorStopFailed:
  141. case InferiorSetupOk:
  142. case EngineRunFailed:
  143. case InferiorExitOk:
  144. case InferiorRunFailed:
  145. case EngineShutdownOk:
  146. case EngineShutdownFailed:
  147. case DebuggerFinished:
  148. return false;
  149. }
  150. return false;
  151. }
  152. static int &currentToken()
  153. {
  154. static int token = 0;
  155. return token;
  156. }
  157. static QByteArray parsePlainConsoleStream(const GdbResponse &response)
  158. {
  159. QByteArray out = response.consoleStreamOutput;
  160. // FIXME: proper decoding needed
  161. if (out.endsWith("\\n"))
  162. out.chop(2);
  163. while (out.endsWith('\n') || out.endsWith(' '))
  164. out.chop(1);
  165. int pos = out.indexOf(" = ");
  166. return out.mid(pos + 3);
  167. }
  168. ///////////////////////////////////////////////////////////////////////
  169. //
  170. // Debuginfo Taskhandler
  171. //
  172. ///////////////////////////////////////////////////////////////////////
  173. class DebugInfoTask
  174. {
  175. public:
  176. QString command;
  177. };
  178. class DebugInfoTaskHandler : public ProjectExplorer::ITaskHandler
  179. {
  180. public:
  181. explicit DebugInfoTaskHandler(GdbEngine *engine)
  182. : m_engine(engine)
  183. {}
  184. bool canHandle(const Task &task) const
  185. {
  186. return m_debugInfoTasks.contains(task.taskId);
  187. }
  188. void handle(const Task &task)
  189. {
  190. m_engine->requestDebugInformation(m_debugInfoTasks.value(task.taskId));
  191. }
  192. void addTask(unsigned id, const DebugInfoTask &task)
  193. {
  194. m_debugInfoTasks[id] = task;
  195. }
  196. QAction *createAction(QObject *parent) const
  197. {
  198. QAction *action = new QAction(DebuggerPlugin::tr("Install &Debug Information"), parent);
  199. action->setToolTip(DebuggerPlugin::tr("This tries to install missing debug information."));
  200. return action;
  201. }
  202. private:
  203. GdbEngine *m_engine;
  204. QHash<unsigned, DebugInfoTask> m_debugInfoTasks;
  205. };
  206. ///////////////////////////////////////////////////////////////////////
  207. //
  208. // GdbEngine
  209. //
  210. ///////////////////////////////////////////////////////////////////////
  211. GdbEngine::GdbEngine(const DebuggerStartParameters &startParameters,
  212. DebuggerEngine *masterEngine)
  213. : DebuggerEngine(startParameters, CppLanguage, masterEngine)
  214. {
  215. setObjectName(_("GdbEngine"));
  216. m_busy = false;
  217. m_debuggingHelperState = DebuggingHelperUninitialized;
  218. m_gdbVersion = 100;
  219. m_gdbBuildVersion = -1;
  220. m_isMacGdb = false;
  221. m_isQnxGdb = false;
  222. m_hasBreakpointNotifications = false;
  223. m_hasPython = false;
  224. m_registerNamesListed = false;
  225. m_hasInferiorThreadList = false;
  226. m_sourcesListUpdating = false;
  227. m_oldestAcceptableToken = -1;
  228. m_nonDiscardableCount = 0;
  229. m_outputCodec = QTextCodec::codecForLocale();
  230. m_pendingBreakpointRequests = 0;
  231. m_commandsDoneCallback = 0;
  232. m_stackNeeded = false;
  233. m_preparedForQmlBreak = false;
  234. m_disassembleUsesComma = false;
  235. m_actingOnExpectedStop = false;
  236. m_fullStartDone = false;
  237. m_forceAsyncModel = false;
  238. invalidateSourcesList();
  239. m_debugInfoTaskHandler = new DebugInfoTaskHandler(this);
  240. ExtensionSystem::PluginManager::addObject(m_debugInfoTaskHandler);
  241. m_commandTimer.setSingleShot(true);
  242. connect(&m_commandTimer, SIGNAL(timeout()), SLOT(commandTimeout()));
  243. connect(debuggerCore()->action(AutoDerefPointers), SIGNAL(valueChanged(QVariant)),
  244. SLOT(reloadLocals()));
  245. connect(debuggerCore()->action(CreateFullBacktrace), SIGNAL(triggered()),
  246. SLOT(createFullBacktrace()));
  247. connect(debuggerCore()->action(UseDebuggingHelpers), SIGNAL(valueChanged(QVariant)),
  248. SLOT(reloadLocals()));
  249. connect(debuggerCore()->action(UseDynamicType), SIGNAL(valueChanged(QVariant)),
  250. SLOT(reloadLocals()));
  251. }
  252. GdbEngine::~GdbEngine()
  253. {
  254. ExtensionSystem::PluginManager::removeObject(m_debugInfoTaskHandler);
  255. delete m_debugInfoTaskHandler;
  256. m_debugInfoTaskHandler = 0;
  257. // Prevent sending error messages afterwards.
  258. disconnect();
  259. }
  260. DebuggerStartMode GdbEngine::startMode() const
  261. {
  262. return startParameters().startMode;
  263. }
  264. QString GdbEngine::errorMessage(QProcess::ProcessError error)
  265. {
  266. switch (error) {
  267. case QProcess::FailedToStart:
  268. return tr("The gdb process failed to start. Either the "
  269. "invoked program '%1' is missing, or you may have insufficient "
  270. "permissions to invoke the program.\n%2")
  271. .arg(m_gdb, gdbProc()->errorString());
  272. case QProcess::Crashed:
  273. if (targetState() == DebuggerFinished)
  274. return tr("The gdb process crashed some time after starting "
  275. "successfully.");
  276. else
  277. return tr("The gdb process was ended forcefully");
  278. case QProcess::Timedout:
  279. return tr("The last waitFor...() function timed out. "
  280. "The state of QProcess is unchanged, and you can try calling "
  281. "waitFor...() again.");
  282. case QProcess::WriteError:
  283. return tr("An error occurred when attempting to write "
  284. "to the gdb process. For example, the process may not be running, "
  285. "or it may have closed its input channel.");
  286. case QProcess::ReadError:
  287. return tr("An error occurred when attempting to read from "
  288. "the gdb process. For example, the process may not be running.");
  289. default:
  290. return tr("An unknown error in the gdb process occurred. ");
  291. }
  292. }
  293. #if 0
  294. static void dump(const char *first, const char *middle, const QString & to)
  295. {
  296. QByteArray ba(first, middle - first);
  297. Q_UNUSED(to)
  298. // note that qDebug cuts off output after a certain size... (bug?)
  299. qDebug("\n>>>>> %s\n%s\n====\n%s\n<<<<<\n",
  300. qPrintable(currentTime()),
  301. qPrintable(QString(ba).trimmed()),
  302. qPrintable(to.trimmed()));
  303. //qDebug() << "";
  304. //qDebug() << qPrintable(currentTime())
  305. // << " Reading response: " << QString(ba).trimmed() << "\n";
  306. }
  307. #endif
  308. // Parse "~:gdb: unknown target exception 0xc0000139 at 0x77bef04e\n"
  309. // and return an exception message
  310. static inline QString msgWinException(const QByteArray &data)
  311. {
  312. const int exCodePos = data.indexOf("0x");
  313. const int blankPos = exCodePos != -1 ? data.indexOf(' ', exCodePos + 1) : -1;
  314. const int addressPos = blankPos != -1 ? data.indexOf("0x", blankPos + 1) : -1;
  315. if (addressPos < 0)
  316. return GdbEngine::tr("An exception was triggered.");
  317. const unsigned exCode = data.mid(exCodePos, blankPos - exCodePos).toUInt(0, 0);
  318. const quint64 address = data.mid(addressPos).trimmed().toULongLong(0, 0);
  319. QString rc;
  320. QTextStream str(&rc);
  321. str << GdbEngine::tr("An exception was triggered: ");
  322. #ifdef Q_OS_WIN
  323. formatWindowsException(exCode, address, 0, 0, 0, str);
  324. #else
  325. Q_UNUSED(exCode)
  326. Q_UNUSED(address)
  327. #endif
  328. str << '.';
  329. return rc;
  330. }
  331. void GdbEngine::readDebugeeOutput(const QByteArray &data)
  332. {
  333. QString msg = m_outputCodec->toUnicode(data.constData(), data.length(),
  334. &m_outputCodecState);
  335. showMessage(msg, AppOutput);
  336. }
  337. static bool isNameChar(char c)
  338. {
  339. // could be 'stopped' or 'shlibs-added'
  340. return (c >= 'a' && c <= 'z') || c == '-';
  341. }
  342. static bool contains(const QByteArray &message, const char *pattern, int size)
  343. {
  344. const int s = message.size();
  345. if (s < size)
  346. return false;
  347. const int pos = message.indexOf(pattern);
  348. if (pos == -1)
  349. return false;
  350. const bool beginFits = pos == 0 || message.at(pos - 1) == '\n';
  351. const bool endFits = pos + size == s || message.at(pos + size) == '\n';
  352. return beginFits && endFits;
  353. }
  354. static bool isGdbConnectionError(const QByteArray &message)
  355. {
  356. // Handle messages gdb client produces when the target exits (gdbserver)
  357. //
  358. // we get this as response either to a specific command, e.g.
  359. // 31^error,msg="Remote connection closed"
  360. // or as informative output:
  361. // &Remote connection closed
  362. const char msg1[] = "Remote connection closed";
  363. const char msg2[] = "Remote communication error. Target disconnected.: No error.";
  364. const char msg3[] = "Quit";
  365. return contains(message, msg1, sizeof(msg1) - 1)
  366. || contains(message, msg2, sizeof(msg2) - 1)
  367. || contains(message, msg3, sizeof(msg3) - 1);
  368. }
  369. void GdbEngine::handleResponse(const QByteArray &buff)
  370. {
  371. showMessage(QString::fromLocal8Bit(buff, buff.length()), LogOutput);
  372. if (buff.isEmpty() || buff == "(gdb) ")
  373. return;
  374. const char *from = buff.constData();
  375. const char *to = from + buff.size();
  376. const char *inner;
  377. int token = -1;
  378. // Token is a sequence of numbers.
  379. for (inner = from; inner != to; ++inner)
  380. if (*inner < '0' || *inner > '9')
  381. break;
  382. if (from != inner) {
  383. token = QByteArray(from, inner - from).toInt();
  384. from = inner;
  385. }
  386. // Next char decides kind of response.
  387. const char c = *from++;
  388. switch (c) {
  389. case '*':
  390. case '+':
  391. case '=': {
  392. QByteArray asyncClass;
  393. for (; from != to; ++from) {
  394. const char c = *from;
  395. if (!isNameChar(c))
  396. break;
  397. asyncClass += *from;
  398. }
  399. GdbMi result;
  400. while (from != to) {
  401. GdbMi data;
  402. if (*from != ',') {
  403. // happens on archer where we get
  404. // 23^running <NL> *running,thread-id="all" <NL> (gdb)
  405. result.m_type = GdbMi::Tuple;
  406. break;
  407. }
  408. ++from; // skip ','
  409. data.parseResultOrValue(from, to);
  410. if (data.isValid()) {
  411. //qDebug() << "parsed result:" << data.toString();
  412. result.m_children += data;
  413. result.m_type = GdbMi::Tuple;
  414. }
  415. }
  416. if (asyncClass == "stopped") {
  417. handleStopResponse(result);
  418. m_pendingLogStreamOutput.clear();
  419. m_pendingConsoleStreamOutput.clear();
  420. } else if (asyncClass == "running") {
  421. // Archer has 'thread-id="all"' here
  422. } else if (asyncClass == "library-loaded") {
  423. // Archer has 'id="/usr/lib/libdrm.so.2",
  424. // target-name="/usr/lib/libdrm.so.2",
  425. // host-name="/usr/lib/libdrm.so.2",
  426. // symbols-loaded="0"
  427. // id="/lib/i386-linux-gnu/libc.so.6"
  428. // target-name="/lib/i386-linux-gnu/libc.so.6"
  429. // host-name="/lib/i386-linux-gnu/libc.so.6"
  430. // symbols-loaded="0",thread-group="i1"
  431. QByteArray id = result.findChild("id").data();
  432. if (!id.isEmpty())
  433. showStatusMessage(tr("Library %1 loaded").arg(_(id)), 1000);
  434. progressPing();
  435. invalidateSourcesList();
  436. Module module;
  437. module.startAddress = 0;
  438. module.endAddress = 0;
  439. module.hostPath = _(result.findChild("host-name").data());
  440. module.modulePath = _(result.findChild("target-name").data());
  441. module.moduleName = QFileInfo(module.hostPath).baseName();
  442. modulesHandler()->updateModule(module);
  443. } else if (asyncClass == "library-unloaded") {
  444. // Archer has 'id="/usr/lib/libdrm.so.2",
  445. // target-name="/usr/lib/libdrm.so.2",
  446. // host-name="/usr/lib/libdrm.so.2"
  447. QByteArray id = result.findChild("id").data();
  448. progressPing();
  449. showStatusMessage(tr("Library %1 unloaded").arg(_(id)), 1000);
  450. invalidateSourcesList();
  451. } else if (asyncClass == "thread-group-added") {
  452. // 7.1-symbianelf has "{id="i1"}"
  453. } else if (asyncClass == "thread-group-created"
  454. || asyncClass == "thread-group-started") {
  455. // Archer had only "{id="28902"}" at some point of 6.8.x.
  456. // *-started seems to be standard in 7.1, but in early
  457. // 7.0.x, there was a *-created instead.
  458. progressPing();
  459. // 7.1.50 has thread-group-started,id="i1",pid="3529"
  460. QByteArray id = result.findChild("id").data();
  461. showStatusMessage(tr("Thread group %1 created").arg(_(id)), 1000);
  462. int pid = id.toInt();
  463. if (!pid) {
  464. id = result.findChild("pid").data();
  465. pid = id.toInt();
  466. }
  467. if (pid)
  468. notifyInferiorPid(pid);
  469. handleThreadGroupCreated(result);
  470. } else if (asyncClass == "thread-created") {
  471. //"{id="1",group-id="28902"}"
  472. QByteArray id = result.findChild("id").data();
  473. showStatusMessage(tr("Thread %1 created").arg(_(id)), 1000);
  474. } else if (asyncClass == "thread-group-exited") {
  475. // Archer has "{id="28902"}"
  476. QByteArray id = result.findChild("id").data();
  477. showStatusMessage(tr("Thread group %1 exited").arg(_(id)), 1000);
  478. handleThreadGroupExited(result);
  479. } else if (asyncClass == "thread-exited") {
  480. //"{id="1",group-id="28902"}"
  481. QByteArray id = result.findChild("id").data();
  482. QByteArray groupid = result.findChild("group-id").data();
  483. showStatusMessage(tr("Thread %1 in group %2 exited")
  484. .arg(_(id)).arg(_(groupid)), 1000);
  485. } else if (asyncClass == "thread-selected") {
  486. QByteArray id = result.findChild("id").data();
  487. showStatusMessage(tr("Thread %1 selected").arg(_(id)), 1000);
  488. //"{id="2"}"
  489. } else if (m_isMacGdb && asyncClass == "shlibs-updated") {
  490. // Apple's gdb announces updated libs.
  491. invalidateSourcesList();
  492. } else if (m_isMacGdb && asyncClass == "shlibs-added") {
  493. // Apple's gdb announces added libs.
  494. // {shlib-info={num="2", name="libmathCommon.A_debug.dylib",
  495. // kind="-", dyld-addr="0x7f000", reason="dyld", requested-state="Y",
  496. // state="Y", path="/usr/lib/system/libmathCommon.A_debug.dylib",
  497. // description="/usr/lib/system/libmathCommon.A_debug.dylib",
  498. // loaded_addr="0x7f000", slide="0x7f000", prefix=""}}
  499. invalidateSourcesList();
  500. } else if (m_isMacGdb && asyncClass == "resolve-pending-breakpoint") {
  501. // Apple's gdb announces resolved breakpoints.
  502. // new_bp="1",pended_bp="1",new_expr="\"gdbengine.cpp\":1584",
  503. // bkpt={number="1",type="breakpoint",disp="keep",enabled="y",
  504. // addr="0x0000000115cc3ddf",func="foo()",file="../foo.cpp",
  505. // line="1584",shlib="/../libFoo_debug.dylib",times="0"}
  506. const GdbMi bkpt = result.findChild("bkpt");
  507. const BreakpointResponseId rid(bkpt.findChild("number").data());
  508. if (!isQmlStepBreakpoint(rid)) {
  509. BreakHandler *handler = breakHandler();
  510. BreakpointModelId id = handler->findBreakpointByResponseId(rid);
  511. BreakpointResponse br = handler->response(id);
  512. updateResponse(br, bkpt);
  513. handler->setResponse(id, br);
  514. attemptAdjustBreakpointLocation(id);
  515. }
  516. } else if (asyncClass == "breakpoint-modified") {
  517. // New in FSF gdb since 2011-04-27.
  518. // "{bkpt={number="3",type="breakpoint",disp="keep",
  519. // enabled="y",addr="<MULTIPLE>",times="1",
  520. // original-location="\\",simple_gdbtest_app.cpp\\":135"},
  521. // {number="3.1",enabled="y",addr="0x0805ff68",
  522. // func="Vector<int>::Vector(int)",
  523. // file="simple_gdbtest_app.cpp",
  524. // fullname="/data/...line="135"},{number="3.2"...}}"
  525. // Note the leading comma in original-location. Filter it out.
  526. // We don't need the field anyway.
  527. QByteArray ba = result.toString();
  528. ba = '[' + ba.mid(6, ba.size() - 7) + ']';
  529. const int pos1 = ba.indexOf(",original-location");
  530. const int pos2 = ba.indexOf("\":", pos1 + 2);
  531. const int pos3 = ba.indexOf('"', pos2 + 2);
  532. ba.remove(pos1, pos3 - pos1 + 1);
  533. result = GdbMi();
  534. result.fromString(ba);
  535. BreakHandler *handler = breakHandler();
  536. BreakpointModelId id;
  537. BreakpointResponse br;
  538. foreach (const GdbMi &bkpt, result.children()) {
  539. const QByteArray nr = bkpt.findChild("number").data();
  540. BreakpointResponseId rid(nr);
  541. if (!isHiddenBreakpoint(rid)) {
  542. if (nr.contains('.')) {
  543. // A sub-breakpoint.
  544. BreakpointResponse sub;
  545. updateResponse(sub, bkpt);
  546. sub.id = rid;
  547. sub.type = br.type;
  548. handler->insertSubBreakpoint(id, sub);
  549. } else {
  550. // A primary breakpoint.
  551. id = handler->findBreakpointByResponseId(rid);
  552. //qDebug() << "NR: " << nr << "RID: " << rid
  553. // << "ID: " << id;
  554. //BreakpointModelId id =
  555. // handler->findBreakpointByResponseId(rid);
  556. br = handler->response(id);
  557. updateResponse(br, bkpt);
  558. handler->setResponse(id, br);
  559. }
  560. }
  561. }
  562. m_hasBreakpointNotifications = true;
  563. } else if (asyncClass == "breakpoint-created") {
  564. // "{bkpt={number="1",type="breakpoint",disp="del",enabled="y",
  565. // addr="<PENDING>",pending="main",times="0",
  566. // original-location="main"}}" -- or --
  567. // {bkpt={number="2",type="hw watchpoint",disp="keep",enabled="y",
  568. // what="*0xbfffed48",times="0",original-location="*0xbfffed48"
  569. BreakHandler *handler = breakHandler();
  570. foreach (const GdbMi &bkpt, result.children()) {
  571. BreakpointResponse br;
  572. br.type = BreakpointByFileAndLine;
  573. updateResponse(br, bkpt);
  574. handler->handleAlienBreakpoint(br, this);
  575. }
  576. } else if (asyncClass == "breakpoint-deleted") {
  577. // "breakpoint-deleted" "{id="1"}"
  578. // New in FSF gdb since 2011-04-27.
  579. BreakHandler *handler = breakHandler();
  580. QByteArray nr = result.findChild("id").data();
  581. BreakpointResponseId rid(nr);
  582. BreakpointModelId id = handler->findBreakpointByResponseId(rid);
  583. if (id.isValid())
  584. handler->removeAlienBreakpoint(id);
  585. } else {
  586. qDebug() << "IGNORED ASYNC OUTPUT"
  587. << asyncClass << result.toString();
  588. }
  589. break;
  590. }
  591. case '~': {
  592. QByteArray data = GdbMi::parseCString(from, to);
  593. m_pendingConsoleStreamOutput += data;
  594. // Parse pid from noise.
  595. if (!inferiorPid()) {
  596. // Linux/Mac gdb: [New [Tt]hread 0x545 (LWP 4554)]
  597. static QRegExp re1(_("New .hread 0x[0-9a-f]+ \\(LWP ([0-9]*)\\)"));
  598. // MinGW 6.8: [New thread 2437.0x435345]
  599. static QRegExp re2(_("New .hread ([0-9]+)\\.0x[0-9a-f]*"));
  600. // Mac: [Switching to process 9294 local thread 0x2e03] or
  601. // [Switching to process 31773]
  602. static QRegExp re3(_("Switching to process ([0-9]+)"));
  603. QTC_ASSERT(re1.isValid() && re2.isValid(), return);
  604. if (re1.indexIn(_(data)) != -1)
  605. maybeHandleInferiorPidChanged(re1.cap(1));
  606. else if (re2.indexIn(_(data)) != -1)
  607. maybeHandleInferiorPidChanged(re2.cap(1));
  608. else if (re3.indexIn(_(data)) != -1)
  609. maybeHandleInferiorPidChanged(re3.cap(1));
  610. }
  611. // Show some messages to give the impression something happens.
  612. if (data.startsWith("Reading symbols from ")) {
  613. showStatusMessage(tr("Reading %1...").arg(_(data.mid(21))), 1000);
  614. progressPing();
  615. invalidateSourcesList();
  616. } else if (data.startsWith("[New ") || data.startsWith("[Thread ")) {
  617. if (data.endsWith('\n'))
  618. data.chop(1);
  619. progressPing();
  620. showStatusMessage(_(data), 1000);
  621. } else if (data.startsWith("gdb: unknown target exception 0x")) {
  622. // [Windows, most likely some DLL/Entry point not found]:
  623. // "gdb: unknown target exception 0xc0000139 at 0x77bef04e"
  624. // This may be fatal and cause the target to exit later
  625. m_lastWinException = msgWinException(data);
  626. showMessage(m_lastWinException, LogMisc);
  627. }
  628. if (data.startsWith("QMLBP:")) {
  629. int pos1 = 6;
  630. int pos2 = data.indexOf(' ', pos1);
  631. m_qmlBreakpointResponseId2 = BreakpointResponseId(data.mid(pos1, pos2 - pos1));
  632. //qDebug() << "FOUND QMLBP: " << m_qmlBreakpointNumbers[2];
  633. //qDebug() << "CURRENT: " << m_qmlBreakpointNumbers;
  634. }
  635. break;
  636. }
  637. case '@': {
  638. readDebugeeOutput(GdbMi::parseCString(from, to));
  639. break;
  640. }
  641. case '&': {
  642. QByteArray data = GdbMi::parseCString(from, to);
  643. m_pendingLogStreamOutput += data;
  644. // On Windows, the contents seem to depend on the debugger
  645. // version and/or OS version used.
  646. if (data.startsWith("warning:"))
  647. showMessage(_(data.mid(9)), AppStuff); // Cut "warning: "
  648. if (isGdbConnectionError(data)) {
  649. notifyInferiorExited();
  650. break;
  651. }
  652. // From SuSE's gdb: >&"Missing separate debuginfo for ...\n"
  653. // ">&"Try: zypper install -C \"debuginfo(build-id)=c084ee5876ed1ac12730181c9f07c3e027d8e943\"\n"
  654. if (data.startsWith("Missing separate debuginfo for ")) {
  655. m_lastMissingDebugInfo = QString::fromLocal8Bit(data.mid(32));
  656. } else if (data.startsWith("Try: zypper")) {
  657. QString cmd = QString::fromLocal8Bit(data.mid(4));
  658. Task task(Task::Warning,
  659. tr("Missing debug information for %1\nTry: %2")
  660. .arg(m_lastMissingDebugInfo).arg(cmd),
  661. FileName(), 0, Core::Id("Debuginfo"));
  662. taskHub()->addTask(task);
  663. DebugInfoTask dit;
  664. dit.command = cmd;
  665. m_debugInfoTaskHandler->addTask(task.taskId, dit);
  666. }
  667. break;
  668. }
  669. case '^': {
  670. GdbResponse response;
  671. response.token = token;
  672. for (inner = from; inner != to; ++inner)
  673. if (*inner < 'a' || *inner > 'z')
  674. break;
  675. QByteArray resultClass = QByteArray::fromRawData(from, inner - from);
  676. if (resultClass == "done") {
  677. response.resultClass = GdbResultDone;
  678. } else if (resultClass == "running") {
  679. response.resultClass = GdbResultRunning;
  680. } else if (resultClass == "connected") {
  681. response.resultClass = GdbResultConnected;
  682. } else if (resultClass == "error") {
  683. response.resultClass = GdbResultError;
  684. } else if (resultClass == "exit") {
  685. response.resultClass = GdbResultExit;
  686. } else {
  687. response.resultClass = GdbResultUnknown;
  688. }
  689. from = inner;
  690. if (from != to) {
  691. if (*from == ',') {
  692. ++from;
  693. response.data.parseTuple_helper(from, to);
  694. response.data.m_type = GdbMi::Tuple;
  695. response.data.m_name = "data";
  696. } else {
  697. // Archer has this.
  698. response.data.m_type = GdbMi::Tuple;
  699. response.data.m_name = "data";
  700. }
  701. }
  702. //qDebug() << "\nLOG STREAM:" + m_pendingLogStreamOutput;
  703. //qDebug() << "\nCONSOLE STREAM:" + m_pendingConsoleStreamOutput;
  704. response.logStreamOutput = m_pendingLogStreamOutput;
  705. response.consoleStreamOutput = m_pendingConsoleStreamOutput;
  706. m_pendingLogStreamOutput.clear();
  707. m_pendingConsoleStreamOutput.clear();
  708. handleResultRecord(&response);
  709. break;
  710. }
  711. default: {
  712. qDebug() << "UNKNOWN RESPONSE TYPE '" << c << "'. REST: " << from;
  713. break;
  714. }
  715. }
  716. }
  717. void GdbEngine::readGdbStandardError()
  718. {
  719. QByteArray err = gdbProc()->readAllStandardError();
  720. showMessage(_("UNEXPECTED GDB STDERR: " + err));
  721. if (err == "Undefined command: \"bb\". Try \"help\".\n")
  722. return;
  723. if (err.startsWith("BFD: reopening"))
  724. return;
  725. qWarning() << "Unexpected GDB stderr:" << err;
  726. }
  727. void GdbEngine::readGdbStandardOutput()
  728. {
  729. m_commandTimer.start(); // Restart timer.
  730. int newstart = 0;
  731. int scan = m_inbuffer.size();
  732. QByteArray out = gdbProc()->readAllStandardOutput();
  733. m_inbuffer.append(out);
  734. // This can trigger when a dialog starts a nested event loop.
  735. if (m_busy)
  736. return;
  737. while (newstart < m_inbuffer.size()) {
  738. int start = newstart;
  739. int end = m_inbuffer.indexOf('\n', scan);
  740. if (end < 0) {
  741. m_inbuffer.remove(0, start);
  742. return;
  743. }
  744. newstart = end + 1;
  745. scan = newstart;
  746. if (end == start)
  747. continue;
  748. if (m_inbuffer.at(end - 1) == '\r') {
  749. --end;
  750. if (end == start)
  751. continue;
  752. }
  753. m_busy = true;
  754. QByteArray ba = QByteArray::fromRawData(m_inbuffer.constData() + start, end - start);
  755. handleResponse(ba);
  756. m_busy = false;
  757. }
  758. m_inbuffer.clear();
  759. }
  760. void GdbEngine::interruptInferior()
  761. {
  762. QTC_ASSERT(state() == InferiorStopRequested,
  763. qDebug() << "INTERRUPT INFERIOR: " << state(); return);
  764. if (usesExecInterrupt()) {
  765. postCommand("-exec-interrupt", Immediate);
  766. } else {
  767. showStatusMessage(tr("Stop requested..."), 5000);
  768. showMessage(_("TRYING TO INTERRUPT INFERIOR"));
  769. interruptInferior2();
  770. }
  771. }
  772. void GdbEngine::interruptInferiorTemporarily()
  773. {
  774. foreach (const GdbCommand &cmd, m_commandsToRunOnTemporaryBreak) {
  775. if (cmd.flags & LosesChild) {
  776. notifyInferiorIll();
  777. return;
  778. }
  779. }
  780. requestInterruptInferior();
  781. }
  782. void GdbEngine::maybeHandleInferiorPidChanged(const QString &pid0)
  783. {
  784. const qint64 pid = pid0.toLongLong();
  785. if (pid == 0) {
  786. showMessage(_("Cannot parse PID from %1").arg(pid0));
  787. return;
  788. }
  789. if (pid == inferiorPid())
  790. return;
  791. showMessage(_("FOUND PID %1").arg(pid));
  792. notifyInferiorPid(pid);
  793. }
  794. void GdbEngine::postCommand(const QByteArray &command, GdbCommandCallback callback,
  795. const char *callbackName, const QVariant &cookie)
  796. {
  797. postCommand(command, NoFlags, callback, callbackName, cookie);
  798. }
  799. void GdbEngine::postCommand(const QByteArray &command, GdbCommandFlags flags,
  800. GdbCommandCallback callback, const char *callbackName,
  801. const QVariant &cookie)
  802. {
  803. GdbCommand cmd;
  804. cmd.command = command;
  805. cmd.flags = flags;
  806. cmd.callback = callback;
  807. cmd.callbackName = callbackName;
  808. cmd.cookie = cookie;
  809. postCommandHelper(cmd);
  810. }
  811. void GdbEngine::postCommandHelper(const GdbCommand &cmd)
  812. {
  813. if (!stateAcceptsGdbCommands(state())) {
  814. PENDING_DEBUG(_("NO GDB PROCESS RUNNING, CMD IGNORED: " + cmd.command));
  815. showMessage(_("NO GDB PROCESS RUNNING, CMD IGNORED: %1 %2")
  816. .arg(_(cmd.command)).arg(state()));
  817. return;
  818. }
  819. if (cmd.flags & RebuildBreakpointModel) {
  820. ++m_pendingBreakpointRequests;
  821. PENDING_DEBUG(" BRWAKPOINT MODEL:" << cmd.command << "=>" << cmd.callbackName
  822. << "INCREMENTS PENDING TO" << m_pendingBreakpointRequests);
  823. } else {
  824. PENDING_DEBUG(" OTHER (IN):" << cmd.command << "=>" << cmd.callbackName
  825. << "LEAVES PENDING WATCH AT" << m_uncompleted.size()
  826. << "LEAVES PENDING BREAKPOINT AT" << m_pendingBreakpointRequests);
  827. }
  828. if (!(cmd.flags & Discardable))
  829. ++m_nonDiscardableCount;
  830. // FIXME: clean up logic below
  831. if (cmd.flags & Immediate) {
  832. // This should always be sent.
  833. flushCommand(cmd);
  834. } else if ((cmd.flags & NeedsStop)
  835. || !m_commandsToRunOnTemporaryBreak.isEmpty()) {
  836. if (state() == InferiorStopOk || state() == InferiorUnrunnable
  837. || state() == InferiorSetupRequested || state() == EngineSetupOk
  838. || state() == InferiorShutdownRequested) {
  839. // Can be safely sent now.
  840. flushCommand(cmd);
  841. } else {
  842. // Queue the commands that we cannot send at once.
  843. showMessage(_("QUEUING COMMAND " + cmd.command));
  844. m_commandsToRunOnTemporaryBreak.append(cmd);
  845. if (state() == InferiorStopRequested) {
  846. if (cmd.flags & LosesChild) {
  847. notifyInferiorIll();
  848. }
  849. showMessage(_("CHILD ALREADY BEING INTERRUPTED. STILL HOPING."));
  850. // Calling shutdown() here breaks all situations where two
  851. // NeedsStop commands are issued in quick succession.
  852. } else if (state() == InferiorRunOk) {
  853. showStatusMessage(tr("Stopping temporarily"), 1000);
  854. interruptInferiorTemporarily();
  855. } else {
  856. qDebug() << "ATTEMPTING TO QUEUE COMMAND "
  857. << cmd.command << "IN INAPPROPRIATE STATE" << state();
  858. }
  859. }
  860. } else if (!cmd.command.isEmpty()) {
  861. flushCommand(cmd);
  862. }
  863. }
  864. void GdbEngine::flushQueuedCommands()
  865. {
  866. showStatusMessage(tr("Processing queued commands"), 1000);
  867. while (!m_commandsToRunOnTemporaryBreak.isEmpty()) {
  868. GdbCommand cmd = m_commandsToRunOnTemporaryBreak.takeFirst();
  869. showMessage(_("RUNNING QUEUED COMMAND " + cmd.command + ' '
  870. + (cmd.callbackName ? cmd.callbackName : "<unnamed callback>")));
  871. flushCommand(cmd);
  872. }
  873. }
  874. void GdbEngine::flushCommand(const GdbCommand &cmd0)
  875. {
  876. if (!stateAcceptsGdbCommands(state())) {
  877. showMessage(_(cmd0.command), LogInput);
  878. showMessage(_("GDB PROCESS ACCEPTS NO CMD IN STATE %1 ").arg(state()));
  879. return;
  880. }
  881. QTC_ASSERT(gdbProc()->state() == QProcess::Running, return);
  882. const int token = ++currentToken();
  883. GdbCommand cmd = cmd0;
  884. cmd.postTime = QTime::currentTime();
  885. m_cookieForToken[token] = cmd;
  886. if (cmd.flags & ConsoleCommand)
  887. cmd.command = "-interpreter-exec console \"" + cmd.command + '"';
  888. cmd.command = QByteArray::number(token) + cmd.command;
  889. showMessage(_(cmd.command), LogInput);
  890. if (m_scheduledTestResponses.contains(token)) {
  891. // Fake response for test cases.
  892. QByteArray buffer = m_scheduledTestResponses.value(token);
  893. buffer.replace("@TOKEN@", QByteArray::number(token));
  894. m_scheduledTestResponses.remove(token);
  895. showMessage(_("FAKING TEST RESPONSE (TOKEN: %2, RESPONSE: '%3')")
  896. .arg(token).arg(_(buffer)));
  897. QMetaObject::invokeMethod(this, "handleResponse",
  898. Q_ARG(QByteArray, buffer));
  899. } else {
  900. write(cmd.command + "\r\n");
  901. // Start Watchdog.
  902. if (m_commandTimer.interval() <= 20000)
  903. m_commandTimer.setInterval(commandTimeoutTime());
  904. // The process can die for external reason between the "-gdb-exit" was
  905. // sent and a response could be retrieved. We don't want the watchdog
  906. // to bark in that case since the only possible outcome is a dead
  907. // process anyway.
  908. if (!cmd.command.endsWith("-gdb-exit"))
  909. m_commandTimer.start();
  910. //if (cmd.flags & LosesChild)
  911. // notifyInferiorIll();
  912. }
  913. }
  914. int GdbEngine::commandTimeoutTime() const
  915. {
  916. int time = debuggerCore()->action(GdbWatchdogTimeout)->value().toInt();
  917. return 1000 * qMax(40, time);
  918. }
  919. void GdbEngine::commandTimeout()
  920. {
  921. QList<int> keys = m_cookieForToken.keys();
  922. qSort(keys);
  923. bool killIt = false;
  924. foreach (int key, keys) {
  925. const GdbCommand &cmd = m_cookieForToken.value(key);
  926. if (!(cmd.flags & NonCriticalResponse))
  927. killIt = true;
  928. QByteArray msg = QByteArray::number(key);
  929. msg += ": " + cmd.command + " => ";
  930. msg += cmd.callbackName ? cmd.callbackName : "<unnamed callback>";
  931. showMessage(_(msg));
  932. }
  933. if (killIt) {
  934. QStringList commands;
  935. foreach (const GdbCommand &cookie, m_cookieForToken)
  936. commands << QString(_("\"%1\"")).arg(
  937. QString::fromLatin1(cookie.command));
  938. showMessage(_("TIMED OUT WAITING FOR GDB REPLY. "
  939. "COMMANDS STILL IN PROGRESS: ") + commands.join(_(", ")));
  940. int timeOut = m_commandTimer.interval();
  941. //m_commandTimer.stop();
  942. const QString msg = tr("The gdb process has not responded "
  943. "to a command within %n second(s). This could mean it is stuck "
  944. "in an endless loop or taking longer than expected to perform "
  945. "the operation.\nYou can choose between waiting "
  946. "longer or abort debugging.", 0, timeOut / 1000);
  947. QMessageBox *mb = showMessageBox(QMessageBox::Critical,
  948. tr("GDB not responding"), msg,
  949. QMessageBox::Ok | QMessageBox::Cancel);
  950. mb->button(QMessageBox::Cancel)->setText(tr("Give GDB more time"));
  951. mb->button(QMessageBox::Ok)->setText(tr("Stop debugging"));
  952. if (mb->exec() == QMessageBox::Ok) {
  953. showMessage(_("KILLING DEBUGGER AS REQUESTED BY USER"));
  954. // This is an undefined state, so we just pull the emergency brake.
  955. gdbProc()->kill();
  956. } else {
  957. showMessage(_("CONTINUE DEBUGGER AS REQUESTED BY USER"));
  958. }
  959. } else {
  960. showMessage(_("\nNON-CRITICAL TIMEOUT\n"));
  961. }
  962. }
  963. void GdbEngine::handleResultRecord(GdbResponse *response)
  964. {
  965. //qDebug() << "TOKEN:" << response->token
  966. // << " ACCEPTABLE:" << m_oldestAcceptableToken;
  967. //qDebug() << "\nRESULT" << response->token << response->toString();
  968. int token = response->token;
  969. if (token == -1)
  970. return;
  971. if (!m_cookieForToken.contains(token)) {
  972. // In theory this should not happen (rather the error should be
  973. // reported in the "first" response to the command) in practice it
  974. // does. We try to handle a few situations we are aware of gracefully.
  975. // Ideally, this code should not be present at all.
  976. showMessage(_("COOKIE FOR TOKEN %1 ALREADY EATEN (%2). "
  977. "TWO RESPONSES FOR ONE COMMAND?").arg(token).
  978. arg(QString::fromLatin1(stateName(state()))));
  979. if (response->resultClass == GdbResultError) {
  980. QByteArray msg = response->data.findChild("msg").data();
  981. if (msg == "Cannot find new threads: generic error") {
  982. // Handle a case known to occur on Linux/gdb 6.8 when debugging moc
  983. // with helpers enabled. In this case we get a second response with
  984. // msg="Cannot find new threads: generic error"
  985. showMessage(_("APPLYING WORKAROUND #1"));
  986. showMessageBox(QMessageBox::Critical,
  987. tr("Executable failed"), QString::fromLocal8Bit(msg));
  988. showStatusMessage(tr("Process failed to start"));
  989. //shutdown();
  990. notifyInferiorIll();
  991. } else if (msg == "\"finish\" not meaningful in the outermost frame.") {
  992. // Handle a case known to appear on GDB 6.4 symbianelf when
  993. // the stack is cut due to access to protected memory.
  994. //showMessage(_("APPLYING WORKAROUND #2"));
  995. notifyInferiorStopOk();
  996. } else if (msg.startsWith("Cannot find bounds of current function")) {
  997. // Happens when running "-exec-next" in a function for which
  998. // there is no debug information. Divert to "-exec-next-step"
  999. showMessage(_("APPLYING WORKAROUND #3"));
  1000. notifyInferiorStopOk();
  1001. executeNextI();
  1002. } else if (msg.startsWith("Couldn't get registers: No such process.")) {
  1003. // Happens on archer-tromey-python 6.8.50.20090910-cvs
  1004. // There might to be a race between a process shutting down
  1005. // and library load messages.
  1006. showMessage(_("APPLYING WORKAROUND #4"));
  1007. notifyInferiorStopOk();
  1008. //notifyInferiorIll();
  1009. //showStatusMessage(tr("Executable failed: %1")
  1010. // .arg(QString::fromLocal8Bit(msg)));
  1011. //shutdown();
  1012. //showMessageBox(QMessageBox::Critical,
  1013. // tr("Executable failed"), QString::fromLocal8Bit(msg));
  1014. } else if (msg.contains("Cannot insert breakpoint")) {
  1015. // For breakpoints set by address to non-existent addresses we
  1016. // might get something like "6^error,msg="Warning:\nCannot insert
  1017. // breakpoint 3.\nError accessing memory address 0x34592327:
  1018. // Input/output error.\nCannot insert breakpoint 4.\nError
  1019. // accessing memory address 0x34592335: Input/output error.\n".
  1020. // This should not stop us from proceeding.
  1021. // Most notably, that happens after a "6^running" and "*running"
  1022. // We are probably sitting at _start and can't proceed as
  1023. // long as the breakpoints are enabled.
  1024. // FIXME: Should we silently disable the offending breakpoints?
  1025. showMessage(_("APPLYING WORKAROUND #5"));
  1026. showMessageBox(QMessageBox::Critical,
  1027. tr("Setting breakpoints failed"), QString::fromLocal8Bit(msg));
  1028. QTC_CHECK(state() == InferiorRunOk);
  1029. notifyInferiorSpontaneousStop();
  1030. notifyEngineIll();
  1031. } else if (isGdbConnectionError(msg)) {
  1032. notifyInferiorExited();
  1033. } else {
  1034. // Windows: Some DLL or some function not found. Report
  1035. // the exception now in a box.
  1036. if (msg.startsWith("During startup program exited with"))
  1037. notifyInferiorExited();
  1038. QString logMsg;
  1039. if (!m_lastWinException.isEmpty())
  1040. logMsg = m_lastWinException + QLatin1Char('\n');
  1041. logMsg += QString::fromLocal8Bit(msg);
  1042. showMessageBox(QMessageBox::Critical, tr("Executable Failed"), logMsg);
  1043. showStatusMessage(tr("Executable failed: %1").arg(logMsg));
  1044. }
  1045. }
  1046. return;
  1047. }
  1048. GdbCommand cmd = m_cookieForToken.take(token);
  1049. if (debuggerCore()->boolSetting(LogTimeStamps)) {
  1050. showMessage(_("Response time: %1: %2 s")
  1051. .arg(_(cmd.command))
  1052. .arg(cmd.postTime.msecsTo(QTime::currentTime()) / 1000.),
  1053. LogTime);
  1054. }
  1055. if (response->token < m_oldestAcceptableToken && (cmd.flags & Discardable)) {
  1056. //showMessage(_("### SKIPPING OLD RESULT") + response.toString());
  1057. return;
  1058. }
  1059. response->cookie = cmd.cookie;
  1060. bool isExpectedResult =
  1061. (response->resultClass == GdbResultError) // Can always happen.
  1062. || (response->resultClass == GdbResultRunning && (cmd.flags & RunRequest))
  1063. || (response->resultClass == GdbResultExit && (cmd.flags & ExitRequest))
  1064. || (response->resultClass == GdbResultDone);
  1065. // GdbResultDone can almost "always" happen. Known examples are:
  1066. // (response->resultClass == GdbResultDone && cmd.command == "continue")
  1067. // Happens with some incarnations of gdb 6.8 for "jump to line"
  1068. // (response->resultClass == GdbResultDone && cmd.command.startsWith("jump"))
  1069. // (response->resultClass == GdbResultDone && cmd.command.startsWith("detach"))
  1070. // Happens when stepping finishes very quickly and issues *stopped and ^done
  1071. // instead of ^running and *stopped
  1072. // (response->resultClass == GdbResultDone && (cmd.flags & RunRequest));
  1073. if (!isExpectedResult) {
  1074. const DebuggerStartParameters &sp = startParameters();
  1075. Abi abi = sp.toolChainAbi;
  1076. if (abi.os() == Abi::WindowsOS
  1077. && cmd.command.startsWith("attach")
  1078. && (sp.startMode == AttachExternal || sp.useTerminal))
  1079. {
  1080. // Ignore spurious 'running' responses to 'attach'.
  1081. } else {
  1082. QByteArray rsp = GdbResponse::stringFromResultClass(response->resultClass);
  1083. rsp = "UNEXPECTED RESPONSE '" + rsp + "' TO COMMAND '" + cmd.command + "'";
  1084. qWarning() << rsp << " AT " __FILE__ ":" STRINGIFY(__LINE__);
  1085. showMessage(_(rsp));
  1086. }
  1087. }
  1088. if (!(cmd.flags & Discardable))
  1089. --m_nonDiscardableCount;
  1090. if (cmd.callback)
  1091. (this->*cmd.callback)(*response);
  1092. if (cmd.flags & RebuildBreakpointModel) {
  1093. --m_pendingBreakpointRequests;
  1094. PENDING_DEBUG(" BREAKPOINT" << cmd.command << "=>" << cmd.callbackName
  1095. << "DECREMENTS PENDING TO" << m_uncompleted.size());
  1096. if (m_pendingBreakpointRequests <= 0) {
  1097. PENDING_DEBUG("\n\n ... AND TRIGGERS BREAKPOINT MODEL UPDATE\n");
  1098. attemptBreakpointSynchronization();
  1099. }
  1100. } else {
  1101. PENDING_DEBUG(" OTHER (OUT):" << cmd.command << "=>" << cmd.callbackName
  1102. << "LEAVES PENDING WATCH AT" << m_uncompleted.size()
  1103. << "LEAVES PENDING BREAKPOINT AT" << m_pendingBreakpointRequests);
  1104. }
  1105. // Commands were queued, but we were in RunningRequested state, so the interrupt
  1106. // was postponed.
  1107. // This is done after the command callbacks so the running-requesting commands
  1108. // can assert on the right state.
  1109. if (state() == InferiorRunOk && !m_commandsToRunOnTemporaryBreak.isEmpty())
  1110. interruptInferiorTemporarily();
  1111. // Continue only if there are no commands wire anymore, so this will
  1112. // be fully synchronous.
  1113. // This is somewhat inefficient, as it makes the last command synchronous.
  1114. // An optimization would be requesting the continue immediately when the
  1115. // event loop is entered, and let individual commands have a flag to suppress
  1116. // that behavior.
  1117. if (m_commandsDoneCallback && m_cookieForToken.isEmpty()) {
  1118. showMessage(_("ALL COMMANDS DONE; INVOKING CALLBACK"));
  1119. CommandsDoneCallback cont = m_commandsDoneCallback;
  1120. m_commandsDoneCallback = 0;
  1121. (this->*cont)();
  1122. } else {
  1123. PENDING_DEBUG("MISSING TOKENS: " << m_cookieForToken.keys());
  1124. }
  1125. if (m_cookieForToken.isEmpty())
  1126. m_commandTimer.stop();
  1127. }
  1128. bool GdbEngine::acceptsDebuggerCommands() const
  1129. {
  1130. return state() == InferiorStopOk
  1131. || state() == InferiorUnrunnable;
  1132. }
  1133. void GdbEngine::executeDebuggerCommand(const QString &command, DebuggerLanguages languages)
  1134. {
  1135. if (!(languages & CppLanguage))
  1136. return;
  1137. QTC_CHECK(acceptsDebuggerCommands());
  1138. GdbCommand cmd;
  1139. cmd.command = command.toLatin1();
  1140. flushCommand(cmd);
  1141. }
  1142. // This is called from CoreAdapter and AttachAdapter.
  1143. void GdbEngine::updateAll()
  1144. {
  1145. if (hasPython())
  1146. updateAllPython();
  1147. else
  1148. updateAllClassic();
  1149. }
  1150. void GdbEngine::handleQuerySources(const GdbResponse &response)
  1151. {
  1152. m_sourcesListUpdating = false;
  1153. if (response.resultClass == GdbResultDone) {
  1154. QMap<QString, QString> oldShortToFull = m_shortToFullName;
  1155. m_shortToFullName.clear();
  1156. m_fullToShortName.clear();
  1157. // "^done,files=[{file="../../../../bin/dumper/dumper.cpp",
  1158. // fullname="/data5/dev/ide/main/bin/dumper/dumper.cpp"},
  1159. GdbMi files = response.data.findChild("files");
  1160. foreach (const GdbMi &item, files.children()) {
  1161. GdbMi fileName = item.findChild("file");
  1162. if (fileName.data().endsWith("<built-in>"))
  1163. continue;
  1164. GdbMi fullName = item.findChild("fullname");
  1165. QString file = QString::fromLocal8Bit(fileName.data());
  1166. QString full;
  1167. if (fullName.isValid()) {
  1168. full = cleanupFullName(QString::fromLocal8Bit(fullName.data()));
  1169. m_fullToShortName[full] = file;
  1170. }
  1171. m_shortToFullName[file] = full;
  1172. }
  1173. if (m_shortToFullName != oldShortToFull)
  1174. sourceFilesHandler()->setSourceFiles(m_shortToFullName);
  1175. }
  1176. }
  1177. void GdbEngine::handleExecuteJumpToLine(const GdbResponse &response)
  1178. {
  1179. if (response.resultClass == GdbResultRunning) {
  1180. doNotifyInferiorRunOk();
  1181. // All is fine. Waiting for the temporary breakpoint to be hit.
  1182. } else if (response.resultClass == GdbResultDone) {
  1183. // This happens on old gdb. Trigger the effect of a '*stopped'.
  1184. showStatusMessage(tr("Jumped. Stopped"));
  1185. notifyInferiorSpontaneousStop();
  1186. handleStop2(response);
  1187. }
  1188. }
  1189. void GdbEngine::handleExecuteRunToLine(const GdbResponse &response)
  1190. {
  1191. if (response.resultClass == GdbResultRunning) {
  1192. doNotifyInferiorRunOk();
  1193. // All is fine. Waiting for the temporary breakpoint to be hit.
  1194. } else if (response.resultClass == GdbResultDone) {
  1195. // This happens on old gdb (Mac). gdb is not stopped yet,
  1196. // but merely accepted the continue.
  1197. // >&"continue\n"
  1198. // >~"Continuing.\n"
  1199. //>~"testArray () at ../simple/app.cpp:241\n"
  1200. //>~"241\t s[1] = \"b\";\n"
  1201. //>122^done
  1202. showStatusMessage(tr("Target line hit. Stopped"));
  1203. notifyInferiorRunOk();
  1204. }
  1205. }
  1206. static bool isExitedReason(const QByteArray &reason)
  1207. {
  1208. return reason == "exited-normally" // inferior exited normally
  1209. || reason == "exited-signalled" // inferior exited because of a signal
  1210. //|| reason == "signal-received" // inferior received signal
  1211. || reason == "exited"; // inferior exited
  1212. }
  1213. #if 0
  1214. void GdbEngine::handleAqcuiredInferior()
  1215. {
  1216. // Reverse debugging. FIXME: Should only be used when available.
  1217. //if (debuggerCore()->boolSetting(EnableReverseDebugging))
  1218. // postCommand("target response");
  1219. tryLoadDebuggingHelpers();
  1220. # ifndef Q_OS_MAC
  1221. // intentionally after tryLoadDebuggingHelpers(),
  1222. // otherwise we'd interrupt solib loading.
  1223. if (debuggerCore()->boolSetting(AllPluginBreakpoints)) {
  1224. postCommand("set auto-solib-add on");
  1225. postCommand("set stop-on-solib-events 0");
  1226. postCommand("sharedlibrary .*");
  1227. } else if (debuggerCore()->boolSetting(SelectedPluginBreakpoints)) {
  1228. postCommand("set auto-solib-add on");
  1229. postCommand("set stop-on-solib-events 1");
  1230. postCommand("sharedlibrary "
  1231. + theDebuggerStringSetting(SelectedPluginBreakpointsPattern));
  1232. } else if (debuggerCore()->boolSetting(NoPluginBreakpoints)) {
  1233. // should be like that already
  1234. postCommand("set auto-solib-add off");
  1235. postCommand("set stop-on-solib-events 0");
  1236. }
  1237. # endif
  1238. // It's nicer to see a bit of the world we live in.
  1239. reloadModulesInternal();
  1240. }
  1241. #endif
  1242. void GdbEngine::handleStopResponse(const GdbMi &data)
  1243. {
  1244. // This is gdb 7+'s initial *stopped in response to attach.
  1245. // For consistency, we just discard it.
  1246. m_actingOnExpectedStop = false;
  1247. if (state() == InferiorSetupRequested)
  1248. return;
  1249. if (isDying()) {
  1250. notifyInferiorStopOk();
  1251. return;
  1252. }
  1253. const QByteArray reason = data.findChild("reason").data();
  1254. if (isExitedReason(reason)) {
  1255. // // The user triggered a stop, but meanwhile the app simply exited ...
  1256. // QTC_ASSERT(state() == InferiorStopRequested
  1257. // /*|| state() == InferiorStopRequested_Kill*/,
  1258. // qDebug() << state());
  1259. QString msg;
  1260. if (reason == "exited") {
  1261. msg = tr("Application exited with exit code %1")
  1262. .arg(_(data.findChild("exit-code").toString()));
  1263. } else if (reason == "exited-signalled" || reason == "signal-received") {
  1264. msg = tr("Application exited after receiving signal %1")
  1265. .arg(_(data.findChild("signal-name").toString()));
  1266. } else {
  1267. msg = tr("Application exited normally");
  1268. }
  1269. showStatusMessage(msg);
  1270. notifyInferiorExited();
  1271. return;
  1272. }
  1273. bool gotoHandleStop1 = true;
  1274. if (!m_fullStartDone) {
  1275. m_fullStartDone = true;
  1276. postCommand("sharedlibrary .*");
  1277. loadPythonDumpers();
  1278. postCommand("p 3", CB(handleStop1));
  1279. gotoHandleStop1 = false;
  1280. }
  1281. BreakpointResponseId rid(data.findChild("bkptno").data());
  1282. const GdbMi frame = data.findChild("frame");
  1283. const int lineNumber = frame.findChild("line").data().toInt();
  1284. QString fullName = cleanupFullName(QString::fromLocal8Bit(frame.findChild("fullname").data()));
  1285. if (fullName.isEmpty())
  1286. fullName = QString::fromLocal8Bit(frame.findChild("file").data());
  1287. if (rid.isValid() && frame.isValid()
  1288. && !isQmlStepBreakpoint(rid)
  1289. && !isQFatalBreakpoint(rid)) {
  1290. // Use opportunity to update the breakpoint marker position.
  1291. BreakHandler *handler = breakHandler();
  1292. //qDebug() << " PROBLEM: " << m_qmlBreakpointNumbers << rid
  1293. // << isQmlStepBreakpoint1(rid)
  1294. // << isQmlStepBreakpoint2(rid)
  1295. BreakpointModelId id = handler->findBreakpointByResponseId(rid);
  1296. const BreakpointResponse &response = handler->response(id);
  1297. QString fileName = response.fileName;
  1298. if (fileName.isEmpty())
  1299. fileName = handler->fileName(id);
  1300. if (fileName.isEmpty())
  1301. fileName = fullName;
  1302. if (!fileName.isEmpty())
  1303. handler->setMarkerFileAndLine(id, fileName, lineNumber);
  1304. }
  1305. //qDebug() << "BP " << rid << data.toString();
  1306. // Quickly set the location marker.
  1307. if (lineNumber && !debuggerCore()->boolSetting(OperateByInstruction)
  1308. && QFileInfo(fullName).exists()
  1309. && !isQmlStepBreakpoint(rid)
  1310. && !isQFatalBreakpoint(rid))
  1311. gotoLocation(Location(fullName, lineNumber));
  1312. if (!m_commandsToRunOnTemporaryBreak.isEmpty()) {
  1313. QTC_ASSERT(state() == InferiorStopRequested, qDebug() << state());
  1314. m_actingOnExpectedStop = true;
  1315. notifyInferiorStopOk();
  1316. flushQueuedCommands();
  1317. if (state() == InferiorStopOk) {
  1318. QTC_CHECK(m_commandsDoneCallback == 0);
  1319. m_commandsDoneCallback = &GdbEngine::autoContinueInferior;
  1320. } else {
  1321. QTC_ASSERT(state() == InferiorShutdownRequested, qDebug() << state());
  1322. }
  1323. return;
  1324. }
  1325. if (state() == InferiorRunOk) {
  1326. // Stop triggered by a breakpoint or otherwise not directly
  1327. // initiated by the user.
  1328. notifyInferiorSpontaneousStop();
  1329. } else if (state() == InferiorRunRequested) {
  1330. // Stop triggered by something like "-exec-step\n"
  1331. // "&"Cannot access memory at address 0xbfffedd4\n"
  1332. // or, on S40,
  1333. // "*running,thread-id="30""
  1334. // "&"Warning:\n""
  1335. // "&"Cannot insert breakpoint -33.\n"
  1336. // "&"Error accessing memory address 0x11673fc: Input/output error.\n""
  1337. // In this case a proper response 94^error,msg="" will follow and
  1338. // be handled in the result handler.
  1339. // -- or --
  1340. // *stopped arriving earlier than ^done response to an -exec-step
  1341. doNotifyInferiorRunOk();
  1342. notifyInferiorSpontaneousStop();
  1343. } else if (state() == InferiorStopOk && isQmlStepBreakpoint2(rid)) {
  1344. // That's expected.
  1345. } else {
  1346. QTC_ASSERT(state() == InferiorStopRequested, qDebug() << state());
  1347. m_actingOnExpectedStop = true;
  1348. notifyInferiorStopOk();
  1349. }
  1350. if (isQmlStepBreakpoint1(rid))
  1351. return;
  1352. if (gotoHandleStop1)
  1353. handleStop1(data);
  1354. }
  1355. static QByteArray stopSignal(Abi abi)
  1356. {
  1357. return (abi.os() == Abi::WindowsOS) ? QByteArray("SIGTRAP") : QByteArray("SIGINT");
  1358. }
  1359. void GdbEngine::handleStop1(const GdbResponse &response)
  1360. {
  1361. handleStop1(response.cookie.value<GdbMi>());
  1362. }
  1363. void GdbEngine::handleStop1(const GdbMi &data)
  1364. {
  1365. const GdbMi frame = data.findChild("frame");
  1366. const QByteArray reason = data.findChild("reason").data();
  1367. // This was seen on XP after removing a breakpoint while running
  1368. // >945*stopped,reason="signal-received",signal-name="SIGTRAP",
  1369. // signal-meaning="Trace/breakpoint trap",thread-id="2",
  1370. // frame={addr="0x7c91120f",func="ntdll!DbgUiConnectToDbg",
  1371. // args=[],from="C:\\WINDOWS\\system32\\ntdll.dll"}
  1372. // also seen on gdb 6.8-symbianelf without qXfer:libraries:read+;
  1373. // FIXME: remote.c parses "loaded" reply. It should be turning
  1374. // that into a TARGET_WAITKIND_LOADED. Does it?
  1375. // The bandaid here has the problem that it breaks for 'next' over a
  1376. // statement that indirectly loads shared libraries
  1377. // 6.1.2010: Breaks interrupting inferiors, disabled:
  1378. // if (reason == "signal-received"
  1379. // && data.findChild("signal-name").data() == "SIGTRAP") {
  1380. // continueInferiorInternal();
  1381. // return;
  1382. // }
  1383. // Jump over well-known frames.
  1384. static int stepCounter = 0;
  1385. if (debuggerCore()->boolSetting(SkipKnownFrames)) {
  1386. if (reason == "end-stepping-range" || reason == "function-finished") {
  1387. //showMessage(frame.toString());
  1388. QString funcName = _(frame.findChild("func").data());
  1389. QString fileName = QString::fromLocal8Bit(frame.findChild("file").data());
  1390. if (isLeavableFunction(funcName, fileName)) {
  1391. //showMessage(_("LEAVING ") + funcName);
  1392. ++stepCounter;
  1393. executeStepOut();
  1394. return;
  1395. }
  1396. if (isSkippableFunction(funcName, fileName)) {
  1397. //showMessage(_("SKIPPING ") + funcName);
  1398. ++stepCounter;
  1399. executeStep();
  1400. return;
  1401. }
  1402. //if (stepCounter)
  1403. // qDebug() << "STEPCOUNTER:" << stepCounter;
  1404. stepCounter = 0;
  1405. }
  1406. }
  1407. // Show return value if possible, usually with reason "function-finished".
  1408. // *stopped,reason="function-finished",frame={addr="0x080556da",
  1409. // func="testReturnValue",args=[],file="/../app.cpp",
  1410. // fullname="/../app.cpp",line="1611"},gdb-result-var="$1",
  1411. // return-value="{d = 0x808d998}",thread-id="1",stopped-threads="all",
  1412. // core="1"
  1413. GdbMi resultVar = data.findChild("gdb-result-var");
  1414. if (resultVar.isValid())
  1415. m_resultVarName = resultVar.data();
  1416. else
  1417. m_resultVarName.clear();
  1418. bool initHelpers = m_debuggingHelperState == DebuggingHelperUninitialized
  1419. || m_debuggingHelperState == DebuggingHelperLoadTried;
  1420. // Don't load helpers on stops triggered by signals unless it's
  1421. // an intentional trap.
  1422. if (initHelpers
  1423. && dumperHandling() != DumperLoadedByGdbPreload
  1424. && reason == "signal-received") {
  1425. const QByteArray name = data.findChild("signal-name").data();
  1426. const DebuggerStartParameters &sp = startParameters();
  1427. if (name != stopSignal(sp.toolChainAbi))
  1428. initHelpers = false;
  1429. }
  1430. if (isSynchronous())
  1431. initHelpers = false;
  1432. if (initHelpers) {
  1433. tryLoadDebuggingHelpersClassic();
  1434. QVariant var = QVariant::fromValue<GdbMi>(data);
  1435. postCommand("p 4", CB(handleStop2), var); // dummy
  1436. } else {
  1437. handleStop2(data);
  1438. }
  1439. // Dumper loading is sequenced, as otherwise the display functions
  1440. // will start requesting data without knowing that dumpers are available.
  1441. }
  1442. void GdbEngine::handleStop2(const GdbResponse &response)
  1443. {
  1444. handleStop2(response.cookie.value<GdbMi>());
  1445. }
  1446. void GdbEngine::handleStop2(const GdbMi &data)
  1447. {
  1448. if (isDying()) {
  1449. qDebug() << "HANDLING STOP WHILE DYING";
  1450. notifyInferiorStopOk();
  1451. return;
  1452. }
  1453. // A user initiated stop looks like the following. Note that there is
  1454. // this extra "stopper thread" created and "properly" reported by gdb.
  1455. //
  1456. // dNOTE: INFERIOR RUN OK
  1457. // dState changed from InferiorRunRequested(10) to InferiorRunOk(11).
  1458. // >*running,thread-id="all"
  1459. // >=thread-exited,id="11",group-id="i1"
  1460. // sThread 11 in group i1 exited
  1461. // dState changed from InferiorRunOk(11) to InferiorStopRequested(13).
  1462. // dCALL: INTERRUPT INFERIOR
  1463. // sStop requested...
  1464. // dTRYING TO INTERRUPT INFERIOR
  1465. // >=thread-created,id="12",group-id="i1"
  1466. // sThread 12 created
  1467. // >~"[New Thread 8576.0x1154]\n"
  1468. // s[New Thread 8576.0x1154]
  1469. // >*running,thread-id="all"
  1470. // >~"[Switching to Thread 8576.0x1154]\n"
  1471. // >*stopped,reason="signal-received",signal-name="SIGTRAP",
  1472. // signal-meaning="Trace/breakpointtrap",frame={addr="0x7c90120f",func=
  1473. // "ntdll!DbgUiConnectToDbg",args=[],from="C:\\WINDOWS\\system32\\ntdll.dll"},
  1474. // thread-id="12",stopped-threads="all"
  1475. // dNOTE: INFERIOR STOP OK
  1476. // dState changed from InferiorStopRequested(13) to InferiorStopOk(14).
  1477. const QByteArray reason = data.findChild("reason").data();
  1478. const QByteArray func = data.findChild("frame").findChild("from").data();
  1479. const DebuggerStartParameters &sp = startParameters();
  1480. bool isStopperThread = false;
  1481. if (sp.useTerminal
  1482. && reason == "signal-received"
  1483. && data.findChild("signal-name").data() == "SIGSTOP"
  1484. && (func.endsWith("/ld-linux.so.2")
  1485. || func.endsWith("/ld-linux-x86-64.so.2")))
  1486. {
  1487. // Ignore signals from the process stub.
  1488. showMessage(_("INTERNAL CONTINUE AFTER SIGSTOP FROM STUB"), LogMisc);
  1489. continueInferiorInternal();
  1490. return;
  1491. }
  1492. if (sp.toolChainAbi.os() == Abi::WindowsOS
  1493. && sp.useTerminal
  1494. && reason == "signal-received"
  1495. && data.findChild("signal-name").data() == "SIGTRAP")
  1496. {
  1497. if (!m_actingOnExpectedStop) {
  1498. // Ignore signals from command line start up traps.
  1499. showMessage(_("INTERNAL CONTINUE AFTER SIGTRAP"), LogMisc);
  1500. continueInferiorInternal();
  1501. return;
  1502. }
  1503. // This is the stopper thread. That also means that the
  1504. // reported thread is not the one we'd like to expose
  1505. // to the user.
  1506. isStopperThread = true;
  1507. }
  1508. if (m_breakListOutdated) {
  1509. reloadBreakListInternal();
  1510. } else {
  1511. // Older gdb versions do not produce "library loaded" messages
  1512. // so the breakpoint update is not triggered.
  1513. if (m_gdbVersion < 70000 && !m_isMacGdb && breakHandler()->size() > 0)
  1514. reloadBreakListInternal();
  1515. }
  1516. if (reason == "watchpoint-trigger") {
  1517. // *stopped,reason="watchpoint-trigger",wpt={number="2",exp="*0xbfffed40"},
  1518. // value={old="1",new="0"},frame={addr="0x00451e1b",
  1519. // func="QScopedPointer",args=[{name="this",value="0xbfffed40"},
  1520. // {name="p",value="0x0"}],file="x.h",fullname="/home/.../x.h",line="95"},
  1521. // thread-id="1",stopped-threads="all",core="2"
  1522. const GdbMi wpt = data.findChild("wpt");
  1523. const BreakpointResponseId rid(wpt.findChild("number").data());
  1524. const BreakpointModelId id = breakHandler()->findBreakpointByResponseId(rid);
  1525. const quint64 bpAddress = wpt.findChild("exp").data().mid(1).toULongLong(0, 0);
  1526. QString msg;
  1527. if (id && breakHandler()->type(id) == WatchpointAtExpression)
  1528. msg = msgWatchpointByExpressionTriggered(id, rid.majorPart(),
  1529. breakHandler()->expression(id));
  1530. if (id && breakHandler()->type(id) == WatchpointAtAddress)
  1531. msg = msgWatchpointByAddressTriggered(id, rid.majorPart(), bpAddress);
  1532. GdbMi value = data.findChild("value");
  1533. GdbMi oldValue = value.findChild("old");
  1534. GdbMi newValue = value.findChild("new");
  1535. if (oldValue.isValid() && newValue.isValid()) {
  1536. msg += QLatin1Char(' ');
  1537. msg += tr("Value changed from %1 to %2.")
  1538. .arg(_(oldValue.data())).arg(_(newValue.data()));
  1539. }
  1540. showStatusMessage(msg);
  1541. } else if (reason == "breakpoint-hit") {
  1542. GdbMi gNumber = data.findChild("bkptno"); // 'number' or 'bkptno'?
  1543. if (!gNumber.isValid())
  1544. gNumber = data.findChild("number");
  1545. const BreakpointResponseId rid(gNumber.data());
  1546. const QByteArray threadId = data.findChild("thread-id").data();
  1547. const BreakpointModelId id = breakHandler()->findBreakpointByResponseId(rid);
  1548. showStatusMessage(msgBreakpointTriggered(id, rid.majorPart(), _(threadId)));
  1549. m_currentThread = threadId;
  1550. } else {
  1551. QString reasontr = msgStopped(_(reason));
  1552. if (reason == "signal-received") {
  1553. QByteArray name = data.findChild("signal-name").data();
  1554. QByteArray meaning = data.findChild("signal-meaning").data();
  1555. // Ignore these as they are showing up regularly when
  1556. // stopping debugging.
  1557. if (name == stopSignal(sp.toolChainAbi)) {
  1558. showMessage(_(name + " CONSIDERED HARMLESS. CONTINUING."));
  1559. } else {
  1560. showMessage(_("HANDLING SIGNAL " + name));
  1561. if (debuggerCore()->boolSetting(UseMessageBoxForSignals)
  1562. && !isStopperThread && !isAutoTestRunning())
  1563. showStoppedBySignalMessageBox(_(meaning), _(name));
  1564. if (!name.isEmpty() && !meaning.isEmpty())
  1565. reasontr = msgStoppedBySignal(_(meaning), _(name));
  1566. }
  1567. }
  1568. if (reason.isEmpty())
  1569. showStatusMessage(msgStopped());
  1570. else
  1571. showStatusMessage(reasontr);
  1572. }
  1573. // Let the event loop run before deciding whether to update the stack.
  1574. m_stackNeeded = true; // setTokenBarrier() might reset this.
  1575. if (isStopperThread)
  1576. m_currentThreadId = 0;
  1577. else
  1578. m_currentThreadId = data.findChild("thread-id").data().toInt();
  1579. QTimer::singleShot(0, this, SLOT(handleStop2()));
  1580. }
  1581. void GdbEngine::handleStop2()
  1582. {
  1583. // We are already continuing.
  1584. if (!m_stackNeeded)
  1585. return;
  1586. reloadStack(false); // Will trigger register reload.
  1587. if (supportsThreads()) {
  1588. if (isCodaAdapter()) {
  1589. codaReloadThreads();
  1590. } else if (m_isMacGdb || m_gdbVersion < 70100) {
  1591. postCommand("-thread-list-ids", Discardable, CB(handleThreadListIds));
  1592. } else {
  1593. // This is only available in gdb 7.1+.
  1594. postCommand("-thread-info", Discardable, CB(handleThreadInfo));
  1595. }
  1596. }
  1597. }
  1598. void GdbEngine::handleInfoProc(const GdbResponse &response)
  1599. {
  1600. if (response.resultClass == GdbResultDone) {
  1601. static QRegExp re(_("\\bprocess ([0-9]+)\n"));
  1602. QTC_ASSERT(re.isValid(), return);
  1603. if (re.indexIn(_(response.consoleStreamOutput)) != -1)
  1604. maybeHandleInferiorPidChanged(re.cap(1));
  1605. }
  1606. }
  1607. void GdbEngine::handleShowVersion(const GdbResponse &response)
  1608. {
  1609. showMessage(_("PARSING VERSION: " + response.toString()));
  1610. if (response.resultClass == GdbResultDone) {
  1611. m_gdbVersion = 100;
  1612. m_gdbBuildVersion = -1;
  1613. m_isMacGdb = false;
  1614. m_isQnxGdb = false;
  1615. QString msg = QString::fromLocal8Bit(response.consoleStreamOutput);
  1616. extractGdbVersion(msg,
  1617. &m_gdbVersion, &m_gdbBuildVersion, &m_isMacGdb, &m_isQnxGdb);
  1618. // On Mac, fsf gdb does not work sufficiently well,
  1619. // and on Linux and Windows we require at least 7.2.
  1620. // Older versions with python still work, but can
  1621. // be significantly slower.
  1622. bool isSupported = m_isMacGdb ? m_gdbVersion < 70000
  1623. : (m_gdbVersion > 70200 && m_gdbVersion < 200000);
  1624. if (isSupported)
  1625. showMessage(_("SUPPORTED GDB VERSION ") + msg);
  1626. else
  1627. showMessage(_("UNSUPPORTED GDB VERSION ") + msg);
  1628. showMessage(_("USING GDB VERSION: %1, BUILD: %2%3").arg(m_gdbVersion)
  1629. .arg(m_gdbBuildVersion).arg(_(m_isMacGdb ? " (APPLE)" : "")));
  1630. if (m_gdbVersion > 70300)
  1631. m_hasBreakpointNotifications = true;
  1632. if (usesExecInterrupt())
  1633. postCommand("set target-async on", ConsoleCommand);
  1634. else
  1635. postCommand("set target-async off", ConsoleCommand);
  1636. if (startParameters().multiProcess)
  1637. postCommand("set detach-on-fork off", ConsoleCommand);
  1638. postCommand("set build-id-verbose 2", ConsoleCommand);
  1639. }
  1640. }
  1641. void GdbEngine::handleListFeatures(const GdbResponse &response)
  1642. {
  1643. showMessage(_("FEATURES: " + response.toString()));
  1644. }
  1645. void GdbEngine::handleHasPython(const GdbResponse &response)
  1646. {
  1647. if (response.resultClass == GdbResultDone) {
  1648. m_hasPython = true;
  1649. GdbMi data;
  1650. data.fromStringMultiple(response.consoleStreamOutput);
  1651. const GdbMi dumpers = data.findChild("dumpers");
  1652. foreach (const GdbMi &dumper, dumpers.children()) {
  1653. QByteArray type = dumper.findChild("type").data();
  1654. QStringList formats(tr("Raw structure"));
  1655. foreach (const QByteArray &format,
  1656. dumper.findChild("formats").data().split(',')) {
  1657. if (format == "Normal")
  1658. formats.append(tr("Normal"));
  1659. else if (format == "Displayed")
  1660. formats.append(tr("Displayed"));
  1661. else if (!format.isEmpty())
  1662. formats.append(_(format));
  1663. }
  1664. watchHandler()->addTypeFormats(type, formats);
  1665. }
  1666. const GdbMi hasInferiorThreadList = data.findChild("hasInferiorThreadList");
  1667. m_hasInferiorThreadList = (hasInferiorThreadList.data().toInt() != 0);
  1668. } else {
  1669. pythonDumpersFailed();
  1670. }
  1671. }
  1672. void GdbEngine::pythonDumpersFailed()
  1673. {
  1674. m_hasPython = false;
  1675. const DebuggerStartParameters &sp = startParameters();
  1676. if (dumperHandling() == DumperLoadedByGdbPreload && checkDebuggingHelpersClassic()) {
  1677. QByteArray cmd = "set environment ";
  1678. if (sp.toolChainAbi.os() == Abi::MacOS)
  1679. cmd += "DYLD_INSERT_LIBRARIES";
  1680. else
  1681. cmd += "LD_PRELOAD";
  1682. cmd += ' ';
  1683. if (sp.startMode == StartRemoteGdb)
  1684. cmd += sp.remoteDumperLib;
  1685. else
  1686. cmd += qtDumperLibraryName().toLocal8Bit();
  1687. postCommand(cmd);
  1688. m_debuggingHelperState = DebuggingHelperLoadTried;
  1689. }
  1690. }
  1691. void GdbEngine::showExecutionError(const QString &message)
  1692. {
  1693. showMessageBox(QMessageBox::Critical, tr("Execution Error"),
  1694. tr("Cannot continue debugged process:\n") + message);
  1695. }
  1696. void GdbEngine::handleExecuteContinue(const GdbResponse &response)
  1697. {
  1698. QTC_ASSERT(state() == InferiorRunRequested, qDebug() << state());
  1699. if (response.resultClass == GdbResultRunning) {
  1700. doNotifyInferiorRunOk();
  1701. return;
  1702. }
  1703. QByteArray msg = response.data.findChild("msg").data();
  1704. if (msg.startsWith("Cannot find bounds of current function")) {
  1705. notifyInferiorRunFailed();
  1706. if (isDying())
  1707. return;
  1708. if (!m_commandsToRunOnTemporaryBreak.isEmpty())
  1709. flushQueuedCommands();
  1710. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  1711. showStatusMessage(tr("Stopped."), 5000);
  1712. reloadStack(true);
  1713. } else if (msg.startsWith("Cannot access memory at address")) {
  1714. // Happens on single step on ARM prolog and epilogs.
  1715. } else if (msg.startsWith("\"finish\" not meaningful in the outermost frame")) {
  1716. notifyInferiorRunFailed();
  1717. if (isDying())
  1718. return;
  1719. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  1720. // FIXME: Fix translation in master.
  1721. showStatusMessage(QString::fromLocal8Bit(msg), 5000);
  1722. gotoLocation(stackHandler()->currentFrame());
  1723. } else if (msg.startsWith("Cannot execute this command while the selected thread is running.")) {
  1724. showExecutionError(QString::fromLocal8Bit(msg));
  1725. notifyInferiorRunFailed() ;
  1726. } else {
  1727. showExecutionError(QString::fromLocal8Bit(msg));
  1728. notifyInferiorIll();
  1729. }
  1730. }
  1731. QString GdbEngine::fullName(const QString &fileName)
  1732. {
  1733. if (fileName.isEmpty())
  1734. return QString();
  1735. //QTC_ASSERT(!m_sourcesListOutdated, /* */);
  1736. QTC_ASSERT(!m_sourcesListUpdating, /* */);
  1737. return m_shortToFullName.value(fileName, QString());
  1738. }
  1739. QString GdbEngine::cleanupFullName(const QString &fileName)
  1740. {
  1741. QString cleanFilePath = fileName;
  1742. // Gdb running on windows often delivers "fullnames" which
  1743. // (a) have no drive letter and (b) are not normalized.
  1744. if (Abi::hostAbi().os() == Abi::WindowsOS) {
  1745. QTC_ASSERT(!fileName.isEmpty(), return QString());
  1746. QFileInfo fi(fileName);
  1747. if (fi.isReadable())
  1748. cleanFilePath = QDir::cleanPath(fi.absoluteFilePath());
  1749. }
  1750. if (startMode() == StartRemoteGdb) {
  1751. cleanFilePath.replace(0, startParameters().remoteMountPoint.length(),
  1752. startParameters().localMountDir);
  1753. }
  1754. if (!debuggerCore()->boolSetting(AutoEnrichParameters))
  1755. return cleanFilePath;
  1756. const QString sysroot = startParameters().sysRoot;
  1757. if (QFileInfo(cleanFilePath).isReadable())
  1758. return cleanFilePath;
  1759. if (!sysroot.isEmpty() && fileName.startsWith(QLatin1Char('/'))) {
  1760. cleanFilePath = sysroot + fileName;
  1761. if (QFileInfo(cleanFilePath).isReadable())
  1762. return cleanFilePath;
  1763. }
  1764. if (m_baseNameToFullName.isEmpty()) {
  1765. QString debugSource = sysroot + QLatin1String("/usr/src/debug");
  1766. if (QFileInfo(debugSource).isDir()) {
  1767. QDirIterator it(debugSource, QDirIterator::Subdirectories);
  1768. while (it.hasNext()) {
  1769. it.next();
  1770. QString name = it.fileName();
  1771. if (!name.startsWith(QLatin1Char('.'))) {
  1772. QString path = it.filePath();
  1773. m_baseNameToFullName.insert(name, path);
  1774. }
  1775. }
  1776. }
  1777. }
  1778. cleanFilePath.clear();
  1779. const QString base = QFileInfo(fileName).fileName();
  1780. QMap<QString, QString>::const_iterator jt = m_baseNameToFullName.find(base);
  1781. while (jt != m_baseNameToFullName.end() && jt.key() == base) {
  1782. // FIXME: Use some heuristics to find the "best" match.
  1783. return jt.value();
  1784. //++jt;
  1785. }
  1786. return cleanFilePath;
  1787. }
  1788. void GdbEngine::shutdownInferior()
  1789. {
  1790. QTC_ASSERT(state() == InferiorShutdownRequested, qDebug() << state());
  1791. m_commandsToRunOnTemporaryBreak.clear();
  1792. switch (startParameters().closeMode) {
  1793. case KillAtClose:
  1794. postCommand("kill", NeedsStop | LosesChild, CB(handleInferiorShutdown));
  1795. return;
  1796. case DetachAtClose:
  1797. postCommand("detach", NeedsStop | LosesChild, CB(handleInferiorShutdown));
  1798. return;
  1799. }
  1800. QTC_ASSERT(false, notifyInferiorShutdownFailed());
  1801. }
  1802. void GdbEngine::handleInferiorShutdown(const GdbResponse &response)
  1803. {
  1804. QTC_ASSERT(state() == InferiorShutdownRequested, qDebug() << state());
  1805. if (response.resultClass == GdbResultDone) {
  1806. notifyInferiorShutdownOk();
  1807. return;
  1808. }
  1809. QByteArray ba = response.data.findChild("msg").data();
  1810. if (ba.contains(": No such file or directory.")) {
  1811. // This happens when someone removed the binary behind our back.
  1812. // It is not really an error from a user's point of view.
  1813. showMessage(_("NOTE: " + ba));
  1814. notifyInferiorShutdownOk();
  1815. return;
  1816. }
  1817. showMessageBox(QMessageBox::Critical,
  1818. tr("Failed to shut down application"),
  1819. msgInferiorStopFailed(QString::fromLocal8Bit(ba)));
  1820. notifyInferiorShutdownFailed();
  1821. }
  1822. void GdbEngine::notifyAdapterShutdownFailed()
  1823. {
  1824. showMessage(_("ADAPTER SHUTDOWN FAILED"));
  1825. QTC_ASSERT(state() == EngineShutdownRequested, qDebug() << state());
  1826. notifyEngineShutdownFailed();
  1827. }
  1828. void GdbEngine::notifyAdapterShutdownOk()
  1829. {
  1830. QTC_ASSERT(state() == EngineShutdownRequested, qDebug() << state());
  1831. showMessage(_("INITIATE GDBENGINE SHUTDOWN IN STATE %1, PROC: %2")
  1832. .arg(lastGoodState()).arg(gdbProc()->state()));
  1833. m_commandsDoneCallback = 0;
  1834. switch (gdbProc()->state()) {
  1835. case QProcess::Running:
  1836. postCommand("-gdb-exit", GdbEngine::ExitRequest, CB(handleGdbExit));
  1837. break;
  1838. case QProcess::NotRunning:
  1839. // Cannot find executable.
  1840. notifyEngineShutdownOk();
  1841. break;
  1842. case QProcess::Starting:
  1843. showMessage(_("GDB NOT REALLY RUNNING; KILLING IT"));
  1844. gdbProc()->kill();
  1845. notifyEngineShutdownFailed();
  1846. break;
  1847. }
  1848. }
  1849. void GdbEngine::handleGdbExit(const GdbResponse &response)
  1850. {
  1851. if (response.resultClass == GdbResultExit) {
  1852. showMessage(_("GDB CLAIMS EXIT; WAITING"));
  1853. // Don't set state here, this will be handled in handleGdbFinished()
  1854. //notifyEngineShutdownOk();
  1855. } else {
  1856. QString msg = msgGdbStopFailed(
  1857. QString::fromLocal8Bit(response.data.findChild("msg").data()));
  1858. qDebug() << (_("GDB WON'T EXIT (%1); KILLING IT").arg(msg));
  1859. showMessage(_("GDB WON'T EXIT (%1); KILLING IT").arg(msg));
  1860. gdbProc()->kill();
  1861. }
  1862. }
  1863. void GdbEngine::detachDebugger()
  1864. {
  1865. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  1866. QTC_ASSERT(startMode() != AttachCore, qDebug() << startMode());
  1867. postCommand("detach", GdbEngine::ExitRequest, CB(handleDetach));
  1868. }
  1869. void GdbEngine::handleDetach(const GdbResponse &response)
  1870. {
  1871. Q_UNUSED(response);
  1872. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  1873. notifyInferiorExited();
  1874. }
  1875. void GdbEngine::handleThreadGroupCreated(const GdbMi &result)
  1876. {
  1877. QByteArray id = result.findChild("id").data();
  1878. QByteArray pid = result.findChild("pid").data();
  1879. Q_UNUSED(id);
  1880. Q_UNUSED(pid);
  1881. }
  1882. void GdbEngine::handleThreadGroupExited(const GdbMi &result)
  1883. {
  1884. QByteArray id = result.findChild("id").data();
  1885. }
  1886. int GdbEngine::currentFrame() const
  1887. {
  1888. return stackHandler()->currentIndex();
  1889. }
  1890. static QString msgNoGdbBinaryForToolChain(const Abi &tc)
  1891. {
  1892. return GdbEngine::tr("There is no gdb binary available for binaries in format '%1'")
  1893. .arg(tc.toString());
  1894. }
  1895. bool GdbEngine::hasCapability(unsigned cap) const
  1896. {
  1897. if (cap & (ReverseSteppingCapability
  1898. | AutoDerefPointersCapability
  1899. | DisassemblerCapability
  1900. | RegisterCapability
  1901. | ShowMemoryCapability
  1902. | JumpToLineCapability
  1903. | ReloadModuleCapability
  1904. | ReloadModuleSymbolsCapability
  1905. | BreakOnThrowAndCatchCapability
  1906. | BreakConditionCapability
  1907. | TracePointCapability
  1908. | ReturnFromFunctionCapability
  1909. | CreateFullBacktraceCapability
  1910. | WatchpointByAddressCapability
  1911. | WatchpointByExpressionCapability
  1912. | AddWatcherCapability
  1913. | WatchWidgetsCapability
  1914. | ShowModuleSymbolsCapability
  1915. | CatchCapability
  1916. | OperateByInstructionCapability
  1917. | RunToLineCapability
  1918. | MemoryAddressCapability))
  1919. return true;
  1920. if (startParameters().startMode == AttachCore)
  1921. return false;
  1922. // FIXME: Remove in case we have gdb 7.x on Mac.
  1923. if (startParameters().toolChainAbi.os() == Abi::MacOS)
  1924. return false;
  1925. return cap == SnapshotCapability;
  1926. }
  1927. void GdbEngine::continueInferiorInternal()
  1928. {
  1929. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  1930. notifyInferiorRunRequested();
  1931. showStatusMessage(tr("Running requested..."), 5000);
  1932. QTC_ASSERT(state() == InferiorRunRequested, qDebug() << state());
  1933. postCommand("-exec-continue", RunRequest, CB(handleExecuteContinue));
  1934. }
  1935. void GdbEngine::doNotifyInferiorRunOk()
  1936. {
  1937. clearToolTip();
  1938. notifyInferiorRunOk();
  1939. }
  1940. void GdbEngine::autoContinueInferior()
  1941. {
  1942. resetLocation();
  1943. continueInferiorInternal();
  1944. showStatusMessage(tr("Continuing after temporary stop..."), 1000);
  1945. }
  1946. void GdbEngine::continueInferior()
  1947. {
  1948. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  1949. setTokenBarrier();
  1950. continueInferiorInternal();
  1951. }
  1952. void GdbEngine::executeStep()
  1953. {
  1954. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  1955. setTokenBarrier();
  1956. notifyInferiorRunRequested();
  1957. showStatusMessage(tr("Step requested..."), 5000);
  1958. if (isCodaAdapter() && stackHandler()->stackSize() > 0)
  1959. postCommand("sal step,0x" + QByteArray::number(stackHandler()->topAddress(), 16));
  1960. if (isReverseDebugging()) {
  1961. postCommand("reverse-step", RunRequest, CB(handleExecuteStep));
  1962. } else {
  1963. postCommand("-exec-step", RunRequest, CB(handleExecuteStep));
  1964. }
  1965. }
  1966. void GdbEngine::handleExecuteStep(const GdbResponse &response)
  1967. {
  1968. if (response.resultClass == GdbResultDone) {
  1969. // Step was finishing too quick, and a '*stopped' messages should
  1970. // have preceded it, so just ignore this result.
  1971. QTC_CHECK(state() == InferiorStopOk);
  1972. return;
  1973. }
  1974. QTC_ASSERT(state() == InferiorRunRequested, qDebug() << state());
  1975. if (response.resultClass == GdbResultRunning) {
  1976. doNotifyInferiorRunOk();
  1977. return;
  1978. }
  1979. QByteArray msg = response.data.findChild("msg").data();
  1980. if (msg.startsWith("Cannot find bounds of current function")
  1981. || msg.contains("Error accessing memory address")
  1982. || msg.startsWith("Cannot access memory at address")) {
  1983. // On S40: "40^error,msg="Warning:\nCannot insert breakpoint -39.\n"
  1984. //" Error accessing memory address 0x11673fc: Input/output error.\n"
  1985. notifyInferiorRunFailed();
  1986. if (isDying())
  1987. return;
  1988. if (!m_commandsToRunOnTemporaryBreak.isEmpty())
  1989. flushQueuedCommands();
  1990. executeStepI(); // Fall back to instruction-wise stepping.
  1991. } else if (msg.startsWith("Cannot execute this command while the selected thread is running.")) {
  1992. showExecutionError(QString::fromLocal8Bit(msg));
  1993. notifyInferiorRunFailed();
  1994. } else if (msg.startsWith("warning: SuspendThread failed")) {
  1995. // On Win: would lead to "PC register is not available" or "\312"
  1996. continueInferiorInternal();
  1997. } else {
  1998. showExecutionError(QString::fromLocal8Bit(msg));
  1999. notifyInferiorIll();
  2000. }
  2001. }
  2002. void GdbEngine::executeStepI()
  2003. {
  2004. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  2005. setTokenBarrier();
  2006. notifyInferiorRunRequested();
  2007. showStatusMessage(tr("Step by instruction requested..."), 5000);
  2008. if (isReverseDebugging())
  2009. postCommand("reverse-stepi", RunRequest, CB(handleExecuteContinue));
  2010. else
  2011. postCommand("-exec-step-instruction", RunRequest, CB(handleExecuteContinue));
  2012. }
  2013. void GdbEngine::executeStepOut()
  2014. {
  2015. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  2016. postCommand("-stack-select-frame 0", Discardable);
  2017. setTokenBarrier();
  2018. notifyInferiorRunRequested();
  2019. showStatusMessage(tr("Finish function requested..."), 5000);
  2020. postCommand("-exec-finish", RunRequest, CB(handleExecuteContinue));
  2021. }
  2022. void GdbEngine::executeNext()
  2023. {
  2024. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  2025. setTokenBarrier();
  2026. notifyInferiorRunRequested();
  2027. showStatusMessage(tr("Step next requested..."), 5000);
  2028. if (isCodaAdapter() && stackHandler()->stackSize() > 0)
  2029. postCommand("sal next,0x" + QByteArray::number(stackHandler()->topAddress(), 16));
  2030. if (isReverseDebugging()) {
  2031. postCommand("reverse-next", RunRequest, CB(handleExecuteNext));
  2032. } else {
  2033. scheduleTestResponse(TestNoBoundsOfCurrentFunction,
  2034. "@TOKEN@^error,msg=\"Warning:\\nCannot insert breakpoint -39.\\n"
  2035. " Error accessing memory address 0x11673fc: Input/output error.\\n\"");
  2036. postCommand("-exec-next", RunRequest, CB(handleExecuteNext));
  2037. }
  2038. }
  2039. void GdbEngine::handleExecuteNext(const GdbResponse &response)
  2040. {
  2041. if (response.resultClass == GdbResultDone) {
  2042. // Step was finishing too quick, and a '*stopped' messages should
  2043. // have preceded it, so just ignore this result.
  2044. QTC_CHECK(state() == InferiorStopOk);
  2045. return;
  2046. }
  2047. QTC_ASSERT(state() == InferiorRunRequested, qDebug() << state());
  2048. if (response.resultClass == GdbResultRunning) {
  2049. doNotifyInferiorRunOk();
  2050. return;
  2051. }
  2052. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  2053. QByteArray msg = response.data.findChild("msg").data();
  2054. if (msg.startsWith("Cannot find bounds of current function")
  2055. || msg.contains("Error accessing memory address ")) {
  2056. if (!m_commandsToRunOnTemporaryBreak.isEmpty())
  2057. flushQueuedCommands();
  2058. notifyInferiorRunFailed();
  2059. if (!isDying())
  2060. executeNextI(); // Fall back to instruction-wise stepping.
  2061. } else if (msg.startsWith("Cannot execute this command while the selected thread is running.")) {
  2062. showExecutionError(QString::fromLocal8Bit(msg));
  2063. notifyInferiorRunFailed();
  2064. } else {
  2065. showMessageBox(QMessageBox::Critical, tr("Execution Error"),
  2066. tr("Cannot continue debugged process:\n") + QString::fromLocal8Bit(msg));
  2067. notifyInferiorIll();
  2068. }
  2069. }
  2070. void GdbEngine::executeNextI()
  2071. {
  2072. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  2073. setTokenBarrier();
  2074. notifyInferiorRunRequested();
  2075. showStatusMessage(tr("Step next instruction requested..."), 5000);
  2076. if (isReverseDebugging())
  2077. postCommand("reverse-nexti", RunRequest, CB(handleExecuteContinue));
  2078. else
  2079. postCommand("-exec-next-instruction", RunRequest, CB(handleExecuteContinue));
  2080. }
  2081. static QByteArray addressSpec(quint64 address)
  2082. {
  2083. return "*0x" + QByteArray::number(address, 16);
  2084. }
  2085. void GdbEngine::executeRunToLine(const ContextData &data)
  2086. {
  2087. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  2088. setTokenBarrier();
  2089. resetLocation();
  2090. notifyInferiorRunRequested();
  2091. showStatusMessage(tr("Run to line %1 requested...").arg(data.lineNumber), 5000);
  2092. #if 1
  2093. QByteArray loc;
  2094. if (m_isMacGdb) {
  2095. if (data.address)
  2096. loc = addressSpec(data.address);
  2097. else
  2098. loc = "\"\\\"" + breakLocation(data.fileName).toLocal8Bit() + "\\\":"
  2099. + QByteArray::number(data.lineNumber) + '"';
  2100. // "tbreak/continue" does _not_ work on Mac. See #4619
  2101. postCommand("-break-insert -t -l -1 -f " + loc);
  2102. postCommand("-exec-continue", RunRequest, CB(handleExecuteRunToLine));
  2103. } else {
  2104. if (data.address)
  2105. loc = addressSpec(data.address);
  2106. else
  2107. loc = '"' + breakLocation(data.fileName).toLocal8Bit() + '"' + ':'
  2108. + QByteArray::number(data.lineNumber);
  2109. postCommand("tbreak " + loc);
  2110. postCommand("continue", RunRequest, CB(handleExecuteRunToLine));
  2111. }
  2112. #else
  2113. // Seems to jump to unpredicatable places. Observed in the manual
  2114. // tests in the Foo::Foo() constructor with both gdb 6.8 and 7.1.
  2115. QByteArray args = '"' + breakLocation(fileName).toLocal8Bit() + '"' + ':'
  2116. + QByteArray::number(lineNumber);
  2117. postCommand("-exec-until " + args, RunRequest, CB(handleExecuteContinue));
  2118. #endif
  2119. }
  2120. void GdbEngine::executeRunToFunction(const QString &functionName)
  2121. {
  2122. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  2123. setTokenBarrier();
  2124. resetLocation();
  2125. postCommand("-break-insert -t " + functionName.toLatin1());
  2126. showStatusMessage(tr("Run to function %1 requested...").arg(functionName), 5000);
  2127. continueInferiorInternal();
  2128. }
  2129. void GdbEngine::executeJumpToLine(const ContextData &data)
  2130. {
  2131. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  2132. QByteArray loc;
  2133. if (data.address)
  2134. loc = addressSpec(data.address);
  2135. else
  2136. loc = '"' + breakLocation(data.fileName).toLocal8Bit() + '"' + ':'
  2137. + QByteArray::number(data.lineNumber);
  2138. postCommand("tbreak " + loc);
  2139. notifyInferiorRunRequested();
  2140. postCommand("jump " + loc, RunRequest, CB(handleExecuteJumpToLine));
  2141. // will produce something like
  2142. // &"jump \"/home/apoenitz/dev/work/test1/test1.cpp\":242"
  2143. // ~"Continuing at 0x4058f3."
  2144. // ~"run1 (argc=1, argv=0x7fffbf1f5538) at test1.cpp:242"
  2145. // ~"242\t x *= 2;"
  2146. // 23^done"
  2147. }
  2148. void GdbEngine::executeReturn()
  2149. {
  2150. QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
  2151. setTokenBarrier();
  2152. notifyInferiorRunRequested();
  2153. showStatusMessage(tr("Immediate return from function requested..."), 5000);
  2154. postCommand("-exec-finish", RunRequest, CB(handleExecuteReturn));
  2155. }
  2156. void GdbEngine::handleExecuteReturn(const GdbResponse &response)
  2157. {
  2158. if (response.resultClass == GdbResultDone) {
  2159. notifyInferiorStopOk();
  2160. updateAll();
  2161. return;
  2162. }
  2163. notifyInferiorRunFailed();
  2164. }
  2165. /*!
  2166. \fn void Debugger::Internal::GdbEngine::setTokenBarrier()
  2167. \brief Discard the results of all pending watch-updating commands.
  2168. This method is called at the beginning of all step/next/finish etc.
  2169. debugger functions.
  2170. If non-watch-updating commands with call-backs are still in the pipe,
  2171. it will complain.
  2172. */
  2173. void GdbEngine::setTokenBarrier()
  2174. {
  2175. //QTC_ASSERT(m_nonDiscardableCount == 0, /**/);
  2176. bool good = true;
  2177. QHashIterator<int, GdbCommand> it(m_cookieForToken);
  2178. while (it.hasNext()) {
  2179. it.next();
  2180. if (!(it.value().flags & Discardable)) {
  2181. qDebug() << "TOKEN: " << it.key()
  2182. << "CMD:" << it.value().command
  2183. << " FLAGS:" << it.value().flags
  2184. << " CALLBACK:" << it.value().callbackName;
  2185. good = false;
  2186. }
  2187. }
  2188. QTC_ASSERT(good, return);
  2189. PENDING_DEBUG("\n--- token barrier ---\n");
  2190. showMessage(_("--- token barrier ---"), LogMiscInput);
  2191. if (debuggerCore()->boolSetting(LogTimeStamps))
  2192. showMessage(LogWindow::logTimeStamp(), LogMiscInput);
  2193. m_oldestAcceptableToken = currentToken();
  2194. m_stackNeeded = false;
  2195. }
  2196. //////////////////////////////////////////////////////////////////////
  2197. //
  2198. // Breakpoint specific stuff
  2199. //
  2200. //////////////////////////////////////////////////////////////////////
  2201. void GdbEngine::updateResponse(BreakpointResponse &response, const GdbMi &bkpt)
  2202. {
  2203. QTC_ASSERT(bkpt.isValid(), return);
  2204. QByteArray originalLocation;
  2205. response.multiple = false;
  2206. response.enabled = true;
  2207. response.pending = false;
  2208. response.condition.clear();
  2209. QByteArray file, fullName;
  2210. foreach (const GdbMi &child, bkpt.children()) {
  2211. if (child.hasName("number")) {
  2212. response.id = BreakpointResponseId(child.data());
  2213. } else if (child.hasName("func")) {
  2214. response.functionName = _(child.data());
  2215. } else if (child.hasName("addr")) {
  2216. // <MULTIPLE> happens in constructors, inline functions, and
  2217. // at other places like 'foreach' lines. In this case there are
  2218. // fields named "addr" in the response and/or the address
  2219. // is called <MULTIPLE>.
  2220. //qDebug() << "ADDR: " << child.data() << (child.data() == "<MULTIPLE>");
  2221. if (child.data() == "<MULTIPLE>")
  2222. response.multiple = true;
  2223. if (child.data().startsWith("0x"))
  2224. response.address = child.toAddress();
  2225. } else if (child.hasName("file")) {
  2226. file = child.data();
  2227. } else if (child.hasName("fullname")) {
  2228. fullName = child.data();
  2229. } else if (child.hasName("line")) {
  2230. // The line numbers here are the uncorrected ones. So don't
  2231. // change it if we know better already.
  2232. if (response.correctedLineNumber == 0)
  2233. response.lineNumber = child.data().toInt();
  2234. } else if (child.hasName("cond")) {
  2235. // gdb 6.3 likes to "rewrite" conditions. Just accept that fact.
  2236. response.condition = child.data();
  2237. } else if (child.hasName("enabled")) {
  2238. response.enabled = (child.data() == "y");
  2239. } else if (child.hasName("pending")) {
  2240. // Any content here would be interesting only if we did accept
  2241. // spontaneously appearing breakpoints (user using gdb commands).
  2242. response.pending = true;
  2243. } else if (child.hasName("at")) {
  2244. // Happens with gdb 6.4 symbianelf.
  2245. QByteArray ba = child.data();
  2246. if (ba.startsWith('<') && ba.endsWith('>'))
  2247. ba = ba.mid(1, ba.size() - 2);
  2248. response.functionName = _(ba);
  2249. } else if (child.hasName("thread")) {
  2250. response.threadSpec = child.data().toInt();
  2251. } else if (child.hasName("type")) {
  2252. // "breakpoint", "hw breakpoint", "tracepoint", "hw watchpoint"
  2253. // {bkpt={number="2",type="hw watchpoint",disp="keep",enabled="y",
  2254. // what="*0xbfffed48",times="0",original-location="*0xbfffed48"
  2255. if (child.data().contains("tracepoint")) {
  2256. response.tracepoint = true;
  2257. } else if (child.data() == "hw watchpoint" || child.data() == "watchpoint") {
  2258. QByteArray what = bkpt.findChild("what").data();
  2259. if (what.startsWith("*0x")) {
  2260. response.type = WatchpointAtAddress;
  2261. response.address = what.mid(1).toULongLong(0, 0);
  2262. } else {
  2263. response.type = WatchpointAtExpression;
  2264. response.expression = QString::fromLocal8Bit(what);
  2265. }
  2266. }
  2267. } else if (child.hasName("original-location")) {
  2268. originalLocation = child.data();
  2269. }
  2270. // This field is not present. Contents needs to be parsed from
  2271. // the plain "ignore" response.
  2272. //else if (child.hasName("ignore"))
  2273. // response.ignoreCount = child.data();
  2274. }
  2275. QString name;
  2276. if (!fullName.isEmpty()) {
  2277. name = cleanupFullName(QFile::decodeName(fullName));
  2278. response.fileName = name;
  2279. //if (data->markerFileName().isEmpty())
  2280. // data->setMarkerFileName(name);
  2281. } else {
  2282. name = QFile::decodeName(file);
  2283. // Use fullName() once we have a mapping which is more complete than
  2284. // gdb's own. No point in assigning markerFileName for now.
  2285. }
  2286. if (!name.isEmpty())
  2287. response.fileName = name;
  2288. if (response.fileName.isEmpty())
  2289. response.updateLocation(originalLocation);
  2290. }
  2291. QString GdbEngine::breakLocation(const QString &file) const
  2292. {
  2293. //QTC_CHECK(!m_breakListOutdated);
  2294. QString where = m_fullToShortName.value(file);
  2295. if (where.isEmpty())
  2296. return QFileInfo(file).fileName();
  2297. return where;
  2298. }
  2299. QByteArray GdbEngine::breakpointLocation(BreakpointModelId id)
  2300. {
  2301. BreakHandler *handler = breakHandler();
  2302. const BreakpointParameters &data = handler->breakpointData(id);
  2303. QTC_ASSERT(data.type != UnknownType, return QByteArray());
  2304. // FIXME: Non-GCC-runtime
  2305. if (data.type == BreakpointAtThrow)
  2306. return "__cxa_throw";
  2307. if (data.type == BreakpointAtCatch)
  2308. return "__cxa_begin_catch";
  2309. if (data.type == BreakpointAtMain) {
  2310. const Abi abi = startParameters().toolChainAbi;
  2311. return (abi.os() == Abi::WindowsOS) ? "qMain" : "main";
  2312. }
  2313. if (data.type == BreakpointByFunction)
  2314. return '"' + data.functionName.toUtf8() + '"';
  2315. if (data.type == BreakpointByAddress)
  2316. return addressSpec(data.address);
  2317. const QString fileName = data.pathUsage == BreakpointUseFullPath
  2318. ? data.fileName : breakLocation(data.fileName);
  2319. // The argument is simply a C-quoted version of the argument to the
  2320. // non-MI "break" command, including the "original" quoting it wants.
  2321. return "\"\\\"" + GdbMi::escapeCString(fileName).toLocal8Bit() + "\\\":"
  2322. + QByteArray::number(data.lineNumber) + '"';
  2323. }
  2324. QByteArray GdbEngine::breakpointLocation2(BreakpointModelId id)
  2325. {
  2326. BreakHandler *handler = breakHandler();
  2327. const BreakpointParameters &data = handler->breakpointData(id);
  2328. const QString fileName = data.pathUsage == BreakpointUseFullPath
  2329. ? data.fileName : breakLocation(data.fileName);
  2330. return GdbMi::escapeCString(fileName).toLocal8Bit() + ':'
  2331. + QByteArray::number(data.lineNumber);
  2332. }
  2333. void GdbEngine::handleWatchInsert(const GdbResponse &response)
  2334. {
  2335. BreakpointModelId id = response.cookie.value<BreakpointModelId>();
  2336. if (response.resultClass == GdbResultDone) {
  2337. BreakHandler *handler = breakHandler();
  2338. BreakpointResponse br = handler->response(id);
  2339. // "Hardware watchpoint 2: *0xbfffed40\n"
  2340. QByteArray ba = response.consoleStreamOutput;
  2341. GdbMi wpt = response.data.findChild("wpt");
  2342. if (wpt.isValid()) {
  2343. // Mac yields:
  2344. //>32^done,wpt={number="4",exp="*4355182176"}
  2345. br.id = BreakpointResponseId(wpt.findChild("number").data());
  2346. QByteArray exp = wpt.findChild("exp").data();
  2347. if (exp.startsWith('*'))
  2348. br.address = exp.mid(1).toULongLong(0, 0);
  2349. handler->setResponse(id, br);
  2350. QTC_CHECK(!handler->needsChange(id));
  2351. handler->notifyBreakpointInsertOk(id);
  2352. } else if (ba.startsWith("Hardware watchpoint ")
  2353. || ba.startsWith("Watchpoint ")) {
  2354. // Non-Mac: "Hardware watchpoint 2: *0xbfffed40\n"
  2355. const int end = ba.indexOf(':');
  2356. const int begin = ba.lastIndexOf(' ', end) + 1;
  2357. const QByteArray address = ba.mid(end + 2).trimmed();
  2358. br.id = BreakpointResponseId(ba.mid(begin, end - begin));
  2359. if (address.startsWith('*'))
  2360. br.address = address.mid(1).toULongLong(0, 0);
  2361. handler->setResponse(id, br);
  2362. QTC_CHECK(!handler->needsChange(id));
  2363. handler->notifyBreakpointInsertOk(id);
  2364. } else {
  2365. showMessage(_("CANNOT PARSE WATCHPOINT FROM " + ba));
  2366. }
  2367. }
  2368. }
  2369. void GdbEngine::attemptAdjustBreakpointLocation(BreakpointModelId id)
  2370. {
  2371. if (m_hasBreakpointNotifications)
  2372. return;
  2373. if (!debuggerCore()->boolSetting(AdjustBreakpointLocations))
  2374. return;
  2375. BreakpointResponse response = breakHandler()->response(id);
  2376. if (response.address == 0 || response.correctedLineNumber != 0)
  2377. return;
  2378. // Prevent endless loop.
  2379. response.correctedLineNumber = -1;
  2380. breakHandler()->setResponse(id, response);
  2381. postCommand("info line *0x" + QByteArray::number(response.address, 16),
  2382. NeedsStop | RebuildBreakpointModel,
  2383. CB(handleInfoLine), QVariant::fromValue(id));
  2384. }
  2385. void GdbEngine::handleCatchInsert(const GdbResponse &response)
  2386. {
  2387. BreakHandler *handler = breakHandler();
  2388. BreakpointModelId id = response.cookie.value<BreakpointModelId>();
  2389. if (response.resultClass == GdbResultDone) {
  2390. handler->notifyBreakpointInsertOk(id);
  2391. attemptAdjustBreakpointLocation(id);
  2392. }
  2393. }
  2394. void GdbEngine::handleBreakInsert1(const GdbResponse &response)
  2395. {
  2396. BreakHandler *handler = breakHandler();
  2397. BreakpointModelId id = response.cookie.value<BreakpointModelId>();
  2398. if (handler->state(id) == BreakpointRemoveRequested) {
  2399. if (response.resultClass == GdbResultDone) {
  2400. // This delete was defered. Act now.
  2401. const GdbMi mainbkpt = response.data.findChild("bkpt");
  2402. handler->notifyBreakpointRemoveProceeding(id);
  2403. QByteArray nr = mainbkpt.findChild("number").data();
  2404. postCommand("-break-delete " + nr,
  2405. NeedsStop | RebuildBreakpointModel);
  2406. handler->notifyBreakpointRemoveOk(id);
  2407. return;
  2408. }
  2409. }
  2410. if (response.resultClass == GdbResultDone) {
  2411. // The result is a list with the first entry marked "bkpt"
  2412. // and "unmarked" rest. The "bkpt" one seems to always be
  2413. // the "main" entry. Use the "main" entry to retrieve the
  2414. // already known data from the BreakpointManager, and then
  2415. // iterate over all items to update main- and sub-data.
  2416. const GdbMi mainbkpt = response.data.findChild("bkpt");
  2417. QByteArray nr = mainbkpt.findChild("number").data();
  2418. BreakpointResponseId rid(nr);
  2419. if (!isHiddenBreakpoint(rid)) {
  2420. BreakpointResponse br = handler->response(id);
  2421. foreach (const GdbMi bkpt, response.data.children()) {
  2422. nr = bkpt.findChild("number").data();
  2423. rid = BreakpointResponseId(nr);
  2424. QTC_ASSERT(rid.isValid(), continue);
  2425. if (nr.contains('.')) {
  2426. // A sub-breakpoint.
  2427. BreakpointResponse sub;
  2428. updateResponse(sub, bkpt);
  2429. sub.id = rid;
  2430. sub.type = br.type;
  2431. handler->insertSubBreakpoint(id, sub);
  2432. } else {
  2433. // A (the?) primary breakpoint.
  2434. updateResponse(br, bkpt);
  2435. br.id = rid;
  2436. handler->setResponse(id, br);
  2437. }
  2438. }
  2439. if (handler->needsChange(id)) {
  2440. handler->notifyBreakpointChangeAfterInsertNeeded(id);
  2441. changeBreakpoint(id);
  2442. } else {
  2443. handler->notifyBreakpointInsertOk(id);
  2444. }
  2445. br = handler->response(id);
  2446. attemptAdjustBreakpointLocation(id);
  2447. // Remove if we only support 7.4 or later.
  2448. if (br.multiple && !m_hasBreakpointNotifications)
  2449. postCommand("info break " + QByteArray::number(br.id.majorPart()),
  2450. NeedsStop, CB(handleBreakListMultiple),
  2451. QVariant::fromValue(id));
  2452. }
  2453. } else if (response.data.findChild("msg").data().contains("Unknown option")) {
  2454. // Older version of gdb don't know the -a option to set tracepoints
  2455. // ^error,msg="mi_cmd_break_insert: Unknown option ``a''"
  2456. const QString fileName = handler->fileName(id);
  2457. const int lineNumber = handler->lineNumber(id);
  2458. QByteArray cmd = "trace "
  2459. "\"" + GdbMi::escapeCString(fileName).toLocal8Bit() + "\":"
  2460. + QByteArray::number(lineNumber);
  2461. QVariant vid = QVariant::fromValue(id);
  2462. postCommand(cmd, NeedsStop | RebuildBreakpointModel,
  2463. CB(handleTraceInsert2), vid);
  2464. } else {
  2465. // Some versions of gdb like "GNU gdb (GDB) SUSE (6.8.91.20090930-2.4)"
  2466. // know how to do pending breakpoints using CLI but not MI. So try
  2467. // again with MI.
  2468. QByteArray cmd = "break " + breakpointLocation2(id);
  2469. QVariant vid = QVariant::fromValue(id);
  2470. postCommand(cmd, NeedsStop | RebuildBreakpointModel,
  2471. CB(handleBreakInsert2), vid);
  2472. }
  2473. }
  2474. void GdbEngine::handleBreakInsert2(const GdbResponse &response)
  2475. {
  2476. if (response.resultClass == GdbResultDone) {
  2477. BreakpointModelId id = response.cookie.value<BreakpointModelId>();
  2478. attemptAdjustBreakpointLocation(id);
  2479. breakHandler()->notifyBreakpointInsertOk(id);
  2480. } else {
  2481. // Note: gdb < 60800 doesn't "do" pending breakpoints.
  2482. // Not much we can do about it except implementing the
  2483. // logic on top of shared library events, and that's not
  2484. // worth the effort.
  2485. }
  2486. }
  2487. void GdbEngine::handleTraceInsert2(const GdbResponse &response)
  2488. {
  2489. if (response.resultClass == GdbResultDone)
  2490. reloadBreakListInternal();
  2491. }
  2492. void GdbEngine::reloadBreakListInternal()
  2493. {
  2494. if (m_hasBreakpointNotifications) {
  2495. // Assume this properly handles breakpoint notifications.
  2496. return;
  2497. }
  2498. postCommand("-break-list", NeedsStop | RebuildBreakpointModel,
  2499. CB(handleBreakList));
  2500. }
  2501. void GdbEngine::handleBreakList(const GdbResponse &response)
  2502. {
  2503. // 45^done,BreakpointTable={nr_rows="2",nr_cols="6",hdr=[
  2504. // {width="3",alignment="-1",col_name="number",colhdr="Num"}, ...
  2505. // body=[bkpt={number="1",type="breakpoint",disp="keep",enabled="y",
  2506. // addr="0x000000000040109e",func="main",file="app.cpp",
  2507. // fullname="/home/apoenitz/dev/work/plugintest/app/app.cpp",
  2508. // line="11",times="1"},
  2509. // bkpt={number="2",type="breakpoint",disp="keep",enabled="y",
  2510. // addr="<PENDING>",pending="plugin.cpp:7",times="0"}] ... }
  2511. if (response.resultClass == GdbResultDone) {
  2512. GdbMi table = response.data.findChild("BreakpointTable");
  2513. if (table.isValid())
  2514. handleBreakList(table);
  2515. }
  2516. }
  2517. void GdbEngine::handleBreakList(const GdbMi &table)
  2518. {
  2519. const GdbMi body = table.findChild("body");
  2520. QList<GdbMi> bkpts;
  2521. if (body.isValid()) {
  2522. // Non-Mac
  2523. bkpts = body.children();
  2524. } else {
  2525. // Mac
  2526. bkpts = table.children();
  2527. // Remove the 'hdr' and artificial items.
  2528. for (int i = bkpts.size(); --i >= 0; ) {
  2529. int num = bkpts.at(i).findChild("number").data().toInt();
  2530. if (num <= 0)
  2531. bkpts.removeAt(i);
  2532. }
  2533. }
  2534. BreakHandler *handler = breakHandler();
  2535. foreach (const GdbMi &bkpt, bkpts) {
  2536. BreakpointResponse needle;
  2537. needle.id = BreakpointResponseId(bkpt.findChild("number").data());
  2538. if (isQmlStepBreakpoint2(needle.id))
  2539. continue;
  2540. if (isQFatalBreakpoint(needle.id))
  2541. continue;
  2542. BreakpointModelId id = handler->findSimilarBreakpoint(needle);
  2543. if (id.isValid()) {
  2544. BreakpointResponse response = handler->response(id);
  2545. updateResponse(response, bkpt);
  2546. handler->setResponse(id, response);
  2547. attemptAdjustBreakpointLocation(id);
  2548. response = handler->response(id);
  2549. if (response.multiple)
  2550. postCommand("info break " + response.id.toString().toLatin1(),
  2551. NeedsStop, CB(handleBreakListMultiple),
  2552. QVariant::fromValue(id));
  2553. } else {
  2554. qDebug() << " NOTHING SUITABLE FOUND";
  2555. showMessage(_("CANNOT FIND BP: " + bkpt.toString()));
  2556. }
  2557. }
  2558. m_breakListOutdated = false;
  2559. }
  2560. void GdbEngine::handleBreakListMultiple(const GdbResponse &response)
  2561. {
  2562. QTC_CHECK(response.resultClass == GdbResultDone);
  2563. const BreakpointModelId id = response.cookie.value<BreakpointModelId>();
  2564. const QString str = QString::fromLocal8Bit(response.consoleStreamOutput);
  2565. extractDataFromInfoBreak(str, id);
  2566. }
  2567. void GdbEngine::handleBreakDisable(const GdbResponse &response)
  2568. {
  2569. QTC_CHECK(response.resultClass == GdbResultDone);
  2570. const BreakpointModelId id = response.cookie.value<BreakpointModelId>();
  2571. BreakHandler *handler = breakHandler();
  2572. // This should only be the requested state.
  2573. QTC_ASSERT(!handler->isEnabled(id), /* Prevent later recursion */);
  2574. BreakpointResponse br = handler->response(id);
  2575. br.enabled = false;
  2576. handler->setResponse(id, br);
  2577. changeBreakpoint(id); // Maybe there's more to do.
  2578. }
  2579. void GdbEngine::handleBreakEnable(const GdbResponse &response)
  2580. {
  2581. QTC_CHECK(response.resultClass == GdbResultDone);
  2582. const BreakpointModelId id = response.cookie.value<BreakpointModelId>();
  2583. BreakHandler *handler = breakHandler();
  2584. // This should only be the requested state.
  2585. QTC_ASSERT(handler->isEnabled(id), /* Prevent later recursion */);
  2586. BreakpointResponse br = handler->response(id);
  2587. br.enabled = true;
  2588. handler->setResponse(id, br);
  2589. changeBreakpoint(id); // Maybe there's more to do.
  2590. }
  2591. void GdbEngine::handleBreakThreadSpec(const GdbResponse &response)
  2592. {
  2593. QTC_CHECK(response.resultClass == GdbResultDone);
  2594. const BreakpointModelId id = response.cookie.value<BreakpointModelId>();
  2595. BreakHandler *handler = breakHandler();
  2596. BreakpointResponse br = handler->response(id);
  2597. br.threadSpec = handler->threadSpec(id);
  2598. handler->setResponse(id, br);
  2599. handler->notifyBreakpointNeedsReinsertion(id);
  2600. insertBreakpoint(id);
  2601. }
  2602. void GdbEngine::handleBreakLineNumber(const GdbResponse &response)
  2603. {
  2604. QTC_CHECK(response.resultClass == GdbResultDone);
  2605. const BreakpointModelId id = response.cookie.value<BreakpointModelId>();
  2606. BreakHandler *handler = breakHandler();
  2607. BreakpointResponse br = handler->response(id);
  2608. br.lineNumber = handler->lineNumber(id);
  2609. handler->setResponse(id, br);
  2610. handler->notifyBreakpointNeedsReinsertion(id);
  2611. insertBreakpoint(id);
  2612. }
  2613. void GdbEngine::handleBreakIgnore(const GdbResponse &response)
  2614. {
  2615. // gdb 6.8:
  2616. // ignore 2 0:
  2617. // ~"Will stop next time breakpoint 2 is reached.\n"
  2618. // 28^done
  2619. // ignore 2 12:
  2620. // &"ignore 2 12\n"
  2621. // ~"Will ignore next 12 crossings of breakpoint 2.\n"
  2622. // 29^done
  2623. //
  2624. // gdb 6.3 does not produce any console output
  2625. QTC_CHECK(response.resultClass == GdbResultDone);
  2626. //QString msg = _(response.consoleStreamOutput);
  2627. BreakpointModelId id = response.cookie.value<BreakpointModelId>();
  2628. BreakHandler *handler = breakHandler();
  2629. BreakpointResponse br = handler->response(id);
  2630. //if (msg.contains(__("Will stop next time breakpoint")))
  2631. // response.ignoreCount = _("0");
  2632. //else if (msg.contains(__("Will ignore next")))
  2633. // response.ignoreCount = data->ignoreCount;
  2634. // FIXME: this assumes it is doing the right thing...
  2635. const BreakpointParameters &parameters = handler->breakpointData(id);
  2636. br.ignoreCount = parameters.ignoreCount;
  2637. br.command = parameters.command;
  2638. handler->setResponse(id, br);
  2639. changeBreakpoint(id); // Maybe there's more to do.
  2640. }
  2641. void GdbEngine::handleBreakCondition(const GdbResponse &response)
  2642. {
  2643. // Can happen at invalid condition strings.
  2644. //QTC_CHECK(response.resultClass == GdbResultDone)
  2645. const BreakpointModelId id = response.cookie.value<BreakpointModelId>();
  2646. BreakHandler *handler = breakHandler();
  2647. // We just assume it was successful. Otherwise we had to parse
  2648. // the output stream data.
  2649. // The following happens on Mac:
  2650. // QByteArray msg = response.data.findChild("msg").data();
  2651. // if (1 || msg.startsWith("Error parsing breakpoint condition. "
  2652. // " Will try again when we hit the breakpoint.")) {
  2653. BreakpointResponse br = handler->response(id);
  2654. br.condition = handler->condition(id);
  2655. handler->setResponse(id, br);
  2656. changeBreakpoint(id); // Maybe there's more to do.
  2657. }
  2658. void GdbEngine::extractDataFromInfoBreak(const QString &output, BreakpointModelId id)
  2659. {
  2660. //qDebug() << output;
  2661. if (output.isEmpty())
  2662. return;
  2663. // "Num Type Disp Enb Address What
  2664. // 4 breakpoint keep y <MULTIPLE> 0x00000000004066ad
  2665. // 4.1 y 0x00000000004066ad in CTorTester
  2666. // at /data5/dev/ide/main/tests/manual/gdbdebugger/simple/app.cpp:124
  2667. // - or -
  2668. // everything on a single line on Windows for constructors of classes
  2669. // within namespaces.
  2670. // Sometimes the path is relative too.
  2671. // 2 breakpoint keep y <MULTIPLE> 0x0040168e
  2672. // 2.1 y 0x0040168e in MainWindow::MainWindow(QWidget*) at mainwindow.cpp:7
  2673. // 2.2 y 0x00401792 in MainWindow::MainWindow(QWidget*) at mainwindow.cpp:7
  2674. // "Num Type Disp Enb Address What
  2675. // 3 breakpoint keep y <MULTIPLE> \n"
  2676. // 3.1 y 0x0806094e in Vector<int>::Vector(int) at simple.cpp:141
  2677. // 3.2 y 0x08060994 in Vector<float>::Vector(int) at simple.cpp:141
  2678. // 3.3 y 0x080609da in Vector<double>::Vector(int) at simple.cpp:141
  2679. // 3.4 y 0x08060a1d in Vector<char>::Vector(int) at simple.cpp:141
  2680. BreakHandler *handler = breakHandler();
  2681. BreakpointResponse response = handler->response(id);
  2682. int posMultiple = output.indexOf(_("<MULTIPLE>"));
  2683. if (posMultiple != -1) {
  2684. QByteArray data = output.toUtf8();
  2685. data.replace('\n', ' ');
  2686. data.replace(" ", " ");
  2687. data.replace(" ", " ");
  2688. data.replace(" ", " ");
  2689. int majorPart = 0;
  2690. int minorPart = 0;
  2691. int hitCount = 0;
  2692. bool hitCountComing = false;
  2693. bool functionComing = false;
  2694. bool locationComing = false;
  2695. QByteArray location;
  2696. QByteArray function;
  2697. qulonglong address = 0;
  2698. foreach (const QByteArray &part, data.split(' ')) {
  2699. if (part.isEmpty())
  2700. continue;
  2701. //qDebug() << "PART: " << part;
  2702. if (majorPart == 0) {
  2703. majorPart = part.toInt();
  2704. if (majorPart > 0)
  2705. continue;
  2706. }
  2707. if (part == "hit") {
  2708. hitCountComing = true;
  2709. continue;
  2710. }
  2711. if (hitCountComing) {
  2712. hitCountComing = false;
  2713. hitCount = part.toInt();
  2714. continue;
  2715. }
  2716. if (part == "at") {
  2717. locationComing = true;
  2718. continue;
  2719. }
  2720. if (locationComing) {
  2721. locationComing = false;
  2722. location = part;
  2723. continue;
  2724. }
  2725. if (part == "in") {
  2726. functionComing = true;
  2727. continue;
  2728. }
  2729. if (functionComing) {
  2730. functionComing = false;
  2731. function = part;
  2732. continue;
  2733. }
  2734. if (part.startsWith("0x")) {
  2735. address = part.toInt(0, 0);
  2736. continue;
  2737. }
  2738. if (part.size() >= 3 && part.count('.') == 1) {
  2739. BreakpointResponseId subId(part);
  2740. int tmpMajor = subId.majorPart();
  2741. int tmpMinor = subId.minorPart();
  2742. if (tmpMajor == majorPart) {
  2743. if (minorPart) {
  2744. // Commit what we had before.
  2745. BreakpointResponse sub;
  2746. sub.address = address;
  2747. sub.functionName = QString::fromUtf8(function);
  2748. sub.updateLocation(location);
  2749. sub.id = BreakpointResponseId(majorPart, minorPart);
  2750. sub.type = response.type;
  2751. sub.address = address;
  2752. sub.hitCount = hitCount;
  2753. handler->insertSubBreakpoint(id, sub);
  2754. location.clear();
  2755. function.clear();
  2756. address = 0;
  2757. }
  2758. // Now start new.
  2759. minorPart = tmpMinor;
  2760. continue;
  2761. }
  2762. }
  2763. }
  2764. if (minorPart) {
  2765. // Commit last chunk.
  2766. BreakpointResponse sub;
  2767. sub.address = address;
  2768. sub.functionName = QString::fromUtf8(function);
  2769. sub.updateLocation(location);
  2770. sub.id = BreakpointResponseId(majorPart, minorPart);
  2771. sub.type = response.type;
  2772. sub.hitCount = hitCount;
  2773. handler->insertSubBreakpoint(id, sub);
  2774. location.clear();
  2775. function.clear();
  2776. address = 0;
  2777. }
  2778. } else {
  2779. qDebug() << "COULD NOT MATCH" << output;
  2780. response.id = BreakpointResponseId(); // Unavailable.
  2781. }
  2782. //handler->setResponse(id, response);
  2783. }
  2784. void GdbEngine::handleInfoLine(const GdbResponse &response)
  2785. {
  2786. if (response.resultClass == GdbResultDone) {
  2787. // Old-style output: "Line 1102 of \"simple/app.cpp\" starts
  2788. // at address 0x80526aa <_Z10...+131> and ends at 0x80526b5
  2789. // <_Z10testQStackv+142>.\n"
  2790. QByteArray ba = response.consoleStreamOutput;
  2791. const BreakpointModelId id = response.cookie.value<BreakpointModelId>();
  2792. const int pos = ba.indexOf(' ', 5);
  2793. if (ba.startsWith("Line ") && pos != -1) {
  2794. const int line = ba.mid(5, pos - 5).toInt();
  2795. BreakpointResponse br = breakHandler()->response(id);
  2796. br.lineNumber = line;
  2797. br.correctedLineNumber = line;
  2798. breakHandler()->setResponse(id, br);
  2799. }
  2800. }
  2801. }
  2802. bool GdbEngine::stateAcceptsBreakpointChanges() const
  2803. {
  2804. switch (state()) {
  2805. case InferiorSetupRequested:
  2806. case InferiorRunRequested:
  2807. case InferiorRunOk:
  2808. case InferiorStopRequested:
  2809. case InferiorStopOk:
  2810. return true;
  2811. default:
  2812. return false;
  2813. }
  2814. }
  2815. bool GdbEngine::acceptsBreakpoint(BreakpointModelId id) const
  2816. {
  2817. return breakHandler()->breakpointData(id).isCppBreakpoint()
  2818. && startParameters().startMode != AttachCore;
  2819. }
  2820. void GdbEngine::insertBreakpoint(BreakpointModelId id)
  2821. {
  2822. // Set up fallback in case of pending breakpoints which aren't handled
  2823. // by the MI interface.
  2824. BreakHandler *handler = breakHandler();
  2825. QTC_CHECK(handler->state(id) == BreakpointInsertRequested);
  2826. handler->notifyBreakpointInsertProceeding(id);
  2827. BreakpointType type = handler->type(id);
  2828. QVariant vid = QVariant::fromValue(id);
  2829. if (type == WatchpointAtAddress) {
  2830. postCommand("watch " + addressSpec(handler->address(id)),
  2831. NeedsStop | RebuildBreakpointModel | ConsoleCommand,
  2832. CB(handleWatchInsert), vid);
  2833. return;
  2834. }
  2835. if (type == WatchpointAtExpression) {
  2836. postCommand("watch " + handler->expression(id).toLocal8Bit(),
  2837. NeedsStop | RebuildBreakpointModel | ConsoleCommand,
  2838. CB(handleWatchInsert), vid);
  2839. return;
  2840. }
  2841. if (type == BreakpointAtFork) {
  2842. postCommand("catch fork",
  2843. NeedsStop | RebuildBreakpointModel | ConsoleCommand,
  2844. CB(handleCatchInsert), vid);
  2845. postCommand("catch vfork",
  2846. NeedsStop | RebuildBreakpointModel | ConsoleCommand,
  2847. CB(handleCatchInsert), vid);
  2848. return;
  2849. }
  2850. //if (type == BreakpointAtVFork) {
  2851. // postCommand("catch vfork", NeedsStop | RebuildBreakpointModel,
  2852. // CB(handleCatchInsert), vid);
  2853. // return;
  2854. //}
  2855. if (type == BreakpointAtExec) {
  2856. postCommand("catch exec",
  2857. NeedsStop | RebuildBreakpointModel | ConsoleCommand,
  2858. CB(handleCatchInsert), vid);
  2859. return;
  2860. }
  2861. if (type == BreakpointAtSysCall) {
  2862. postCommand("catch syscall",
  2863. NeedsStop | RebuildBreakpointModel | ConsoleCommand,
  2864. CB(handleCatchInsert), vid);
  2865. return;
  2866. }
  2867. QByteArray cmd = "xxx";
  2868. if (handler->isTracepoint(id)) {
  2869. cmd = "-break-insert -a -f ";
  2870. } else if (m_isMacGdb) {
  2871. cmd = "-break-insert -l -1 -f ";
  2872. } else if (isCodaAdapter()) {
  2873. cmd = "-break-insert -h -f ";
  2874. } else if (m_gdbVersion >= 70000) {
  2875. int spec = handler->threadSpec(id);
  2876. cmd = "-break-insert ";
  2877. if (spec >= 0)
  2878. cmd += "-p " + QByteArray::number(spec);
  2879. cmd += " -f ";
  2880. } else if (m_gdbVersion >= 60800) {
  2881. // Probably some earlier version would work as well.
  2882. cmd = "-break-insert -f ";
  2883. } else {
  2884. cmd = "-break-insert ";
  2885. }
  2886. //if (!data->condition.isEmpty())
  2887. // cmd += "-c " + data->condition + ' ';
  2888. cmd += breakpointLocation(id);
  2889. postCommand(cmd, NeedsStop | RebuildBreakpointModel,
  2890. CB(handleBreakInsert1), vid);
  2891. }
  2892. void GdbEngine::changeBreakpoint(BreakpointModelId id)
  2893. {
  2894. BreakHandler *handler = breakHandler();
  2895. const BreakpointParameters &data = handler->breakpointData(id);
  2896. QTC_ASSERT(data.type != UnknownType, return);
  2897. const BreakpointResponse &response = handler->response(id);
  2898. QTC_ASSERT(response.id.isValid(), return);
  2899. const QByteArray bpnr = response.id.toByteArray();
  2900. const BreakpointState state = handler->state(id);
  2901. if (state == BreakpointChangeRequested)
  2902. handler->notifyBreakpointChangeProceeding(id);
  2903. const BreakpointState state2 = handler->state(id);
  2904. QTC_ASSERT(state2 == BreakpointChangeProceeding, qDebug() << state2);
  2905. QVariant vid = QVariant::fromValue(id);
  2906. if (data.threadSpec != response.threadSpec) {
  2907. // The only way to change this seems to be to re-set the bp completely.
  2908. postCommand("-break-delete " + bpnr,
  2909. NeedsStop | RebuildBreakpointModel,
  2910. CB(handleBreakThreadSpec), vid);
  2911. return;
  2912. }
  2913. if (data.lineNumber != response.lineNumber) {
  2914. // The only way to change this seems to be to re-set the bp completely.
  2915. postCommand("-break-delete " + bpnr,
  2916. NeedsStop | RebuildBreakpointModel,
  2917. CB(handleBreakLineNumber), vid);
  2918. return;
  2919. }
  2920. if (data.command != response.command) {
  2921. QByteArray breakCommand = "-break-commands " + bpnr;
  2922. foreach (const QString &command, data.command.split(QLatin1String("\\n"))) {
  2923. if (!command.isEmpty()) {
  2924. breakCommand.append(" \"");
  2925. breakCommand.append(command.toLatin1());
  2926. breakCommand.append('"');
  2927. }
  2928. }
  2929. postCommand(breakCommand, NeedsStop | RebuildBreakpointModel,
  2930. CB(handleBreakIgnore), vid);
  2931. return;
  2932. }
  2933. if (!data.conditionsMatch(response.condition)) {
  2934. postCommand("condition " + bpnr + ' ' + data.condition,
  2935. NeedsStop | RebuildBreakpointModel,
  2936. CB(handleBreakCondition), vid);
  2937. return;
  2938. }
  2939. if (data.ignoreCount != response.ignoreCount) {
  2940. postCommand("ignore " + bpnr + ' ' + QByteArray::number(data.ignoreCount),
  2941. NeedsStop | RebuildBreakpointModel,
  2942. CB(handleBreakIgnore), vid);
  2943. return;
  2944. }
  2945. if (!data.enabled && response.enabled) {
  2946. postCommand("-break-disable " + bpnr,
  2947. NeedsStop | RebuildBreakpointModel,
  2948. CB(handleBreakDisable), vid);
  2949. return;
  2950. }
  2951. if (data.enabled && !response.enabled) {
  2952. postCommand("-break-enable " + bpnr,
  2953. NeedsStop | RebuildBreakpointModel,
  2954. CB(handleBreakEnable), vid);
  2955. return;
  2956. }
  2957. handler->notifyBreakpointChangeOk(id);
  2958. attemptAdjustBreakpointLocation(id);
  2959. }
  2960. void GdbEngine::removeBreakpoint(BreakpointModelId id)
  2961. {
  2962. BreakHandler *handler = breakHandler();
  2963. QTC_CHECK(handler->state(id) == BreakpointRemoveRequested);
  2964. BreakpointResponse br = handler->response(id);
  2965. if (br.id.isValid()) {
  2966. // We already have a fully inserted breakpoint.
  2967. handler->notifyBreakpointRemoveProceeding(id);
  2968. showMessage(_("DELETING BP %1 IN %2").arg(br.id.toString())
  2969. .arg(handler->fileName(id)));
  2970. postCommand("-break-delete " + br.id.toByteArray(),
  2971. NeedsStop | RebuildBreakpointModel);
  2972. // Pretend it succeeds without waiting for response. Feels better.
  2973. // FIXME: Really?
  2974. handler->notifyBreakpointRemoveOk(id);
  2975. } else {
  2976. // Breakpoint was scheduled to be inserted, but we haven't had
  2977. // an answer so far. Postpone activity by doing nothing.
  2978. }
  2979. }
  2980. //////////////////////////////////////////////////////////////////////
  2981. //
  2982. // Modules specific stuff
  2983. //
  2984. //////////////////////////////////////////////////////////////////////
  2985. void GdbEngine::loadSymbols(const QString &modulePath)
  2986. {
  2987. // FIXME: gdb does not understand quoted names here (tested with 6.8)
  2988. postCommand("sharedlibrary " + dotEscape(modulePath.toLocal8Bit()));
  2989. reloadModulesInternal();
  2990. reloadBreakListInternal();
  2991. reloadStack(true);
  2992. updateLocals();
  2993. }
  2994. void GdbEngine::loadAllSymbols()
  2995. {
  2996. postCommand("sharedlibrary .*");
  2997. reloadModulesInternal();
  2998. reloadBreakListInternal();
  2999. reloadStack(true);
  3000. updateLocals();
  3001. }
  3002. void GdbEngine::loadSymbolsForStack()
  3003. {
  3004. bool needUpdate = false;
  3005. const Modules &modules = modulesHandler()->modules();
  3006. foreach (const StackFrame &frame, stackHandler()->frames()) {
  3007. if (frame.function == _("??")) {
  3008. //qDebug() << "LOAD FOR " << frame.address;
  3009. foreach (const Module &module, modules) {
  3010. if (module.startAddress <= frame.address
  3011. && frame.address < module.endAddress) {
  3012. postCommand("sharedlibrary "
  3013. + dotEscape(module.modulePath.toLocal8Bit()));
  3014. needUpdate = true;
  3015. }
  3016. }
  3017. }
  3018. }
  3019. if (needUpdate) {
  3020. //reloadModulesInternal();
  3021. reloadBreakListInternal();
  3022. reloadStack(true);
  3023. updateLocals();
  3024. }
  3025. }
  3026. void GdbEngine::requestModuleSymbols(const QString &modulePath)
  3027. {
  3028. QTemporaryFile tf(QDir::tempPath() + _("/gdbsymbols"));
  3029. if (!tf.open())
  3030. return;
  3031. QString fileName = tf.fileName();
  3032. tf.close();
  3033. postCommand("maint print msymbols " + fileName.toLocal8Bit()
  3034. + ' ' + modulePath.toLocal8Bit(),
  3035. NeedsStop, CB(handleShowModuleSymbols),
  3036. QVariant(modulePath + QLatin1Char('@') + fileName));
  3037. }
  3038. void GdbEngine::handleShowModuleSymbols(const GdbResponse &response)
  3039. {
  3040. const QString cookie = response.cookie.toString();
  3041. const QString modulePath = cookie.section(QLatin1Char('@'), 0, 0);
  3042. const QString fileName = cookie.section(QLatin1Char('@'), 1, 1);
  3043. if (response.resultClass == GdbResultDone) {
  3044. Symbols rc;
  3045. QFile file(fileName);
  3046. file.open(QIODevice::ReadOnly);
  3047. // Object file /opt/dev/qt/lib/libQtNetworkMyns.so.4:
  3048. // [ 0] A 0x16bd64 _DYNAMIC moc_qudpsocket.cpp
  3049. // [12] S 0xe94680 _ZN4myns5QFileC1Ev section .plt myns::QFile::QFile()
  3050. foreach (const QByteArray &line, file.readAll().split('\n')) {
  3051. if (line.isEmpty())
  3052. continue;
  3053. if (line.at(0) != '[')
  3054. continue;
  3055. int posCode = line.indexOf(']') + 2;
  3056. int posAddress = line.indexOf("0x", posCode);
  3057. if (posAddress == -1)
  3058. continue;
  3059. int posName = line.indexOf(" ", posAddress);
  3060. int lenAddress = posName - posAddress;
  3061. int posSection = line.indexOf(" section ");
  3062. int lenName = 0;
  3063. int lenSection = 0;
  3064. int posDemangled = 0;
  3065. if (posSection == -1) {
  3066. lenName = line.size() - posName;
  3067. posDemangled = posName;
  3068. } else {
  3069. lenName = posSection - posName;
  3070. posSection += 10;
  3071. posDemangled = line.indexOf(' ', posSection + 1);
  3072. if (posDemangled == -1) {
  3073. lenSection = line.size() - posSection;
  3074. } else {
  3075. lenSection = posDemangled - posSection;
  3076. posDemangled += 1;
  3077. }
  3078. }
  3079. int lenDemangled = 0;
  3080. if (posDemangled != -1)
  3081. lenDemangled = line.size() - posDemangled;
  3082. Symbol symbol;
  3083. symbol.state = _(line.mid(posCode, 1));
  3084. symbol.address = _(line.mid(posAddress, lenAddress));
  3085. symbol.name = _(line.mid(posName, lenName));
  3086. symbol.section = _(line.mid(posSection, lenSection));
  3087. symbol.demangled = _(line.mid(posDemangled, lenDemangled));
  3088. rc.push_back(symbol);
  3089. }
  3090. file.close();
  3091. file.remove();
  3092. debuggerCore()->showModuleSymbols(modulePath, rc);
  3093. } else {
  3094. showMessageBox(QMessageBox::Critical, tr("Cannot Read Symbols"),
  3095. tr("Cannot read symbols for module \"%1\".").arg(fileName));
  3096. }
  3097. }
  3098. void GdbEngine::reloadModules()
  3099. {
  3100. if (state() == InferiorRunOk || state() == InferiorStopOk)
  3101. reloadModulesInternal();
  3102. }
  3103. void GdbEngine::reloadModulesInternal()
  3104. {
  3105. postCommand("info shared", NeedsStop, CB(handleModulesList));
  3106. }
  3107. static QString nameFromPath(const QString &path)
  3108. {
  3109. return QFileInfo(path).baseName();
  3110. }
  3111. void GdbEngine::handleModulesList(const GdbResponse &response)
  3112. {
  3113. if (response.resultClass == GdbResultDone) {
  3114. ModulesHandler *handler = modulesHandler();
  3115. Module module;
  3116. // That's console-based output, likely Linux or Windows,
  3117. // but we can avoid the target dependency here.
  3118. QString data = QString::fromLocal8Bit(response.consoleStreamOutput);
  3119. QTextStream ts(&data, QIODevice::ReadOnly);
  3120. bool found = false;
  3121. while (!ts.atEnd()) {
  3122. QString line = ts.readLine();
  3123. QString symbolsRead;
  3124. QTextStream ts(&line, QIODevice::ReadOnly);
  3125. if (line.startsWith(QLatin1String("0x"))) {
  3126. ts >> module.startAddress >> module.endAddress >> symbolsRead;
  3127. module.modulePath = ts.readLine().trimmed();
  3128. module.moduleName = nameFromPath(module.modulePath);
  3129. module.symbolsRead =
  3130. (symbolsRead == QLatin1String("Yes") ? Module::ReadOk : Module::ReadFailed);
  3131. handler->updateModule(module);
  3132. found = true;
  3133. } else if (line.trimmed().startsWith(QLatin1String("No"))) {
  3134. // gdb 6.4 symbianelf
  3135. ts >> symbolsRead;
  3136. QTC_ASSERT(symbolsRead == QLatin1String("No"), continue);
  3137. module.startAddress = 0;
  3138. module.endAddress = 0;
  3139. module.modulePath = ts.readLine().trimmed();
  3140. module.moduleName = nameFromPath(module.modulePath);
  3141. handler->updateModule(module);
  3142. found = true;
  3143. }
  3144. }
  3145. if (!found) {
  3146. // Mac has^done,shlib-info={num="1",name="dyld",kind="-",
  3147. // dyld-addr="0x8fe00000",reason="dyld",requested-state="Y",
  3148. // state="Y",path="/usr/lib/dyld",description="/usr/lib/dyld",
  3149. // loaded_addr="0x8fe00000",slide="0x0",prefix="__dyld_"},
  3150. // shlib-info={...}...
  3151. foreach (const GdbMi &item, response.data.children()) {
  3152. module.modulePath =
  3153. QString::fromLocal8Bit(item.findChild("path").data());
  3154. module.moduleName = nameFromPath(module.modulePath);
  3155. module.symbolsRead = (item.findChild("state").data() == "Y")
  3156. ? Module::ReadOk : Module::ReadFailed;
  3157. module.startAddress =
  3158. item.findChild("loaded_addr").data().toULongLong(0, 0);
  3159. module.endAddress = 0; // FIXME: End address not easily available.
  3160. handler->updateModule(module);
  3161. }
  3162. }
  3163. }
  3164. }
  3165. void GdbEngine::examineModules()
  3166. {
  3167. ModulesHandler *handler = modulesHandler();
  3168. foreach (Module module, handler->modules()) {
  3169. if (module.elfData.symbolsType == UnknownSymbols)
  3170. handler->updateModule(module);
  3171. }
  3172. }
  3173. //////////////////////////////////////////////////////////////////////
  3174. //
  3175. // Source files specific stuff
  3176. //
  3177. //////////////////////////////////////////////////////////////////////
  3178. void GdbEngine::invalidateSourcesList()
  3179. {
  3180. m_breakListOutdated = true;
  3181. }
  3182. void GdbEngine::reloadSourceFiles()
  3183. {
  3184. if ((state() == InferiorRunOk || state() == InferiorStopOk)
  3185. && !m_sourcesListUpdating)
  3186. reloadSourceFilesInternal();
  3187. }
  3188. void GdbEngine::reloadSourceFilesInternal()
  3189. {
  3190. QTC_CHECK(!m_sourcesListUpdating);
  3191. m_sourcesListUpdating = true;
  3192. postCommand("-file-list-exec-source-files", NeedsStop, CB(handleQuerySources));
  3193. #if 0
  3194. if (m_gdbVersion < 70000 && !m_isMacGdb)
  3195. postCommand("set stop-on-solib-events 1");
  3196. #endif
  3197. }
  3198. //////////////////////////////////////////////////////////////////////
  3199. //
  3200. // Stack specific stuff
  3201. //
  3202. //////////////////////////////////////////////////////////////////////
  3203. void GdbEngine::selectThread(int index)
  3204. {
  3205. threadsHandler()->setCurrentThread(index);
  3206. Threads threads = threadsHandler()->threads();
  3207. QTC_ASSERT(index < threads.size(), return);
  3208. const int id = threads.at(index).id;
  3209. showStatusMessage(tr("Retrieving data for stack view thread 0x%1...")
  3210. .arg(id, 0, 16), 10000);
  3211. postCommand("-thread-select " + QByteArray::number(id), Discardable,
  3212. CB(handleStackSelectThread));
  3213. }
  3214. void GdbEngine::handleStackSelectThread(const GdbResponse &)
  3215. {
  3216. QTC_CHECK(state() == InferiorUnrunnable || state() == InferiorStopOk);
  3217. showStatusMessage(tr("Retrieving data for stack view..."), 3000);
  3218. reloadStack(true); // Will reload registers.
  3219. updateLocals();
  3220. }
  3221. void GdbEngine::reloadFullStack()
  3222. {
  3223. PENDING_DEBUG("RELOAD FULL STACK");
  3224. postCommand("-stack-list-frames", Discardable, CB(handleStackListFrames),
  3225. QVariant::fromValue<StackCookie>(StackCookie(true, true)));
  3226. }
  3227. void GdbEngine::reloadStack(bool forceGotoLocation)
  3228. {
  3229. PENDING_DEBUG("RELOAD STACK");
  3230. QByteArray cmd = "-stack-list-frames";
  3231. int stackDepth = debuggerCore()->action(MaximalStackDepth)->value().toInt();
  3232. if (stackDepth && !isCodaAdapter())
  3233. cmd += " 0 " + QByteArray::number(stackDepth);
  3234. postCommand(cmd, Discardable, CB(handleStackListFrames),
  3235. QVariant::fromValue<StackCookie>(StackCookie(false, forceGotoLocation)));
  3236. }
  3237. StackFrame GdbEngine::parseStackFrame(const GdbMi &frameMi, int level)
  3238. {
  3239. //qDebug() << "HANDLING FRAME:" << frameMi.toString();
  3240. StackFrame frame;
  3241. frame.level = level;
  3242. GdbMi fullName = frameMi.findChild("fullname");
  3243. if (fullName.isValid())
  3244. frame.file = cleanupFullName(QFile::decodeName(fullName.data()));
  3245. else
  3246. frame.file = QFile::decodeName(frameMi.findChild("file").data());
  3247. frame.function = _(frameMi.findChild("func").data());
  3248. frame.from = _(frameMi.findChild("from").data());
  3249. frame.line = frameMi.findChild("line").data().toInt();
  3250. frame.address = frameMi.findChild("addr").toAddress();
  3251. frame.usable = QFileInfo(frame.file).isReadable();
  3252. return frame;
  3253. }
  3254. void GdbEngine::handleStackListFrames(const GdbResponse &response)
  3255. {
  3256. bool handleIt = (m_isMacGdb || response.resultClass == GdbResultDone);
  3257. if (!handleIt) {
  3258. // That always happens on symbian gdb with
  3259. // ^error,data={msg="Previous frame identical to this frame (corrupt stack?)"
  3260. // logStreamOutput: "Previous frame identical to this frame (corrupt stack?)\n"
  3261. //qDebug() << "LISTING STACK FAILED: " << response.toString();
  3262. reloadRegisters();
  3263. return;
  3264. }
  3265. StackCookie cookie = response.cookie.value<StackCookie>();
  3266. QList<StackFrame> stackFrames;
  3267. GdbMi stack = response.data.findChild("stack");
  3268. if (!stack.isValid()) {
  3269. qDebug() << "FIXME: stack:" << stack.toString();
  3270. return;
  3271. }
  3272. int targetFrame = -1;
  3273. int n = stack.childCount();
  3274. for (int i = 0; i != n; ++i) {
  3275. stackFrames.append(parseStackFrame(stack.childAt(i), i));
  3276. const StackFrame &frame = stackFrames.back();
  3277. // Initialize top frame to the first valid frame.
  3278. const bool isValid = frame.isUsable() && !frame.function.isEmpty();
  3279. if (isValid && targetFrame == -1)
  3280. targetFrame = i;
  3281. }
  3282. bool canExpand = !cookie.isFull
  3283. && (n >= debuggerCore()->action(MaximalStackDepth)->value().toInt());
  3284. debuggerCore()->action(ExpandStack)->setEnabled(canExpand);
  3285. stackHandler()->setFrames(stackFrames, canExpand);
  3286. // We can't jump to any file if we don't have any frames.
  3287. if (stackFrames.isEmpty())
  3288. return;
  3289. // targetFrame contains the top most frame for which we have source
  3290. // information. That's typically the frame we'd like to jump to, with
  3291. // a few exceptions:
  3292. // Always jump to frame #0 when stepping by instruction.
  3293. if (debuggerCore()->boolSetting(OperateByInstruction))
  3294. targetFrame = 0;
  3295. // If there is no frame with source, jump to frame #0.
  3296. if (targetFrame == -1)
  3297. targetFrame = 0;
  3298. stackHandler()->setCurrentIndex(targetFrame);
  3299. activateFrame(targetFrame);
  3300. }
  3301. void GdbEngine::activateFrame(int frameIndex)
  3302. {
  3303. if (state() != InferiorStopOk && state() != InferiorUnrunnable)
  3304. return;
  3305. StackHandler *handler = stackHandler();
  3306. if (frameIndex == handler->stackSize()) {
  3307. reloadFullStack();
  3308. return;
  3309. }
  3310. QTC_ASSERT(frameIndex < handler->stackSize(), return);
  3311. // Assuming the command always succeeds this saves a roundtrip.
  3312. // Otherwise the lines below would need to get triggered
  3313. // after a response to this -stack-select-frame here.
  3314. handler->setCurrentIndex(frameIndex);
  3315. QByteArray cmd = "-stack-select-frame";
  3316. //if (!m_currentThread.isEmpty())
  3317. // cmd += " --thread " + m_currentThread;
  3318. cmd += ' ';
  3319. cmd += QByteArray::number(frameIndex);
  3320. postCommand(cmd, Discardable, CB(handleStackSelectFrame));
  3321. gotoLocation(stackHandler()->currentFrame());
  3322. updateLocals();
  3323. reloadRegisters();
  3324. }
  3325. void GdbEngine::handleStackSelectFrame(const GdbResponse &response)
  3326. {
  3327. Q_UNUSED(response);
  3328. }
  3329. void GdbEngine::handleThreadInfo(const GdbResponse &response)
  3330. {
  3331. if (response.resultClass == GdbResultDone) {
  3332. int currentThreadId;
  3333. const Threads threads =
  3334. ThreadsHandler::parseGdbmiThreads(response.data, &currentThreadId);
  3335. threadsHandler()->setThreads(threads);
  3336. threadsHandler()->setCurrentThreadId(currentThreadId);
  3337. updateViews(); // Adjust Threads combobox.
  3338. if (m_hasInferiorThreadList && debuggerCore()->boolSetting(ShowThreadNames)) {
  3339. postCommand("threadnames " +
  3340. debuggerCore()->action(MaximalStackDepth)->value().toByteArray(),
  3341. Discardable, CB(handleThreadNames));
  3342. }
  3343. } else {
  3344. // Fall back for older versions: Try to get at least a list
  3345. // of running threads.
  3346. postCommand("-thread-list-ids", Discardable, CB(handleThreadListIds));
  3347. }
  3348. }
  3349. void GdbEngine::handleThreadListIds(const GdbResponse &response)
  3350. {
  3351. // "72^done,{thread-ids={thread-id="2",thread-id="1"},number-of-threads="2"}
  3352. // In gdb 7.1+ additionally: current-thread-id="1"
  3353. const QList<GdbMi> items = response.data.findChild("thread-ids").children();
  3354. Threads threads;
  3355. for (int index = 0, n = items.size(); index != n; ++index) {
  3356. ThreadData thread;
  3357. thread.id = items.at(index).data().toInt();
  3358. threads.append(thread);
  3359. }
  3360. threadsHandler()->setThreads(threads);
  3361. threadsHandler()->setCurrentThreadId(m_currentThreadId);
  3362. }
  3363. void GdbEngine::handleThreadNames(const GdbResponse &response)
  3364. {
  3365. if (response.resultClass == GdbResultDone) {
  3366. GdbMi names;
  3367. names.fromString(response.consoleStreamOutput);
  3368. Threads threads = threadsHandler()->threads();
  3369. foreach (const GdbMi &name, names.children()) {
  3370. int id = name.findChild("id").data().toInt();
  3371. for (int index = 0, n = threads.size(); index != n; ++index) {
  3372. ThreadData &thread = threads[index];
  3373. if (thread.id == quint64(id)) {
  3374. thread.name = decodeData(name.findChild("value").data(),
  3375. name.findChild("valueencoded").data().toInt());
  3376. break;
  3377. }
  3378. }
  3379. }
  3380. threadsHandler()->setThreads(threads);
  3381. updateViews();
  3382. }
  3383. }
  3384. //////////////////////////////////////////////////////////////////////
  3385. //
  3386. // Snapshot specific stuff
  3387. //
  3388. //////////////////////////////////////////////////////////////////////
  3389. void GdbEngine::createSnapshot()
  3390. {
  3391. QString fileName;
  3392. QTemporaryFile tf(QDir::tempPath() + _("/gdbsnapshot"));
  3393. if (tf.open()) {
  3394. fileName = tf.fileName();
  3395. tf.close();
  3396. postCommand("gcore " + fileName.toLocal8Bit(),
  3397. NeedsStop|ConsoleCommand, CB(handleMakeSnapshot), fileName);
  3398. } else {
  3399. showMessageBox(QMessageBox::Critical, tr("Snapshot Creation Error"),
  3400. tr("Cannot create snapshot file."));
  3401. }
  3402. }
  3403. void GdbEngine::handleMakeSnapshot(const GdbResponse &response)
  3404. {
  3405. if (response.resultClass == GdbResultDone) {
  3406. DebuggerStartParameters sp = startParameters();
  3407. sp.startMode = AttachCore;
  3408. sp.coreFile = response.cookie.toString();
  3409. //snapshot.setDate(QDateTime::currentDateTime());
  3410. StackFrames frames = stackHandler()->frames();
  3411. QString function = _("<unknown>");
  3412. if (!frames.isEmpty()) {
  3413. const StackFrame &frame = frames.at(0);
  3414. function = frame.function + _(":") + QString::number(frame.line);
  3415. }
  3416. sp.displayName = function + _(": ") + QDateTime::currentDateTime().toString();
  3417. sp.isSnapshot = true;
  3418. DebuggerRunControl *rc = DebuggerPlugin::createDebugger(sp);
  3419. DebuggerPlugin::startDebugger(rc);
  3420. } else {
  3421. QByteArray msg = response.data.findChild("msg").data();
  3422. showMessageBox(QMessageBox::Critical, tr("Snapshot Creation Error"),
  3423. tr("Cannot create snapshot:\n") + QString::fromLocal8Bit(msg));
  3424. }
  3425. }
  3426. //////////////////////////////////////////////////////////////////////
  3427. //
  3428. // Register specific stuff
  3429. //
  3430. //////////////////////////////////////////////////////////////////////
  3431. void GdbEngine::reloadRegisters()
  3432. {
  3433. if (!debuggerCore()->isDockVisible(_(Constants::DOCKWIDGET_REGISTER)))
  3434. return;
  3435. if (state() != InferiorStopOk && state() != InferiorUnrunnable)
  3436. return;
  3437. if (!m_registerNamesListed) {
  3438. postCommand("-data-list-register-names", CB(handleRegisterListNames));
  3439. m_registerNamesListed = true;
  3440. // FIXME: Maybe better completely re-do this logic in CODA adapter.
  3441. if (isCodaAdapter())
  3442. return;
  3443. }
  3444. if (isCodaAdapter()) {
  3445. codaReloadRegisters();
  3446. } else {
  3447. postCommand("-data-list-register-values r",
  3448. Discardable, CB(handleRegisterListValues));
  3449. }
  3450. }
  3451. void GdbEngine::setRegisterValue(int nr, const QString &value)
  3452. {
  3453. Register reg = registerHandler()->registers().at(nr);
  3454. postCommand("set $" + reg.name + "=" + value.toLatin1());
  3455. reloadRegisters();
  3456. }
  3457. void GdbEngine::handleRegisterListNames(const GdbResponse &response)
  3458. {
  3459. if (response.resultClass != GdbResultDone) {
  3460. m_registerNamesListed = false;
  3461. return;
  3462. }
  3463. Registers registers;
  3464. foreach (const GdbMi &item, response.data.findChild("register-names").children())
  3465. if (!item.data().isEmpty())
  3466. registers.append(Register(item.data()));
  3467. registerHandler()->setRegisters(registers);
  3468. if (isCodaAdapter())
  3469. codaReloadRegisters();
  3470. }
  3471. void GdbEngine::handleRegisterListValues(const GdbResponse &response)
  3472. {
  3473. if (response.resultClass != GdbResultDone)
  3474. return;
  3475. Registers registers = registerHandler()->registers();
  3476. const int registerCount = registers.size();
  3477. // 24^done,register-values=[{number="0",value="0xf423f"},...]
  3478. const GdbMi values = response.data.findChild("register-values");
  3479. QTC_ASSERT(registerCount == values.children().size(), return);
  3480. foreach (const GdbMi &item, values.children()) {
  3481. const int number = item.findChild("number").data().toInt();
  3482. if (number >= 0 && number < registerCount)
  3483. registers[number].value = item.findChild("value").data();
  3484. }
  3485. registerHandler()->setAndMarkRegisters(registers);
  3486. }
  3487. //////////////////////////////////////////////////////////////////////
  3488. //
  3489. // Thread specific stuff
  3490. //
  3491. //////////////////////////////////////////////////////////////////////
  3492. bool GdbEngine::supportsThreads() const
  3493. {
  3494. // FSF gdb 6.3 crashes happily on -thread-list-ids. So don't use it.
  3495. // The test below is a semi-random pick, 6.8 works fine
  3496. return m_isMacGdb || m_gdbVersion > 60500;
  3497. }
  3498. //////////////////////////////////////////////////////////////////////
  3499. //
  3500. // Tooltip specific stuff
  3501. //
  3502. //////////////////////////////////////////////////////////////////////
  3503. void GdbEngine::showToolTip()
  3504. {
  3505. if (m_toolTipContext.isNull())
  3506. return;
  3507. const QString expression = m_toolTipContext->expression;
  3508. const QByteArray iname = tooltipIName(m_toolTipContext->expression);
  3509. if (DebuggerToolTipManager::debug())
  3510. qDebug() << "GdbEngine::showToolTip " << expression << iname << (*m_toolTipContext);
  3511. if (!debuggerCore()->boolSetting(UseToolTipsInMainEditor)) {
  3512. watchHandler()->removeData(iname);
  3513. return;
  3514. }
  3515. if (!watchHandler()->isValidToolTip(iname)) {
  3516. watchHandler()->removeData(iname);
  3517. return;
  3518. }
  3519. DebuggerToolTipWidget *tw = new DebuggerToolTipWidget;
  3520. tw->setDebuggerModel(TooltipType);
  3521. tw->setExpression(expression);
  3522. tw->setContext(*m_toolTipContext);
  3523. tw->acquireEngine(this);
  3524. DebuggerToolTipManager::instance()->showToolTip(m_toolTipContext->mousePosition,
  3525. m_toolTipContext->editor, tw);
  3526. // Prevent tooltip from re-occurring (classic GDB, QTCREATORBUG-4711).
  3527. m_toolTipContext.reset();
  3528. }
  3529. QString GdbEngine::tooltipExpression() const
  3530. {
  3531. return m_toolTipContext.isNull() ? QString() : m_toolTipContext->expression;
  3532. }
  3533. void GdbEngine::clearToolTip()
  3534. {
  3535. m_toolTipContext.reset();
  3536. }
  3537. bool GdbEngine::setToolTipExpression(const QPoint &mousePos,
  3538. TextEditor::ITextEditor *editor, const DebuggerToolTipContext &contextIn)
  3539. {
  3540. if (state() != InferiorStopOk || !isCppEditor(editor)) {
  3541. //qDebug() << "SUPPRESSING DEBUGGER TOOLTIP, INFERIOR NOT STOPPED "
  3542. // " OR NOT A CPPEDITOR";
  3543. return false;
  3544. }
  3545. DebuggerToolTipContext context = contextIn;
  3546. int line, column;
  3547. QString exp = cppExpressionAt(editor, context.position, &line, &column, &context.function);
  3548. if (DebuggerToolTipManager::debug())
  3549. qDebug() << "GdbEngine::setToolTipExpression1 " << exp << context;
  3550. if (exp.isEmpty())
  3551. return false;
  3552. // Extract the first identifier, everything else is considered
  3553. // too dangerous.
  3554. int pos1 = 0, pos2 = exp.size();
  3555. bool inId = false;
  3556. for (int i = 0; i != exp.size(); ++i) {
  3557. const QChar c = exp.at(i);
  3558. const bool isIdChar = c.isLetterOrNumber() || c.unicode() == '_';
  3559. if (inId && !isIdChar) {
  3560. pos2 = i;
  3561. break;
  3562. }
  3563. if (!inId && isIdChar) {
  3564. inId = true;
  3565. pos1 = i;
  3566. }
  3567. }
  3568. exp = exp.mid(pos1, pos2 - pos1);
  3569. if (exp.isEmpty() || exp.startsWith(QLatin1Char('#')) || !hasLetterOrNumber(exp) || isKeyWord(exp))
  3570. return false;
  3571. if (exp.startsWith(QLatin1Char('"')) && exp.endsWith(QLatin1Char('"')))
  3572. return false;
  3573. if (exp.startsWith(QLatin1String("++")) || exp.startsWith(QLatin1String("--")))
  3574. exp = exp.mid(2);
  3575. if (exp.endsWith(QLatin1String("++")) || exp.endsWith(QLatin1String("--")))
  3576. exp = exp.mid(2);
  3577. if (exp.startsWith(QLatin1Char('<')) || exp.startsWith(QLatin1Char('[')))
  3578. return false;
  3579. if (hasSideEffects(exp) || exp.isEmpty())
  3580. return false;
  3581. if (!m_toolTipContext.isNull() && m_toolTipContext->expression == exp) {
  3582. showToolTip();
  3583. return true;
  3584. }
  3585. m_toolTipContext.reset(new GdbToolTipContext(context));
  3586. m_toolTipContext->mousePosition = mousePos;
  3587. m_toolTipContext->expression = exp;
  3588. m_toolTipContext->editor = editor;
  3589. if (DebuggerToolTipManager::debug())
  3590. qDebug() << "GdbEngine::setToolTipExpression2 " << exp << (*m_toolTipContext);
  3591. if (isSynchronous()) {
  3592. UpdateParameters params;
  3593. params.tryPartial = true;
  3594. params.tooltipOnly = true;
  3595. params.varList = tooltipIName(exp);
  3596. updateLocalsPython(params);
  3597. } else {
  3598. WatchData toolTip;
  3599. toolTip.exp = exp.toLatin1();
  3600. toolTip.name = exp;
  3601. toolTip.iname = tooltipIName(exp);
  3602. watchHandler()->insertData(toolTip);
  3603. }
  3604. return true;
  3605. }
  3606. //////////////////////////////////////////////////////////////////////
  3607. //
  3608. // Watch specific stuff
  3609. //
  3610. //////////////////////////////////////////////////////////////////////
  3611. void GdbEngine::reloadLocals()
  3612. {
  3613. setTokenBarrier();
  3614. updateLocals();
  3615. }
  3616. bool GdbEngine::hasDebuggingHelperForType(const QByteArray &type) const
  3617. {
  3618. if (!debuggerCore()->boolSetting(UseDebuggingHelpers))
  3619. return false;
  3620. if (dumperHandling() == DumperNotAvailable) {
  3621. // Inferior calls are not possible in gdb when looking at core files.
  3622. return type == "QString" || type.endsWith("::QString")
  3623. || type == "QStringList" || type.endsWith("::QStringList");
  3624. }
  3625. if (m_debuggingHelperState != DebuggingHelperAvailable)
  3626. return false;
  3627. // Simple types.
  3628. return m_dumperHelper.type(type) != DumperHelper::UnknownType;
  3629. }
  3630. void GdbEngine::updateWatchData(const WatchData &data, const WatchUpdateFlags &flags)
  3631. {
  3632. if (isSynchronous()) {
  3633. // This should only be called for fresh expanded items, not for
  3634. // items that had their children retrieved earlier.
  3635. //qDebug() << "\nUPDATE WATCH DATA: " << data.toString() << "\n";
  3636. if (data.iname.endsWith("."))
  3637. return;
  3638. // Avoid endless loops created by faulty dumpers.
  3639. QByteArray processedName = "1-" + data.iname;
  3640. //qDebug() << "PROCESSED NAMES: " << processedName << m_processedNames;
  3641. if (m_processedNames.contains(processedName)) {
  3642. WatchData data1 = data;
  3643. showMessage(_("<Breaking endless loop for " + data.iname + '>'),
  3644. LogMiscInput);
  3645. data1.setAllUnneeded();
  3646. data1.setValue(_("<unavailable>"));
  3647. data1.setHasChildren(false);
  3648. insertData(data1);
  3649. return;
  3650. }
  3651. m_processedNames.insert(processedName);
  3652. // FIXME: Is this sufficient when "external" changes are
  3653. // triggered e.g. by manually entered command in the gdb console?
  3654. //qDebug() << "TRY PARTIAL: " << flags.tryIncremental
  3655. // << hasPython()
  3656. // << (m_pendingBreakpointRequests == 0);
  3657. UpdateParameters params;
  3658. params.tooltipOnly = data.iname.startsWith("tooltip");
  3659. params.tryPartial = flags.tryIncremental
  3660. && hasPython()
  3661. && m_pendingBreakpointRequests == 0;
  3662. params.varList = data.iname;
  3663. updateLocalsPython(params);
  3664. } else {
  3665. PENDING_DEBUG("UPDATE WATCH BUMPS PENDING UP TO " << m_uncompleted.size());
  3666. updateSubItemClassic(data);
  3667. }
  3668. }
  3669. void GdbEngine::rebuildWatchModel()
  3670. {
  3671. QTC_CHECK(m_completed.isEmpty());
  3672. QTC_CHECK(m_uncompleted.isEmpty());
  3673. static int count = 0;
  3674. ++count;
  3675. if (!isSynchronous())
  3676. m_processedNames.clear();
  3677. PENDING_DEBUG("REBUILDING MODEL" << count);
  3678. if (debuggerCore()->boolSetting(LogTimeStamps))
  3679. showMessage(LogWindow::logTimeStamp(), LogMiscInput);
  3680. showMessage(_("<Rebuild Watchmodel %1>").arg(count), LogMiscInput);
  3681. showStatusMessage(tr("Finished retrieving data"), 400);
  3682. showToolTip();
  3683. handleAutoTests();
  3684. }
  3685. static QByteArray arrayFillCommand(const char *array, const QByteArray &params)
  3686. {
  3687. QString buf;
  3688. buf.sprintf("set {char[%d]} &%s = {", params.size(), array);
  3689. QByteArray encoded;
  3690. encoded.append(buf.toLocal8Bit());
  3691. const int size = params.size();
  3692. for (int i = 0; i != size; ++i) {
  3693. buf.sprintf("%d,", int(params[i]));
  3694. encoded.append(buf.toLocal8Bit());
  3695. }
  3696. encoded[encoded.size() - 1] = '}';
  3697. return encoded;
  3698. }
  3699. void GdbEngine::sendWatchParameters(const QByteArray &params0)
  3700. {
  3701. QByteArray params = params0;
  3702. params.append('\0');
  3703. const QByteArray inBufferCmd = arrayFillCommand("qDumpInBuffer", params);
  3704. params.replace('\0','!');
  3705. showMessage(QString::fromUtf8(params), LogMiscInput);
  3706. params.clear();
  3707. params.append('\0');
  3708. const QByteArray outBufferCmd = arrayFillCommand("qDumpOutBuffer", params);
  3709. postCommand(inBufferCmd);
  3710. postCommand(outBufferCmd);
  3711. }
  3712. void GdbEngine::handleVarAssign(const GdbResponse &)
  3713. {
  3714. // Everything might have changed, force re-evaluation.
  3715. setTokenBarrier();
  3716. updateLocals();
  3717. }
  3718. void GdbEngine::handleVarCreate(const GdbResponse &response)
  3719. {
  3720. WatchData data = response.cookie.value<WatchData>();
  3721. // Happens e.g. when we already issued a var-evaluate command.
  3722. if (!data.isValid())
  3723. return;
  3724. //qDebug() << "HANDLE VARIABLE CREATION:" << data.toString();
  3725. if (response.resultClass == GdbResultDone) {
  3726. data.variable = data.iname;
  3727. setWatchDataType(data, response.data.findChild("type"));
  3728. if (watchHandler()->isExpandedIName(data.iname)
  3729. && !response.data.findChild("children").isValid())
  3730. data.setChildrenNeeded();
  3731. else
  3732. data.setChildrenUnneeded();
  3733. setWatchDataChildCount(data, response.data.findChild("numchild"));
  3734. insertData(data);
  3735. } else {
  3736. data.setError(QString::fromLocal8Bit(response.data.findChild("msg").data()));
  3737. if (data.isWatcher()) {
  3738. data.value = WatchData::msgNotInScope();
  3739. data.type = " ";
  3740. data.setAllUnneeded();
  3741. data.setHasChildren(false);
  3742. data.valueEnabled = false;
  3743. data.valueEditable = false;
  3744. insertData(data);
  3745. }
  3746. }
  3747. }
  3748. void GdbEngine::handleDebuggingHelperSetup(const GdbResponse &response)
  3749. {
  3750. if (response.resultClass == GdbResultDone) {
  3751. } else {
  3752. QString msg = QString::fromLocal8Bit(response.data.findChild("msg").data());
  3753. showStatusMessage(tr("Custom dumper setup: %1").arg(msg), 10000);
  3754. }
  3755. }
  3756. void GdbEngine::updateLocals()
  3757. {
  3758. if (hasPython())
  3759. updateLocalsPython(UpdateParameters());
  3760. else
  3761. updateLocalsClassic();
  3762. }
  3763. // Parse a local variable from GdbMi.
  3764. WatchData GdbEngine::localVariable(const GdbMi &item,
  3765. const QStringList &uninitializedVariables,
  3766. QMap<QByteArray, int> *seen)
  3767. {
  3768. // Local variables of inlined code are reported as
  3769. // 26^done,locals={varobj={exp="this",value="",name="var4",exp="this",
  3770. // numchild="1",type="const QtSharedPointer::Basic<CPlusPlus::..."}}
  3771. // We do not want these at all. Current hypotheses is that those
  3772. // "spurious" locals have _two_ "exp" field. Try to filter them:
  3773. QByteArray name;
  3774. if (m_isMacGdb) {
  3775. int numExps = 0;
  3776. foreach (const GdbMi &child, item.children())
  3777. numExps += int(child.name() == "exp");
  3778. if (numExps > 1)
  3779. return WatchData();
  3780. name = item.findChild("exp").data();
  3781. } else {
  3782. name = item.findChild("name").data();
  3783. }
  3784. const QMap<QByteArray, int>::iterator it = seen->find(name);
  3785. if (it != seen->end()) {
  3786. const int n = it.value();
  3787. ++(it.value());
  3788. WatchData data;
  3789. QString nam = _(name);
  3790. data.iname = "local." + name + QByteArray::number(n + 1);
  3791. data.name = WatchData::shadowedName(nam, n);
  3792. if (uninitializedVariables.contains(data.name)) {
  3793. data.setError(WatchData::msgNotInScope());
  3794. return data;
  3795. }
  3796. setWatchDataValue(data, item);
  3797. //: Type of local variable or parameter shadowed by another
  3798. //: variable of the same name in a nested block.
  3799. data.setType(GdbEngine::tr("<shadowed>").toUtf8());
  3800. data.setHasChildren(false);
  3801. return data;
  3802. }
  3803. seen->insert(name, 1);
  3804. WatchData data;
  3805. QString nam = _(name);
  3806. data.iname = "local." + name;
  3807. data.name = nam;
  3808. data.exp = name;
  3809. setWatchDataType(data, item.findChild("type"));
  3810. if (uninitializedVariables.contains(data.name)) {
  3811. data.setError(WatchData::msgNotInScope());
  3812. return data;
  3813. }
  3814. if (isSynchronous()) {
  3815. setWatchDataValue(data, item);
  3816. // We know that the complete list of children is
  3817. // somewhere in the response.
  3818. data.setChildrenUnneeded();
  3819. } else {
  3820. // Set value only directly if it is simple enough, otherwise
  3821. // pass through the insertData() machinery.
  3822. if (isIntOrFloatType(data.type) || isPointerType(data.type))
  3823. setWatchDataValue(data, item);
  3824. if (isSymbianIntType(data.type)) {
  3825. setWatchDataValue(data, item);
  3826. data.setHasChildren(false);
  3827. }
  3828. }
  3829. if (!watchHandler()->isExpandedIName(data.iname))
  3830. data.setChildrenUnneeded();
  3831. GdbMi t = item.findChild("numchild");
  3832. if (t.isValid())
  3833. data.setHasChildren(t.data().toInt() > 0);
  3834. else if (isPointerType(data.type) || data.name == QLatin1String("this"))
  3835. data.setHasChildren(true);
  3836. return data;
  3837. }
  3838. void GdbEngine::insertData(const WatchData &data)
  3839. {
  3840. PENDING_DEBUG("INSERT DATA" << data.toString());
  3841. if (data.isSomethingNeeded()) {
  3842. m_uncompleted.insert(data.iname);
  3843. WatchUpdateFlags flags;
  3844. flags.tryIncremental = true;
  3845. updateWatchData(data, flags);
  3846. } else {
  3847. m_completed.append(data);
  3848. m_uncompleted.remove(data.iname);
  3849. if (m_uncompleted.isEmpty()) {
  3850. watchHandler()->insertData(m_completed);
  3851. m_completed.clear();
  3852. rebuildWatchModel();
  3853. }
  3854. }
  3855. }
  3856. void GdbEngine::assignValueInDebugger(const WatchData *data,
  3857. const QString &expression, const QVariant &value)
  3858. {
  3859. if (hasPython() && !isIntOrFloatType(data->type)) {
  3860. QByteArray cmd = "bbedit "
  3861. + data->type.toHex() + ','
  3862. + expression.toUtf8().toHex() + ','
  3863. + value.toString().toUtf8().toHex();
  3864. postCommand(cmd, Discardable, CB(handleVarAssign));
  3865. } else {
  3866. postCommand("-var-delete assign");
  3867. postCommand("-var-create assign * " + expression.toLatin1());
  3868. postCommand("-var-assign assign " +
  3869. GdbMi::escapeCString(value.toString().toLatin1()),
  3870. Discardable, CB(handleVarAssign));
  3871. }
  3872. }
  3873. void GdbEngine::watchPoint(const QPoint &pnt)
  3874. {
  3875. QByteArray x = QByteArray::number(pnt.x());
  3876. QByteArray y = QByteArray::number(pnt.y());
  3877. postCommand("print '" + qtNamespace() + "QApplication::widgetAt'("
  3878. + x + ',' + y + ')',
  3879. NeedsStop, CB(handleWatchPoint));
  3880. }
  3881. void GdbEngine::handleWatchPoint(const GdbResponse &response)
  3882. {
  3883. if (response.resultClass == GdbResultDone) {
  3884. // "$5 = (void *) 0xbfa7ebfc\n"
  3885. const QByteArray ba = parsePlainConsoleStream(response);
  3886. //qDebug() << "BA: " << ba;
  3887. const int posWidget = ba.indexOf("QWidget");
  3888. const int pos0x = ba.indexOf("0x", posWidget + 7);
  3889. if (posWidget == -1 || pos0x == -1) {
  3890. showStatusMessage(tr("Cannot read widget data: %1").arg(_(ba)));
  3891. } else {
  3892. const QByteArray addr = ba.mid(pos0x);
  3893. if (addr.toULongLong(0, 0)) { // Non-null pointer
  3894. const QByteArray ns = qtNamespace();
  3895. const QByteArray type = ns.isEmpty() ? "QWidget*"
  3896. : QByteArray("'" + ns + "QWidget'*");
  3897. const QString exp = _("(*(struct %1)%2)").arg(_(type)).arg(_(addr));
  3898. // qDebug() << posNs << posWidget << pos0x << addr << ns << type;
  3899. watchHandler()->watchExpression(exp);
  3900. } else {
  3901. showStatusMessage(tr("Could not find a widget."));
  3902. }
  3903. }
  3904. }
  3905. }
  3906. class MemoryAgentCookie
  3907. {
  3908. public:
  3909. MemoryAgentCookie() : agent(0), token(0), address(0) {}
  3910. MemoryAgentCookie(MemoryAgent *agent_, QObject *token_, quint64 address_)
  3911. : agent(agent_), token(token_), address(address_)
  3912. {}
  3913. public:
  3914. QPointer<MemoryAgent> agent;
  3915. QPointer<QObject> token;
  3916. quint64 address;
  3917. };
  3918. void GdbEngine::changeMemory(MemoryAgent *agent, QObject *token,
  3919. quint64 addr, const QByteArray &data)
  3920. {
  3921. QByteArray cmd = "-data-write-memory " + QByteArray::number(addr) + " d 1";
  3922. foreach (unsigned char c, data) {
  3923. cmd.append(' ');
  3924. cmd.append(QByteArray::number(uint(c)));
  3925. }
  3926. postCommand(cmd, NeedsStop, CB(handleChangeMemory),
  3927. QVariant::fromValue(MemoryAgentCookie(agent, token, addr)));
  3928. }
  3929. void GdbEngine::handleChangeMemory(const GdbResponse &response)
  3930. {
  3931. Q_UNUSED(response);
  3932. }
  3933. void GdbEngine::fetchMemory(MemoryAgent *agent, QObject *token, quint64 addr,
  3934. quint64 length)
  3935. {
  3936. postCommand("-data-read-memory " + QByteArray::number(addr) + " x 1 1 "
  3937. + QByteArray::number(length),
  3938. NeedsStop, CB(handleFetchMemory),
  3939. QVariant::fromValue(MemoryAgentCookie(agent, token, addr)));
  3940. }
  3941. void GdbEngine::handleFetchMemory(const GdbResponse &response)
  3942. {
  3943. // ^done,addr="0x08910c88",nr-bytes="16",total-bytes="16",
  3944. // next-row="0x08910c98",prev-row="0x08910c78",next-page="0x08910c98",
  3945. // prev-page="0x08910c78",memory=[{addr="0x08910c88",
  3946. // data=["1","0","0","0","5","0","0","0","0","0","0","0","0","0","0","0"]}]
  3947. MemoryAgentCookie ac = response.cookie.value<MemoryAgentCookie>();
  3948. QTC_ASSERT(ac.agent, return);
  3949. QByteArray ba;
  3950. GdbMi memory = response.data.findChild("memory");
  3951. QTC_ASSERT(memory.children().size() <= 1, return);
  3952. if (memory.children().isEmpty())
  3953. return;
  3954. GdbMi memory0 = memory.children().at(0); // we asked for only one 'row'
  3955. GdbMi data = memory0.findChild("data");
  3956. foreach (const GdbMi &child, data.children()) {
  3957. bool ok = true;
  3958. unsigned char c = '?';
  3959. c = child.data().toUInt(&ok, 0);
  3960. QTC_ASSERT(ok, return);
  3961. ba.append(c);
  3962. }
  3963. ac.agent->addLazyData(ac.token, ac.address, ba);
  3964. }
  3965. class DisassemblerAgentCookie
  3966. {
  3967. public:
  3968. DisassemblerAgentCookie() : agent(0) {}
  3969. DisassemblerAgentCookie(DisassemblerAgent *agent_) : agent(agent_) {}
  3970. public:
  3971. QPointer<DisassemblerAgent> agent;
  3972. };
  3973. void GdbEngine::fetchDisassembler(DisassemblerAgent *agent)
  3974. {
  3975. // As of 7.2 the MI output is often less informative then the CLI version.
  3976. // So globally fall back to CLI.
  3977. if (agent->isMixed())
  3978. fetchDisassemblerByCliPointMixed(agent);
  3979. else
  3980. fetchDisassemblerByCliPointPlain(agent);
  3981. #if 0
  3982. if (agent->isMixed())
  3983. fetchDisassemblerByMiRangeMixed(agent)
  3984. else
  3985. fetchDisassemblerByMiRangePlain(agent);
  3986. #endif
  3987. }
  3988. #if 0
  3989. void GdbEngine::fetchDisassemblerByMiRangePlain(const DisassemblerAgentCookie &ac0)
  3990. {
  3991. // Disassemble full function:
  3992. const StackFrame &frame = agent->frame();
  3993. DisassemblerAgentCookie ac = ac0;
  3994. QTC_ASSERT(ac.agent, return);
  3995. const quint64 address = ac.agent->address();
  3996. QByteArray cmd = "-data-disassemble"
  3997. " -f " + frame.file.toLocal8Bit() +
  3998. " -l " + QByteArray::number(frame.line) + " -n -1 -- 1";
  3999. postCommand(cmd, Discardable, CB(handleFetchDisassemblerByMiPointMixed),
  4000. QVariant::fromValue(DisassemblerAgentCookie(agent)));
  4001. }
  4002. #endif
  4003. #if 0
  4004. void GdbEngine::fetchDisassemblerByMiRangeMixed(const DisassemblerAgentCookie &ac0)
  4005. {
  4006. DisassemblerAgentCookie ac = ac0;
  4007. QTC_ASSERT(ac.agent, return);
  4008. const quint64 address = ac.agent->address();
  4009. QByteArray start = QByteArray::number(address - 20, 16);
  4010. QByteArray end = QByteArray::number(address + 100, 16);
  4011. // -data-disassemble [ -s start-addr -e end-addr ]
  4012. // | [ -f filename -l linenum [ -n lines ] ] -- mode
  4013. postCommand("-data-disassemble -s 0x" + start + " -e 0x" + end + " -- 1",
  4014. Discardable, CB(handleFetchDisassemblerByMiRangeMixed),
  4015. QVariant::fromValue(ac));
  4016. }
  4017. #endif
  4018. #if 0
  4019. void GdbEngine::fetchDisassemblerByMiRangePlain(const DisassemblerAgentCookie &ac0)
  4020. {
  4021. DisassemblerAgentCookie ac = ac0;
  4022. QTC_ASSERT(ac.agent, return);
  4023. const quint64 address = ac.agent->address();
  4024. QByteArray start = QByteArray::number(address - 20, 16);
  4025. QByteArray end = QByteArray::number(address + 100, 16);
  4026. // -data-disassemble [ -s start-addr -e end-addr ]
  4027. // | [ -f filename -l linenum [ -n lines ] ] -- mode
  4028. postCommand("-data-disassemble -s 0x" + start + " -e 0x" + end + " -- 0",
  4029. Discardable, CB(handleFetchDisassemblerByMiRangePlain),
  4030. QVariant::fromValue(ac));
  4031. }
  4032. #endif
  4033. static inline QByteArray disassemblerCommand(const Location &location, bool mixed)
  4034. {
  4035. QByteArray command = "disassemble ";
  4036. if (mixed)
  4037. command += "/m ";
  4038. if (const quint64 address = location.address()) {
  4039. command += "0x";
  4040. command += QByteArray::number(address, 16);
  4041. } else if (!location.functionName().isEmpty()) {
  4042. command += location.functionName().toLatin1();
  4043. } else {
  4044. QTC_ASSERT(false, return QByteArray(); );
  4045. }
  4046. return command;
  4047. }
  4048. void GdbEngine::fetchDisassemblerByCliPointMixed(const DisassemblerAgentCookie &ac0)
  4049. {
  4050. DisassemblerAgentCookie ac = ac0;
  4051. QTC_ASSERT(ac.agent, return);
  4052. postCommand(disassemblerCommand(ac.agent->location(), true), Discardable|ConsoleCommand,
  4053. CB(handleFetchDisassemblerByCliPointMixed),
  4054. QVariant::fromValue(ac));
  4055. }
  4056. void GdbEngine::fetchDisassemblerByCliPointPlain(const DisassemblerAgentCookie &ac0)
  4057. {
  4058. DisassemblerAgentCookie ac = ac0;
  4059. QTC_ASSERT(ac.agent, return);
  4060. postCommand(disassemblerCommand(ac.agent->location(), false), Discardable,
  4061. CB(handleFetchDisassemblerByCliPointPlain),
  4062. QVariant::fromValue(ac));
  4063. }
  4064. void GdbEngine::fetchDisassemblerByCliRangeMixed(const DisassemblerAgentCookie &ac0)
  4065. {
  4066. DisassemblerAgentCookie ac = ac0;
  4067. QTC_ASSERT(ac.agent, return);
  4068. const quint64 address = ac.agent->address();
  4069. QByteArray start = QByteArray::number(address - 20, 16);
  4070. QByteArray end = QByteArray::number(address + 100, 16);
  4071. const char sep = m_disassembleUsesComma ? ',' : ' ';
  4072. QByteArray cmd = "disassemble /m 0x" + start + sep + "0x" + end;
  4073. postCommand(cmd, Discardable|ConsoleCommand,
  4074. CB(handleFetchDisassemblerByCliRangeMixed), QVariant::fromValue(ac));
  4075. }
  4076. void GdbEngine::fetchDisassemblerByCliRangePlain(const DisassemblerAgentCookie &ac0)
  4077. {
  4078. DisassemblerAgentCookie ac = ac0;
  4079. QTC_ASSERT(ac.agent, return);
  4080. const quint64 address = ac.agent->address();
  4081. QByteArray start = QByteArray::number(address - 20, 16);
  4082. QByteArray end = QByteArray::number(address + 100, 16);
  4083. const char sep = m_disassembleUsesComma ? ',' : ' ';
  4084. QByteArray cmd = "disassemble 0x" + start + sep + "0x" + end;
  4085. postCommand(cmd, Discardable,
  4086. CB(handleFetchDisassemblerByCliRangePlain), QVariant::fromValue(ac));
  4087. }
  4088. static DisassemblerLine parseLine(const GdbMi &line)
  4089. {
  4090. DisassemblerLine dl;
  4091. QByteArray address = line.findChild("address").data();
  4092. dl.address = address.toULongLong(0, 0);
  4093. dl.data = _(line.findChild("inst").data());
  4094. dl.function = _(line.findChild("func-name").data());
  4095. dl.offset = line.findChild("offset").data().toUInt();
  4096. return dl;
  4097. }
  4098. DisassemblerLines GdbEngine::parseMiDisassembler(const GdbMi &lines)
  4099. {
  4100. // ^done,data={asm_insns=[src_and_asm_line={line="1243",file=".../app.cpp",
  4101. // line_asm_insn=[{address="0x08054857",func-name="main",offset="27",
  4102. // inst="call 0x80545b0 <_Z13testQFileInfov>"}]},
  4103. // src_and_asm_line={line="1244",file=".../app.cpp",
  4104. // line_asm_insn=[{address="0x0805485c",func-name="main",offset="32",
  4105. //inst="call 0x804cba1 <_Z11testObject1v>"}]}]}
  4106. // - or - (non-Mac)
  4107. // ^done,asm_insns=[
  4108. // {address="0x0805acf8",func-name="...",offset="25",inst="and $0xe8,%al"},
  4109. // {address="0x0805acfa",func-name="...",offset="27",inst="pop %esp"}, ..]
  4110. // - or - (MAC)
  4111. // ^done,asm_insns={
  4112. // {address="0x0d8f69e0",func-name="...",offset="1952",inst="add $0x0,%al"},..}
  4113. DisassemblerLines result;
  4114. // FIXME: Performance?
  4115. foreach (const GdbMi &child, lines.children()) {
  4116. if (child.hasName("src_and_asm_line")) {
  4117. const QString fileName = QFile::decodeName(child.findChild("file").data());
  4118. const uint line = child.findChild("line").data().toUInt();
  4119. result.appendSourceLine(fileName, line);
  4120. GdbMi insn = child.findChild("line_asm_insn");
  4121. foreach (const GdbMi &item, insn.children())
  4122. result.appendLine(parseLine(item));
  4123. } else {
  4124. // The non-mixed version.
  4125. result.appendLine(parseLine(child));
  4126. }
  4127. }
  4128. return result;
  4129. }
  4130. DisassemblerLines GdbEngine::parseCliDisassembler(const QByteArray &output)
  4131. {
  4132. // First line is something like
  4133. // "Dump of assembler code from 0xb7ff598f to 0xb7ff5a07:"
  4134. DisassemblerLines dlines;
  4135. foreach (const QByteArray &line, output.split('\n'))
  4136. dlines.appendUnparsed(_(line));
  4137. return dlines;
  4138. }
  4139. DisassemblerLines GdbEngine::parseDisassembler(const GdbResponse &response)
  4140. {
  4141. // Apple's gdb produces MI output even for CLI commands.
  4142. // FIXME: Check whether wrapping this into -interpreter-exec console
  4143. // (i.e. usgind the 'ConsoleCommand' GdbCommandFlag makes a
  4144. // difference.
  4145. GdbMi lines = response.data.findChild("asm_insns");
  4146. if (lines.isValid())
  4147. return parseMiDisassembler(lines);
  4148. return parseCliDisassembler(response.consoleStreamOutput);
  4149. }
  4150. void GdbEngine::handleDisassemblerCheck(const GdbResponse &response)
  4151. {
  4152. m_disassembleUsesComma = response.resultClass != GdbResultDone;
  4153. }
  4154. void GdbEngine::handleFetchDisassemblerByCliPointMixed(const GdbResponse &response)
  4155. {
  4156. DisassemblerAgentCookie ac = response.cookie.value<DisassemblerAgentCookie>();
  4157. QTC_ASSERT(ac.agent, return);
  4158. if (response.resultClass == GdbResultDone) {
  4159. DisassemblerLines dlines = parseDisassembler(response);
  4160. if (dlines.coversAddress(ac.agent->address())) {
  4161. ac.agent->setContents(dlines);
  4162. return;
  4163. }
  4164. }
  4165. fetchDisassemblerByCliPointPlain(ac);
  4166. }
  4167. void GdbEngine::handleFetchDisassemblerByCliPointPlain(const GdbResponse &response)
  4168. {
  4169. DisassemblerAgentCookie ac = response.cookie.value<DisassemblerAgentCookie>();
  4170. QTC_ASSERT(ac.agent, return);
  4171. // Agent address is 0 when disassembling a function name only
  4172. const quint64 agentAddress = ac.agent->address();
  4173. if (response.resultClass == GdbResultDone) {
  4174. DisassemblerLines dlines = parseDisassembler(response);
  4175. if (!agentAddress || dlines.coversAddress(agentAddress)) {
  4176. ac.agent->setContents(dlines);
  4177. return;
  4178. }
  4179. }
  4180. if (agentAddress) {
  4181. if (ac.agent->isMixed())
  4182. fetchDisassemblerByCliRangeMixed(ac);
  4183. else
  4184. fetchDisassemblerByCliRangePlain(ac);
  4185. }
  4186. }
  4187. void GdbEngine::handleFetchDisassemblerByCliRangeMixed(const GdbResponse &response)
  4188. {
  4189. DisassemblerAgentCookie ac = response.cookie.value<DisassemblerAgentCookie>();
  4190. QTC_ASSERT(ac.agent, return);
  4191. if (response.resultClass == GdbResultDone) {
  4192. DisassemblerLines dlines = parseDisassembler(response);
  4193. if (dlines.coversAddress(ac.agent->address())) {
  4194. ac.agent->setContents(dlines);
  4195. return;
  4196. }
  4197. }
  4198. fetchDisassemblerByCliRangePlain(ac);
  4199. }
  4200. void GdbEngine::handleFetchDisassemblerByCliRangePlain(const GdbResponse &response)
  4201. {
  4202. DisassemblerAgentCookie ac = response.cookie.value<DisassemblerAgentCookie>();
  4203. QTC_ASSERT(ac.agent, return);
  4204. if (response.resultClass == GdbResultDone) {
  4205. DisassemblerLines dlines = parseDisassembler(response);
  4206. if (dlines.size()) {
  4207. ac.agent->setContents(dlines);
  4208. return;
  4209. }
  4210. }
  4211. // Finally, give up.
  4212. //76^error,msg="No function contains program counter for selected..."
  4213. //76^error,msg="No function contains specified address."
  4214. //>568^error,msg="Line number 0 out of range;
  4215. QByteArray msg = response.data.findChild("msg").data();
  4216. showStatusMessage(tr("Disassembler failed: %1")
  4217. .arg(QString::fromLocal8Bit(msg)), 5000);
  4218. }
  4219. // Binary/configuration check logic.
  4220. static QString gdbBinary(const DebuggerStartParameters &sp)
  4221. {
  4222. // 1) Environment.
  4223. const QByteArray envBinary = qgetenv("QTC_DEBUGGER_PATH");
  4224. if (!envBinary.isEmpty())
  4225. return QString::fromLocal8Bit(envBinary);
  4226. // 2) Command from profile.
  4227. return sp.debuggerCommand;
  4228. }
  4229. bool checkGdbConfiguration(const DebuggerStartParameters &sp, ConfigurationCheck *check)
  4230. {
  4231. const QString binary = gdbBinary(sp);
  4232. const Abi abi = sp.toolChainAbi;
  4233. if (binary.isEmpty()) {
  4234. check->errorDetails.push_back(msgNoGdbBinaryForToolChain(abi));
  4235. check->settingsCategory = _(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY);
  4236. check->settingsPage = _(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY);
  4237. return false;
  4238. }
  4239. if (abi.os() == Abi::WindowsOS && !QFileInfo(binary).isAbsolute()) {
  4240. // See initialization below, we need an absolute path to be able to locate Python on Windows.
  4241. check->errorDetails.push_back(GdbEngine::tr("The gdb location must be given as an "
  4242. "absolute path in the debugger settings (%1).").arg(binary));
  4243. check->settingsCategory = _(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY);
  4244. check->settingsPage = _(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY);
  4245. return false;
  4246. }
  4247. return true;
  4248. }
  4249. //
  4250. // Starting up & shutting down
  4251. //
  4252. void GdbEngine::startGdb(const QStringList &args)
  4253. {
  4254. const QByteArray tests = qgetenv("QTC_DEBUGGER_TESTS");
  4255. foreach (const QByteArray &test, tests.split(','))
  4256. m_testCases.insert(test.toInt());
  4257. foreach (int test, m_testCases)
  4258. showMessage(_("ENABLING TEST CASE: " + QByteArray::number(test)));
  4259. gdbProc()->disconnect(); // From any previous runs
  4260. const DebuggerStartParameters &sp = startParameters();
  4261. m_gdb = gdbBinary(sp);
  4262. if (m_gdb.isEmpty()) {
  4263. handleGdbStartFailed();
  4264. handleAdapterStartFailed(
  4265. msgNoGdbBinaryForToolChain(sp.toolChainAbi),
  4266. _(Constants::DEBUGGER_COMMON_SETTINGS_ID));
  4267. return;
  4268. }
  4269. QStringList gdbArgs;
  4270. gdbArgs << _("-i");
  4271. gdbArgs << _("mi");
  4272. if (!debuggerCore()->boolSetting(LoadGdbInit))
  4273. gdbArgs << _("-n");
  4274. gdbArgs += args;
  4275. connect(gdbProc(), SIGNAL(error(QProcess::ProcessError)),
  4276. SLOT(handleGdbError(QProcess::ProcessError)));
  4277. connect(gdbProc(), SIGNAL(finished(int,QProcess::ExitStatus)),
  4278. SLOT(handleGdbFinished(int,QProcess::ExitStatus)));
  4279. connect(gdbProc(), SIGNAL(readyReadStandardOutput()),
  4280. SLOT(readGdbStandardOutput()));
  4281. connect(gdbProc(), SIGNAL(readyReadStandardError()),
  4282. SLOT(readGdbStandardError()));
  4283. showMessage(_("STARTING ") + m_gdb + _(" ") + gdbArgs.join(_(" ")));
  4284. gdbProc()->start(m_gdb, gdbArgs);
  4285. if (!gdbProc()->waitForStarted()) {
  4286. handleGdbStartFailed();
  4287. const QString msg = errorMessage(QProcess::FailedToStart);
  4288. handleAdapterStartFailed(msg);
  4289. return;
  4290. }
  4291. showMessage(_("GDB STARTED, INITIALIZING IT"));
  4292. postCommand("show version", CB(handleShowVersion));
  4293. //postCommand("-list-features", CB(handleListFeatures));
  4294. postCommand("show debug-file-directory", CB(handleDebugInfoLocation));
  4295. //postCommand("-enable-timings");
  4296. //postCommand("set print static-members off"); // Seemingly doesn't work.
  4297. //postCommand("set debug infrun 1");
  4298. //postCommand("define hook-stop\n-thread-list-ids\n-stack-list-frames\nend");
  4299. //postCommand("define hook-stop\nprint 4\nend");
  4300. //postCommand("define hookpost-stop\nprint 5\nend");
  4301. //postCommand("define hook-call\nprint 6\nend");
  4302. //postCommand("define hookpost-call\nprint 7\nend");
  4303. postCommand("set print object on");
  4304. //postCommand("set step-mode on"); // we can't work with that yes
  4305. //postCommand("set exec-done-display on");
  4306. //postCommand("set print pretty on");
  4307. //postCommand("set confirm off");
  4308. //postCommand("set pagination off");
  4309. // The following does not work with 6.3.50-20050815 (Apple version gdb-1344)
  4310. // (Mac OS 10.6), but does so for gdb-966 (10.5):
  4311. //postCommand("set print inferior-events 1");
  4312. postCommand("set breakpoint pending on");
  4313. postCommand("set print elements 10000");
  4314. // Produces a few messages during symtab loading
  4315. //postCommand("set verbose on");
  4316. //postCommand("set substitute-path /var/tmp/qt-x11-src-4.5.0 "
  4317. // "/home/sandbox/qtsdk-2009.01/qt");
  4318. // one of the following is needed to prevent crashes in gdb on code like:
  4319. // template <class T> T foo() { return T(0); }
  4320. // int main() { return foo<int>(); }
  4321. // (gdb) call 'int foo<int>'()
  4322. // /build/buildd/gdb-6.8/gdb/valops.c:2069: internal-error:
  4323. postCommand("set overload-resolution off");
  4324. //postCommand(_("set demangle-style none"));
  4325. // From the docs:
  4326. // Stop means reenter debugger if this signal happens (implies print).
  4327. // Print means print a message if this signal happens.
  4328. // Pass means let program see this signal;
  4329. // otherwise program doesn't know.
  4330. // Pass and Stop may be combined.
  4331. // We need "print" as otherwise we will get no feedback whatsoever
  4332. // when Custom DebuggingHelper crash (which happen regularly when accessing
  4333. // uninitialized variables).
  4334. postCommand("handle SIGSEGV nopass stop print");
  4335. // This is useful to kill the inferior whenever gdb dies.
  4336. //postCommand(_("handle SIGTERM pass nostop print"));
  4337. postCommand("set unwindonsignal on");
  4338. postCommand("set width 0");
  4339. postCommand("set height 0");
  4340. postCommand("set breakpoint always-inserted on", ConsoleCommand);
  4341. // displaced-stepping does not work in Thumb mode.
  4342. //postCommand("set displaced-stepping on");
  4343. postCommand("set trust-readonly-sections on", ConsoleCommand);
  4344. postCommand("set remotecache on", ConsoleCommand);
  4345. //postCommand("set non-stop on", ConsoleCommand);
  4346. // Work around https://bugreports.qt-project.org/browse/QTCREATORBUG-2004
  4347. postCommand("maintenance set internal-warning quit no", ConsoleCommand);
  4348. postCommand("maintenance set internal-error quit no", ConsoleCommand);
  4349. showMessage(_("THE FOLLOWING COMMAND CHECKS AVAILABLE FEATURES. "
  4350. "AN ERROR IS EXPECTED."));
  4351. postCommand("disassemble 0 0", ConsoleCommand, CB(handleDisassemblerCheck));
  4352. typedef GlobalDebuggerOptions::SourcePathMap SourcePathMap;
  4353. typedef SourcePathMap::const_iterator SourcePathMapIterator;
  4354. if (debuggerCore()->boolSetting(WarnOnReleaseBuilds))
  4355. checkForReleaseBuild();
  4356. showStatusMessage(tr("Setting up inferior..."));
  4357. // Addint executable to modules list.
  4358. Module module;
  4359. module.startAddress = 0;
  4360. module.endAddress = 0;
  4361. module.modulePath = sp.executable;
  4362. module.moduleName = QLatin1String("<executable>");
  4363. modulesHandler()->updateModule(module);
  4364. // Apply source path mappings from global options.
  4365. const SourcePathMap sourcePathMap =
  4366. DebuggerSourcePathMappingWidget::mergePlatformQtPath(sp.qtInstallPath,
  4367. debuggerCore()->globalDebuggerOptions()->sourcePathMap);
  4368. const SourcePathMapIterator cend = sourcePathMap.constEnd();
  4369. SourcePathMapIterator it = sourcePathMap.constBegin();
  4370. for ( ; it != cend; ++it)
  4371. postCommand("set substitute-path " + it.key().toLocal8Bit()
  4372. + " " + it.value().toLocal8Bit());
  4373. // Spaces just will not work.
  4374. foreach (const QString &src, sp.debugSourceLocation)
  4375. postCommand("directory " + src.toLocal8Bit());
  4376. const QByteArray sysroot = sp.sysRoot.toLocal8Bit();
  4377. if (!sysroot.isEmpty()) {
  4378. postCommand("set sysroot " + sysroot);
  4379. // sysroot is not enough to correctly locate the sources, so explicitly
  4380. // relocate the most likely place for the debug source
  4381. postCommand("set substitute-path /usr/src " + sysroot + "/usr/src");
  4382. }
  4383. //QByteArray ba = QFileInfo(sp.dumperLibrary).path().toLocal8Bit();
  4384. //if (!ba.isEmpty())
  4385. // postCommand("set solib-search-path " + ba);
  4386. if (attemptQuickStart()) {
  4387. postCommand("set auto-solib-add off", ConsoleCommand);
  4388. } else {
  4389. m_fullStartDone = true;
  4390. postCommand("set auto-solib-add on", ConsoleCommand);
  4391. loadPythonDumpers();
  4392. }
  4393. // Dummy command to guarantee a roundtrip before the adapter proceed.
  4394. postCommand("pwd", ConsoleCommand, CB(reportEngineSetupOk));
  4395. }
  4396. void GdbEngine::reportEngineSetupOk(const GdbResponse &response)
  4397. {
  4398. Q_UNUSED(response);
  4399. QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
  4400. showMessage(_("ENGINE SUCCESSFULLY STARTED"));
  4401. notifyEngineSetupOk();
  4402. }
  4403. void GdbEngine::handleGdbStartFailed()
  4404. {
  4405. }
  4406. void GdbEngine::loadInitScript()
  4407. {
  4408. const QString script = startParameters().overrideStartScript;
  4409. if (!script.isEmpty()) {
  4410. if (QFileInfo(script).isReadable()) {
  4411. postCommand("source " + script.toLocal8Bit());
  4412. } else {
  4413. showMessageBox(QMessageBox::Warning,
  4414. tr("Cannot find debugger initialization script"),
  4415. tr("The debugger settings point to a script file at '%1' "
  4416. "which is not accessible. If a script file is not needed, "
  4417. "consider clearing that entry to avoid this warning. "
  4418. ).arg(script));
  4419. }
  4420. } else {
  4421. const QString commands = debuggerCore()->stringSetting(GdbStartupCommands);
  4422. if (!commands.isEmpty())
  4423. postCommand(commands.toLocal8Bit());
  4424. }
  4425. }
  4426. void GdbEngine::loadPythonDumpers()
  4427. {
  4428. if (m_forceAsyncModel)
  4429. return;
  4430. const QByteArray dumperSourcePath =
  4431. Core::ICore::resourcePath().toLocal8Bit() + "/dumper/";
  4432. postCommand("python execfile('" + dumperSourcePath + "bridge.py')",
  4433. ConsoleCommand|NonCriticalResponse);
  4434. postCommand("python execfile('" + dumperSourcePath + "dumper.py')",
  4435. ConsoleCommand|NonCriticalResponse);
  4436. postCommand("python execfile('" + dumperSourcePath + "qttypes.py')",
  4437. ConsoleCommand|NonCriticalResponse);
  4438. loadInitScript();
  4439. postCommand("bbsetup", ConsoleCommand, CB(handleHasPython));
  4440. }
  4441. void GdbEngine::handleGdbError(QProcess::ProcessError error)
  4442. {
  4443. const QString msg = errorMessage(error);
  4444. showMessage(_("HANDLE GDB ERROR: ") + msg);
  4445. // Show a message box for asynchronously reported issues.
  4446. switch (error) {
  4447. case QProcess::FailedToStart:
  4448. // This should be handled by the code trying to start the process.
  4449. break;
  4450. case QProcess::Crashed:
  4451. // This will get a processExited() as well.
  4452. break;
  4453. case QProcess::ReadError:
  4454. case QProcess::WriteError:
  4455. case QProcess::Timedout:
  4456. default:
  4457. //gdbProc()->kill();
  4458. //notifyEngineIll();
  4459. showMessageBox(QMessageBox::Critical, tr("GDB I/O Error"), msg);
  4460. break;
  4461. }
  4462. }
  4463. void GdbEngine::handleGdbFinished(int code, QProcess::ExitStatus type)
  4464. {
  4465. if (m_commandTimer.isActive())
  4466. m_commandTimer.stop();
  4467. showMessage(_("GDB PROCESS FINISHED, status %1, code %2").arg(type).arg(code));
  4468. switch (state()) {
  4469. case EngineShutdownRequested:
  4470. notifyEngineShutdownOk();
  4471. break;
  4472. case InferiorRunOk:
  4473. // This could either be a real gdb crash or a quickly exited inferior
  4474. // in the terminal adapter. In this case the stub proc will die soon,
  4475. // too, so there's no need to act here.
  4476. showMessage(_("The gdb process exited somewhat unexpectedly."));
  4477. notifyEngineSpontaneousShutdown();
  4478. break;
  4479. default: {
  4480. notifyEngineIll(); // Initiate shutdown sequence
  4481. const QString msg = type == QProcess::CrashExit ?
  4482. tr("The gdb process terminated.") :
  4483. tr("The gdb process terminated unexpectedly (code %1)").arg(code);
  4484. showMessageBox(QMessageBox::Critical, tr("Unexpected GDB Exit"), msg);
  4485. break;
  4486. }
  4487. }
  4488. }
  4489. void GdbEngine::abortDebugger()
  4490. {
  4491. if (targetState() == DebuggerFinished) {
  4492. // We already tried. Try harder.
  4493. showMessage(_("ABORTING DEBUGGER. SECOND TIME."));
  4494. QTC_ASSERT(gdbProc(), return);
  4495. gdbProc()->kill();
  4496. } else {
  4497. // Be friendly the first time. This will change targetState().
  4498. showMessage(_("ABORTING DEBUGGER. FIRST TIME."));
  4499. quitDebugger();
  4500. }
  4501. }
  4502. void GdbEngine::handleAdapterStartFailed(const QString &msg,
  4503. const QString &settingsIdHint)
  4504. {
  4505. QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
  4506. showMessage(_("ADAPTER START FAILED"));
  4507. if (!msg.isEmpty()) {
  4508. const QString title = tr("Adapter start failed");
  4509. if (settingsIdHint.isEmpty()) {
  4510. Core::ICore::showWarningWithOptions(title, msg);
  4511. } else {
  4512. Core::ICore::showWarningWithOptions(title, msg, QString(),
  4513. _(Debugger::Constants::DEBUGGER_SETTINGS_CATEGORY), settingsIdHint);
  4514. }
  4515. }
  4516. notifyEngineSetupFailed();
  4517. }
  4518. void GdbEngine::notifyInferiorSetupFailed()
  4519. {
  4520. // FIXME: that's not enough to stop gdb from getting confused
  4521. // by a timeout of the adapter.
  4522. //resetCommandQueue();
  4523. DebuggerEngine::notifyInferiorSetupFailed();
  4524. }
  4525. void GdbEngine::handleInferiorPrepared()
  4526. {
  4527. const DebuggerStartParameters &sp = startParameters();
  4528. QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
  4529. if (sp.breakOnMain) {
  4530. QByteArray cmd = "tbreak ";
  4531. cmd += sp.toolChainAbi.os() == Abi::WindowsOS ? "qMain" : "main";
  4532. postCommand(cmd);
  4533. }
  4534. // Initial attempt to set breakpoints.
  4535. if (sp.startMode != AttachCore) {
  4536. showStatusMessage(tr("Setting breakpoints..."));
  4537. showMessage(tr("Setting breakpoints..."));
  4538. attemptBreakpointSynchronization();
  4539. }
  4540. if (m_cookieForToken.isEmpty()) {
  4541. finishInferiorSetup();
  4542. } else {
  4543. QTC_CHECK(m_commandsDoneCallback == 0);
  4544. m_commandsDoneCallback = &GdbEngine::finishInferiorSetup;
  4545. }
  4546. }
  4547. void GdbEngine::finishInferiorSetup()
  4548. {
  4549. QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
  4550. // Extract Qt namespace.
  4551. QString fileName;
  4552. {
  4553. QTemporaryFile symbols(QDir::tempPath() + _("/gdb_ns_"));
  4554. symbols.open();
  4555. fileName = symbols.fileName();
  4556. }
  4557. postCommand("maint print msymbols " + fileName.toLocal8Bit(),
  4558. CB(handleNamespaceExtraction), fileName);
  4559. }
  4560. void GdbEngine::handleDebugInfoLocation(const GdbResponse &response)
  4561. {
  4562. #ifdef Q_OS_WIN
  4563. const char pathSep = ';';
  4564. #else
  4565. const char pathSep = ':';
  4566. #endif
  4567. if (response.resultClass == GdbResultDone) {
  4568. const QByteArray debugInfoLocation = startParameters().debugInfoLocation.toLocal8Bit();
  4569. if (QFile::exists(QString::fromLocal8Bit(debugInfoLocation))) {
  4570. const QByteArray curDebugInfoLocations = response.consoleStreamOutput.split('"').value(1);
  4571. if (curDebugInfoLocations.isEmpty())
  4572. postCommand("set debug-file-directory " + debugInfoLocation);
  4573. else
  4574. postCommand("set debug-file-directory " + debugInfoLocation + pathSep + curDebugInfoLocations);
  4575. }
  4576. }
  4577. }
  4578. void GdbEngine::handleNamespaceExtraction(const GdbResponse &response)
  4579. {
  4580. QFile file(response.cookie.toString());
  4581. file.open(QIODevice::ReadOnly);
  4582. QByteArray ba = file.readAll();
  4583. file.close();
  4584. file.remove();
  4585. int pos = ba.indexOf("7QString9fromAscii");
  4586. int pos1 = pos - 1;
  4587. while (pos1 > 0 && ba.at(pos1) != 'N' && ba.at(pos1) > '@')
  4588. --pos1;
  4589. ++pos1;
  4590. const QByteArray ns = ba.mid(pos1, pos - pos1);
  4591. if (ns.isEmpty()) {
  4592. showMessage(_("FOUND NON-NAMESPACED QT"));
  4593. } else {
  4594. showMessage(_("FOUND NAMESPACED QT: " + ns));
  4595. setQtNamespace(ns + "::");
  4596. }
  4597. if (startParameters().startMode == AttachCore) {
  4598. notifyInferiorSetupOk(); // No breakpoints in core files.
  4599. } else {
  4600. if (debuggerCore()->boolSetting(BreakOnAbort))
  4601. postCommand("-break-insert -f abort");
  4602. if (debuggerCore()->boolSetting(BreakOnWarning))
  4603. postCommand("-break-insert -f '" + qtNamespace() + "qWarning'");
  4604. if (debuggerCore()->boolSetting(BreakOnFatal))
  4605. postCommand("-break-insert -f '" + qtNamespace() + "qFatal'",
  4606. CB(handleBreakOnQFatal));
  4607. else
  4608. notifyInferiorSetupOk();
  4609. }
  4610. }
  4611. void GdbEngine::handleBreakOnQFatal(const GdbResponse &response)
  4612. {
  4613. if (response.resultClass == GdbResultDone) {
  4614. GdbMi bkpt = response.data.findChild("bkpt");
  4615. GdbMi number = bkpt.findChild("number");
  4616. BreakpointResponseId rid(number.data());
  4617. if (rid.isValid()) {
  4618. m_qFatalBreakpointResponseId = rid;
  4619. postCommand("-break-commands " + number.data() + " return");
  4620. }
  4621. }
  4622. // Continue setup.
  4623. notifyInferiorSetupOk();
  4624. }
  4625. void GdbEngine::notifyInferiorSetupFailed(const QString &msg)
  4626. {
  4627. showStatusMessage(tr("Failed to start application: ") + msg);
  4628. if (state() == EngineSetupFailed) {
  4629. showMessage(_("INFERIOR START FAILED, BUT ADAPTER DIED ALREADY"));
  4630. return; // Adapter crashed meanwhile, so this notification is meaningless.
  4631. }
  4632. showMessage(_("INFERIOR START FAILED"));
  4633. showMessageBox(QMessageBox::Critical, tr("Failed to start application"), msg);
  4634. DebuggerEngine::notifyInferiorSetupFailed();
  4635. }
  4636. void GdbEngine::handleAdapterCrashed(const QString &msg)
  4637. {
  4638. showMessage(_("ADAPTER CRASHED"));
  4639. // The adapter is expected to have cleaned up after itself when we get here,
  4640. // so the effect is about the same as AdapterStartFailed => use it.
  4641. // Don't bother with state transitions - this can happen in any state and
  4642. // the end result is always the same, so it makes little sense to find a
  4643. // "path" which does not assert.
  4644. if (state() == EngineSetupRequested)
  4645. notifyEngineSetupFailed();
  4646. else
  4647. notifyEngineIll();
  4648. // No point in being friendly here ...
  4649. gdbProc()->kill();
  4650. if (!msg.isEmpty())
  4651. showMessageBox(QMessageBox::Critical, tr("Adapter crashed"), msg);
  4652. }
  4653. bool GdbEngine::hasPython() const
  4654. {
  4655. return m_hasPython;
  4656. }
  4657. void GdbEngine::createFullBacktrace()
  4658. {
  4659. postCommand("thread apply all bt full",
  4660. NeedsStop|ConsoleCommand, CB(handleCreateFullBacktrace));
  4661. }
  4662. void GdbEngine::handleCreateFullBacktrace(const GdbResponse &response)
  4663. {
  4664. if (response.resultClass == GdbResultDone) {
  4665. debuggerCore()->openTextEditor(_("Backtrace $"),
  4666. _(response.consoleStreamOutput + response.logStreamOutput));
  4667. }
  4668. }
  4669. void GdbEngine::resetCommandQueue()
  4670. {
  4671. m_commandTimer.stop();
  4672. if (!m_cookieForToken.isEmpty()) {
  4673. QString msg;
  4674. QTextStream ts(&msg);
  4675. ts << "RESETING COMMAND QUEUE. LEFT OVER TOKENS: ";
  4676. foreach (const GdbCommand &cookie, m_cookieForToken)
  4677. ts << "CMD:" << cookie.command << cookie.callbackName;
  4678. m_cookieForToken.clear();
  4679. showMessage(msg);
  4680. }
  4681. }
  4682. bool GdbEngine::setupQmlStep(bool on)
  4683. {
  4684. QTC_ASSERT(isSlaveEngine(), return false);
  4685. m_qmlBreakpointResponseId1 = BreakpointResponseId();
  4686. m_qmlBreakpointResponseId2 = BreakpointResponseId();
  4687. //qDebug() << "CLEAR: " << m_qmlBreakpointNumbers;
  4688. postCommand("tbreak '" + qtNamespace() + "QScript::FunctionWrapper::proxyCall'\n"
  4689. "commands\n"
  4690. "set $d=(void*)((FunctionWrapper*)callee)->data->function\n"
  4691. "tbreak *$d\nprintf \"QMLBP:%d \\n\",$bpnum\ncontinue\nend",
  4692. NeedsStop, CB(handleSetQmlStepBreakpoint));
  4693. m_preparedForQmlBreak = on;
  4694. return true;
  4695. }
  4696. void GdbEngine::handleSetQmlStepBreakpoint(const GdbResponse &response)
  4697. {
  4698. //QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
  4699. if (response.resultClass == GdbResultDone) {
  4700. // logStreamOutput: "tbreak 'myns::QScript::FunctionWrapper::proxyCall'\n"
  4701. // consoleStreamOutput: "Temporary breakpoint 1 at 0xf166e7:
  4702. // file bridge/qscriptfunction.cpp, line 75.\n"}
  4703. QByteArray ba = parsePlainConsoleStream(response);
  4704. const int pos2 = ba.indexOf(" at 0x");
  4705. const int pos1 = ba.lastIndexOf(" ", pos2 - 1) + 1;
  4706. QByteArray mid = ba.mid(pos1, pos2 - pos1);
  4707. m_qmlBreakpointResponseId1 = BreakpointResponseId(mid);
  4708. //qDebug() << "SET: " << m_qmlBreakpointResponseId1;
  4709. }
  4710. QTC_ASSERT(masterEngine(), return);
  4711. masterEngine()->readyToExecuteQmlStep();
  4712. }
  4713. bool GdbEngine::isQmlStepBreakpoint(const BreakpointResponseId &id) const
  4714. {
  4715. return isQmlStepBreakpoint1(id) || isQmlStepBreakpoint2(id);
  4716. }
  4717. bool GdbEngine::isQmlStepBreakpoint1(const BreakpointResponseId &id) const
  4718. {
  4719. return id.isValid() && m_qmlBreakpointResponseId1 == id;
  4720. }
  4721. bool GdbEngine::isQmlStepBreakpoint2(const BreakpointResponseId &id) const
  4722. {
  4723. return id.isValid() && m_qmlBreakpointResponseId2 == id;
  4724. }
  4725. bool GdbEngine::isQFatalBreakpoint(const BreakpointResponseId &id) const
  4726. {
  4727. return id.isValid() && m_qFatalBreakpointResponseId == id;
  4728. }
  4729. bool GdbEngine::isHiddenBreakpoint(const BreakpointResponseId &id) const
  4730. {
  4731. return isQFatalBreakpoint(id) || isQmlStepBreakpoint(id);
  4732. }
  4733. bool GdbEngine::usesExecInterrupt() const
  4734. {
  4735. if (m_gdbVersion < 70000)
  4736. return false;
  4737. // debuggerCore()->boolSetting(TargetAsync)
  4738. DebuggerStartMode mode = startParameters().startMode;
  4739. return (mode == AttachToRemoteServer || mode == AttachToRemoteProcess)
  4740. && debuggerCore()->boolSetting(TargetAsync);
  4741. }
  4742. void GdbEngine::scheduleTestResponse(int testCase, const QByteArray &response)
  4743. {
  4744. if (!m_testCases.contains(testCase) && startParameters().testCase != testCase)
  4745. return;
  4746. int token = currentToken() + 1;
  4747. showMessage(_("SCHEDULING TEST RESPONSE (CASE: %1, TOKEN: %2, RESPONSE: '%3')")
  4748. .arg(testCase).arg(token).arg(_(response)));
  4749. m_scheduledTestResponses[token] = response;
  4750. }
  4751. void GdbEngine::requestDebugInformation(const DebugInfoTask &task)
  4752. {
  4753. QProcess::startDetached(task.command);
  4754. }
  4755. bool GdbEngine::attemptQuickStart() const
  4756. {
  4757. if (m_forceAsyncModel)
  4758. return false;
  4759. // Don't try if the user does not ask for it.
  4760. if (!debuggerCore()->boolSetting(AttemptQuickStart))
  4761. return false;
  4762. // Don't try if there are breakpoints we might be able to handle.
  4763. BreakHandler *handler = breakHandler();
  4764. foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {
  4765. if (acceptsBreakpoint(id))
  4766. return false;
  4767. }
  4768. return true;
  4769. }
  4770. void GdbEngine::checkForReleaseBuild()
  4771. {
  4772. QString binary = startParameters().executable;
  4773. ElfReader reader(binary);
  4774. ElfData elfData = reader.readHeaders();
  4775. QString error = reader.errorString();
  4776. showMessage(_("EXAMINING ") + binary);
  4777. QByteArray msg = "ELF SECTIONS: ";
  4778. static QList<QByteArray> interesting;
  4779. if (interesting.isEmpty()) {
  4780. interesting.append(".debug_info");
  4781. interesting.append(".debug_abbrev");
  4782. interesting.append(".debug_line");
  4783. interesting.append(".debug_str");
  4784. interesting.append(".debug_loc");
  4785. interesting.append(".debug_range");
  4786. interesting.append(".gdb_index");
  4787. interesting.append(".note.gnu.build-id");
  4788. interesting.append(".gnu.hash");
  4789. interesting.append(".gnu_debuglink");
  4790. }
  4791. QSet<QByteArray> seen;
  4792. foreach (const ElfSectionHeader &header, elfData.sectionHeaders) {
  4793. msg.append(header.name);
  4794. msg.append(' ');
  4795. if (interesting.contains(header.name))
  4796. seen.insert(header.name);
  4797. }
  4798. showMessage(_(msg));
  4799. if (!error.isEmpty()) {
  4800. showMessage(_("ERROR WHILE READING ELF SECTIONS: ") + error);
  4801. return;
  4802. }
  4803. if (elfData.sectionHeaders.isEmpty()) {
  4804. showMessage(_("NO SECTION HEADERS FOUND. IS THIS AN EXECUTABLE?"));
  4805. return;
  4806. }
  4807. // Note: .note.gnu.build-id also appears in regular release builds.
  4808. // bool hasBuildId = elfData.indexOf(".note.gnu.build-id") >= 0;
  4809. bool hasEmbeddedInfo = elfData.indexOf(".debug_info") >= 0;
  4810. bool hasLink = elfData.indexOf(".gnu_debuglink") >= 0;
  4811. if (hasEmbeddedInfo || hasLink)
  4812. return;
  4813. QString warning;
  4814. warning = tr("This does not seem to be a \"Debug\" build.\n"
  4815. "Setting breakpoints by file name and line number may fail.\n");
  4816. foreach (const QByteArray &name, interesting) {
  4817. QString found = seen.contains(name) ? tr("Found.") : tr("Not Found.");
  4818. warning.append(tr("\nSection %1: %2").arg(_(name)).arg(found));
  4819. }
  4820. showMessageBox(QMessageBox::Information, tr("Warning"), warning);
  4821. }
  4822. void GdbEngine::write(const QByteArray &data)
  4823. {
  4824. gdbProc()->write(data);
  4825. }
  4826. bool GdbEngine::isCodaAdapter() const
  4827. {
  4828. return false;
  4829. }
  4830. bool GdbEngine::prepareCommand()
  4831. {
  4832. #ifdef Q_OS_WIN
  4833. Utils::QtcProcess::SplitError perr;
  4834. startParameters().processArgs = Utils::QtcProcess::prepareArgs(
  4835. startParameters().processArgs, &perr,
  4836. &startParameters().environment, &startParameters().workingDirectory);
  4837. if (perr != Utils::QtcProcess::SplitOk) {
  4838. // perr == BadQuoting is never returned on Windows
  4839. // FIXME? QTCREATORBUG-2809
  4840. handleAdapterStartFailed(QCoreApplication::translate("DebuggerEngine", // Same message in CdbEngine
  4841. "Debugging complex command lines is currently not supported on Windows."), QString());
  4842. return false;
  4843. }
  4844. #endif
  4845. return true;
  4846. }
  4847. QString GdbEngine::msgGdbStopFailed(const QString &why)
  4848. {
  4849. return tr("The gdb process could not be stopped:\n%1").arg(why);
  4850. }
  4851. QString GdbEngine::msgInferiorStopFailed(const QString &why)
  4852. {
  4853. return tr("Application process could not be stopped:\n%1").arg(why);
  4854. }
  4855. QString GdbEngine::msgInferiorSetupOk()
  4856. {
  4857. return tr("Application started");
  4858. }
  4859. QString GdbEngine::msgInferiorRunOk()
  4860. {
  4861. return tr("Application running");
  4862. }
  4863. QString GdbEngine::msgAttachedToStoppedInferior()
  4864. {
  4865. return tr("Attached to stopped application");
  4866. }
  4867. QString GdbEngine::msgConnectRemoteServerFailed(const QString &why)
  4868. {
  4869. return tr("Connecting to remote server failed:\n%1").arg(why);
  4870. }
  4871. void GdbEngine::interruptLocalInferior(qint64 pid)
  4872. {
  4873. QTC_ASSERT(state() == InferiorStopRequested, qDebug() << state(); return);
  4874. if (pid <= 0) {
  4875. showMessage(QLatin1String("TRYING TO INTERRUPT INFERIOR BEFORE PID WAS OBTAINED"), LogError);
  4876. return;
  4877. }
  4878. QString errorMessage;
  4879. if (interruptProcess(pid, GdbEngineType, &errorMessage)) {
  4880. showMessage(QLatin1String("Interrupted ") + QString::number(pid));
  4881. } else {
  4882. showMessage(errorMessage, LogError);
  4883. notifyInferiorStopFailed();
  4884. }
  4885. }
  4886. //
  4887. // Factory
  4888. //
  4889. DebuggerEngine *createGdbEngine(const DebuggerStartParameters &sp,
  4890. DebuggerEngine *masterEngine)
  4891. {
  4892. if (sp.toolChainAbi.os() == Abi::SymbianOS) {
  4893. // FIXME: 1 of 3 testing hacks.
  4894. return new GdbCodaEngine(sp, masterEngine);
  4895. }
  4896. switch (sp.startMode) {
  4897. case AttachCore:
  4898. return new GdbCoreEngine(sp, masterEngine);
  4899. case AttachToRemoteServer:
  4900. return new GdbRemoteServerEngine(sp, masterEngine);
  4901. case StartRemoteGdb:
  4902. return new GdbRemotePlainEngine(sp, masterEngine);
  4903. case AttachExternal:
  4904. return new GdbAttachEngine(sp, masterEngine);
  4905. default:
  4906. if (sp.useTerminal)
  4907. return new GdbTermEngine(sp, masterEngine);
  4908. return new GdbLocalPlainEngine(sp, masterEngine);
  4909. }
  4910. }
  4911. void addGdbOptionPages(QList<Core::IOptionsPage *> *opts)
  4912. {
  4913. opts->push_back(new GdbOptionsPage());
  4914. }
  4915. } // namespace Internal
  4916. } // namespace Debugger
  4917. Q_DECLARE_METATYPE(Debugger::Internal::MemoryAgentCookie)
  4918. Q_DECLARE_METATYPE(Debugger::Internal::DisassemblerAgentCookie)
  4919. Q_DECLARE_METATYPE(Debugger::Internal::GdbMi)