3 #include "apitracecall.h"
6 #include "image/image.hpp"
8 #include "trace_profiler.hpp"
15 #include <qjson/parser.h>
18 * Wrapper around a QProcess which enforces IO to block .
20 * Several QIODevice users (notably QJSON) expect blocking semantics, e.g.,
21 * they expect that QIODevice::read() will blocked until the requested ammount
22 * of bytes is read or end of file is reached. But by default QProcess, does
23 * not block. And passing QIODevice::Unbuffered mitigates but does not fully
24 * address the problem either.
26 * This class wraps around QProcess, providing QIODevice interface, while
27 * ensuring that all reads block.
29 * This class also works around a bug in QProcess::atEnd() implementation.
32 * - http://qt-project.org/wiki/Simple_Crypt_IO_Device
33 * - http://qt-project.org/wiki/Custom_IO_Device
35 class BlockingIODevice : public QIODevice
37 /* We don't use the Q_OBJECT in this class given we don't declare any
38 * signals and slots or use any other services provided by Qt's meta-object
41 BlockingIODevice(QProcess * io);
42 bool isSequential() const;
44 bool waitForReadyRead(int msecs = -1);
47 qint64 readData(char * data, qint64 maxSize);
48 qint64 writeData(const char * data, qint64 maxSize);
54 BlockingIODevice::BlockingIODevice(QProcess * io) :
58 * We pass QIODevice::Unbuffered to prevent the base QIODevice class to do
59 * its own buffering on top of the overridden readData() method.
61 * The only buffering used will be to satisfy QIODevice::peek() and
62 * QIODevice::ungetChar().
64 setOpenMode(ReadOnly | Unbuffered);
67 bool BlockingIODevice::isSequential() const
72 bool BlockingIODevice::atEnd() const
75 * XXX: QProcess::atEnd() documentation is wrong -- it will return true
76 * even when the process is running --, so we try to workaround that here.
78 if (m_device->atEnd()) {
79 if (m_device->state() == QProcess::Running) {
80 if (!m_device->waitForReadyRead(-1)) {
88 bool BlockingIODevice::waitForReadyRead(int msecs)
94 qint64 BlockingIODevice::readData(char * data, qint64 maxSize)
96 qint64 bytesToRead = maxSize;
99 qint64 chunkSize = m_device->read(data + readSoFar, bytesToRead);
107 Q_ASSERT(chunkSize <= bytesToRead);
108 bytesToRead -= chunkSize;
109 readSoFar += chunkSize;
111 if (!m_device->waitForReadyRead(-1)) {
112 qDebug() << "waitForReadyRead failed\n";
116 } while(bytesToRead);
121 qint64 BlockingIODevice::writeData(const char * data, qint64 maxSize)
127 Q_DECLARE_METATYPE(QList<ApiTraceError>);
129 Retracer::Retracer(QObject *parent)
131 m_benchmarking(false),
132 m_doubleBuffered(true),
133 m_captureState(false),
137 m_profilePixels(false)
139 qRegisterMetaType<QList<ApiTraceError> >();
142 QString Retracer::fileName() const
147 void Retracer::setFileName(const QString &name)
152 QString Retracer::remoteTarget() const
154 return m_remoteTarget;
157 void Retracer::setRemoteTarget(const QString &host)
159 m_remoteTarget = host;
162 void Retracer::setAPI(trace::API api)
167 bool Retracer::isBenchmarking() const
169 return m_benchmarking;
172 void Retracer::setBenchmarking(bool bench)
174 m_benchmarking = bench;
177 bool Retracer::isDoubleBuffered() const
179 return m_doubleBuffered;
182 void Retracer::setDoubleBuffered(bool db)
184 m_doubleBuffered = db;
187 bool Retracer::isProfilingGpu() const
192 bool Retracer::isProfilingCpu() const
197 bool Retracer::isProfilingPixels() const
199 return m_profilePixels;
202 bool Retracer::isProfiling() const
204 return m_profileGpu || m_profileCpu || m_profilePixels;
207 void Retracer::setProfiling(bool gpu, bool cpu, bool pixels)
211 m_profilePixels = pixels;
214 void Retracer::setCaptureAtCallNumber(qlonglong num)
219 qlonglong Retracer::captureAtCallNumber() const
221 return m_captureCall;
224 bool Retracer::captureState() const
226 return m_captureState;
229 void Retracer::setCaptureState(bool enable)
231 m_captureState = enable;
234 bool Retracer::captureThumbnails() const
236 return m_captureThumbnails;
239 void Retracer::setCaptureThumbnails(bool enable)
241 m_captureThumbnails = enable;
245 * Starting point for the retracing thread.
247 * Overrides QThread::run().
251 QString msg = QLatin1String("Replay finished!");
254 * Construct command line
258 QStringList arguments;
262 prog = QLatin1String("glretrace");
265 prog = QLatin1String("eglretrace");
268 case trace::API_D3D7:
269 case trace::API_D3D8:
270 case trace::API_D3D9:
271 case trace::API_DXGI:
273 prog = QLatin1String("d3dretrace");
275 prog = QLatin1String("wine");
276 arguments << QLatin1String("d3dretrace.exe");
280 emit finished(QLatin1String("Unsupported API"));
284 if (m_captureState) {
285 arguments << QLatin1String("-D");
286 arguments << QString::number(m_captureCall);
287 } else if (m_captureThumbnails) {
288 arguments << QLatin1String("-s"); // emit snapshots
289 arguments << QLatin1String("-"); // emit to stdout
290 } else if (isProfiling()) {
292 arguments << QLatin1String("--pgpu");
296 arguments << QLatin1String("--pcpu");
299 if (m_profilePixels) {
300 arguments << QLatin1String("--ppd");
303 if (m_doubleBuffered) {
304 arguments << QLatin1String("--db");
306 arguments << QLatin1String("--sb");
309 if (m_benchmarking) {
310 arguments << QLatin1String("-b");
314 arguments << m_fileName;
317 * Support remote execution on a separate target.
320 if (m_remoteTarget.length() != 0) {
321 arguments.prepend(prog);
322 arguments.prepend(m_remoteTarget);
323 prog = QLatin1String("ssh");
332 process.start(prog, arguments, QIODevice::ReadOnly);
333 if (!process.waitForStarted(-1)) {
334 emit finished(QLatin1String("Could not start process"));
339 * Process standard output
342 QList<QImage> thumbnails;
343 QVariantMap parsedJson;
344 trace::Profile* profile = NULL;
346 process.setReadChannel(QProcess::StandardOutput);
347 if (process.waitForReadyRead(-1)) {
348 BlockingIODevice io(&process);
350 if (m_captureState) {
352 * Parse JSON from the output.
354 * XXX: QJSON's scanner is inneficient as it abuses single
355 * character QIODevice::peek (not cheap), instead of maintaining a
356 * lookahead character on its own.
360 QJson::Parser jsonParser;
362 // Allow Nan/Infinity
363 jsonParser.allowSpecialNumbers(true);
365 parsedJson = jsonParser.parse(&io, &ok).toMap();
368 * XXX: QJSON expects blocking IO, and it looks like
369 * BlockingIODevice does not work reliably in all cases.
371 process.waitForFinished(-1);
372 parsedJson = jsonParser.parse(&process, &ok).toMap();
375 msg = QLatin1String("failed to parse JSON");
377 } else if (m_captureThumbnails) {
379 * Parse concatenated PNM images from output.
382 while (!io.atEnd()) {
383 unsigned channels = 0;
388 qint64 headerSize = 0;
389 int headerLines = 3; // assume no optional comment line
391 for (int headerLine = 0; headerLine < headerLines; ++headerLine) {
392 qint64 headerRead = io.readLine(&header[headerSize], sizeof(header) - headerSize);
394 // if header actually contains optional comment line, ...
395 if (headerLine == 1 && header[headerSize] == '#') {
399 headerSize += headerRead;
402 const char *headerEnd = image::readPNMHeader(header, headerSize, &channels, &width, &height);
404 // if invalid PNM header was encountered, ...
405 if (header == headerEnd) {
406 qDebug() << "error: invalid snapshot stream encountered";
410 // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height";
412 QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888);
414 int rowBytes = channels * width;
415 for (int y = 0; y < height; ++y) {
416 unsigned char *scanLine = snapshot.scanLine(y);
417 qint64 readBytes = io.read((char *) scanLine, rowBytes);
418 Q_ASSERT(readBytes == rowBytes);
422 QImage thumb = thumbnail(snapshot);
423 thumbnails.append(thumb);
426 Q_ASSERT(process.state() != QProcess::Running);
427 } else if (isProfiling()) {
428 profile = new trace::Profile();
430 while (!io.atEnd()) {
434 lineLength = io.readLine(line, 256);
436 if (lineLength == -1)
439 trace::Profiler::parseLine(line, profile);
443 output = process.readAllStandardOutput();
444 if (output.length() < 80) {
445 msg = QString::fromUtf8(output);
451 * Wait for process termination
454 process.waitForFinished(-1);
456 if (process.exitStatus() != QProcess::NormalExit) {
457 msg = QLatin1String("Process crashed");
458 } else if (process.exitCode() != 0) {
459 msg = QLatin1String("Process exited with non zero exit code");
466 QList<ApiTraceError> errors;
467 process.setReadChannel(QProcess::StandardError);
468 QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$");
469 while (!process.atEnd()) {
470 QString line = process.readLine();
471 if (regexp.indexIn(line) != -1) {
473 error.callIndex = regexp.cap(1).toInt();
474 error.type = regexp.cap(2);
475 error.message = regexp.cap(3);
476 errors.append(error);
477 } else if (!errors.isEmpty()) {
478 // Probably a multiligne message
479 ApiTraceError &previous = errors.last();
480 if (line.endsWith("\n")) {
483 previous.message.append('\n');
484 previous.message.append(line);
492 if (m_captureState) {
493 ApiTraceState *state = new ApiTraceState(parsedJson);
494 emit foundState(state);
497 if (m_captureThumbnails && !thumbnails.isEmpty()) {
498 emit foundThumbnails(thumbnails);
501 if (isProfiling() && profile) {
502 emit foundProfile(profile);
505 if (!errors.isEmpty()) {
506 emit retraceErrors(errors);
512 #include "retracer.moc"