/
PackageCompiler.jl
1633 lines (1406 loc) · 64.5 KB
/
PackageCompiler.jl
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
module PackageCompiler
using Base: active_project
using Libdl: Libdl
using Pkg: Pkg
using Printf
using Artifacts
using LazyArtifacts
using UUIDs: UUID, uuid1
using RelocatableFolders
using TOML
using Glob
using p7zip_jll: p7zip_path
export create_sysimage, create_app, create_library
include("juliaconfig.jl")
include("../ext/TerminalSpinners.jl")
include("library_selection.jl")
##############
# Arch utils #
##############
const NATIVE_CPU_TARGET = "native"
const TLS_SYNTAX = VERSION >= v"1.7.0-DEV.1205" ? `-DNEW_DEFINE_FAST_TLS_SYNTAX` : ``
const DEFAULT_EMBEDDING_WRAPPER = @path joinpath(@__DIR__, "embedding_wrapper.c")
const DEFAULT_JULIA_INIT = @path joinpath(@__DIR__, "julia_init.c")
const DEFAULT_JULIA_INIT_HEADER = @path joinpath(@__DIR__, "julia_init.h")
default_julia_init() = String(DEFAULT_JULIA_INIT)
default_julia_init_header() = String(DEFAULT_JULIA_INIT_HEADER)
# See https://github.com/JuliaCI/julia-buildbot/blob/489ad6dee5f1e8f2ad341397dc15bb4fce436b26/master/inventory.py
function default_app_cpu_target()
Sys.ARCH === :i686 ? "pentium4;sandybridge,-xsaveopt,clone_all" :
Sys.ARCH === :x86_64 ? "generic;sandybridge,-xsaveopt,clone_all;haswell,-rdrnd,base(1)" :
Sys.ARCH === :arm ? "armv7-a;armv7-a,neon;armv7-a,neon,vfp4" :
Sys.ARCH === :aarch64 ? "generic" #= is this really the best here? =# :
Sys.ARCH === :powerpc64le ? "pwr8" :
"generic"
end
function bitflag()
Sys.ARCH === :i686 ? `-m32` :
Sys.ARCH === :x86_64 ? `-m64` :
``
end
function march()
Sys.ARCH === :i686 ? `-march=pentium4` :
Sys.ARCH === :x86_64 ? `-march=x86-64` :
Sys.ARCH === :arm ? `-march=armv7-a+simd` :
Sys.ARCH === :aarch64 ? `-march=armv8-a+crypto+simd` :
Sys.ARCH === :powerpc64le ? `` :
``
end
#############
# Pkg utils #
#############
function create_pkg_context(project)
if isfile(project)
error("`project` should be a path to a directory containing a Project/Manifest, not a file")
end
project_toml_path = Pkg.Types.projectfile_path(project; strict=true)
if project_toml_path === nothing
error("could not find project at $(repr(project))")
end
ctx = Pkg.Types.Context(env=Pkg.Types.EnvCache(project_toml_path))
if !isfile(ctx.env.manifest_file)
@warn "it is not recommended to create an app/library without a preexisting manifest"
end
return ctx
end
function load_all_deps(ctx)
ctx_or_env = VERSION <= v"1.7.0-" ? ctx : ctx.env
if isdefined(Pkg.Operations, :load_all_deps!)
pkgs = Pkg.Types.PackageSpec[]
Pkg.Operations.load_all_deps!(ctx_or_env, pkgs)
else
pkgs = Pkg.Operations.load_all_deps(ctx_or_env)
end
return pkgs
end
function source_path(ctx, pkg)
if VERSION <= v"1.7.0-"
Pkg.Operations.source_path(ctx, pkg)
else
Pkg.Operations.source_path(ctx.env.project_file, pkg)
end
end
const _STDLIBS = readdir(Sys.STDLIB)
sysimage_modules() = map(x->x.name, Base._sysimage_modules)
stdlibs_in_sysimage() = intersect(_STDLIBS, sysimage_modules())
# TODO: Also check UUIDs for stdlibs, not only names<
function gather_stdlibs_project(ctx)
@assert ctx.env.manifest !== nothing
stdlib_names = String[pkg.name for (_, pkg) in ctx.env.manifest]
filter!(pkg -> pkg in _STDLIBS, stdlib_names)
return stdlib_names
end
function check_packages_in_project(ctx, packages)
packages_in_project = collect(keys(ctx.env.project.deps))
if ctx.env.pkg !== nothing
push!(packages_in_project, ctx.env.pkg.name)
end
packages_not_in_project = setdiff(string.(packages), packages_in_project)
if !isempty(packages_not_in_project)
error("package(s) $(join(packages_not_in_project, ", ")) not in project")
end
end
##############
# Misc utils #
##############
macro monitor_oom(ex)
quote
lowest_free_mem = Sys.free_memory()
mem_monitor = Timer(0, interval = 1) do t
lowest_free_mem = min(lowest_free_mem, Sys.free_memory())
end
try
$(esc(ex))
catch
if lowest_free_mem < 512 * 1024 * 1024 # Less than 512 MB
@warn """
Free system memory dropped to $(Base.format_bytes(lowest_free_mem)) during sysimage compilation.
If the reason the subprocess errored isn't clear, it may have been OOM-killed.
"""
end
rethrow()
finally
close(mem_monitor)
end
end
end
const WARNED_CPP_COMPILER = Ref{Bool}(false)
function get_compiler_cmd(; cplusplus::Bool=false)
cc = get(ENV, "JULIA_CC", nothing)
path = nothing
@static if Sys.iswindows()
path = joinpath(LazyArtifacts.artifact"mingw-w64", (Int==Int64 ? "mingw64" : "mingw32"), "bin", cplusplus ? "g++.exe" : "gcc.exe")
compiler_cmd = `$path`
end
if cc !== nothing
compiler_cmd = Cmd(Base.shell_split(cc))
path = nothing
elseif !Sys.iswindows()
compilers_cpp = ("g++", "clang++")
compilers_c = ("gcc", "clang")
found_compiler = false
if cplusplus
for compiler in compilers_cpp
if Sys.which(compiler) !== nothing
compiler_cmd = `$compiler`
found_compiler = true
break
end
end
end
if !found_compiler
for compiler in compilers_c
if Sys.which(compiler) !== nothing
compiler_cmd = `$compiler`
found_compiler = true
if cplusplus && !WARNED_CPP_COMPILER[]
@warn "could not find a c++ compiler (g++ or clang++), falling back to $compiler, this might cause link errors"
WARNED_CPP_COMPILER[] = true
end
break
end
end
end
found_compiler || error("could not find a compiler, looked for ",
join(((cplusplus ? compilers_cpp : ())..., compilers_c...), ", ", " and "))
end
if path !== nothing
compiler_cmd = addenv(compiler_cmd, "PATH" => string(ENV["PATH"], ";", dirname(path)))
end
return compiler_cmd
end
function run_compiler(cmd::Cmd; cplusplus::Bool=false)
compiler_cmd = get_compiler_cmd(; cplusplus)
full_cmd = `$compiler_cmd $cmd`
@debug "running $full_cmd"
run(full_cmd)
end
function get_julia_cmd()
julia_path = joinpath(Sys.BINDIR, Base.julia_exename())
color = Base.have_color === nothing ? "auto" : Base.have_color ? "yes" : "no"
if isdefined(Base, :Linking) # pkgimage support feature flag
`$julia_path --color=$color --startup-file=no --pkgimages=no`
else
`$julia_path --color=$color --startup-file=no`
end
end
function rewrite_sysimg_jl_only_needed_stdlibs(stdlibs::Vector{String})
sysimg_source_path = Base.find_source_file("sysimg.jl")
sysimg_content = read(sysimg_source_path, String)
# replaces the hardcoded list of stdlibs in sysimg.jl with
# the stdlibs that is given as argument
return replace(sysimg_content,
r"stdlibs = \[(.*?)\]"s => string("stdlibs = [", join(":" .* stdlibs, ",\n"), "]"))
end
function create_fresh_base_sysimage(stdlibs::Vector{String}; cpu_target::String, sysimage_build_args::Cmd)
tmp = mktempdir()
sysimg_source_path = Base.find_source_file("sysimg.jl")
base_dir = dirname(sysimg_source_path)
tmp_corecompiler_ji = joinpath(tmp, "corecompiler.ji")
tmp_sys_o = joinpath(tmp, "sys.o")
tmp_sys_sl = joinpath(tmp, "sys." * Libdl.dlext)
compiler_source_path = joinpath(base_dir, "compiler", "compiler.jl")
# we can't strip the IR from the base sysimg, so we filter out this flag
# also presumably `--compile=all` and maybe a few others we missed here...
sysimage_build_args_strs = map(p -> "$(p...)", values(sysimage_build_args))
filter!(p -> !contains(p, "--compile") && p ∉ ("--strip-ir",), sysimage_build_args_strs)
sysimage_build_args = Cmd(sysimage_build_args_strs)
cd(base_dir) do
spinner = TerminalSpinners.Spinner(msg = "PackageCompiler: creating compiler .ji image (incremental=false)")
TerminalSpinners.@spin spinner begin
# Create corecompiler.ji
cmd = `$(get_julia_cmd()) --cpu-target $cpu_target
--output-ji $tmp_corecompiler_ji $sysimage_build_args
$compiler_source_path`
@debug "running $cmd"
read(cmd)
end
spinner = TerminalSpinners.Spinner(msg = "PackageCompiler: compiling fresh sysimage (incremental=false)")
TerminalSpinners.@spin spinner begin
# Use that to create sys.ji
new_sysimage_content = rewrite_sysimg_jl_only_needed_stdlibs(stdlibs)
new_sysimage_content *= "\nempty!(Base.atexit_hooks)\n"
new_sysimage_source_path = joinpath(tmp, "sysimage_packagecompiler_$(uuid1()).jl")
write(new_sysimage_source_path, new_sysimage_content)
try
cmd = addenv(`$(get_julia_cmd()) --cpu-target $cpu_target
--sysimage=$tmp_corecompiler_ji
$sysimage_build_args --output-o=$tmp_sys_o
$new_sysimage_source_path`,
"JULIA_LOAD_PATH" => "@stdlib")
@debug "running $cmd"
read(cmd)
create_sysimg_from_object_file(String[tmp_sys_o],
tmp_sys_sl;
version=nothing,
soname=nothing,
compat_level="major")
finally
rm(new_sysimage_source_path; force=true)
rm(tmp_corecompiler_ji; force=true)
rm(tmp_sys_o; force=true)
end
end
end
return tmp_sys_sl
end
function ensurecompiled(project, packages, sysimage)
length(packages) == 0 && return
# TODO: Only precompile `packages` (should be available in Pkg 1.8)
cmd = `$(get_julia_cmd()) --sysimage=$sysimage -e 'using Pkg; Pkg.precompile()'`
splitter = Sys.iswindows() ? ';' : ':'
@debug "ensurecompiled: running $cmd" JULIA_LOAD_PATH = "$project$(splitter)@stdlib"
cmd = addenv(cmd, "JULIA_LOAD_PATH" => "$project$(splitter)@stdlib")
run(cmd)
return
end
function run_precompilation_script(project::String, sysimg::String, precompile_file::Union{String, Nothing}, precompile_dir::String)
tracefile, io = mktemp(precompile_dir; cleanup=false)
close(io)
arg = precompile_file === nothing ? `-e ''` : `$precompile_file`
cmd = `$(get_julia_cmd()) --sysimage=$(sysimg) --compile=all --trace-compile=$tracefile $arg`
# --project is not propagated well with Distributed, so use environment
splitter = Sys.iswindows() ? ';' : ':'
@debug "run_precompilation_script: running $cmd" JULIA_LOAD_PATH = "$project$(splitter)@stdlib"
cmd = addenv(cmd, "JULIA_LOAD_PATH" => "$project$(splitter)@stdlib")
precompile_file === nothing || @info "PackageCompiler: Executing $(abspath(precompile_file)) => $(tracefile)"
run(cmd) # `Run` this command so that we'll display stdout from the user's script.
precompile_file === nothing || @info "PackageCompiler: Done"
return tracefile
end
function create_sysimg_object_file(object_file::String,
packages::Vector{String},
packages_sysimg::Set{Base.PkgId};
project::String,
base_sysimage::String,
precompile_execution_file::Vector{String},
precompile_statements_file::Vector{String},
cpu_target::String,
script::Union{Nothing, String},
sysimage_build_args::Cmd,
extra_precompiles::String,
incremental::Bool)
julia_code_buffer = IOBuffer()
# include all packages into the sysimg
print(julia_code_buffer, """
Base.reinit_stdio()
@eval Sys BINDIR = ccall(:jl_get_julia_bindir, Any, ())::String
@eval Sys STDLIB = $(repr(abspath(Sys.BINDIR, "../share/julia/stdlib", string('v', VERSION.major, '.', VERSION.minor))))
copy!(LOAD_PATH, [$(repr(project))]) # Only allow loading packages from current project
Base.init_depot_path()
""")
for pkg in packages_sysimg
print(julia_code_buffer, """
Base.require(Base.PkgId(Base.UUID("$(string(pkg.uuid))"), $(repr(pkg.name))))
""")
end
# Handle precompilation
precompile_files = String[]
@debug "running precompilation execution script..."
precompile_dir = mktempdir(; prefix="jl_packagecompiler_", cleanup=false)
for file in (isempty(precompile_execution_file) ? (nothing,) : precompile_execution_file)
tracefile = run_precompilation_script(project, base_sysimage, file, precompile_dir)
push!(precompile_files, tracefile)
end
append!(precompile_files, abspath.(precompile_statements_file))
precompile_code = """
# This @eval prevents symbols from being put into Main
@eval Module() begin
using Base.Meta
PrecompileStagingArea = Module()
precompile_files = String[
$(join(map(repr, precompile_files), "\n" * " " ^ 8))
]
for file in precompile_files, statement in eachline(file)
# println(statement)
# This is taken from https://github.com/JuliaLang/julia/blob/2c9e051c460dd9700e6814c8e49cc1f119ed8b41/contrib/generate_precompile.jl#L375-L393
ps = try
Meta.parse(statement)
catch
# guard against precompile statements that are not valid Julia syntax
continue
end
isexpr(ps, :call) || continue
popfirst!(ps.args) # precompile(...)
ps.head = :tuple
@static if VERSION <= v"1.9.0"
l = ps.args[end]
if (isexpr(l, :tuple) || isexpr(l, :curly)) && length(l.args) > 0 # Tuple{...} or (...)
# XXX: precompile doesn't currently handle overloaded Vararg arguments very well.
# Replacing N with a large number works around it.
l = l.args[end]
if isexpr(l, :curly) && length(l.args) == 2 && l.args[1] === :Vararg # Vararg{T}
push!(l.args, 100) # form Vararg{T, 100} instead
end
end
end
# println(ps)
local ps
while true
try
ps = Core.eval(PrecompileStagingArea, ps)
@static if VERSION <= v"1.9.0-beta1"
# XXX: precompile doesn't currently handle overloaded nospecialize arguments very well.
# Skipping them avoids the warning.
ms = length(ps) == 1 ? Base._methods_by_ftype(ps[1], 1, Base.get_world_counter()) : Base.methods(ps...)
ms isa Vector || @goto skip_precompile
end
break
catch e
if e isa UndefVarError
dep = string(e.var)
mods = filter(p -> p.first.name == dep, Base.loaded_modules)
if length(mods) != 1
@debug "zero or multiple modules loaded with name \$dep"
@goto skip_precompile
else
_, mod = only(mods)
@debug "importing \$dep into PrecompileStagingArea"
Base.eval(PrecompileStagingArea, :(\$(Symbol(dep)) = \$(mod)))
end
else
# See julia issue #28808
@debug "failed to execute \$statement: \$e"
@goto skip_precompile
end
end
end
precompile(ps...)
@label skip_precompile
end
@eval PrecompileStagingArea begin
$extra_precompiles
end
end # module
"""
# Make packages available in Main. It is unclear if this is the right thing to do.
for pkg in packages
print(julia_code_buffer, """
import $pkg
""")
end
print(julia_code_buffer, precompile_code)
if script !== nothing
print(julia_code_buffer, """
include($(repr(abspath(script))))
""")
end
print(julia_code_buffer, """
empty!(Core.ARGS)
empty!(Base.ARGS)
empty!(LOAD_PATH)
empty!(DEPOT_PATH)
empty!(Base.TOML_CACHE.d)
Base.TOML.reinit!(Base.TOML_CACHE.p, "")
@eval Sys begin
BINDIR = ""
STDLIB = ""
end
""")
if "--strip-metadata" in sysimage_build_args
print(julia_code_buffer, """
empty!(Base._included_files)
empty!(Base.pkgorigins)
empty!(Base.Docs.keywords)
""")
end
julia_code = String(take!(julia_code_buffer))
outputo_file = tempname()
@debug "writing precompile staging code to $outputo_file"
write(outputo_file, julia_code)
# Read the input via stdin to avoid hitting the maximum command line limit
cmd = `$(get_julia_cmd()) --cpu-target=$cpu_target $sysimage_build_args
--sysimage=$base_sysimage --project=$project --output-o=$(object_file)
$outputo_file`
@debug "running $cmd"
non = incremental ? "" : "non"
spinner = TerminalSpinners.Spinner(msg = "PackageCompiler: compiling $(non)incremental system image")
@monitor_oom TerminalSpinners.@spin spinner run(cmd)
return
end
"""
create_sysimage(packages::Vector{String}; kwargs...)
Create a system image that includes the package(s) in `packages` (given as a
string or vector). If the `packages` argument is not passed, all packages in the
project will be put into the sysimage.
An attempt to automatically find a compiler will be done but can also be given
explicitly by setting the environment variable `JULIA_CC` to a path to a
compiler (can also include extra arguments to the compiler, like `-g`).
### Keyword arguments:
- `sysimage_path::String`: The path to where the resulting sysimage should be saved.
- `project::String`: The project directory that should be active when the sysimage is created,
defaults to the currently active project.
- `precompile_execution_file::Union{String, Vector{String}}`: A file or list of
files that contain code from which precompilation statements should be recorded.
- `precompile_statements_file::Union{String, Vector{String}}`: A file or list of
files that contain precompilation statements that should be included in the sysimage.
- `incremental::Bool`: If `true`, build the new sysimage on top of the sysimage
of the current process otherwise build a new sysimage from scratch. Defaults to `true`.
- `filter_stdlibs::Bool`: If `true`, only include stdlibs that are in the project file.
Defaults to `false`, only set to `true` if you know the potential pitfalls.
- `include_transitive_dependencies::Bool`: If `true`, explicitly put all
transitive dependencies into the sysimage. This only makes a difference if some
packages do not load all their dependencies when themselves are loaded. Defaults to `true`.
### Advanced keyword arguments
- `base_sysimage::Union{Nothing, String}`: If a `String`, names an existing sysimage upon which to build
the new sysimage incrementally, instead of the sysimage of the current process. Defaults to `nothing`.
Keyword argument `incremental` must be `true` if `base_sysimage` is not `nothing`.
- `cpu_target::String`: The value to use for `JULIA_CPU_TARGET` when building the system image. Defaults
to `native`.
- `script::String`: Path to a file that gets executed in the `--output-o` process.
- `sysimage_build_args::Cmd`: A set of command line options that is used in the Julia process building the sysimage,
for example `-O1 --check-bounds=yes`.
"""
function create_sysimage(packages::Union{Nothing, Symbol, Vector{String}, Vector{Symbol}}=nothing;
sysimage_path::String,
project::String=dirname(active_project()),
precompile_execution_file::Union{String, Vector{String}}=String[],
precompile_statements_file::Union{String, Vector{String}}=String[],
incremental::Bool=true,
filter_stdlibs::Bool=false,
cpu_target::String=NATIVE_CPU_TARGET,
script::Union{Nothing, String}=nothing,
sysimage_build_args::Cmd=``,
include_transitive_dependencies::Bool=true,
# Internal args
base_sysimage::Union{Nothing, String}=nothing,
julia_init_c_file=nothing,
julia_init_h_file=nothing,
version=nothing,
soname=nothing,
compat_level::String="major",
extra_precompiles::String = "",
)
# We call this at the very beginning to make sure that the user has a compiler available. Therefore, if no compiler
# is found, we throw an error immediately, instead of making the user wait a while before the error is thrown.
get_compiler_cmd()
if isdir(sysimage_path)
error("The provided sysimage_path is a directory: $(sysimage_path). Please specify a full path including the sysimage filename.")
end
if filter_stdlibs && incremental
error("must use `incremental=false` to use `filter_stdlibs=true`")
end
ctx = create_pkg_context(project)
if packages === nothing
packages = collect(keys(ctx.env.project.deps))
if ctx.env.pkg !== nothing
push!(packages, ctx.env.pkg.name)
end
end
packages = string.(vcat(packages))
precompile_execution_file = vcat(precompile_execution_file)
precompile_statements_file = vcat(precompile_statements_file)
check_packages_in_project(ctx, packages)
# Instantiate the project
@debug "instantiating project at $(repr(project))"
Pkg.instantiate(ctx, verbose=true, allow_autoprecomp = false)
if !incremental
if base_sysimage !== nothing
error("cannot specify `base_sysimage` when `incremental=false`")
end
sysimage_stdlibs = filter_stdlibs ? gather_stdlibs_project(ctx) : stdlibs_in_sysimage()
base_sysimage = create_fresh_base_sysimage(sysimage_stdlibs; cpu_target, sysimage_build_args)
else
base_sysimage = something(base_sysimage, unsafe_string(Base.JLOptions().image_file))
end
ensurecompiled(project, packages, base_sysimage)
packages_sysimg = Set{Base.PkgId}()
if include_transitive_dependencies
# We are not sure that packages actually load their dependencies on `using`
# but we still want them to end up in the sysimage. Therefore, explicitly
# collect their dependencies, recursively.
frontier = Set{Base.PkgId}()
deps = ctx.env.project.deps
for pkg in packages
# Add all dependencies of the package
if ctx.env.pkg !== nothing && pkg == ctx.env.pkg.name
push!(frontier, Base.PkgId(ctx.env.pkg.uuid, pkg))
else
uuid = ctx.env.project.deps[pkg]
push!(frontier, Base.PkgId(uuid, pkg))
end
end
copy!(packages_sysimg, frontier)
new_frontier = Set{Base.PkgId}()
while !(isempty(frontier))
for pkgid in frontier
deps = if ctx.env.pkg !== nothing && pkgid.uuid == ctx.env.pkg.uuid
ctx.env.project.deps
else
ctx.env.manifest[pkgid.uuid].deps
end
pkgid_deps = [Base.PkgId(uuid, name) for (name, uuid) in deps]
for pkgid_dep in pkgid_deps
if !(pkgid_dep in packages_sysimg) #
push!(packages_sysimg, pkgid_dep)
push!(new_frontier, pkgid_dep)
end
end
end
copy!(frontier, new_frontier)
empty!(new_frontier)
end
end
# Create the sysimage
object_file = tempname() * ".o"
create_sysimg_object_file(object_file, packages, packages_sysimg;
project,
base_sysimage,
precompile_execution_file,
precompile_statements_file,
cpu_target,
script,
sysimage_build_args,
extra_precompiles,
incremental)
object_files = [object_file]
if julia_init_c_file !== nothing
if julia_init_c_file isa String
julia_init_c_file = [julia_init_c_file]
end
mktempdir() do include_dir
if julia_init_h_file !== nothing
if julia_init_h_file isa String
julia_init_h_file = [julia_init_h_file]
end
for f in julia_init_h_file
cp(f, joinpath(include_dir, basename(f)))
end
end
for f in julia_init_c_file
filename = compile_c_init_julia(f, basename(sysimage_path), include_dir)
push!(object_files, filename)
end
end
end
create_sysimg_from_object_file(object_files,
sysimage_path;
compat_level,
version,
soname)
rm(object_file; force=true)
if Sys.isapple()
cd(dirname(abspath(sysimage_path))) do
sysimage_file = basename(sysimage_path)
cmd = `install_name_tool -id @rpath/$(sysimage_file) $sysimage_file`
@debug "running $cmd"
run(cmd)
end
end
return nothing
end
function create_sysimg_from_object_file(object_files::Vector{String},
sysimage_path::String;
version,
compat_level::String,
soname::Union{Nothing, String})
if soname === nothing && (Sys.isunix() && !Sys.isapple())
soname = basename(sysimage_path)
end
mkpath(dirname(sysimage_path))
# Prevent compiler from stripping all symbols from the shared lib.
o_file_flags = Sys.isapple() ? `-Wl,-all_load $object_files` : `-Wl,--whole-archive $object_files -Wl,--no-whole-archive`
extra = get_extra_linker_flags(version, compat_level, soname)
cmd = `$(bitflag()) $(march()) -shared -L$(julia_libdir()) -L$(julia_private_libdir()) -o $sysimage_path $o_file_flags $(Base.shell_split(ldlibs())) $extra`
run_compiler(cmd; cplusplus=true)
return nothing
end
function get_extra_linker_flags(version, compat_level, soname)
current_ver_arg = ``
compat_ver_arg = ``
if version !== nothing
compat_version = get_compat_version(version, compat_level)
current_ver_arg = `-current_version $version`
compat_ver_arg = `-compatibility_version $compat_version`
end
soname_arg = soname === nothing ? `` : `-Wl,-soname,$soname`
rpath_args = rpath_sysimage()
extra = Sys.iswindows() ? `-Wl,--export-all-symbols` :
Sys.isapple() ? `-fPIC $compat_ver_arg $current_ver_arg $rpath_args` :
Sys.isunix() ? `-fPIC $soname_arg $rpath_args` :
error("unknown machine type, not windows, macOS not UNIX")
return extra
end
function compile_c_init_julia(julia_init_c_file::String, sysimage_name::String, include_dir::String)
@debug "Compiling $julia_init_c_file"
flags = Base.shell_split(cflags())
o_init_file = splitext(julia_init_c_file)[1] * ".o"
cmd = `-c -I$include_dir -DJULIAC_PROGRAM_LIBNAME=$(repr(sysimage_name)) $TLS_SYNTAX $(bitflag()) $flags $(march()) -o $o_init_file $julia_init_c_file`
run_compiler(cmd)
return o_init_file
end
function try_rm_dir(dest_dir; force)
if isdir(dest_dir)
if !force
error("directory $(repr(dest_dir)) already exists, use `force=true` to overwrite (will completely",
" remove the directory)")
end
rm(dest_dir; force=true, recursive=true)
end
end
#######
# App #
#######
# Previously there was a slash.
# The slash was removed in https://github.com/JuliaLang/julia/pull/53978
const IS_OFFICIAL = Base.TAGGED_RELEASE_BANNER in ("Official https://julialang.org/ release", "Official https://julialang.org release")
function warn_official()
if !IS_OFFICIAL
@warn "PackageCompiler: This does not look like an official Julia build, functionality may suffer." _module=nothing _file=nothing
end
end
"""
create_app(package_dir::String, compiled_app::String; kwargs...)
Compile an app with the source in `package_dir` to the folder `compiled_app`.
The folder `package_dir` needs to contain a package where the package includes a
function with the signature
```julia
julia_main()::Cint
# Perhaps do something based on ARGS
...
end
```
The executable will be placed in a folder called `bin` in `compiled_app` and
when the executable run the `julia_main` function is called.
Note that since an app-specific `Project.toml` is placed in the `share/julia` folder in
`compiled_app`, it is generally *not* possible to install multiple unrelated apps to the
same location.
Standard Julia arguments are set by passing them after a `--julia-args`
argument, for example:
```
\$ ./MyApp input.csv --julia-args -O3 -t8
```
An attempt to automatically find a compiler will be done but can also be given
explicitly by setting the environment variable `JULIA_CC` to a path to a
compiler (can also include extra arguments to the compiler, like `-g`).
### Keyword arguments:
- `executables::Vector{Pair{String, String}}`: A list of executables to
produce, given as pairs of `executable_name => julia_main` where
`executable_name` is the name of the produced executable with the
julia function `julia_main`. If not provided, the name
of the package (as specified in `Project.toml`) is used and the main function
in julia is taken as `julia_main`.
- `precompile_execution_file::Union{String, Vector{String}}`: A file or list of
files that contain code from which precompilation statements should be recorded.
- `precompile_statements_file::Union{String, Vector{String}}`: A file or list of
files that contain precompilation statements that should be included in the sysimage
for the app.
- `incremental::Bool`: If `true`, build the new sysimage on top of the sysimage
of the current process otherwise build a new sysimage from scratch. Defaults to `false`.
- `filter_stdlibs::Bool`: If `true`, only include stdlibs that are in the project file.
Defaults to `false`, only set to `true` if you know the potential pitfalls.
- `force::Bool`: Remove the folder `compiled_app` if it exists before creating the app.
- `include_lazy_artifacts::Bool`: if lazy artifacts should be included in the bundled artifacts,
defaults to `false`.
- `include_transitive_dependencies::Bool`: If `true`, explicitly put all
transitive dependencies into the sysimage. This only makes a difference if some
packages do not load all their dependencies when themselves are loaded. Defaults to `true`.
- `include_preferences::Bool`: If `true`, store all preferences visible by the project in
`package_dir` in the app bundle. Defaults to `true`.
### Advanced keyword arguments
- `cpu_target::String`: The value to use for `JULIA_CPU_TARGET` when building the system image.
- `sysimage_build_args::Cmd`: A set of command line options that is used in the Julia process building the sysimage,
for example `-O1 --check-bounds=yes`.
- `script::String`: Path to a file that gets executed in the `--output-o` process.
"""
function create_app(package_dir::String,
app_dir::String;
executables::Union{Nothing, Vector{Pair{String, String}}}=nothing,
precompile_execution_file::Union{String, Vector{String}}=String[],
precompile_statements_file::Union{String, Vector{String}}=String[],
incremental::Bool=false,
filter_stdlibs::Bool=false,
force::Bool=false,
c_driver_program::String=String(DEFAULT_EMBEDDING_WRAPPER),
cpu_target::String=default_app_cpu_target(),
include_lazy_artifacts::Bool=false,
sysimage_build_args::Cmd=``,
include_transitive_dependencies::Bool=true,
include_preferences::Bool=true,
script::Union{Nothing, String}=nothing)
warn_official()
if filter_stdlibs && incremental
error("must use `incremental=false` to use `filter_stdlibs=true`")
end
# We call this at the very beginning to make sure that the user has a compiler available. Therefore, if no compiler
# is found, we throw an error immediately, instead of making the user wait a while before the error is thrown.
get_compiler_cmd()
ctx = create_pkg_context(package_dir)
ctx.env.pkg === nothing && error("expected package to have a `name` and `uuid`")
Pkg.instantiate(ctx, verbose=true, allow_autoprecomp = false)
if executables === nothing
executables = [ctx.env.pkg.name => "julia_main"]
end
try_rm_dir(app_dir; force)
stdlibs = gather_stdlibs_project(ctx)
if !filter_stdlibs
stdlibs = unique(vcat(stdlibs, stdlibs_in_sysimage()))
end
bundle_julia_libraries(app_dir, stdlibs)
bundle_julia_libexec(ctx, app_dir)
bundle_julia_executable(app_dir)
bundle_artifacts(ctx, app_dir; include_lazy_artifacts)
bundle_project(ctx, app_dir)
include_preferences && bundle_preferences(ctx, app_dir)
bundle_cert(app_dir)
sysimage_path = joinpath(app_dir, "lib", "julia", "sys." * Libdl.dlext)
package_name = ctx.env.pkg.name
project = dirname(ctx.env.project_file)
# add precompile statements for functions that will be called from the C main() wrapper
precompiles = String[]
for (_, julia_main) in executables
push!(precompiles, "@isdefined($package_name) || (import $package_name)")
push!(precompiles, "isdefined($package_name, :$julia_main) && precompile(Tuple{typeof($package_name.$julia_main)})")
end
push!(precompiles, "precompile(Tuple{typeof(append!), Vector{String}, Vector{Any}})")
push!(precompiles, "precompile(Tuple{typeof(empty!), Vector{String}})")
push!(precompiles, "precompile(Tuple{typeof(popfirst!), Vector{String}})")
create_sysimage([package_name]; sysimage_path, project,
incremental,
filter_stdlibs,
precompile_execution_file,
precompile_statements_file,
cpu_target,
sysimage_build_args,
include_transitive_dependencies,
extra_precompiles = join(precompiles, "\n"),
script)
for (app_name, julia_main) in executables
create_executable_from_sysimg(joinpath(app_dir, "bin", app_name), c_driver_program, string(package_name, ".", julia_main))
end
end
function create_executable_from_sysimg(exe_path::String,
c_driver_program::String,
julia_main::String)
c_driver_program = abspath(c_driver_program)
mkpath(dirname(exe_path))
flags = Base.shell_split(join((cflags(), ldflags(), ldlibs()), " "))
m = something(march(), ``)
cmd = `-DJULIA_MAIN=\"$julia_main\" $TLS_SYNTAX $(bitflag()) $m -o $(exe_path) $(c_driver_program) $(rpath_executable()) $flags`
run_compiler(cmd)
return nothing
end
###########
# Library #
###########
"""
create_library(package_or_project::String, dest_dir::String; kwargs...)
Compile a library with the source in `package_or_project` to the folder `dest_dir`.
The folder `package_or_project` should contain a package with C-callable functions,
e.g.
```
Base.@ccallable function julia_cg(fptr::Ptr{Cvoid}, cx::Ptr{Cdouble}, cb::Ptr{Cdouble}, len::Csize_t)::Cint
try
x = unsafe_wrap(Array, cx, (len,))
b = unsafe_wrap(Array, cb, (len,))
A = COp(fptr,len)
cg!(x, A, b)
catch
Base.invokelatest(Base.display_error, Base.catch_stack())
return 1
end
return 0
end
```
Alternatively, it can contain a project with dependencies that have C-callable functions.
The library will be placed in the `lib` folder in `dest_dir` (or `bin` on Windows),
and can be linked to and called into from C/C++ or other languages that can use C libraries.
Note that since a library-specific `Project.toml` is placed in the `share/julia` folder in
`dest_dir`, it is generally *not* possible to install multiple libraries to the same
location.
Note that any applications/programs linking to this library may need help finding
it at run time. Options include
* Installing all libraries somewhere in the library search path.
* Adding `/path/to/libname` to an appropriate library search path environment
variable (`DYLD_LIBRARY_PATH` on OSX, `PATH` on Windows, or `LD_LIBRARY_PATH`
on Linux/BSD/Unix).
* Running `install_name_tool -change libname /path/to/libname` (OSX)
To use any Julia exported functions, you *must* first call `init_julia(argc, argv)`,
where `argc` and `argv` are parameters that would normally be passed to `julia` on the
command line (e.g., to set up the number of threads or processes).
When your program is exiting, it is also suggested to call `shutdown_julia(retcode)`,
to allow Julia to cleanly clean up resources and call any finalizers. (This function
simply calls `jl_atexit_hook(retcode)`.)
An attempt to automatically find a compiler will be done but can also be given
explicitly by setting the environment variable `JULIA_CC` to a path to a
compiler (can also include extra arguments to the compiler, like `-g`).
### Keyword arguments:
- `lib_name::String`: an alternative name for the compiled library. If not provided,
the name of the package (as specified in Project.toml) is used. `lib` will be
prepended to the name if it is not already present.
- `precompile_execution_file::Union{String, Vector{String}}`: A file or list of
files that contain code from which precompilation statements should be recorded.
- `precompile_statements_file::Union{String, Vector{String}}`: A file or list of
files that contain precompilation statements that should be included in the sysimage
for the library.
- `incremental::Bool`: If `true`, build the new sysimage on top of the sysimage
of the current process otherwise build a new sysimage from scratch. Defaults to `false`.
- `filter_stdlibs::Bool`: If `true`, only include stdlibs that are in the project file.
Defaults to `false`, only set to `true` if you know the potential pitfalls.
- `force::Bool`: Remove the folder `compiled_lib` if it exists before creating the library.
- `header_files::Vector{String}`: A list of header files to include in the library bundle.
- `julia_init_c_file::::Union{String, Vector{String}}`: A file or list of files to include
in the system image with functions for initializing Julia from external code
(default: `PackageCompiler.default_julia_init()`).
- `julia_init_h_file::::Union{String, Vector{String}}`: A file or list of files to include
in the library bundle, with declarations for the functions defined in the file(s) provided
via `julia_init_c_file` (default: `PackageCompiler.default_julia_init_header()`).
- `version::VersionNumber`: Library version number. Added to the sysimg `.so` name
on Linux, and the `.dylib` name on Apple platforms, and with `compat_level`, used to
determine and set the `current_version`, `compatibility_version` (on Apple) and