Skip to content

Commit c22a3d4

Browse files
committed
Add Libdl.LazyLibrary
This provides an in-base mechanism to handle chained library dependencies. In essence, the `LazyLibrary` object can be used anywhere a pointer to a library can be used (`dlopen`, `dlsym`, `ccall`, etc...) but it delays loading the library (and its recursive dependencies) until it is actually needed. This is the foundational piece needed to upgrade JLLs to lazily-load their libraries. In this new scheme, JLLs would generally lose all executable code and consist of nothing more than `LazyLibrary` definitions.
1 parent 0919cba commit c22a3d4

File tree

19 files changed

+286
-56
lines changed

19 files changed

+286
-56
lines changed

Makefile

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,12 @@ julia-base: julia-deps $(build_sysconfdir)/julia/startup.jl $(build_man1dir)/jul
8484
julia-libccalltest: julia-deps
8585
@$(MAKE) $(QUIET_MAKE) -C $(BUILDROOT)/src libccalltest
8686

87+
julia-libccalllazyfoo: julia-deps
88+
@$(MAKE) $(QUIET_MAKE) -C $(BUILDROOT)/src libccalllazyfoo
89+
90+
julia-libccalllazybar: julia-deps julia-libccalllazyfoo
91+
@$(MAKE) $(QUIET_MAKE) -C $(BUILDROOT)/src libccalllazybar
92+
8793
julia-libllvmcalltest: julia-deps
8894
@$(MAKE) $(QUIET_MAKE) -C $(BUILDROOT)/src libllvmcalltest
8995

@@ -102,7 +108,8 @@ julia-sysimg-bc : julia-stdlib julia-base julia-cli-$(JULIA_BUILD_MODE) julia-sr
102108
julia-sysimg-release julia-sysimg-debug : julia-sysimg-% : julia-sysimg-ji julia-src-%
103109
@$(MAKE) $(QUIET_MAKE) -C $(BUILDROOT) -f sysimage.mk sysimg-$*
104110

105-
julia-debug julia-release : julia-% : julia-sysimg-% julia-src-% julia-symlink julia-libccalltest julia-libllvmcalltest julia-base-cache
111+
julia-debug julia-release : julia-% : julia-sysimg-% julia-src-% julia-symlink julia-libccalltest \
112+
julia-libccalllazyfoo julia-libccalllazybar julia-libllvmcalltest julia-base-cache
106113

107114
stdlibs-cache-release stdlibs-cache-debug : stdlibs-cache-% : julia-%
108115
@$(MAKE) $(QUIET_MAKE) -C $(BUILDROOT) -f pkgimage.mk all-$*
@@ -189,7 +196,7 @@ JL_TARGETS := julia-debug
189196
endif
190197

191198
# private libraries, that are installed in $(prefix)/lib/julia
192-
JL_PRIVATE_LIBS-0 := libccalltest libllvmcalltest
199+
JL_PRIVATE_LIBS-0 := libccalltest libccalllazyfoo libccalllazybar libllvmcalltest
193200
ifeq ($(JULIA_BUILD_MODE),release)
194201
JL_PRIVATE_LIBS-0 += libjulia-internal libjulia-codegen
195202
else ifeq ($(JULIA_BUILD_MODE),debug)

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ Compiler/Runtime improvements
2727

