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 format = QLatin1String("%1;");
144 QString format = QLatin1String("%1:");
146 QString buildPath = format.arg(APITRACE_BINARY_DIR);
147 m_processEnvironment = QProcessEnvironment::systemEnvironment();
148 m_processEnvironment.insert("PATH", buildPath +
149 m_processEnvironment.value("PATH"));
152 m_processEnvironment.value("PATH").toLatin1());
155 QString Retracer::fileName() const
160 void Retracer::setFileName(const QString &name)
165 void Retracer::setAPI(trace::API api)
170 bool Retracer::isBenchmarking() const
172 return m_benchmarking;
175 void Retracer::setBenchmarking(bool bench)
177 m_benchmarking = bench;
180 bool Retracer::isDoubleBuffered() const
182 return m_doubleBuffered;
185 void Retracer::setDoubleBuffered(bool db)
187 m_doubleBuffered = db;
190 bool Retracer::isProfilingGpu() const
195 bool Retracer::isProfilingCpu() const
200 bool Retracer::isProfilingPixels() const
202 return m_profilePixels;
205 bool Retracer::isProfiling() const
207 return m_profileGpu || m_profileCpu || m_profilePixels;
210 void Retracer::setProfiling(bool gpu, bool cpu, bool pixels)
214 m_profilePixels = pixels;
217 void Retracer::setCaptureAtCallNumber(qlonglong num)
222 qlonglong Retracer::captureAtCallNumber() const
224 return m_captureCall;
227 bool Retracer::captureState() const
229 return m_captureState;
232 void Retracer::setCaptureState(bool enable)
234 m_captureState = enable;
237 bool Retracer::captureThumbnails() const
239 return m_captureThumbnails;
242 void Retracer::setCaptureThumbnails(bool enable)
244 m_captureThumbnails = enable;
248 * Starting point for the retracing thread.
250 * Overrides QThread::run().
254 QString msg = QLatin1String("Replay finished!");
257 * Construct command line
261 QStringList arguments;
265 prog = QLatin1String("glretrace");
268 prog = QLatin1String("eglretrace");
271 case trace::API_D3D7:
272 case trace::API_D3D8:
273 case trace::API_D3D9:
274 case trace::API_D3D10:
275 case trace::API_D3D10_1:
276 case trace::API_D3D11:
278 prog = QLatin1String("d3dretrace");
280 prog = QLatin1String("wine");
281 arguments << QLatin1String("d3dretrace.exe");
285 emit finished(QLatin1String("Unsupported API"));
289 if (m_captureState) {
290 arguments << QLatin1String("-D");
291 arguments << QString::number(m_captureCall);
292 } else if (m_captureThumbnails) {
293 arguments << QLatin1String("-s"); // emit snapshots
294 arguments << QLatin1String("-"); // emit to stdout
295 } else if (isProfiling()) {
297 arguments << QLatin1String("--pgpu");
301 arguments << QLatin1String("--pcpu");
304 if (m_profilePixels) {
305 arguments << QLatin1String("--ppd");
308 if (m_doubleBuffered) {
309 arguments << QLatin1String("--db");
311 arguments << QLatin1String("--sb");
314 if (m_benchmarking) {
315 arguments << QLatin1String("-b");
319 arguments << m_fileName;
327 process.start(prog, arguments, QIODevice::ReadOnly);
328 if (!process.waitForStarted(-1)) {
329 emit finished(QLatin1String("Could not start process"));
334 * Process standard output
337 QList<QImage> thumbnails;
338 QVariantMap parsedJson;
339 trace::Profile* profile = NULL;
341 process.setReadChannel(QProcess::StandardOutput);
342 if (process.waitForReadyRead(-1)) {
343 BlockingIODevice io(&process);
345 if (m_captureState) {
347 * Parse JSON from the output.
349 * XXX: QJSON's scanner is inneficient as it abuses single
350 * character QIODevice::peek (not cheap), instead of maintaining a
351 * lookahead character on its own.
355 QJson::Parser jsonParser;
357 // Allow Nan/Infinity
358 jsonParser.allowSpecialNumbers(true);
360 parsedJson = jsonParser.parse(&io, &ok).toMap();
363 * XXX: QJSON expects blocking IO, and it looks like
364 * BlockingIODevice does not work reliably in all cases.
366 process.waitForFinished(-1);
367 parsedJson = jsonParser.parse(&process, &ok).toMap();
370 msg = QLatin1String("failed to parse JSON");
372 } else if (m_captureThumbnails) {
374 * Parse concatenated PNM images from output.
377 while (!io.atEnd()) {
378 unsigned channels = 0;
383 qint64 headerSize = 0;
384 int headerLines = 3; // assume no optional comment line
386 for (int headerLine = 0; headerLine < headerLines; ++headerLine) {
387 qint64 headerRead = io.readLine(&header[headerSize], sizeof(header) - headerSize);
389 // if header actually contains optional comment line, ...
390 if (headerLine == 1 && header[headerSize] == '#') {
394 headerSize += headerRead;
397 const char *headerEnd = image::readPNMHeader(header, headerSize, &channels, &width, &height);
399 // if invalid PNM header was encountered, ...
400 if (header == headerEnd) {
401 qDebug() << "error: invalid snapshot stream encountered";
405 // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height";
407 QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888);
409 int rowBytes = channels * width;
410 for (int y = 0; y < height; ++y) {
411 unsigned char *scanLine = snapshot.scanLine(y);
412 qint64 readBytes = io.read((char *) scanLine, rowBytes);
413 Q_ASSERT(readBytes == rowBytes);
417 QImage thumb = thumbnail(snapshot);
418 thumbnails.append(thumb);
421 Q_ASSERT(process.state() != QProcess::Running);
422 } else if (isProfiling()) {
423 profile = new trace::Profile();
425 while (!io.atEnd()) {
429 lineLength = io.readLine(line, 256);
431 if (lineLength == -1)
434 trace::Profiler::parseLine(line, profile);
438 output = process.readAllStandardOutput();
439 if (output.length() < 80) {
440 msg = QString::fromUtf8(output);
446 * Wait for process termination
449 process.waitForFinished(-1);
451 if (process.exitStatus() != QProcess::NormalExit) {
452 msg = QLatin1String("Process crashed");
453 } else if (process.exitCode() != 0) {
454 msg = QLatin1String("Process exited with non zero exit code");
461 QList<ApiTraceError> errors;
462 process.setReadChannel(QProcess::StandardError);
463 QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$");
464 while (!process.atEnd()) {
465 QString line = process.readLine();
466 if (regexp.indexIn(line) != -1) {
468 error.callIndex = regexp.cap(1).toInt();
469 error.type = regexp.cap(2);
470 error.message = regexp.cap(3);
471 errors.append(error);
472 } else if (!errors.isEmpty()) {
473 // Probably a multiligne message
474 ApiTraceError &previous = errors.last();
475 if (line.endsWith("\n")) {
478 previous.message.append('\n');
479 previous.message.append(line);
487 if (m_captureState) {
488 ApiTraceState *state = new ApiTraceState(parsedJson);
489 emit foundState(state);
490 msg = QLatin1String("State fetched.");
493 if (m_captureThumbnails && !thumbnails.isEmpty()) {
494 emit foundThumbnails(thumbnails);
497 if (isProfiling() && profile) {
498 emit foundProfile(profile);
501 if (!errors.isEmpty()) {
502 emit retraceErrors(errors);
508 #include "retracer.moc"