Commit c2eada27 authored by hjk's avatar hjk

Debugger: Fix Window grabbing on GDB

Needs to make namespace detection work without valid frame

Task-number: QTCREATORBUG-17326
Change-Id: Ia7c7017db4ef384d4f246e11a5601d01f4f366f1
Reviewed-by: default avatarhjk <hjk@qt.io>
parent 6c8d6c97
......@@ -33,6 +33,7 @@ import os
import os.path
import sys
import struct
import tempfile
import types
from dumper import *
......@@ -1023,27 +1024,21 @@ class Dumper(DumperBase):
for objfile in gdb.objfiles():
name = objfile.filename
if name.find('/libQt5Core') >= 0:
fd, tmppath = tempfile.mkstemp()
os.close(fd)
cmd = 'maint print msymbols %s "%s"' % (tmppath, name)
symbols = gdb.execute(cmd, to_string = True)
ns = ''
# This only works when called from a valid frame.
try:
cand = 'QArrayData::shared_null'
symbol = gdb.lookup_symbol(cand)[0]
if symbol:
ns = symbol.name[:-len(cand)]
except:
symbol = None
if symbol is None:
try:
# Some GDB 7.11.1 on Arch Linux.
cand = 'QArrayData::shared_null[0]'
val = gdb.parse_and_eval(cand)
if val.type is not None:
typeobj = val.type.unqualified()
ns = typeobj.name[:-len('QArrayData')]
except:
pass
with open(tmppath) as f:
for line in f:
if line.find('msgHandlerGrabbed ') >= 0:
# [11] b 0x7ffff683c000 _ZN4MynsL17msgHandlerGrabbedE
# section .tbss Myns::msgHandlerGrabbed qlogging.cpp
ns = re.split('_ZN(\d*)(\w*)L17msgHandlerGrabbedE ', line)[2]
if len(ns):
ns += '::'
break
os.remove(tmppath)
lenns = len(ns)
strns = ('%d%s' % (lenns - 2, ns[:lenns - 2])) if lenns else ''
......@@ -1054,10 +1049,7 @@ class Dumper(DumperBase):
sym = '_ZN7QObject11customEventEP6QEvent'
self.qtCustomEventFunc = self.findSymbol(sym)
if lenns:
sym = '_ZN%s7QObject11customEventEPNS_6QEventE@plt' % strns
else:
sym = '_ZN7QObject11customEventEP6QEvent@plt'
sym += '@plt'
self.qtCustomEventPltFunc = self.findSymbol(sym)
sym = '_ZNK7%sQObject8propertyEPKc' % strns
......@@ -1093,6 +1085,17 @@ class Dumper(DumperBase):
cmd = 'set variable (%s)=%s' % (expr, value)
gdb.execute(cmd)
def watchPoint(self, args):
ns = self.qtNamespace()
lenns = len(ns)
strns = ('%d%s' % (lenns - 2, ns[:lenns - 2])) if lenns else ''
sym = '_ZN%s12QApplication8widgetAtEii' % strns
expr = '%s(%s,%s)' % (sym, args['x'], args['y'])
res = self.parseAndEvaluate(expr)
p = 0 if res is None else res.pointer()
n = ("'%sQWidget'" % ns) if lenns else 'QWidget'
safePrint('{selected="0x%x",expr="(%s*)0x%x"}' % (p, n, p))
def nativeDynamicTypeName(self, address, baseType):
# Needed for Gdb13393 test.
nativeType = self.lookupNativeType(baseType.name)
......@@ -1361,7 +1364,6 @@ class Dumper(DumperBase):
def profile1(self, args):
'''Internal profiling'''
import tempfile
import cProfile
tempDir = tempfile.gettempdir() + '/bbprof'
cProfile.run('theDumper.fetchVariables(%s)' % args, tempDir)
......
......@@ -1646,7 +1646,7 @@ class Dumper(DumperBase):
result += ',data="%s %s"' % (insn.GetMnemonic(self.target),
insn.GetOperands(self.target))
result += ',function="%s"' % functionName
rawData = insn.GetData(lldb.target).uint8s
rawData = insn.GetData(self.target).uint8s
result += ',rawdata="%s"' % ' '.join(["%02x" % x for x in rawData])
if comment:
result += ',comment="%s"' % self.hexencode(comment)
......@@ -1678,6 +1678,20 @@ class Dumper(DumperBase):
lhs.SetValueFromCString(value, error)
self.reportResult(self.describeError(error), args)
def watchPoint(self, args):
self.reportToken(args)
ns = self.qtNamespace()
lenns = len(ns)
funcs = self.target.FindGlobalFunctions('.*QApplication::widgetAt', 2, 1)
func = funcs[1]
addr = func.GetFunction().GetStartAddress().GetLoadAddress(self.target)
expr = '((void*(*)(int,int))0x%x)' % addr
#expr = '%sQApplication::widgetAt(%s,%s)' % (ns, args['x'], args['y'])
res = self.parseAndEvaluate(expr)
p = 0 if res is None else res.pointer()
n = ns + 'QWidget'
self.reportResult('selected="0x%x",expr="(%s*)0x%x"' % (p, n, p), args)
def createResolvePendingBreakpointsHookBreakpoint(self, args):
bp = self.target.BreakpointCreateByName('qt_qmlDebugConnectorOpen')
bp.SetOneShot(True)
......
......@@ -75,6 +75,23 @@ private:
void argHelper(const char *name, const QByteArray &value);
};
class DebuggerCommandSequence
{
public:
DebuggerCommandSequence() {}
bool isEmpty() const { return m_commands.isEmpty(); }
bool wantContinue() const { return m_continue; }
const QList<DebuggerCommand> &commands() const { return m_commands; }
void append(const DebuggerCommand &cmd, bool wantContinue) {
m_commands.append(cmd);
m_continue = wantContinue;
}
public:
QList<DebuggerCommand> m_commands;
bool m_continue = false;
};
// FIXME: rename into GdbMiValue
class GdbMi
{
......
This diff is collapsed.
......@@ -44,6 +44,8 @@
#include <QTime>
#include <QTimer>
#include <functional>
namespace Debugger {
namespace Internal {
......@@ -151,11 +153,13 @@ private: ////////// Gdb Command Management //////////
enum GdbCommandFlag {
NoFlags = 0,
// The command needs a stopped inferior.
NeedsStop = 1,
NeedsTemporaryStop = 1,
// No need to wait for the reply before continuing inferior.
Discardable = 2,
// Needs a dummy extra command to force GDB output flushing.
NeedsFlush = 4,
// The command needs a stopped inferior and will stay stopped afterward.
NeedsFullStop = 8,
// Callback expects ResultRunning instead of ResultDone.
RunRequest = 16,
// Callback expects ResultExit instead of ResultDone.
......@@ -267,6 +271,7 @@ private: ////////// View & Data Stuff //////////
void selectThread(ThreadId threadId) override;
void activateFrame(int index) override;
void handleAutoContinueInferior();
//
// Breakpoint specific stuff
......@@ -378,7 +383,7 @@ protected:
void changeMemory(MemoryAgent *agent, quint64 addr, const QByteArray &data) override;
void handleFetchMemory(const DebuggerResponse &response, MemoryAgentCookie ac);
virtual void watchPoint(const QPoint &) override;
void watchPoint(const QPoint &) override;
void handleWatchPoint(const DebuggerResponse &response);
void showToolTip();
......@@ -420,10 +425,11 @@ protected:
QString m_lastWinException;
QString m_lastMissingDebugInfo;
bool m_terminalTrap;
bool m_temporaryStopPending;
bool usesExecInterrupt() const;
bool usesTargetAsync() const;
DebuggerCommandSequence m_onStop;
QHash<int, QString> m_scheduledTestResponses;
QSet<int> m_testCases;
......
......@@ -112,25 +112,34 @@ void LldbEngine::executeDebuggerCommand(const QString &command, DebuggerLanguage
runCommand(cmd);
}
void LldbEngine::runCommand(const DebuggerCommand &cmd)
void LldbEngine::runCommand(const DebuggerCommand &command)
{
if (m_lldbProc.state() != QProcess::Running) {
// This can legally happen e.g. through a reloadModule()
// triggered by changes in view visibility.
showMessage(QString("NO LLDB PROCESS RUNNING, CMD IGNORED: %1 %2")
.arg(cmd.function).arg(state()));
.arg(command.function).arg(state()));
return;
}
const int tok = ++currentToken();
DebuggerCommand command = cmd;
command.arg("token", tok);
DebuggerCommand cmd = command;
cmd.arg("token", tok);
QString token = QString::number(tok);
QString function = command.function + "(" + command.argsToPython() + ")";
QString function = cmd.function + "(" + cmd.argsToPython() + ")";
QString msg = token + function + '\n';
if (cmd.flags == LldbEngine::Silent)
if (cmd.flags == Silent)
msg.replace(QRegularExpression("\"environment\":.[^]]*."), "<environment suppressed>");
if (cmd.flags == NeedsFullStop) {
cmd.flags &= ~NeedsFullStop;
if (state() == InferiorRunOk) {
showStatusMessage(tr("Stopping temporarily"), 1000);
m_onStop.append(cmd, false);
requestInterruptInferior();
return;
}
}
showMessage(msg, LogInput);
m_commandForToken[currentToken()] = command;
m_commandForToken[currentToken()] = cmd;
m_lldbProc.write("script theDumper." + function.toUtf8() + "\n");
}
......@@ -139,6 +148,22 @@ void LldbEngine::debugLastCommand()
runCommand(m_lastDebuggableCommand);
}
void LldbEngine::watchPoint(const QPoint &pnt)
{
DebuggerCommand cmd("watchPoint", NeedsFullStop);
cmd.arg("x", pnt.x());
cmd.arg("y", pnt.y());
cmd.callback = [this](const DebuggerResponse &response) {
qulonglong addr = response.data["selected"].toAddress();
if (addr == 0)
showStatusMessage(tr("Could not find a widget."));
// Add the watcher entry nevertheless, as that's the place where
// the user expects visual feedback.
watchHandler()->watchExpression(response.data["expr"].data(), QString(), true);
};
runCommand(cmd);
}
void LldbEngine::shutdownInferior()
{
QTC_ASSERT(state() == InferiorShutdownRequested, qDebug() << state());
......@@ -907,11 +932,21 @@ void LldbEngine::handleStateNotification(const GdbMi &reportedState)
m_continueAtNextSpontaneousStop = true;
else if (newState == "stopped") {
notifyInferiorSpontaneousStop();
if (m_continueAtNextSpontaneousStop) {
m_continueAtNextSpontaneousStop = false;
continueInferior();
if (m_onStop.isEmpty()) {
if (m_continueAtNextSpontaneousStop) {
m_continueAtNextSpontaneousStop = false;
continueInferior();
} else {
updateAll();
}
} else {
updateAll();
showMessage("HANDLING QUEUED COMMANDS AFTER TEMPORARY STOP", LogMisc);
DebuggerCommandSequence seq = m_onStop;
m_onStop = DebuggerCommandSequence();
for (const DebuggerCommand &cmd : seq.commands())
runCommand(cmd);
if (seq.wantContinue())
continueInferior();
}
} else if (newState == "inferiorstopok") {
notifyInferiorStopOk();
......@@ -1098,8 +1133,8 @@ bool LldbEngine::hasCapability(unsigned cap) const
| CreateFullBacktraceCapability
| WatchpointByAddressCapability
| WatchpointByExpressionCapability
| AddWatcherCapability
| WatchWidgetsCapability
| AddWatcherCapability
| ShowModuleSymbolsCapability
| ShowModuleSectionsCapability
| CatchCapability
......
......@@ -64,7 +64,9 @@ public:
enum LldbCommandFlag {
NoFlags = 0,
// Do not echo to log.
Silent = 1
Silent = 1,
// The command needs a stopped inferior and will stay stopped afterward.
NeedsFullStop = 8,
};
signals:
......@@ -150,6 +152,9 @@ private:
void runCommand(const DebuggerCommand &cmd) override;
void debugLastCommand() override;
void watchPoint(const QPoint &) override;
void handleWatchPoint(const DebuggerResponse &response);
private:
DebuggerCommand m_lastDebuggableCommand;
......@@ -163,6 +168,7 @@ private:
QMap<QPointer<DisassemblerAgent>, int> m_disassemblerAgents;
QHash<int, DebuggerCommand> m_commandForToken;
DebuggerCommandSequence m_onStop;
// Console handling.
void stubError(const QString &msg);
......
......@@ -66,6 +66,7 @@
#include <QMimeData>
#include <QPainter>
#include <QProcess>
#include <QSet>
#include <QTabWidget>
#include <QTextEdit>
#include <QTableWidget>
......@@ -89,6 +90,7 @@ enum { debugModel = 0 };
#define MODEL_DEBUG(s) do { if (debugModel) qDebug() << s; } while (0)
static QMap<QString, int> theWatcherNames; // Keep order, QTCREATORBUG-12308.
static QSet<QString> theTemporaryWatchers; // Used for 'watched widgets'.
static int theWatcherCount = 0;
static QHash<QString, int> theTypeFormats;
static QHash<QString, int> theIndividualFormats;
......@@ -430,6 +432,11 @@ public:
void removeWatchItem(WatchItem *item);
void inputNewExpression();
void grabWidget();
void ungrabWidget();
void timerEvent(QTimerEvent *event) override;
int m_grabWidgetTimerId = -1;
public:
WatchHandler *m_handler; // Not owned.
DebuggerEngine *m_engine; // Not owned.
......@@ -446,7 +453,6 @@ public:
QSet<QString> m_expandedINames;
QTimer m_requestUpdateTimer;
bool m_grabbing = false;
QHash<QString, TypeInfo> m_reportedTypeInfo;
QHash<QString, DisplayFormats> m_reportedTypeFormats; // Type name -> Dumper Formats
......@@ -1067,13 +1073,6 @@ bool WatchModel::setData(const QModelIndex &idx, const QVariant &value, int role
return true;
}
if (ev.as<QMouseEvent>(QEvent::MouseButtonPress)) {
m_grabbing = false;
ev.view()->releaseMouse();
m_engine->watchPoint(ev.globalPos());
return true;
}
if (ev.as<QMouseEvent>(QEvent::MouseButtonDblClick)) {
if (item && !item->parent()) { // if item is the invisible root item
inputNewExpression();
......@@ -1268,6 +1267,46 @@ static QString variableToolTip(const QString &name, const QString &type, quint64
WatchModel::tr("<i>%1</i> %2").arg(type, name);
}
void WatchModel::grabWidget()
{
qApp->setOverrideCursor(Qt::CrossCursor);
m_grabWidgetTimerId = startTimer(30);
ICore::mainWindow()->grabMouse();
}
void WatchModel::timerEvent(QTimerEvent *event)
{
if (event->timerId() == m_grabWidgetTimerId) {
QPoint pnt = QCursor::pos();
Qt::KeyboardModifiers mods = QApplication::queryKeyboardModifiers();
QString msg;
if (mods == Qt::NoModifier) {
msg = tr("Press Ctrl to select widget at (%1, %2). "
"Press any other keyboard modifier to stop selection.")
.arg(pnt.x()).arg(pnt.y());
} else {
if (mods == Qt::CTRL) {
msg = tr("Selecting widget at (%1, %2).").arg(pnt.x()).arg(pnt.y());
m_engine->watchPoint(pnt);
} else {
msg = tr("Selection aborted.");
}
ungrabWidget();
}
showMessage(msg, StatusBar);
} else {
WatchModelBase::timerEvent(event);
}
}
void WatchModel::ungrabWidget()
{
ICore::mainWindow()->releaseMouse();
qApp->restoreOverrideCursor();
killTimer(m_grabWidgetTimerId);
m_grabWidgetTimerId = -1;
}
int WatchModel::memberVariableRecursion(WatchItem *item,
const QString &name,
quint64 start, quint64 end,
......@@ -1608,10 +1647,9 @@ bool WatchModel::contextMenuEvent(const ItemViewEvent &ev)
canRemoveWatches && !m_handler->watchedExpressions().isEmpty(),
[this] { clearWatches(); });
// FIXME:
// addAction(menu, tr("Select Widget to Add into Expression Evaluator"),
// canHandleWatches && canInsertWatches && m_engine->hasCapability(WatchWidgetsCapability),
// [this, ev] { ev.view()->grabMouse(Qt::CrossCursor); m_grabbing = true; });
addAction(menu, tr("Select Widget to Add into Expression Evaluator"),
state == InferiorRunOk && m_engine->hasCapability(WatchWidgetsCapability),
[this] { grabWidget(); });
menu->addSeparator();
menu->addMenu(createFormatMenu(item));
......@@ -1901,6 +1939,9 @@ void WatchHandler::cleanup()
{
m_model->m_expandedINames.clear();
theWatcherNames.remove(QString());
for (const QString &exp : theTemporaryWatchers)
theWatcherNames.remove(exp);
theTemporaryWatchers.clear();
saveWatchers();
m_model->reinitialize();
emit m_model->updateFinished();
......@@ -2080,13 +2121,15 @@ QString WatchHandler::watcherName(const QString &exp)
}
// If \a name is empty, \a exp will be used as name.
void WatchHandler::watchExpression(const QString &exp, const QString &name)
void WatchHandler::watchExpression(const QString &exp, const QString &name, bool temporary)
{
// Do not insert the same entry more then once.
if (exp.isEmpty() || theWatcherNames.contains(exp))
return;
theWatcherNames[exp] = theWatcherCount++;
if (temporary)
theTemporaryWatchers.insert(exp);
auto item = new WatchItem;
item->exp = exp;
......
......@@ -66,7 +66,9 @@ public:
WatchModelBase *model() const;
void cleanup();
void watchExpression(const QString &exp, const QString &name = QString());
void grabWidget(QWidget *viewParent);
void watchExpression(const QString &exp, const QString &name = QString(),
bool temporary = false);
void updateWatchExpression(WatchItem *item, const QString &newExp);
void watchVariable(const QString &exp);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment