Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qv4debugger.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant
4
5#include "qv4debugger.h"
6#include "qv4debugjob.h"
8
9#include <private/qqmlcontext_p.h>
10#include <private/qqmlengine_p.h>
11#include <private/qv4compileddata_p.h>
12#include <private/qv4debuginstructions_p.h>
13#include <private/qv4function_p.h>
14#include <private/qv4scopedvalue_p.h>
15#include <private/qv4script_p.h>
16#include <private/qv4stackframe_p.h>
17
18#include <algorithm>
19
20QT_BEGIN_NAMESPACE
21
22QV4Debugger::BreakPoint::BreakPoint(const QString &fileName, int line)
23 : fileName(fileName), lineNumber(line)
24{}
25
26inline size_t qHash(const QV4Debugger::BreakPoint &b, size_t seed = 0) noexcept
27{
28 return qHash(b.fileName, seed) ^ b.lineNumber;
29}
30
31inline bool operator==(const QV4Debugger::BreakPoint &a,
32 const QV4Debugger::BreakPoint &b)
33{
34 return a.lineNumber == b.lineNumber && a.fileName == b.fileName;
35}
36
37QV4Debugger::QV4Debugger(QV4::ExecutionEngine *engine)
39 , m_state(Running)
40 , m_stepping(NotStepping)
41 , m_pauseRequested(false)
42 , m_haveBreakPoints(false)
43 , m_breakOnThrow(false)
45 , m_gatherSources(nullptr)
46 , m_runningJob(nullptr)
48{
49 static int debuggerId = qRegisterMetaType<QV4Debugger*>();
50 static int pauseReasonId = qRegisterMetaType<QV4Debugger::PauseReason>();
51 Q_UNUSED(debuggerId);
52 Q_UNUSED(pauseReasonId);
53 connect(this, &QV4Debugger::scheduleJob,
54 this, &QV4Debugger::runJobUnpaused, Qt::QueuedConnection);
55}
56
58{
59 return m_engine;
60}
61
63{
64 return &m_collector;
65}
66
68{
69 return &m_collector;
70}
71
73{
74 QMutexLocker locker(&m_lock);
75 if (m_state == Paused)
76 return;
77 m_pauseRequested = true;
78}
79
81{
82 QMutexLocker locker(&m_lock);
83 if (m_state != Paused)
84 return;
85
86 if (!m_returnedValue.isUndefined())
87 m_returnedValue.set(m_engine, QV4::Encode::undefined());
88
89 m_currentFrame = m_engine->currentStackFrame;
90 m_stepping = speed;
91 m_runningCondition.wakeAll();
92}
93
95{
96 return m_state;
97}
98
99void QV4Debugger::addBreakPoint(const QString &fileName, int lineNumber, const QString &condition)
100{
101 QMutexLocker locker(&m_lock);
102 m_breakPoints.insert(BreakPoint(fileName.mid(fileName.lastIndexOf('/') + 1),
103 lineNumber), {fileName, condition});
104 m_haveBreakPoints = true;
105 m_breakPointsChanged = true;
106}
107
108void QV4Debugger::removeBreakPoint(const QString &fileName, int lineNumber)
109{
110 QMutexLocker locker(&m_lock);
111 m_breakPoints.remove(BreakPoint(fileName.mid(fileName.lastIndexOf('/') + 1),
112 lineNumber));
113 m_haveBreakPoints = !m_breakPoints.isEmpty();
114 m_breakPointsChanged = true;
115}
116
118{
119 QMutexLocker locker(&m_lock);
120
121 m_breakOnThrow = onoff;
122}
123
125{
126 QMutexLocker locker(&m_lock);
127 m_pauseRequested = false;
128}
129
131{
132 QMutexLocker locker(&m_lock);
133 return m_executableLines.size();
134}
135
137{
138 ExecutionState state;
139 state.fileName = QUrl(getFunction()->sourceFile()).fileName();
140 state.lineNumber = engine()->currentStackFrame->lineNumber();
141
142 return state;
143}
144
146 // A change of breakpoints has to reach maybeBreakAtInstruction() even when
147 // none are left, so that the cache of executable lines gets pruned.
148 return m_pauseRequested || m_haveBreakPoints || m_breakPointsChanged || m_gatherSources
149 || m_stepping >= StepOver;
150}
151
152QList<QV4::StackFrame> QV4Debugger::stackTrace(int frameLimit) const
153{
154 return m_engine->stackTrace(frameLimit);
155}
156
158{
159 if (m_runningJob) // do not re-enter when we're doing a job for the debugger.
160 return;
161
162 QMutexLocker locker(&m_lock);
163
164 if (m_gatherSources) {
165 m_gatherSources->run();
166 delete m_gatherSources;
167 m_gatherSources = nullptr;
168 }
169
170 if (m_breakPointsChanged) {
171 m_breakPointsChanged = false;
172 pruneExecutableLines();
173 }
174
175 switch (m_stepping) {
176 case StepOver:
177 if (m_currentFrame != m_engine->currentStackFrame)
178 break;
179 Q_FALLTHROUGH();
180 case StepIn:
181 pauseAndWait(Step);
182 return;
183 case StepOut:
184 case NotStepping:
185 break;
186 }
187
188 if (m_pauseRequested) { // Serve debugging requests from the agent
189 m_pauseRequested = false;
190 pauseAndWait(PauseRequest);
191 } else if (m_haveBreakPoints) {
192 if (QV4::Function *f = getFunction()) {
193 // lineNumber will be negative for Ret instructions, so those won't match
194 const int lineNumber = engine()->currentStackFrame->lineNumber();
195 if (reallyHitTheBreakPoint(f, f->sourceFile(), lineNumber))
196 pauseAndWait(BreakPointHit);
197 }
198 }
199}
200
202{
203 if (m_runningJob)
204 return;
205 QMutexLocker locker(&m_lock);
206
207 if (m_stepping == StepIn)
208 m_currentFrame = m_engine->currentStackFrame;
209}
210
211void QV4Debugger::leavingFunction(const QV4::ReturnedValue &retVal)
212{
213 if (m_runningJob)
214 return;
215 Q_UNUSED(retVal); // TODO
216
217 QMutexLocker locker(&m_lock);
218
219 if (m_stepping != NotStepping && m_currentFrame == m_engine->currentStackFrame) {
220 m_currentFrame = m_currentFrame->parentFrame();
221 m_stepping = StepOver;
222 m_returnedValue.set(m_engine, retVal);
223 }
224}
225
227{
228 if (!m_breakOnThrow)
229 return;
230
231 if (m_runningJob) // do not re-enter when we're doing a job for the debugger.
232 return;
233
234 QMutexLocker locker(&m_lock);
235 pauseAndWait(Throwing);
236}
237
239{
240 return &QV4::Moth::DebugInstructions::insert;
241}
242
244{
245 if (m_engine->currentStackFrame)
246 return m_engine->currentStackFrame->v4Function;
247 else
248 return m_engine->globalCode;
249}
250
251void QV4Debugger::runJobUnpaused()
252{
253 QMutexLocker locker(&m_lock);
254 if (m_runningJob)
255 m_runningJob->run();
256 m_jobIsRunning.wakeAll();
257}
258
259void QV4Debugger::pauseAndWait(PauseReason reason)
260{
261 if (m_runningJob)
262 return;
263
264 m_state = Paused;
265 emit debuggerPaused(this, reason);
266
267 while (true) {
268 m_runningCondition.wait(&m_lock);
269 if (m_runningJob) {
270 m_runningJob->run();
271 m_jobIsRunning.wakeAll();
272 } else {
273 break;
274 }
275 }
276
277 m_state = Running;
278}
279
280/*!
281 \internal
282
283 Collects the executable lines of every function in \a unit, i.e. of the
284 whole source file. Resolution has to be file-global: a breakpoint on a
285 comment inside a nested function must not also match the outer function's
286 first line after the comment.
287*/
288QV4Debugger::ExecutableLines QV4Debugger::collectExecutableLines(
289 const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &unit)
290{
291 ExecutableLines result;
292 const QV4::CompiledData::Unit *data = unit ? unit->unitData() : nullptr;
293 if (!data)
294 return result;
295 for (uint f = 0, fn = data->functionTableSize; f < fn; ++f) {
296 const QV4::CompiledData::Function *cf = data->functionAt(f);
297 const int start = cf->location.line();
298 result.functionStarts.append(start);
299 const QV4::CompiledData::CodeOffsetToLineAndStatement *table
300 = cf->lineAndStatementNumberTable();
301 for (uint i = 0, n = cf->nLineAndStatementNumbers; i < n; ++i) {
302 const int line = table[i].line;
303 if (line > 0) // debug instructions get negative line numbers
304 result.lines.append({line, start});
305 }
306 }
307 std::sort(result.lines.begin(), result.lines.end());
308 result.lines.erase(std::unique(result.lines.begin(), result.lines.end()),
309 result.lines.end());
310 std::sort(result.functionStarts.begin(), result.functionStarts.end());
311 return result;
312}
313
314int QV4Debugger::firstLineAtOrAfter(const ExecutableLines &executable, int requestedLine)
315{
316 // Lines are sorted by line, then by the start of their function, so the
317 // first one at or after the request is from the earliest starting function.
318 const auto it = std::lower_bound(executable.lines.cbegin(), executable.lines.cend(),
319 ExecutableLine{requestedLine, 0});
320 if (it == executable.lines.cend())
321 return -1;
322 // Only move within code that starts at or before the requested line, and
323 // not past the start of another function or binding. A function starting
324 // later runs at an unrelated time, and in QML the requested line may be a
325 // declaration without code, such as an id or a literal binding. A unit may
326 // also cover only a fragment of its file (a binding compiled from a
327 // string, a chunk passed to QJSEngine::evaluate() with a line offset), and
328 // a line before its code belongs to some other unit.
329 if (it->functionStart > requestedLine)
330 return -1;
331 const QList<int> &starts = executable.functionStarts;
332 const auto start = std::upper_bound(starts.cbegin(), starts.cend(), requestedLine);
333 if (start != starts.cend() && *start < it->line)
334 return -1;
335 return it->line;
336}
337
338void QV4Debugger::pruneExecutableLines()
339{
340 // Drop the units of files without breakpoints, so that the cache does not
341 // keep them from being trimmed. This runs on the engine thread, which is
342 // the only one allowed to release a unit.
343 m_executableLines.removeIf([this](const UnitLines &cached) {
344 const QString file = QUrl(cached.unit->fileName()).fileName();
345 for (auto it = m_breakPoints.keyBegin(), end = m_breakPoints.keyEnd(); it != end; ++it) {
346 if (it->fileName == file)
347 return false;
348 }
349 return true;
350 });
351}
352
353/*!
354 \internal
355
356 Returns the executable lines of the compilation unit \a function belongs
357 to, cached for the most recent units.
358*/
359const QV4Debugger::ExecutableLines &QV4Debugger::executableLines(QV4::Function *function)
360{
361 // Enough for execution moving back and forth between the files of a scene
362 // that all have breakpoints, few enough for a linear search.
363 constexpr qsizetype MaxCachedUnits = 8;
364
365 const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &unit
366 = function->executableCompilationUnit()->baseCompilationUnit();
367 for (qsizetype i = 0, n = m_executableLines.size(); i < n; ++i) {
368 if (m_executableLines.at(i).unit == unit) {
369 if (i > 0)
370 m_executableLines.move(i, 0);
371 return m_executableLines.first().lines;
372 }
373 }
374 if (m_executableLines.size() == MaxCachedUnits)
375 m_executableLines.removeLast();
376 m_executableLines.prepend({unit, collectExecutableLines(unit)});
377 return m_executableLines.first().lines;
378}
379
380/*!
381 \internal
382
383 While paused, returns the line a breakpoint requested on \a requestedLine
384 resolves to in the unit currently being executed, or -1. Lets the agent
385 attribute a hit that landed on a shifted line back to the breakpoint the
386 user placed on a non-executable line.
387*/
388int QV4Debugger::resolvedBreakpointLine(int requestedLine)
389{
390 QMutexLocker locker(&m_lock);
391 QV4::Function *f = getFunction();
392 if (!f)
393 return -1;
394 // This runs on the agent's thread, so it must not change the cache: dropping
395 // the reference to an evicted unit could destroy that unit here.
396 const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &unit
397 = f->executableCompilationUnit()->baseCompilationUnit();
398 for (const UnitLines &cached : std::as_const(m_executableLines)) {
399 if (cached.unit == unit)
400 return firstLineAtOrAfter(cached.lines, requestedLine);
401 }
402 return firstLineAtOrAfter(collectExecutableLines(unit), requestedLine);
403}
404
405bool QV4Debugger::reallyHitTheBreakPoint(QV4::Function *function, const QString &filename,
406 int linenr)
407{
408 const QString file = QUrl(filename).fileName();
409
410 // Besides a breakpoint exactly on this line, a breakpoint requested on a
411 // non-executable line (e.g. a comment or blank line) counts here if this is
412 // the first executable line at or after it. Any of them can stop execution,
413 // so all of them have to be checked.
414 QStringList conditions;
415 for (auto bp = m_breakPoints.constBegin(), end = m_breakPoints.constEnd(); bp != end; ++bp) {
416 if (bp.key().fileName != file || bp.key().lineNumber > linenr)
417 continue;
418 // Only relocate in a unit the client's target identifies: a same-named
419 // file elsewhere has unrelated executable lines.
420 if (bp.key().lineNumber != linenr
421 && (!filename.endsWith(bp.value().target)
422 || firstLineAtOrAfter(executableLines(function), bp.key().lineNumber)
423 != linenr)) {
424 continue;
425 }
426 if (bp.value().condition.isEmpty())
427 return true;
428 conditions.append(bp.value().condition);
429 }
430
431 for (const QString &condition : std::as_const(conditions)) {
432 Q_ASSERT(m_runningJob == nullptr);
433 EvalJob evilJob(m_engine, condition);
434 m_runningJob = &evilJob;
435 m_runningJob->run();
436 m_runningJob = nullptr;
437 if (evilJob.resultAsBoolean())
438 return true;
439 }
440 return false;
441}
442
444{
445 QMutexLocker locker(&m_lock);
446 runInEngine_havingLock(job);
447}
448
449void QV4Debugger::runInEngine_havingLock(QV4DebugJob *job)
450{
451 Q_ASSERT(job);
452 Q_ASSERT(m_runningJob == nullptr);
453
454 m_runningJob = job;
455 if (state() == Paused)
456 m_runningCondition.wakeAll();
457 else
458 emit scheduleJob();
459 m_jobIsRunning.wait(&m_lock);
460 m_runningJob = nullptr;
461}
462
463QT_END_NAMESPACE
464
465#include "moc_qv4debugger.cpp"
friend bool operator==(const QByteArray::FromBase64Result &lhs, const QByteArray::FromBase64Result &rhs) noexcept
Returns true if lhs and rhs are equal, otherwise returns false.
Definition qbytearray.h:834
virtual void run()=0
qsizetype executableLinesCacheSize()
void maybeBreakAtInstruction() override
QV4::Function * getFunction() const
void enteringFunction() override
void scheduleJob()
void runInEngine(QV4DebugJob *job)
int resolvedBreakpointLine(int requestedLine)
QV4DataCollector * collector()
void removeBreakPoint(const QString &fileName, int lineNumber)
QV4::ExecutionEngine * engine() const
void resume(Speed speed)
void setBreakOnThrow(bool onoff)
bool pauseAtNextOpportunity() const override
void leavingFunction(const QV4::ReturnedValue &retVal) override
State state() const
ExecutionState currentExecutionState() const
QV4::Moth::DebugInstructionPass debugInstructionPass() const override
const QV4DataCollector * collector() const
QV4Debugger(QV4::ExecutionEngine *engine)
void aboutToThrow() override
void addBreakPoint(const QString &fileName, int lineNumber, const QString &condition=QString())
void clearPauseRequest()
QList< QV4::StackFrame > stackTrace(int frameLimit=-1) const
constexpr size_t qHash(const QSize &s, size_t seed=0) noexcept
Definition qsize.h:192