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) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
4#include <QCoreApplication>
5#include <QCommandLineParser>
6#include <QCommandLineOption>
7#include <QDebug>
8#include <QDir>
9#include <QDirIterator>
10#include <QFile>
11#include <QFileInfo>
12#include <QHash>
13#include <QJsonDocument>
14#include <QJsonObject>
15#include <QJsonArray>
16#include <QProcess>
17#include <QStandardPaths>
18#include <QString>
19#include <QStringList>
20#include <QSet>
21#include <QElapsedTimer>
22#include <QRegularExpression>
23
24#include "../shared/depfile_shared.h"
25
26using namespace Qt::StringLiterals;
27
28// Global list of all source files that contribute to the HAP
29// Used to generate dependency file for CMake DEPFILE support
31
37
44
45struct Options
46{
51 QStringList projectLibraries; // Project-built libraries from CMake
59 QStringList pluginsImportPaths; // Build-tree plugin search paths (processed before qtPluginsDirectory)
61
62 // Qt installation directories (following androiddeployqt pattern)
63 QString qtLibsDirectory; // Target Qt libs
64 QString qtPluginsDirectory; // Target Qt plugins
65 QString qtQmlDirectory; // Target Qt QML modules
66 QString qtLibExecsDirectory; // Host Qt tools (qmlimportscanner, etc.)
67 QString qtHostDirectory; // Host Qt installation
68 QStringList extraLibsDirs; // Extra library search paths (e.g. HARMONYOS_DEPS_ROOT/lib)
69
70 bool verbose = false;
71 bool releaseMode = false;
72 bool installApk = false; // Keep name for consistency with androiddeployqt
73 bool buildPackage = true;
74
75 QString depFilePath; // Path to write dependency file
76 QString depFileBase; // Base directory for relative paths in depfile
77
78 // HarmonyOS permissions injected via qt_add_harmonyos_permission
80
81 // App-level metadata from the QT_HARMONYOS_APP_* target properties.
82 // Empty/zero means "user did not set this", so harmonydeployqt leaves the
83 // template default in place.
89
90 // SDK versions from the QT_HARMONYOS_*_SDK_VERSION target properties.
91 // Substituted into entry/build-profile.json5. Empty means "leave template
92 // default".
96
97 // Additional plugin .so files from QT_HARMONYOS_EXTRA_PLUGINS.
99
100 // Module-level metadata from the QT_HARMONYOS_MODULE_* and
101 // QT_HARMONYOS_ABILITY_* target properties.
105
106 // Test bundle mode
107 bool testBundleMode = false;
108 QString testBinariesDirectory; // Directory to scan for libtst_*.so
109 QStringList testExcludeList; // Filenames to exclude from test bundle
111
112 // HAP signing material from --signing-* CLI flags (empty = use env vars).
122
124};
125
126static void printHelp()
127{
128 fprintf(stdout, "Usage: harmonydeployqt [options]\n\n"
129 "Options:\n"
130 " --input <file> JSON configuration file (required)\n"
131 " --output <dir> Output directory for generated project\n"
132 " --hvigor <path> Path to hvigorw for building HAP (or set QT_HARMONYOS_HVIGOR)\n"
133 " --install Install HAP to connected device via hdc\n"
134 " --release Build release configuration (default: debug)\n"
135 " --verbose Enable verbose output\n"
136 " --no-build Skip building the HAP\n"
137 " --test-bundle Enable test bundle mode (bundles all test binaries into one HAP)\n"
138 " --depfile <path> Write dependency file for build system\n"
139 " --depfile-base <dir> Base directory for relative paths in depfile\n"
140 " --signing-cert-path <p> .cer file (or QT_HARMONYOS_SIGNING_CERT_PATH)\n"
141 " --signing-profile <p> .p7b profile (or QT_HARMONYOS_SIGNING_PROFILE)\n"
142 " --signing-store-file <p> .p12 keystore (or QT_HARMONYOS_SIGNING_STORE_FILE)\n"
143 " --signing-key-alias <a> Key alias (or QT_HARMONYOS_SIGNING_KEY_ALIAS)\n"
144 " --signing-key-password <s> Encrypted key pwd (or QT_HARMONYOS_SIGNING_KEY_PASSWORD)\n"
145 " --signing-store-password <s> Encrypted store pwd (or QT_HARMONYOS_SIGNING_STORE_PASSWORD)\n"
146 " --signing-plain-key-password <s>\n"
147 " Plain key pwd (or QT_HARMONYOS_SIGNING_PLAIN_KEY_PASSWORD)\n"
148 " --signing-plain-store-password <s>\n"
149 " Plain store pwd (or QT_HARMONYOS_SIGNING_PLAIN_STORE_PASSWORD)\n"
150 " --signing-alg <alg> Signature algorithm, default SHA256withECDSA\n"
151 " (or QT_HARMONYOS_SIGNING_ALG)\n"
152 " --help Show this help\n\n"
153 "Signing: CLI flags above win per field over the matching env vars.\n"
154 "Both passwords must be given either hvigor-encrypted or in plain text.\n"
155 "If any signing input is set, all required values must be present,\n"
156 "otherwise harmonydeployqt fails. With none set the HAP is left unsigned.\n"
157 "With encrypted passwords, hvigor signs the HAP. With plain passwords, the\n"
158 "SDK's hap-sign-tool does, located via the SDK root or\n"
159 "QT_HARMONYOS_HAP_SIGN_TOOL and run with QT_HARMONYOS_JAVA, JAVA_HOME or\n"
160 "java from PATH.\n");
161}
162
163class QProcessExt : public QProcess
164{
165public:
167 connect(this, &QProcess::readyReadStandardOutput, [this]() {
168 QByteArray output = readAllStandardOutput();
169 QString text = QString::fromUtf8(output);
170 fprintf(stderr, "harmonydeployqt: external application output: %s\n", qPrintable(text));
171 });
172 connect(this, &QProcess::readyReadStandardError, [this]() {
173 QByteArray error = readAllStandardError();
174 QString text = QString::fromUtf8(error);
175 fprintf(stderr, "harmonydeployqt: external application error: %s\n", qPrintable(text));
176 });
177 }
178};
179
180static bool parseCommandLine(const QStringList &arguments, Options *options)
181{
182 QCommandLineParser parser;
183 parser.setApplicationDescription("Qt HarmonyOS Deployment Tool"_L1);
184
185 QCommandLineOption inputOption("input"_L1, "JSON configuration file"_L1, "file"_L1);
186 QCommandLineOption outputOption("output"_L1, "Output directory"_L1, "dir"_L1);
187 QCommandLineOption hvigorOption("hvigor"_L1, "Path to hvigorw"_L1, "path"_L1);
188 QCommandLineOption installOption("install"_L1, "Install to device"_L1);
189 QCommandLineOption releaseOption("release"_L1, "Build release configuration"_L1);
190 QCommandLineOption verboseOption("verbose"_L1, "Verbose output"_L1);
191 QCommandLineOption noBuildOption("no-build"_L1, "Skip building"_L1);
192 QCommandLineOption testBundleOption("test-bundle"_L1, "Enable test bundle mode"_L1);
193 QCommandLineOption depfileOption("depfile"_L1, "Dependency file output"_L1, "path"_L1);
194 QCommandLineOption depfileBaseOption("depfile-base"_L1, "Base directory for depfile paths"_L1, "dir"_L1);
195 QCommandLineOption signingCertPathOption("signing-cert-path"_L1,
196 "Path to the .cer file"_L1, "path"_L1);
197 QCommandLineOption signingProfileOption("signing-profile"_L1,
198 "Path to the .p7b profile"_L1, "path"_L1);
199 QCommandLineOption signingStoreFileOption("signing-store-file"_L1,
200 "Path to the .p12 keystore"_L1, "path"_L1);
201 QCommandLineOption signingKeyAliasOption("signing-key-alias"_L1,
202 "Key alias inside the keystore"_L1, "alias"_L1);
203 QCommandLineOption signingKeyPasswordOption("signing-key-password"_L1,
204 "Encrypted key password"_L1, "pwd"_L1);
205 QCommandLineOption signingStorePasswordOption("signing-store-password"_L1,
206 "Encrypted keystore password"_L1, "pwd"_L1);
207 QCommandLineOption signingPlainKeyPasswordOption("signing-plain-key-password"_L1,
208 "Plain text key password"_L1, "pwd"_L1);
209 QCommandLineOption signingPlainStorePasswordOption("signing-plain-store-password"_L1,
210 "Plain text keystore password"_L1, "pwd"_L1);
211 QCommandLineOption signingAlgOption("signing-alg"_L1,
212 "Signature algorithm (default SHA256withECDSA)"_L1, "alg"_L1);
213 QCommandLineOption helpOption("help"_L1, "Show help"_L1);
214
215 parser.addOption(inputOption);
216 parser.addOption(outputOption);
217 parser.addOption(hvigorOption);
218 parser.addOption(installOption);
219 parser.addOption(releaseOption);
220 parser.addOption(verboseOption);
221 parser.addOption(noBuildOption);
222 parser.addOption(testBundleOption);
223 parser.addOption(depfileOption);
224 parser.addOption(depfileBaseOption);
225 parser.addOption(signingCertPathOption);
226 parser.addOption(signingProfileOption);
227 parser.addOption(signingStoreFileOption);
228 parser.addOption(signingKeyAliasOption);
229 parser.addOption(signingKeyPasswordOption);
230 parser.addOption(signingStorePasswordOption);
231 parser.addOption(signingPlainKeyPasswordOption);
232 parser.addOption(signingPlainStorePasswordOption);
233 parser.addOption(signingAlgOption);
234 parser.addOption(helpOption);
235
236 if (!parser.parse(arguments)) {
237 fprintf(stderr, "%s\n", qPrintable(parser.errorText()));
238 return false;
239 }
240
241 if (parser.isSet(helpOption)) {
243 return false;
244 }
245
246 if (!parser.isSet(inputOption)) {
247 fprintf(stderr, "Error: --input option is required\n");
249 return false;
250 }
251
252 options->inputFile = parser.value(inputOption);
253 options->outputDirectory = parser.value(outputOption);
254 options->hvigorPath = parser.value(hvigorOption);
255 options->installApk = parser.isSet(installOption);
256 options->releaseMode = parser.isSet(releaseOption);
257 options->verbose = parser.isSet(verboseOption);
258 options->buildPackage = !parser.isSet(noBuildOption);
259 options->testBundleMode = parser.isSet(testBundleOption);
260 options->depFilePath = parser.value(depfileOption);
261 options->depFileBase = parser.value(depfileBaseOption);
262 options->signingCertPath = parser.value(signingCertPathOption);
263 options->signingProfile = parser.value(signingProfileOption);
264 options->signingStoreFile = parser.value(signingStoreFileOption);
265 options->signingKeyAlias = parser.value(signingKeyAliasOption);
266 options->signingKeyPassword = parser.value(signingKeyPasswordOption);
267 options->signingStorePassword = parser.value(signingStorePasswordOption);
268 options->signingPlainKeyPassword = parser.value(signingPlainKeyPasswordOption);
269 options->signingPlainStorePassword = parser.value(signingPlainStorePasswordOption);
270 options->signingAlg = parser.value(signingAlgOption);
271
272 return true;
273}
274
275// Returns the version of the SDK that hvigor builds with, in build-profile.json5
276// format, for example "26.0.0", or an empty string if it cannot be determined.
277// hvigor uses DEVECO_SDK_HOME; without it, assume the SDK Qt was built with.
278static QString sdkVersion(const QString &sdkRoot)
279{
280 QStringList candidates;
281 const QString devEcoSdkHome = qEnvironmentVariable("DEVECO_SDK_HOME");
282 if (!devEcoSdkHome.isEmpty())
283 candidates << devEcoSdkHome + "/default/sdk-pkg.json"_L1;
284 if (!sdkRoot.isEmpty())
285 candidates << sdkRoot + "/../sdk-pkg.json"_L1;
286 for (const QString &candidate : std::as_const(candidates)) {
287 QFile file(candidate);
288 if (!file.open(QIODevice::ReadOnly))
289 continue;
290 const QJsonObject data = QJsonDocument::fromJson(file.readAll())["data"_L1].toObject();
291 const QString platformVersion = data["platformVersion"_L1].toString();
292 const QString apiVersion = data["apiVersion"_L1].toVariant().toString();
293 if (platformVersion.isEmpty() || apiVersion.isEmpty())
294 return {};
295 return platformVersion;
296 }
297 return {};
298}
299
300static bool readInputConfiguration(Options *options)
301{
302 QFile inputFile(options->inputFile);
303 if (!inputFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
304 fprintf(stderr, "Failed to open input file: %s\n", qPrintable(options->inputFile));
305 return false;
306 }
307
308 QJsonParseError parseError;
309 QJsonDocument doc = QJsonDocument::fromJson(inputFile.readAll(), &parseError);
310 if (doc.isNull()) {
311 fprintf(stderr, "Failed to parse JSON: %s\n", qPrintable(parseError.errorString()));
312 return false;
313 }
314
315 QJsonObject obj = doc.object();
316
317 options->applicationBinary = obj["application-binary"_L1].toString();
318 options->harmonyOsPackageSourceDirectory = obj["harmonyos-package-source-directory"_L1].toString();
319 options->harmonyOsAppName = obj["harmonyos-app-name"_L1].toString();
320 options->harmonyOsAppBundleName = obj["harmonyos-app-bundle-name"_L1].toString();
321 options->sdkRoot = obj["sdk-root"_L1].toString();
322 options->ndkRoot = obj["ndk-root"_L1].toString();
323 // qml-root-path may be a string (legacy) or an array (current).
324 {
325 const QJsonValue rootPathValue = obj["qml-root-path"_L1];
326 if (rootPathValue.isArray()) {
327 for (const QJsonValue &v : rootPathValue.toArray()) {
328 const QString s = v.toString();
329 if (!s.isEmpty())
330 options->qmlRootPaths.append(s);
331 }
332 } else {
333 const QString s = rootPathValue.toString();
334 if (!s.isEmpty())
335 options->qmlRootPaths.append(s);
336 }
337 }
338
339 // Qt installation directories
340 options->qtLibsDirectory = obj["qtLibsDirectory"_L1].toString();
341 options->qtPluginsDirectory = obj["qtPluginsDirectory"_L1].toString();
342 options->qtQmlDirectory = obj["qtQmlDirectory"_L1].toString();
343 options->qtLibExecsDirectory = obj["qtLibExecsDirectory"_L1].toString();
344 options->qtHostDirectory = obj["qtHostDirectory"_L1].toString();
345
346 QJsonArray extraLibsDirsArray = obj["extra-libs-dirs"_L1].toArray();
347 for (const QJsonValue &value : extraLibsDirsArray)
348 options->extraLibsDirs.append(value.toString());
349
350 // Test bundle mode settings (JSON can override CLI flag)
351 if (obj["test-bundle"_L1].toBool())
352 options->testBundleMode = true;
353 options->testBinariesDirectory = obj["test-binaries-directory"_L1].toString();
354 QJsonArray excludeArray = obj["test-exclude-list"_L1].toArray();
355 for (const QJsonValue &value : excludeArray)
356 options->testExcludeList.append(value.toString());
357 const QJsonArray rawfilesArray = obj["test-rawfiles"_L1].toArray();
358 for (const QJsonValue &value : rawfilesArray) {
359 const QJsonObject rawfile = value.toObject();
360 QString destination = QDir::cleanPath(rawfile["destination"_L1].toString());
361 if (destination == "."_L1)
362 destination.clear();
363 if (QDir::isAbsolutePath(destination) || destination == ".."_L1
364 || destination.startsWith("../"_L1)) {
365 fprintf(stderr, "Test rawfile destination is outside the rawfile directory: %s\n",
366 qPrintable(destination));
367 return false;
368 }
369 options->testRawfiles.append({ rawfile["source"_L1].toString(), destination });
370 }
371
372 // Parse project libraries
373 QJsonArray projectLibsArray = obj["project-libraries"_L1].toArray();
374 for (const QJsonValue &value : projectLibsArray)
375 options->projectLibraries.append(value.toString());
376
377 // Parse QML import paths
378 QJsonArray importPathsArray = obj["qml-import-paths"_L1].toArray();
379 for (const QJsonValue &value : importPathsArray)
380 options->qmlImportPaths.append(value.toString());
381
382 // Parse plugins import paths
383 QJsonArray pluginsImportPathsArray = obj["plugins-import-paths"_L1].toArray();
384 for (const QJsonValue &value : pluginsImportPathsArray)
385 options->pluginsImportPaths.append(value.toString());
386
387 // Parse target architectures
388 QJsonArray archArray = obj["harmonyos-target-arch"_L1].toArray();
389 for (const QJsonValue &value : archArray)
390 options->targetArchs.append(value.toString());
391 if (options->targetArchs.isEmpty())
392 options->targetArchs.append("arm64-v8a"_L1);
393
394 // Parse HarmonyOS permissions injected via qt_add_harmonyos_permission
395 options->permissions = obj["permissions"_L1].toArray();
396
397 // App-level metadata injected via the QT_HARMONYOS_APP_* target properties.
398 options->harmonyOsAppVendor = obj["harmonyos-app-vendor"_L1].toString();
399 options->harmonyOsAppVersionCode = obj["harmonyos-app-version-code"_L1].toInt();
400 options->harmonyOsAppVersionName = obj["harmonyos-app-version-name"_L1].toString();
401 options->harmonyOsAppLabel = obj["harmonyos-app-label"_L1].toString();
402 options->harmonyOsAppIcon = obj["harmonyos-app-icon"_L1].toString();
403
404 // SDK versions for entry/build-profile.json5.
405 options->harmonyOsCompatibleSdkVersion =
406 obj["harmonyos-compatible-sdk-version"_L1].toString();
407 options->harmonyOsTargetSdkVersion =
408 obj["harmonyos-target-sdk-version"_L1].toString();
409 options->harmonyOsCompileSdkVersion =
410 obj["harmonyos-compile-sdk-version"_L1].toString();
411 // DevEco Studio asks to add a targetSdkVersion matching the SDK when it is missing.
412 // With an explicit compileSdkVersion the SDK version could exceed it.
413 if (options->harmonyOsTargetSdkVersion.isEmpty()
414 && options->harmonyOsCompileSdkVersion.isEmpty()) {
415 options->harmonyOsTargetSdkVersion = sdkVersion(options->sdkRoot);
416 }
417
418 // Extra plugins (resolved file paths). Categories are derived from the
419 // parent directory name of each path.
420 {
421 const QJsonArray extraPluginsArray =
422 obj["harmonyos-extra-plugins"_L1].toArray();
423 for (const QJsonValue &v : extraPluginsArray) {
424 const QString s = v.toString();
425 if (!s.isEmpty())
426 options->extraPlugins.append(s);
427 }
428 }
429
430 // Module-level metadata injected via the QT_HARMONYOS_MODULE_* and
431 // QT_HARMONYOS_ABILITY_* target properties.
432 options->harmonyOsModuleDescription = obj["harmonyos-module-description"_L1].toString();
433 const QJsonArray deviceTypesArray = obj["harmonyos-module-device-types"_L1].toArray();
434 for (const QJsonValue &value : deviceTypesArray)
435 options->harmonyOsModuleDeviceTypes.append(value.toString());
436 options->harmonyOsAbilityOrientation = obj["harmonyos-ability-orientation"_L1].toString();
437
438 // Validate required fields
439 if (!options->testBundleMode) {
440 if (options->applicationBinary.isEmpty()) {
441 fprintf(stderr, "Error: 'application-binary' not specified in JSON\n");
442 return false;
443 }
444
445 // The settings file is generated at CMake generate time, so it names the
446 // application binary long before the build produces it. Fail early with a
447 // clear reason instead of copying the whole template first and then
448 // tripping over the missing file in copyApplicationBinary().
449 if (!QFile::exists(options->applicationBinary)) {
450 fprintf(stderr, "Error: application binary does not exist: %s\n",
451 qPrintable(options->applicationBinary));
452 fprintf(stderr, " Build the project before running harmonydeployqt.\n");
453 return false;
454 }
455 }
456
457 // Set defaults for test bundle mode
458 if (options->testBundleMode) {
459 if (options->harmonyOsAppBundleName.isEmpty())
460 options->harmonyOsAppBundleName = "org.qtproject.autotests"_L1;
461 if (options->harmonyOsAppName.isEmpty())
462 options->harmonyOsAppName = "QtAutoTests"_L1;
463 }
464
465 // Auto-detect template directory if not specified
466 if (options->harmonyOsPackageSourceDirectory.isEmpty()) {
467 // For test bundle mode, use qtLibsDirectory as starting point;
468 // otherwise start from the application binary location
469 QString searchPath;
470 if (options->testBundleMode && !options->qtLibsDirectory.isEmpty()) {
471 searchPath = QDir::cleanPath(options->qtLibsDirectory);
472 } else if (!options->applicationBinary.isEmpty()) {
473 QFileInfo appInfo(options->applicationBinary);
474 searchPath = QDir::cleanPath(appInfo.absolutePath());
475 }
476
477 if (searchPath.isEmpty()) {
478 fprintf(stderr, "Error: 'harmonyos-package-source-directory' not specified in JSON\n");
479 fprintf(stderr, " and could not auto-detect template location (no search path)\n");
480 return false;
481 }
482
483 if (options->verbose)
484 fprintf(stdout, "Searching for template starting from: %s\n", qPrintable(searchPath));
485
486 // Walk up directory tree to find Qt installation using string manipulation
487 for (int i = 0; i < 10; ++i) {
488 // Check for installed template in share directory (matches CMakeLists.txt install path)
489 QString templatePath = searchPath + "/share/qt6/src/harmonyos/templates"_L1;
490 if (options->verbose) {
491 fprintf(stdout, " Checking: %s ... %s\n", qPrintable(templatePath),
492 QDir(templatePath).exists() ? "FOUND" : "not found");
493 }
494 if (QDir(templatePath).exists()) {
495 options->harmonyOsPackageSourceDirectory = std::move(templatePath);
496 break;
497 }
498
499 // Check for source tree location (development builds)
500 templatePath = searchPath + "/src/harmonyos/templates"_L1;
501 if (options->verbose) {
502 fprintf(stdout, " Checking: %s ... %s\n", qPrintable(templatePath),
503 QDir(templatePath).exists() ? "FOUND" : "not found");
504 }
505 if (QDir(templatePath).exists()) {
506 options->harmonyOsPackageSourceDirectory = std::move(templatePath);
507 break;
508 }
509
510 // Move up one directory by removing last path component
511 const auto lastSlash = searchPath.lastIndexOf('/'_L1);
512 if (lastSlash <= 0) {
513 if (options->verbose)
514 fprintf(stdout, " Reached root directory\n");
515 break;
516 }
517 searchPath.resize(lastSlash);
518 }
519
520 if (options->harmonyOsPackageSourceDirectory.isEmpty()) {
521 fprintf(stderr, "Error: 'harmonyos-package-source-directory' not specified in JSON\n");
522 fprintf(stderr, " and could not auto-detect template location\n");
523 fprintf(stderr, " Please specify the path to the HarmonyOS application template\n");
524 return false;
525 } else if (options->verbose) {
526 fprintf(stdout, "Auto-detected template: %s\n", qPrintable(options->harmonyOsPackageSourceDirectory));
527 }
528 }
529
530 if (options->harmonyOsAppName.isEmpty()) {
531 fprintf(stderr, "Error: 'harmonyos-app-name' not specified in JSON\n");
532 return false;
533 }
534
535 if (options->harmonyOsAppBundleName.isEmpty()) {
536 fprintf(stderr, "Error: 'harmonyos-app-bundle-name' not specified in JSON\n");
537 return false;
538 }
539
540 // Set default output directory if not specified
541 if (options->outputDirectory.isEmpty()) {
542 if (options->testBundleMode) {
543 options->outputDirectory = QDir::currentPath() + "/harmonyos-tests-bundle"_L1;
544 } else {
545 QFileInfo appInfo(options->applicationBinary);
546 options->outputDirectory = QDir::currentPath() + "/"_L1 +
547 appInfo.completeBaseName() + "-harmonyos"_L1;
548 }
549 }
550
551 if (options->verbose) {
552 fprintf(stdout, "Configuration loaded:\n");
553 if (options->testBundleMode) {
554 fprintf(stdout, " Mode: test bundle\n");
555 fprintf(stdout, " Test binaries directory: %s\n", qPrintable(options->testBinariesDirectory));
556 if (!options->testExcludeList.isEmpty())
557 fprintf(stdout, " Exclude list: %s\n", qPrintable(options->testExcludeList.join(", "_L1)));
558 } else {
559 fprintf(stdout, " Application binary: %s\n", qPrintable(options->applicationBinary));
560 }
561 fprintf(stdout, " Template directory: %s\n", qPrintable(options->harmonyOsPackageSourceDirectory));
562 fprintf(stdout, " App name: %s\n", qPrintable(options->harmonyOsAppName));
563 fprintf(stdout, " Bundle name: %s\n", qPrintable(options->harmonyOsAppBundleName));
564 fprintf(stdout, " Output directory: %s\n", qPrintable(options->outputDirectory));
565 fprintf(stdout, " Target architectures: %s\n", qPrintable(options->targetArchs.join(", "_L1)));
566 }
567
568 return true;
569}
570
571static bool copyFileIfNewer(const QString &sourceFileName,
572 const QString &destinationFileName, bool verbose,
573 bool forceOverwrite = false)
574{
575 if (QFile::exists(destinationFileName)) {
576 QFileInfo destinationFileInfo(destinationFileName);
577 QFileInfo sourceFileInfo(sourceFileName);
578
579 // Skip if destination is same or newer (unless forcing overwrite)
580 if (!forceOverwrite &&
581 sourceFileInfo.lastModified() <= destinationFileInfo.lastModified()) {
582 if (verbose)
583 fprintf(stdout, " Skipping: %s (destination is up to date)\n",
584 qPrintable(sourceFileInfo.fileName()));
585 return true;
586 }
587
588 // Remove old file before copying
589 if (!QFile(destinationFileName).remove()) {
590 fprintf(stderr, "Failed to remove old file: %s\n",
591 qPrintable(destinationFileName));
592 return false;
593 }
594 }
595
596 // Ensure destination directory exists
597 QFileInfo destInfo(destinationFileName);
598 if (!QDir().mkpath(destInfo.absolutePath())) {
599 fprintf(stderr, "Failed to create directory for: %s\n", qPrintable(destinationFileName));
600 return false;
601 }
602
603 if (verbose)
604 fprintf(stdout, " Copying: %s\n", qPrintable(QFileInfo(sourceFileName).fileName()));
605
606 QFile sourceFile(sourceFileName);
607 if (!sourceFile.copy(destinationFileName)) {
608 fprintf(stderr, "Failed to copy file: %s to %s: %s\n", qPrintable(sourceFileName),
609 qPrintable(destinationFileName), qPrintable(sourceFile.errorString()));
610 return false;
611 }
612
613 return true;
614}
615
616// Write dependency file for CMake DEPFILE support
617static bool writeDepfile(const Options &options, const QString &hapOutputPath)
618{
619 if (options.depFilePath.isEmpty())
620 return true; // Not requested
621
622 if (options.verbose)
623 fprintf(stdout, "Writing dependency file: %s\n", qPrintable(options.depFilePath));
624
625 // Calculate relative HAP path from depfile base directory
626 QString relativeHapPath;
627 if (!options.depFileBase.isEmpty() && !hapOutputPath.isEmpty())
628 relativeHapPath = QDir(options.depFileBase).relativeFilePath(hapOutputPath);
629 else
630 relativeHapPath = hapOutputPath;
631
632 // Open depfile for writing
633 QFile depFile(options.depFilePath);
634 if (!depFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
635 fprintf(stderr, "Failed to open depfile: %s\n", qPrintable(options.depFilePath));
636 return false;
637 }
638
639 // Write Makefile-style dependency format: target: dep1 \ dep2 \ ...
640 depFile.write(escapeAndEncodeDependencyPath(relativeHapPath));
641 depFile.write(": ");
642
643 for (const QString &dep : dependenciesForDepfile) {
644 depFile.write(" \\\n ");
645 depFile.write(escapeAndEncodeDependencyPath(dep));
646 }
647
648 depFile.write("\n");
649 depFile.close();
650
651 if (options.verbose)
652 fprintf(stdout, "Wrote %lld dependencies to depfile\n",
653 static_cast<long long>(dependenciesForDepfile.size()));
654
655 return true;
656}
657
658static bool copyRecursively(const QString &sourceDir, const QString &destDir, bool verbose,
659 const QString &topDest = {})
660{
661 QDir srcDir(sourceDir);
662 if (!srcDir.exists()) {
663 fprintf(stderr, "Source directory does not exist: %s\n", qPrintable(sourceDir));
664 return false;
665 }
666
667 QDir destDirectory(destDir);
668 if (!destDirectory.exists()) {
669 if (!destDirectory.mkpath("."_L1)) {
670 fprintf(stderr, "Failed to create destination directory: %s\n", qPrintable(destDir));
671 return false;
672 }
673 }
674
675 // Fixed top-level destination so the check below matches the output dir at any depth.
676 const QFileInfo cleanDestInfo{ topDest.isEmpty()
677 ? QDir::cleanPath(destDirectory.absolutePath())
678 : topDest };
679
680 const QFileInfoList entries = srcDir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden);
681 for (const QFileInfo &entry : entries) {
682 QString destPath = destDir + "/"_L1 + entry.fileName();
683
684 if (entry.isDir()) {
685 // Skip the destination itself; otherwise the copy descends into its own output.
686 const QFileInfo cleanSrcInfo{ QDir::cleanPath(entry.absoluteFilePath()) };
687 if (cleanSrcInfo == cleanDestInfo) {
688 if (verbose)
689 fprintf(stdout, " Skipping %s (is the destination directory)\n",
690 qPrintable(cleanSrcInfo.filePath()));
691 continue;
692 }
693 if (!copyRecursively(entry.filePath(), destPath, verbose, cleanDestInfo.filePath()))
694 return false;
695 } else {
696 if (!copyFileIfNewer(entry.filePath(), destPath, verbose))
697 return false;
698 }
699 }
700 return true;
701}
702
703// Returns the array value of key in the JSON5 text content, brackets included,
704// or an empty string if there is none.
705static QString json5ArrayValue(const QString &content, QLatin1StringView key)
706{
707 const QRegularExpression keyRe("[\"']"_L1 + QRegularExpression::escape(QString(key))
708 + "[\"']\\s*:\\s*\\‍["_L1);
709 const QRegularExpressionMatch match = keyRe.match(content);
710 if (!match.hasMatch())
711 return {};
712 const qsizetype start = match.capturedEnd() - 1;
713 int depth = 0;
714 QChar quote;
715 for (qsizetype i = start; i < content.size(); ++i) {
716 const QChar c = content.at(i);
717 if (!quote.isNull()) {
718 if (c == u'\\')
719 ++i;
720 else if (c == quote)
721 quote = QChar();
722 } else if (c == u'"' || c == u'\'') {
723 quote = c;
724 } else if (c == u'[') {
725 ++depth;
726 } else if (c == u']' && --depth == 0) {
727 return content.sliced(start, i - start + 1);
728 }
729 }
730 return {};
731}
732
733static bool copyTemplate(const Options &options, bool keepSigningConfigs)
734{
735 if (options.verbose) {
736 fprintf(stdout, "Copying template from %s to %s\n",
737 qPrintable(options.harmonyOsPackageSourceDirectory),
738 qPrintable(options.outputDirectory));
739 }
740
741 // Check if template exists
742 QDir templateDir(options.harmonyOsPackageSourceDirectory);
743 if (!templateDir.exists()) {
744 fprintf(stderr, "Template directory does not exist: %s\n",
745 qPrintable(options.harmonyOsPackageSourceDirectory));
746 return false;
747 }
748
749 // The module manifest is mandatory; without it hvigor cannot build the HAP and
750 // customizeTemplate() would silently skip every substitution, producing a broken
751 // package. Fail early with a targeted message instead.
752 const QString moduleManifest =
753 options.harmonyOsPackageSourceDirectory + "/entry/src/main/module.json5"_L1;
754 if (!QFile::exists(moduleManifest)) {
755 fprintf(stderr,
756 "'%s' is not a valid HarmonyOS package template: missing "
757 "entry/src/main/module.json5\n",
758 qPrintable(options.harmonyOsPackageSourceDirectory));
759 return false;
760 }
761
762 // Create output directory
763 QDir outputDir(options.outputDirectory);
764 if (outputDir.exists()) {
765 if (options.verbose)
766 fprintf(stdout, "Output directory already exists, will overwrite files\n");
767 }
768
769 // DevEco Studio stores its signing configuration in build-profile.json5. Carry it
770 // over the overwrite below, so that it does not have to be set up after every build.
771 // Signing input passed to harmonydeployqt replaces it.
772 const QString buildProfilePath = options.outputDirectory + "/build-profile.json5"_L1;
773 QString signingConfigs;
774 if (keepSigningConfigs) {
775 QFile buildProfile(buildProfilePath);
776 if (buildProfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
777 signingConfigs =
778 json5ArrayValue(QString::fromUtf8(buildProfile.readAll()), "signingConfigs"_L1);
779 }
780 }
781
782 // Copy entire template
783 if (!copyRecursively(options.harmonyOsPackageSourceDirectory, options.outputDirectory, options.verbose))
784 return false;
785
786 // Force-overwrite the manifest files. customizeTemplate() does one-shot
787 // sentinel/regex substitutions on these; if the destination is left over
788 // from a previous deploy the sentinels are already gone and any change to
789 // the CMake-supplied metadata would be silently ignored. The same applies
790 // to build-profile.json5: injectSigningConfig() looks for the empty
791 // template array and refuses to touch anything else.
792 for (const char *relPath : { "AppScope/app.json5", "entry/src/main/module.json5",
793 "build-profile.json5" }) {
794 const QString src = options.harmonyOsPackageSourceDirectory
795 + QLatin1Char('/') + QLatin1String(relPath);
796 const QString dst = options.outputDirectory + QLatin1Char('/') + QLatin1String(relPath);
797 if (QFile::exists(src) && !copyFileIfNewer(src, dst, options.verbose, true))
798 return false;
799 }
800
801 if (!signingConfigs.isEmpty() && signingConfigs != "[]"_L1) {
802 QFile buildProfile(buildProfilePath);
803 if (!buildProfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
804 fprintf(stderr, "Failed to open %s for reading\n", qPrintable(buildProfilePath));
805 return false;
806 }
807 QString content = QString::fromUtf8(buildProfile.readAll());
808 buildProfile.close();
809 const auto emptySigningConfigs = "\"signingConfigs\": []"_L1;
810 if (!content.contains(emptySigningConfigs)) {
811 fprintf(stderr,
812 "Warning: the template's build-profile.json5 does not contain %s, so the"
813 " existing signingConfigs are not kept\n",
814 emptySigningConfigs.data());
815 } else {
816 content.replace(emptySigningConfigs, "\"signingConfigs\": "_L1 + signingConfigs);
817 if (!buildProfile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
818 fprintf(stderr, "Failed to open %s for writing\n", qPrintable(buildProfilePath));
819 return false;
820 }
821 const QByteArray data = content.toUtf8();
822 if (buildProfile.write(data) != data.size()) {
823 fprintf(stderr, "Failed to write %s\n", qPrintable(buildProfilePath));
824 return false;
825 }
826 if (options.verbose)
827 fprintf(stdout, " Kept signingConfigs of the existing build-profile.json5\n");
828 }
829 }
830
831 if (options.verbose)
832 fprintf(stdout, "Template copied successfully\n");
833
834 return true;
835}
836
837// Hvigor's module.json5 schema rejects free-form reason strings: it requires
838// either a "$string:<id>" resource reference or a parameterised token (one
839// containing both '{' and '}'). Plain English literals supplied via
840// qt_add_harmonyos_permission(... REASON "...") therefore have to be
841// auto-promoted to a synthesized resource entry before substitution.
842static bool reasonNeedsPromotion(const QString &reason)
843{
844 if (reason.startsWith("$string:"_L1))
845 return false;
846 if (reason.contains(QLatin1Char('{')) && reason.contains(QLatin1Char('}')))
847 return false;
848 return true;
849}
850
851// Synthesize a stable resource id from a permission name. The trailing
852// dot-separated component is unique among ohos.permission.* permissions, so
853// "ohos.permission.CAMERA" -> "qt_permission_reason_camera".
854static QString synthesizePermissionReasonId(const QString &permissionName)
855{
856 const QString suffix = permissionName.section(QLatin1Char('.'), -1).toLower();
857 return "qt_permission_reason_"_L1 + suffix;
858}
859
860// scalar. User-supplied metadata (vendor, label, etc.) is substituted into
861// the OHOS manifest files verbatim, so embedded '"' or '\' would otherwise
862// produce invalid JSON that hvigor rejects. Re-uses Qt's own JSON writer
863// for the canonical escape: wrap in a single-element array, serialize, strip
864// the surrounding `["` and `"]`.
865static QString jsonStringEscape(const QString &s)
866{
867 QByteArray ba = QJsonDocument(QJsonArray{s}).toJson(QJsonDocument::Compact);
868 return QString::fromUtf8(ba.sliced(2, ba.size() - 4));
869}
870
871// Returns true when value is one of the orientation strings the HarmonyOS
872// module.json5 schema accepts. Anything else gets rejected with a warning and
873// dropped, so a typo never reaches hvigor (which would fail with a less
874// targeted schema error).
875static bool isValidHarmonyOsAbilityOrientation(const QString &value)
876{
877 static const QStringList allowed = {
878 "unspecified"_L1,
879 "landscape"_L1,
880 "portrait"_L1,
881 "follow_recent"_L1,
882 "landscape_inverted"_L1,
883 "portrait_inverted"_L1,
884 "auto_rotation"_L1,
885 "auto_rotation_landscape"_L1,
886 "auto_rotation_portrait"_L1,
887 "auto_rotation_restricted"_L1,
888 "auto_rotation_landscape_restricted"_L1,
889 "auto_rotation_portrait_restricted"_L1,
890 "locked"_L1,
891 "follow_desktop"_L1,
892 };
893 return allowed.contains(value);
894}
895
901
902static bool customizeTemplate(const Options &options)
903{
904 if (options.verbose)
905 fprintf(stdout, "Customizing template files\n");
906
907 // Customize QtAppConstants.ets
908 QString qtAppConstantsPath = options.outputDirectory + "/entry/src/main/ets/common/QtAppConstants.ets"_L1;
909 QFile qtAppConstantsFile(qtAppConstantsPath);
910
911 if (qtAppConstantsFile.exists()) {
912 if (!qtAppConstantsFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
913 fprintf(stderr, "Failed to open QtAppConstants.ets for reading\n");
914 return false;
915 }
916
917 QString content = QString::fromUtf8(qtAppConstantsFile.readAll());
918 qtAppConstantsFile.close();
919
920 // Replace APP_LIBRARY_NAME
921 // In test bundle mode, use a placeholder — runtime override selects the actual test
922 QString appLibName;
923 if (options.testBundleMode) {
924 appLibName = "libtst_placeholder.so"_L1;
925 } else {
926 QFileInfo appInfo(options.applicationBinary);
927 appLibName = appInfo.fileName(); // Keep the full filename with lib prefix and .so extension
928 }
929
930 content.replace(QRegularExpression("APP_LIBRARY_NAME = '[^']*'"_L1),
931 "APP_LIBRARY_NAME = '"_L1 + appLibName + "'"_L1);
932
933 if (!qtAppConstantsFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
934 fprintf(stderr, "Failed to open QtAppConstants.ets for writing\n");
935 return false;
936 }
937
938 qtAppConstantsFile.write(content.toUtf8());
939 qtAppConstantsFile.close();
940
941 if (options.verbose)
942 fprintf(stdout, " Updated QtAppConstants.ets with app name: %s\n", qPrintable(appLibName));
943 }
944
945 // Resolve the icon value once -- it is consumed by both the app.json5
946 // (app-level icon) and module.json5 (ability/launcher icon) customizations
947 // below. $media: references pass through; literal filesystem paths get
948 // copied into the AppScope *and* entry resource dirs and rewritten to a
949 // $media:<basename> reference. OHOS restool restricts resource names to
950 // [a-zA-Z0-9_]; sanitize the basename so files like "qt-logo.png" are
951 // accepted (becomes "qt_logo.png" / $media:qt_logo).
952 QString iconValue = options.harmonyOsAppIcon;
953 if (!iconValue.isEmpty() && !iconValue.startsWith("$media:"_L1)) {
954 QFileInfo iconInfo(iconValue);
955 if (!iconInfo.exists() || !iconInfo.isFile()) {
956 fprintf(stderr, "App icon does not exist: %s\n", qPrintable(iconValue));
957 return false;
958 }
959 QString safeStem = iconInfo.completeBaseName();
960 for (QChar &c : safeStem) {
961 if (!c.isLetterOrNumber() && c != QLatin1Char('_'))
962 c = QLatin1Char('_');
963 }
964 const QString destFileName = iconInfo.suffix().isEmpty()
965 ? safeStem
966 : safeStem + "."_L1 + iconInfo.suffix();
967 const QStringList destDirs = {
968 options.outputDirectory + "/AppScope/resources/base/media"_L1,
969 options.outputDirectory + "/entry/src/main/resources/base/media"_L1,
970 };
971 for (const QString &destDir : destDirs) {
972 QDir().mkpath(destDir);
973 const QString destPath = destDir + "/"_L1 + destFileName;
974 if (!copyFileIfNewer(iconValue, destPath, options.verbose)) {
975 fprintf(stderr, "Failed to copy app icon to: %s\n", qPrintable(destPath));
976 return false;
977 }
978 }
979 iconValue = "$media:"_L1 + safeStem;
980 }
981
982 // Customize AppScope/app.json5. Use targeted text substitution rather
983 // than parse-and-rewrite so JSON5 features in the template (comments,
984 // trailing commas, single-quoted strings) survive the round trip --
985 // QJsonDocument is a strict JSON parser and would reject those.
986 QString appJsonPath = options.outputDirectory + "/AppScope/app.json5"_L1;
987 QFile appJsonFile(appJsonPath);
988
989 if (appJsonFile.exists()) {
990 if (!appJsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
991 fprintf(stderr, "Failed to open app.json5 for reading\n");
992 return false;
993 }
994 QString content = QString::fromUtf8(appJsonFile.readAll());
995 appJsonFile.close();
996
997 auto replaceStringField =
998 [&content](QLatin1StringView key, const QString &value) {
999 if (value.isEmpty())
1000 return;
1001 content.replace(
1002 QRegularExpression("\""_L1 + key + "\":\\s*\"[^\"]*\""_L1),
1003 "\""_L1 + key + "\": \""_L1 + jsonStringEscape(value) + "\""_L1);
1004 };
1005
1006 replaceStringField("bundleName"_L1, options.harmonyOsAppBundleName);
1007 replaceStringField("vendor"_L1, options.harmonyOsAppVendor);
1008 replaceStringField("versionName"_L1, options.harmonyOsAppVersionName);
1009 // The OHOS schema for app.label requires either "$string:<id>" or a
1010 // brace-substituted value -- a plain literal is rejected. So only
1011 // substitute the label field directly when the user supplied a
1012 // $string: reference. Literal labels are routed below to the
1013 // app_name/QAbility_label string resources, which app.json5 and
1014 // module.json5 already reference via $string:.
1015 if (options.harmonyOsAppLabel.startsWith("$string:"_L1))
1016 replaceStringField("label"_L1, options.harmonyOsAppLabel);
1017 replaceStringField("icon"_L1, iconValue);
1018
1019 if (options.harmonyOsAppVersionCode > 0) {
1020 content.replace(
1021 QRegularExpression("\"versionCode\":\\s*\\d+"_L1),
1022 "\"versionCode\": "_L1 + QString::number(options.harmonyOsAppVersionCode));
1023 }
1024
1025 if (!appJsonFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
1026 fprintf(stderr, "Failed to open app.json5 for writing\n");
1027 return false;
1028 }
1029 appJsonFile.write(content.toUtf8());
1030 appJsonFile.close();
1031
1032 if (options.verbose) {
1033 fprintf(stdout, " Updated app.json5 (bundle: %s)\n",
1034 qPrintable(options.harmonyOsAppBundleName));
1035 }
1036 }
1037
1038 // Display label that lands in the app_name and QAbility_label string
1039 // resources. A literal LABEL wins; a "$string:..." LABEL was substituted
1040 // into app.json5 above and is therefore the user's own resource id, so we
1041 // fall back to the target name here.
1042 const QString displayLabel =
1043 (!options.harmonyOsAppLabel.isEmpty()
1044 && !options.harmonyOsAppLabel.startsWith("$string:"_L1))
1045 ? options.harmonyOsAppLabel
1046 : options.harmonyOsAppName;
1047
1048 // Auto-promote plain-literal permission reasons to $string: references.
1049 // The literal values are appended to the entry/.../string.json files below
1050 // so the synthesized resource ids resolve correctly at HAP build time.
1051 QJsonArray transformedPermissions;
1052 QList<PromotedReason> promotedReasons;
1053 QSet<QString> seenPromotedIds;
1054 for (const QJsonValue &value : std::as_const(options.permissions)) {
1055 if (!value.isObject()) {
1056 transformedPermissions.append(value);
1057 continue;
1058 }
1059 QJsonObject entry = value.toObject();
1060 if (entry.contains("reason"_L1)) {
1061 const QString reason = entry["reason"_L1].toString();
1062 if (reasonNeedsPromotion(reason)) {
1063 const QString permName = entry["name"_L1].toString();
1064 const QString stringId = synthesizePermissionReasonId(permName);
1065 entry["reason"_L1] = QString("$string:"_L1 + stringId);
1066 if (!seenPromotedIds.contains(stringId)) {
1067 promotedReasons.append({stringId, reason});
1068 seenPromotedIds.insert(stringId);
1069 }
1070 }
1071 }
1072 transformedPermissions.append(entry);
1073 }
1074
1075 // Customize entry module string resources: replace QAbility_label with the
1076 // app name, and append any synthesized permission-reason strings.
1077 // Update all locale variants: base, en_US, zh_CN
1078 QStringList locales = QStringList() << "base"_L1 << "en_US"_L1 << "zh_CN"_L1;
1079
1080 for (const QString &locale : locales) {
1081 QString stringJsonPath = options.outputDirectory + "/entry/src/main/resources/"_L1 +
1082 locale + "/element/string.json"_L1;
1083 QFile stringJsonFile(stringJsonPath);
1084
1085 if (!stringJsonFile.exists())
1086 continue;
1087
1088 if (!stringJsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
1089 fprintf(stderr, "Failed to open %s string.json for reading\n", qPrintable(locale));
1090 continue;
1091 }
1092
1093 const QByteArray bytes = stringJsonFile.readAll();
1094 stringJsonFile.close();
1095
1096 QJsonParseError parseErr;
1097 QJsonDocument doc = QJsonDocument::fromJson(bytes, &parseErr);
1098 if (parseErr.error != QJsonParseError::NoError || !doc.isObject()) {
1099 fprintf(stderr, "Failed to parse %s string.json: %s\n",
1100 qPrintable(locale), qPrintable(parseErr.errorString()));
1101 continue;
1102 }
1103 QJsonObject root = doc.object();
1104 QJsonArray strings = root["string"_L1].toArray();
1105
1106 // Replace QAbility_label value with app name and collect existing names
1107 QSet<QString> existingNames;
1108 for (qsizetype i = 0; i < strings.size(); ++i) {
1109 QJsonObject e = strings[i].toObject();
1110 const QString name = e["name"_L1].toString();
1111 existingNames.insert(name);
1112 if (name == "QAbility_label"_L1) {
1113 e["value"_L1] = displayLabel;
1114 strings[i] = e;
1115 }
1116 }
1117
1118 // Append synthesized permission-reason strings (skip ids already present)
1119 for (const PromotedReason &p : std::as_const(promotedReasons)) {
1120 if (existingNames.contains(p.id))
1121 continue;
1122 QJsonObject e;
1123 e["name"_L1] = p.id;
1124 e["value"_L1] = p.value;
1125 strings.append(e);
1126 existingNames.insert(p.id);
1127 }
1128 root["string"_L1] = strings;
1129 doc.setObject(root);
1130
1131 if (!stringJsonFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
1132 fprintf(stderr, "Failed to open %s string.json for writing\n", qPrintable(locale));
1133 continue;
1134 }
1135
1136 stringJsonFile.write(doc.toJson(QJsonDocument::Indented));
1137 stringJsonFile.close();
1138
1139 if (options.verbose) {
1140 fprintf(stdout,
1141 " Updated %s string.json (label: %s, +%lld promoted permission reasons)\n",
1142 qPrintable(locale), qPrintable(displayLabel),
1143 static_cast<long long>(promotedReasons.size()));
1144 }
1145 }
1146
1147 // Also update AppScope app_name for consistency
1148 QString appScopeStringPath = options.outputDirectory + "/AppScope/resources/base/element/string.json"_L1;
1149 QFile appScopeStringFile(appScopeStringPath);
1150
1151 if (appScopeStringFile.exists()) {
1152 if (!appScopeStringFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
1153 fprintf(stderr, "Failed to open AppScope string.json for reading\n");
1154 return false;
1155 }
1156
1157 QString content = QString::fromUtf8(appScopeStringFile.readAll());
1158 appScopeStringFile.close();
1159
1160 // Replace app_name value
1161 QRegularExpression appNameRegex("(\"name\":\\s*\"app_name\"[^}]*\"value\":\\s*)\"[^\"]*\""_L1);
1162 content.replace(appNameRegex, "\\1\""_L1 + jsonStringEscape(displayLabel) + "\""_L1);
1163
1164 if (!appScopeStringFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
1165 fprintf(stderr, "Failed to open AppScope string.json for writing\n");
1166 return false;
1167 }
1168
1169 appScopeStringFile.write(content.toUtf8());
1170 appScopeStringFile.close();
1171
1172 if (options.verbose)
1173 fprintf(stdout, " Updated AppScope string.json with app name: %s\n",
1174 qPrintable(displayLabel));
1175 }
1176
1177 // Customize module.json5
1178 // Note: We only update the description, not the module name which must remain "entry"
1179 QString moduleJsonPath = options.outputDirectory + "/entry/src/main/module.json5"_L1;
1180 QFile moduleJsonFile(moduleJsonPath);
1181
1182 if (moduleJsonFile.exists()) {
1183 if (!moduleJsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
1184 fprintf(stderr, "Failed to open module.json5 for reading\n");
1185 return false;
1186 }
1187
1188 QString content = QString::fromUtf8(moduleJsonFile.readAll());
1189 moduleJsonFile.close();
1190
1191 // Substitute the module description sentinel. The user's value (if set
1192 // via QT_HARMONYOS_MODULE_DESCRIPTION) takes precedence;
1193 // otherwise fall back to the template's $string:module_desc reference,
1194 // which resolves via the entry/.../resources/.../string.json file.
1195 const QString descriptionSentinel = "%%INSERT_MODULE_DESCRIPTION%%"_L1;
1196 const QString descriptionValue = options.harmonyOsModuleDescription.isEmpty()
1197 ? "$string:module_desc"_L1
1198 : jsonStringEscape(options.harmonyOsModuleDescription);
1199 content.replace(descriptionSentinel, descriptionValue);
1200
1201 // Substitute the deviceTypes sentinel.
1202 const QString deviceTypesSentinel = "/* %%INSERT_DEVICE_TYPES%% */"_L1;
1203 QStringList deviceTypes = options.harmonyOsModuleDeviceTypes;
1204 if (deviceTypes.isEmpty())
1205 deviceTypes = QStringList{ "phone"_L1, "tablet"_L1, "2in1"_L1 };
1206 QStringList quotedDeviceTypes;
1207 quotedDeviceTypes.reserve(deviceTypes.size());
1208 for (const QString &dt : std::as_const(deviceTypes))
1209 quotedDeviceTypes.append("\""_L1 + dt + "\""_L1);
1210 content.replace(deviceTypesSentinel, quotedDeviceTypes.join(", "_L1));
1211
1212 // Substitute the ability-orientation sentinel. The template ships the
1213 // sentinel as a block comment so module.json5 stays valid JSON5 when
1214 // the user has not set an orientation; in that case the sentinel line
1215 // is dropped entirely. When set, replace it with the orientation field
1216 // (matching the surrounding 8-space indentation already in the
1217 // template). Unknown values are rejected with a warning rather than
1218 // forwarded to hvigor, which would fail with a less targeted error.
1219 const QString orientationSentinelLine =
1220 " /* %%INSERT_ABILITY_ORIENTATION%% */\n"_L1;
1221 QString orientationReplacement;
1222 if (!options.harmonyOsAbilityOrientation.isEmpty()) {
1223 if (isValidHarmonyOsAbilityOrientation(options.harmonyOsAbilityOrientation)) {
1224 orientationReplacement = " \"orientation\": \""_L1
1225 + options.harmonyOsAbilityOrientation
1226 + "\",\n"_L1;
1227 } else {
1228 fprintf(stderr,
1229 "Warning: Ignoring unknown harmonyos-ability-orientation value '%s'\n",
1230 qPrintable(options.harmonyOsAbilityOrientation));
1231 }
1232 }
1233 content.replace(orientationSentinelLine, orientationReplacement);
1234
1235 // Override the ability/launcher icon so QT_HARMONYOS_APP_ICON
1236 // is reflected on the device home screen, not just in Settings. The
1237 // template ships "$media:layered_image" -- only replace that specific
1238 // value so user-customized icons in subsequent runs aren't clobbered.
1239 if (!iconValue.isEmpty()) {
1240 content.replace(
1241 QRegularExpression("\"icon\":\\s*\"\\$media:layered_image\""_L1),
1242 "\"icon\": \""_L1 + iconValue + "\""_L1);
1243 }
1244
1245 // Build the requestPermissions array fragment from the (possibly
1246 // promoted) transformedPermissions computed above. The sentinel
1247 // "/* %%INSERT_PERMISSIONS%% */" sits inside an empty [] so the
1248 // template stays valid JSON5 even without substitution.
1249 const QString sentinel = "/* %%INSERT_PERMISSIONS%% */"_L1;
1250 QString permissionsFragment;
1251 if (!transformedPermissions.isEmpty()) {
1252 QStringList entryStrings;
1253 entryStrings.reserve(transformedPermissions.size());
1254 for (const QJsonValue &value : std::as_const(transformedPermissions)) {
1255 if (!value.isObject())
1256 continue;
1257 const QJsonObject entry = value.toObject();
1258
1259 // Pretty-print the entry, then re-indent so it lines up with the
1260 // surrounding "requestPermissions" array (8-space base indent).
1261 const QByteArray pretty =
1262 QJsonDocument(entry).toJson(QJsonDocument::Indented).trimmed();
1263 const QStringList lines = QString::fromUtf8(pretty).split(QLatin1Char('\n'));
1264 QStringList indented;
1265 indented.reserve(lines.size());
1266 for (const QString &line : lines)
1267 indented.append(" "_L1 + line);
1268 entryStrings.append(indented.join(QLatin1Char('\n')));
1269 }
1270 if (!entryStrings.isEmpty()) {
1271 permissionsFragment = "\n"_L1 + entryStrings.join(",\n"_L1) + "\n "_L1;
1272 }
1273 }
1274 content.replace(sentinel, permissionsFragment);
1275
1276 if (!moduleJsonFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
1277 fprintf(stderr, "Failed to open module.json5 for writing\n");
1278 return false;
1279 }
1280
1281 moduleJsonFile.write(content.toUtf8());
1282 moduleJsonFile.close();
1283
1284 if (options.verbose) {
1285 fprintf(stdout, " Updated module.json5 description\n");
1286 fprintf(stdout, " Injected %lld permissions into module.json5\n",
1287 static_cast<long long>(transformedPermissions.size()));
1288 }
1289 }
1290
1291 // Customize build-profile.json5 with the SDK version metadata. Only fields
1292 // that are set are substituted; others keep the template default.
1293 //
1294 // * compatibleSdkVersion is an existing key with a default value -- we
1295 // replace its value via the same regex pattern used in app.json5.
1296 // * targetSdkVersion / compileSdkVersion don't appear in the template by
1297 // default. They are added via comment-style sentinels that the JSON5
1298 // parser ignores when not substituted.
1299 {
1300 const bool anySdkVersionSet =
1301 !options.harmonyOsCompatibleSdkVersion.isEmpty()
1302 || !options.harmonyOsTargetSdkVersion.isEmpty()
1303 || !options.harmonyOsCompileSdkVersion.isEmpty();
1304
1305 const QString buildProfilePath =
1306 options.outputDirectory + "/build-profile.json5"_L1;
1307 QFile buildProfileFile(buildProfilePath);
1308 if (anySdkVersionSet && buildProfileFile.exists()) {
1309 if (!buildProfileFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
1310 fprintf(stderr, "Failed to open build-profile.json5 for reading\n");
1311 return false;
1312 }
1313 QString content = QString::fromUtf8(buildProfileFile.readAll());
1314 buildProfileFile.close();
1315
1316 if (!options.harmonyOsCompatibleSdkVersion.isEmpty()) {
1317 content.replace(
1318 QRegularExpression(
1319 "\"compatibleSdkVersion\":\\s*\"[^\"]*\""_L1),
1320 "\"compatibleSdkVersion\": \""_L1
1321 + jsonStringEscape(options.harmonyOsCompatibleSdkVersion)
1322 + "\""_L1);
1323 }
1324
1325 const QString targetSentinel = "/* %%INSERT_TARGET_SDK_VERSION%% */"_L1;
1326 const QString targetReplacement =
1327 options.harmonyOsTargetSdkVersion.isEmpty()
1328 ? QString()
1329 : "\"targetSdkVersion\": \""_L1
1330 + jsonStringEscape(options.harmonyOsTargetSdkVersion)
1331 + "\","_L1;
1332 content.replace(targetSentinel, targetReplacement);
1333
1334 const QString compileSentinel = "/* %%INSERT_COMPILE_SDK_VERSION%% */"_L1;
1335 const QString compileReplacement =
1336 options.harmonyOsCompileSdkVersion.isEmpty()
1337 ? QString()
1338 : "\"compileSdkVersion\": \""_L1
1339 + jsonStringEscape(options.harmonyOsCompileSdkVersion)
1340 + "\","_L1;
1341 content.replace(compileSentinel, compileReplacement);
1342
1343 if (!buildProfileFile.open(
1344 QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
1345 fprintf(stderr, "Failed to open build-profile.json5 for writing\n");
1346 return false;
1347 }
1348 buildProfileFile.write(content.toUtf8());
1349 buildProfileFile.close();
1350
1351 if (options.verbose) {
1352 fprintf(stdout,
1353 " Updated build-profile.json5 SDK versions"
1354 " (compatible=%s, target=%s, compile=%s)\n",
1355 qPrintable(options.harmonyOsCompatibleSdkVersion),
1356 qPrintable(options.harmonyOsTargetSdkVersion),
1357 qPrintable(options.harmonyOsCompileSdkVersion));
1358 }
1359 }
1360 }
1361
1362 if (options.verbose)
1363 fprintf(stdout, "Template customization completed\n");
1364
1365 return true;
1366}
1367
1368static bool copyApplicationBinary(const Options &options)
1369{
1370 if (options.verbose)
1371 fprintf(stdout, "Copying application binary and dependencies\n");
1372
1373 // For each target architecture, copy the application binary
1374 for (const QString &arch : options.targetArchs) {
1375 QString archLibPath = options.outputDirectory + "/entry/libs/"_L1 + arch;
1376 QDir archDir(archLibPath);
1377 if (!archDir.exists()) {
1378 if (!archDir.mkpath("."_L1)) {
1379 fprintf(stderr, "Failed to create architecture directory: %s\n", qPrintable(archLibPath));
1380 return false;
1381 }
1382 }
1383
1384 // Copy application binary
1385 QFileInfo appInfo(options.applicationBinary);
1386 QString destPath = archLibPath + "/"_L1 + appInfo.fileName();
1387
1388 if (!appInfo.fileName().startsWith("lib"_L1)) {
1389 // Ensure it has lib prefix
1390 destPath = archLibPath + "/lib"_L1 + appInfo.fileName();
1391 }
1392
1393 if (!destPath.endsWith(".so"_L1)) {
1394 // Ensure it has .so extension
1395 destPath += ".so"_L1;
1396 }
1397
1398 if (options.verbose) {
1399 fprintf(stdout, " Copying application binary for %s: %s -> %s\n",
1400 qPrintable(arch), qPrintable(options.applicationBinary), qPrintable(destPath));
1401 }
1402
1403 if (!copyFileIfNewer(options.applicationBinary, destPath, options.verbose)) {
1404 fprintf(stderr, "Failed to copy application binary to: %s\n",
1405 qPrintable(destPath));
1406 return false;
1407 }
1408
1409 // Track as dependency for depfile
1410 if (!options.depFilePath.isEmpty())
1411 dependenciesForDepfile << options.applicationBinary;
1412 }
1413
1414 if (options.verbose)
1415 fprintf(stdout, "Application binary copied successfully\n");
1416
1417 return true;
1418}
1419
1420static bool copyFileToArchitectures(const Options &options,
1421 const QString &sourcePath,
1422 const QString &relativeDestPath,
1423 bool trackInDepfile = true)
1424{
1425 for (const QString &arch : options.targetArchs) {
1426 QString destPath = "%1/entry/libs/%2/%3"_L1
1427 .arg(options.outputDirectory, arch, relativeDestPath);
1428
1429 QDir().mkpath(QFileInfo(destPath).absolutePath());
1430
1431 if (options.verbose)
1432 fprintf(stdout, " Copying for %s: %s\n",
1433 qPrintable(arch), qPrintable(QFileInfo(sourcePath).fileName()));
1434
1435 if (!copyFileIfNewer(sourcePath, destPath, options.verbose)) {
1436 fprintf(stderr, "Failed to copy file: %s to %s\n",
1437 qPrintable(sourcePath), qPrintable(destPath));
1438 return false;
1439 }
1440
1441 // Track as dependency for depfile (only once, not per-arch)
1442 if (trackInDepfile && !options.depFilePath.isEmpty() && arch == options.targetArchs.first())
1443 dependenciesForDepfile << sourcePath;
1444 }
1445 return true;
1446}
1447
1448static QString findStdCppLibrary(const Options &options, const QString &arch)
1449{
1450 // Map architecture to NDK triple
1451 QString ndkArch;
1452 if (arch == "arm64-v8a"_L1) {
1453 ndkArch = "aarch64-linux-ohos"_L1;
1454 } else if (arch == "armeabi-v7a"_L1) {
1455 ndkArch = "arm-linux-ohos"_L1;
1456 } else if (arch == "x86_64"_L1) {
1457 ndkArch = "x86_64-linux-ohos"_L1;
1458 } else if (arch == "x86"_L1) {
1459 ndkArch = "i686-linux-ohos"_L1;
1460 } else {
1461 return QString();
1462 }
1463
1464 QString stdCppPath = options.ndkRoot + "/llvm/lib/"_L1 + ndkArch + "/c++/libc++_shared.so"_L1;
1465 if (QFile::exists(stdCppPath))
1466 return stdCppPath;
1467
1468 stdCppPath = options.ndkRoot + "/llvm/lib/"_L1 + ndkArch + "/libc++_shared.so"_L1;
1469 if (QFile::exists(stdCppPath))
1470 return stdCppPath;
1471
1472 return QString();
1473}
1474
1475// Copy project-specific shared libraries (test helper libs, etc.) flat into
1476// entry/libs/<arch>/. These are non-Qt libs listed in "project-libraries" in
1477// the deployment settings JSON, collected from the target's LINK_LIBRARIES by
1478// Qt6HarmonyOSMacros.cmake.
1479static bool copyProjectLibraries(const Options &options)
1480{
1481 if (options.projectLibraries.isEmpty())
1482 return true;
1483
1484 if (options.verbose)
1485 fprintf(stdout, "Copying project libraries\n");
1486
1487 for (const QString &projectLib : options.projectLibraries) {
1488 QFileInfo libInfo(projectLib);
1489 if (!libInfo.exists()) {
1490 if (options.verbose)
1491 fprintf(stdout, " Project library not found, skipping: %s\n",
1492 qPrintable(projectLib));
1493 continue;
1494 }
1495
1496 for (const QString &arch : options.targetArchs) {
1497 QString archLibPath = options.outputDirectory + "/entry/libs/"_L1 + arch;
1498 QString destPath = archLibPath + "/"_L1 + libInfo.fileName();
1499
1500 if (options.verbose) {
1501 fprintf(stdout, " Copying project library for %s: %s\n",
1502 qPrintable(arch), qPrintable(libInfo.fileName()));
1503 }
1504
1505 if (!copyFileIfNewer(projectLib, destPath, options.verbose)) {
1506 fprintf(stderr, "Failed to copy project library to: %s\n",
1507 qPrintable(destPath));
1508 return false;
1509 }
1510
1511 if (!options.depFilePath.isEmpty())
1512 dependenciesForDepfile << projectLib;
1513 }
1514 }
1515
1516 if (options.verbose)
1517 fprintf(stdout, "Project libraries copied successfully\n");
1518
1519 return true;
1520}
1521
1522// Recursively scan dirPath for libtst_*.so test binaries and their co-located helper libs.
1523// Test binaries are appended to found; helper libs (lib*.so* in the same directory as a
1524// test binary) are appended to foundHelpers. helperNames guards against filename collisions
1525// across directories. excludeDirs is a list of absolute paths to skip during recursion.
1526static void scanTestBinariesDir(const QString &dirPath,
1527 const QStringList &excludeList,
1528 const QStringList &excludeDirs,
1529 QStringList &found,
1530 QStringList &foundHelpers,
1531 QSet<QString> &helperNames)
1532{
1533 const QFileInfoList entries =
1534 QDir(dirPath).entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
1535
1536 bool hasTestBinary = false;
1537 for (const QFileInfo &entry : entries) {
1538 if (!entry.isDir()
1539 && entry.fileName().startsWith("libtst_"_L1)
1540 && entry.suffix() == "so"_L1
1541 && !excludeList.contains(entry.fileName())) {
1542 found.append(entry.filePath());
1543 hasTestBinary = true;
1544 }
1545 }
1546
1547 // For each directory that contains a test binary, also collect co-located helper libs
1548 // (e.g. libqmetatype_lib1.so.0) so that $ORIGIN rpath lookups resolve on-device.
1549 if (hasTestBinary) {
1550 for (const QFileInfo &entry : entries) {
1551 if (!entry.isDir()
1552 && entry.fileName().startsWith("lib"_L1)
1553 && !entry.fileName().startsWith("libtst_"_L1)
1554 && entry.fileName().contains(".so"_L1)
1555 && !helperNames.contains(entry.fileName())) {
1556 foundHelpers.append(entry.filePath());
1557 helperNames.insert(entry.fileName());
1558 }
1559 }
1560 }
1561
1562 for (const QFileInfo &entry : entries) {
1563 if (entry.isDir() && !excludeDirs.contains(entry.absoluteFilePath()))
1564 scanTestBinariesDir(entry.filePath(), excludeList, excludeDirs, found, foundHelpers, helperNames);
1565 }
1566}
1567
1568static bool copyTestBinaries(const Options &options, QStringList &bundledBinaries)
1569{
1570 if (options.testBinariesDirectory.isEmpty()) {
1571 fprintf(stderr, "Error: 'test-binaries-directory' not specified for test bundle mode\n");
1572 return false;
1573 }
1574
1575 if (!QDir(options.testBinariesDirectory).exists()) {
1576 fprintf(stderr, "Error: test-binaries-directory does not exist: %s\n",
1577 qPrintable(options.testBinariesDirectory));
1578 return false;
1579 }
1580
1581 if (options.verbose)
1582 fprintf(stdout, "Scanning for test binaries in %s\n", qPrintable(options.testBinariesDirectory));
1583
1584 QStringList found;
1585 QStringList foundHelpers;
1586 QSet<QString> helperNames;
1587 // Exclude the output directory to avoid scanning previously generated HAP bundle contents,
1588 // which would cause libentry.so (built by hvigor/CMake) to be picked up as a helper lib
1589 // and then conflict with the CMake-built version during the hvigor build.
1590 const QStringList excludeDirs = { QFileInfo(options.outputDirectory).absoluteFilePath() };
1591 scanTestBinariesDir(options.testBinariesDirectory, options.testExcludeList, excludeDirs,
1592 found, foundHelpers, helperNames);
1593
1594 if (found.isEmpty()) {
1595 fprintf(stderr, "Warning: No test binaries (libtst_*.so) found in %s\n",
1596 qPrintable(options.testBinariesDirectory));
1597 return true; // Not fatal
1598 }
1599
1600 if (options.verbose) {
1601 fprintf(stdout, "Found %lld test binaries\n", static_cast<long long>(found.size()));
1602 if (!foundHelpers.isEmpty())
1603 fprintf(stdout, "Found %lld test helper libraries\n",
1604 static_cast<long long>(foundHelpers.size()));
1605 }
1606
1607 // Copy all test binaries AND helper libs flat to entry/libs/${arch}/
1608 for (const QString &arch : options.targetArchs) {
1609 QString archLibPath = options.outputDirectory + "/entry/libs/"_L1 + arch;
1610 QDir().mkpath(archLibPath);
1611
1612 for (const QString &testBinary : found) {
1613 QFileInfo testInfo(testBinary);
1614 QString destPath = archLibPath + "/"_L1 + testInfo.fileName();
1615
1616 if (options.verbose)
1617 fprintf(stdout, " Copying test binary: %s\n", qPrintable(testInfo.fileName()));
1618
1619 if (!copyFileIfNewer(testBinary, destPath, options.verbose)) {
1620 fprintf(stderr, "Failed to copy test binary: %s\n", qPrintable(testBinary));
1621 return false;
1622 }
1623 }
1624
1625 for (const QString &helperLib : foundHelpers) {
1626 QFileInfo helperInfo(helperLib);
1627 QString destPath = archLibPath + "/"_L1 + helperInfo.fileName();
1628
1629 if (options.verbose)
1630 fprintf(stdout, " Copying test helper lib: %s\n", qPrintable(helperInfo.fileName()));
1631
1632 if (!copyFileIfNewer(helperLib, destPath, options.verbose)) {
1633 fprintf(stderr, "Failed to copy test helper lib: %s\n", qPrintable(helperLib));
1634 return false;
1635 }
1636 }
1637 }
1638
1639 // Build list of bundled binary filenames (no duplicates)
1640 for (const QString &testBinary : found) {
1641 QString fileName = QFileInfo(testBinary).fileName();
1642 if (!bundledBinaries.contains(fileName))
1643 bundledBinaries.append(fileName);
1644 }
1645
1646 // Track for depfile
1647 if (!options.depFilePath.isEmpty()) {
1648 for (const QString &testBinary : found)
1649 dependenciesForDepfile << testBinary;
1650 for (const QString &helperLib : foundHelpers)
1651 dependenciesForDepfile << helperLib;
1652 }
1653
1654 return true;
1655}
1656
1657static bool writeTestBinariesList(const Options &options, const QStringList &bundledBinaries)
1658{
1659 QString binariesListPath = options.outputDirectory + "/binaries.txt"_L1;
1660
1661 if (options.verbose)
1662 fprintf(stdout, "Writing test binaries list: %s\n", qPrintable(binariesListPath));
1663
1664 QFile file(binariesListPath);
1665 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
1666 fprintf(stderr, "Failed to open binaries.txt for writing: %s\n",
1667 qPrintable(binariesListPath));
1668 return false;
1669 }
1670
1671 for (const QString &binary : bundledBinaries) {
1672 file.write(binary.toUtf8());
1673 file.write("\n");
1674 }
1675 file.close();
1676
1677 if (options.verbose) {
1678 fprintf(stdout, "Wrote %lld test binary names to binaries.txt\n",
1679 static_cast<long long>(bundledBinaries.size()));
1680 }
1681
1682 return true;
1683}
1684
1685static QString readElfSoname(const Options &options, const QString &binaryPath);
1686
1687static bool copyAllQtLibs(const Options &options)
1688{
1689 if (options.qtLibsDirectory.isEmpty())
1690 return true;
1691
1692 if (!QDir(options.qtLibsDirectory).exists()) {
1693 if (options.verbose) {
1694 fprintf(stdout, "Qt libs directory not found, skipping: %s\n",
1695 qPrintable(options.qtLibsDirectory));
1696 }
1697 return true;
1698 }
1699
1700 if (options.verbose)
1701 fprintf(stdout, "Copying all Qt libraries from %s\n", qPrintable(options.qtLibsDirectory));
1702
1703 QDir libsDir(options.qtLibsDirectory);
1704 const QFileInfoList entries = libsDir.entryInfoList({"*.so"_L1, "*.so.*"_L1}, QDir::Files);
1705
1706 for (const QFileInfo &entry : entries) {
1707 for (const QString &arch : options.targetArchs) {
1708 QString destPath = options.outputDirectory + "/entry/libs/"_L1 + arch + "/"_L1 + entry.fileName();
1709 QDir().mkpath(QFileInfo(destPath).absolutePath());
1710 if (!copyFileIfNewer(entry.filePath(), destPath, options.verbose))
1711 return false;
1712 }
1713 if (!options.depFilePath.isEmpty())
1714 dependenciesForDepfile << entry.filePath();
1715 }
1716
1717 // Also copy libc++_shared.so from NDK for each architecture
1718 for (const QString &arch : options.targetArchs) {
1719 QString stdCppPath = findStdCppLibrary(options, arch);
1720 if (!stdCppPath.isEmpty()) {
1721 QString destPath = options.outputDirectory + "/entry/libs/"_L1 + arch + "/libc++_shared.so"_L1;
1722 if (options.verbose)
1723 fprintf(stdout, " Copying C++ standard library for %s\n", qPrintable(arch));
1724 if (!copyFileIfNewer(stdCppPath, destPath, options.verbose))
1725 return false;
1726 if (!options.depFilePath.isEmpty())
1727 dependenciesForDepfile << stdCppPath;
1728 }
1729 }
1730
1731 // Copy all libraries from extra-libs-dirs (e.g. third-party deps like ICU, fontconfig)
1732 for (const QString &extraDir : options.extraLibsDirs) {
1733 QDir dir(extraDir);
1734 if (!dir.exists()) {
1735 if (options.verbose)
1736 fprintf(stdout, "Extra libs dir not found, skipping: %s\n", qPrintable(extraDir));
1737 continue;
1738 }
1739
1740 if (options.verbose)
1741 fprintf(stdout, "Copying extra libraries from %s\n", qPrintable(extraDir));
1742
1743 const QFileInfoList entries = dir.entryInfoList({"*.so"_L1, "*.so.*"_L1}, QDir::Files);
1744 for (const QFileInfo &entry : entries) {
1745 // Deploy using the library's SONAME if it differs from the on-disk filename,
1746 // so the dynamic linker can find it at runtime (e.g. libicudata.so.78,
1747 // not libicudata.so).
1748 const QString soname = readElfSoname(options, entry.filePath());
1749 const QString deployName = (!soname.isEmpty() && soname != entry.fileName())
1750 ? soname : entry.fileName();
1751 for (const QString &arch : options.targetArchs) {
1752 QString destPath = options.outputDirectory + "/entry/libs/"_L1 + arch + "/"_L1 + deployName;
1753 QDir().mkpath(QFileInfo(destPath).absolutePath());
1754 if (!copyFileIfNewer(entry.filePath(), destPath, options.verbose))
1755 return false;
1756 }
1757 if (!options.depFilePath.isEmpty())
1758 dependenciesForDepfile << entry.filePath();
1759 }
1760 }
1761
1762 return true;
1763}
1764
1765static bool copyAllQtPlugins(const Options &options)
1766{
1767 // Copy all plugins from one plugins root directory.
1768 auto copyPluginsFromDir = [&options](const QString &pluginsRootPath) -> bool {
1769 QDir pluginsDir(pluginsRootPath);
1770 const QStringList categories = pluginsDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
1771
1772 for (const QString &category : categories) {
1773 QDir categoryDir(pluginsDir.filePath(category));
1774 const QFileInfoList plugins = categoryDir.entryInfoList({"*.so"_L1}, QDir::Files);
1775
1776 for (const QFileInfo &pluginInfo : plugins) {
1777 const QString &plugin = pluginInfo.fileName();
1778 const QString &pluginPath = pluginInfo.filePath();
1779
1780 if (category == "platforms"_L1 && plugin == "libqohos.so"_L1) {
1781 // Platform plugin goes flat to root libs directory
1782 for (const QString &arch : options.targetArchs) {
1783 QString destPath = options.outputDirectory + "/entry/libs/"_L1 + arch + "/libqohos.so"_L1;
1784 QDir().mkpath(QFileInfo(destPath).absolutePath());
1785 if (!copyFileIfNewer(pluginPath, destPath, options.verbose))
1786 return false;
1787 }
1788 } else {
1789 // All other plugins go into their category subdirectory
1790 QString relativeDestPath = category + "/"_L1 + plugin;
1791 if (!copyFileToArchitectures(options, pluginPath, relativeDestPath, false))
1792 return false;
1793 }
1794
1795 if (!options.depFilePath.isEmpty())
1796 dependenciesForDepfile << pluginPath;
1797 }
1798 }
1799 return true;
1800 };
1801
1802 // Process plugins-import-paths first (typically CMAKE_BINARY_DIR/plugins,
1803 // i.e. the module's own build-tree plugin output). Files written here
1804 // receive dest mtime = now, so the subsequent qtPluginsDirectory pass
1805 // skips any file that was already copied — this gives build-dir contents
1806 // unconditional priority over the installed Qt prefix without requiring a
1807 // force-overwrite flag.
1808 for (const QString &importPath : options.pluginsImportPaths) {
1809 if (!QDir(importPath).exists()) {
1810 if (options.verbose)
1811 fprintf(stdout, "Plugins import path not found, skipping: %s\n",
1812 qPrintable(importPath));
1813 continue;
1814 }
1815 if (options.verbose)
1816 fprintf(stdout, "Copying Qt plugins from import path: %s\n",
1817 qPrintable(importPath));
1818 if (!copyPluginsFromDir(importPath))
1819 return false;
1820 }
1821
1822 // Process qtPluginsDirectory second (the installed Qt prefix). Files
1823 // already present in dest (copied from plugins-import-paths above) are
1824 // skipped by copyFileIfNewer; plugins that exist only in the installed
1825 // prefix are copied normally.
1826 if (options.qtPluginsDirectory.isEmpty())
1827 return true;
1828
1829 if (!QDir(options.qtPluginsDirectory).exists()) {
1830 if (options.verbose) {
1831 fprintf(stdout, "Qt plugins directory not found, skipping: %s\n",
1832 qPrintable(options.qtPluginsDirectory));
1833 }
1834 return true;
1835 }
1836
1837 if (options.verbose)
1838 fprintf(stdout, "Copying all Qt plugins from %s\n", qPrintable(options.qtPluginsDirectory));
1839
1840 return copyPluginsFromDir(options.qtPluginsDirectory);
1841}
1842
1843// Copy user-supplied extra plugins listed in QT_HARMONYOS_EXTRA_PLUGINS into
1844// entry/libs/<arch>/<category>/. The category is derived from the parent
1845// directory of each plugin source path (e.g. .../imageformats/libfoo.so ->
1846// "imageformats/libfoo.so"); plugins without a usable parent directory name
1847// are deployed flat under entry/libs/<arch>/.
1848static bool copyExtraPlugins(const Options &options)
1849{
1850 if (options.extraPlugins.isEmpty())
1851 return true;
1852
1853 if (options.verbose)
1854 fprintf(stdout, "Copying extra plugins\n");
1855
1856 for (const QString &pluginPath : options.extraPlugins) {
1857 const QFileInfo pluginInfo(pluginPath);
1858 if (!pluginInfo.exists() || !pluginInfo.isFile()) {
1859 fprintf(stderr, "Extra plugin does not exist: %s\n", qPrintable(pluginPath));
1860 return false;
1861 }
1862
1863 const QString category = pluginInfo.absoluteDir().dirName();
1864 QString relativeDestPath;
1865 if (category.isEmpty() || category == "plugins"_L1)
1866 relativeDestPath = pluginInfo.fileName();
1867 else
1868 relativeDestPath = category + "/"_L1 + pluginInfo.fileName();
1869
1870 if (options.verbose) {
1871 fprintf(stdout, " Extra plugin: %s -> entry/libs/<arch>/%s\n",
1872 qPrintable(pluginInfo.fileName()), qPrintable(relativeDestPath));
1873 }
1874
1875 if (!copyFileToArchitectures(options, pluginInfo.filePath(), relativeDestPath))
1876 return false;
1877 }
1878
1879 return true;
1880}
1881
1882// .so files in the QML directory go flat to entry/libs/<arch>/; all other files
1883// preserve directory structure under resfile/qml/.
1884static bool copyQmlDir(const QString &srcDir, const QString &relPath,
1885 const QString &qmlDestBase, const Options &options)
1886{
1887 const QFileInfoList entries =
1888 QDir(srcDir).entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden);
1889
1890 for (const QFileInfo &entry : entries) {
1891 const QString entryRelPath = relPath.isEmpty()
1892 ? entry.fileName()
1893 : relPath + "/"_L1 + entry.fileName();
1894
1895 if (entry.isDir()) {
1896 if (!copyQmlDir(entry.filePath(), entryRelPath, qmlDestBase, options))
1897 return false;
1898 } else if (entry.suffix() == "so"_L1) {
1899 for (const QString &arch : options.targetArchs) {
1900 QString destPath = options.outputDirectory + "/entry/libs/"_L1
1901 + arch + "/"_L1 + entry.fileName();
1902 QDir().mkpath(QFileInfo(destPath).absolutePath());
1903 if (!copyFileIfNewer(entry.filePath(), destPath, options.verbose))
1904 return false;
1905 }
1906 if (!options.depFilePath.isEmpty())
1907 dependenciesForDepfile << entry.filePath();
1908 } else {
1909 QString destPath = qmlDestBase + "/"_L1 + entryRelPath;
1910 QDir().mkpath(QFileInfo(destPath).absolutePath());
1911 if (!copyFileIfNewer(entry.filePath(), destPath, options.verbose))
1912 return false;
1913 if (!options.depFilePath.isEmpty())
1914 dependenciesForDepfile << entry.filePath();
1915 }
1916 }
1917 return true;
1918}
1919
1920static QString hapQmlDir(const Options &options)
1921{
1922 return options.outputDirectory + "/entry/src/main/resources/resfile/qml"_L1;
1923}
1924
1925static bool copyAllQmlModules(const Options &options)
1926{
1927 const QString qmlDestBase = hapQmlDir(options);
1928
1929 // Process qml-import-paths first (typically CMAKE_BINARY_DIR/qml, i.e. the
1930 // module's own build-tree QML output). Files written here receive dest
1931 // mtime = now, so the subsequent qtQmlDirectory pass skips any file that
1932 // was already copied — this gives build-dir contents unconditional priority
1933 // over the installed Qt prefix without requiring a force-overwrite flag.
1934 for (const QString &importPath : options.qmlImportPaths) {
1935 if (!QDir(importPath).exists()) {
1936 if (options.verbose)
1937 fprintf(stdout, "QML import path not found, skipping: %s\n",
1938 qPrintable(importPath));
1939 continue;
1940 }
1941 if (options.verbose)
1942 fprintf(stdout, "Copying QML modules from import path: %s\n",
1943 qPrintable(importPath));
1944 if (!copyQmlDir(importPath, QString(), qmlDestBase, options))
1945 return false;
1946 }
1947
1948 // Process qtQmlDirectory second (the installed Qt prefix). Files that are
1949 // already present in dest (copied from qml-import-paths above) are skipped
1950 // by copyFileIfNewer; files that exist only here — e.g. QtQml/QtQuick when
1951 // building qtlottie against an installed qtdeclarative — are copied normally.
1952 if (options.qtQmlDirectory.isEmpty())
1953 return true;
1954 if (!QDir(options.qtQmlDirectory).exists()) {
1955 if (options.verbose)
1956 fprintf(stdout, "QML directory not found, skipping: %s\n",
1957 qPrintable(options.qtQmlDirectory));
1958 return true;
1959 }
1960 if (options.verbose)
1961 fprintf(stdout, "Copying all QML modules from %s\n",
1962 qPrintable(options.qtQmlDirectory));
1963 return copyQmlDir(options.qtQmlDirectory, QString(), qmlDestBase, options);
1964}
1965
1966static bool readQmldirLines(const QString &qmldirPath, QStringList &lines)
1967{
1968 QFile qmldir(qmldirPath);
1969 if (!qmldir.open(QIODevice::ReadOnly | QIODevice::Text)) {
1970 fprintf(stderr, "Failed to open qmldir %s: %s\n",
1971 qPrintable(qmldirPath), qPrintable(qmldir.errorString()));
1972 return false;
1973 }
1974
1975 lines = QString::fromUtf8(qmldir.readAll()).split(u'\n');
1976
1977 return true;
1978}
1979
1980// Deploy the plugins (*.so files) a qmldir declares to libs/<arch>.
1981static bool copyQmldirPlugins(const QString &qmldirPath, const Options &options)
1982{
1983 QStringList lines;
1984 if (!readQmldirLines(qmldirPath, lines))
1985 return false;
1986
1987 static const QRegularExpression pluginLine(
1988 "^\\s*(?:optional\\s+)?plugin\\s+(?<name>\\S+)(?:\\s+(?<path>\\S+))?"_L1);
1989
1990 const QDir moduleDir = QFileInfo(qmldirPath).absoluteDir();
1991
1992 for (const QString &line : lines) {
1993 const QRegularExpressionMatch match = pluginLine.match(line);
1994 if (!match.hasMatch())
1995 continue;
1996
1997 const QString pluginName = match.captured(u"name");
1998 const QString pluginFile = "lib"_L1 + pluginName + ".so"_L1;
1999 const QString optionalPluginPath = match.captured(u"path");
2000 const QString pluginSrc = moduleDir.filePath(
2001 optionalPluginPath.isEmpty() ? pluginFile : optionalPluginPath + "/"_L1 + pluginFile);
2002
2003 if (!QFileInfo::exists(pluginSrc)) {
2004 if (options.verbose) {
2005 fprintf(stdout, " qmldir %s declares plugin %s, but %s is missing\n",
2006 qPrintable(qmldirPath), qPrintable(pluginName),
2007 qPrintable(pluginSrc));
2008 }
2009 continue;
2010 }
2011
2012 if (!copyFileToArchitectures(options, pluginSrc, pluginFile))
2013 return false;
2014 }
2015
2016 return true;
2017}
2018
2019static bool getQmldirModuleUri(const QString &qmldirPath, QString &uri)
2020{
2021 QStringList lines;
2022 if (!readQmldirLines(qmldirPath, lines))
2023 return false;
2024
2025 static const QRegularExpression moduleLine("^\\s*module\\s+(?<uri>\\S+)"_L1);
2026 for (const QString &line : lines) {
2027 const QRegularExpressionMatch match = moduleLine.match(line);
2028 if (match.hasMatch()) {
2029 uri = match.captured(u"uri");
2030 return true;
2031 }
2032 }
2033
2034 uri.clear();
2035
2036 return true;
2037}
2038
2039static QString findNearestEnclosingTestDir(const QString &startDir, const QSet<QString> &testDirs)
2040{
2041 for (QDir dir(startDir); ; ) {
2042 const QString path = dir.absolutePath();
2043
2044 if (testDirs.contains(path))
2045 return path;
2046
2047 if (!dir.cdUp())
2048 return QString();
2049 }
2050}
2051
2057
2058static bool getTestQmlModuleDeployDir(const TestQmlModule &testModule, QString &deployDir)
2059{
2060 QString uri;
2061 if (!getQmldirModuleUri(testModule.qmldirPath, uri))
2062 return false;
2063
2064 if (uri.isEmpty()) {
2065 deployDir = QDir(testModule.testDir).relativeFilePath(
2066 QFileInfo(testModule.qmldirPath).absolutePath());
2067 } else {
2068 deployDir = uri.replace(u'.', u'/');
2069 }
2070
2071 return true;
2072}
2073
2075{
2076 if (options.testBinariesDirectory.isEmpty())
2077 return {};
2078
2079 QStringList testBinaries;
2080 QStringList unusedHelperLibs;
2081 QSet<QString> unusedHelperLibNames;
2082 const QStringList excludeDirs = { QFileInfo(options.outputDirectory).absoluteFilePath() };
2083 scanTestBinariesDir(options.testBinariesDirectory, options.testExcludeList, excludeDirs,
2084 testBinaries, unusedHelperLibs, unusedHelperLibNames);
2085
2086 QSet<QString> testDirs;
2087 for (const QString &testBinary : std::as_const(testBinaries))
2088 testDirs.insert(QFileInfo(testBinary).absoluteDir().absolutePath());
2089
2090 QList<TestQmlModule> modules;
2091 QSet<QString> seenQmldirs;
2092 for (const QString &testDir : std::as_const(testDirs)) {
2093 QDirIterator it(testDir, { "qmldir"_L1 }, QDir::Files, QDirIterator::Subdirectories);
2094 while (it.hasNext()) {
2095 const QString qmldirPath = it.next();
2096 if (seenQmldirs.contains(qmldirPath))
2097 continue;
2098
2099 const QString testDir =
2100 findNearestEnclosingTestDir(QFileInfo(qmldirPath).absolutePath(), testDirs);
2101 seenQmldirs.insert(qmldirPath);
2102 modules.append({ qmldirPath, testDir });
2103 }
2104 }
2105
2106 return modules;
2107}
2108
2109// Fail if two test QML modules in the bundle deploy to the same directory under
2110// resfile/qml, where one would overwrite the other.
2111static bool verifyUniqueTestQmlModuleDeployDirs(const QList<TestQmlModule> &modules)
2112{
2113 QHash<QString, QString> deployDirToQmldir;
2114 for (const TestQmlModule &module : modules) {
2115 QString deployDir;
2116 if (!getTestQmlModuleDeployDir(module, deployDir))
2117 return false;
2118
2119 const auto existing = deployDirToQmldir.constFind(deployDir);
2120 if (existing != deployDirToQmldir.constEnd()) {
2121 fprintf(stderr,
2122 "Error: two test QML modules deploy to the same directory \"%s\" "
2123 "under resfile/qml:\n %s\n %s\n"
2124 "They would overwrite one another; give one a different module URI.\n",
2125 qPrintable(deployDir), qPrintable(*existing), qPrintable(module.qmldirPath));
2126 return false;
2127 }
2128 deployDirToQmldir.insert(deployDir, module.qmldirPath);
2129 }
2130
2131 return true;
2132}
2133
2134static bool copyTestQmlModuleFiles(const QString &moduleSrcDirPath,
2135 const QString &destModuleDirPath, const Options &options)
2136{
2137 static const QStringList qmlModuleFileNameFilters = {
2138 "qmldir"_L1,
2139 "*.qmltypes"_L1,
2140 "*.qml"_L1,
2141 "*.js"_L1,
2142 "*.mjs"_L1,
2143 };
2144
2145 const QDir moduleSrcDir(moduleSrcDirPath);
2146 QDirIterator it(
2147 moduleSrcDirPath, qmlModuleFileNameFilters, QDir::Files, QDirIterator::Subdirectories);
2148 while (it.hasNext()) {
2149 const QString srcPath = it.next();
2150 const QString destPath =
2151 destModuleDirPath + "/"_L1 + moduleSrcDir.relativeFilePath(srcPath);
2152
2153 QDir().mkpath(QFileInfo(destPath).absolutePath());
2154
2155 if (!copyFileIfNewer(srcPath, destPath, options.verbose))
2156 return false;
2157
2158 if (!options.depFilePath.isEmpty())
2159 dependenciesForDepfile << srcPath;
2160
2161 if (it.fileName() == "qmldir"_L1 && !copyQmldirPlugins(srcPath, options))
2162 return false;
2163 }
2164
2165 return true;
2166}
2167
2168// Deploy each test's generated QML modules into resfile/qml
2169static bool copyTestQmlModules(const QList<TestQmlModule> &modules, const Options &options)
2170{
2171 for (const TestQmlModule &module : modules) {
2172 const QString moduleSrcDir = QFileInfo(module.qmldirPath).absolutePath();
2173
2174 QString deployDir;
2175 if (!getTestQmlModuleDeployDir(module, deployDir))
2176 return false;
2177
2178 const QString destModuleDir = hapQmlDir(options) + "/"_L1 + deployDir;
2179 if (!copyTestQmlModuleFiles(moduleSrcDir, destModuleDir, options))
2180 return false;
2181 }
2182
2183 return true;
2184}
2185
2186static QStringList listDirectoryTree(const QString &root)
2187{
2188 QStringList entries;
2189 QDirIterator it(
2190 root, QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden,
2191 QDirIterator::Subdirectories | QDirIterator::FollowSymlinks);
2192 while (it.hasNext())
2193 entries << it.next();
2194 return entries;
2195}
2196
2198{
2199 const QFileInfo source(rawfile.source);
2200 const QString rawfileRoot = rawfile.destination.isEmpty()
2201 ? source.fileName()
2202 : rawfile.destination + u'/' + source.fileName();
2203 QList<TestRawfileEntry> entries = { { rawfileRoot, rawfile.source, source.isDir() } };
2204 if (!source.isDir())
2205 return entries;
2206 const QDir sourceDir(rawfile.source);
2207 for (const QString &sourcePath : listDirectoryTree(rawfile.source)) {
2208 entries.append({ rawfileRoot + u'/' + sourceDir.relativeFilePath(sourcePath), sourcePath,
2209 QFileInfo(sourcePath).isDir() });
2210 }
2211 return entries;
2212}
2213
2215{
2216 QList<TestRawfileEntry> directories;
2217 QString rawfilePath;
2218 for (const QString &segment : rawfile.destination.split(u'/', Qt::SkipEmptyParts)) {
2219 rawfilePath += rawfilePath.isEmpty() ? segment : u'/' + segment;
2220 directories.append({ rawfilePath,
2221 rawfile.source + " (DESTINATION "_L1 + rawfile.destination + u')',
2222 true });
2223 }
2224 return directories;
2225}
2226
2227static bool verifyUniqueTestRawfilePaths(const QList<TestRawfile> &rawfiles)
2228{
2229 QHash<QString, TestRawfileEntry> entryByCaseFoldedPath;
2230 for (const TestRawfile &rawfile : rawfiles) {
2231 if (!QFileInfo::exists(rawfile.source)) {
2232 fprintf(stderr, "Test rawfile source does not exist: %s\n", qPrintable(rawfile.source));
2233 return false;
2234 }
2235 const QList<TestRawfileEntry> entries =
2236 listDestinationDirectories(rawfile) + listTestRawfileEntries(rawfile);
2237 for (const TestRawfileEntry &entry : entries) {
2238 const QString caseFoldedPath = entry.rawfilePath.toCaseFolded();
2239 const auto existing = entryByCaseFoldedPath.constFind(caseFoldedPath);
2240 if (existing == entryByCaseFoldedPath.constEnd()) {
2241 entryByCaseFoldedPath.insert(caseFoldedPath, entry);
2242 continue;
2243 }
2244 if (existing->isDirectory && entry.isDirectory
2245 && existing->rawfilePath == entry.rawfilePath) {
2246 continue;
2247 }
2248 fprintf(
2249 stderr,
2250 "Error: test rawfiles clash at rawfile/%s:\n %s\n %s\n"
2251 "They would overwrite one another; rename one of them.\n",
2252 qPrintable(entry.rawfilePath), qPrintable(existing->sourcePath),
2253 qPrintable(entry.sourcePath));
2254 return false;
2255 }
2256 }
2257 return true;
2258}
2259
2260static bool copyTestRawfiles(const Options &options)
2261{
2262 const QString rawfileDir = options.outputDirectory + "/entry/src/main/resources/rawfile"_L1;
2263 if (!QDir(rawfileDir).removeRecursively()) {
2264 fprintf(stderr, "Failed to remove previous test rawfiles: %s\n", qPrintable(rawfileDir));
2265 return false;
2266 }
2267 for (const TestRawfile &rawfile : options.testRawfiles) {
2268 for (const TestRawfileEntry &entry : listTestRawfileEntries(rawfile)) {
2269 const QString destination = rawfileDir + u'/' + entry.rawfilePath;
2270 if (entry.isDirectory) {
2271 if (!QDir().mkpath(destination)) {
2272 fprintf(stderr, "Failed to create directory: %s\n", qPrintable(destination));
2273 return false;
2274 }
2275 } else if (!copyFileIfNewer(entry.sourcePath, destination, options.verbose)) {
2276 return false;
2277 }
2278 if (!options.depFilePath.isEmpty())
2279 dependenciesForDepfile << entry.sourcePath;
2280 }
2281 }
2282 return true;
2283}
2284
2285static QString findLlvmReadobj(const Options &options)
2286{
2287 // Look for llvm-readobj in the NDK and alternative path
2288 const QStringList searchPaths = {
2289 options.ndkRoot + "/llvm/bin"_L1,
2290 options.sdkRoot + "/command-line-tools/sdk/default/openharmony/native/llvm/bin"_L1
2291 };
2292
2293 const QString llvmReadobj = QStandardPaths::findExecutable("llvm-readobj"_L1, searchPaths);
2294 if (!llvmReadobj.isEmpty())
2295 return llvmReadobj;
2296
2297 return QString();
2298}
2299
2300struct QtDependency
2301{
2302 QString relativePath; // e.g., "lib/libQt6Core.so"
2303 QString absolutePath; // Full path on filesystem
2304};
2305
2306// Returns the SONAME embedded in the ELF dynamic section of the library, or an empty
2307// string if it cannot be determined. The SONAME may differ from the on-disk filename
2308// (e.g. libicudata.so has SONAME libicudata.so.78).
2309static QString readElfSoname(const Options &options, const QString &binaryPath)
2310{
2311 const QString llvmReadobj = findLlvmReadobj(options);
2312 if (llvmReadobj.isEmpty())
2313 return QString();
2314
2315 QProcess process;
2316 process.start(llvmReadobj, {"--dynamic"_L1, binaryPath});
2317 if (!process.waitForStarted() || !process.waitForFinished(30000))
2318 return QString();
2319
2320 const QString output = QString::fromUtf8(process.readAllStandardOutput());
2321 // Output line: " 0x...E SONAME Library soname: [libfoo.so.1]"
2322 for (const auto &line : output.split('\n'_L1)) {
2323 if (!line.contains("SONAME"_L1))
2324 continue;
2325 const int lb = line.indexOf('['_L1);
2326 const int rb = line.indexOf(']'_L1, lb);
2327 if (lb >= 0 && rb > lb)
2328 return line.mid(lb + 1, rb - lb - 1);
2329 }
2330 return QString();
2331}
2332
2333static QStringList readElfDependencies(const Options &options, const QString &binaryPath)
2334{
2335 QString llvmReadobj = findLlvmReadobj(options);
2336 if (llvmReadobj.isEmpty()) {
2337 fprintf(stderr, "Warning: llvm-readobj not found, cannot detect dependencies\n");
2338 return QStringList();
2339 }
2340
2341 QProcess process;
2342 QStringList arguments;
2343 arguments << "--needed-libs"_L1 << binaryPath;
2344
2345 process.start(llvmReadobj, arguments);
2346 if (!process.waitForStarted()) {
2347 fprintf(stderr, "Failed to start llvm-readobj\n");
2348 return QStringList();
2349 }
2350
2351 if (!process.waitForFinished(30000)) { // 30 second timeout
2352 fprintf(stderr, "llvm-readobj timed out\n");
2353 process.kill();
2354 return QStringList();
2355 }
2356
2357 if (process.exitCode() != 0) {
2358 fprintf(stderr, "llvm-readobj failed with exit code %d\n", process.exitCode());
2359 return QStringList();
2360 }
2361
2362 QStringList dependencies;
2363 QString output = QString::fromUtf8(process.readAllStandardOutput());
2364 QStringList lines = output.split('\n'_L1);
2365
2366 bool inNeededLibs = false;
2367 for (const QString &line : lines) {
2368 QString trimmed = line.trimmed();
2369
2370 if (trimmed.startsWith("NeededLibraries"_L1)) {
2371 inNeededLibs = true;
2372 continue;
2373 }
2374
2375 if (!inNeededLibs)
2376 continue;
2377
2378 // Stop at next section
2379 if (trimmed.isEmpty() || trimmed.contains(':'_L1))
2380 break;
2381
2382 // Extract library name
2383 if (trimmed.startsWith("lib"_L1))
2384 dependencies.append(trimmed);
2385 }
2386
2387 return dependencies;
2388}
2389
2390static QString findExtraDepLibrary(const Options &options, const QString &libName)
2391{
2392 for (const QString &dir : options.extraLibsDirs) {
2393 // Try exact name first (e.g. libicudata.so.78)
2394 QString libPath = dir + "/"_L1 + libName;
2395 if (QFile::exists(libPath))
2396 return libPath;
2397 // Fall back to unversioned name (e.g. libicudata.so) for libraries whose
2398 // SONAME carries a version suffix but the file on disk does not.
2399 int soIdx = libName.indexOf(".so."_L1);
2400 if (soIdx >= 0) {
2401 QString baseName = libName.left(soIdx + 3); // up to and including ".so"
2402 libPath = dir + "/"_L1 + baseName;
2403 if (QFile::exists(libPath))
2404 return libPath;
2405 }
2406 }
2407 return QString();
2408}
2409
2410static bool isSystemLibrary(const QString &libName)
2411{
2412 // System libraries that should not be bundled
2413 return libName.startsWith("libc."_L1) ||
2414 libName.startsWith("libm."_L1) ||
2415 libName.startsWith("libdl."_L1) ||
2416 libName == "libEGL.so"_L1 ||
2417 libName == "libGLESv2.so"_L1 ||
2418 libName == "libGLESv3.so"_L1 ||
2419 libName.startsWith("libz."_L1) ||
2420 libName == "libc++_shared.so"_L1;
2421}
2422
2423static QString findQtLibrary(const Options &options, const QString &libName)
2424{
2425 // Use qtLibsDirectory if provided (preferred method, from JSON config)
2426 if (!options.qtLibsDirectory.isEmpty()) {
2427 QString libPath = options.qtLibsDirectory + "/"_L1 + libName;
2428 if (QFile::exists(libPath))
2429 return libPath;
2430 }
2431
2432 // Fallback: walk up from application binary to find Qt installation
2433 QFileInfo appInfo(options.applicationBinary);
2434 QDir dir(appInfo.absolutePath());
2435 for (int i = 0; i < 10; ++i) {
2436 // Check qtbase/lib (common for non-prefix builds)
2437 QString qtbaseLib = dir.absoluteFilePath("qtbase/lib"_L1);
2438 if (QDir(qtbaseLib).exists()) {
2439 QString libPath = qtbaseLib + "/"_L1 + libName;
2440 if (QFile::exists(libPath))
2441 return libPath;
2442 }
2443 // Check lib directory
2444 QString libDir = dir.absoluteFilePath("lib"_L1);
2445 if (QDir(libDir).exists()) {
2446 QString libPath = libDir + "/"_L1 + libName;
2447 if (QFile::exists(libPath))
2448 return libPath;
2449 }
2450 if (!dir.cdUp())
2451 break;
2452 }
2453
2454 return QString();
2455}
2456
2457static bool detectAndCopyDependencies(const Options &options, QSet<QString> &processedLibs)
2458{
2459 if (options.verbose)
2460 fprintf(stdout, "Detecting Qt library dependencies\n");
2461
2462 // Start with the application binary
2463 QStringList toProcess;
2464 toProcess.append(options.applicationBinary);
2465
2466 // Add project libraries to the ELF dependency analysis queue so their Qt
2467 // dependencies are also transitively scanned and deployed.
2468 for (const QString &projectLib : options.projectLibraries)
2469 toProcess.append(projectLib);
2470
2471 QList<QtDependency> qtDependencies;
2472 QStringList detectedQtModules; // Track detected Qt module names
2473 bool needsStdCpp = false;
2474
2475 while (!toProcess.isEmpty()) {
2476 QString currentLib = toProcess.takeFirst();
2477
2478 if (processedLibs.contains(currentLib))
2479 continue;
2480
2481 processedLibs.insert(currentLib);
2482
2483 if (options.verbose)
2484 fprintf(stdout, " Analyzing: %s\n", qPrintable(QFileInfo(currentLib).fileName()));
2485
2486 QStringList deps = readElfDependencies(options, currentLib);
2487
2488 for (const QString &dep : deps) {
2489 // Check if we need C++ standard library
2490 if (dep == "libc++_shared.so"_L1) {
2491 needsStdCpp = true;
2492 continue;
2493 }
2494
2495 // Skip system libraries
2496 if (isSystemLibrary(dep))
2497 continue;
2498
2499 // Only process Qt libraries, platform plugins, and third-party libs from extra dirs
2500 if (!dep.startsWith("libQt6"_L1) && !dep.startsWith("libqohos"_L1)) {
2501 // Check extra library search directories (e.g. HARMONYOS_DEPS_ROOT/lib)
2502 QString extraDepPath = findExtraDepLibrary(options, dep);
2503 if (extraDepPath.isEmpty())
2504 continue;
2505 // Guard against duplicates without blocking recursive ELF scanning:
2506 // do NOT insert into processedLibs here — the while-loop dequeue does
2507 // that, which also ensures the library's own ELF deps get scanned.
2508 if (!processedLibs.contains(extraDepPath) && !toProcess.contains(extraDepPath)) {
2509 if (options.verbose)
2510 fprintf(stdout, " Found extra dep: %s\n", qPrintable(dep));
2511 QtDependency extraDep;
2512 extraDep.relativePath = "lib/"_L1 + dep;
2513 extraDep.absolutePath = extraDepPath;
2514 qtDependencies.append(extraDep);
2515 toProcess.append(extraDepPath);
2516 }
2517 continue;
2518 }
2519
2520 // Extract module name from Qt library (e.g., libQt6Core.so -> Core)
2521 if (dep.startsWith("libQt6"_L1)) {
2522 QString moduleName = dep.mid(6); // Skip "libQt6"
2523 if (moduleName.endsWith(".so"_L1))
2524 moduleName.chop(3);
2525 if (!moduleName.isEmpty() && !detectedQtModules.contains(moduleName))
2526 detectedQtModules.append(moduleName);
2527 }
2528
2529 QString depPath = findQtLibrary(options, dep);
2530 if (depPath.isEmpty()) {
2531 if (options.verbose)
2532 fprintf(stdout, " Warning: Could not find Qt library: %s\n", qPrintable(dep));
2533 continue;
2534 }
2535
2536 if (processedLibs.contains(depPath))
2537 continue;
2538
2539 if (options.verbose)
2540 fprintf(stdout, " Found dependency: %s\n", qPrintable(dep));
2541
2542 QtDependency qtDep;
2543 qtDep.relativePath = "lib/"_L1 + dep;
2544 qtDep.absolutePath = depPath;
2545 qtDependencies.append(std::move(qtDep));
2546
2547 // Add to processing queue for recursive dependency detection
2548 toProcess.append(std::move(depPath));
2549 }
2550 }
2551
2552 if (options.verbose) {
2553 fprintf(stdout, "Found %lld Qt library dependencies\n", static_cast<long long>(qtDependencies.size()));
2554 if (needsStdCpp)
2555 fprintf(stdout, "C++ standard library required\n");
2556 }
2557
2558 // Copy C++ standard library if needed (per-arch, since source path is arch-specific)
2559 if (needsStdCpp) {
2560 for (const QString &arch : options.targetArchs) {
2561 QString archLibPath = options.outputDirectory + "/entry/libs/"_L1 + arch;
2562 QString stdCppPath = findStdCppLibrary(options, arch);
2563 if (stdCppPath.isEmpty()) {
2564 fprintf(stderr, "Warning: Could not find C++ standard library for %s\n", qPrintable(arch));
2565 } else {
2566 QString destPath = archLibPath + "/libc++_shared.so"_L1;
2567 if (options.verbose)
2568 fprintf(stdout, " Copying C++ standard library for %s\n", qPrintable(arch));
2569 if (!copyFileIfNewer(stdCppPath, destPath, options.verbose)) {
2570 fprintf(stderr,
2571 "Failed to copy C++ standard library to: %s\n",
2572 qPrintable(destPath));
2573 return false;
2574 }
2575
2576 // Track as dependency for depfile
2577 if (!options.depFilePath.isEmpty())
2578 dependenciesForDepfile << stdCppPath;
2579 }
2580 }
2581 }
2582
2583 // Copy all detected Qt/extra libraries to all target architectures.
2584 // copyFileToArchitectures handles all arches internally; call it once per library.
2585 // Use dep.relativePath filename so the deployed name matches the ELF SONAME
2586 // (e.g. libicudata.so.78, not the unversioned on-disk name libicudata.so).
2587 for (const QtDependency &dep : qtDependencies) {
2588 QFileInfo libInfo(dep.relativePath);
2589 if (!copyFileToArchitectures(options, dep.absolutePath, libInfo.fileName(), false))
2590 return false;
2591
2592 if (!options.depFilePath.isEmpty())
2593 dependenciesForDepfile << dep.absolutePath;
2594 }
2595
2596 return true;
2597}
2598
2600{
2601 // 1. Use qtPluginsDirectory if provided (from JSON config)
2602 if (!options.qtPluginsDirectory.isEmpty() &&
2603 QDir(options.qtPluginsDirectory).exists()) {
2604 return options.qtPluginsDirectory;
2605 }
2606
2607 // 2. Fallback: walk up from application binary
2608 QFileInfo appInfo(options.applicationBinary);
2609 QDir dir(appInfo.absolutePath());
2610 for (int i = 0; i < 10; ++i) {
2611 // Check qtbase/plugins for modular builds
2612 QString candidate = dir.absoluteFilePath("qtbase/plugins"_L1);
2613 if (QDir(candidate).exists())
2614 return candidate;
2615
2616 // Check plugins directory
2617 if (dir.exists("plugins"_L1))
2618 return dir.absoluteFilePath("plugins"_L1);
2619
2620 if (!dir.cdUp())
2621 break;
2622 }
2623
2624 return QString();
2625}
2626
2627static bool copyPlatformPlugin(const Options &options,
2628 const QString &qtPluginsPath,
2629 QSet<QString> &processedLibs)
2630{
2631 // Copy libqohos.so to ROOT libs directory (not in platforms subdirectory)
2632 QString qohosPlugin = qtPluginsPath + "/platforms/libqohos.so"_L1;
2633 if (!QFile::exists(qohosPlugin)) {
2634 fprintf(stderr, "Warning: Platform plugin libqohos.so not found at: %s\n",
2635 qPrintable(qohosPlugin));
2636 return true; // Not fatal
2637 }
2638
2639 // Detect dependencies of libqohos.so
2640 if (options.verbose)
2641 fprintf(stdout, " Detecting platform plugin dependencies\n");
2642
2643 QStringList pluginDeps = readElfDependencies(options, qohosPlugin);
2644 QList<QtDependency> additionalLibs;
2645
2646 for (const QString &dep : pluginDeps) {
2647 // Only process Qt libraries we haven't already copied
2648 if (!dep.startsWith("libQt6"_L1))
2649 continue;
2650
2651 QString depPath = findQtLibrary(options, dep);
2652 if (depPath.isEmpty()) {
2653 if (options.verbose)
2654 fprintf(stdout, " Warning: Could not find plugin dependency: %s\n",
2655 qPrintable(dep));
2656 continue;
2657 }
2658
2659 if (processedLibs.contains(depPath))
2660 continue;
2661
2662 if (options.verbose)
2663 fprintf(stdout, " Found plugin dependency: %s\n", qPrintable(dep));
2664
2665 processedLibs.insert(depPath);
2666 QtDependency qtDep;
2667 qtDep.relativePath = "lib/"_L1 + dep;
2668 qtDep.absolutePath = std::move(depPath);
2669 additionalLibs.append(std::move(qtDep));
2670 }
2671
2672 // Copy additional Qt libraries needed by the plugin
2673 for (const QString &arch : options.targetArchs) {
2674 QString archLibPath = options.outputDirectory + "/entry/libs/"_L1 + arch;
2675
2676 for (const QtDependency &dep : additionalLibs) {
2677 QString destPath = archLibPath + "/"_L1 + QFileInfo(dep.absolutePath).fileName();
2678
2679 if (options.verbose) {
2680 fprintf(stdout, " Copying plugin dependency for %s: %s\n",
2681 qPrintable(arch), qPrintable(QFileInfo(dep.absolutePath).fileName()));
2682 }
2683
2684 if (!copyFileIfNewer(dep.absolutePath, destPath, options.verbose)) {
2685 fprintf(stderr, "Failed to copy library: %s\n", qPrintable(destPath));
2686 return false;
2687 }
2688
2689 // Track as dependency for depfile
2690 if (!options.depFilePath.isEmpty())
2691 dependenciesForDepfile << dep.absolutePath;
2692 }
2693 }
2694
2695 // Now copy libqohos.so itself to root
2696 for (const QString &arch : options.targetArchs) {
2697 QString archLibPath = options.outputDirectory + "/entry/libs/"_L1 + arch;
2698 QString destPath = archLibPath + "/libqohos.so"_L1;
2699
2700 if (options.verbose)
2701 fprintf(stdout, " Copying platform plugin for %s: libqohos.so (to root)\n",
2702 qPrintable(arch));
2703
2704 if (!copyFileIfNewer(qohosPlugin, destPath, options.verbose)) {
2705 fprintf(stderr, "Failed to copy libqohos.so to: %s\n", qPrintable(destPath));
2706 return false;
2707 }
2708
2709 // Track as dependency for depfile
2710 if (!options.depFilePath.isEmpty())
2711 dependenciesForDepfile << qohosPlugin;
2712 }
2713
2714 return true;
2715}
2716
2717static bool copyPlugins(const Options &options, QSet<QString> &processedLibs)
2718{
2719 if (options.verbose)
2720 fprintf(stdout, "Copying required Qt plugins\n");
2721
2722 // Find Qt plugins directory
2723 QString qtPluginsPath = findQtPluginsDirectory(options);
2724 if (qtPluginsPath.isEmpty()) {
2725 fprintf(stderr, "Warning: Could not find Qt plugins directory\n");
2726 return true; // Not fatal
2727 }
2728
2729 if (options.verbose)
2730 fprintf(stdout, " Qt plugins directory: %s\n", qPrintable(qtPluginsPath));
2731
2732 // Copy platform plugin (special case: goes to root, not platforms/)
2733 if (!copyPlatformPlugin(options, qtPluginsPath, processedLibs))
2734 return false;
2735
2736 // Discover and copy all other plugins based on dependencies
2737 QDir pluginsDir(qtPluginsPath);
2738 QStringList pluginCategories = pluginsDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
2739
2740 if (options.verbose)
2741 fprintf(stdout, "Scanning plugin categories: %s\n",
2742 qPrintable(pluginCategories.join(", "_L1)));
2743
2744 for (const QString &category : pluginCategories) {
2745 // Skip platforms category - libqohos.so already handled specially above
2746 if (category == "platforms"_L1)
2747 continue;
2748
2749 QDir categoryDir(pluginsDir.filePath(category));
2750 QStringList plugins = categoryDir.entryList({"*.so"_L1}, QDir::Files);
2751
2752 if (plugins.isEmpty())
2753 continue;
2754
2755 if (options.verbose)
2756 fprintf(stdout, "\nChecking %s plugins (%lld found):\n",
2757 qPrintable(category), static_cast<long long>(plugins.size()));
2758
2759 for (const QString &plugin : plugins) {
2760 QString pluginPath = categoryDir.filePath(plugin);
2761
2762 // Read plugin's ELF dependencies
2763 QStringList deps = readElfDependencies(options, pluginPath);
2764
2765 // Check if all Qt dependencies are satisfied
2766 bool allDepsSatisfied = true;
2767 QStringList unsatisfiedDeps;
2768
2769 for (const QString &dep : deps) {
2770 // Skip system libraries
2771 if (isSystemLibrary(dep))
2772 continue;
2773
2774 // Check if Qt6 dependency is being included
2775 if (dep.startsWith("libQt6"_L1)) {
2776 QString depPath = findQtLibrary(options, dep);
2777 if (depPath.isEmpty() || !processedLibs.contains(depPath)) {
2778 allDepsSatisfied = false;
2779 unsatisfiedDeps.append(dep);
2780 }
2781 }
2782 }
2783
2784 if (allDepsSatisfied) {
2785 // Copy this plugin to entry/libs/{arch}/{category}/
2786 if (options.verbose)
2787 fprintf(stdout, " [✓] %s (dependencies satisfied)\n", qPrintable(plugin));
2788
2789 QString relativeDestPath = "%1/%2"_L1.arg(category, plugin);
2790 if (!copyFileToArchitectures(options, pluginPath, relativeDestPath))
2791 return false;
2792 } else {
2793 if (options.verbose) {
2794 fprintf(stdout, " [✗] %s (missing: %s)\n",
2795 qPrintable(plugin), qPrintable(unsatisfiedDeps.join(", "_L1)));
2796 }
2797 }
2798 }
2799 }
2800
2801 if (options.verbose)
2802 fprintf(stdout, "Plugin copying completed\n");
2803
2804 return true;
2805}
2806
2808{
2809 QString name; // Module name (e.g., "QtQuick")
2810 QString path; // Absolute path to module directory
2811 QString type; // "module" or "plugin"
2812 QString plugin; // Plugin name (e.g., "qtquick2plugin")
2813 bool pluginIsOptional = false; // Whether plugin is optional
2814 QString prefer; // Preferred location (e.g., ":/" means embedded in resources)
2815 QStringList components; // List of QML component file paths
2816 QStringList scripts; // List of JavaScript file paths
2817};
2818
2819static QList<QmlImportInfo> scanQmlImports(const Options &options, bool *ok = nullptr)
2820{
2821 if (ok)
2822 *ok = true;
2823
2824 QList<QmlImportInfo> imports;
2825
2826 if (options.qmlRootPaths.isEmpty()) {
2827 if (options.verbose)
2828 fprintf(stdout,
2829 "No QML root path specified, skipping QML import scanning\n");
2830 return imports;
2831 }
2832
2833 if (options.verbose)
2834 fprintf(stdout, "Scanning for QML imports\n");
2835
2836 // 1. Use qtLibExecsDirectory if provided (preferred, from JSON config)
2837 QStringList searchPaths;
2838 if (!options.qtLibExecsDirectory.isEmpty())
2839 searchPaths.append(options.qtLibExecsDirectory);
2840
2841 // 2. Try qtHostDirectory/bin as fallback
2842 if (!options.qtHostDirectory.isEmpty())
2843 searchPaths.append(options.qtHostDirectory + "/bin"_L1);
2844
2845 QString qmlImportScannerPath =
2846 QStandardPaths::findExecutable("qmlimportscanner"_L1, searchPaths);
2847
2848 // 3. Fallback: search from application binary path
2849 if (qmlImportScannerPath.isEmpty()) {
2850 QDir dir(QFileInfo(options.applicationBinary).absolutePath());
2851
2852 for (int i = 0; i < 10; ++i) {
2853 qmlImportScannerPath = QStandardPaths::findExecutable(
2854 "qmlimportscanner"_L1,
2855 {dir.absoluteFilePath("libexec"_L1), dir.absoluteFilePath("bin"_L1)});
2856
2857 if (!qmlImportScannerPath.isEmpty())
2858 break;
2859
2860 if (!dir.cdUp())
2861 break;
2862 }
2863 }
2864
2865 if (qmlImportScannerPath.isEmpty()) {
2866 fprintf(
2867 stderr,
2868 "Warning: qmlimportscanner not found, skipping QML import scanning\n");
2869 return imports;
2870 }
2871
2872 if (options.verbose)
2873 fprintf(stdout, " Using qmlimportscanner: %s\n",
2874 qPrintable(qmlImportScannerPath));
2875
2876 // Build import paths argument
2877 QStringList importPaths;
2878
2879 // Add QML import paths from config
2880 for (const QString &path : options.qmlImportPaths)
2881 if (QFile::exists(path))
2882 importPaths.append(path);
2883
2884 // Add application build directory for locally-built QML modules
2885 // This is needed to find modules like "shared" that are built alongside the
2886 // app
2887 QFileInfo appBinary(options.applicationBinary);
2888 QString appBuildDir = appBinary.absolutePath();
2889 if (QDir(appBuildDir).exists())
2890 importPaths.append(appBuildDir);
2891
2892 // Add Qt QML directory (target platform)
2893 if (!options.qtQmlDirectory.isEmpty() &&
2894 QDir(options.qtQmlDirectory).exists()) {
2895 importPaths.append(options.qtQmlDirectory);
2896 } else {
2897 // Fallback: search from application binary path
2898 QFileInfo appBinary(options.applicationBinary);
2899 QDir qtDir(appBinary.absolutePath());
2900 for (int i = 0; i < 10; ++i) {
2901 QString qmlDir = qtDir.absoluteFilePath("qml"_L1);
2902 if (QDir(qmlDir).exists()) {
2903 importPaths.append(qmlDir);
2904 break;
2905 }
2906 // Also check qtbase/../qml for modular builds
2907 qmlDir = qtDir.absoluteFilePath("qtbase/../qml"_L1);
2908 if (QDir(qmlDir).exists()) {
2909 importPaths.append(QDir::cleanPath(qmlDir));
2910 break;
2911 }
2912 if (!qtDir.cdUp())
2913 break;
2914 }
2915 }
2916
2917 if (importPaths.isEmpty()) {
2918 fprintf(stderr, "Warning: No QML import paths found\n");
2919 return imports;
2920 }
2921
2922 // Build qmlimportscanner command. qmlimportscanner accepts a -rootPath flag
2923 // per root, so emit them in order.
2924 QStringList arguments;
2925 for (const QString &rootPath : options.qmlRootPaths)
2926 arguments << "-rootPath"_L1 << rootPath;
2927
2928 for (const QString &importPath : importPaths)
2929 arguments << "-importPath"_L1 << importPath;
2930
2931 if (options.verbose) {
2932 fprintf(stdout, " Root paths:\n");
2933 for (const QString &rootPath : options.qmlRootPaths)
2934 fprintf(stdout, " %s\n", qPrintable(rootPath));
2935 fprintf(stdout, " Import paths:\n");
2936 for (const QString &path : importPaths)
2937 fprintf(stdout, " %s\n", qPrintable(path));
2938 }
2939
2940 // Run qmlimportscanner
2941 QProcess process;
2942 process.start(qmlImportScannerPath, arguments);
2943
2944 if (!process.waitForFinished(30000)) {
2945 process.kill();
2946 process.waitForFinished(2000);
2947 fprintf(stderr, "Error: qmlimportscanner timed out after 30 seconds\n");
2948 fprintf(stderr, " Command: %s %s\n", qPrintable(qmlImportScannerPath),
2949 qPrintable(arguments.join(u' ')));
2950 const QByteArray errorOutput = process.readAllStandardError();
2951 if (!errorOutput.isEmpty())
2952 fprintf(stderr, "%s\n", errorOutput.constData());
2953 if (ok)
2954 *ok = false;
2955 return imports;
2956 }
2957
2958 if (process.exitStatus() != QProcess::NormalExit) {
2959 fprintf(stderr, "Error: qmlimportscanner crashed\n");
2960 fprintf(stderr, "%s\n", process.readAllStandardError().constData());
2961 if (ok)
2962 *ok = false;
2963 return imports;
2964 }
2965
2966 if (process.exitCode() != 0) {
2967 fprintf(stderr, "Error: qmlimportscanner failed with exit code %d\n",
2968 process.exitCode());
2969 fprintf(stderr, "%s\n", process.readAllStandardError().constData());
2970 if (ok)
2971 *ok = false;
2972 return imports;
2973 }
2974
2975 // Parse JSON output
2976 QByteArray output = process.readAllStandardOutput();
2977 QJsonDocument doc = QJsonDocument::fromJson(output);
2978
2979 if (!doc.isArray()) {
2980 fprintf(stderr, "Error: Invalid JSON output from qmlimportscanner\n");
2981 if (ok)
2982 *ok = false;
2983 return imports;
2984 }
2985
2986 QJsonArray array = doc.array();
2987 for (const QJsonValue &value : array) {
2988 if (!value.isObject())
2989 continue;
2990
2991 QJsonObject obj = value.toObject();
2992 QmlImportInfo info;
2993 info.name = obj["name"_L1].toString();
2994 info.path = obj["path"_L1].toString();
2995 info.type = obj["type"_L1].toString();
2996
2997 if (obj.contains("plugin"_L1))
2998 info.plugin = obj["plugin"_L1].toString();
2999
3000 if (obj.contains("pluginIsOptional"_L1))
3001 info.pluginIsOptional = obj["pluginIsOptional"_L1].toBool();
3002
3003 if (obj.contains("prefer"_L1))
3004 info.prefer = obj["prefer"_L1].toString();
3005
3006 // Parse components array
3007 if (obj.contains("components"_L1)) {
3008 QJsonArray componentsArray = obj["components"_L1].toArray();
3009 for (const QJsonValue &comp : componentsArray)
3010 info.components.append(comp.toString());
3011 }
3012
3013 // Parse scripts array
3014 if (obj.contains("scripts"_L1)) {
3015 QJsonArray scriptsArray = obj["scripts"_L1].toArray();
3016 for (const QJsonValue &script : scriptsArray)
3017 info.scripts.append(script.toString());
3018 }
3019
3020 // Skip if path is empty (unresolved import)
3021 if (info.path.isEmpty()) {
3022 if (options.verbose)
3023 fprintf(stdout, " Warning: Could not resolve QML import: %s\n",
3024 qPrintable(info.name));
3025 continue;
3026 }
3027
3028 // Skip if type is not module
3029 if (info.type != "module"_L1)
3030 continue;
3031
3032 if (options.verbose)
3033 fprintf(stdout, " Found QML import: %s at %s\n", qPrintable(info.name),
3034 qPrintable(info.path));
3035
3036 imports.append(info);
3037 }
3038
3039 return imports;
3040}
3041
3042static bool copyQmlFiles(const Options &options)
3043{
3044 if (options.qmlRootPaths.isEmpty())
3045 return true; // Not an error, just no QML files to copy
3046
3047 // Target directory: entry/src/main/resources/rawfile/qml/.
3048 //
3049 // Multiple roots are merged into the same destination. copyFileIfNewer
3050 // only overwrites when the source mtime is newer than the destination,
3051 // so in practice the *first* root to land a given file wins. User-set
3052 // QT_QML_ROOT_PATH values are emitted before auto-collected roots (see
3053 // _qt_internal_harmonyos_format_deployment_paths in Qt6HarmonyOSMacros.cmake),
3054 // giving explicit user settings precedence over auto-collected ones on
3055 // collision.
3056 const QString destDir =
3057 options.outputDirectory + "/entry/src/main/resources/rawfile/qml"_L1;
3058 if (!QDir().mkpath(destDir)) {
3059 fprintf(stderr, "Failed to create QML destination directory: %s\n",
3060 qPrintable(destDir));
3061 return false;
3062 }
3063
3064 for (const QString &rootPath : options.qmlRootPaths) {
3065 if (options.verbose)
3066 fprintf(stdout, "Copying QML files from %s\n", qPrintable(rootPath));
3067
3068 if (!copyRecursively(rootPath, destDir, options.verbose)) {
3069 fprintf(stderr, "Failed to copy QML files from %s\n", qPrintable(rootPath));
3070 return false;
3071 }
3072 }
3073
3074 if (options.verbose)
3075 fprintf(stdout, "QML files copied successfully\n");
3076
3077 return true;
3078}
3079
3080static bool copyQmlImports(const Options &options,
3081 const QList<QmlImportInfo> &imports,
3082 QSet<QString> &processedLibs)
3083{
3084 if (imports.isEmpty())
3085 return true;
3086
3087 if (options.verbose)
3088 fprintf(stdout, "Copying QML imports\n");
3089
3090 // QML non-.so files go to resfile/qml/ (maintaining directory structure)
3091 // QML plugin .so files go to libs/arm64-v8a/ (flat, no subdirectory)
3092 QString qmlDestBase = hapQmlDir(options);
3093 QDir().mkpath(qmlDestBase);
3094
3095 // Track QML plugins to scan for dependencies
3096 QStringList qmlPluginsToScan;
3097
3098 for (const QmlImportInfo &import : imports) {
3099 if (options.verbose)
3100 fprintf(stdout, " Copying QML module: %s\n", qPrintable(import.name));
3101
3102 // Determine module subdirectory - preserve full path structure
3103 // e.g., QtQuick.Window should go to QtQuick/Window/, not just Window/
3104 QString relativePath;
3105
3106 // Calculate relative path from Qt QML directory
3107 if (!options.qtQmlDirectory.isEmpty() && import.path.startsWith(options.qtQmlDirectory)) {
3108 // Qt module - use relative path from Qt QML dir
3109 relativePath = import.path.mid(options.qtQmlDirectory.length());
3110 if (relativePath.startsWith('/'_L1))
3111 relativePath = relativePath.mid(1);
3112 } else {
3113 // Application module or other - use module name converted to path
3114 // e.g., "QtQuick.Window" -> "QtQuick/Window"
3115 relativePath = import.name;
3116 relativePath.replace('.'_L1, '/'_L1);
3117 }
3118
3119 QString destModuleDir = qmlDestBase + "/"_L1 + relativePath;
3120 QDir().mkpath(destModuleDir);
3121
3122 // Copy qmldir file (required for module discovery)
3123 QString qmldirSrc = import.path + "/qmldir"_L1;
3124 QString qmldirDest = destModuleDir + "/qmldir"_L1;
3125 if (QFile::exists(qmldirSrc)) {
3126 if (copyFileIfNewer(qmldirSrc, qmldirDest, options.verbose)) {
3127 if (options.verbose)
3128 fprintf(stdout, " Copied qmldir\n");
3129
3130 // Track as dependency for depfile
3131 if (!options.depFilePath.isEmpty())
3132 dependenciesForDepfile << qmldirSrc;
3133 } else {
3134 fprintf(stderr, "Warning: Failed to copy qmldir for %s\n",
3135 qPrintable(import.name));
3136 }
3137 }
3138
3139 // Copy plugin library if not embedded in resources
3140 // Check "prefer" field - if it starts with ":/" then QML files are in
3141 // resources
3142 bool qmlFilesAreEmbedded = import.prefer.startsWith(":/"_L1);
3143
3144 if (!import.plugin.isEmpty()) {
3145 // QML plugin .so files go to libs/arm64-v8a/ (flat, per HarmonyOS requirements)
3146 QString pluginFileName = "lib"_L1 + import.plugin + ".so"_L1;
3147 QString pluginSrc = import.path + "/"_L1 + pluginFileName;
3148
3149 if (QFile::exists(pluginSrc)) {
3150 // Copy to libs directory for each architecture
3151 for (const QString &arch : options.targetArchs) {
3152 QString pluginDest = options.outputDirectory + "/entry/libs/"_L1 + arch
3153 + "/"_L1 + pluginFileName;
3154
3155 if (copyFileIfNewer(pluginSrc, pluginDest, options.verbose)) {
3156 if (options.verbose)
3157 fprintf(stdout, " Copied plugin to libs/%s: %s\n",
3158 qPrintable(arch), qPrintable(pluginFileName));
3159 processedLibs.insert(pluginSrc);
3160
3161 // Add plugin to list for dependency scanning
3162 if (!qmlPluginsToScan.contains(pluginSrc))
3163 qmlPluginsToScan.append(pluginSrc);
3164
3165 // Track as dependency for depfile
3166 if (!options.depFilePath.isEmpty())
3167 dependenciesForDepfile << pluginSrc;
3168 } else if (!import.pluginIsOptional) {
3169 fprintf(stderr, "Warning: Failed to copy required plugin: %s\n",
3170 qPrintable(pluginFileName));
3171 }
3172 }
3173 } else if (!import.pluginIsOptional) {
3174 if (options.verbose)
3175 fprintf(stdout, " Warning: Required plugin not found: %s\n",
3176 qPrintable(pluginFileName));
3177 }
3178 }
3179
3180 // Copy QML component files (only if not embedded in resources)
3181 if (!qmlFilesAreEmbedded) {
3182 for (const QString &component : import.components) {
3183 QFileInfo compInfo(component);
3184 if (!compInfo.exists()) {
3185 if (options.verbose)
3186 fprintf(stdout, " Warning: Component file not found: %s\n",
3187 qPrintable(component));
3188 continue;
3189 }
3190
3191 QString relativePath = component.mid(import.path.length());
3192 if (relativePath.startsWith('/'_L1))
3193 relativePath = relativePath.mid(1);
3194
3195 QString destFile = destModuleDir + "/"_L1 + relativePath;
3196 QFileInfo destInfo(destFile);
3197 QDir().mkpath(destInfo.absolutePath());
3198
3199 if (copyFileIfNewer(component, destFile, options.verbose)) {
3200 if (options.verbose)
3201 fprintf(stdout, " Copied component: %s\n", qPrintable(compInfo.fileName()));
3202
3203 // Track as dependency for depfile
3204 if (!options.depFilePath.isEmpty())
3205 dependenciesForDepfile << component;
3206 }
3207 }
3208
3209 // Copy JavaScript files
3210 for (const QString &script : import.scripts) {
3211 QFileInfo scriptInfo(script);
3212 if (!scriptInfo.exists())
3213 continue;
3214
3215 QString relativePath = script.mid(import.path.length());
3216 if (relativePath.startsWith('/'_L1))
3217 relativePath = relativePath.mid(1);
3218
3219 QString destFile = destModuleDir + "/"_L1 + relativePath;
3220 QFileInfo destInfo(destFile);
3221 QDir().mkpath(destInfo.absolutePath());
3222
3223 if (copyFileIfNewer(script, destFile, options.verbose)) {
3224 if (options.verbose)
3225 fprintf(stdout, " Copied script: %s\n", qPrintable(scriptInfo.fileName()));
3226
3227 // Track as dependency for depfile
3228 if (!options.depFilePath.isEmpty())
3229 dependenciesForDepfile << script;
3230 }
3231 }
3232 } else {
3233 if (options.verbose)
3234 fprintf(stdout, " Skipping QML files (embedded in resources)\n");
3235 }
3236 }
3237
3238 // Scan QML plugin dependencies and copy any missing Qt libraries
3239 if (!qmlPluginsToScan.isEmpty()) {
3240 if (options.verbose)
3241 fprintf(stdout, "Scanning QML plugin dependencies\n");
3242
3243 QStringList toProcess = qmlPluginsToScan;
3244 while (!toProcess.isEmpty()) {
3245 QString pluginPath = toProcess.takeFirst();
3246
3247 if (options.verbose)
3248 fprintf(stdout, " Scanning plugin: %s\n", qPrintable(QFileInfo(pluginPath).fileName()));
3249
3250 QStringList deps = readElfDependencies(options, pluginPath);
3251 for (const QString &dep : deps) {
3252 // Skip system libraries
3253 if (isSystemLibrary(dep))
3254 continue;
3255
3256 // Resolve the library path from Qt libs or extra-libs-dirs
3257 QString depPath;
3258 if (dep.startsWith("libQt6"_L1)) {
3259 depPath = findQtLibrary(options, dep);
3260 if (depPath.isEmpty()) {
3261 if (options.verbose)
3262 fprintf(stdout, " Warning: Could not find Qt library: %s\n", qPrintable(dep));
3263 continue;
3264 }
3265 } else if (!options.extraLibsDirs.isEmpty()) {
3266 depPath = findExtraDepLibrary(options, dep);
3267 if (depPath.isEmpty())
3268 continue;
3269 } else {
3270 continue;
3271 }
3272
3273 if (processedLibs.contains(depPath))
3274 continue;
3275
3276 if (options.verbose)
3277 fprintf(stdout, " Found dependency: %s\n", qPrintable(dep));
3278
3279 // Copy the library
3280 for (const QString &arch : options.targetArchs) {
3281 QString destPath = options.outputDirectory + "/entry/libs/"_L1 + arch + "/"_L1 + dep;
3282 if (copyFileIfNewer(depPath, destPath, options.verbose)) {
3283 if (options.verbose)
3284 fprintf(stdout, " Copied %s to libs/%s\n", qPrintable(dep), qPrintable(arch));
3285
3286 // Track as dependency for depfile
3287 if (!options.depFilePath.isEmpty())
3288 dependenciesForDepfile << depPath;
3289 }
3290 }
3291
3292 processedLibs.insert(depPath);
3293 // Recursively scan this dependency
3294 toProcess.append(depPath);
3295 }
3296 }
3297 }
3298
3299 if (options.verbose)
3300 fprintf(stdout, "QML imports copied successfully\n");
3301
3302 return true;
3303}
3304
3305// Signing material resolved from the --signing-* flags and the matching
3306// QT_HARMONYOS_SIGNING_* environment variables.
3308{
3309 bool enabled = false;
3310 // hvigor-encrypted passwords are left to hvigor's sign task, the only one that
3311 // can decrypt them.
3320};
3321
3322// Signing is all-or-nothing: setting any input commits to signing, so a missing
3323// one is an error rather than a silently unsigned HAP.
3324static bool resolveSigningConfig(const Options &options, SigningConfig *signing)
3325{
3326 struct Field
3327 {
3328 const char *envName;
3329 const char *cliFlag;
3330 QString cliValue;
3331 QString envValue;
3332
3333 QString resolved() const
3334 {
3335 if (!cliValue.isEmpty())
3336 return cliValue;
3337 return envValue;
3338 }
3339 QString label() const
3340 {
3341 return QString::fromLatin1(cliFlag) + " / "_L1 + QString::fromLatin1(envName);
3342 }
3343 };
3344
3345 Field required[] = {
3346 { "QT_HARMONYOS_SIGNING_CERT_PATH", "--signing-cert-path", options.signingCertPath,
3347 qEnvironmentVariable("QT_HARMONYOS_SIGNING_CERT_PATH") },
3348 { "QT_HARMONYOS_SIGNING_PROFILE", "--signing-profile", options.signingProfile,
3349 qEnvironmentVariable("QT_HARMONYOS_SIGNING_PROFILE") },
3350 { "QT_HARMONYOS_SIGNING_STORE_FILE", "--signing-store-file", options.signingStoreFile,
3351 qEnvironmentVariable("QT_HARMONYOS_SIGNING_STORE_FILE") },
3352 { "QT_HARMONYOS_SIGNING_KEY_ALIAS", "--signing-key-alias", options.signingKeyAlias,
3353 qEnvironmentVariable("QT_HARMONYOS_SIGNING_KEY_ALIAS") },
3354 };
3355
3356 // Each password is required in exactly one of its two forms: encrypted, plain.
3357 Field passwords[][2] = {
3358 { { "QT_HARMONYOS_SIGNING_KEY_PASSWORD", "--signing-key-password",
3359 options.signingKeyPassword, qEnvironmentVariable("QT_HARMONYOS_SIGNING_KEY_PASSWORD") },
3360 { "QT_HARMONYOS_SIGNING_PLAIN_KEY_PASSWORD", "--signing-plain-key-password",
3361 options.signingPlainKeyPassword,
3362 qEnvironmentVariable("QT_HARMONYOS_SIGNING_PLAIN_KEY_PASSWORD") } },
3363 { { "QT_HARMONYOS_SIGNING_STORE_PASSWORD", "--signing-store-password",
3364 options.signingStorePassword,
3365 qEnvironmentVariable("QT_HARMONYOS_SIGNING_STORE_PASSWORD") },
3366 { "QT_HARMONYOS_SIGNING_PLAIN_STORE_PASSWORD", "--signing-plain-store-password",
3367 options.signingPlainStorePassword,
3368 qEnvironmentVariable("QT_HARMONYOS_SIGNING_PLAIN_STORE_PASSWORD") } },
3369 };
3370
3371 QString signAlg = options.signingAlg.isEmpty()
3372 ? qEnvironmentVariable("QT_HARMONYOS_SIGNING_ALG")
3373 : options.signingAlg;
3374
3375 bool anySet = !signAlg.isEmpty();
3376 for (const Field &f : required)
3377 anySet = anySet || !f.resolved().isEmpty();
3378 for (const auto &forms : passwords)
3379 anySet = anySet || !forms[0].resolved().isEmpty() || !forms[1].resolved().isEmpty();
3380 if (!anySet)
3381 return true;
3382
3383 QStringList missing;
3384 for (const Field &f : required) {
3385 if (f.resolved().isEmpty())
3386 missing << f.label();
3387 }
3388 for (const auto &forms : passwords) {
3389 if (forms[0].resolved().isEmpty() && forms[1].resolved().isEmpty())
3390 missing << forms[0].label() + " or "_L1 + forms[1].label();
3391 }
3392 if (!missing.isEmpty()) {
3393 fprintf(stderr, "Error: HAP signing requested, but the following required input(s)\n"
3394 " are missing (neither CLI flag nor env var was supplied):\n");
3395 for (const QString &name : missing)
3396 fprintf(stderr, " %s\n", qPrintable(name));
3397 return false;
3398 }
3399
3400 for (const auto &forms : passwords) {
3401 if (!forms[0].resolved().isEmpty() && !forms[1].resolved().isEmpty()) {
3402 fprintf(stderr, "Error: both %s and %s are set; pass only one of them\n",
3403 qPrintable(forms[0].label()), qPrintable(forms[1].label()));
3404 return false;
3405 }
3406 }
3407
3408 const bool encryptedKeyPassword = !passwords[0][0].resolved().isEmpty();
3409 const bool encryptedStorePassword = !passwords[1][0].resolved().isEmpty();
3410 if (encryptedKeyPassword != encryptedStorePassword) {
3411 fprintf(stderr,
3412 "Error: the key password and the keystore password must both be\n"
3413 " hvigor-encrypted or both plain text.\n");
3414 return false;
3415 }
3416
3417 signing->enabled = true;
3418 signing->encryptedPasswords = encryptedKeyPassword;
3419 signing->certPath = required[0].resolved();
3420 signing->profile = required[1].resolved();
3421 signing->storeFile = required[2].resolved();
3422 signing->keyAlias = required[3].resolved();
3423 signing->keyPassword = passwords[0][encryptedKeyPassword ? 0 : 1].resolved();
3424 signing->storePassword = passwords[1][encryptedStorePassword ? 0 : 1].resolved();
3425 signing->signAlg = signAlg.isEmpty() ? "SHA256withECDSA"_L1 : signAlg;
3426
3427 const std::pair<const char *, QString> files[] = {
3428 { required[0].cliFlag, signing->certPath },
3429 { required[1].cliFlag, signing->profile },
3430 { required[2].cliFlag, signing->storeFile },
3431 };
3432 for (const auto &file : files) {
3433 if (!QFile::exists(file.second)) {
3434 fprintf(stderr, "Error: signing input %s does not exist: %s\n", file.first,
3435 qPrintable(file.second));
3436 return false;
3437 }
3438 }
3439
3440 if (options.verbose) {
3441 fprintf(stdout, "HAP signing enabled\n");
3442 fprintf(stdout, " certpath: %s\n", qPrintable(signing->certPath));
3443 fprintf(stdout, " profile: %s\n", qPrintable(signing->profile));
3444 fprintf(stdout, " storeFile: %s\n", qPrintable(signing->storeFile));
3445 fprintf(stdout, " keyAlias: %s\n", qPrintable(signing->keyAlias));
3446 fprintf(stdout, " signAlg: %s\n", qPrintable(signing->signAlg));
3447 fprintf(stdout, " passwords: %s\n",
3448 signing->encryptedPasswords ? "hvigor-encrypted" : "plain text");
3449 }
3450 return true;
3451}
3452
3453// build-profile.json5 ships with `"signingConfigs": []`; replace that literal
3454// with a populated block, so that hvigor signs the HAP with encrypted passwords.
3455// JSON5 input (trailing commas, // comments) precludes QJsonDocument, hence
3456// string surgery.
3457static bool injectSigningConfig(const Options &options, const SigningConfig &signing)
3458{
3459 if (!signing.enabled || !signing.encryptedPasswords)
3460 return true;
3461
3462 const QString buildProfilePath = options.outputDirectory + "/build-profile.json5"_L1;
3463 QFile profileFile(buildProfilePath);
3464 if (!profileFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
3465 fprintf(stderr, "Error: cannot open %s for reading: %s\n",
3466 qPrintable(buildProfilePath), qPrintable(profileFile.errorString()));
3467 return false;
3468 }
3469 QByteArray content = profileFile.readAll();
3470 profileFile.close();
3471
3472 // Anything other than the literal empty array means the user already edited
3473 // the file; refuse rather than risk corrupting it.
3474 static const QByteArray needle = "\"signingConfigs\": []";
3475 const int idx = content.indexOf(needle);
3476 if (idx < 0) {
3477 fprintf(stderr, "Error: '%s' not found in %s. The template may have been modified;\n"
3478 " cannot inject signing configuration safely.\n",
3479 needle.constData(), qPrintable(buildProfilePath));
3480 return false;
3481 }
3482
3483 // Only backslash and double-quote need escaping; inputs are paths, aliases,
3484 // and hex blobs — no control characters.
3485 auto escapeJsonString = [](const QByteArray &in) {
3486 QByteArray out;
3487 out.reserve(in.size());
3488 for (char c : in) {
3489 if (c == '\\' || c == '"')
3490 out.append('\\');
3491 out.append(c);
3492 }
3493 return out;
3494 };
3495
3496 QByteArray replacement;
3497 replacement.append("\"signingConfigs\": [\n");
3498 replacement.append(" {\n");
3499 replacement.append(" \"name\": \"default\",\n");
3500 replacement.append(" \"type\": \"HarmonyOS\",\n");
3501 replacement.append(" \"material\": {\n");
3502 auto appendField = [&](const char *key, const QString &value, bool last) {
3503 replacement.append(" \"");
3504 replacement.append(key);
3505 replacement.append("\": \"");
3506 replacement.append(escapeJsonString(value.toUtf8()));
3507 replacement.append('"');
3508 if (!last)
3509 replacement.append(',');
3510 replacement.append('\n');
3511 };
3512 appendField("certpath", signing.certPath, false);
3513 appendField("keyAlias", signing.keyAlias, false);
3514 appendField("keyPassword", signing.keyPassword, false);
3515 appendField("profile", signing.profile, false);
3516 appendField("signAlg", signing.signAlg, false);
3517 appendField("storeFile", signing.storeFile, false);
3518 appendField("storePassword", signing.storePassword, true);
3519 replacement.append(" }\n");
3520 replacement.append(" }\n");
3521 replacement.append(" ]");
3522
3523 content.replace(idx, needle.size(), replacement);
3524
3525 if (!profileFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
3526 fprintf(stderr, "Error: cannot open %s for writing: %s\n",
3527 qPrintable(buildProfilePath), qPrintable(profileFile.errorString()));
3528 return false;
3529 }
3530 if (profileFile.write(content) != content.size()) {
3531 fprintf(stderr, "Error: failed to write full content to %s\n",
3532 qPrintable(buildProfilePath));
3533 profileFile.close();
3534 return false;
3535 }
3536 profileFile.close();
3537
3538 if (options.verbose)
3539 fprintf(stdout, "Injected HAP signingConfig into %s\n", qPrintable(buildProfilePath));
3540 return true;
3541}
3542
3544{
3545 const QString envJava = qEnvironmentVariable("QT_HARMONYOS_JAVA");
3546 if (!envJava.isEmpty())
3547 return envJava;
3548
3549 const QString javaHome = qEnvironmentVariable("JAVA_HOME");
3550 if (!javaHome.isEmpty()) {
3551 const QString fromHome =
3552 QStandardPaths::findExecutable("java"_L1, { javaHome + "/bin"_L1 });
3553 if (!fromHome.isEmpty())
3554 return fromHome;
3555 }
3556
3557 return QStandardPaths::findExecutable("java"_L1);
3558}
3559
3560// OHOS_SDK_ROOT normally points at the openharmony directory; accept the
3561// enclosing directories too.
3563{
3564 if (options.sdkRoot.isEmpty())
3565 return {};
3566 return { options.sdkRoot + "/toolchains"_L1,
3567 options.sdkRoot + "/openharmony/toolchains"_L1,
3568 options.sdkRoot + "/command-line-tools/sdk/default/openharmony/toolchains"_L1 };
3569}
3570
3571static QString findHapSignTool(const Options &options)
3572{
3573 const QString envTool = qEnvironmentVariable("QT_HARMONYOS_HAP_SIGN_TOOL");
3574 if (!envTool.isEmpty())
3575 return envTool;
3576
3577 for (const QString &dir : sdkToolchainsDirs(options)) {
3578 const QString candidate = dir + "/lib/hap-sign-tool.jar"_L1;
3579 if (QFile::exists(candidate))
3580 return candidate;
3581 }
3582 return QString();
3583}
3584
3585// hap-sign-tool falls back to API level 9 when -compatibleVersion is omitted,
3586// which understates what the manifest declares. Recover the real level from the
3587// generated build-profile.json5, where it is written as "6.1.0(23)".
3589{
3590 QFile profileFile(options.outputDirectory + "/build-profile.json5"_L1);
3591 if (!profileFile.open(QIODevice::ReadOnly | QIODevice::Text))
3592 return QString();
3593 const QString content = QString::fromUtf8(profileFile.readAll());
3594
3595 static const QRegularExpression keyRe("\"compatibleSdkVersion\"\\s*:\\s*([^,\\n}]+)"_L1);
3596 const QRegularExpressionMatch keyMatch = keyRe.match(content);
3597 if (!keyMatch.hasMatch())
3598 return QString();
3599
3600 QString value = keyMatch.captured(1).trimmed();
3601 static const QRegularExpression apiRe("\\‍((\\d+)\\‍)"_L1);
3602 const QRegularExpressionMatch apiMatch = apiRe.match(value);
3603 if (apiMatch.hasMatch())
3604 return apiMatch.captured(1);
3605
3606 value.remove(u'"');
3607 value = value.trimmed();
3608 bool ok = false;
3609 value.toInt(&ok);
3610 return ok ? value : QString();
3611}
3612
3613// Sign the HAP that hvigor produced, using the SDK's hap-sign-tool. With
3614// encrypted passwords hvigor has signed it already, and only its path changes.
3615//
3616// hvigor's own sign task runs both passwords through a decryptor keyed on the
3617// contents of DevEco Studio's material directory, so it rejects plain passwords.
3618// hap-sign-tool takes the passwords as given, which is the form material from
3619// AGC, a CI secret store or Qt Creator's keychain comes in. See QTBUG-149206.
3620static bool signHap(const Options &options, const SigningConfig &signing, QString *hapPath)
3621{
3622 if (!signing.enabled)
3623 return true;
3624 if (hapPath->isEmpty()) {
3625 fprintf(stderr, "Warning: HAP signing is configured, but no HAP was built to sign\n");
3626 return true;
3627 }
3628
3629 const QFileInfo unsignedInfo(*hapPath);
3630 QString baseName = unsignedInfo.completeBaseName();
3631 if (baseName.endsWith("-unsigned"_L1))
3632 baseName.chop(9);
3633 const QString signedPath = unsignedInfo.absolutePath() + "/"_L1 + baseName + "-signed.hap"_L1;
3634
3635 if (signing.encryptedPasswords) {
3636 if (!QFile::exists(signedPath)) {
3637 fprintf(stderr, "Error: hvigor did not produce the signed HAP %s\n",
3638 qPrintable(signedPath));
3639 return false;
3640 }
3641 *hapPath = signedPath;
3642 return true;
3643 }
3644
3645 const QString signTool = findHapSignTool(options);
3646 if (signTool.isEmpty()) {
3647 fprintf(stderr,
3648 "Error: hap-sign-tool.jar not found. Set QT_HARMONYOS_HAP_SIGN_TOOL\n"
3649 " to its path, or configure with OHOS_SDK_ROOT set to the SDK\n"
3650 " that contains it.\n");
3651 return false;
3652 }
3653
3654 const QString javaExecutable = findJavaExecutable();
3655 if (javaExecutable.isEmpty()) {
3656 fprintf(stderr,
3657 "Error: no java executable found for running hap-sign-tool.\n"
3658 " Set QT_HARMONYOS_JAVA or JAVA_HOME, or add java to PATH.\n");
3659 return false;
3660 }
3661
3662 // hap-sign-tool refuses to overwrite, and a leftover from an earlier build
3663 // would otherwise be mistaken for this build's output.
3664 if (QFile::exists(signedPath) && !QFile::remove(signedPath)) {
3665 fprintf(stderr, "Error: cannot remove stale %s\n", qPrintable(signedPath));
3666 return false;
3667 }
3668
3669 QStringList arguments;
3670 arguments << "-jar"_L1 << signTool << "sign-app"_L1
3671 << "-mode"_L1 << "localSign"_L1
3672 << "-signAlg"_L1 << signing.signAlg << "-signCode"_L1 << "1"_L1
3673 << "-keyAlias"_L1 << signing.keyAlias << "-keystoreFile"_L1 << signing.storeFile
3674 << "-appCertFile"_L1 << signing.certPath << "-profileFile"_L1 << signing.profile
3675 << "-inFile"_L1 << *hapPath << "-outFile"_L1 << signedPath;
3676
3677 const QString apiVersion = compatibleApiVersion(options);
3678 if (apiVersion.isEmpty()) {
3679 fprintf(stderr,
3680 "Warning: cannot determine compatibleSdkVersion from build-profile.json5;"
3681 " hap-sign-tool uses its default\n");
3682 } else {
3683 arguments << "-compatibleVersion"_L1 << apiVersion;
3684 }
3685
3686 if (options.verbose) {
3687 fprintf(stdout, "Signing HAP with %s\n", qPrintable(signTool));
3688 fprintf(stdout, " Running: %s %s -keyPwd <hidden> -keystorePwd <hidden>\n",
3689 qPrintable(javaExecutable), qPrintable(arguments.join(u' ')));
3690 }
3691
3692 // hap-sign-tool only reads the passwords from argv (-pwdInputMode 1 prompts
3693 // on a console, which a build step does not have), so they are visible in a
3694 // process listing for the duration of the call.
3695 arguments << "-keyPwd"_L1 << signing.keyPassword << "-keystorePwd"_L1 << signing.storePassword;
3696
3697 QProcessExt process;
3698 process.setProcessChannelMode(QProcess::MergedChannels);
3699 process.start(javaExecutable, arguments);
3700 if (!process.waitForStarted()) {
3701 fprintf(stderr, "Error: failed to start %s\n", qPrintable(javaExecutable));
3702 return false;
3703 }
3704 // The test bundle holds every Qt library, so code signing can take long.
3705 if (!process.waitForFinished(-1)) {
3706 fprintf(stderr, "Error: hap-sign-tool did not finish\n");
3707 process.kill();
3708 return false;
3709 }
3710 if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) {
3711 QFile::remove(signedPath);
3712 fprintf(stderr, "Error: hap-sign-tool failed with exit code %d\n", process.exitCode());
3713 return false;
3714 }
3715 if (!QFile::exists(signedPath)) {
3716 fprintf(stderr, "Error: hap-sign-tool reported success but %s was not created\n",
3717 qPrintable(signedPath));
3718 return false;
3719 }
3720
3721 if (options.verbose)
3722 fprintf(stdout, " Signed HAP: %s\n", qPrintable(signedPath));
3723
3724 *hapPath = signedPath;
3725 return true;
3726}
3727
3728static bool buildHap(const Options &options, QString *hapOutputPath = nullptr)
3729{
3730 if (!options.buildPackage) {
3731 if (options.verbose)
3732 fprintf(stdout, "Skipping HAP build (--no-build specified)\n");
3733 return true;
3734 }
3735
3736 // Resolve hvigorw path: CLI option → env var → auto-detect in output directory
3737 QString hvigorPath = options.hvigorPath;
3738
3739 if (hvigorPath.isEmpty()) {
3740 QByteArray envHvigor = qgetenv("QT_HARMONYOS_HVIGOR");
3741 if (!envHvigor.isEmpty())
3742 hvigorPath = QString::fromLocal8Bit(envHvigor);
3743 }
3744
3745 if (hvigorPath.isEmpty()) {
3746 // Auto-detect hvigorw in the output directory (always present in the template)
3747 QString candidate = options.outputDirectory + "/hvigorw"_L1;
3748 if (QFile::exists(candidate))
3749 hvigorPath = std::move(candidate);
3750 }
3751
3752 if (hvigorPath.isEmpty()) {
3753 fprintf(stderr, "Warning: No hvigor path specified, skipping build\n");
3754 fprintf(stderr, "Use --hvigor <path> or set QT_HARMONYOS_HVIGOR\n");
3755 return true; // Not fatal
3756 }
3757
3758 if (options.verbose)
3759 fprintf(stdout, "Building HarmonyOS HAP package\n");
3760
3761 // Check if hvigorw exists
3762 if (!QFile::exists(hvigorPath)) {
3763 fprintf(stderr, "Error: hvigorw not found at: %s\n", qPrintable(hvigorPath));
3764 return false;
3765 }
3766
3767 // Determine build task and build mode. hvigor's assembleHap builds in debug
3768 // mode unless the mode is passed explicitly.
3769 QString buildTask = "assembleHap"_L1;
3770 QString buildMode = options.releaseMode ? "release"_L1 : "debug"_L1;
3771
3772 if (options.verbose) {
3773 fprintf(stdout, " Build mode: %s\n", qPrintable(buildMode));
3774 fprintf(stdout, " Running: %s %s\n", qPrintable(hvigorPath), qPrintable(buildTask));
3775 }
3776
3777 // Execute hvigorw
3778 QProcessExt process;
3779 process.setWorkingDirectory(options.outputDirectory);
3780 process.setProcessChannelMode(QProcess::MergedChannels);
3781
3782 QStringList arguments;
3783 arguments << buildTask << "-p"_L1 << ("buildMode="_L1 + buildMode);
3784 // The hvigor daemon outlives the build and, on Windows, inherits our output
3785 // pipe; QProcess then never sees EOF and this call hangs. Build daemon-less.
3786 arguments << "--no-daemon"_L1;
3787
3788 process.start(hvigorPath, arguments);
3789
3790 if (!process.waitForStarted()) {
3791 fprintf(stderr, "Failed to start hvigorw\n");
3792 return false;
3793 }
3794
3795 // Show output in real-time if verbose
3796 while (process.state() != QProcess::NotRunning) {
3797 if (!process.waitForReadyRead(1000)) {
3798 // Timeout is OK, just check if process is still running
3799 if (process.state() == QProcess::NotRunning)
3800 break;
3801 continue;
3802 }
3803
3804 if (options.verbose) {
3805 QByteArray output = process.readAll();
3806 fprintf(stdout, "%s", output.constData());
3807 fflush(stdout);
3808 }
3809 }
3810
3811 // Read any remaining output
3812 if (options.verbose) {
3813 QByteArray output = process.readAll();
3814 if (!output.isEmpty()) {
3815 fprintf(stdout, "%s", output.constData());
3816 fflush(stdout);
3817 }
3818 }
3819
3820 if (process.exitCode() != 0) {
3821 fprintf(stderr, "hvigorw failed with exit code %d\n", process.exitCode());
3822 if (!options.verbose)
3823 fprintf(stderr, "Run with --verbose to see build output\n");
3824 return false;
3825 }
3826
3827 if (options.verbose)
3828 fprintf(stdout, "HAP build completed successfully\n");
3829
3830 // Try to locate the generated HAP file
3831 if (hapOutputPath) {
3832 QString hapSearchPath = options.outputDirectory + "/entry/build/default/outputs/default"_L1;
3833 QDir hapDir(hapSearchPath);
3834
3835 if (hapDir.exists()) {
3836 QStringList hapFiles = hapDir.entryList(QStringList() << "*.hap"_L1, QDir::Files);
3837 // A signed HAP from an earlier build sorts before the unsigned one
3838 // hvigor just wrote, so pick the unsigned artifact explicitly.
3839 for (qsizetype i = 0; i < hapFiles.size(); ++i) {
3840 if (hapFiles.at(i).endsWith("-unsigned.hap"_L1)) {
3841 hapFiles.move(i, 0);
3842 break;
3843 }
3844 }
3845 if (!hapFiles.isEmpty()) {
3846 *hapOutputPath = hapDir.absoluteFilePath(hapFiles.first());
3847 if (options.verbose)
3848 fprintf(stdout, " Generated HAP: %s\n", qPrintable(*hapOutputPath));
3849 }
3850 }
3851 }
3852
3853 return true;
3854}
3855
3856// Returns the mainElement of the generated module.json5, which is the ability to launch.
3857static QString mainAbilityName(const Options &options)
3858{
3859 QFile moduleFile(options.outputDirectory + "/entry/src/main/module.json5"_L1);
3860 if (moduleFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
3861 static const QRegularExpression re("\"mainElement\"\\s*:\\s*\"([^\"]+)\""_L1);
3862 const QRegularExpressionMatch match = re.match(QString::fromUtf8(moduleFile.readAll()));
3863 if (match.hasMatch())
3864 return match.captured(1);
3865 }
3866 return "QAbility"_L1;
3867}
3868
3869static bool installToDevice(const Options &options, const QString &builtHapPath)
3870{
3871 if (!options.installApk)
3872 return true; // Not requested
3873
3874 if (builtHapPath.isEmpty()) {
3875 fprintf(stderr, "Error: Cannot install - HAP file path not found\n");
3876 return false;
3877 }
3878
3879 // When hvigor signed the HAP with a configuration from build-profile.json5, the
3880 // signed artifact sits next to the unsigned one that buildHap() reports.
3881 QString hapPath = builtHapPath;
3882 if (hapPath.endsWith("-unsigned.hap"_L1)) {
3883 QString signedPath = hapPath;
3884 signedPath.replace(signedPath.size() - 13, 13, "-signed.hap"_L1);
3885 const QFileInfo signedInfo(signedPath);
3886 if (signedInfo.exists()
3887 && signedInfo.lastModified() >= QFileInfo(hapPath).lastModified()) {
3888 hapPath = signedPath;
3889 }
3890 }
3891
3892 if (options.verbose)
3893 fprintf(stdout, "Installing HAP to device\n");
3894
3895 QString hdcPath = qEnvironmentVariable("QT_HARMONYOS_HDC");
3896 if (hdcPath.isEmpty())
3897 hdcPath = QStandardPaths::findExecutable("hdc"_L1, sdkToolchainsDirs(options));
3898 if (hdcPath.isEmpty())
3899 hdcPath = "hdc"_L1;
3900
3901 // Plain QProcess: QProcessExt consumes the output that is parsed here.
3902 QProcess checkDevices;
3903 checkDevices.start(hdcPath, QStringList() << "list"_L1 << "targets"_L1);
3904 if (!checkDevices.waitForFinished(5000)) {
3905 fprintf(stderr, "Error: Failed to check for connected devices with %s\n",
3906 qPrintable(hdcPath));
3907 return false;
3908 }
3909
3910 // hdc exits with 0 on errors and reports them with a "[Fail]" prefix.
3911 QString devicesOutput = QString::fromUtf8(checkDevices.readAllStandardOutput());
3912 if (devicesOutput.contains("[Fail]"_L1)) {
3913 fprintf(stderr, "Error: Failed to list devices:\n%s\n", qPrintable(devicesOutput));
3914 return false;
3915 }
3916 if (devicesOutput.trimmed().isEmpty()
3917 || devicesOutput.contains("[Empty]"_L1, Qt::CaseInsensitive)) {
3918 fprintf(stderr, "Error: No HarmonyOS devices connected\n");
3919 fprintf(stderr, "Connect a device and ensure USB debugging is enabled\n");
3920 return false;
3921 }
3922
3923 if (options.verbose)
3924 fprintf(stdout, " Connected devices:\n%s\n", qPrintable(devicesOutput));
3925
3926 // Uninstall old version if exists
3927 if (options.verbose)
3928 fprintf(stdout, " Uninstalling old version (if exists)\n");
3929
3930 QProcessExt uninstall;
3931 uninstall.start(hdcPath, QStringList() << "uninstall"_L1 << options.harmonyOsAppBundleName);
3932 uninstall.waitForFinished(10000);
3933 // Don't check result - it's OK if app wasn't installed
3934
3935 // Install new HAP
3936 if (options.verbose)
3937 fprintf(stdout, " Installing: %s\n", qPrintable(hapPath));
3938
3939 QProcess install;
3940 install.setProcessChannelMode(QProcess::MergedChannels);
3941 // hdc on Windows takes a path with forward slashes as relative.
3942 install.start(hdcPath, QStringList() << "install"_L1 << QDir::toNativeSeparators(hapPath));
3943
3944 if (!install.waitForFinished(60000)) { // 60 second timeout
3945 fprintf(stderr, "Error: Installation timed out\n");
3946 return false;
3947 }
3948
3949 QString installOutput = QString::fromUtf8(install.readAll());
3950
3951 if (install.exitCode() != 0 || installOutput.contains("[Fail]"_L1)
3952 || installOutput.contains("failed to install"_L1)) {
3953 fprintf(stderr, "Error: Installation failed\n");
3954 fprintf(stderr, "%s\n", qPrintable(installOutput));
3955 return false;
3956 }
3957
3958 if (options.verbose)
3959 fprintf(stdout, " Installation output:\n%s\n", qPrintable(installOutput));
3960
3961 // Launch the app
3962 if (options.verbose)
3963 fprintf(stdout, " Launching application\n");
3964
3965 QProcess launch;
3966 launch.setProcessChannelMode(QProcess::MergedChannels);
3967 QStringList launchArgs;
3968 launchArgs << "shell"_L1 << "aa"_L1 << "start"_L1
3969 << "-a"_L1 << mainAbilityName(options)
3970 << "-b"_L1 << options.harmonyOsAppBundleName;
3971
3972 launch.start(hdcPath, launchArgs);
3973 launch.waitForFinished(5000);
3974
3975 const QString launchOutput = QString::fromUtf8(launch.readAll());
3976 if (launch.exitCode() != 0 || launchOutput.contains("[Fail]"_L1)
3977 || launchOutput.contains("error:"_L1)) {
3978 // Not fatal
3979 fprintf(stderr, "Warning: Failed to launch application:\n%s\n", qPrintable(launchOutput));
3980 fprintf(stdout, "Successfully installed application on device\n");
3981 return true;
3982 }
3983
3984 fprintf(stdout, "Successfully installed and launched application on device\n");
3985
3986 return true;
3987}
3988
3989int main(int argc, char *argv[])
3990{
3991 QCoreApplication app(argc, argv);
3992 QCoreApplication::setApplicationName("harmonydeployqt"_L1);
3993 QCoreApplication::setApplicationVersion("1.0"_L1);
3994
3995 Options options;
3996 options.timer.start();
3997
3998 if (!parseCommandLine(app.arguments(), &options))
3999 return 1;
4000
4001 if (options.verbose) {
4002 fprintf(stdout, "Qt HarmonyOS Deployment Tool\n");
4003 fprintf(stdout, "==============================\n\n");
4004 }
4005
4006 if (!readInputConfiguration(&options))
4007 return 1;
4008
4009 // Resolve before anything is generated: bad signing input should not cost a
4010 // full HAP build to report.
4011 SigningConfig signing;
4012 if (!resolveSigningConfig(options, &signing))
4013 return 1;
4014
4015 const QList<TestQmlModule> testQmlModules =
4016 options.testBundleMode ? findTestQmlModules(options) : QList<TestQmlModule>{};
4017
4018 if (options.testBundleMode && !verifyUniqueTestQmlModuleDeployDirs(testQmlModules))
4019 return 1;
4020
4021 if (options.testBundleMode && !verifyUniqueTestRawfilePaths(options.testRawfiles))
4022 return 1;
4023
4024 if (options.verbose)
4025 fprintf(stdout, "\nDeployment process started...\n");
4026
4027 QString hapOutputPath;
4028
4029 // Phase 1: Copy template
4030 if (!copyTemplate(options, !signing.enabled)) {
4031 fprintf(stderr, "Failed to copy template\n");
4032 return 1;
4033 }
4034
4035 // Phase 2: Customize template (in test bundle mode, APP_LIBRARY_NAME uses a placeholder)
4036 if (!customizeTemplate(options)) {
4037 fprintf(stderr, "Failed to customize template\n");
4038 return 1;
4039 }
4040
4041 // Phase 3: Copy libraries / dependencies (mode-specific)
4042 QStringList bundledBinaries; // populated only in test bundle mode
4043 if (options.testBundleMode) {
4044 if (!copyTestBinaries(options, bundledBinaries)) {
4045 fprintf(stderr, "Failed to copy test binaries\n");
4046 return 1;
4047 }
4048 if (!copyAllQtLibs(options)) {
4049 fprintf(stderr, "Failed to copy Qt libraries\n");
4050 return 1;
4051 }
4052 if (!copyAllQtPlugins(options)) {
4053 fprintf(stderr, "Failed to copy Qt plugins\n");
4054 return 1;
4055 }
4056 if (!copyAllQmlModules(options)) {
4057 fprintf(stderr, "Failed to copy QML modules\n");
4058 return 1;
4059 }
4060 if (!copyTestQmlModules(testQmlModules, options)) {
4061 fprintf(stderr, "Failed to copy test QML modules\n");
4062 return 1;
4063 }
4064 if (!copyTestRawfiles(options)) {
4065 fprintf(stderr, "Failed to copy test rawfiles\n");
4066 return 1;
4067 }
4068 } else {
4069 if (!copyApplicationBinary(options)) {
4070 fprintf(stderr, "Failed to copy application binary\n");
4071 return 1;
4072 }
4073 if (!copyProjectLibraries(options)) {
4074 fprintf(stderr, "Failed to copy project libraries\n");
4075 return 1;
4076 }
4077 QSet<QString> processedLibs;
4078 if (!detectAndCopyDependencies(options, processedLibs)) {
4079 fprintf(stderr, "Failed to detect and copy dependencies\n");
4080 return 1;
4081 }
4082 bool qmlScanOk = true;
4083 QList<QmlImportInfo> qmlImports = scanQmlImports(options, &qmlScanOk);
4084 if (!qmlScanOk) {
4085 fprintf(stderr, "Failed to scan QML imports\n");
4086 return 1;
4087 }
4088 if (!copyQmlFiles(options)) {
4089 fprintf(stderr, "Failed to copy QML files\n");
4090 return 1;
4091 }
4092 if (!copyQmlImports(options, qmlImports, processedLibs)) {
4093 fprintf(stderr, "Failed to copy QML imports\n");
4094 return 1;
4095 }
4096 if (!copyPlugins(options, processedLibs)) {
4097 fprintf(stderr, "Failed to copy plugins\n");
4098 return 1;
4099 }
4100 }
4101
4102 if (!copyExtraPlugins(options)) {
4103 fprintf(stderr, "Failed to copy extra plugins\n");
4104 return 1;
4105 }
4106
4107 if (!injectSigningConfig(options, signing)) {
4108 fprintf(stderr, "Failed to inject signing configuration\n");
4109 return 1;
4110 }
4111
4112 // Phase 4: Build HAP package
4113 if (!buildHap(options, &hapOutputPath)) {
4114 fprintf(stderr, "Failed to build HAP\n");
4115 return 1;
4116 }
4117
4118 if (!signHap(options, signing, &hapOutputPath)) {
4119 fprintf(stderr, "Failed to sign HAP\n");
4120 return 1;
4121 }
4122
4123 // Phase 5: Test bundle finalization
4124 if (options.testBundleMode) {
4125 if (!writeTestBinariesList(options, bundledBinaries)) {
4126 fprintf(stderr, "Failed to write binaries.txt\n");
4127 return 1;
4128 }
4129 }
4130
4131 // hvigor writes the unsigned HAP whether or not it also signs, so that is the
4132 // OUTPUT of the CMake custom command.
4133 if (!options.depFilePath.isEmpty()) {
4134 const QString unsignedHapPath = options.outputDirectory
4135 + "/entry/build/default/outputs/default/entry-default-unsigned.hap"_L1;
4136 if (!writeDepfile(options, unsignedHapPath))
4137 fprintf(stderr, "Warning: Failed to write dependency file\n");
4138 }
4139
4140 // Phase 6: Install to device (standard mode only)
4141 if (!options.testBundleMode) {
4142 if (!installToDevice(options, hapOutputPath)) {
4143 fprintf(stderr, "Failed to install to device\n");
4144 return 1;
4145 }
4146 }
4147
4148 fprintf(stdout, "\n==============================================\n");
4149 fprintf(stdout, "Deployment completed successfully!\n");
4150 fprintf(stdout, "==============================================\n");
4151 fprintf(stdout, "Project location: %s\n", qPrintable(options.outputDirectory));
4152
4153 if (!hapOutputPath.isEmpty())
4154 fprintf(stdout, "HAP package: %s\n", qPrintable(hapOutputPath));
4155
4156 if (options.verbose)
4157 fprintf(stdout, "\nTotal time: %lld ms\n", options.timer.elapsed());
4158
4159 return 0;
4160}
QProcessExt()
Definition main.cpp:166
static QStringList dependenciesForDepfile
Definition main.cpp:49
static bool copyRecursively(const QString &sourceDir, const QString &destDir, bool verbose, const QString &topDest={})
Definition main.cpp:658
static bool verifyUniqueTestRawfilePaths(const QList< TestRawfile > &rawfiles)
Definition main.cpp:2227
static bool customizeTemplate(const Options &options)
Definition main.cpp:902
static bool readInputConfiguration(Options *options)
Definition main.cpp:300
static bool writeDepfile(const Options &options, const QString &hapOutputPath)
Definition main.cpp:617
static bool copyTestRawfiles(const Options &options)
Definition main.cpp:2260
static bool writeTestBinariesList(const Options &options, const QStringList &bundledBinaries)
Definition main.cpp:1657
static bool installToDevice(const Options &options, const QString &builtHapPath)
Definition main.cpp:3869
static bool getTestQmlModuleDeployDir(const TestQmlModule &testModule, QString &deployDir)
Definition main.cpp:2058
static QString json5ArrayValue(const QString &content, QLatin1StringView key)
Definition main.cpp:705
static bool copyFileIfNewer(const QString &sourceFileName, const QString &destinationFileName, bool verbose, bool forceOverwrite=false)
Definition main.cpp:571
static QString findJavaExecutable()
Definition main.cpp:3543
static void scanTestBinariesDir(const QString &dirPath, const QStringList &excludeList, const QStringList &excludeDirs, QStringList &found, QStringList &foundHelpers, QSet< QString > &helperNames)
Definition main.cpp:1526
static QString findNearestEnclosingTestDir(const QString &startDir, const QSet< QString > &testDirs)
Definition main.cpp:2039
static QString sdkVersion(const QString &sdkRoot)
Definition main.cpp:278
static bool buildHap(const Options &options, QString *hapOutputPath=nullptr)
Definition main.cpp:3728
static bool copyApplicationBinary(const Options &options)
Definition main.cpp:1368
static bool readQmldirLines(const QString &qmldirPath, QStringList &lines)
Definition main.cpp:1966
static QList< TestQmlModule > findTestQmlModules(const Options &options)
Definition main.cpp:2074
static QList< TestRawfileEntry > listTestRawfileEntries(const TestRawfile &rawfile)
Definition main.cpp:2197
static QString jsonStringEscape(const QString &s)
Definition main.cpp:865
static bool copyTestBinaries(const Options &options, QStringList &bundledBinaries)
Definition main.cpp:1568
static QString findQtPluginsDirectory(const Options &options)
Definition main.cpp:2599
static QString findHapSignTool(const Options &options)
Definition main.cpp:3571
static bool copyAllQtLibs(const Options &options)
Definition main.cpp:1687
static QStringList readElfDependencies(const Options &options, const QString &binaryPath)
Definition main.cpp:2333
static bool copyFileToArchitectures(const Options &options, const QString &sourcePath, const QString &relativeDestPath, bool trackInDepfile=true)
Definition main.cpp:1420
static bool getQmldirModuleUri(const QString &qmldirPath, QString &uri)
Definition main.cpp:2019
static bool copyQmlImports(const Options &options, const QList< QmlImportInfo > &imports, QSet< QString > &processedLibs)
Definition main.cpp:3080
static bool reasonNeedsPromotion(const QString &reason)
Definition main.cpp:842
static bool parseCommandLine(const QStringList &arguments, Options *options)
Definition main.cpp:180
static bool resolveSigningConfig(const Options &options, SigningConfig *signing)
Definition main.cpp:3324
static QStringList sdkToolchainsDirs(const Options &options)
Definition main.cpp:3562
static QString findStdCppLibrary(const Options &options, const QString &arch)
Definition main.cpp:1448
static bool copyTestQmlModules(const QList< TestQmlModule > &modules, const Options &options)
Definition main.cpp:2169
static bool signHap(const Options &options, const SigningConfig &signing, QString *hapPath)
Definition main.cpp:3620
static void printHelp()
Definition main.cpp:126
static bool copyExtraPlugins(const Options &options)
Definition main.cpp:1848
static QString mainAbilityName(const Options &options)
Definition main.cpp:3857
static bool copyPlugins(const Options &options, QSet< QString > &processedLibs)
Definition main.cpp:2717
static QString findQtLibrary(const Options &options, const QString &libName)
Definition main.cpp:2423
static QList< TestRawfileEntry > listDestinationDirectories(const TestRawfile &rawfile)
Definition main.cpp:2214
static bool copyQmlFiles(const Options &options)
Definition main.cpp:3042
static bool copyAllQtPlugins(const Options &options)
Definition main.cpp:1765
static bool copyTemplate(const Options &options, bool keepSigningConfigs)
Definition main.cpp:733
static bool copyAllQmlModules(const Options &options)
Definition main.cpp:1925
static QString findLlvmReadobj(const Options &options)
Definition main.cpp:2285
static bool injectSigningConfig(const Options &options, const SigningConfig &signing)
Definition main.cpp:3457
static bool copyTestQmlModuleFiles(const QString &moduleSrcDirPath, const QString &destModuleDirPath, const Options &options)
Definition main.cpp:2134
static QString synthesizePermissionReasonId(const QString &permissionName)
Definition main.cpp:854
static bool isValidHarmonyOsAbilityOrientation(const QString &value)
Definition main.cpp:875
static QString hapQmlDir(const Options &options)
Definition main.cpp:1920
static bool verifyUniqueTestQmlModuleDeployDirs(const QList< TestQmlModule > &modules)
Definition main.cpp:2111
static bool copyPlatformPlugin(const Options &options, const QString &qtPluginsPath, QSet< QString > &processedLibs)
Definition main.cpp:2627
static QString compatibleApiVersion(const Options &options)
Definition main.cpp:3588
static bool detectAndCopyDependencies(const Options &options, QSet< QString > &processedLibs)
Definition main.cpp:2457
static bool copyProjectLibraries(const Options &options)
Definition main.cpp:1479
static QString readElfSoname(const Options &options, const QString &binaryPath)
Definition main.cpp:2309
static bool isSystemLibrary(const QString &libName)
Definition main.cpp:2410
static bool copyQmldirPlugins(const QString &qmldirPath, const Options &options)
Definition main.cpp:1981
static QStringList listDirectoryTree(const QString &root)
Definition main.cpp:2186
static QList< QmlImportInfo > scanQmlImports(const Options &options, bool *ok=nullptr)
Definition main.cpp:2819
static QString findExtraDepLibrary(const Options &options, const QString &libName)
Definition main.cpp:2390
static bool copyQmlDir(const QString &srcDir, const QString &relPath, const QString &qmlDestBase, const Options &options)
Definition main.cpp:1884
int main(int argc, char *argv[])
[ctor_close]
QString signingCertPath
Definition main.cpp:113
bool installApk
Definition main.cpp:224
QString harmonyOsTargetSdkVersion
Definition main.cpp:94
QString harmonyOsAppVendor
Definition main.cpp:84
bool releaseMode
Definition main.cpp:71
QString testBinariesDirectory
Definition main.cpp:108
QStringList permissions
Definition main.cpp:65
QString signingPlainStorePassword
Definition main.cpp:120
QString harmonyOsAppBundleName
Definition main.cpp:54
QString sdkRoot
Definition main.cpp:55
QString signingAlg
Definition main.cpp:121
QString inputFile
Definition main.cpp:47
QStringList targetArchs
Definition main.cpp:60
QStringList qmlImportPaths
Definition main.cpp:169
QStringList qmlRootPaths
Definition main.cpp:57
QString harmonyOsModuleDescription
Definition main.cpp:102
QString qtHostDirectory
Definition main.cpp:154
QString qtLibExecsDirectory
Definition main.cpp:151
QStringList projectLibraries
Definition main.cpp:51
int harmonyOsAppVersionCode
Definition main.cpp:85
QString depFilePath
Definition main.cpp:167
bool testBundleMode
Definition main.cpp:107
QString qtLibsDirectory
Definition main.cpp:150
QStringList testExcludeList
Definition main.cpp:109
QString harmonyOsPackageSourceDirectory
Definition main.cpp:52
QString harmonyOsAppLabel
Definition main.cpp:87
QStringList harmonyOsModuleDeviceTypes
Definition main.cpp:103
QStringList extraLibsDirs
Definition main.cpp:68
QString harmonyOsCompatibleSdkVersion
Definition main.cpp:93
QString signingProfile
Definition main.cpp:114
QString hvigorPath
Definition main.cpp:49
QString signingKeyAlias
Definition main.cpp:116
QStringList pluginsImportPaths
Definition main.cpp:59
bool verbose
Definition main.cpp:130
QStringList extraPlugins
Definition main.cpp:200
QString signingKeyPassword
Definition main.cpp:117
QString harmonyOsAppVersionName
Definition main.cpp:86
QString depFileBase
Definition main.cpp:76
QString qtPluginsDirectory
Definition main.cpp:152
QString harmonyOsAbilityOrientation
Definition main.cpp:104
QString qtQmlDirectory
Definition main.cpp:153
QString outputDirectory
Definition main.cpp:161
QString applicationBinary
Definition main.cpp:163
QString harmonyOsAppName
Definition main.cpp:53
QString signingStorePassword
Definition main.cpp:118
QString harmonyOsCompileSdkVersion
Definition main.cpp:95
QList< TestRawfile > testRawfiles
Definition main.cpp:110
QString harmonyOsAppIcon
Definition main.cpp:88
QString signingStoreFile
Definition main.cpp:115
QString signingPlainKeyPassword
Definition main.cpp:119
QElapsedTimer timer
Definition main.cpp:136
bool buildPackage
Definition main.cpp:73
QString ndkRoot
Definition main.cpp:56
QString value
Definition main.cpp:899
QString id
Definition main.cpp:898
bool pluginIsOptional
Definition main.cpp:2813
QString path
Definition main.cpp:2810
QString prefer
Definition main.cpp:2814
QString plugin
Definition main.cpp:2812
QString name
Definition main.cpp:2809
QStringList scripts
Definition main.cpp:2816
QStringList components
Definition main.cpp:2815
QString type
Definition main.cpp:2811
QString absolutePath
Definition main.cpp:73
QString relativePath
Definition main.cpp:72
QString storePassword
Definition main.cpp:3318
QString certPath
Definition main.cpp:3313
QString keyAlias
Definition main.cpp:3316
bool encryptedPasswords
Definition main.cpp:3312
QString profile
Definition main.cpp:3314
QString keyPassword
Definition main.cpp:3317
QString signAlg
Definition main.cpp:3319
QString storeFile
Definition main.cpp:3315
QString qmldirPath
Definition main.cpp:2054
QString testDir
Definition main.cpp:2055
QString sourcePath
Definition main.cpp:41
bool isDirectory
Definition main.cpp:42
QString rawfilePath
Definition main.cpp:40
QString source
Definition main.cpp:34
QString destination
Definition main.cpp:35