2828
* The `@pure` macro is now deprecated. Use `Base.@assume_effects :foldable` instead ([#48682]).
2929
* The mark phase of the Garbage Collector is now multi-threaded ([#48600]).
30+
* A new `LazyLibrary` type is exported from `Libdl` for use in building chained lazy library
31+
loads, primarily to be used within JLLs ([#50074]).
3032

3133
Command-line option changes
3234
---------------------------

base/Base.jl

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,12 @@ include("missing.jl")
314314
# version
315315
include("version.jl")
316316

317+
# Concurrency (part 1)
318+
include("linked_list.jl")
319+
include("condition.jl")
320+
include("threads.jl")
321+
include("lock.jl")
322+
317323
# system & environment
318324
include("sysinfo.jl")
319325
include("libc.jl")
@@ -328,11 +334,9 @@ const liblapack_name = libblas_name
328334
include("logging.jl")
329335
using .CoreLogging
330336

331-
# Concurrency
332-
include("linked_list.jl")
333-
include("condition.jl")
334-
include("threads.jl")
335-
include("lock.jl")
337+
# Concurrency (part 2)
338+
# Note that `atomics.jl` here should be deprecated
339+
Core.eval(Threads, :(include("atomics.jl")))
336340
include("channels.jl")
337341
include("partr.jl")
338342
include("task.jl")

base/libdl.jl

Lines changed: 102 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import Base.DL_LOAD_PATH
99

1010
export DL_LOAD_PATH, RTLD_DEEPBIND, RTLD_FIRST, RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL,
1111
RTLD_NODELETE, RTLD_NOLOAD, RTLD_NOW, dlclose, dlopen, dlopen_e, dlsym, dlsym_e,
12-
dlpath, find_library, dlext, dllist
12+
dlpath, find_library, dlext, dllist, LazyLibrary, LazyStringFunc
1313

1414
"""
1515
DL_LOAD_PATH
@@ -45,6 +45,9 @@ applicable.
4545
"""
4646
(RTLD_DEEPBIND, RTLD_FIRST, RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, RTLD_NODELETE, RTLD_NOLOAD, RTLD_NOW)
4747

48+
# The default flags for `dlopen()`
49+
const default_rtld_flags = RTLD_LAZY | RTLD_DEEPBIND
50+
4851
"""
4952
dlsym(handle, sym; throw_error::Bool = true)
5053
@@ -72,8 +75,8 @@ end
7275
Look up a symbol from a shared library handle, silently return `C_NULL` on lookup failure.
7376
This method is now deprecated in favor of `dlsym(handle, sym; throw_error=false)`.
7477
"""
75-
function dlsym_e(hnd::Ptr, s::Union{Symbol,AbstractString})
76-
return something(dlsym(hnd, s; throw_error=false), C_NULL)
78+
function dlsym_e(args...)
79+
return something(dlsym(args...; throw_error=false), C_NULL)
7780
end
7881

7982
"""
@@ -110,10 +113,10 @@ If the library cannot be found, this method throws an error, unless the keyword
110113
"""
111114
function dlopen end
112115

113-
dlopen(s::Symbol, flags::Integer = RTLD_LAZY | RTLD_DEEPBIND; kwargs...) =
116+
dlopen(s::Symbol, flags::Integer = default_rtld_flags; kwargs...) =
114117
dlopen(string(s), flags; kwargs...)
115118

116-
function dlopen(s::AbstractString, flags::Integer = RTLD_LAZY | RTLD_DEEPBIND; throw_error::Bool = true)
119+
function dlopen(s::AbstractString, flags::Integer = default_rtld_flags; throw_error::Bool = true)
117120
ret = ccall(:jl_load_dynamic_library, Ptr{Cvoid}, (Cstring,UInt32,Cint), s, flags, Cint(throw_error))
118121
if ret == C_NULL
119122
return nothing
@@ -314,4 +317,98 @@ function dllist()
314317
return dynamic_libraries
315318
end
316319

320+
321+
const LazyLibraryLock = Base.ReentrantLock()
322+
"""
323+
LazyLibrary(name, flags = <default dlopen flags>,
324+
dependencies = LazyLibrary[], on_load_callback = nothing)
325+
326+
Represents a lazily-loaded library that opens itself and its dependencies on first usage
327+
in a `dlopen()`, `dlsym()`, or `ccall()` usage. While this structure contains the
328+
ability to run arbitrary code on first load via `on_load_callback`, we caution that this
329+
should be used sparingly, as it is not expected that `ccall()` should result in large
330+
amounts of Julia code being run. You may call `ccall()` from within the
331+
`on_load_callback` but only for the current library and its dependencies.
332+
"""
333+
mutable struct LazyLibrary
334+
# Name and flags to open with
335+
const name::AbstractString
336+
const flags::UInt32
337+
338+
# Dependencies that must be loaded before we can load
339+
dependencies::Vector{LazyLibrary}
340+
341+
# Function that gets called once upon initial load with the pointer as an argument
342+
on_load_callback::Union{Nothing,Function}
343+
344+
# Pointer that we eventually fill out upon first `dlopen()`
345+
@atomic handle::Ptr{Cvoid}
346+
function LazyLibrary(name; flags = default_rtld_flags, dependencies = LazyLibrary[],
347+
on_load_callback = nothing)
348+
return new(
349+
name,
350+
UInt32(flags),
351+
collect(dependencies),
352+
on_load_callback,
353+
C_NULL,
354+
)
355+
end
356+
end
357+
358+
# Register this LazyLibrary type with the C code during bootstrap,
359+
# so that `ccall()` lowering knows what a `LazyLibrary` is, and how
360+
# to `dlopen()` it. This hack brought to you by Valentin. \[0_o]/
361+
Base.unsafe_store!(cglobal(:jl_lazy_library_type, Any), LazyLibrary)
362+
Base.unsafe_store!(cglobal(:jl_libdl_dlopen_func, Any), dlopen)
363+
364+
"""
365+
LazyStringFunc
366+
367+
Helper type for `LazyString` to be used with `LazyLibrary` so that runtime-generated
368+
library paths can be used with lazy libraries. Note that the value will only be computed
369+
once; it is cached after initial computation. Typical usage:
370+
371+
```
372+
libfoo = LazyLibrary(LazyStringFunc(() -> joinpath(artifact"foo/lib/libfoo.so.1.2.3")))
373+
```
374+
"""
375+
LazyStringFunc(f) = LazyString(_LazyStringFunc(f))
376+
377+
struct _LazyStringFunc <: AbstractString
378+
f::Function
379+
end
380+
Base.print(io::IO, lsf::_LazyStringFunc) = print(io, lsf.f())
381+
382+
function dlopen(ll::LazyLibrary, flags::Integer = ll.flags; kwargs...)
383+
handle = @atomic :acquire ll.handle
384+
if handle != C_NULL
385+
return handle
386+
end
387+
388+
# Ensure that all dependencies are loaded
389+
for dep in ll.dependencies
390+
dlopen(dep; kwargs...)
391+
end
392+
393+
# Only let a single thread run callbacks at a time
394+
@lock LazyLibraryLock begin
395+
# Check to see if another thread has already run this
396+
handle = @atomic :acquire ll.handle
397+
if handle == C_NULL
398+
# Load our library
399+
handle = dlopen(ll.name, flags; kwargs...)
400+
401+
# Invoke our on load callback, if it exists
402+
if ll.on_load_callback !== nothing
403+
ll.on_load_callback(handle)
404+
end
405+
406+
@atomic :release ll.handle = handle
407+
end
408+
end
409+
410+
return handle
411+
end
412+
dlsym(ll::LazyLibrary, args...; kwargs...) = dlsym(dlopen(ll), args...; kwargs...)
413+
dlpath(ll::LazyLibrary) = dlpath(dlopen(ll))
317414
end # module Libdl

base/threads.jl

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ module Threads
88
global Condition # we'll define this later, make sure we don't import Base.Condition
99

1010
include("threadingconstructs.jl")
11-
include("atomics.jl")
1211
include("locks-mt.jl")
1312

1413
end

doc/src/devdocs/locks.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ may result in pernicious and hard-to-find deadlocks. BE VERY CAREFUL!
9191
>
9292
> > this may continue to be held after releasing the iolock, or acquired without it,
9393
> > but be very careful to never attempt to acquire the iolock while holding it
94+
>
95+
> * Libdl.LazyLibrary lock
9496
9597

9698
The following is the root lock, meaning no other lock shall be held when trying to acquire it:

src/Makefile

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,8 @@ $(build_includedir)/julia/uv/*.h: $(LIBUV_INC)/uv/*.h | $(build_includedir)/juli
249249
$(INSTALL_F) $^ $(build_includedir)/julia/uv
250250

251251
libccalltest: $(build_shlibdir)/libccalltest.$(SHLIB_EXT)
252+
libccalllazyfoo: $(build_shlibdir)/libccalllazyfoo.$(SHLIB_EXT)
253+
libccalllazybar: $(build_shlibdir)/libccalllazybar.$(SHLIB_EXT)
252254
libllvmcalltest: $(build_shlibdir)/libllvmcalltest.$(SHLIB_EXT)
253255

254256
ifeq ($(OS), Linux)
@@ -273,6 +275,12 @@ endif
273275
274276
$(INSTALL_NAME_CMD)libccalltest.$(SHLIB_EXT) $@
275277

278+
$(build_shlibdir)/libccalllazyfoo.$(SHLIB_EXT): $(SRCDIR)/ccalllazyfoo.c
279+
@$(call PRINT_CC, $(CC) $(JCFLAGS) $(JL_CFLAGS) $(JCPPFLAGS) $(FLAGS) -O3 $< $(fPIC) -shared -o $@ $(LDFLAGS) $(COMMON_LIBPATHS) $(call SONAME_FLAGS,ccalllazyfoo.$(SHLIB_EXT)))
280+
281+
$(build_shlibdir)/libccalllazybar.$(SHLIB_EXT): $(SRCDIR)/ccalllazybar.c $(build_shlibdir)/libccalllazyfoo.$(SHLIB_EXT)
282+
@$(call PRINT_CC, $(CC) $(JCFLAGS) $(JL_CFLAGS) $(JCPPFLAGS) $(FLAGS) -O3 $< $(fPIC) -shared -o $@ $(LDFLAGS) $(COMMON_LIBPATHS) $(call SONAME_FLAGS,ccalllazybar.$(SHLIB_EXT)) -lccalllazyfoo)
283+
276284
$(build_shlibdir)/libllvmcalltest.$(SHLIB_EXT): $(SRCDIR)/llvmcalltest.cpp $(LLVM_CONFIG_ABSOLUTE)
277285
@$(call PRINT_CC, $(CXX) $(LLVM_CXXFLAGS) $(FLAGS) $(CPPFLAGS) $(CXXFLAGS) -O3 $< $(fPIC) -shared -o $@ $(LDFLAGS) $(COMMON_LIBPATHS) $(NO_WHOLE_ARCHIVE) $(CG_LLVMLINK)) -lpthread
278286

src/ccall.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -651,6 +651,9 @@ static void interpret_symbol_arg(jl_codectx_t &ctx, native_sym_arg_t &out, jl_va
651651
f_lib = jl_symbol_name((jl_sym_t*)t1);
652652
else if (jl_is_string(t1))
653653
f_lib = jl_string_data(t1);
654+
else if (jl_lazy_library_type != NULL && jl_isa(t1, (jl_value_t *)jl_lazy_library_type)) {
655+
out.lib_expr = t1;
656+
}
654657
else
655658
f_name = NULL;
656659
}

src/ccalllazybar.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// This file is a part of Julia. License is MIT: https://julialang.org/license
2+
3+
#include "ccalltest_common.h"
4+
5+
// We expect this to come from `libccalllazyfoo`
6+
extern int foo(int);
7+
8+
DLLEXPORT int bar(int a) {
9+
return foo(a + 1);
10+
}

src/ccalllazyfoo.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// This file is a part of Julia. License is MIT: https://julialang.org/license
2+
3+
#include "ccalltest_common.h"
4+
5+
DLLEXPORT int foo(int a) {
6+
return a*2;
7+
}

0 commit comments

Comments
 (0)