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
main.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 BogDan Vatra <bogdan@kde.org>
2// Copyright (C) 2023 The Qt Company Ltd.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
4
5#include <QtCore/QCommandLineParser>
6#include <QtCore/QCoreApplication>
7#include <QtCore/QDeadlineTimer>
8#include <QtCore/qdebug.h>
9#include <QtCore/QDir>
10#include <QtCore/QHash>
11#include <QtCore/QLockFile>
12#include <QtCore/QProcess>
13#include <QtCore/QProcessEnvironment>
14#include <QtCore/QRegularExpression>
15#include <QtCore/QSet>
16#include <QtCore/QStandardPaths>
17#include <QtCore/QThread>
18#include <QtCore/QXmlStreamReader>
19#include <QtCore/QFileInfo>
20#include <QtCore/QTemporaryFile>
21
22#include "../../../tests/shared/cidetect.h"
23
24#include <atomic>
25#include <chrono>
26#include <csignal>
27#include <QtCore/qxpfunctional.h>
28#include <optional>
29
30#if defined(Q_OS_WIN32)
31#include <process.h>
32#else
33#include <unistd.h>
34#endif
35
36using namespace Qt::StringLiterals;
37using namespace std::chrono_literals;
38
39
40// QTest-based test processes may exit with up to 127 for normal test failures
41static constexpr int HIGHEST_QTEST_EXITCODE = 127;
42// Something went wrong in androidtestrunner, in general
43static constexpr int EXIT_ERROR = 254;
44// More specific exit codes for failures in androidtestrunner:
45static constexpr int EXIT_NOEXITCODE = 253; // Failed to transfer exit code from device
46static constexpr int EXIT_ANR = 252; // Android ANR error (Application Not Responding)
47static constexpr int EXIT_NORESULTS = 251; // Failed to transfer result files from device
48static constexpr int EXIT_DEVICE_GONE = 250; // Device disconnected mid-test
49
50
51struct Options
52{
53 bool verbose = false;
54 bool skipAddInstallRoot = false;
55 int timeoutSecs = 600; // 10 minutes
73 bool showLogcatOutput = false;
75};
76
78
80{
81 int sdkVersion = -1;
82 int pid = -1;
84
85 std::atomic<bool> isPackageInstalled { false };
86 std::atomic<bool> isTestRunnerInterrupted { false };
87 std::atomic<bool> deviceGone { false };
89};
90
91// sigHandler reads/writes these from arbitrary signal contexts.
92static_assert(std::atomic<bool>::is_always_lock_free);
93static_assert(std::atomic<qint64>::is_always_lock_free);
94
96
97// QTest-based processes return 0 if all tests PASSed, or the number of FAILs up to 127.
98// Other exitcodes signify abnormal termination and are system-dependent.
99static bool isTestExitCodeNormal(const int ec)
100{
101 return (ec >= 0 && ec <= HIGHEST_QTEST_EXITCODE);
102}
103
104static QByteArray execCommand(const QString &program, const QStringList &args, bool verbose = false,
105 std::chrono::milliseconds timeout = std::chrono::milliseconds(-1))
106{
107 const auto command = program + " "_L1 + args.join(u' ');
108
109 if (verbose && g_options.verbose)
110 fprintf(stdout,"Execute %s.\n", command.toUtf8().constData());
111
112 QProcess process;
113 process.start(program, args);
114 if (!process.waitForStarted()) {
115 qCritical("Cannot execute command %s.", qPrintable(command));
116 return QByteArray();
117 }
118
119 const bool finished = timeout.count() < 0
120 ? process.waitForFinished()
121 : process.waitForFinished(static_cast<int>(timeout.count()));
122 if (!finished) {
123 qCritical("Execution of command %s timed out.", qPrintable(command));
124 process.kill();
125 process.waitForFinished();
126 // Beyond the kill's own "killed by signal", stderr may hint at the hang.
127 const QByteArray stdErr = process.readAllStandardError();
128 if (!stdErr.isEmpty())
129 qWarning().noquote() << stdErr.trimmed();
130 return QByteArray();
131 }
132
133 const auto stdOut = process.readAllStandardOutput();
134 const auto stdErr = process.readAllStandardError();
135
136 if (process.exitCode() != 0) {
137 // Surface why a notable (verbose) command failed; quiet polls stay quiet.
138 if (verbose && !stdOut.isEmpty())
139 qWarning().noquote() << stdOut.trimmed();
140 if (!stdErr.isEmpty())
141 qWarning().noquote() << stdErr.trimmed();
142 return QByteArray();
143 }
144
145 if (verbose && g_options.verbose)
146 fprintf(stdout, "%s\n", stdOut.constData());
147
148 // Non-null even when empty so a silent success is distinct from failure.
149 return stdOut.isNull() ? QByteArray("") : stdOut;
150}
151
152static QStringList adbArgsWithSerial(const QStringList &args)
153{
154 if (g_options.serial.isEmpty())
155 return args;
156 return QStringList{ "-s"_L1, g_options.serial } + args;
157}
158
159static QByteArray execAdbCommand(const QStringList &args, bool verbose = true,
160 std::chrono::milliseconds timeout = 30s)
161{
162 return execCommand(g_options.adbCommand, adbArgsWithSerial(args), verbose, timeout);
163}
164
165static QByteArray execBundletoolCommand(const QStringList &args, bool verbose = true)
166{
167 QString java("java"_L1);
168 QStringList argsFull = QStringList() << "-jar"_L1 << g_options.bundletoolPath << args;
169 return execCommand(java, argsFull, verbose);
170}
171
172static bool setPackagePath(const QString &path)
173{
174 if (!g_options.packagePath.isEmpty()) {
175 qCritical("Only one of --apk or --aab may be set, and only once.");
176 return false;
177 }
178 g_options.packagePath = path;
179 return true;
180}
181
182static bool collectPackagePaths(const QStringList &apkValues, const QStringList &aabValues)
183{
184 if (apkValues.size() > 1) {
185 qCritical("--apk specified %lld times; only one APK path is supported.",
186 static_cast<long long>(apkValues.size()));
187 return false;
188 }
189 if (aabValues.size() > 1) {
190 qCritical("--aab specified %lld times; only one AAB path is supported.",
191 static_cast<long long>(aabValues.size()));
192 return false;
193 }
194 if (!apkValues.isEmpty() && !setPackagePath(apkValues.first()))
195 return false;
196 if (!aabValues.isEmpty() && !setPackagePath(aabValues.first()))
197 return false;
198 return true;
199}
200
201static QByteArray execCommand(const QString &command, bool verbose = true,
202 std::chrono::milliseconds timeout = std::chrono::milliseconds(-1))
203{
204 auto args = QProcess::splitCommand(command);
205 const auto program = args.takeFirst();
206 return execCommand(program, args, verbose, timeout);
207}
208
209// Split argv into our and test options, then re-join as "<ours> -- <test args>".
210static QStringList splitOwnAndTestArgs(const QStringList &args,
211 const QSet<QString> &knownOpts,
212 const QSet<QString> &valueOpts)
213{
214 QStringList ownArgs;
215 QStringList testArgs;
216 ownArgs.reserve(args.size() + 1);
217 for (int i = 0; i < args.size(); ++i) {
218 const QString &arg = args.at(i);
219 if (i == 0) {
220 ownArgs << arg;
221 continue;
222 }
223 if (arg == "--"_L1) {
224 // Caller already split things explicitly, so forward the rest as-is.
225 for (int j = i + 1; j < args.size(); ++j)
226 testArgs << args.at(j);
227 break;
228 }
229 if (arg.startsWith("--"_L1) && arg.size() > 2) {
230 QString name = arg.mid(2);
231 const qsizetype eqIdx = name.indexOf(u'=');
232 if (eqIdx != -1)
233 name.truncate(eqIdx);
234 if (!knownOpts.contains(name)) {
235 qCritical("Unknown option '--%s'. Use '--' to forward test arguments.",
236 qPrintable(name));
237 return {};
238 }
239 ownArgs << arg;
240 if (eqIdx == -1 && valueOpts.contains(name)) {
241 if (i + 1 >= args.size()) {
242 qCritical("Option --%s requires a value.", qPrintable(name));
243 return {};
244 }
245 ownArgs << args.at(++i);
246 }
247 continue;
248 }
249 // Keep scanning, because CMake appends our flags after the test's flags.
250 testArgs << arg;
251 }
252
253 if (!testArgs.isEmpty()) {
254 ownArgs << "--"_L1;
255 ownArgs += testArgs;
256 }
257 return ownArgs;
258}
259
261{
262#ifdef Q_OS_WIN
263 const QStringList candidates = { "ndk-stack.cmd"_L1, "ndk-stack.bat"_L1, "ndk-stack"_L1 };
264#else
265 const QStringList candidates = { "ndk-stack"_L1 };
266#endif
267 for (const char *var : { "ANDROID_NDK_ROOT", "ANDROID_NDK_HOME" }) {
268 const QString ndkPath = qEnvironmentVariable(var);
269 if (ndkPath.isEmpty())
270 continue;
271 for (const QString &name : candidates) {
272 const QString path = ndkPath + QDir::separator() + name;
273 if (QFile::exists(path))
274 return path;
275 }
276 }
277 return {};
278}
279
280static bool parseOptions()
281{
282 QCommandLineParser parser;
283 parser.setApplicationDescription(
284 "Runs a Qt for Android test on an emulator or a device. Specify a "
285 "device via --serial, ANDROID_SERIAL or ANDROID_DEVICE_SERIAL.\n"
286 "\n"
287 "Exit codes:\n"
288 " 0-127 QTest exit code (number of failed test functions)\n"
289 " 250 EXIT_DEVICE_GONE device disconnected\n"
290 " 251 EXIT_NORESULTS result files could not be pulled\n"
291 " 252 EXIT_ANR Android Not Responding\n"
292 " 253 EXIT_NOEXITCODE exit code could not be read from device\n"
293 " 254 EXIT_ERROR generic runner failure"_L1);
294
295 QCommandLineOption pathOpt(
296 "path"_L1, "Path where the Android Gradle package is built."_L1, "path"_L1);
297 QCommandLineOption makeOpt(
298 "make"_L1, "make command to build the APK."_L1, "command"_L1);
299 QCommandLineOption apkOpt(
300 "apk"_L1, "Test APK path. Built via --make if absent."_L1, "path"_L1);
301 QCommandLineOption aabOpt(
302 "aab"_L1, "Test AAB path. Built via --make if absent."_L1, "path"_L1);
303 QCommandLineOption bundletoolOpt(
304 "bundletool"_L1, "Path to Android bundletool jar."_L1, "path"_L1);
305 QCommandLineOption manifestOpt(
306 "manifest"_L1, "Custom AndroidManifest.xml path."_L1, "path"_L1);
307 QCommandLineOption adbOpt(
308 "adb"_L1, "Path to adb. Falls back to $PATH."_L1, "command"_L1, "adb"_L1);
309 QCommandLineOption serialOpt(
310 "serial"_L1,
311 "Android device serial. Overrides ANDROID_SERIAL / ANDROID_DEVICE_SERIAL."_L1,
312 "serial"_L1);
313 QCommandLineOption activityOpt(
314 "activity"_L1, "Activity to run. Defaults to the first in the manifest."_L1, "name"_L1);
315 QCommandLineOption timeoutOpt(
316 "timeout"_L1, "Test timeout in seconds (default 600)."_L1, "seconds"_L1, "600"_L1);
317 QCommandLineOption preTestAdbOpt("pre-test-adb-command"_L1,
318 "adb command to run after install, before test."_L1, "command"_L1);
319 QCommandLineOption skipInstallRootOpt(
320 "skip-install-root"_L1,
321 "Don't append INSTALL_ROOT=... to --make. Only honored for make-family "
322 "tools (make, gmake, nmake, mingw32-make, jom)."_L1);
323 QCommandLineOption ndkStackOpt(
324 "ndk-stack"_L1, "Path to ndk-stack (default: ndk-stack under $ANDROID_NDK_ROOT "
325 "or $ANDROID_NDK_HOME)."_L1, "path"_L1);
326 QCommandLineOption showLogcatOpt(
327 "show-logcat"_L1, "Print logcat output (+ system_server on ANR)."_L1);
328 QCommandLineOption verboseOpt(
329 "verbose"_L1, "Print extra information."_L1);
330 QCommandLineOption helpOpt("help"_L1, "Show this help message."_L1);
331
332 const QList<QCommandLineOption> ourOptions = {
333 pathOpt, makeOpt, apkOpt, aabOpt,
334 bundletoolOpt, manifestOpt,
335 adbOpt, serialOpt,
336 activityOpt, timeoutOpt, preTestAdbOpt,
337 skipInstallRootOpt,
338 ndkStackOpt, showLogcatOpt, verboseOpt,
339 helpOpt,
340 };
341 parser.addOptions(ourOptions);
342 parser.addPositionalArgument("testargs"_L1, "Arguments forwarded to the test."_L1,
343 "[-- TESTARGS]"_L1);
344
345 QSet<QString> knownOpts;
346 QSet<QString> valueOpts;
347 for (const QCommandLineOption &opt : ourOptions) {
348 const bool takesValue = !opt.valueName().isEmpty();
349 for (const QString &name : opt.names()) {
350 knownOpts.insert(name);
351 if (takesValue)
352 valueOpts.insert(name);
353 }
354 }
355
356 const QStringList processedArgs =
357 splitOwnAndTestArgs(QCoreApplication::arguments(), knownOpts, valueOpts);
358 if (processedArgs.isEmpty())
359 return false;
360 if (!parser.parse(processedArgs)) {
361 qCritical("%s", qPrintable(parser.errorText()));
362 return false;
363 }
364 if (parser.isSet(helpOpt))
365 parser.showHelp(0);
366
367 g_options.buildPath = parser.value(pathOpt);
368 g_options.makeCommand = parser.value(makeOpt);
369 if (!collectPackagePaths(parser.values(apkOpt), parser.values(aabOpt)))
370 return false;
371 g_options.adbCommand = parser.value(adbOpt);
372 g_options.activity = parser.value(activityOpt);
373 g_options.serial = parser.value(serialOpt);
374 bool timeoutOk = false;
375 g_options.timeoutSecs = parser.value(timeoutOpt).toInt(&timeoutOk);
376 if (!timeoutOk || g_options.timeoutSecs <= 0) {
377 qCritical("--timeout must be a positive integer (got '%s').",
378 qPrintable(parser.value(timeoutOpt)));
379 return false;
380 }
381 g_options.skipAddInstallRoot = parser.isSet(skipInstallRootOpt);
382 g_options.showLogcatOutput = parser.isSet(showLogcatOpt);
383 g_options.ndkStackPath = parser.value(ndkStackOpt);
384 g_options.verbose = parser.isSet(verboseOpt);
385 g_options.manifestPath = parser.value(manifestOpt);
386 g_options.bundletoolPath = parser.value(bundletoolOpt);
387
388 for (const QString &cmd : parser.values(preTestAdbOpt))
389 g_options.preTestRunAdbCommands += QProcess::splitCommand(cmd);
390 g_options.testArgsList = parser.positionalArguments();
391
392 static const QStringList makeNames = {
393 "make"_L1, "gmake"_L1, "nmake"_L1, "mingw32-make"_L1, "jom"_L1,
394 };
395 const QStringList makeParts = QProcess::splitCommand(g_options.makeCommand);
396 const QString makeBaseName = QFileInfo(makeParts.value(0)).baseName();
397 const bool makeIsGnuMakeFamily = makeNames.contains(makeBaseName, Qt::CaseInsensitive);
398 if (!g_options.skipAddInstallRoot && makeIsGnuMakeFamily) {
399 g_options.makeCommand = "%1 INSTALL_ROOT=%2 install"_L1
400 .arg(g_options.makeCommand, QDir::toNativeSeparators(g_options.buildPath));
401 }
402
403 if (g_options.buildPath.isEmpty() || g_options.packagePath.isEmpty()) {
404 qCritical("--path and --apk (or --aab) are required.");
405 fputs(qPrintable(parser.helpText()), stderr);
406 return false;
407 }
408
409 if (!g_options.packagePath.endsWith(".apk"_L1)
410 && !g_options.packagePath.endsWith(".aab"_L1)) {
411 qCritical("Package path '%s' must end with .apk or .aab.",
412 qPrintable(g_options.packagePath));
413 return false;
414 }
415
416 if (g_options.packagePath.endsWith(".aab"_L1)) {
417 if (g_options.bundletoolPath.isEmpty()) {
418 qCritical("--aab requires --bundletool to locate the bundletool jar.");
419 return false;
420 }
421 if (!QFile::exists(g_options.bundletoolPath)) {
422 qCritical("--bundletool path '%s' does not exist.",
423 qPrintable(g_options.bundletoolPath));
424 return false;
425 }
426 }
427
428 if (g_options.serial.isEmpty())
429 g_options.serial = qEnvironmentVariable("ANDROID_SERIAL");
430 if (g_options.serial.isEmpty())
431 g_options.serial = qEnvironmentVariable("ANDROID_DEVICE_SERIAL");
432
433 if (g_options.ndkStackPath.isEmpty())
434 g_options.ndkStackPath = ndkStackPath();
435
436 return true;
437}
438
440{
441 static QString path;
442 if (!path.isEmpty())
443 return path;
444
445 QTemporaryFile initScript;
446 initScript.setAutoRemove(false);
447 if (!initScript.open())
448 return {};
449
450 initScript.write(
451 "gradle.projectsEvaluated {\n"
452 " def prop = gradle.rootProject.findProperty(\"property\")\n"
453 " def target = gradle.rootProject.findProject(':app') ?: gradle.rootProject\n"
454 " for (part in prop.tokenize('.')) {\n"
455 " target = target.\"${part}\"\n"
456 " }\n"
457 " println target\n"
458 "}\n"
459 "rootProject { tasks.register(\"printProjectProperty\") }\n");
460 initScript.close();
461
462 path = initScript.fileName();
463 qAddPostRoutine([] { QFile::remove(path); });
464 return path;
465}
466
467// Query a Gradle project's property using dot-separated path notation e.g. "android.namespace".
468static QString getGradleProjectProperty(const QString &androidBuildDir, const QString &property)
469{
470#ifdef Q_OS_WIN
471 QString gradlew = androidBuildDir + "/gradlew.bat"_L1;
472#else
473 QString gradlew = androidBuildDir + "/gradlew"_L1;
474#endif
475 if (!QFile::exists(gradlew))
476 return {};
477
478 const QString scriptPath = gradleInitScriptPath();
479 if (scriptPath.isEmpty())
480 return {};
481
482 QProcess process;
483 process.setWorkingDirectory(androidBuildDir);
484 process.start(gradlew, { "-q"_L1, "--init-script"_L1, scriptPath,
485 "-Pproperty="_L1 + property, "printProjectProperty"_L1 });
486
487 if (!process.waitForFinished()) {
488 qWarning("gradlew '%s' timed out.", qPrintable(property));
489 process.kill();
490 process.waitForFinished();
491 return {};
492 }
493 if (process.exitCode() != 0) {
494 qWarning("gradlew '%s' exited with %d:\n%s", qPrintable(property),
495 process.exitCode(), process.readAllStandardError().constData());
496 return {};
497 }
498 return QString::fromUtf8(process.readAllStandardOutput()).trimmed();
499}
500
502{
503 if (!g_options.manifestPath.isEmpty()) {
504 if (!QFile::exists(g_options.manifestPath)) {
505 qCritical("--manifest path '%s' does not exist.",
506 qPrintable(g_options.manifestPath));
507 return false;
508 }
509 } else {
510 const QStringList candidates = {
511 g_options.buildPath + "/AndroidManifest.xml"_L1,
512 g_options.buildPath + "/app/AndroidManifest.xml"_L1
513 };
514 for (const QString &candidate : candidates) {
515 if (QFile::exists(candidate)) {
516 g_options.manifestPath = candidate;
517 break;
518 }
519 }
520 }
521 if (g_options.manifestPath.isEmpty()) {
522 qCritical("Unable to find AndroidManifest.xml at '%s'.", qPrintable(g_options.buildPath));
523 return false;
524 }
525 QFile androidManifestXml(g_options.manifestPath);
526 if (!androidManifestXml.open(QIODevice::ReadOnly)) {
527 qCritical("Unable to read android manifest '%s'", qPrintable(g_options.manifestPath));
528 return false;
529 }
530
531 QXmlStreamReader reader(&androidManifestXml);
532 while (!reader.atEnd()) {
533 reader.readNext();
534 if (!reader.isStartElement())
535 continue;
536
537 if (reader.name() == "activity"_L1 && g_options.activity.isEmpty())
538 g_options.activity = reader.attributes().value("android:name"_L1).toString();
539 else if (reader.name() == "uses-permission"_L1)
540 g_options.permissions.append(reader.attributes().value("android:name"_L1).toString());
541 }
542 return true;
543}
544
546{
547 const QStringList args({ "shell"_L1, "dumpsys"_L1, "package"_L1, "permissions"_L1 });
548 const QByteArray output = execAdbCommand(args, false);
549 if (output.isNull()) {
550 qWarning("Failed to query permissions via dumpsys");
551 return {};
552 }
553
554 /*
555 * Permissions section from this command look like:
556 *
557 * Permission [android.permission.INTERNET] (c8cafdc):
558 * sourcePackage=android
559 * uid=1000 gids=[3003] type=0 prot=normal|instant
560 * perm=PermissionInfo{5f5bfbb android.permission.INTERNET}
561 * flags=0x0
562 */
563 const static QRegularExpression regex("^\\s*Permission\\s+\\‍[([^\\‍]]+)\\‍]\\s+\\‍([^)]+\\‍):"_L1);
564 QStringList dangerousPermissions;
565 QString currentPerm;
566
567 const QStringList lines = QString::fromUtf8(output).split(u'\n');
568 for (const QString &line : lines) {
569 QRegularExpressionMatch match = regex.match(line);
570 if (match.hasMatch()) {
571 currentPerm = match.captured(1);
572 continue;
573 }
574
575 if (currentPerm.isEmpty())
576 continue;
577
578 int protIndex = line.indexOf("prot="_L1);
579 if (protIndex == -1)
580 continue;
581
582 QString protectionTypes = line.mid(protIndex + 5).trimmed();
583 if (protectionTypes.contains("dangerous"_L1, Qt::CaseInsensitive))
584 dangerousPermissions.append(currentPerm);
585 currentPerm.clear();
586 }
587
588 return dangerousPermissions;
589}
590
591static QString deviceOutputFileName(const QString &format, const QString &hostPath)
592{
593 return hostPath.isEmpty() ? "stdout.%1"_L1.arg(format) : QFileInfo(hostPath).fileName();
594}
595
596static void setOutputFile(QString file, QString format)
597{
598 if (format.isEmpty())
599 format = "txt"_L1;
600 if (file == u'-')
601 file.clear();
602
603 if (file.isEmpty()) {
604 if (!g_options.outFiles.contains(format))
605 g_options.outFiles.insert(format, QString());
606 g_options.stdoutFileName = deviceOutputFileName(format, g_options.outFiles.value(format));
607 } else {
608 g_options.outFiles[format] = file;
609 }
610}
611
612static bool parseTestArgs()
613{
614 QRegularExpression oldFormats{"^-(txt|csv|xunitxml|junitxml|xml|lightxml|teamcity|tap)$"_L1};
615 QRegularExpression newLoggingFormat{"^(.*),(txt|csv|xunitxml|junitxml|xml|lightxml|teamcity|tap)$"_L1};
616
617 QString file;
618 QString logType;
619 QStringList unhandledArgs;
620 for (int i = 0; i < g_options.testArgsList.size(); ++i) {
621 const QString &arg = g_options.testArgsList[i].trimmed();
622 if (arg == "--"_L1)
623 continue;
624 if (arg == "-o"_L1 || arg == "--output"_L1) {
625 if (i >= g_options.testArgsList.size() - 1)
626 return false; // missing file argument
627
628 const auto &filePath = g_options.testArgsList[++i];
629 const auto match = newLoggingFormat.match(filePath);
630 if (!match.hasMatch()) {
631 file = filePath;
632 } else {
633 const auto capturedTexts = match.capturedTexts();
634 setOutputFile(capturedTexts.at(1), capturedTexts.at(2));
635 }
636 } else {
637 auto match = oldFormats.match(arg);
638 if (match.hasMatch()) {
639 logType = match.capturedTexts().at(1);
640 } else {
641 // Use triple literal quotes so that QProcess::splitCommand() in androidjnimain.cpp
642 // keeps quotes characters inside the string.
643 QString quotedArg = QString(arg).replace("\""_L1, "\\\"\\\"\\\""_L1);
644 // Add escaped double quote character so that args with spaces are treated as one.
645 unhandledArgs << " \\\"%1\\\""_L1.arg(quotedArg);
646 }
647 }
648 }
649 if (g_options.outFiles.isEmpty() || !file.isEmpty() || !logType.isEmpty())
650 setOutputFile(file, logType);
651
652 QString testAppArgs;
653 for (auto it = g_options.outFiles.constBegin(); it != g_options.outFiles.constEnd(); ++it)
654 testAppArgs += "-o %1,%2 "_L1.arg(deviceOutputFileName(it.key(), it.value()), it.key());
655
656 testAppArgs += unhandledArgs.join(u' ').trimmed();
657 testAppArgs = "\"%1\""_L1.arg(testAppArgs.trimmed());
658 const QString activityName = "%1/%2"_L1.arg(g_options.package).arg(g_options.activity);
659
660 // Pass over any qt or testlib env vars if set
661 QStringList testEnvVarArgs;
662 const QStringList envVarsList = QProcessEnvironment::systemEnvironment().toStringList();
663 for (const QString &var : envVarsList) {
664 if (!var.startsWith("QTEST_"_L1) && !var.startsWith("QT_"_L1))
665 continue;
666 const qsizetype index = var.indexOf(u'=');
667 if (index < 0)
668 continue;
669 const QString key = var.left(index);
670 QString escapedValue = var.mid(index + 1);
671 escapedValue.replace("'"_L1, "'\\''"_L1);
672 const QString value = "'%1'"_L1.arg(escapedValue);
673 testEnvVarArgs << "-e"_L1 << ("extraenvvars_"_L1 + key) << value;
674 }
675
676 g_options.amStarttestArgs = { "shell"_L1, "am"_L1, "start"_L1, "-W"_L1,
677 "-n"_L1, activityName,
678 "-e"_L1, "applicationArguments"_L1, testAppArgs };
679 g_options.amStarttestArgs.append(testEnvVarArgs);
680
681 return true;
682}
683
684static int getPid(const QString &package)
685{
686 const QByteArray output = execAdbCommand({ "shell"_L1, "pidof"_L1, "-s"_L1, package }, false);
687 if (output.isNull())
688 return -1;
689
690 bool ok = false;
691 // Android 9's toybox ignores -s and lists every match; a fork()ing test has two.
692 const int pid = output.simplified().split(' ').constFirst().toInt(&ok);
693 return ok && pid > 0 ? pid : -1;
694}
695
696static QString runCommandAsUserArgs(const QString &cmd)
697{
698 return "run-as %1 --user %2 %3"_L1.arg(g_options.package, g_testInfo.userId, cmd);
699}
700
701// Returns nullopt when `adb devices` itself failed, so callers don't confuse
702// a transient daemon hiccup with "device disconnected".
704{
705 const QByteArray output = execAdbCommand({ "devices"_L1 }, false);
706 if (output.isNull())
707 return std::nullopt;
708
709 QStringList devices;
710 for (const QByteArray &line : output.split(u'\n')) {
711 if (line.contains("\tdevice"_L1))
712 devices.append(QString::fromUtf8(line.split(u'\t').first()));
713 }
714
715 return devices;
716}
717
719{
720 const auto devices = runningDevices();
721 return devices && !devices->contains(g_options.serial);
722}
723
724static bool isRunning() {
725 if (g_testInfo.deviceGone.load())
726 return false;
727
728 if (getPid(g_options.package) > 0)
729 return true;
730
731 // No pid means the test exited, but adb failing looks the same; check the
732 // device list to tell them apart and flag a disconnect when warranted.
733 if (!g_options.serial.isEmpty() && deviceDisconnected())
734 g_testInfo.deviceGone.store(true);
735
736 return false;
737}
738
739static bool pollUntil(qxp::function_ref<bool() const> predicate,
740 QDeadlineTimer deadline,
741 std::chrono::nanoseconds interval)
742{
743 do {
744 if (predicate())
745 return true;
746 QThread::sleep(interval);
747 } while (!deadline.hasExpired() && !g_testInfo.isTestRunnerInterrupted.load());
748 if (g_testInfo.isTestRunnerInterrupted.load())
749 return false;
750 // Predicate may have flipped during the final sleep; check once more.
751 return predicate();
752}
753
754static void waitForStarted()
755{
756 using namespace std::chrono_literals;
757 // Grab the pid for logcat filtering if pidof catches it, but don't block
758 // on a short-lived process that waitForFinished tracks by presence anyway
759 pollUntil([]() {
760 const int pid = getPid(g_options.package);
761 if (pid > 0)
762 g_testInfo.pid = pid;
763 return pid > 0 || !isRunning();
764 }, QDeadlineTimer(10s), 100ms);
765}
766
768{
769 using namespace std::chrono_literals;
770 if (g_options.stdoutFileName.isEmpty())
771 return false;
772 const QString existsCmd = "head -c 0 files/%1 2>/dev/null"_L1.arg(g_options.stdoutFileName);
773 const QStringList adbExistsCmd = { "shell"_L1, runCommandAsUserArgs(existsCmd) };
774 auto fileExists = [&]() { return !execAdbCommand(adbExistsCmd, false).isNull(); };
775 // Wait for the output file, but stop early if the test exits first
776 pollUntil([&]() { return fileExists() || !isRunning(); }, QDeadlineTimer(5s), 25ms);
777 return fileExists();
778}
779
780static bool setupStdoutLogger()
781{
782 // Empty stdoutFileName means file-only output; nothing to stream live.
783 if (g_options.stdoutFileName.isEmpty())
784 return true;
785
786 const QString tailPipeCmd = "tail -n +1 -f 'files/%1'"_L1.arg(g_options.stdoutFileName);
787 const QStringList adbTailCmd = { "shell"_L1, runCommandAsUserArgs(tailPipeCmd) };
788
789 g_options.stdoutLogger.emplace();
790 g_options.stdoutLogger->setProcessChannelMode(QProcess::ForwardedOutputChannel);
791 g_options.stdoutLogger->start(g_options.adbCommand, adbArgsWithSerial(adbTailCmd));
792 g_testInfo.stdoutLoggerPid.store(g_options.stdoutLogger->processId());
793
794 if (!g_options.stdoutLogger->waitForStarted()) {
795 g_testInfo.stdoutLoggerPid.store(0);
796 qCritical() << "Error: failed to run adb command to fetch stdout test results.";
797 g_options.stdoutLogger = std::nullopt;
798 return false;
799 }
800
801 return true;
802}
803
804static bool stopStdoutLogger()
805{
806 if (!g_options.stdoutLogger.has_value())
807 return true;
808
809 if (g_options.stdoutLogger->state() == QProcess::NotRunning) {
810 // sigHandler already SIGTERM'd the logger; that's expected.
811 if (g_testInfo.isTestRunnerInterrupted.load())
812 return true;
813 qCritical() << "The stdout logger process was terminated unexpectedly, "
814 "It might have been terminated by an external process";
815 return false;
816 }
817
818 g_options.stdoutLogger->terminate();
819 g_testInfo.stdoutLoggerPid.store(0);
820
821 if (!g_options.stdoutLogger->waitForFinished(5000)) {
822 g_options.stdoutLogger->kill();
823 g_options.stdoutLogger->waitForFinished();
824 qCritical() << "Error: adb test results tail command timed out.";
825 return false;
826 }
827
828 return true;
829}
830
831static void waitForFinished()
832{
833 using namespace std::chrono_literals;
834 const bool finished = pollUntil([]() { return !isRunning(); },
835 QDeadlineTimer(g_options.timeoutSecs * 1s), 100ms);
836 if (!finished && !g_testInfo.isTestRunnerInterrupted.load())
837 qWarning() << "Timed out while waiting for the test to finish";
838}
839
840static void obtainSdkVersion()
841{
842 // Best-effort: SDK version gates userId() for multi-user, legacyDate formatting,
843 // and ApplicationExitInfo queries. Falling back to defaults is safe.
844 const QStringList versionArgs = { "shell"_L1, "getprop"_L1, "ro.build.version.sdk"_L1 };
845 const QByteArray output = execAdbCommand(versionArgs, false);
846 if (output.isNull()) {
847 qWarning() << "Unable to query the SDK version: adb getprop ro.build.version.sdk failed.";
848 return;
849 }
850 bool ok = false;
851 int sdkVersion = output.toInt(&ok);
852 if (ok)
853 g_testInfo.sdkVersion = sdkVersion;
854 else
855 qWarning("Unable to parse SDK version from adb getprop output: '%s'.", output.constData());
856}
857
859{
860 // adb get-current-user command is available starting from API level 26.
861 QByteArray userId;
862 if (g_testInfo.sdkVersion >= 26) {
863 const QStringList userIdArgs = {"shell"_L1, "cmd"_L1, "activity"_L1, "get-current-user"_L1};
864 userId = execAdbCommand(userIdArgs, false);
865 if (userId.isNull())
866 qCritical() << "Error: failed to retrieve the user ID";
867 }
868
869 if (userId.isEmpty())
870 userId = "0";
871
872 return QString::fromUtf8(userId.simplified());
873}
874
875static QByteArray adbReadAppFile(const QString &fileName, int retries,
876 std::chrono::milliseconds backoff)
877{
878 const QString catCmd = "cat files/%1 2> /dev/null"_L1.arg(fileName);
879 const QStringList args = { "shell"_L1, runCommandAsUserArgs(catCmd) };
880 while (retries > 0) {
881 const QByteArray output = execAdbCommand(args, false);
882 if (!output.isEmpty())
883 return output;
884 if (--retries)
885 QThread::msleep(backoff.count());
886 }
887 return QByteArray();
888}
889
890static bool pullResults()
891{
892 using namespace std::chrono_literals;
893 for (auto it = g_options.outFiles.constBegin(); it != g_options.outFiles.constEnd(); ++it) {
894 const QString filePath = it.value();
895 if (filePath.isEmpty())
896 continue; // stdout-streamed format so nothing to pull
897 const QString fileName = QFileInfo(filePath).fileName();
898
899 const QByteArray output = adbReadAppFile(fileName, g_options.resultsPullRetries, 200ms);
900 if (output.isNull()) {
902 g_testInfo.deviceGone.store(true);
903 qCritical() << "Error: failed to retrieve test result file %1 (missing or empty)."_L1
904 .arg(fileName);
905 return false;
906 }
907
908 QFile out{filePath};
909 if (!out.open(QIODevice::WriteOnly)) {
910 qCritical() << "Error: failed to open %1 to write results to host."_L1.arg(filePath);
911 return false;
912 }
913 if (out.write(output) != output.size()) {
914 qCritical() << "Error: short write of results to %1: %2"_L1
915 .arg(filePath).arg(out.errorString());
916 return false;
917 }
918 }
919
920 return true;
921}
922
924{
925 QString libsPath = "%1/libs/"_L1.arg(g_options.buildPath);
926 if (!QDir(libsPath).exists())
927 libsPath = "%1/app/libs/"_L1.arg(g_options.buildPath);
928 const QStringList abiArgs = { "shell"_L1, "getprop"_L1, "ro.product.cpu.abi"_L1 };
929 QByteArray abi = execAdbCommand(abiArgs, false).trimmed();
930 if (abi.isEmpty()) {
931 const QStringList subDirs = QDir(libsPath).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
932 if (!subDirs.isEmpty())
933 abi = subDirs.first().toUtf8();
934 }
935
936 if (abi.isEmpty())
937 return {};
938
939 return libsPath + QString::fromUtf8(abi);
940}
941
942static void printLogcatCrash(const QByteArray &logcat)
943{
944 // No crash report, do nothing
945 if (logcat.isEmpty())
946 return;
947
948 QByteArray crashLogcat(logcat);
949 if (g_options.ndkStackPath.isEmpty()) {
950 qWarning() << "Warning: ndk-stack path not provided and couldn't be deduced "
951 "using the ANDROID_NDK_ROOT or ANDROID_NDK_HOME environment "
952 "variables.";
953 } else if (const QString libsPath = getAbiLibsPath(); libsPath.isEmpty()) {
954 qWarning() << "Warning: could not determine the device ABI, "
955 "skipping ndk-stack and printing the raw dump.";
956 } else {
957 QProcess ndkStackProc;
958 ndkStackProc.start(g_options.ndkStackPath, { "-sym"_L1, libsPath });
959
960 if (ndkStackProc.waitForStarted()) {
961 ndkStackProc.write(crashLogcat);
962 ndkStackProc.closeWriteChannel();
963
964 // Drain ndk-stack to completion so its output isn't truncated.
965 if (ndkStackProc.waitForFinished()) {
966 // Keep the raw dump if ndk-stack produced no output.
967 const QByteArray ndkOutput = ndkStackProc.readAllStandardOutput();
968 if (!ndkOutput.trimmed().isEmpty())
969 crashLogcat = ndkOutput;
970 } else {
971 qCritical() << "Error: ndk-stack command timed out.";
972 ndkStackProc.kill();
973 ndkStackProc.waitForFinished();
974 }
975 } else {
976 qCritical() << "Error: failed to run ndk-stack command.";
977 }
978 }
979
980 if (crashLogcat.startsWith("********** Crash dump")) {
981 qDebug().noquote() << crashLogcat.trimmed();
982 } else {
983 qDebug() << "[androidtestrunner] ********** BEGIN crash dump **********";
984 qDebug().noquote() << crashLogcat.trimmed();
985 qDebug() << "[androidtestrunner] ********** END crash dump **********";
986 }
987}
988
989// Shortened from debuggerd's full banner so emulator/oem builds that wrap
990// or truncate the line still slice cleanly.
991static constexpr auto crashBannerMarker = "*** *** *** *** *** *** *** ***";
992
993static QByteArray fetchLogcat(const QString &timeStamp, bool waitForDiagnostics)
994{
995 using namespace std::chrono_literals;
996 // Read all three default buffers explicitly: crashes land in crash,
997 // ANR notices in system, and the test's QtTestLib/Qt output in main.
998 QStringList logcatArgs = { "shell"_L1, "logcat"_L1,
999 "-b"_L1, "main,system,crash"_L1,
1000 "-v"_L1, "brief"_L1 };
1001 // Without a timestamp the time arg is useless; cap by line count instead.
1002 if (!timeStamp.isEmpty())
1003 logcatArgs << "-t"_L1 << "'%1'"_L1.arg(timeStamp);
1004 else
1005 logcatArgs << "-t"_L1 << "5000"_L1;
1006 const bool useColor = !QTestCiDetect::ciInTestEnvironment();
1007 if (useColor)
1008 logcatArgs << "-v"_L1 << "color"_L1;
1009
1010 QByteArray logcat = execAdbCommand(logcatArgs, false);
1011 if (logcat.isNull())
1012 qWarning() << "Warning: failed to fetch logcat of the test";
1013
1014 if (!waitForDiagnostics)
1015 return logcat;
1016
1017 const QByteArray anrMarker = "ANR in " + g_options.package.toUtf8();
1018 if (logcat.contains(crashBannerMarker) || logcat.contains(anrMarker))
1019 return logcat;
1020
1021 // Debuggerd banner and ANR notice land seconds after death; poll for them.
1022 QByteArray polled;
1023 constexpr auto timeout = 15s;
1024 const bool found = pollUntil([&]() {
1025 polled = execAdbCommand(logcatArgs, false);
1026 return !polled.isNull()
1027 && (polled.contains(crashBannerMarker) || polled.contains(anrMarker));
1028 }, QDeadlineTimer(timeout), 250ms);
1029 if (!polled.isEmpty())
1030 logcat = std::move(polled);
1031 if (!found && !g_testInfo.isTestRunnerInterrupted.load()) {
1032 qWarning().noquote() << QString::fromLatin1("[androidtestrunner] No crash banner or "
1033 "ANR marker found in logcat within %1s; output below may be incomplete.")
1034 .arg(timeout.count());
1035 }
1036 return logcat;
1037}
1038
1039static QByteArray takeCrashDump(QByteArray *logcat)
1040{
1041 const qsizetype idx = logcat->indexOf(crashBannerMarker);
1042 if (idx == -1)
1043 return {};
1044 QByteArray dump = logcat->mid(idx);
1045 *logcat = logcat->left(idx);
1046 return dump;
1047}
1048
1049static QByteArray filterTestLogcat(const QByteArray &logcat, int testPid, int systemServerPid)
1050{
1051 // No pid to anchor on: return the logcat unfiltered.
1052 if (testPid <= 0)
1053 return logcat;
1054
1055 static const QRegularExpression logcatRegEx{
1056 "(?:^\\x1B\\‍[[0-9;]*m)?" // color
1057 "(\\w)/" // message type 1. capture
1058 ".*?" // source (non-greedy so the pid capture group binds first)
1059 "(\\‍(\\s*\\d*\\‍)):" // pid 2. capture
1060 "\\s*"
1061 ".*" // message
1062 "(?:\\x1B\\‍[[0-9;]*m)?" // color
1063 "[\\n\\r]*$"_L1
1064 };
1065 QByteArrayList kept;
1066 for (const QByteArray &line : logcat.split(u'\n')) {
1067 QRegularExpressionMatch match = logcatRegEx.match(QString::fromUtf8(line));
1068 if (!match.hasMatch()) {
1069 // Unparseable line; keep it rather than drop silently.
1070 kept.append(line);
1071 continue;
1072 }
1073 const QString msgType = match.captured(1);
1074 const QString pidStr = match.captured(2);
1075 const int capturedPid = pidStr.mid(1, pidStr.size() - 2).trimmed().toInt();
1076 const bool isFatal = msgType == u'F';
1077 const bool isOurTest = capturedPid == testPid;
1078 const bool isAnrSource = systemServerPid > 0 && capturedPid == systemServerPid;
1079 if (isOurTest || isFatal || isAnrSource)
1080 kept.append(line);
1081 }
1082 return kept.join('\n');
1083}
1084
1085static void analyseLogcat(const QString &timeStamp, int *exitCode)
1086{
1087 const bool wasAbnormal = !isTestExitCodeNormal(*exitCode)
1088 && !g_testInfo.isTestRunnerInterrupted.load();
1089 QByteArray logcat = fetchLogcat(timeStamp, wasAbnormal);
1090 if (logcat.isEmpty()) {
1092 qWarning() << "The retrieved logcat is empty";
1093 return;
1094 }
1095
1096 const QByteArray crashDump = takeCrashDump(&logcat);
1097
1098 const bool anrOccurred = logcat.contains(
1099 "ANR in %1"_L1.arg(g_options.package).toUtf8());
1100 if (anrOccurred) {
1101 // ANR may fire after a clean exit code. Surface it via the exit code,
1102 // but preserve other abnormal codes.
1103 if (isTestExitCodeNormal(*exitCode) || *exitCode == EXIT_NOEXITCODE)
1104 *exitCode = EXIT_ANR;
1105 qCritical("[androidtestrunner] An ANR has occurred while running the test '%s';"
1106 " consult logcat for additional logs from the system_server process",
1107 qPrintable(g_options.package));
1108 }
1109
1110 const int systemServerPid = anrOccurred ? getPid("system_server"_L1) : -1;
1111 const QByteArray filtered = filterTestLogcat(logcat, g_testInfo.pid, systemServerPid);
1112
1113 // Print whenever the caller asked (--show-logcat) or the test exited
1114 // abnormally; the crash buffer is only meaningful on abnormal exit.
1115 const bool testCrashed = !isTestExitCodeNormal(*exitCode)
1116 && !g_testInfo.isTestRunnerInterrupted.load();
1117 if (g_options.showLogcatOutput || testCrashed) {
1118 qDebug() << "[androidtestrunner] ********** BEGIN logcat dump **********";
1119 qDebug().noquote() << filtered.trimmed();
1120 qDebug() << "[androidtestrunner] ********** END logcat dump **********";
1121 }
1122 if (testCrashed && !crashDump.isEmpty())
1123 printLogcatCrash(crashDump);
1124}
1125
1127{
1128 const bool legacyDate = g_testInfo.sdkVersion > 0 && g_testInfo.sdkVersion <= 23;
1129 const QString timeFormat = legacyDate ?
1130 "%m-%d %H:%M:%S.000"_L1 : "%Y-%m-%d %H:%M:%S.%3N"_L1;
1131
1132 QStringList dateArgs = { "shell"_L1, "date"_L1, "+'%1'"_L1.arg(timeFormat) };
1133 const QByteArray output = execAdbCommand(dateArgs, false);
1134 if (output.isNull()) {
1135 qWarning() << "[androidtestrunner] ERROR in command: adb shell date";
1136 return {};
1137 }
1138
1139 return QString::fromUtf8(output.simplified());
1140}
1141
1142static int testExitCode()
1143{
1144 using namespace std::chrono_literals;
1145 const QByteArray exitCodeOutput =
1146 adbReadAppFile(u"qtest_last_exit_code"_s, g_options.resultsPullRetries, 200ms);
1147 if (exitCodeOutput.isNull()) {
1149 g_testInfo.deviceGone.store(true);
1150 qCritical() << "[androidtestrunner] ERROR in command: adb shell cat"
1151 " files/qtest_last_exit_code";
1152 return EXIT_NOEXITCODE;
1153 }
1154 qDebug() << "[androidtestrunner] Test exitcode: " << exitCodeOutput;
1155
1156 bool ok;
1157 int exitCode = exitCodeOutput.toInt(&ok);
1158
1159 return ok ? exitCode : EXIT_NOEXITCODE;
1160}
1161
1163{
1164 return !execAdbCommand({ "uninstall"_L1, g_options.package }).isNull();
1165}
1166
1167
1168void sigHandler(int signal)
1169{
1170#if !defined(Q_OS_WIN32)
1171 // Reap the adb-tail subprocess so a second SIGINT doesn't orphan it.
1172 const qint64 loggerPid = g_testInfo.stdoutLoggerPid.exchange(0);
1173 if (loggerPid > 0)
1174 ::kill(static_cast<pid_t>(loggerPid), SIGTERM);
1175#endif
1176 std::signal(signal, SIG_DFL);
1177 if (!g_testInfo.isPackageInstalled.load())
1178 _exit(EXIT_ERROR);
1179 g_testInfo.isTestRunnerInterrupted.store(true);
1180}
1181
1182int main(int argc, char *argv[])
1183{
1184 using namespace std::chrono_literals;
1185 std::signal(SIGINT, sigHandler);
1186 std::signal(SIGTERM, sigHandler);
1187
1188 QCoreApplication a(argc, argv);
1189 if (!parseOptions())
1190 return EXIT_ERROR;
1191
1192 if (g_options.makeCommand.isEmpty()) {
1193 qCritical() << "It is required to provide a make command with the \"--make\" parameter "
1194 "to generate the apk.";
1195 return EXIT_ERROR;
1196 }
1197
1198 if (execCommand(g_options.makeCommand, true, g_options.timeoutSecs * 1s).isNull()) {
1199 qCritical("The APK build command \"%s\" failed.", qPrintable(g_options.makeCommand));
1200 return EXIT_ERROR;
1201 }
1202
1203 if (!QFile::exists(g_options.packagePath)) {
1204 qCritical("No package \"%s\" found after running the make command. "
1205 "Check the provided path and the make command.",
1206 qPrintable(g_options.packagePath));
1207 return EXIT_ERROR;
1208 }
1209
1210 const std::optional<QStringList> devices = runningDevices();
1211 if (!devices) {
1212 qCritical("Failed to query connected devices via 'adb devices'.");
1213 return EXIT_ERROR;
1214 } else if (devices->isEmpty()) {
1215 qCritical("No connected devices or running emulators can be found.");
1216 return EXIT_ERROR;
1217 } else if (!g_options.serial.isEmpty() && !devices->contains(g_options.serial)) {
1218 qCritical("No connected device or running emulator with serial '%s' can be found.",
1219 qPrintable(g_options.serial));
1220 return EXIT_ERROR;
1221 } else if (g_options.serial.isEmpty() && devices->size() == 1) {
1222 g_options.serial = devices->first();
1223 } else if (g_options.serial.isEmpty()) {
1224 qCritical("Multiple devices connected, set ANDROID_SERIAL or ANDROID_DEVICE_SERIAL.");
1225 return EXIT_ERROR;
1226 }
1227
1229
1230 g_testInfo.userId = userId();
1231
1233 return EXIT_ERROR;
1234
1235 const QString ns = getGradleProjectProperty(g_options.buildPath, "android.namespace"_L1);
1236 if (!ns.isEmpty())
1237 g_options.package = ns;
1238
1239 if (g_options.package.isEmpty()) {
1240 qCritical("Unable to get package name for '%s'", qPrintable(g_options.packagePath));
1241 return EXIT_ERROR;
1242 }
1243
1244 // parseTestArgs depends on g_options.package
1245 if (!parseTestArgs())
1246 return EXIT_ERROR;
1247
1248 // Per-user prefix so a shared TempLocation doesn't collide across users.
1249 const QString user = qEnvironmentVariable("USER",
1250 qEnvironmentVariable("USERNAME", u"default"_s));
1251 const QString lockName = u"androidtestrunner-%1-%2.lock"_s.arg(user, g_options.serial);
1252 const QDir tempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
1253 QLockFile testRunnerLock(tempDir.absoluteFilePath(lockName));
1254 testRunnerLock.setStaleLockTime(0);
1255 if (!testRunnerLock.lock()) {
1256 qCritical("Failed to acquire test runner lock for '%s'.", qPrintable(g_options.serial));
1257 return EXIT_ERROR;
1258 }
1259
1260 if (g_options.packagePath.endsWith(".apk"_L1)) {
1261 const QStringList installArgs = { "install"_L1, "-r"_L1, g_options.packagePath };
1262 if (execAdbCommand(installArgs, true, 5min).isNull())
1263 return EXIT_ERROR;
1264 } else if (g_options.packagePath.endsWith(".aab"_L1)) {
1265 QFileInfo aab(g_options.packagePath);
1266 const auto apksFilePath = aab.absoluteDir().absoluteFilePath(aab.baseName() + ".apks"_L1);
1267 QStringList installApksArgs = { "install-apks"_L1, "--apks"_L1, apksFilePath };
1268 if (!g_options.serial.isEmpty())
1269 installApksArgs << "--device-id"_L1 << g_options.serial;
1270 if (execBundletoolCommand({ "build-apks"_L1, "--bundle"_L1, g_options.packagePath,
1271 "--output"_L1, apksFilePath, "--local-testing"_L1,
1272 "--overwrite"_L1 }).isNull()
1273 || execBundletoolCommand(installApksArgs).isNull())
1274 return EXIT_ERROR;
1275 }
1276 g_testInfo.isPackageInstalled.store(true);
1277
1278 const QStringList dangerousPermissions = queryDangerousPermissions();
1279 for (const auto &permission : g_options.permissions) {
1280 if (!dangerousPermissions.contains(permission))
1281 continue;
1282
1283 if (execAdbCommand({ "shell"_L1, "pm"_L1, "grant"_L1, "--user"_L1, g_testInfo.userId,
1284 g_options.package, permission }).isNull()) {
1285 qWarning("Unable to grant '%s' to '%s'. Probably the Android version mismatch.",
1286 qPrintable(permission), qPrintable(g_options.package));
1287 }
1288 }
1289
1290 // Call additional adb command if set after installation and before starting the test
1291 for (const auto &command : g_options.preTestRunAdbCommands) {
1292 if (execAdbCommand(command).isNull()) {
1293 qCritical("The pre test ADB command \"%s\" failed.",
1294 qUtf8Printable(command.join(u' ')));
1295 return EXIT_ERROR;
1296 }
1297 }
1298
1299 // Pre test start
1300 const QString formattedStartTime = getCurrentTimeString();
1301
1302 // Start the test
1303 if (execAdbCommand(g_options.amStarttestArgs).isNull()) {
1304 // am start -W never returns when the app crashes before main; treat the
1305 // failure as a launch-time crash and surface it from logcat.
1306 int exitCode = EXIT_NOEXITCODE;
1307 analyseLogcat(formattedStartTime, &exitCode);
1308 return exitCode;
1309 }
1310
1312
1314 qWarning("Continuing without live stdout streaming; result files are still pulled.");
1315
1317
1318 if (g_testInfo.deviceGone.load()) {
1319 qCritical("[androidtestrunner] Device '%s' became unreachable during the test, "
1320 "result transfer and uninstall skipped.", qPrintable(g_options.serial));
1322 return EXIT_DEVICE_GONE;
1323 }
1324
1325 // Post test run
1326 if (!stopStdoutLogger())
1327 return EXIT_ERROR;
1328
1329 int exitCode = testExitCode();
1330
1332 analyseLogcat(formattedStartTime, &exitCode);
1333
1334 const bool pullRes = pullResults();
1335 if (g_testInfo.deviceGone.load()) {
1336 qCritical("[androidtestrunner] Device '%s' became unreachable during cleanup, "
1337 "uninstall skipped.", qPrintable(g_options.serial));
1338 return EXIT_DEVICE_GONE;
1339 }
1340 if (!pullRes && isTestExitCodeNormal(exitCode))
1341 exitCode = EXIT_NORESULTS;
1342
1344 qWarning("Failed to uninstall test package '%s'. The test exit code is preserved.",
1345 qPrintable(g_options.package));
1346 }
1347
1348 if (g_testInfo.isTestRunnerInterrupted.load()) {
1349 qCritical() << "The androidtestrunner was interrupted and the test was cleaned up.";
1350 return EXIT_ERROR;
1351 }
1352
1353 return exitCode;
1354}
static QByteArray execCommand(const QString &command, bool verbose=true, std::chrono::milliseconds timeout=std::chrono::milliseconds(-1))
Definition main.cpp:201
static QByteArray execCommand(const QString &program, const QStringList &args, bool verbose=false, std::chrono::milliseconds timeout=std::chrono::milliseconds(-1))
Definition main.cpp:104
static QString userId()
Definition main.cpp:858
static QString runCommandAsUserArgs(const QString &cmd)
Definition main.cpp:696
static bool setupStdoutLogger()
Definition main.cpp:780
static QByteArray execAdbCommand(const QStringList &args, bool verbose=true, std::chrono::milliseconds timeout=30s)
Definition main.cpp:159
static QString getCurrentTimeString()
Definition main.cpp:1126
static int getPid(const QString &package)
Definition main.cpp:684
static QString getAbiLibsPath()
Definition main.cpp:923
static constexpr int EXIT_DEVICE_GONE
Definition main.cpp:48
static int testExitCode()
Definition main.cpp:1142
static void setOutputFile(QString file, QString format)
Definition main.cpp:596
static bool parseTestArgs()
Definition main.cpp:612
static QByteArray execBundletoolCommand(const QStringList &args, bool verbose=true)
Definition main.cpp:165
static QByteArray adbReadAppFile(const QString &fileName, int retries, std::chrono::milliseconds backoff)
Definition main.cpp:875
static QString deviceOutputFileName(const QString &format, const QString &hostPath)
Definition main.cpp:591
static QByteArray takeCrashDump(QByteArray *logcat)
Definition main.cpp:1039
static std::optional< QStringList > runningDevices()
Definition main.cpp:703
static QString gradleInitScriptPath()
Definition main.cpp:439
static bool deviceDisconnected()
Definition main.cpp:718
static TestInfo g_testInfo
Definition main.cpp:95
static bool isRunning()
Definition main.cpp:724
static bool pullResults()
Definition main.cpp:890
static void obtainSdkVersion()
Definition main.cpp:840
static bool collectPackagePaths(const QStringList &apkValues, const QStringList &aabValues)
Definition main.cpp:182
static constexpr auto crashBannerMarker
Definition main.cpp:991
static bool setPackagePath(const QString &path)
Definition main.cpp:172
static void analyseLogcat(const QString &timeStamp, int *exitCode)
Definition main.cpp:1085
static constexpr int EXIT_NOEXITCODE
Definition main.cpp:45
static constexpr int HIGHEST_QTEST_EXITCODE
Definition main.cpp:41
static void waitForFinished()
Definition main.cpp:831
static constexpr int EXIT_NORESULTS
Definition main.cpp:47
static bool parseOptions()
Definition main.cpp:280
static QString ndkStackPath()
Definition main.cpp:260
static bool isTestExitCodeNormal(const int ec)
Definition main.cpp:99
static QStringList queryDangerousPermissions()
Definition main.cpp:545
static constexpr int EXIT_ERROR
Definition main.cpp:43
static QString getGradleProjectProperty(const QString &androidBuildDir, const QString &property)
Definition main.cpp:468
static bool pollUntil(qxp::function_ref< bool() const > predicate, QDeadlineTimer deadline, std::chrono::nanoseconds interval)
Definition main.cpp:739
static QStringList splitOwnAndTestArgs(const QStringList &args, const QSet< QString > &knownOpts, const QSet< QString > &valueOpts)
Definition main.cpp:210
static QByteArray fetchLogcat(const QString &timeStamp, bool waitForDiagnostics)
Definition main.cpp:993
static QByteArray filterTestLogcat(const QByteArray &logcat, int testPid, int systemServerPid)
Definition main.cpp:1049
static void printLogcatCrash(const QByteArray &logcat)
Definition main.cpp:942
void sigHandler(int signal)
Definition main.cpp:1168
static bool waitForLoggingStarted()
Definition main.cpp:767
static void waitForStarted()
Definition main.cpp:754
static bool stopStdoutLogger()
Definition main.cpp:804
static QStringList adbArgsWithSerial(const QStringList &args)
Definition main.cpp:152
static bool uninstallTestPackage()
Definition main.cpp:1162
static bool processAndroidManifest()
Definition main.cpp:501
static constexpr int EXIT_ANR
Definition main.cpp:46
static Options g_options
Definition main.cpp:77
int main(int argc, char *argv[])
[ctor_close]
QString makeCommand
Definition main.cpp:62
QStringList amStarttestArgs
Definition main.cpp:69
std::optional< QProcess > stdoutLogger
Definition main.cpp:74
QStringList permissions
Definition main.cpp:65
QHash< QString, QString > outFiles
Definition main.cpp:68
QString adbCommand
Definition main.cpp:59
int timeoutSecs
Definition main.cpp:55
bool showLogcatOutput
Definition main.cpp:73
QString bundletoolPath
Definition main.cpp:60
int resultsPullRetries
Definition main.cpp:56
QString stdoutFileName
Definition main.cpp:67
bool skipAddInstallRoot
Definition main.cpp:54
QList< QStringList > preTestRunAdbCommands
Definition main.cpp:72
QString package
Definition main.cpp:63
QString serial
Definition main.cpp:61
QString packagePath
Definition main.cpp:70
bool verbose
Definition main.cpp:130
QString ndkStackPath
Definition main.cpp:71
QStringList testArgsList
Definition main.cpp:66
QString manifestPath
Definition main.cpp:58
QString activity
Definition main.cpp:64
QString buildPath
Definition main.cpp:57
QString userId
Definition main.cpp:83
std::atomic< bool > isPackageInstalled
Definition main.cpp:85
int sdkVersion
Definition main.cpp:81
std::atomic< bool > deviceGone
Definition main.cpp:87
int pid
Definition main.cpp:82
std::atomic< qint64 > stdoutLoggerPid
Definition main.cpp:88
std::atomic< bool > isTestRunnerInterrupted
Definition main.cpp:86