-
Notifications
You must be signed in to change notification settings - Fork 285
feat(rust) add native link option #1685
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BjornTheProgrammer
wants to merge
4
commits into
bytecodealliance:main
Choose a base branch
from
BjornTheProgrammer:wit-native
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
ced97de
feat(rust) add native link option
BjornTheProgrammer 782f400
feat(rust) make link_native_symbols default
BjornTheProgrammer 3f87282
a
BjornTheProgrammer ae12065
feat(rust): identify native imports by module#name via a host resolver
BjornTheProgrammer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
| use wit_bindgen_core::abi; | ||
| use crate::abi; | ||
|
|
||
| fn hexdigit(v: u32) -> char { | ||
| if v < 10 { | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -894,6 +894,72 @@ extern crate std; | |
| /// }); | ||
| /// ``` | ||
| /// | ||
| /// ## Native (non-WebAssembly) targets | ||
| /// | ||
| /// Generated bindings also compile for native targets, which is useful for | ||
| /// testing component code without a wasm runtime or for building it as a | ||
| /// `cdylib` plugin. Native linkers don't accept the `:`, `/`, `#`, `[` and | ||
| /// `]` characters that canonical ABI symbol names use, so on native targets | ||
| /// symbols are hex-encoded with the scheme in | ||
| /// `wit_bindgen_core::symbol_name` (the same one the C++ generator uses). | ||
| /// | ||
| /// Imports are not resolved by the native linker. Each import calls through | ||
| /// a function pointer that starts out null and is looked up on first use | ||
| /// from a host-installed resolver: after loading the library a host calls | ||
| /// the exported `__wit_bindgen_set_import_resolver` function with a callback | ||
| /// that maps an import's core module and function names to a function | ||
| /// pointer with the import's core signature. Its signature is | ||
| /// | ||
| /// ```c | ||
| /// void __wit_bindgen_set_import_resolver( | ||
| /// void *(*resolver)(void *ctx, const char *import), | ||
| /// void *ctx); | ||
| /// ``` | ||
| /// | ||
| /// where `import` is the import's core module and function name joined by | ||
| /// `#` as one NUL-terminated string, e.g. `my:pkg/[email protected]#[method]res.frob` | ||
| /// (see `wit_bindgen::rt::ImportResolver`). Passing a null `resolver` | ||
| /// uninstalls the current one. | ||
| /// | ||
| /// This means everything links whether or not a host is present, the import | ||
| /// shims define no global symbols at all, and a host only needs to implement | ||
| /// the imports it cares about — calling an import the resolver doesn't | ||
| /// provide aborts with a message naming it. | ||
| /// | ||
| /// The resolver should be installed once, before any export is called: each | ||
| /// import caches the pointer it was given, so a later | ||
| /// `__wit_bindgen_set_import_resolver` call won't be seen by imports that | ||
| /// have already been resolved. The resolver is also shared by every | ||
| /// `generate!` invocation linked into the library and is keyed only by core | ||
| /// module and function name, so two worlds importing the same core name | ||
| /// necessarily get the same implementation. | ||
| /// | ||
| /// Exports, including post-return functions, async callbacks, and resource | ||
| /// destructors, are exported under their hex-encoded core export names. A | ||
| /// `__wit_bindgen_cabi_realloc` function is also exported so hosts can | ||
| /// allocate guest-owned memory when lowering arguments, as the canonical ABI | ||
| /// requires. That symbol and `__wit_bindgen_set_import_resolver` are defined | ||
| /// once in the `wit-bindgen` runtime crate rather than per world. | ||
| /// | ||
| /// Each world additionally exports a marker function | ||
| /// `const char *__wit_bindgen_world_<world>(void)`, where `<world>` is the | ||
| /// hex-encoded fully qualified world name including its package version and | ||
| /// `type_section_suffix`, e.g. `my:[email protected]/my-world`. Since `dlsym` can't | ||
| /// tell a host whether the library it opened implements the world it expects | ||
| /// — and the canonical ABI lowering of a world changes with the world, so | ||
| /// guessing wrong corrupts memory instead of failing cleanly — a host should | ||
| /// look this symbol up before installing a resolver or calling an export, and | ||
| /// treat a missing symbol as the wrong plugin. Calling it returns the world | ||
| /// name as a NUL-terminated string, for the resulting error message. | ||
| /// | ||
| /// This marker is keyed the same way as the `component-type` custom section a | ||
| /// wasm build emits, so the rules are the ones a wasm build already imposes. | ||
| /// Binding the same world twice needs a `type_section_suffix` to tell the | ||
| /// markers apart (plus `export_prefix` for the core export names). Two | ||
| /// *different* worlds sharing one fully qualified name is not a supported | ||
| /// configuration at all: here the linker rejects the duplicate marker, and on | ||
| /// wasm `wit-component` refuses to merge the two packages. | ||
| /// | ||
| /// [WIT package]: https://component-model.bytecodealliance.org/design/packages.html | ||
| #[cfg(feature = "macros")] | ||
| pub use wit_bindgen_rust_macro::generate; | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -153,7 +153,7 @@ pub fn maybe_link_cabi_realloc() { | |
| /// `cabi_realloc` module above. It's otherwise never explicitly called. | ||
| /// | ||
| /// For more information about this see `./ci/rebuild-libwit-bindgen-cabi.sh`. | ||
| #[cfg(any(target_env = "p1", target_env = ""))] | ||
| #[cfg(any(target_env = "p1", target_env = "", not(target_arch = "wasm32")))] | ||
| pub unsafe fn cabi_realloc( | ||
| old_ptr: *mut u8, | ||
| old_len: usize, | ||
|
|
@@ -192,6 +192,105 @@ pub unsafe fn cabi_realloc( | |
| return ptr; | ||
| } | ||
|
|
||
| /// Native (non-wasm) import resolution. | ||
| /// | ||
| /// On native targets imports aren't resolved by the linker. Each generated | ||
| /// import shim instead asks a host-installed resolver for its implementation | ||
| /// the first time it's called, identifying the import by its core module and | ||
| /// function name as plain strings. The host installs the resolver once per | ||
| /// loaded library through `__wit_bindgen_set_import_resolver`, so the import | ||
| /// shims define no global symbols at all and any number of `generate!` | ||
| /// invocations can share one resolver. (Export symbols and world markers are | ||
| /// a separate matter: those are global, so binding the same world twice in | ||
| /// one binary needs `export_prefix` and `type_section_suffix` respectively to | ||
| /// avoid duplicate symbols.) | ||
| /// | ||
| /// Because each shim caches the pointer the resolver handed it, installing a | ||
| /// resolver a second time has no effect on imports that have already been | ||
| /// called. Hosts are expected to install one before calling any export. | ||
| #[cfg(not(target_arch = "wasm32"))] | ||
| mod native_imports { | ||
| use core::ffi::{CStr, c_char}; | ||
| use core::sync::atomic::{AtomicPtr, Ordering}; | ||
|
|
||
| /// A host-provided callback returning the implementation of the import | ||
| /// named by `import`, or null if the host doesn't implement it. The | ||
| /// returned pointer must be a function with the import's core signature. | ||
| /// `ctx` is the value passed alongside the resolver, returned to the host | ||
| /// on every call. | ||
| /// | ||
| /// `import` is the import's canonical ABI core module and function name | ||
| /// joined by `#`, as a single NUL-terminated string — for example | ||
| /// `my:pkg/[email protected]#[method]res.frob`, or `$root#some-func` for a | ||
| /// function imported at the top level of a world. (Note the package | ||
| /// version trails the interface name here, unlike in a world name.) It | ||
| /// points into the guest's static data and stays valid for as long as the | ||
| /// library is loaded, so a host may use it as a lookup key without | ||
| /// copying it. | ||
| pub type ImportResolver = unsafe extern "C" fn(ctx: *mut (), import: *const c_char) -> *mut (); | ||
|
|
||
| static RESOLVER: AtomicPtr<()> = AtomicPtr::new(core::ptr::null_mut()); | ||
| static RESOLVER_CTX: AtomicPtr<()> = AtomicPtr::new(core::ptr::null_mut()); | ||
|
|
||
| /// Installs the import resolver for this linkage unit. Hosts call this | ||
| /// (typically via `dlsym`) after loading the library and before calling | ||
| /// any export. | ||
| /// | ||
| /// Passing `None` for `resolver` uninstalls the current one. That only | ||
| /// affects imports which haven't been resolved yet; imports already | ||
| /// called keep the pointer they cached. | ||
| #[unsafe(no_mangle)] | ||
| pub unsafe extern "C" fn __wit_bindgen_set_import_resolver( | ||
| resolver: Option<ImportResolver>, | ||
| ctx: *mut (), | ||
| ) { | ||
| let resolver = match resolver { | ||
| Some(resolver) => resolver as *mut (), | ||
| None => core::ptr::null_mut(), | ||
| }; | ||
| RESOLVER_CTX.store(ctx, Ordering::Relaxed); | ||
| // The release store of the resolver publishes the context above. | ||
| RESOLVER.store(resolver, Ordering::Release); | ||
| } | ||
|
|
||
| /// Called by generated import shims on their first invocation. | ||
| /// | ||
| /// `import` is the `module#name` string described on [`ImportResolver`]. | ||
| pub fn resolve_import(import: &CStr) -> *mut () { | ||
| let display = import.to_str().unwrap_or("<invalid utf-8>"); | ||
| let resolver = RESOLVER.load(Ordering::Acquire); | ||
| assert!( | ||
| !resolver.is_null(), | ||
| "import `{display}` was called before the host installed an \ | ||
| import resolver via `__wit_bindgen_set_import_resolver`" | ||
| ); | ||
| let ctx = RESOLVER_CTX.load(Ordering::Relaxed); | ||
| let resolver: ImportResolver = unsafe { core::mem::transmute(resolver) }; | ||
| let ptr = unsafe { resolver(ctx, import.as_ptr()) }; | ||
| assert!( | ||
| !ptr.is_null(), | ||
| "the host's import resolver provided no implementation for \ | ||
| import `{display}`" | ||
| ); | ||
| ptr | ||
| } | ||
|
|
||
| /// The guest allocator, exported so hosts can allocate guest-owned | ||
| /// memory when lowering data, as the canonical ABI requires. | ||
| #[unsafe(no_mangle)] | ||
| pub unsafe extern "C" fn __wit_bindgen_cabi_realloc( | ||
| old_ptr: *mut u8, | ||
| old_len: usize, | ||
| align: usize, | ||
| new_len: usize, | ||
| ) -> *mut u8 { | ||
| unsafe { crate::rt::cabi_realloc(old_ptr, old_len, align, new_len) } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(not(target_arch = "wasm32"))] | ||
| pub use native_imports::{ImportResolver, resolve_import}; | ||
|
|
||
| /// Provide a hook for generated export functions to run static constructors at | ||
| /// most once. | ||
| /// | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You might need to revert 8cde5ce
Now that you actually need
cabi_reallocfor native platforms as well.