-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathappdirtool.go
1604 lines (1392 loc) · 57 KB
/
appdirtool.go
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
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"path"
"strconv"
"syscall"
"debug/elf"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/otiai10/copy"
"github.com/probonopd/go-appimage/internal/helpers"
)
type QMLImport struct {
Classname string `json:"classname,omitempty"`
Name string `json:"name"`
Path string `json:"path,omitempty"`
Plugin string `json:"plugin,omitempty"`
RelativePath string `json:"relativePath,omitempty"`
Type string `json:"type"`
Version string `json:"version"`
}
var allELFs []string
var libraryLocations []string // All directories in the host system that may contain libraries
var seenDeps []string
var quirksModePatchQtPrfxPath = false
var AppRunData = `#!/bin/sh
HERE="$(dirname "$(readlink -f "${0}")")"
MAIN=$(grep -r "^Exec=.*" "$HERE"/*.desktop | head -n 1 | cut -d "=" -f 2 | cut -d " " -f 1)
############################################################################################
# Use bundled paths
############################################################################################
export PATH="${HERE}"/usr/bin/:"${HERE}"/usr/sbin/:"${HERE}"/usr/games/:"${HERE}"/bin/:"${HERE}"/sbin/:"${PATH}"
export XDG_DATA_DIRS="${HERE}"/usr/share/:"${XDG_DATA_DIRS}"
############################################################################################
# Use bundled Python
############################################################################################
export PYTHONHOME="${HERE}"/usr/
############################################################################################
# Use bundled Tcl/Tk
############################################################################################
if [ -e "${HERE}"/usr/share/tcltk/tcl8.6 ] ; then
export TCL_LIBRARY="${HERE}"/usr/share/tcltk/tcl8.6:$TCL_LIBRARY:$TK_LIBRARY
export TK_LIBRARY="${HERE}"/usr/share/tcltk/tk8.6:$TK_LIBRARY:$TCL_LIBRARY
fi
############################################################################################
# Make it look more native on Gtk+ based systems
############################################################################################
case "${XDG_CURRENT_DESKTOP}" in
*GNOME*|*gnome*)
export QT_QPA_PLATFORMTHEME=gtk2
esac
############################################################################################
# If .ui files are in the AppDir, then chances are that we need to cd into usr/
# because we may have had to patch the absolute paths away in the binary
############################################################################################
UIFILES=$(find "$HERE" -name "*.ui")
if [ ! -z "$UIFILES" ] ; then
cd "$HERE/usr"
fi
############################################################################################
# Use bundled GStreamer
# NOTE: May need to remove libgstvaapi.so
############################################################################################
if [ ! -z $(find "${HERE}" -name "libgstcoreelements.so" -type f) ] ; then
export GST_PLUGIN_PATH=$(dirname $(readlink -f $(find "${HERE}" -name "libgstcoreelements.so" -type f | head -n 1)))
export GST_PLUGIN_SCANNER=$(find "${HERE}" -name "gst-plugin-scanner" -type f | head -n 1)
export GST_PLUGIN_SYSTEM_PATH=$GST_PLUGIN_PATH
env | grep GST
fi
############################################################################################
# Run experimental bundle that bundles everything if a private ld-linux-x86-64.so.2 is there
# This allows the bundle to run even on older systems than the one it was built on
############################################################################################
cd "$HERE/usr" # Not all applications will need this; TODO: Make this opt-in
# Try to find a binary with the same name as the AppImage or the symlink through which
# it was invoked, without any suffix
if [ -z "$ARGV0" ] ; then
# AppRun is being executed outside of an AppImage
ARGV0="$0"
fi
BINARY_NAME=$(basename "$ARGV0")
if [ "$BINARY_NAME" = "AppRun" ] ; then
unset BINARY_NAME
fi
BINARY_NAME="${BINARY_NAME%.*}" # remove everything after the last "."
MAIN_BIN=$(find "$HERE/usr/bin" -name "$BINARY_NAME" | head -n 1)
# Fall back to finding the main binary based on the Exec= line in the desktop file
if [ -z "$MAIN_BIN" ] ; then
MAIN_BIN=$(find "$HERE/usr/bin" -name "$MAIN" | head -n 1)
fi
LD_LINUX=$(find "$HERE" -name 'ld-*.so.*' | head -n 1)
if [ -e "$LD_LINUX" ] ; then
export GCONV_PATH="$HERE/usr/lib/gconv"
export FONTCONFIG_FILE="$HERE/etc/fonts/fonts.conf"
export GTK_PATH=$(find "$HERE/lib" -name gtk-* -type d)
export GTK_THEME=Default # This one should be bundled so that it can work on systems without Gtk
export GDK_PIXBUF_MODULEDIR=$(find "$HERE" -name loaders -type d -path '*gdk-pixbuf*')
export GDK_PIXBUF_MODULE_FILE=$(find "$HERE" -name loaders.cache -type f -path '*gdk-pixbuf*') # Patched to contain no paths
export XDG_DATA_DIRS="${HERE}"/usr/share/:"${XDG_DATA_DIRS}"
export PERLLIB="${HERE}"/usr/share/perl5/:"${HERE}"/usr/lib/perl5/:"${PERLLIB}"
export GSETTINGS_SCHEMA_DIR="${HERE}"/usr/share/glib-2.0/runtime-schemas/:"${HERE}"/usr/share/glib-2.0/schemas/:"${GSETTINGS_SCHEMA_DIR}"
export QT_PLUGIN_PATH="$(readlink -f "$(dirname "$(find "${HERE}" -type d -path '*/plugins/platforms' 2>/dev/null)" 2>/dev/null)" 2>/dev/null)"
case $line in
"ld-linux"*) exec "${LD_LINUX}" --inhibit-cache "${MAIN_BIN}" "$@" ;;
*) exec "${LD_LINUX}" "${MAIN_BIN}" "$@" ;;
esac
else
exec "${MAIN_BIN}" "$@"
fi
`
type ELF struct {
path string
relpaths []string
rpath string
}
// Key: name of the package, value: location of the copyright file
var copyrightFiles = make(map[string]string) // Need to use 'make', otherwise we can't add to it
// Key: Path of the file, value: name of the package
var packagesContainingFiles = make(map[string]string) // Need to use 'make', otherwise we can't add to it
/*
man ld.so says:
If a shared object dependency does not contain a slash, then it is searched for in the following order:
o Using the directories specified in the DT_RPATH dynamic section attribute of the binary if present and DT_RUNPATH attribute does not exist. Use
of DT_RPATH is deprecated.
o Using the environment variable LD_LIBRARY_PATH, unless the executable is being run in secure-execution mode (see below), in which case this vari‐
able is ignored.
o Using the directories specified in the DT_RUNPATH dynamic section attribute of the binary if present. Such directories are searched only to find
those objects required by DT_NEEDED (direct dependencies) entries and do not apply to those objects' children, which must themselves have their
own DT_RUNPATH entries. This is unlike DT_RPATH, which is applied to searches for all children in the dependency tree.
o From the cache file /etc/ld.so.cache, which contains a compiled list of candidate shared objects previously found in the augmented library path.
If, however, the binary was linked with the -z nodeflib linker option, shared objects in the default paths are skipped. Shared objects installed
in hardware capability directories (see below) are preferred to other shared objects.
NOTE: Clear Linux* OS has this in /var/cache/ldconfig/ld.so.cache
o In the default path /lib, and then /usr/lib. (On some 64-bit architectures, the default paths for 64-bit shared objects are /lib64, and then
/usr/lib64.) If the binary was linked with the -z nodeflib linker option, this step is skipped.
*/
type DeployOptions struct {
standalone bool
libAppRunHooks bool
}
// this is the public options instance
// which need to be set before the function is called
var options DeployOptions
func AppDirDeploy(path string) {
appdir, err := helpers.NewAppDir(path)
if err != nil {
helpers.PrintError("AppDir", err)
os.Exit(1)
}
log.Println("Gathering all required libraries for the AppDir...")
determineELFsInDirTree(appdir, appdir.Path)
// Gdk
handleGdk(appdir)
// GStreamer
handleGStreamer(appdir)
// Gtk modules/plugins
// If there is a .so with the name libgtk-* inside the AppDir, then we need to
// bundle Gdk modules/plugins
deployGtkDirectory(appdir, 4)
deployGtkDirectory(appdir, 3)
deployGtkDirectory(appdir, 2)
deployGtkUiFiles(appdir)
// ALSA
handleAlsa(appdir)
// PulseAudio
handlePulseAudio(appdir)
// ld-linux interpreter
ldLinux, err := deployInterpreter(appdir)
// Glib 2 schemas
if helpers.Exists(appdir.Path + "/usr/share/glib-2.0/schemas") {
err = handleGlibSchemas(appdir)
if err != nil {
helpers.PrintError("Could not deploy GLib schemas", err)
}
}
// Fonts
err = deployFontconfig(appdir)
if err != nil {
helpers.PrintError("Could not deploy Fontconfig", err)
}
// AppRun
if options.libAppRunHooks == false {
// If libapprun_hooks is not used
log.Println("Adding AppRun...")
err = os.WriteFile(appdir.Path+"/AppRun", []byte(AppRunData), 0755)
if err != nil {
helpers.PrintError("write AppRun", err)
os.Exit(1)
}
} else {
log.Println("TODO: Add AppRun suitable for libapprun_hooks...")
}
log.Println("Find out whether Qt is a dependency of the application to be bundled...")
qtVersionDetected := 0
for i := 5; i <= 99; i++ {
if containsString(allELFs, fmt.Sprintf("libQt%dCore.so.%d", i, i)) == true {
log.Printf("Detected Qt %d", i)
qtVersionDetected = i
break
}
}
if containsString(allELFs, "libQtCore.so.4") == true {
log.Println("Detected Qt 4")
qtVersionDetected = 4
}
if qtVersionDetected > 0 {
handleQt(appdir, qtVersionDetected)
}
fmt.Println("")
log.Println("libraryLocations:")
for _, lib := range libraryLocations {
fmt.Println(lib)
}
fmt.Println("")
// This is used when calculating the rpath that gets written into the ELFs as they are copied into the AppDir
// and when modifying the ELFs that were pre-existing in the AppDir so that they become aware of the other locations
var libraryLocationsInAppDir []string
for _, lib := range libraryLocations {
if strings.HasPrefix(lib, appdir.Path) == false {
lib = appdir.Path + lib
}
libraryLocationsInAppDir = helpers.AppendIfMissing(libraryLocationsInAppDir, lib)
}
fmt.Println("")
log.Println("libraryLocationsInAppDir:")
for _, lib := range libraryLocationsInAppDir {
fmt.Println(lib)
}
fmt.Println("")
/*
fmt.Println("")
log.Println("allELFs:")
for _, lib := range allELFs {
fmt.Println(lib)
}
*/
log.Println("Only after this point should we start copying around any ELFs")
log.Println("Copying in and patching ELFs which are not already in the AppDir...")
handleNvidia()
for _, lib := range allELFs {
deployElf(lib, appdir, err)
patchRpathsInElf(appdir, libraryLocationsInAppDir, lib)
if strings.Contains(lib, fmt.Sprintf("libQt%dCore.so.%d", qtVersionDetected, qtVersionDetected)) {
fmt.Println("Patching Qt prefix path in " + lib)
patchQtPrfxpath(appdir, lib, libraryLocationsInAppDir, ldLinux)
}
}
deployCopyrightFiles(appdir)
}
func deployFontconfig(appdir helpers.AppDir) error {
var err error
if helpers.Exists(appdir.Path+"/etc/fonts") == false {
log.Println("Adding fontconfig symlink... (is this really the right thing to do?)")
err = os.MkdirAll(appdir.Path+"/etc/fonts", 0755)
if err != nil {
helpers.PrintError("MkdirAll", err)
os.Exit(1)
}
err = os.Symlink("/etc/fonts/fonts.conf", appdir.Path+"/etc/fonts/fonts.conf")
if err != nil {
helpers.PrintError("MkdirAll", err)
os.Exit(1)
}
}
return err
}
func deployInterpreter(appdir helpers.AppDir) (string, error) {
var ldLinux, err = appdir.GetElfInterpreter(appdir)
if err != nil {
helpers.PrintError("Could not determine ELF interpreter", err)
os.Exit(1)
}
if helpers.Exists(appdir.Path+"/"+ldLinux) == true {
log.Println("Removing pre-existing", ldLinux+"...")
err = syscall.Unlink(appdir.Path + "/" + ldLinux)
if err != nil {
helpers.PrintError("Could not remove pre-existing ld-linux", err)
os.Exit(1)
}
}
if options.standalone {
var err error
// ld-linux might be a symlink; hence we first need to resolve it
src, err := filepath.EvalSymlinks(ldLinux)
if err != nil {
helpers.PrintError("Could not get the location of ld-linux", err)
src = ldLinux
}
log.Println("Deploying", ldLinux+"...")
ldTargetPath := appdir.Path + ldLinux
if options.libAppRunHooks {
// This file is part of the libc family of libraries and we want to use libapprun_hooks,
// hence copy to a separate directory unlike the rest of the libraries. The reason is
// that this familiy of libraries will only be used by libapprun_hooks if the
// bundled version is newer than what is already on the target system; this allows
// us to also load libraries from the system such as proprietary GPU drivers
log.Println(ldLinux, "is part of libc; copy to", LibcDir, "subdirectory")
ldTargetPath = appdir.Path + "/" + LibcDir + "/" + ldLinux // If libapprun_hooks is used
}
err = copy.Copy(src, ldTargetPath)
if err != nil {
helpers.PrintError("Could not copy ld-linux", err)
return "", err
}
// Do what we do in the Scribus AppImage script, namely
// sed -i -e 's|/usr|/xxx|g' lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
log.Println("Patching ld-linux...")
err = PatchFile(ldTargetPath, "/lib", "/XXX")
if err != nil {
helpers.PrintError("PatchFile", err)
return "", err
}
err = PatchFile(ldTargetPath, "/usr", "/xxx")
if err != nil {
helpers.PrintError("PatchFile", err)
return "", err
}
// --inhibit-cache is not working, it is still using /etc/ld.so.cache
err = PatchFile(ldTargetPath, "/etc", "/EEE")
if err != nil {
helpers.PrintError("PatchFile", err)
return "", err
}
log.Println("Determining gconv (for GCONV_PATH)...")
// Search in all of the system's library directories for a directory called gconv
// and put it into the a location which matches the GCONV_PATH we export in AppRun
gconvs, err := findWithPrefixInLibraryLocations("gconv")
if err == nil {
// Target location must match GCONV_PATH exported in AppRun
determineELFsInDirTree(appdir, gconvs[0])
}
if err != nil {
helpers.PrintError("Could not deploy the interpreter", err) // TODO: Don't print this for musl libc
// os.Exit(1) // There is no gconf is musl libc
}
// Make ld-linux executable
err = os.Chmod(ldTargetPath, 0755)
if err != nil {
helpers.PrintError("Could not set permissions on the interpreter", err)
os.Exit(1)
}
} else {
log.Println("Not deploying", ldLinux, "because it was not requested or it is not needed")
}
return ldLinux, err
}
// deployElf deploys an ELF (executable or shared library) to the AppDir
// if it is not on the exclude list and it is not yet at the target location
func deployElf(lib string, appdir helpers.AppDir, err error) {
for _, excludePrefix := range ExcludedLibraries {
if strings.HasPrefix(filepath.Base(lib), excludePrefix) == true && !options.standalone {
log.Println("Skipping", lib, "because it is on the excludelist")
return
}
}
log.Println("Working on", lib)
if strings.HasPrefix(lib, appdir.Path) == false { // Do not copy if it is already in the AppDir
libTargetPath := appdir.Path + "/" + lib
if options.libAppRunHooks && checkWhetherPartOfLibc(lib) == true {
// This file is part of the libc family of libraries and we want to use libapprun_hooks,
// hence copy to a separate directory unlike the rest of the libraries. The reason is
// that this familiy of libraries will only be used by libapprun_hooks if the
// bundled version is newer than what is already on the target system; this allows
// us to also load libraries from the system such as proprietary GPU drivers
log.Println(lib, "is part of libc; copy to", LibcDir, "subdirectory")
libTargetPath = appdir.Path + "/" + LibcDir + "/" + lib // If libapprun_hooks is used
}
// Skip copying if the source is a directory
if fi, err := os.Stat(lib); err == nil && fi.IsDir() {
log.Println(lib, "is a directory, skipping")
return
}
log.Println("Copying to libTargetPath:", libTargetPath)
err = helpers.CopyFile(lib, libTargetPath) // If libapprun_hooks is not used
if err != nil {
log.Println(libTargetPath, "could not be copied:", err)
// os.Exit(1)
}
}
}
// patchQtPrfxpath patches qt_prfxpath of the libQt5Core.so.5/libQt6Core.so.6 in an AppDir
// so that the Qt installation finds its own components in the AppDir
func patchQtPrfxpath(appdir helpers.AppDir, lib string, libraryLocationsInAppDir []string, ldLinux string) {
log.Println("Patching qt_prfxpath, otherwise can't load platform plugin...")
libPath := lib
// Determine libPath:
// if lib is inside the AppDir, use that; otherwise,
// if appdir.Path + "/" + lib exists, use that. IMPORTANT: Use the absolute, not relative paths!
absoluteAppDirPath, err := filepath.Abs(appdir.Path)
if err != nil {
helpers.PrintError("Could not determine absolute path of AppDir", err)
os.Exit(1)
}
absoluteLibPath, err := filepath.Abs(lib)
if err != nil {
helpers.PrintError("Could not determine absolute path of lib", err)
os.Exit(1)
}
if strings.HasPrefix(absoluteLibPath, absoluteAppDirPath) {
libPath = absoluteLibPath
} else {
if _, err := os.Stat(absoluteAppDirPath + "/" + lib); err == nil {
libPath = absoluteAppDirPath + "/" + lib
} else {
helpers.PrintError("Could not determine absolute path of lib", err)
os.Exit(1)
}
}
log.Println("libPath:", libPath)
f, err := os.Open(libPath)
// Get the filename of lib withouth the path, e.g., libQt5Core.so.5/libQt6Core.so.6
libFilename := filepath.Base(lib)
// Open file for reading/determining the offset
defer f.Close()
if err != nil {
helpers.PrintError("Could not open "+libFilename+" for reading", err)
os.Exit(1)
}
f.Seek(0, 0)
// Search from the beginning of the file
search := []byte("qt_prfxpath=")
prfxpathPos := ScanFile(f, search)
if prfxpathPos < 0 {
helpers.PrintError("Could not find offset for " + string(search), errors.New("no " + string(search) + " token in binary"))
os.Exit(1)
}
offset := prfxpathPos + int64(len(search))
log.Println("Offset of qt_prfxpath:", offset)
/*
What does qt_prfxpath=. actually mean on a Linux system? Where is "."?
Looks like it means "relative to args[0]".
So 'qt_prfxpath=.' would be wrong if we load the application through ld-linux.so because that one
lives in, e.g., appdir/lib64 which is actually not where the Qt 'plugins' directory is.
Hence we do NOT have to patch qt_prfxpath=. but to qt_prfxpath=../opt/qt512/'
(the relative path from args[0] to the directory in which the Qt 'plugins' directory is)
*/
// Note: The following is correct only if we bundle (and run through) ld-linux; in all other cases
// we should calculate the relative path relative to the main binary
var qtPrefixDir string
for _, libraryLocationInAppDir := range libraryLocationsInAppDir {
if strings.HasSuffix(libraryLocationInAppDir, "/plugins/platforms") {
qtPrefixDir = filepath.Dir(filepath.Dir(libraryLocationInAppDir))
break
}
}
if qtPrefixDir == "" {
helpers.PrintError("Could not determine the the Qt prefix directory:", err)
os.Exit(1)
} else {
log.Println("Qt prefix directory in the AppDir:", qtPrefixDir)
}
relPathToQt, err := filepath.Rel(filepath.Dir(appdir.Path+ldLinux), qtPrefixDir)
if err != nil {
helpers.PrintError("Could not compute the location of the Qt plugins directory:", err)
os.Exit(1)
} else {
log.Println("Relative path from ld-linux to Qt prefix directory in the AppDir:", relPathToQt)
}
f, err = os.OpenFile(libPath, os.O_WRONLY, 0644)
// Open file writable, why is this so complicated
defer f.Close()
if err != nil {
helpers.PrintError("Could not open "+libPath+" for writing", err)
os.Exit(1)
}
// Now that we know where in the file the information is, go write it
f.Seek(offset, 0)
if quirksModePatchQtPrfxPath == false {
log.Println("Patching qt_prfxpath in " + libPath + " to " + relPathToQt)
_, err = f.Write([]byte(relPathToQt + "\x00"))
} else {
log.Println("Patching qt_prfxpath in " + libPath + " to ..")
_, err = f.Write([]byte(".." + "\x00"))
}
if err != nil {
helpers.PrintError("Could not patch qt_prfxpath in "+libPath, err)
}
}
// deployCopyrightFiles deploys copyright files into the AppDir
// for each ELF in allELFs that are inside the AppDir and have matching equivalents outside of the AppDir
func deployCopyrightFiles(appdir helpers.AppDir) {
log.Println("Copying in copyright files...")
for _, lib := range allELFs {
shouldDoIt := true
for _, excludePrefix := range ExcludedLibraries {
if strings.HasPrefix(filepath.Base(lib), excludePrefix) == true && options.standalone == false {
log.Println("Skipping copyright file for ", lib, "because it is on the excludelist")
shouldDoIt = false
break
}
}
if shouldDoIt == true && strings.HasPrefix(lib, appdir.Path) == false {
// Copy copyright files into the AppImage
copyrightFile, err := getCopyrightFile(lib)
// It is perfectly fine for this to error - on non-dpkg systems, or if lib was not in a deb package
if err == nil {
os.MkdirAll(filepath.Dir(appdir.Path+copyrightFile), 0755)
copy.Copy(copyrightFile, appdir.Path+copyrightFile)
}
}
}
log.Println("Done")
if options.standalone == true {
log.Println("To check whether it is really self-contained, run:")
fmt.Println("LD_LIBRARY_PATH='' find " + appdir.Path + " -type f -exec ldd {} 2>&1 \\; | grep '=>' | grep -v " + appdir.Path)
}
if options.libAppRunHooks == true {
log.Println("The option '-m' was used. Hence, you need to manually add AppRun, .env, and libapprun_hooks.so")
log.Println("from https://github.com/AppImageCrafters/AppRun/releases/tag/continuous. TODO: Automate this")
}
}
// handleGlibSchemas compiles GLib schemas if the subdirectory is present in the AppImage.
// AppRun has to export GSETTINGS_SCHEMA_DIR for this to work
func handleGlibSchemas(appdir helpers.AppDir) error {
var err error
if helpers.Exists(appdir.Path+"/usr/share/glib-2.0/schemas") && !helpers.Exists(appdir.Path+"/usr/share/glib-2.0/schemas/gschemas.compiled") {
log.Println("Compiling glib-2.0 schemas...")
cmd := exec.Command("glib-compile-schemas", ".")
cmd.Dir = appdir.Path + "/usr/share/glib-2.0/schemas"
err = cmd.Run()
if err != nil {
helpers.PrintError("Run glib-compile-schemas", err)
os.Exit(1)
}
}
return err
}
func handleGdk(appdir helpers.AppDir) {
// If there is a .so with the name libgdk_pixbuf inside the AppDir, then we need to
// bundle Gdk pixbuf loaders without which the bundled Gtk does not work
// cp /usr/lib/x86_64-linux-gnu/gdk-pixbuf-*/*/loaders/* usr/lib/x86_64-linux-gnu/gdk-pixbuf-*/*/loaders/
// cp /usr/lib/x86_64-linux-gnu/gdk-pixbuf-*/*/loaders.cache usr/lib/x86_64-linux-gnu/gdk-pixbuf-*/*/ -
// this file must also be patched not to contain paths to the libraries
for _, lib := range allELFs {
if strings.HasPrefix(filepath.Base(lib), "libgdk_pixbuf") {
log.Println("Determining Gdk pixbuf loaders (for GDK_PIXBUF_MODULEDIR and GDK_PIXBUF_MODULE_FILE)...")
locs, err := findWithPrefixInLibraryLocations("gdk-pixbuf")
if err != nil {
log.Println("Could not find Gdk pixbuf loaders")
os.Exit(1)
} else {
for _, loc := range locs {
determineELFsInDirTree(appdir, loc)
// We need to patch away the path to libpixbufloader-png.so from the file loaders.cache, similar to:
// sed -i -e 's|/usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/2.10.0/loaders/||g' usr/lib/x86_64-linux-gnu/gdk-pixbuf-*/*/loaders.cache
// the patched file must not contain paths to the libraries
loadersCaches := helpers.FilesWithSuffixInDirectoryRecursive(loc, "loaders.cache")
if len(loadersCaches) < 1 {
helpers.PrintError("loadersCaches", errors.New("could not find loaders.cache"))
os.Exit(1)
}
err = copy.Copy(loadersCaches[0], appdir.Path+loadersCaches[0])
if err != nil {
helpers.PrintError("Could not copy loaders.cache", err)
os.Exit(1)
}
loadersCache, err := filepath.EvalSymlinks(filepath.Dir(loadersCaches[0]))
if err != nil {
helpers.PrintError("Could not get the location of loaders.cache", err)
break
}
whatToPatchAway := loadersCache + "/loaders/"
log.Println("Patching", appdir.Path+loadersCaches[0], "removing", whatToPatchAway)
err = PatchFile(appdir.Path+loadersCaches[0], whatToPatchAway, "")
if err != nil {
helpers.PrintError("PatchFile loaders.cache", err)
break // os.Exit(1)
}
}
}
break
}
}
}
func handlePulseAudio(appdir helpers.AppDir) {
// TODO: What about the `/usr/lib/pulse-*` directory?
for _, lib := range allELFs {
if strings.HasPrefix(filepath.Base(lib), "libpulse.so") {
log.Println("Bundling pulseaudio directory (for <tbd>)...")
locs, err := findWithPrefixInLibraryLocations("pulseaudio")
if err != nil {
log.Println("Could not find pulseaudio directory")
os.Exit(1)
} else {
log.Println("Bundling dependencies of pulseaudio directory...")
determineELFsInDirTree(appdir, locs[0])
}
break
}
}
}
func handleNvidia() {
// As soon as we bundle libnvidia*, we get a segfault.
// Hence we exit whenever libGL.so.1 requires libnvidia*
for _, elf := range allELFs {
if strings.HasPrefix(filepath.Base(elf), "libnvidia") {
log.Println("System (most likely libGL) uses libnvidia*, please build on another system that does not use NVIDIA drivers, exiting")
os.Exit(1)
}
}
}
func handleAlsa(appdir helpers.AppDir) {
// FIXME: Doesn't seem to get loaded. Is ALSA_PLUGIN_DIR needed and working in ALSA?
// Is something like https://github.com/flatpak/freedesktop-sdk-images/blob/1.6/alsa-lib-plugin-path.patch needed in the bundled ALSA?
// TODO: What about the `share/alsa` subdirectory? libasound.so.* refers to it as well
for _, lib := range allELFs {
if strings.HasPrefix(filepath.Base(lib), "libasound.so") {
log.Println("Bundling alsa-lib directory (for <tbd>)...")
locs, err := findWithPrefixInLibraryLocations("alsa-lib")
if err != nil {
log.Println("Could not find alsa-lib directory")
log.Println("E.g., in Alpine Linux: apk add alsa-plugins alsa-plugins-pulse")
os.Exit(1)
} else {
log.Println("Bundling dependencies of alsa-lib directory...")
determineELFsInDirTree(appdir, locs[0])
}
break
}
}
}
func handleGStreamer(appdir helpers.AppDir) {
for _, lib := range allELFs {
if strings.HasPrefix(filepath.Base(lib), "libgstreamer-1.0") {
log.Println("Bundling GStreamer 1.0 directory (for GST_PLUGIN_PATH)...")
locs, err := findWithPrefixInLibraryLocations("gstreamer-1.0")
if err != nil {
log.Println("Could not find GStreamer 1.0 directory")
os.Exit(1)
} else {
log.Println("Bundling dependencies of GStreamer 1.0 directory...")
determineELFsInDirTree(appdir, locs[0])
}
// FIXME: This is not going to scale, every distribution is cooking their own soup,
// we need to determine the location of gst-plugin-scanner dynamically by parsing it out of libgstreamer-1.0
gstPluginScannerCandidates := []string{"/usr/libexec/gstreamer-1.0/gst-plugin-scanner", // Clear Linux* OS
"/usr/lib/x86_64-linux-gnu/gstreamer1.0/gstreamer-1.0/gst-plugin-scanner"} // sic! Ubuntu 18.04
for _, cand := range gstPluginScannerCandidates {
if helpers.Exists(cand) {
log.Println("Determining gst-plugin-scanner...")
determineELFsInDirTree(appdir, cand)
break
}
}
break
}
}
}
func patchRpathsInElf(appdir helpers.AppDir, libraryLocationsInAppDir []string, path string) {
if strings.HasPrefix(path, appdir.Path) == false {
path = filepath.Clean(appdir.Path + "/" + path)
}
var newRpathStringForElf string
var newRpathStrings []string
for _, libloc := range libraryLocationsInAppDir {
relpath, err := filepath.Rel(filepath.Dir(path), libloc)
if err != nil {
helpers.PrintError("Could not compute relative path", err)
}
newRpathStrings = append(newRpathStrings, "$ORIGIN/"+filepath.Clean(relpath))
}
newRpathStringForElf = strings.Join(newRpathStrings, ":")
// fmt.Println("Computed newRpathStringForElf:", appdir.Path+"/"+lib, newRpathStringForElf)
if options.libAppRunHooks && checkWhetherPartOfLibc(path) {
log.Println("Not writing rpath because file is part of the libc family of libraries")
return
}
// If the file starts with ld- or libc., we don't patch the rpath
// NOTE: In Alpine Linux, ld-musl-x86_64.so.1 links to libc.musl-x86_64.so.1
basePath := filepath.Base(path)
if strings.HasPrefix(basePath, "ld-") || strings.HasPrefix(basePath, "libc.") {
log.Println("Not patching rpath because file starts with ld- or libc.")
} else {
// Call patchelf to set the rpath
if helpers.Exists(path) == true {
// log.Println("Rewriting rpath of", path)
cmd := exec.Command("patchelf", "--set-rpath", newRpathStringForElf, path)
// log.Println(cmd.Args)
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println(cmd.String())
helpers.PrintError("patchelf --set-rpath "+path+": "+string(out), err)
os.Exit(1)
}
}
}
}
func deployGtkDirectory(appdir helpers.AppDir, gtkVersion int) {
for _, lib := range allELFs {
if strings.HasPrefix(filepath.Base(lib), "libgtk-"+strconv.Itoa(gtkVersion)) {
log.Println("Bundling Gtk", strconv.Itoa(gtkVersion), "directory (for GTK_EXE_PREFIX)...")
locs, err := findWithPrefixInLibraryLocations("gtk-" + strconv.Itoa(gtkVersion))
if err != nil {
log.Println("Could not find Gtk", strconv.Itoa(gtkVersion), "directory")
os.Exit(1)
} else {
for _, loc := range locs {
log.Println("Bundling dependencies of Gtk", strconv.Itoa(gtkVersion), "directory...")
determineELFsInDirTree(appdir, loc)
if gtkVersion <= 3 {
log.Println("Bundling Default theme for Gtk", strconv.Itoa(gtkVersion), "(for GTK_THEME=Default)...")
err = copy.Copy("/usr/share/themes/Default/gtk-"+strconv.Itoa(gtkVersion)+".0", appdir.Path+"/usr/share/themes/Default/gtk-"+strconv.Itoa(gtkVersion)+".0")
if err != nil {
helpers.PrintError("Copy", err)
os.Exit(1)
}
}
if gtkVersion <= 3 {
log.Println("Bundling immodules.cache for Gtk", strconv.Itoa(gtkVersion))
immodulesCaches := helpers.FilesWithSuffixInDirectoryRecursive(loc, "immodules.cache")
if len(immodulesCaches) < 1 {
log.Println("Couldn't find immodules.cache")
os.Exit(1)
}
immodulesCache := immodulesCaches[0]
err = copy.Copy(immodulesCache, appdir.Path + immodulesCache)
if err != nil {
helpers.PrintError("Copy", err)
os.Exit(1)
}
immodulesCacheLoc, err := filepath.EvalSymlinks(filepath.Dir(immodulesCache))
if err != nil {
helpers.PrintError("Could not get the location of immodules.cache", err)
os.Exit(1)
}
whatToPatchAway := immodulesCacheLoc + "/immodules/"
log.Println("Patching", appdir.Path + immodulesCache, "removing", whatToPatchAway)
err = PatchFile(appdir.Path + immodulesCache, whatToPatchAway, "")
if err != nil {
helpers.PrintError("PatchFile immodules.cache", err)
os.Exit(1)
}
}
/*
log.Println("Bundling icons for Default theme...")
err = copy.Copy("/usr/share/icons/Adwaita", appdir.Path+"/usr/share/icons/Adwaita")
if err != nil {
helpers.PrintError("Copy", err)
os.Exit(1)
}
*/
}
}
break
}
}
}
func deployGtkUiFiles(appdir helpers.AppDir) {
// Check for the presence of Gtk .ui files
uifiles := helpers.FilesWithSuffixInDirectoryRecursive(appdir.Path, ".ui")
if len(uifiles) > 0 {
log.Println("Gtk .ui files found. Need to take care to have them loaded from a relative rather than absolute path")
log.Println("TODO: Check if they are at hardcoded absolute paths in the application and if yes, patch")
var dirswithUiFiles []string
for _, uifile := range uifiles {
dirswithUiFiles = helpers.AppendIfMissing(dirswithUiFiles, filepath.Dir(uifile))
err := PatchFile(appdir.MainExecutable, "/usr", "././")
if err != nil {
helpers.PrintError("PatchFile", err)
os.Exit(1)
}
}
log.Println("Directories with .ui files:", dirswithUiFiles)
}
}
// appendLib appends library in path to allELFs and adds its location as well as any pre-existing rpaths to libraryLocations
func appendLib(path string) {
for _, excludedlib := range ExcludedLibraries {
if filepath.Base(path) == excludedlib && !options.standalone {
// log.Println("Skipping", excludedlib, "because it is on the excludelist")
return
}
}
// Find out whether there are pre-existing rpaths and if so, add them to libraryLocations
// so that we can find libraries there, too
// See if the library had a pre-existing rpath that did not start with $. If so, replace it by one that
// points to the equal location as the original but inside the AppDir
rpaths, err := readRpaths(path)
if err != nil {
helpers.PrintError("Could not determine rpath in "+path, err)
os.Exit(1)
}
for _, rpath := range rpaths {
rpath = filepath.Clean(strings.Replace(rpath, "$ORIGIN", filepath.Dir(path), -1))
if helpers.SliceContains(libraryLocations, rpath) == false && rpath != "" {
log.Println("Add", rpath, "to the libraryLocations directories we search for libraries")
libraryLocations = helpers.AppendIfMissing(libraryLocations, filepath.Clean(rpath))
}
}
libraryLocations = helpers.AppendIfMissing(libraryLocations, filepath.Clean(filepath.Dir(path)))
allELFs = helpers.AppendIfMissing(allELFs, path)
}
func determineELFsInDirTree(appdir helpers.AppDir, pathToDirTreeToBeDeployed string) {
allelfs, err := findAllExecutablesAndLibraries(pathToDirTreeToBeDeployed)
if err != nil {
helpers.PrintError("findAllExecutablesAndLibraries", err)
}
// Find the libraries determined by our ldd replacement and add them to
// allELFsUnderPath if they are not there yet
for _, lib := range allelfs {
appendLib(lib)
}
var allELFsUnderPath []ELF
for _, elfpath := range allelfs {
elfobj := ELF{}
elfobj.path = elfpath
allELFsUnderPath = append(allELFsUnderPath, elfobj)
err = getDeps(elfpath)
if err != nil {
helpers.PrintError("getDeps", err)
os.Exit(1)
}
}
log.Println("len(allELFsUnderPath):", len(allELFsUnderPath))
// Find out in which directories we now actually have libraries
log.Println("libraryLocations:", libraryLocations)
log.Println("len(allELFs):", len(allELFs))
}
func readRpaths(path string) ([]string, error) {
// Call patchelf to find out whether the ELF already has an rpath set
cmd := exec.Command("patchelf", "--print-rpath", path)
// log.Println("patchelf cmd.Args:", cmd.Args)
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println(cmd.String())
helpers.PrintError("patchelf --print-rpath "+path+": "+string(out), err)
log.Println("Perhaps it is not dynamically linked, or perhaps it is a script. Continuing...")
// os.Exit(1)
return []string{}, nil
}
rpathStringInELF := strings.TrimSpace(string(out))
if rpathStringInELF == "" {
return []string{}, err
}
rpaths := strings.Split(rpathStringInELF, ":")
// log.Println("Determined", len(rpaths), "rpaths:", rpaths)
return rpaths, err
}
// findAllExecutablesAndLibraries returns all ELF libraries and executables
// found in directory, and error
func findAllExecutablesAndLibraries(path string) ([]string, error) {
var allExecutablesAndLibraries []string
// fmt.Println(" findAllExecutablesAndLibrarieschecking", path)
// If we have a file, then there is nothing to walk and we can return it directly
if helpers.IsDirectory(path) != true {
allExecutablesAndLibraries = append(allExecutablesAndLibraries, path)
return allExecutablesAndLibraries, nil
}
filepath.Walk(path, func(path string, info os.FileInfo, e error) error {
if e != nil {
return e
}
// Add ELF files
if info.Mode().IsRegular() {
f, err := os.Open(path)
defer f.Close()
if err == nil {