-
Notifications
You must be signed in to change notification settings - Fork 428
/
Copy pathshared.cpp
1732 lines (1503 loc) · 71.5 KB
/
shared.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd. and Simon Peter
** Contact: https://www.qt.io/licensing/
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QCoreApplication>
#include <QString>
#include <QStringList>
#include <QDebug>
#include <iostream>
#include <QProcess>
#include <QDir>
#include <QRegExp>
#include <QSet>
#include <QStack>
#include <QDirIterator>
#include <QLibraryInfo>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QRegularExpression>
#include <QStandardPaths>
#include "shared.h"
QString appBinaryPath;
bool runStripEnabled = true;
bool bundleAllButCoreLibs = false;
bool fhsLikeMode = false;
QString fhsPrefix;
bool alwaysOwerwriteEnabled = false;
QStringList librarySearchPath;
bool appstoreCompliant = false;
int logLevel = 1;
int qtDetected = 0;
bool qtDetectionComplete = 0; // As long as Qt is not detected yet, ldd may encounter "not found" messages, continue anyway
bool deployLibrary = false;
using std::cout;
using std::endl;
QMap<QString,QString> qtToBeBundledInfo;
enum QtModule
#if defined(Q_COMPILER_CLASS_ENUM) || defined(Q_CC_MSVC)
: quint64
#endif
{
QtBluetoothModule = 0x0000000000000001,
QtCLuceneModule = 0x0000000000000002,
QtConcurrentModule = 0x0000000000000004,
QtCoreModule = 0x0000000000000008,
QtDeclarativeModule = 0x0000000000000010,
QtDesignerComponents = 0x0000000000000020,
QtDesignerModule = 0x0000000000000040,
QtGuiModule = 0x0000000000000080,
QtCluceneModule = 0x0000000000000100,
QtHelpModule = 0x0000000000000200,
QtMultimediaModule = 0x0000000000000400,
QtMultimediaWidgetsModule = 0x0000000000000800,
QtMultimediaQuickModule = 0x0000000000001000,
QtNetworkModule = 0x0000000000002000,
QtNfcModule = 0x0000000000004000,
QtOpenGLModule = 0x0000000000008000,
QtPositioningModule = 0x0000000000010000,
QtPrintSupportModule = 0x0000000000020000,
QtQmlModule = 0x0000000000040000,
QtQuickModule = 0x0000000000080000,
QtQuickParticlesModule = 0x0000000000100000,
QtScriptModule = 0x0000000000200000,
QtScriptToolsModule = 0x0000000000400000,
QtSensorsModule = 0x0000000000800000,
QtSerialPortModule = 0x0000000001000000,
QtSqlModule = 0x0000000002000000,
QtSvgModule = 0x0000000004000000,
QtTestModule = 0x0000000008000000,
QtWidgetsModule = 0x0000000010000000,
QtWinExtrasModule = 0x0000000020000000,
QtXmlModule = 0x0000000040000000,
QtXmlPatternsModule = 0x0000000080000000,
QtWebKitModule = 0x0000000100000000,
QtWebKitWidgetsModule = 0x0000000200000000,
QtQuickWidgetsModule = 0x0000000400000000,
QtWebSocketsModule = 0x0000000800000000,
QtEnginioModule = 0x0000001000000000,
QtWebEngineCoreModule = 0x0000002000000000,
QtWebEngineModule = 0x0000004000000000,
QtWebEngineWidgetsModule = 0x0000008000000000,
QtQmlToolingModule = 0x0000010000000000,
Qt3DCoreModule = 0x0000020000000000,
Qt3DRendererModule = 0x0000040000000000,
Qt3DQuickModule = 0x0000080000000000,
Qt3DQuickRendererModule = 0x0000100000000000,
Qt3DInputModule = 0x0000200000000000,
QtLocationModule = 0x0000400000000000,
QtWebChannelModule = 0x0000800000000000,
QtTextToSpeechModule = 0x0001000000000000,
QtSerialBusModule = 0x0002000000000000
};
struct QtModuleEntry {
quint64 module;
const char *option;
const char *libraryName;
const char *translation;
};
static QtModuleEntry qtModuleEntries[] = {
{ QtBluetoothModule, "bluetooth", "Qt5Bluetooth", 0 },
{ QtCLuceneModule, "clucene", "Qt5CLucene", "qt_help" },
{ QtConcurrentModule, "concurrent", "Qt5Concurrent", "qtbase" },
{ QtCoreModule, "core", "Qt5Core", "qtbase" },
{ QtDeclarativeModule, "declarative", "Qt5Declarative", "qtquick1" },
{ QtDesignerModule, "designer", "Qt5Designer", 0 },
{ QtDesignerComponents, "designercomponents", "Qt5DesignerComponents", 0 },
{ QtEnginioModule, "enginio", "Enginio", 0 },
{ QtGuiModule, "gui", "Qt5Gui", "qtbase" },
{ QtHelpModule, "qthelp", "Qt5Help", "qt_help" },
{ QtMultimediaModule, "multimedia", "Qt5Multimedia", "qtmultimedia" },
{ QtMultimediaWidgetsModule, "multimediawidgets", "Qt5MultimediaWidgets", "qtmultimedia" },
{ QtMultimediaQuickModule, "multimediaquick", "Qt5MultimediaQuick_p", "qtmultimedia" },
{ QtNetworkModule, "network", "Qt5Network", "qtbase" },
{ QtNfcModule, "nfc", "Qt5Nfc", 0 },
{ QtOpenGLModule, "opengl", "Qt5OpenGL", 0 },
{ QtPositioningModule, "positioning", "Qt5Positioning", 0 },
{ QtPrintSupportModule, "printsupport", "Qt5PrintSupport", 0 },
{ QtQmlModule, "qml", "Qt5Qml", "qtdeclarative" },
{ QtQmlToolingModule, "qmltooling", "qmltooling", 0 },
{ QtQuickModule, "quick", "Qt5Quick", "qtdeclarative" },
{ QtQuickParticlesModule, "quickparticles", "Qt5QuickParticles", 0 },
{ QtQuickWidgetsModule, "quickwidgets", "Qt5QuickWidgets", 0 },
{ QtScriptModule, "script", "Qt5Script", "qtscript" },
{ QtScriptToolsModule, "scripttools", "Qt5ScriptTools", "qtscript" },
{ QtSensorsModule, "sensors", "Qt5Sensors", 0 },
{ QtSerialPortModule, "serialport", "Qt5SerialPort", "qtserialport" },
{ QtSqlModule, "sql", "Qt5Sql", "qtbase" },
{ QtSvgModule, "svg", "Qt5Svg", 0 },
{ QtTestModule, "test", "Qt5Test", "qtbase" },
{ QtWebKitModule, "webkit", "Qt5WebKit", 0 },
{ QtWebKitWidgetsModule, "webkitwidgets", "Qt5WebKitWidgets", 0 },
{ QtWebSocketsModule, "websockets", "Qt5WebSockets", "qtwebsockets" },
{ QtWidgetsModule, "widgets", "Qt5Widgets", "qtbase" },
{ QtWinExtrasModule, "winextras", "Qt5WinExtras", 0 },
{ QtXmlModule, "xml", "Qt5Xml", "qtbase" },
{ QtXmlPatternsModule, "xmlpatterns", "Qt5XmlPatterns", "qtxmlpatterns" },
{ QtWebEngineCoreModule, "webenginecore", "Qt5WebEngineCore", 0 },
{ QtWebEngineModule, "webengine", "Qt5WebEngine", "qtwebengine" },
{ QtWebEngineWidgetsModule, "webenginewidgets", "Qt5WebEngineWidgets", 0 },
{ Qt3DCoreModule, "3dcore", "Qt53DCore", 0 },
{ Qt3DRendererModule, "3drenderer", "Qt53DRenderer", 0 },
{ Qt3DQuickModule, "3dquick", "Qt53DQuick", 0 },
{ Qt3DQuickRendererModule, "3dquickrenderer", "Qt53DQuickRenderer", 0 },
{ Qt3DInputModule, "3dinput", "Qt53DInput", 0 },
{ QtLocationModule, "geoservices", "Qt5Location", 0 },
{ QtWebChannelModule, "webchannel", "Qt5WebChannel", 0 },
{ QtTextToSpeechModule, "texttospeech", "Qt5TextToSpeech", 0 },
{ QtSerialBusModule, "serialbus", "Qt5SerialBus", 0 }
};
bool operator==(const LibraryInfo &a, const LibraryInfo &b)
{
return ((a.libraryPath == b.libraryPath) && (a.binaryPath == b.binaryPath));
}
QDebug operator<<(QDebug debug, const LibraryInfo &info)
{
debug << "Library name" << info.libraryName << "\n";
debug << "Library directory" << info.libraryDirectory << "\n";
debug << "Library path" << info.libraryPath << "\n";
debug << "Binary directory" << info.binaryDirectory << "\n";
debug << "Binary name" << info.binaryName << "\n";
debug << "Binary path" << info.binaryPath << "\n";
debug << "Version" << info.version << "\n";
debug << "Install name" << info.installName << "\n";
debug << "Deployed install name" << info.deployedInstallName << "\n";
debug << "Source file Path" << info.sourceFilePath << "\n";
debug << "Library Destination Directory (relative to bundle)" << info.libraryDestinationDirectory << "\n";
debug << "Binary Destination Directory (relative to bundle)" << info.binaryDestinationDirectory << "\n";
return debug;
}
QString bundleLibraryDirectory;
inline QDebug operator<<(QDebug debug, const AppDirInfo &info)
{
debug << "Application bundle path" << info.path << "\n";
debug << "Binary path" << info.binaryPath << "\n";
debug << "Additional libraries" << info.libraryPaths << "\n";
return debug;
}
// Determine whether the given 'ldd' output contains a Linux VDSO
// shared object. The name of the VDSO object differs depending
// on architecture. See "vDSO names" in the notes section of vdso(7)
// for more information.
static bool lddOutputContainsLinuxVDSO(const QString &lddOutput) {
// aarch64, arm, mips, x86_64, x86/x32
if (lddOutput.contains(QStringLiteral("linux-vdso.so.1"))) {
return true;
// ppc32, s390
} else if (lddOutput.contains(QStringLiteral("linux-vdso32.so.1"))) {
return true;
// ppc64, s390x
} else if (lddOutput.contains(QStringLiteral("linux-vdso64.so.1"))) {
return true;
// ia64, sh, i386
} else if (lddOutput.contains(QStringLiteral("linux-gate.so.1"))) {
return true;
}
return false;
}
bool copyFilePrintStatus(const QString &from, const QString &to)
{
if (QFile(to).exists()) {
if (alwaysOwerwriteEnabled) {
QFile(to).remove();
} else {
LogDebug() << QFileInfo(to).fileName() << "already deployed, skipping.";
return false;
}
}
if (QFile::copy(from, to)) {
QFile dest(to);
dest.setPermissions(dest.permissions() | QFile::WriteOwner | QFile::WriteUser);
LogNormal() << " copied:" << from;
LogNormal() << " to" << to;
// The source file might not have write permissions set. Set the
// write permission on the target file to make sure we can use
// install_name_tool on it later.
QFile toFile(to);
if (toFile.permissions() & QFile::WriteOwner)
return true;
if (!toFile.setPermissions(toFile.permissions() | QFile::WriteOwner)) {
LogError() << "Failed to set u+w permissions on target file: " << to;
return false;
}
return true;
} else {
LogError() << "file copy failed from" << from;
LogError() << " to" << to;
return false;
}
}
LddInfo findDependencyInfo(const QString &binaryPath)
{
LddInfo info;
info.binaryPath = binaryPath;
LogDebug() << "Using ldd:";
LogDebug() << " inspecting" << binaryPath;
QProcess ldd;
ldd.start("ldd", QStringList() << binaryPath);
ldd.waitForFinished();
if (ldd.exitStatus() != QProcess::NormalExit || ldd.exitCode() != 0) {
LogError() << "findDependencyInfo:" << ldd.readAllStandardError();
return info;
}
static const QRegularExpression regexp(QStringLiteral("^.+ => (.+) \\("));
QString output = ldd.readAllStandardOutput();
QStringList outputLines = output.split("\n", QString::SkipEmptyParts);
if (outputLines.size() < 2) {
if ((output.contains("statically linked") == false)){
LogError() << "Could not parse ldd output under 2 lines:" << output;
}
return info;
}
foreach (QString outputLine, outputLines) {
// LogDebug() << "ldd outputLine:" << outputLine;
if ((outputLine.contains("not found")) && (qtDetectionComplete == 1)){
LogError() << "ldd outputLine:" << outputLine.replace("\t", "");
LogError() << "Please ensure that all libraries can be found by ldd. Aborting.";
exit(1);
}
}
if ((binaryPath.contains(".so.") || binaryPath.endsWith(".so")) && (!lddOutputContainsLinuxVDSO(output))) {
const QRegularExpressionMatch match = regexp.match(outputLines.first());
if (match.hasMatch()) {
info.installName = match.captured(1);
} else {
LogError() << "Could not parse ldd output line:" << outputLines.first();
}
outputLines.removeFirst();
}
foreach (const QString &outputLine, outputLines) {
const QRegularExpressionMatch match = regexp.match(outputLine);
if (match.hasMatch()) {
DylibInfo dylib;
dylib.binaryPath = match.captured(1).trimmed();
LogDebug() << " dylib.binaryPath" << dylib.binaryPath;
/*
dylib.compatibilityVersion = 0;
dylib.currentVersion = 0;
*/
info.dependencies << dylib;
}
}
return info;
}
int containsHowOften(QStringList haystack, QString needle) {
int result = haystack.filter(needle).length();
return result;
}
LibraryInfo parseLddLibraryLine(const QString &line, const QString &appDirPath, const QSet<QString> &rpaths)
{
(void)rpaths;
if(fhsLikeMode == false){
bundleLibraryDirectory= "lib"; // relative to bundle
} else {
QString relativePrefix = fhsPrefix.replace(appDirPath+"/", "");
bundleLibraryDirectory = relativePrefix + "/lib/";
}
LogDebug() << "bundleLibraryDirectory:" << bundleLibraryDirectory;
LibraryInfo info;
QString trimmed = line.trimmed();
LogDebug() << "parsing" << trimmed;
if (trimmed.isEmpty())
return info;
if(bundleAllButCoreLibs) {
/*
Bundle every lib including the low-level ones except those that are explicitly blacklisted.
This is more suitable for bundling in a way that is portable between different distributions and target systems.
Along the way, this also takes care of non-Qt libraries.
The excludelist can be updated by running
#/bin/bash
blacklisted=$(wget https://raw.githubusercontent.com/probonopd/AppImages/master/excludelist -O - | sort | uniq | grep -v "^#.*" | grep "[^-\s]")
for item in $blacklisted; do
echo -ne '"'$item'" << '
done
*/
QStringList excludelist;
excludelist << "libasound.so.2" << "libcom_err.so.2" << "libcrypt.so.1" << "libc.so.6" << "libdl.so.2" << "libdrm.so.2" << "libexpat.so.1" << "libfontconfig.so.1" << "libgcc_s.so.1" << "libgdk_pixbuf-2.0.so.0" << "libgdk-x11-2.0.so.0" << "libgio-2.0.so.0" << "libglib-2.0.so.0" << "libGL.so.1" << "libgobject-2.0.so.0" << "libgpg-error.so.0" << "libgssapi_krb5.so.2" << "libgtk-x11-2.0.so.0" << "libhcrypto.so.4" << "libhx509.so.5" << "libICE.so.6" << "libidn.so.11" << "libk5crypto.so.3" << "libkeyutils.so.1" << "libkrb5.so.26" << "libkrb5.so.3" << "libkrb5support.so.0" << "libm.so.6" << "libnss3.so" << "libnssutil3.so" << "libp11-kit.so.0" << "libpangoft2-1.0.so.0" << "libpangocairo-1.0.so.0" << "libpango-1.0.so.0" << "libpcre.so.3" << "libpthread.so.0" << "libresolv.so.2" << "libroken.so.18" << "librt.so.1" << "libselinux.so.1" << "libSM.so.6" << "libstdc++.so.6" << "libusb-1.0.so.0" << "libuuid.so.1" << "libwind.so.0" << "libX11.so.6" << "libxcb.so.1" << "libz.so.1";
LogDebug() << "excludelist:" << excludelist;
if (! trimmed.contains("libicu")) {
if (containsHowOften(excludelist, QFileInfo(trimmed).completeBaseName())) {
LogDebug() << "Skipping blacklisted" << trimmed;
return info;
}
}
} else {
/*
Don't deploy low-level libraries in /usr or /lib because these tend to break if moved to a system with a different glibc.
TODO: Could make bundling these low-level libraries optional but then the bundles might need to
use something like patchelf --set-interpreter or http://bitwagon.com/rtldi/rtldi.html
With the Qt provided by qt.io the libicu libraries come bundled, but that is not the case with e.g.,
Qt from ppas. Hence we make sure libicu is always bundled since it cannot be assumed to be on target sytems
*/
// Manual make of Qt deploys it to /usr/local/Qt-x.x.x so we cannot remove this path just like that, so let's allow known libs of Qt.
if (!trimmed.contains("libicu") && !trimmed.contains("lib/libQt") && !trimmed.contains("lib/libqgsttools")) {
if ((trimmed.startsWith("/usr") or (trimmed.startsWith("/lib")))) {
return info;
}
}
}
enum State {QtPath, LibraryName, Version, End};
State state = QtPath;
int part = 0;
QString name;
QString qtPath;
QString suffix = "";
// Split the line into [Qt-path]/lib/qt[Module].library/Versions/[Version]/
QStringList parts = trimmed.split("/");
while (part < parts.count()) {
const QString currentPart = parts.at(part).simplified() ;
++part;
if (currentPart == "")
continue;
if (state == QtPath) {
// Check for library name part
if (part < parts.count() && parts.at(part).contains(".so")) {
info.libraryDirectory += "/" + (qtPath + currentPart + "/").simplified();
LogDebug() << "info.libraryDirectory:" << info.libraryDirectory;
state = LibraryName;
continue;
} else if (trimmed.startsWith("/") == false) { // If the line does not contain a full path, the app is using a binary Qt package.
QStringList partsCopy = parts;
partsCopy.removeLast();
foreach (QString path, librarySearchPath) {
if (!path.endsWith("/"))
path += '/';
QString nameInPath = path + parts.join("/");
if (QFile::exists(nameInPath)) {
info.libraryDirectory = path + partsCopy.join("/");
break;
}
}
if (info.libraryDirectory.isEmpty())
info.libraryDirectory = "/usr/lib/" + partsCopy.join("/");
if (!info.libraryDirectory.endsWith("/"))
info.libraryDirectory += "/";
state = LibraryName;
--part;
continue;
}
qtPath += (currentPart + "/");
} if (state == LibraryName) {
name = currentPart;
info.isDylib = true;
info.libraryName = name;
info.binaryName = name.left(name.indexOf('.')) + suffix + name.mid(name.indexOf('.'));
info.deployedInstallName = "$ORIGIN"; // + info.binaryName;
info.libraryPath = info.libraryDirectory + info.binaryName;
info.sourceFilePath = info.libraryPath;
info.libraryDestinationDirectory = bundleLibraryDirectory + "/";
info.binaryDestinationDirectory = info.libraryDestinationDirectory;
info.binaryDirectory = info.libraryDirectory;
info.binaryPath = info.libraryPath;
state = End;
++part;
continue;
} else if (state == End) {
break;
}
}
if (!info.sourceFilePath.isEmpty() && QFile::exists(info.sourceFilePath)) {
info.installName = findDependencyInfo(info.sourceFilePath).installName;
if (info.installName.startsWith("@rpath/"))
info.deployedInstallName = info.installName;
}
return info;
}
QStringList findAppLibraries(const QString &appDirPath)
{
QStringList result;
// .so
QDirIterator iter(appDirPath, QStringList() << QString::fromLatin1("*.so"),
QDir::Files, QDirIterator::Subdirectories);
while (iter.hasNext()) {
iter.next();
result << iter.fileInfo().filePath();
}
// .so.*, FIXME: Is the above really needed or is it covered by the below too?
QDirIterator iter2(appDirPath, QStringList() << QString::fromLatin1("*.so*"),
QDir::Files, QDirIterator::Subdirectories);
while (iter2.hasNext()) {
iter2.next();
result << iter2.fileInfo().filePath();
}
return result;
}
QList<LibraryInfo> getQtLibraries(const QList<DylibInfo> &dependencies, const QString &appDirPath, const QSet<QString> &rpaths)
{
QList<LibraryInfo> libraries;
foreach (const DylibInfo &dylibInfo, dependencies) {
LibraryInfo info = parseLddLibraryLine(dylibInfo.binaryPath, appDirPath, rpaths);
if (info.libraryName.isEmpty() == false) {
LogDebug() << "Adding library:";
LogDebug() << info;
libraries.append(info);
}
}
return libraries;
}
// TODO: Switch the following to using patchelf
QSet<QString> getBinaryRPaths(const QString &path, bool resolve = true, QString executablePath = QString())
{
QSet<QString> rpaths;
QProcess objdump;
objdump.start("objdump", QStringList() << "-x" << path);
if (!objdump.waitForStarted()) {
if(objdump.errorString().contains("execvp: No such file or directory")){
LogError() << "Could not start objdump.";
LogError() << "Make sure it is installed on your $PATH.";
} else {
LogError() << "Could not start objdump. Process error is" << objdump.errorString();
}
exit(1);
}
objdump.waitForFinished();
if (objdump.exitCode() != 0) {
LogError() << "getBinaryRPaths:" << objdump.readAllStandardError();
}
if (resolve && executablePath.isEmpty()) {
executablePath = path;
}
QString output = objdump.readAllStandardOutput();
QStringList outputLines = output.split("\n");
QStringListIterator i(outputLines);
while (i.hasNext()) {
if (i.next().contains("RUNPATH") && i.hasNext()) {
i.previous();
const QString &rpathCmd = i.next();
int pathStart = rpathCmd.indexOf("RUNPATH");
if (pathStart >= 0) {
QString rpath = rpathCmd.mid(pathStart+8).trimmed();
LogDebug() << "rpath:" << rpath;
rpaths << rpath;
}
}
}
return rpaths;
}
QList<LibraryInfo> getQtLibraries(const QString &path, const QString &appDirPath, const QSet<QString> &rpaths)
{
const LddInfo info = findDependencyInfo(path);
return getQtLibraries(info.dependencies, appDirPath, rpaths + getBinaryRPaths(path));
}
QList<LibraryInfo> getQtLibrariesForPaths(const QStringList &paths, const QString &appDirPath, const QSet<QString> &rpaths)
{
QList<LibraryInfo> result;
QSet<QString> existing;
foreach (const QString &path, paths) {
foreach (const LibraryInfo &info, getQtLibraries(path, appDirPath, rpaths)) {
if (!existing.contains(info.libraryPath)) { // avoid duplicates
existing.insert(info.libraryPath);
result << info;
}
}
}
return result;
}
QStringList getBinaryDependencies(const QString executablePath,
const QString &path,
const QList<QString> &additionalBinariesContainingRpaths)
{
QStringList binaries;
const QList<DylibInfo> dependencies = findDependencyInfo(path).dependencies;
bool rpathsLoaded = false;
QSet<QString> rpaths;
// return bundle-local dependencies. (those starting with @executable_path)
foreach (const DylibInfo &info, dependencies) {
QString trimmedLine = info.binaryPath;
if (trimmedLine.startsWith("@executable_path/")) {
QString binary = QDir::cleanPath(executablePath + trimmedLine.mid(QStringLiteral("@executable_path/").length()));
if (binary != path)
binaries.append(binary);
} else if (trimmedLine.startsWith("@rpath/")) {
if (!rpathsLoaded) {
rpaths = getBinaryRPaths(path, true, executablePath);
foreach (const QString &binaryPath, additionalBinariesContainingRpaths) {
QSet<QString> binaryRpaths = getBinaryRPaths(binaryPath, true);
rpaths += binaryRpaths;
}
rpathsLoaded = true;
}
bool resolved = false;
foreach (const QString &rpath, rpaths) {
QString binary = QDir::cleanPath(rpath + "/" + trimmedLine.mid(QStringLiteral("@rpath/").length()));
LogDebug() << "Checking for" << binary;
if (QFile::exists(binary)) {
binaries.append(binary);
resolved = true;
break;
}
}
if (!resolved && !rpaths.isEmpty()) {
LogError() << "Cannot resolve rpath" << trimmedLine;
LogError() << " using" << rpaths;
}
}
}
return binaries;
}
// copies everything _inside_ sourcePath to destinationPath
bool recursiveCopy(const QString &sourcePath, const QString &destinationPath)
{
if (!QDir(sourcePath).exists())
return false;
QDir().mkpath(destinationPath);
LogNormal() << "copy:" << sourcePath << destinationPath;
QStringList files = QDir(sourcePath).entryList(QStringList() << "*", QDir::Files | QDir::NoDotAndDotDot);
foreach (QString file, files) {
const QString fileSourcePath = sourcePath + "/" + file;
const QString fileDestinationPath = destinationPath + "/" + file;
copyFilePrintStatus(fileSourcePath, fileDestinationPath);
}
QStringList subdirs = QDir(sourcePath).entryList(QStringList() << "*", QDir::Dirs | QDir::NoDotAndDotDot);
foreach (QString dir, subdirs) {
recursiveCopy(sourcePath + "/" + dir, destinationPath + "/" + dir);
}
return true;
}
void recursiveCopyAndDeploy(const QString &appDirPath, const QSet<QString> &rpaths, const QString &sourcePath, const QString &destinationPath)
{
QDir().mkpath(destinationPath);
LogNormal() << "copy:" << sourcePath << destinationPath;
QStringList files = QDir(sourcePath).entryList(QStringList() << QStringLiteral("*"), QDir::Files | QDir::NoDotAndDotDot);
foreach (QString file, files) {
const QString fileSourcePath = sourcePath + QLatin1Char('/') + file;
QString fileDestinationPath = destinationPath + QLatin1Char('/') + file;
copyFilePrintStatus(fileSourcePath, fileDestinationPath);
if(fileDestinationPath.endsWith(".so")){
LogDebug() << "Deploying .so in QML import" << fileSourcePath;
runStrip(fileDestinationPath);
// Find out the relative path to the lib/ directory and set it as the rpath
// FIXME: remove code duplication - the next few lines exist elsewhere already
if(fhsLikeMode == false){
bundleLibraryDirectory= "lib"; // relative to bundle
} else {
QString relativePrefix = fhsPrefix.replace(appDirPath+"/", "");
bundleLibraryDirectory = relativePrefix + "/lib/";
}
QDir dir(QFileInfo(fileDestinationPath).canonicalFilePath());
QString relativePath = dir.relativeFilePath(appDirPath + "/" + bundleLibraryDirectory);
relativePath.remove(0, 3); // remove initial '../'
changeIdentification("$ORIGIN:$ORIGIN/" + relativePath, QFileInfo(fileDestinationPath).canonicalFilePath());
QList<LibraryInfo> libraries = getQtLibraries(fileSourcePath, appDirPath, QSet<QString>());
deployQtLibraries(libraries, appDirPath, QStringList() << destinationPath, false);
}
}
QStringList subdirs = QDir(sourcePath).entryList(QStringList() << QStringLiteral("*"), QDir::Dirs | QDir::NoDotAndDotDot);
foreach (QString dir, subdirs) {
recursiveCopyAndDeploy(appDirPath, rpaths, sourcePath + QLatin1Char('/') + dir, destinationPath + QLatin1Char('/') + dir);
}
}
QString copyDylib(const LibraryInfo &library, const QString path)
{
if (!QFile::exists(library.sourceFilePath)) {
LogError() << "no file at" << library.sourceFilePath;
return QString();
}
// Construct destination paths. The full path typically looks like
// MyApp.app/Contents/Libraries/libfoo.dylib
QString dylibDestinationDirectory = path + QLatin1Char('/') + library.libraryDestinationDirectory;
QString dylibDestinationBinaryPath = dylibDestinationDirectory + QLatin1Char('/') + library.binaryName;
// Create destination directory
if (!QDir().mkpath(dylibDestinationDirectory)) {
LogError() << "could not create destination directory" << dylibDestinationDirectory;
return QString();
}
// Retrun if the dylib has aleardy been deployed
if (QFileInfo(dylibDestinationBinaryPath).exists() && !alwaysOwerwriteEnabled)
return dylibDestinationBinaryPath;
// Copy dylib binary
copyFilePrintStatus(library.sourceFilePath, dylibDestinationBinaryPath);
return dylibDestinationBinaryPath;
}
void runPatchelf(QStringList options)
{
QProcess patchelftool;
patchelftool.start("patchelf", options);
if (!patchelftool.waitForStarted()) {
if(patchelftool.errorString().contains("execvp: No such file or directory")){
LogError() << "Could not start patchelf.";
LogError() << "Make sure it is installed on your $PATH, e.g., in /usr/local/bin.";
LogError() << "You can get it from https://nixos.org/patchelf.html.";
} else {
LogError() << "Could not start patchelftool. Process error is" << patchelftool.errorString();
}
exit(1);
}
patchelftool.waitForFinished();
if (patchelftool.exitCode() != 0) {
LogError() << "runPatchelf:" << patchelftool.readAllStandardError();
LogError() << "runPatchelf:" << patchelftool.readAllStandardOutput();
// exit(1); // Do not exit because this could be a script that patchelf can't work on
}
}
bool patchQtCore(const QString &path, const QString &variable, const QString &value)
{
return true; // ################################### Disabling for now since using qt.conf
QFile file(path);
if (!file.open(QIODevice::ReadWrite)) {
LogWarning() << QString::fromLatin1("Unable to patch %1: %2").arg(
QDir::toNativeSeparators(path), file.errorString());
return false;
}
QByteArray content = file.readAll();
if (content.isEmpty()) {
LogWarning() << QString::fromLatin1("Unable to patch %1: Could not read file content").arg(
QDir::toNativeSeparators(path));
return false;
}
QString searchString = QString::fromLatin1("%1=").arg(variable);
QByteArray searchStringQByteArray = searchString.toLatin1().data();
int startPos = content.indexOf(searchStringQByteArray);
if (startPos != -1) {
LogNormal() << QString::fromLatin1(
"Patching value of %2 in %1 to '%3'").arg(QDir::toNativeSeparators(path), variable, value);
}
startPos += searchStringQByteArray.length();
int endPos = content.indexOf(char(0), startPos);
if (endPos == -1) {
LogWarning() << QString::fromLatin1("Unable to patch %1: Internal error").arg(
QDir::toNativeSeparators(path));
return false;
}
QByteArray replacement = QByteArray(endPos - startPos, char(0));
QByteArray replacementBegin = value.toLatin1().data();
replacement.prepend(replacementBegin);
replacement.truncate(endPos - startPos);
content.replace(startPos, endPos - startPos, replacement);
if (!file.seek(0) || (file.write(content) != content.size())) {
LogWarning() << QString::fromLatin1("Unable to patch %1: Could not write to file").arg(
QDir::toNativeSeparators(path));
return false;
}
return true;
}
void changeIdentification(const QString &id, const QString &binaryPath)
{
LogNormal() << "Changing rpath in" << binaryPath << "to" << id;
runPatchelf(QStringList() << "--set-rpath" << id << binaryPath);
// qt_prfxpath:
if (binaryPath.contains("libQt5Core")) {
LogDebug() << "libQt5Core detected, patching its hardcoded strings";
/* https://codereview.qt-project.org/gitweb?p=qt/qttools.git;a=blob_plain;f=src/windeployqt/utils.cpp;h=e89496ea1f371ed86f6937284c1c801daf576572;hb=7be81b804da102b374c2089aac38353a0383c254
* Search for "qt_prfxpath=<xxx>" in a path, and replace it with "qt_prfxpath=." or "qt_prfxpath=.." */
if(fhsLikeMode == true){
patchQtCore(binaryPath, "qt_prfxpath", "..");
} else {
patchQtCore(binaryPath, "qt_prfxpath", ".");
}
patchQtCore(binaryPath, "qt_adatpath", ".");
patchQtCore(binaryPath, "qt_docspath", "doc");
patchQtCore(binaryPath, "qt_hdrspath", "include");
patchQtCore(binaryPath, "qt_libspath", "lib");
patchQtCore(binaryPath, "qt_lbexpath", "libexec");
patchQtCore(binaryPath, "qt_binspath", "bin");
patchQtCore(binaryPath, "qt_plugpath", "plugins");
patchQtCore(binaryPath, "qt_impspath", "imports");
patchQtCore(binaryPath, "qt_qml2path", "qml");
patchQtCore(binaryPath, "qt_datapath", ".");
patchQtCore(binaryPath, "qt_trnspath", "translations");
patchQtCore(binaryPath, "qt_xmplpath", "examples");
patchQtCore(binaryPath, "qt_demopath", "demos");
patchQtCore(binaryPath, "qt_tstspath", "tests");
patchQtCore(binaryPath, "qt_hpfxpath", ".");
patchQtCore(binaryPath, "qt_hbinpath", "bin");
patchQtCore(binaryPath, "qt_hdatpath", ".");
patchQtCore(binaryPath, "qt_stngpath", "."); // e.g., /opt/qt53/etc/xdg; does it load Trolltech.conf from there?
/* Qt on Arch Linux comes with more hardcoded paths
* https://github.com/probonopd/linuxdeployqt/issues/98
patchString(binaryPath, "lib/qt/libexec", "libexec");
patchString(binaryPath, "lib/qt/plugins", "plugins");
patchString(binaryPath, "lib/qt/imports", "imports");
patchString(binaryPath, "lib/qt/qml", "qml");
patchString(binaryPath, "lib/qt", "");
patchString(binaryPath, "share/doc/qt", "doc");
patchString(binaryPath, "include/qt", "include");
patchString(binaryPath, "share/qt", "");
patchString(binaryPath, "share/qt/translations", "translations");
patchString(binaryPath, "share/doc/qt/examples", "examples");
*/
}
}
void runStrip(const QString &binaryPath)
{
if (runStripEnabled == false)
return;
// Since we might have a symlink, we need to find its target first
QString resolvedPath = QFileInfo(binaryPath).canonicalFilePath();
LogDebug() << "Determining whether to run strip:";
LogDebug() << " checking whether" << resolvedPath << "has an rpath set";
LogDebug() << "patchelf" << "--print-rpath" << resolvedPath;
QProcess patchelfread;
patchelfread.start("patchelf", QStringList() << "--print-rpath" << resolvedPath);
if (!patchelfread.waitForStarted()) {
if(patchelfread.errorString().contains("execvp: No such file or directory")){
LogError() << "Could not start patchelf.";
LogError() << "Make sure it is installed on your $PATH.";
} else {
LogError() << "Could not start patchelf. Process error is" << patchelfread.errorString();
}
// exit(1); // Do not exit because this could be a script that patchelf can't work on
}
patchelfread.waitForFinished();
if (patchelfread.exitCode() != 0){
LogError() << "Error reading rpath with patchelf" << QFileInfo(resolvedPath).completeBaseName() << ":" << patchelfread.readAllStandardError();
LogError() << "Error reading rpath with patchelf" << QFileInfo(resolvedPath).completeBaseName() << ":" << patchelfread.readAllStandardOutput();
exit(1);
}
QString rpath = patchelfread.readAllStandardOutput();
if (rpath.startsWith("$")){
LogDebug() << "Already contains rpath starting with $, hence not stripping";
LogDebug() << patchelfread.readAllStandardOutput();
return;
}
LogDebug() << "Using strip:";
LogDebug() << " stripping" << resolvedPath;
QProcess strip;
strip.start("strip", QStringList() << resolvedPath);
if (!strip.waitForStarted()) {
if(strip.errorString().contains("execvp: No such file or directory")){
LogError() << "Could not start strip.";
LogError() << "Make sure it is installed on your $PATH.";
} else {
LogError() << "Could not start strip. Process error is" << strip.errorString();
}
exit(1);
}
strip.waitForFinished();
if (strip.exitCode() == 0)
return;
if (strip.readAllStandardError().contains("Not enough room for program headers")) {
LogNormal() << QFileInfo(resolvedPath).completeBaseName() << "already stripped.";
} else {
LogError() << "Error stripping" << QFileInfo(resolvedPath).completeBaseName() << ":" << strip.readAllStandardError();
LogError() << "Error stripping" << QFileInfo(resolvedPath).completeBaseName() << ":" << strip.readAllStandardOutput();
exit(1);
}
}
void stripAppBinary(const QString &bundlePath)
{
(void)bundlePath;
runStrip(appBinaryPath);
}
/*
Deploys the the libraries listed into an app bundle.
The libraries are searched for dependencies, which are also deployed.
(deploying Qt3Support will also deploy QtNetwork and QtSql for example.)
Returns a DeploymentInfo structure containing the Qt path used and a
a list of actually deployed libraries.
*/
DeploymentInfo deployQtLibraries(QList<LibraryInfo> libraries,
const QString &bundlePath, const QStringList &binaryPaths,
bool useLoaderPath)
{
LogNormal() << "Deploying the following libraries:" << binaryPaths;
QStringList copiedLibraries;
DeploymentInfo deploymentInfo;
deploymentInfo.requiresQtWidgetsLibrary = false;
deploymentInfo.useLoaderPath = useLoaderPath;
deploymentInfo.pluginPath = qtToBeBundledInfo.value("QT_INSTALL_PLUGINS");
QSet<QString> rpathsUsed;
while (libraries.isEmpty() == false) {
const LibraryInfo library = libraries.takeFirst();
copiedLibraries.append(library.libraryName);
if(library.libraryName.contains("libQt") and library.libraryName.contains("Core.so")) {
LogNormal() << "Setting deploymentInfo.qtPath to:" << library.libraryDirectory;
deploymentInfo.qtPath = library.libraryDirectory;
}
if(library.libraryName.contains("libQt") and library.libraryName.contains("Widgets.so")) {
deploymentInfo.requiresQtWidgetsLibrary = true;
}
if (library.libraryDirectory.startsWith(bundlePath)) {
LogNormal() << library.libraryName << "already deployed, skipping.";
continue;
}
if (library.rpathUsed.isEmpty() != true) {
rpathsUsed << library.rpathUsed;
}
// Copy the library to the app bundle.
const QString deployedBinaryPath = copyDylib(library, bundlePath);
// Skip the rest if already was deployed.
if (deployedBinaryPath.isNull())
continue;
runStrip(deployedBinaryPath);
if (!library.rpathUsed.length()) {
changeIdentification(library.deployedInstallName, QFileInfo(deployedBinaryPath).canonicalFilePath());
}
// Check for library dependencies
QList<LibraryInfo> dependencies = getQtLibraries(deployedBinaryPath, bundlePath, rpathsUsed);
foreach (LibraryInfo dependency, dependencies) {
if (dependency.rpathUsed.isEmpty() != true) {
rpathsUsed << dependency.rpathUsed;
}
// Deploy library if necessary.
if (copiedLibraries.contains(dependency.libraryName) == false && libraries.contains(dependency) == false) {
libraries.append(dependency);
}
}
}
deploymentInfo.deployedLibraries = copiedLibraries;
deploymentInfo.rpathsUsed += rpathsUsed;
return deploymentInfo;
}
static QString captureOutput(const QString &command)
{
QProcess process;
process.start(command, QIODevice::ReadOnly);
process.waitForFinished();
if (process.exitStatus() != QProcess::NormalExit) {
LogError() << command << "crashed:" << process.readAllStandardError();
} else if (process.exitCode() != 0) {
LogError() << command << "exited with" << process.exitCode() << ":" << process.readAllStandardError();