Rename SimpleJIT to JIT as it isn't simple anymore
This commit is contained in:
38
cranelift/jit/Cargo.toml
Normal file
38
cranelift/jit/Cargo.toml
Normal file
@@ -0,0 +1,38 @@
|
||||
[package]
|
||||
name = "cranelift-jit"
|
||||
version = "0.68.0"
|
||||
authors = ["The Cranelift Project Developers"]
|
||||
description = "A JIT library backed by Cranelift"
|
||||
repository = "https://github.com/bytecodealliance/wasmtime"
|
||||
documentation = "https://docs.rs/cranelift-jit"
|
||||
license = "Apache-2.0 WITH LLVM-exception"
|
||||
readme = "README.md"
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
cranelift-module = { path = "../module", version = "0.68.0" }
|
||||
cranelift-native = { path = "../native", version = "0.68.0" }
|
||||
cranelift-codegen = { path = "../codegen", version = "0.68.0", default-features = false, features = ["std"] }
|
||||
cranelift-entity = { path = "../entity", version = "0.68.0" }
|
||||
anyhow = "1.0"
|
||||
region = "2.2.0"
|
||||
libc = { version = "0.2.42" }
|
||||
errno = "0.2.4"
|
||||
target-lexicon = "0.11"
|
||||
memmap = { version = "0.7.0", optional = true }
|
||||
log = { version = "0.4.6", default-features = false }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
winapi = { version = "0.3", features = ["winbase", "memoryapi"] }
|
||||
|
||||
[features]
|
||||
selinux-fix = ['memmap']
|
||||
default = []
|
||||
|
||||
[dev-dependencies]
|
||||
cranelift = { path = "../umbrella", version = "0.68.0" }
|
||||
cranelift-frontend = { path = "../frontend", version = "0.68.0" }
|
||||
cranelift-entity = { path = "../entity", version = "0.68.0" }
|
||||
|
||||
[badges]
|
||||
maintenance = { status = "experimental" }
|
||||
220
cranelift/jit/LICENSE
Normal file
220
cranelift/jit/LICENSE
Normal file
@@ -0,0 +1,220 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
|
||||
--- LLVM Exceptions to the Apache 2.0 License ----
|
||||
|
||||
As an exception, if, as a result of your compiling your source code, portions
|
||||
of this Software are embedded into an Object form of such source code, you
|
||||
may redistribute such embedded portions in such Object form without complying
|
||||
with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
|
||||
|
||||
In addition, if you combine or link compiled forms of this Software with
|
||||
software that is licensed under the GPLv2 ("Combined Software") and if a
|
||||
court of competent jurisdiction determines that the patent provision (Section
|
||||
3), the indemnity provision (Section 9) or other Section of the License
|
||||
conflicts with the conditions of the GPLv2, you may retroactively and
|
||||
prospectively choose to deem waived or otherwise exclude such Section(s) of
|
||||
the License, but only in their entirety and only with respect to the Combined
|
||||
Software.
|
||||
|
||||
8
cranelift/jit/README.md
Normal file
8
cranelift/jit/README.md
Normal file
@@ -0,0 +1,8 @@
|
||||
This crate provides a JIT library that uses
|
||||
[Cranelift](https://crates.io/crates/cranelift).
|
||||
|
||||
This crate is extremely experimental.
|
||||
|
||||
See the [example program] for a brief overview of how to use this.
|
||||
|
||||
[example program]: https://github.com/bytecodealliance/wasmtime/blob/main/cranelift/jit/examples/jit-minimal.rs
|
||||
94
cranelift/jit/examples/jit-minimal.rs
Normal file
94
cranelift/jit/examples/jit-minimal.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
use cranelift::prelude::*;
|
||||
use cranelift_codegen::binemit::NullTrapSink;
|
||||
use cranelift_codegen::settings::{self, Configurable};
|
||||
use cranelift_jit::{JITBuilder, JITModule};
|
||||
use cranelift_module::{default_libcall_names, Linkage, Module};
|
||||
use std::mem;
|
||||
|
||||
fn main() {
|
||||
let mut flag_builder = settings::builder();
|
||||
flag_builder.set("use_colocated_libcalls", "false").unwrap();
|
||||
// FIXME set back to true once the x64 backend supports it.
|
||||
flag_builder.set("is_pic", "false").unwrap();
|
||||
let isa_builder = cranelift_native::builder().unwrap_or_else(|msg| {
|
||||
panic!("host machine is not supported: {}", msg);
|
||||
});
|
||||
let isa = isa_builder.finish(settings::Flags::new(flag_builder));
|
||||
let mut module = JITModule::new(JITBuilder::with_isa(isa, default_libcall_names()));
|
||||
|
||||
let mut ctx = module.make_context();
|
||||
let mut func_ctx = FunctionBuilderContext::new();
|
||||
|
||||
let mut sig_a = module.make_signature();
|
||||
sig_a.params.push(AbiParam::new(types::I32));
|
||||
sig_a.returns.push(AbiParam::new(types::I32));
|
||||
|
||||
let mut sig_b = module.make_signature();
|
||||
sig_b.returns.push(AbiParam::new(types::I32));
|
||||
|
||||
let func_a = module
|
||||
.declare_function("a", Linkage::Local, &sig_a)
|
||||
.unwrap();
|
||||
let func_b = module
|
||||
.declare_function("b", Linkage::Local, &sig_b)
|
||||
.unwrap();
|
||||
|
||||
ctx.func.signature = sig_a;
|
||||
ctx.func.name = ExternalName::user(0, func_a.as_u32());
|
||||
{
|
||||
let mut bcx: FunctionBuilder = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
|
||||
let block = bcx.create_block();
|
||||
|
||||
bcx.switch_to_block(block);
|
||||
bcx.append_block_params_for_function_params(block);
|
||||
let param = bcx.block_params(block)[0];
|
||||
let cst = bcx.ins().iconst(types::I32, 37);
|
||||
let add = bcx.ins().iadd(cst, param);
|
||||
bcx.ins().return_(&[add]);
|
||||
bcx.seal_all_blocks();
|
||||
bcx.finalize();
|
||||
}
|
||||
let mut trap_sink = NullTrapSink {};
|
||||
module
|
||||
.define_function(func_a, &mut ctx, &mut trap_sink)
|
||||
.unwrap();
|
||||
module.clear_context(&mut ctx);
|
||||
|
||||
ctx.func.signature = sig_b;
|
||||
ctx.func.name = ExternalName::user(0, func_b.as_u32());
|
||||
{
|
||||
let mut bcx: FunctionBuilder = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
|
||||
let block = bcx.create_block();
|
||||
|
||||
bcx.switch_to_block(block);
|
||||
let local_func = module.declare_func_in_func(func_a, &mut bcx.func);
|
||||
let arg = bcx.ins().iconst(types::I32, 5);
|
||||
let call = bcx.ins().call(local_func, &[arg]);
|
||||
let value = {
|
||||
let results = bcx.inst_results(call);
|
||||
assert_eq!(results.len(), 1);
|
||||
results[0].clone()
|
||||
};
|
||||
bcx.ins().return_(&[value]);
|
||||
bcx.seal_all_blocks();
|
||||
bcx.finalize();
|
||||
}
|
||||
module
|
||||
.define_function(func_b, &mut ctx, &mut trap_sink)
|
||||
.unwrap();
|
||||
module.clear_context(&mut ctx);
|
||||
|
||||
// Perform linking.
|
||||
module.finalize_definitions();
|
||||
|
||||
// Get a raw pointer to the generated code.
|
||||
let code_b = module.get_finalized_function(func_b);
|
||||
|
||||
// Cast it to a rust function pointer type.
|
||||
let ptr_b = unsafe { mem::transmute::<_, fn() -> u32>(code_b) };
|
||||
|
||||
// Call it!
|
||||
let res = ptr_b();
|
||||
|
||||
assert_eq!(res, 42);
|
||||
}
|
||||
897
cranelift/jit/src/backend.rs
Normal file
897
cranelift/jit/src/backend.rs
Normal file
@@ -0,0 +1,897 @@
|
||||
//! Defines `JITModule`.
|
||||
|
||||
use crate::{compiled_blob::CompiledBlob, memory::Memory};
|
||||
use cranelift_codegen::isa::TargetIsa;
|
||||
use cranelift_codegen::settings::Configurable;
|
||||
use cranelift_codegen::{self, ir, settings};
|
||||
use cranelift_codegen::{
|
||||
binemit::{self, Addend, CodeInfo, CodeOffset, Reloc, RelocSink, TrapSink},
|
||||
CodegenError,
|
||||
};
|
||||
use cranelift_entity::SecondaryMap;
|
||||
use cranelift_module::{
|
||||
DataContext, DataDescription, DataId, FuncId, Init, Linkage, Module, ModuleCompiledFunction,
|
||||
ModuleDeclarations, ModuleError, ModuleResult, RelocRecord,
|
||||
};
|
||||
use cranelift_native;
|
||||
#[cfg(not(windows))]
|
||||
use libc;
|
||||
use log::info;
|
||||
use std::collections::HashMap;
|
||||
use std::convert::{TryFrom, TryInto};
|
||||
use std::ffi::CString;
|
||||
use std::io::Write;
|
||||
use std::ptr;
|
||||
use std::ptr::NonNull;
|
||||
use target_lexicon::PointerWidth;
|
||||
#[cfg(windows)]
|
||||
use winapi;
|
||||
|
||||
const EXECUTABLE_DATA_ALIGNMENT: u64 = 0x10;
|
||||
const WRITABLE_DATA_ALIGNMENT: u64 = 0x8;
|
||||
const READONLY_DATA_ALIGNMENT: u64 = 0x1;
|
||||
|
||||
/// A builder for `JITModule`.
|
||||
pub struct JITBuilder {
|
||||
isa: Box<dyn TargetIsa>,
|
||||
symbols: HashMap<String, *const u8>,
|
||||
libcall_names: Box<dyn Fn(ir::LibCall) -> String + Send + Sync>,
|
||||
hotswap_enabled: bool,
|
||||
}
|
||||
|
||||
impl JITBuilder {
|
||||
/// Create a new `JITBuilder`.
|
||||
///
|
||||
/// The `libcall_names` function provides a way to translate `cranelift_codegen`'s `ir::LibCall`
|
||||
/// enum to symbols. LibCalls are inserted in the IR as part of the legalization for certain
|
||||
/// floating point instructions, and for stack probes. If you don't know what to use for this
|
||||
/// argument, use `cranelift_module::default_libcall_names()`.
|
||||
pub fn new(libcall_names: Box<dyn Fn(ir::LibCall) -> String + Send + Sync>) -> Self {
|
||||
let mut flag_builder = settings::builder();
|
||||
// On at least AArch64, "colocated" calls use shorter-range relocations,
|
||||
// which might not reach all definitions; we can't handle that here, so
|
||||
// we require long-range relocation types.
|
||||
flag_builder.set("use_colocated_libcalls", "false").unwrap();
|
||||
flag_builder.set("is_pic", "true").unwrap();
|
||||
let isa_builder = cranelift_native::builder().unwrap_or_else(|msg| {
|
||||
panic!("host machine is not supported: {}", msg);
|
||||
});
|
||||
let isa = isa_builder.finish(settings::Flags::new(flag_builder));
|
||||
Self::with_isa(isa, libcall_names)
|
||||
}
|
||||
|
||||
/// Create a new `JITBuilder` with an arbitrary target. This is mainly
|
||||
/// useful for testing.
|
||||
///
|
||||
/// To create a `JITBuilder` for native use, use the `new` constructor
|
||||
/// instead.
|
||||
///
|
||||
/// The `libcall_names` function provides a way to translate `cranelift_codegen`'s `ir::LibCall`
|
||||
/// enum to symbols. LibCalls are inserted in the IR as part of the legalization for certain
|
||||
/// floating point instructions, and for stack probes. If you don't know what to use for this
|
||||
/// argument, use `cranelift_module::default_libcall_names()`.
|
||||
pub fn with_isa(
|
||||
isa: Box<dyn TargetIsa>,
|
||||
libcall_names: Box<dyn Fn(ir::LibCall) -> String + Send + Sync>,
|
||||
) -> Self {
|
||||
let symbols = HashMap::new();
|
||||
Self {
|
||||
isa,
|
||||
symbols,
|
||||
libcall_names,
|
||||
hotswap_enabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Define a symbol in the internal symbol table.
|
||||
///
|
||||
/// The JIT will use the symbol table to resolve names that are declared,
|
||||
/// but not defined, in the module being compiled. A common example is
|
||||
/// external functions. With this method, functions and data can be exposed
|
||||
/// to the code being compiled which are defined by the host.
|
||||
///
|
||||
/// If a symbol is defined more than once, the most recent definition will
|
||||
/// be retained.
|
||||
///
|
||||
/// If the JIT fails to find a symbol in its internal table, it will fall
|
||||
/// back to a platform-specific search (this typically involves searching
|
||||
/// the current process for public symbols, followed by searching the
|
||||
/// platform's C runtime).
|
||||
pub fn symbol<K>(&mut self, name: K, ptr: *const u8) -> &Self
|
||||
where
|
||||
K: Into<String>,
|
||||
{
|
||||
self.symbols.insert(name.into(), ptr);
|
||||
self
|
||||
}
|
||||
|
||||
/// Define multiple symbols in the internal symbol table.
|
||||
///
|
||||
/// Using this is equivalent to calling `symbol` on each element.
|
||||
pub fn symbols<It, K>(&mut self, symbols: It) -> &Self
|
||||
where
|
||||
It: IntoIterator<Item = (K, *const u8)>,
|
||||
K: Into<String>,
|
||||
{
|
||||
for (name, ptr) in symbols {
|
||||
self.symbols.insert(name.into(), ptr);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Enable or disable hotswap support. See [`JITModule::prepare_for_function_redefine`]
|
||||
/// for more information.
|
||||
///
|
||||
/// Enabling hotswap support requires PIC code.
|
||||
pub fn hotswap(&mut self, enabled: bool) -> &mut Self {
|
||||
self.hotswap_enabled = enabled;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A `JITModule` implements `Module` and emits code and data into memory where it can be
|
||||
/// directly called and accessed.
|
||||
///
|
||||
/// See the `JITBuilder` for a convenient way to construct `JITModule` instances.
|
||||
pub struct JITModule {
|
||||
isa: Box<dyn TargetIsa>,
|
||||
hotswap_enabled: bool,
|
||||
symbols: HashMap<String, *const u8>,
|
||||
libcall_names: Box<dyn Fn(ir::LibCall) -> String>,
|
||||
memory: MemoryHandle,
|
||||
declarations: ModuleDeclarations,
|
||||
function_got_entries: SecondaryMap<FuncId, Option<NonNull<*const u8>>>,
|
||||
function_plt_entries: SecondaryMap<FuncId, Option<NonNull<[u8; 16]>>>,
|
||||
data_object_got_entries: SecondaryMap<DataId, Option<NonNull<*const u8>>>,
|
||||
libcall_got_entries: HashMap<ir::LibCall, NonNull<*const u8>>,
|
||||
libcall_plt_entries: HashMap<ir::LibCall, NonNull<[u8; 16]>>,
|
||||
compiled_functions: SecondaryMap<FuncId, Option<CompiledBlob>>,
|
||||
compiled_data_objects: SecondaryMap<DataId, Option<CompiledBlob>>,
|
||||
functions_to_finalize: Vec<FuncId>,
|
||||
data_objects_to_finalize: Vec<DataId>,
|
||||
}
|
||||
|
||||
/// A handle to allow freeing memory allocated by the `Module`.
|
||||
struct MemoryHandle {
|
||||
code: Memory,
|
||||
readonly: Memory,
|
||||
writable: Memory,
|
||||
}
|
||||
|
||||
impl JITModule {
|
||||
/// Free memory allocated for code and data segments of compiled functions.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// Because this function invalidates any pointers retrived from the
|
||||
/// corresponding module, it should only be used when none of the functions
|
||||
/// from that module are currently executing and none of the `fn` pointers
|
||||
/// are called afterwards.
|
||||
pub unsafe fn free_memory(&mut self) {
|
||||
self.memory.code.free_memory();
|
||||
self.memory.readonly.free_memory();
|
||||
self.memory.writable.free_memory();
|
||||
}
|
||||
|
||||
fn lookup_symbol(&self, name: &str) -> Option<*const u8> {
|
||||
self.symbols
|
||||
.get(name)
|
||||
.copied()
|
||||
.or_else(|| lookup_with_dlsym(name))
|
||||
}
|
||||
|
||||
unsafe fn write_plt_entry_bytes(plt_ptr: *mut [u8; 16], got_ptr: *mut *const u8) {
|
||||
assert!(
|
||||
cfg!(target_arch = "x86_64"),
|
||||
"PLT is currently only supported on x86_64"
|
||||
);
|
||||
// jmp *got_ptr; ud2; ud2; ud2; ud2; ud2
|
||||
let mut plt_val = [
|
||||
0xff, 0x25, 0, 0, 0, 0, 0x0f, 0x0b, 0x0f, 0x0b, 0x0f, 0x0b, 0x0f, 0x0b, 0x0f, 0x0b,
|
||||
];
|
||||
let what = got_ptr as isize - 4;
|
||||
let at = plt_ptr as isize + 2;
|
||||
plt_val[2..6].copy_from_slice(&i32::to_ne_bytes(i32::try_from(what - at).unwrap()));
|
||||
std::ptr::write(plt_ptr, plt_val);
|
||||
}
|
||||
|
||||
fn get_address(&self, name: &ir::ExternalName) -> *const u8 {
|
||||
match *name {
|
||||
ir::ExternalName::User { .. } => {
|
||||
let (name, linkage) = if ModuleDeclarations::is_function(name) {
|
||||
if self.hotswap_enabled {
|
||||
return self.get_plt_address(name);
|
||||
} else {
|
||||
let func_id = FuncId::from_name(name);
|
||||
match &self.compiled_functions[func_id] {
|
||||
Some(compiled) => return compiled.ptr,
|
||||
None => {
|
||||
let decl = self.declarations.get_function_decl(func_id);
|
||||
(&decl.name, decl.linkage)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let data_id = DataId::from_name(name);
|
||||
match &self.compiled_data_objects[data_id] {
|
||||
Some(compiled) => return compiled.ptr,
|
||||
None => {
|
||||
let decl = self.declarations.get_data_decl(data_id);
|
||||
(&decl.name, decl.linkage)
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(ptr) = self.lookup_symbol(&name) {
|
||||
ptr
|
||||
} else if linkage == Linkage::Preemptible {
|
||||
0 as *const u8
|
||||
} else {
|
||||
panic!("can't resolve symbol {}", name);
|
||||
}
|
||||
}
|
||||
ir::ExternalName::LibCall(ref libcall) => {
|
||||
let sym = (self.libcall_names)(*libcall);
|
||||
self.lookup_symbol(&sym)
|
||||
.unwrap_or_else(|| panic!("can't resolve libcall {}", sym))
|
||||
}
|
||||
_ => panic!("invalid ExternalName {}", name),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_got_address(&self, name: &ir::ExternalName) -> *const u8 {
|
||||
match *name {
|
||||
ir::ExternalName::User { .. } => {
|
||||
if ModuleDeclarations::is_function(name) {
|
||||
let func_id = FuncId::from_name(name);
|
||||
self.function_got_entries[func_id]
|
||||
.unwrap()
|
||||
.as_ptr()
|
||||
.cast::<u8>()
|
||||
} else {
|
||||
let data_id = DataId::from_name(name);
|
||||
self.data_object_got_entries[data_id]
|
||||
.unwrap()
|
||||
.as_ptr()
|
||||
.cast::<u8>()
|
||||
}
|
||||
}
|
||||
ir::ExternalName::LibCall(ref libcall) => self
|
||||
.libcall_got_entries
|
||||
.get(libcall)
|
||||
.unwrap_or_else(|| panic!("can't resolve libcall {}", libcall))
|
||||
.as_ptr()
|
||||
.cast::<u8>(),
|
||||
_ => panic!("invalid ExternalName {}", name),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_plt_address(&self, name: &ir::ExternalName) -> *const u8 {
|
||||
match *name {
|
||||
ir::ExternalName::User { .. } => {
|
||||
if ModuleDeclarations::is_function(name) {
|
||||
let func_id = FuncId::from_name(name);
|
||||
self.function_plt_entries[func_id]
|
||||
.unwrap()
|
||||
.as_ptr()
|
||||
.cast::<u8>()
|
||||
} else {
|
||||
unreachable!("PLT relocations can only have functions as target");
|
||||
}
|
||||
}
|
||||
ir::ExternalName::LibCall(ref libcall) => self
|
||||
.libcall_plt_entries
|
||||
.get(libcall)
|
||||
.unwrap_or_else(|| panic!("can't resolve libcall {}", libcall))
|
||||
.as_ptr()
|
||||
.cast::<u8>(),
|
||||
_ => panic!("invalid ExternalName {}", name),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the address of a finalized function.
|
||||
pub fn get_finalized_function(&self, func_id: FuncId) -> *const u8 {
|
||||
let info = &self.compiled_functions[func_id];
|
||||
assert!(
|
||||
!self.functions_to_finalize.iter().any(|x| *x == func_id),
|
||||
"function not yet finalized"
|
||||
);
|
||||
info.as_ref()
|
||||
.expect("function must be compiled before it can be finalized")
|
||||
.ptr
|
||||
}
|
||||
|
||||
/// Returns the address and size of a finalized data object.
|
||||
pub fn get_finalized_data(&self, data_id: DataId) -> (*const u8, usize) {
|
||||
let info = &self.compiled_data_objects[data_id];
|
||||
assert!(
|
||||
!self.data_objects_to_finalize.iter().any(|x| *x == data_id),
|
||||
"data object not yet finalized"
|
||||
);
|
||||
let compiled = info
|
||||
.as_ref()
|
||||
.expect("data object must be compiled before it can be finalized");
|
||||
|
||||
(compiled.ptr, compiled.size)
|
||||
}
|
||||
|
||||
fn record_function_for_perf(&self, ptr: *mut u8, size: usize, name: &str) {
|
||||
// The Linux perf tool supports JIT code via a /tmp/perf-$PID.map file,
|
||||
// which contains memory regions and their associated names. If we
|
||||
// are profiling with perf and saving binaries to PERF_BUILDID_DIR
|
||||
// for post-profile analysis, write information about each function
|
||||
// we define.
|
||||
if cfg!(target_os = "linux") && ::std::env::var_os("PERF_BUILDID_DIR").is_some() {
|
||||
let mut map_file = ::std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(format!("/tmp/perf-{}.map", ::std::process::id()))
|
||||
.unwrap();
|
||||
|
||||
let _ = writeln!(map_file, "{:x} {:x} {}", ptr as usize, size, name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Finalize all functions and data objects that are defined but not yet finalized.
|
||||
/// All symbols referenced in their bodies that are declared as needing a definition
|
||||
/// must be defined by this point.
|
||||
///
|
||||
/// Use `get_finalized_function` and `get_finalized_data` to obtain the final
|
||||
/// artifacts.
|
||||
pub fn finalize_definitions(&mut self) {
|
||||
for func in std::mem::take(&mut self.functions_to_finalize) {
|
||||
let decl = self.declarations.get_function_decl(func);
|
||||
assert!(decl.linkage.is_definable());
|
||||
let func = self.compiled_functions[func]
|
||||
.as_ref()
|
||||
.expect("function must be compiled before it can be finalized");
|
||||
func.perform_relocations(
|
||||
|name| self.get_address(name),
|
||||
|name| self.get_got_address(name),
|
||||
|name| self.get_plt_address(name),
|
||||
);
|
||||
}
|
||||
|
||||
for data in std::mem::take(&mut self.data_objects_to_finalize) {
|
||||
let decl = self.declarations.get_data_decl(data);
|
||||
assert!(decl.linkage.is_definable());
|
||||
let data = self.compiled_data_objects[data]
|
||||
.as_ref()
|
||||
.expect("data object must be compiled before it can be finalized");
|
||||
data.perform_relocations(
|
||||
|name| self.get_address(name),
|
||||
|name| self.get_got_address(name),
|
||||
|name| self.get_plt_address(name),
|
||||
);
|
||||
}
|
||||
|
||||
// Now that we're done patching, prepare the memory for execution!
|
||||
self.memory.readonly.set_readonly();
|
||||
self.memory.code.set_readable_and_executable();
|
||||
}
|
||||
|
||||
/// Create a new `JITModule`.
|
||||
pub fn new(builder: JITBuilder) -> Self {
|
||||
if builder.hotswap_enabled {
|
||||
assert!(
|
||||
builder.isa.flags().is_pic(),
|
||||
"Hotswapping requires PIC code"
|
||||
);
|
||||
}
|
||||
|
||||
let mut memory = MemoryHandle {
|
||||
code: Memory::new(),
|
||||
readonly: Memory::new(),
|
||||
writable: Memory::new(),
|
||||
};
|
||||
|
||||
let mut libcall_got_entries = HashMap::new();
|
||||
let mut libcall_plt_entries = HashMap::new();
|
||||
|
||||
// Pre-create a GOT and PLT entry for each libcall.
|
||||
let all_libcalls = if builder.isa.flags().is_pic() {
|
||||
ir::LibCall::all_libcalls()
|
||||
} else {
|
||||
&[] // Not PIC, so no GOT and PLT entries necessary
|
||||
};
|
||||
for &libcall in all_libcalls {
|
||||
let got_entry = memory
|
||||
.writable
|
||||
.allocate(
|
||||
std::mem::size_of::<*const u8>(),
|
||||
std::mem::align_of::<*const u8>().try_into().unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
.cast::<*const u8>();
|
||||
libcall_got_entries.insert(libcall, NonNull::new(got_entry).unwrap());
|
||||
let sym = (builder.libcall_names)(libcall);
|
||||
let addr = if let Some(addr) = builder
|
||||
.symbols
|
||||
.get(&sym)
|
||||
.copied()
|
||||
.or_else(|| lookup_with_dlsym(&sym))
|
||||
{
|
||||
addr
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
unsafe {
|
||||
std::ptr::write(got_entry, addr);
|
||||
}
|
||||
let plt_entry = memory
|
||||
.code
|
||||
.allocate(std::mem::size_of::<[u8; 16]>(), EXECUTABLE_DATA_ALIGNMENT)
|
||||
.unwrap()
|
||||
.cast::<[u8; 16]>();
|
||||
libcall_plt_entries.insert(libcall, NonNull::new(plt_entry).unwrap());
|
||||
unsafe {
|
||||
Self::write_plt_entry_bytes(plt_entry, got_entry);
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
isa: builder.isa,
|
||||
hotswap_enabled: builder.hotswap_enabled,
|
||||
symbols: builder.symbols,
|
||||
libcall_names: builder.libcall_names,
|
||||
memory,
|
||||
declarations: ModuleDeclarations::default(),
|
||||
function_got_entries: SecondaryMap::new(),
|
||||
function_plt_entries: SecondaryMap::new(),
|
||||
data_object_got_entries: SecondaryMap::new(),
|
||||
libcall_got_entries,
|
||||
libcall_plt_entries,
|
||||
compiled_functions: SecondaryMap::new(),
|
||||
compiled_data_objects: SecondaryMap::new(),
|
||||
functions_to_finalize: Vec::new(),
|
||||
data_objects_to_finalize: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Allow a single future `define_function` on a previously defined function. This allows for
|
||||
/// hot code swapping and lazy compilation of functions.
|
||||
///
|
||||
/// This requires hotswap support to be enabled first using [`JITBuilder::hotswap`].
|
||||
pub fn prepare_for_function_redefine(&mut self, func_id: FuncId) -> ModuleResult<()> {
|
||||
assert!(self.hotswap_enabled, "Hotswap support is not enabled");
|
||||
let decl = self.declarations.get_function_decl(func_id);
|
||||
if !decl.linkage.is_definable() {
|
||||
return Err(ModuleError::InvalidImportDefinition(decl.name.clone()));
|
||||
}
|
||||
|
||||
if self.compiled_functions[func_id].is_none() {
|
||||
return Err(ModuleError::Backend(anyhow::anyhow!(
|
||||
"Tried to redefine not yet defined function {}",
|
||||
decl.name
|
||||
)));
|
||||
}
|
||||
|
||||
self.compiled_functions[func_id] = None;
|
||||
|
||||
// FIXME return some kind of handle that allows for deallocating the function
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Module for JITModule {
|
||||
fn isa(&self) -> &dyn TargetIsa {
|
||||
&*self.isa
|
||||
}
|
||||
|
||||
fn declarations(&self) -> &ModuleDeclarations {
|
||||
&self.declarations
|
||||
}
|
||||
|
||||
fn declare_function(
|
||||
&mut self,
|
||||
name: &str,
|
||||
linkage: Linkage,
|
||||
signature: &ir::Signature,
|
||||
) -> ModuleResult<FuncId> {
|
||||
let (id, _decl) = self
|
||||
.declarations
|
||||
.declare_function(name, linkage, signature)?;
|
||||
if self.function_got_entries[id].is_none() && self.isa.flags().is_pic() {
|
||||
let got_entry = self
|
||||
.memory
|
||||
.writable
|
||||
.allocate(
|
||||
std::mem::size_of::<*const u8>(),
|
||||
std::mem::align_of::<*const u8>().try_into().unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
.cast::<*const u8>();
|
||||
self.function_got_entries[id] = Some(NonNull::new(got_entry).unwrap());
|
||||
// FIXME populate got entries with a null pointer when defined
|
||||
let val = self.lookup_symbol(name).unwrap_or(std::ptr::null());
|
||||
unsafe {
|
||||
std::ptr::write(got_entry, val);
|
||||
}
|
||||
let plt_entry = self
|
||||
.memory
|
||||
.code
|
||||
.allocate(std::mem::size_of::<[u8; 16]>(), EXECUTABLE_DATA_ALIGNMENT)
|
||||
.unwrap()
|
||||
.cast::<[u8; 16]>();
|
||||
self.record_function_for_perf(
|
||||
plt_entry as *mut _,
|
||||
std::mem::size_of::<[u8; 16]>(),
|
||||
&format!("{}@plt", name),
|
||||
);
|
||||
self.function_plt_entries[id] = Some(NonNull::new(plt_entry).unwrap());
|
||||
unsafe {
|
||||
Self::write_plt_entry_bytes(plt_entry, got_entry);
|
||||
}
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn declare_data(
|
||||
&mut self,
|
||||
name: &str,
|
||||
linkage: Linkage,
|
||||
writable: bool,
|
||||
tls: bool,
|
||||
) -> ModuleResult<DataId> {
|
||||
assert!(!tls, "JIT doesn't yet support TLS");
|
||||
let (id, _decl) = self
|
||||
.declarations
|
||||
.declare_data(name, linkage, writable, tls)?;
|
||||
if self.data_object_got_entries[id].is_none() && self.isa.flags().is_pic() {
|
||||
let got_entry = self
|
||||
.memory
|
||||
.writable
|
||||
.allocate(
|
||||
std::mem::size_of::<*const u8>(),
|
||||
std::mem::align_of::<*const u8>().try_into().unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
.cast::<*const u8>();
|
||||
self.data_object_got_entries[id] = Some(NonNull::new(got_entry).unwrap());
|
||||
// FIXME populate got entries with a null pointer when defined
|
||||
let val = self.lookup_symbol(name).unwrap_or(std::ptr::null());
|
||||
unsafe {
|
||||
std::ptr::write(got_entry, val);
|
||||
}
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Use this when you're building the IR of a function to reference a function.
|
||||
///
|
||||
/// TODO: Coalesce redundant decls and signatures.
|
||||
/// TODO: Look into ways to reduce the risk of using a FuncRef in the wrong function.
|
||||
fn declare_func_in_func(&self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {
|
||||
let decl = self.declarations.get_function_decl(func);
|
||||
let signature = in_func.import_signature(decl.signature.clone());
|
||||
let colocated = !self.hotswap_enabled && decl.linkage.is_final();
|
||||
in_func.import_function(ir::ExtFuncData {
|
||||
name: ir::ExternalName::user(0, func.as_u32()),
|
||||
signature,
|
||||
colocated,
|
||||
})
|
||||
}
|
||||
|
||||
/// Use this when you're building the IR of a function to reference a data object.
|
||||
///
|
||||
/// TODO: Same as above.
|
||||
fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {
|
||||
let decl = self.declarations.get_data_decl(data);
|
||||
let colocated = !self.hotswap_enabled && decl.linkage.is_final();
|
||||
func.create_global_value(ir::GlobalValueData::Symbol {
|
||||
name: ir::ExternalName::user(1, data.as_u32()),
|
||||
offset: ir::immediates::Imm64::new(0),
|
||||
colocated,
|
||||
tls: decl.tls,
|
||||
})
|
||||
}
|
||||
|
||||
/// TODO: Same as above.
|
||||
fn declare_func_in_data(&self, func: FuncId, ctx: &mut DataContext) -> ir::FuncRef {
|
||||
ctx.import_function(ir::ExternalName::user(0, func.as_u32()))
|
||||
}
|
||||
|
||||
/// TODO: Same as above.
|
||||
fn declare_data_in_data(&self, data: DataId, ctx: &mut DataContext) -> ir::GlobalValue {
|
||||
ctx.import_global_value(ir::ExternalName::user(1, data.as_u32()))
|
||||
}
|
||||
|
||||
fn define_function<TS>(
|
||||
&mut self,
|
||||
id: FuncId,
|
||||
ctx: &mut cranelift_codegen::Context,
|
||||
trap_sink: &mut TS,
|
||||
) -> ModuleResult<ModuleCompiledFunction>
|
||||
where
|
||||
TS: TrapSink,
|
||||
{
|
||||
info!("defining function {}: {}", id, ctx.func.display(self.isa()));
|
||||
let CodeInfo {
|
||||
total_size: code_size,
|
||||
..
|
||||
} = ctx.compile(self.isa())?;
|
||||
|
||||
let decl = self.declarations.get_function_decl(id);
|
||||
if !decl.linkage.is_definable() {
|
||||
return Err(ModuleError::InvalidImportDefinition(decl.name.clone()));
|
||||
}
|
||||
|
||||
if !self.compiled_functions[id].is_none() {
|
||||
return Err(ModuleError::DuplicateDefinition(decl.name.to_owned()));
|
||||
}
|
||||
|
||||
let size = code_size as usize;
|
||||
let ptr = self
|
||||
.memory
|
||||
.code
|
||||
.allocate(size, EXECUTABLE_DATA_ALIGNMENT)
|
||||
.expect("TODO: handle OOM etc.");
|
||||
|
||||
let mut reloc_sink = JITRelocSink::default();
|
||||
let mut stack_map_sink = binemit::NullStackMapSink {};
|
||||
unsafe {
|
||||
ctx.emit_to_memory(
|
||||
&*self.isa,
|
||||
ptr,
|
||||
&mut reloc_sink,
|
||||
trap_sink,
|
||||
&mut stack_map_sink,
|
||||
)
|
||||
};
|
||||
|
||||
self.record_function_for_perf(ptr, size, &decl.name);
|
||||
self.compiled_functions[id] = Some(CompiledBlob {
|
||||
ptr,
|
||||
size,
|
||||
relocs: reloc_sink.relocs,
|
||||
});
|
||||
|
||||
if self.isa.flags().is_pic() {
|
||||
unsafe {
|
||||
std::ptr::write(self.function_got_entries[id].unwrap().as_ptr(), ptr);
|
||||
}
|
||||
}
|
||||
|
||||
if self.hotswap_enabled {
|
||||
self.compiled_functions[id]
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.perform_relocations(
|
||||
|name| match *name {
|
||||
ir::ExternalName::User { .. } => {
|
||||
unreachable!("non GOT or PLT relocation in function {} to {}", id, name)
|
||||
}
|
||||
ir::ExternalName::LibCall(ref libcall) => self
|
||||
.libcall_plt_entries
|
||||
.get(libcall)
|
||||
.unwrap_or_else(|| panic!("can't resolve libcall {}", libcall))
|
||||
.as_ptr()
|
||||
.cast::<u8>(),
|
||||
_ => panic!("invalid ExternalName {}", name),
|
||||
},
|
||||
|name| self.get_got_address(name),
|
||||
|name| self.get_plt_address(name),
|
||||
);
|
||||
} else {
|
||||
self.functions_to_finalize.push(id);
|
||||
}
|
||||
|
||||
Ok(ModuleCompiledFunction { size: code_size })
|
||||
}
|
||||
|
||||
fn define_function_bytes(
|
||||
&mut self,
|
||||
id: FuncId,
|
||||
bytes: &[u8],
|
||||
relocs: &[RelocRecord],
|
||||
) -> ModuleResult<ModuleCompiledFunction> {
|
||||
info!("defining function {} with bytes", id);
|
||||
let total_size: u32 = match bytes.len().try_into() {
|
||||
Ok(total_size) => total_size,
|
||||
_ => Err(CodegenError::CodeTooLarge)?,
|
||||
};
|
||||
|
||||
let decl = self.declarations.get_function_decl(id);
|
||||
if !decl.linkage.is_definable() {
|
||||
return Err(ModuleError::InvalidImportDefinition(decl.name.clone()));
|
||||
}
|
||||
|
||||
if !self.compiled_functions[id].is_none() {
|
||||
return Err(ModuleError::DuplicateDefinition(decl.name.to_owned()));
|
||||
}
|
||||
|
||||
let size = bytes.len();
|
||||
let ptr = self
|
||||
.memory
|
||||
.code
|
||||
.allocate(size, EXECUTABLE_DATA_ALIGNMENT)
|
||||
.expect("TODO: handle OOM etc.");
|
||||
|
||||
unsafe {
|
||||
ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, size);
|
||||
}
|
||||
|
||||
self.record_function_for_perf(ptr, size, &decl.name);
|
||||
self.compiled_functions[id] = Some(CompiledBlob {
|
||||
ptr,
|
||||
size,
|
||||
relocs: relocs.to_vec(),
|
||||
});
|
||||
|
||||
if self.isa.flags().is_pic() {
|
||||
unsafe {
|
||||
std::ptr::write(self.function_got_entries[id].unwrap().as_ptr(), ptr);
|
||||
}
|
||||
}
|
||||
|
||||
if self.hotswap_enabled {
|
||||
self.compiled_functions[id]
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.perform_relocations(
|
||||
|name| unreachable!("non GOT or PLT relocation in function {} to {}", id, name),
|
||||
|name| self.get_got_address(name),
|
||||
|name| self.get_plt_address(name),
|
||||
);
|
||||
} else {
|
||||
self.functions_to_finalize.push(id);
|
||||
}
|
||||
|
||||
Ok(ModuleCompiledFunction { size: total_size })
|
||||
}
|
||||
|
||||
fn define_data(&mut self, id: DataId, data: &DataContext) -> ModuleResult<()> {
|
||||
let decl = self.declarations.get_data_decl(id);
|
||||
if !decl.linkage.is_definable() {
|
||||
return Err(ModuleError::InvalidImportDefinition(decl.name.clone()));
|
||||
}
|
||||
|
||||
if !self.compiled_data_objects[id].is_none() {
|
||||
return Err(ModuleError::DuplicateDefinition(decl.name.to_owned()));
|
||||
}
|
||||
|
||||
assert!(!decl.tls, "JIT doesn't yet support TLS");
|
||||
|
||||
let &DataDescription {
|
||||
ref init,
|
||||
function_decls: _,
|
||||
data_decls: _,
|
||||
function_relocs: _,
|
||||
data_relocs: _,
|
||||
custom_segment_section: _,
|
||||
align,
|
||||
} = data.description();
|
||||
|
||||
let size = init.size();
|
||||
let ptr = if decl.writable {
|
||||
self.memory
|
||||
.writable
|
||||
.allocate(size, align.unwrap_or(WRITABLE_DATA_ALIGNMENT))
|
||||
.expect("TODO: handle OOM etc.")
|
||||
} else {
|
||||
self.memory
|
||||
.readonly
|
||||
.allocate(size, align.unwrap_or(READONLY_DATA_ALIGNMENT))
|
||||
.expect("TODO: handle OOM etc.")
|
||||
};
|
||||
|
||||
match *init {
|
||||
Init::Uninitialized => {
|
||||
panic!("data is not initialized yet");
|
||||
}
|
||||
Init::Zeros { .. } => {
|
||||
unsafe { ptr::write_bytes(ptr, 0, size) };
|
||||
}
|
||||
Init::Bytes { ref contents } => {
|
||||
let src = contents.as_ptr();
|
||||
unsafe { ptr::copy_nonoverlapping(src, ptr, size) };
|
||||
}
|
||||
}
|
||||
|
||||
let pointer_reloc = match self.isa.triple().pointer_width().unwrap() {
|
||||
PointerWidth::U16 => panic!(),
|
||||
PointerWidth::U32 => Reloc::Abs4,
|
||||
PointerWidth::U64 => Reloc::Abs8,
|
||||
};
|
||||
let relocs = data
|
||||
.description()
|
||||
.all_relocs(pointer_reloc)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
self.compiled_data_objects[id] = Some(CompiledBlob { ptr, size, relocs });
|
||||
self.data_objects_to_finalize.push(id);
|
||||
if self.isa.flags().is_pic() {
|
||||
unsafe {
|
||||
std::ptr::write(self.data_object_got_entries[id].unwrap().as_ptr(), ptr);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn lookup_with_dlsym(name: &str) -> Option<*const u8> {
|
||||
let c_str = CString::new(name).unwrap();
|
||||
let c_str_ptr = c_str.as_ptr();
|
||||
let sym = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c_str_ptr) };
|
||||
if sym.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(sym as *const u8)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn lookup_with_dlsym(name: &str) -> Option<*const u8> {
|
||||
const MSVCRT_DLL: &[u8] = b"msvcrt.dll\0";
|
||||
|
||||
let c_str = CString::new(name).unwrap();
|
||||
let c_str_ptr = c_str.as_ptr();
|
||||
|
||||
unsafe {
|
||||
let handles = [
|
||||
// try to find the searched symbol in the currently running executable
|
||||
ptr::null_mut(),
|
||||
// try to find the searched symbol in local c runtime
|
||||
winapi::um::libloaderapi::GetModuleHandleA(MSVCRT_DLL.as_ptr() as *const i8),
|
||||
];
|
||||
|
||||
for handle in &handles {
|
||||
let addr = winapi::um::libloaderapi::GetProcAddress(*handle, c_str_ptr);
|
||||
if addr.is_null() {
|
||||
continue;
|
||||
}
|
||||
return Some(addr as *const u8);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct JITRelocSink {
|
||||
relocs: Vec<RelocRecord>,
|
||||
}
|
||||
|
||||
impl RelocSink for JITRelocSink {
|
||||
fn reloc_external(
|
||||
&mut self,
|
||||
offset: CodeOffset,
|
||||
_srcloc: ir::SourceLoc,
|
||||
reloc: Reloc,
|
||||
name: &ir::ExternalName,
|
||||
addend: Addend,
|
||||
) {
|
||||
self.relocs.push(RelocRecord {
|
||||
offset,
|
||||
reloc,
|
||||
name: name.clone(),
|
||||
addend,
|
||||
});
|
||||
}
|
||||
|
||||
fn reloc_jt(&mut self, _offset: CodeOffset, reloc: Reloc, _jt: ir::JumpTable) {
|
||||
match reloc {
|
||||
Reloc::X86PCRelRodata4 => {
|
||||
// Not necessary to record this unless we are going to split apart code and its
|
||||
// jumptbl/rodata.
|
||||
}
|
||||
_ => {
|
||||
panic!("Unhandled reloc");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reloc_constant(&mut self, _offset: CodeOffset, reloc: Reloc, _constant: ir::ConstantOffset) {
|
||||
match reloc {
|
||||
Reloc::X86PCRelRodata4 => {
|
||||
// Not necessary to record this unless we are going to split apart code and its
|
||||
// jumptbl/rodata.
|
||||
}
|
||||
_ => {
|
||||
panic!("Unhandled reloc");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
79
cranelift/jit/src/compiled_blob.rs
Normal file
79
cranelift/jit/src/compiled_blob.rs
Normal file
@@ -0,0 +1,79 @@
|
||||
use cranelift_codegen::binemit::Reloc;
|
||||
use cranelift_codegen::ir::ExternalName;
|
||||
use cranelift_module::RelocRecord;
|
||||
use std::convert::TryFrom;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CompiledBlob {
|
||||
pub(crate) ptr: *mut u8,
|
||||
pub(crate) size: usize,
|
||||
pub(crate) relocs: Vec<RelocRecord>,
|
||||
}
|
||||
|
||||
impl CompiledBlob {
|
||||
pub(crate) fn perform_relocations(
|
||||
&self,
|
||||
get_address: impl Fn(&ExternalName) -> *const u8,
|
||||
get_got_entry: impl Fn(&ExternalName) -> *const u8,
|
||||
get_plt_entry: impl Fn(&ExternalName) -> *const u8,
|
||||
) {
|
||||
use std::ptr::write_unaligned;
|
||||
|
||||
for &RelocRecord {
|
||||
reloc,
|
||||
offset,
|
||||
ref name,
|
||||
addend,
|
||||
} in &self.relocs
|
||||
{
|
||||
debug_assert!((offset as usize) < self.size);
|
||||
let at = unsafe { self.ptr.offset(isize::try_from(offset).unwrap()) };
|
||||
match reloc {
|
||||
Reloc::Abs4 => {
|
||||
let base = get_address(name);
|
||||
let what = unsafe { base.offset(isize::try_from(addend).unwrap()) };
|
||||
#[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_ptr_alignment))]
|
||||
unsafe {
|
||||
write_unaligned(at as *mut u32, u32::try_from(what as usize).unwrap())
|
||||
};
|
||||
}
|
||||
Reloc::Abs8 => {
|
||||
let base = get_address(name);
|
||||
let what = unsafe { base.offset(isize::try_from(addend).unwrap()) };
|
||||
#[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_ptr_alignment))]
|
||||
unsafe {
|
||||
write_unaligned(at as *mut u64, u64::try_from(what as usize).unwrap())
|
||||
};
|
||||
}
|
||||
Reloc::X86PCRel4 | Reloc::X86CallPCRel4 => {
|
||||
let base = get_address(name);
|
||||
let what = unsafe { base.offset(isize::try_from(addend).unwrap()) };
|
||||
let pcrel = i32::try_from((what as isize) - (at as isize)).unwrap();
|
||||
#[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_ptr_alignment))]
|
||||
unsafe {
|
||||
write_unaligned(at as *mut i32, pcrel)
|
||||
};
|
||||
}
|
||||
Reloc::X86GOTPCRel4 => {
|
||||
let base = get_got_entry(name);
|
||||
let what = unsafe { base.offset(isize::try_from(addend).unwrap()) };
|
||||
let pcrel = i32::try_from((what as isize) - (at as isize)).unwrap();
|
||||
#[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_ptr_alignment))]
|
||||
unsafe {
|
||||
write_unaligned(at as *mut i32, pcrel)
|
||||
};
|
||||
}
|
||||
Reloc::X86CallPLTRel4 => {
|
||||
let base = get_plt_entry(name);
|
||||
let what = unsafe { base.offset(isize::try_from(addend).unwrap()) };
|
||||
let pcrel = i32::try_from((what as isize) - (at as isize)).unwrap();
|
||||
#[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_ptr_alignment))]
|
||||
unsafe {
|
||||
write_unaligned(at as *mut i32, pcrel)
|
||||
};
|
||||
}
|
||||
_ => unimplemented!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
33
cranelift/jit/src/lib.rs
Normal file
33
cranelift/jit/src/lib.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
//! Top-level lib.rs for `cranelift_jit`.
|
||||
|
||||
#![deny(
|
||||
missing_docs,
|
||||
trivial_numeric_casts,
|
||||
unused_extern_crates,
|
||||
unstable_features,
|
||||
unreachable_pub
|
||||
)]
|
||||
#![warn(unused_import_braces)]
|
||||
#![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../../clippy.toml")))]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(clippy::new_without_default))]
|
||||
#![cfg_attr(
|
||||
feature = "cargo-clippy",
|
||||
warn(
|
||||
clippy::float_arithmetic,
|
||||
clippy::mut_mut,
|
||||
clippy::nonminimal_bool,
|
||||
clippy::map_unwrap_or,
|
||||
clippy::clippy::print_stdout,
|
||||
clippy::unicode_not_nfc,
|
||||
clippy::use_self
|
||||
)
|
||||
)]
|
||||
|
||||
mod backend;
|
||||
mod compiled_blob;
|
||||
mod memory;
|
||||
|
||||
pub use crate::backend::{JITBuilder, JITModule};
|
||||
|
||||
/// Version number of this crate.
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
260
cranelift/jit/src/memory.rs
Normal file
260
cranelift/jit/src/memory.rs
Normal file
@@ -0,0 +1,260 @@
|
||||
#[cfg(not(feature = "selinux-fix"))]
|
||||
use errno;
|
||||
|
||||
#[cfg(not(any(feature = "selinux-fix", windows)))]
|
||||
use libc;
|
||||
|
||||
#[cfg(feature = "selinux-fix")]
|
||||
use memmap::MmapMut;
|
||||
|
||||
use region;
|
||||
use std::convert::TryFrom;
|
||||
use std::mem;
|
||||
use std::ptr;
|
||||
|
||||
/// Round `size` up to the nearest multiple of `page_size`.
|
||||
fn round_up_to_page_size(size: usize, page_size: usize) -> usize {
|
||||
(size + (page_size - 1)) & !(page_size - 1)
|
||||
}
|
||||
|
||||
/// A simple struct consisting of a pointer and length.
|
||||
struct PtrLen {
|
||||
#[cfg(feature = "selinux-fix")]
|
||||
map: Option<MmapMut>,
|
||||
|
||||
ptr: *mut u8,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl PtrLen {
|
||||
/// Create a new empty `PtrLen`.
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
#[cfg(feature = "selinux-fix")]
|
||||
map: None,
|
||||
|
||||
ptr: ptr::null_mut(),
|
||||
len: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new `PtrLen` pointing to at least `size` bytes of memory,
|
||||
/// suitably sized and aligned for memory protection.
|
||||
#[cfg(all(not(target_os = "windows"), feature = "selinux-fix"))]
|
||||
fn with_size(size: usize) -> Result<Self, String> {
|
||||
let page_size = region::page::size();
|
||||
let alloc_size = round_up_to_page_size(size, page_size);
|
||||
let map = MmapMut::map_anon(alloc_size);
|
||||
|
||||
match map {
|
||||
Ok(mut map) => {
|
||||
// The order here is important; we assign the pointer first to get
|
||||
// around compile time borrow errors.
|
||||
Ok(Self {
|
||||
ptr: map.as_mut_ptr(),
|
||||
map: Some(map),
|
||||
len: alloc_size,
|
||||
})
|
||||
}
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_os = "windows"), not(feature = "selinux-fix")))]
|
||||
fn with_size(size: usize) -> Result<Self, String> {
|
||||
let mut ptr = ptr::null_mut();
|
||||
let page_size = region::page::size();
|
||||
let alloc_size = round_up_to_page_size(size, page_size);
|
||||
unsafe {
|
||||
let err = libc::posix_memalign(&mut ptr, page_size, alloc_size);
|
||||
|
||||
if err == 0 {
|
||||
Ok(Self {
|
||||
ptr: ptr as *mut u8,
|
||||
len: alloc_size,
|
||||
})
|
||||
} else {
|
||||
Err(errno::Errno(err).to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn with_size(size: usize) -> Result<Self, String> {
|
||||
use winapi::um::memoryapi::VirtualAlloc;
|
||||
use winapi::um::winnt::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE};
|
||||
|
||||
let page_size = region::page::size();
|
||||
|
||||
// VirtualAlloc always rounds up to the next multiple of the page size
|
||||
let ptr = unsafe {
|
||||
VirtualAlloc(
|
||||
ptr::null_mut(),
|
||||
size,
|
||||
MEM_COMMIT | MEM_RESERVE,
|
||||
PAGE_READWRITE,
|
||||
)
|
||||
};
|
||||
if !ptr.is_null() {
|
||||
Ok(Self {
|
||||
ptr: ptr as *mut u8,
|
||||
len: round_up_to_page_size(size, page_size),
|
||||
})
|
||||
} else {
|
||||
Err(errno::errno().to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `MMapMut` from `cfg(feature = "selinux-fix")` already deallocates properly.
|
||||
#[cfg(all(not(target_os = "windows"), not(feature = "selinux-fix")))]
|
||||
impl Drop for PtrLen {
|
||||
fn drop(&mut self) {
|
||||
if !self.ptr.is_null() {
|
||||
unsafe {
|
||||
region::protect(self.ptr, self.len, region::Protection::READ_WRITE)
|
||||
.expect("unable to unprotect memory");
|
||||
libc::free(self.ptr as _);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: add a `Drop` impl for `cfg(target_os = "windows")`
|
||||
|
||||
/// JIT memory manager. This manages pages of suitably aligned and
|
||||
/// accessible memory. Memory will be leaked by default to have
|
||||
/// function pointers remain valid for the remainder of the
|
||||
/// program's life.
|
||||
pub(crate) struct Memory {
|
||||
allocations: Vec<PtrLen>,
|
||||
executable: usize,
|
||||
current: PtrLen,
|
||||
position: usize,
|
||||
}
|
||||
|
||||
impl Memory {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
allocations: Vec::new(),
|
||||
executable: 0,
|
||||
current: PtrLen::new(),
|
||||
position: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_current(&mut self) {
|
||||
self.allocations
|
||||
.push(mem::replace(&mut self.current, PtrLen::new()));
|
||||
self.position = 0;
|
||||
}
|
||||
|
||||
/// TODO: Use a proper error type.
|
||||
pub(crate) fn allocate(&mut self, size: usize, align: u64) -> Result<*mut u8, String> {
|
||||
let align = usize::try_from(align).expect("alignment too big");
|
||||
if self.position % align != 0 {
|
||||
self.position += align - self.position % align;
|
||||
debug_assert!(self.position % align == 0);
|
||||
}
|
||||
|
||||
if size <= self.current.len - self.position {
|
||||
// TODO: Ensure overflow is not possible.
|
||||
let ptr = unsafe { self.current.ptr.add(self.position) };
|
||||
self.position += size;
|
||||
return Ok(ptr);
|
||||
}
|
||||
|
||||
self.finish_current();
|
||||
|
||||
// TODO: Allocate more at a time.
|
||||
self.current = PtrLen::with_size(size)?;
|
||||
self.position = size;
|
||||
Ok(self.current.ptr)
|
||||
}
|
||||
|
||||
/// Set all memory allocated in this `Memory` up to now as readable and executable.
|
||||
pub(crate) fn set_readable_and_executable(&mut self) {
|
||||
self.finish_current();
|
||||
|
||||
#[cfg(feature = "selinux-fix")]
|
||||
{
|
||||
for &PtrLen { ref map, ptr, len } in &self.allocations[self.executable..] {
|
||||
if len != 0 && map.is_some() {
|
||||
unsafe {
|
||||
region::protect(ptr, len, region::Protection::READ_EXECUTE)
|
||||
.expect("unable to make memory readable+executable");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "selinux-fix"))]
|
||||
{
|
||||
for &PtrLen { ptr, len } in &self.allocations[self.executable..] {
|
||||
if len != 0 {
|
||||
unsafe {
|
||||
region::protect(ptr, len, region::Protection::READ_EXECUTE)
|
||||
.expect("unable to make memory readable+executable");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set all memory allocated in this `Memory` up to now as readonly.
|
||||
pub(crate) fn set_readonly(&mut self) {
|
||||
self.finish_current();
|
||||
|
||||
#[cfg(feature = "selinux-fix")]
|
||||
{
|
||||
for &PtrLen { ref map, ptr, len } in &self.allocations[self.executable..] {
|
||||
if len != 0 && map.is_some() {
|
||||
unsafe {
|
||||
region::protect(ptr, len, region::Protection::READ)
|
||||
.expect("unable to make memory readonly");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "selinux-fix"))]
|
||||
{
|
||||
for &PtrLen { ptr, len } in &self.allocations[self.executable..] {
|
||||
if len != 0 {
|
||||
unsafe {
|
||||
region::protect(ptr, len, region::Protection::READ)
|
||||
.expect("unable to make memory readonly");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees all allocated memory regions that would be leaked otherwise.
|
||||
/// Likely to invalidate existing function pointers, causing unsafety.
|
||||
pub(crate) unsafe fn free_memory(&mut self) {
|
||||
self.allocations.clear();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Memory {
|
||||
fn drop(&mut self) {
|
||||
// leak memory to guarantee validity of function pointers
|
||||
mem::replace(&mut self.allocations, Vec::new())
|
||||
.into_iter()
|
||||
.for_each(mem::forget);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_round_up_to_page_size() {
|
||||
assert_eq!(round_up_to_page_size(0, 4096), 0);
|
||||
assert_eq!(round_up_to_page_size(1, 4096), 4096);
|
||||
assert_eq!(round_up_to_page_size(4096, 4096), 4096);
|
||||
assert_eq!(round_up_to_page_size(4097, 4096), 8192);
|
||||
}
|
||||
}
|
||||
213
cranelift/jit/tests/basic.rs
Normal file
213
cranelift/jit/tests/basic.rs
Normal file
@@ -0,0 +1,213 @@
|
||||
use cranelift_codegen::binemit::NullTrapSink;
|
||||
use cranelift_codegen::ir::*;
|
||||
use cranelift_codegen::isa::CallConv;
|
||||
use cranelift_codegen::settings::{self, Configurable};
|
||||
use cranelift_codegen::{ir::types::I16, Context};
|
||||
use cranelift_entity::EntityRef;
|
||||
use cranelift_frontend::*;
|
||||
use cranelift_jit::*;
|
||||
use cranelift_module::*;
|
||||
|
||||
#[test]
|
||||
fn error_on_incompatible_sig_in_declare_function() {
|
||||
let mut flag_builder = settings::builder();
|
||||
flag_builder.set("use_colocated_libcalls", "false").unwrap();
|
||||
// FIXME set back to true once the x64 backend supports it.
|
||||
flag_builder.set("is_pic", "false").unwrap();
|
||||
let isa_builder = cranelift_native::builder().unwrap_or_else(|msg| {
|
||||
panic!("host machine is not supported: {}", msg);
|
||||
});
|
||||
let isa = isa_builder.finish(settings::Flags::new(flag_builder));
|
||||
let mut module = JITModule::new(JITBuilder::with_isa(isa, default_libcall_names()));
|
||||
|
||||
let mut sig = Signature {
|
||||
params: vec![AbiParam::new(types::I64)],
|
||||
returns: vec![],
|
||||
call_conv: CallConv::SystemV,
|
||||
};
|
||||
module
|
||||
.declare_function("abc", Linkage::Local, &sig)
|
||||
.unwrap();
|
||||
sig.params[0] = AbiParam::new(types::I32);
|
||||
module
|
||||
.declare_function("abc", Linkage::Local, &sig)
|
||||
.err()
|
||||
.unwrap(); // Make sure this is an error
|
||||
}
|
||||
|
||||
fn define_simple_function(module: &mut JITModule) -> FuncId {
|
||||
let sig = Signature {
|
||||
params: vec![],
|
||||
returns: vec![],
|
||||
call_conv: CallConv::SystemV,
|
||||
};
|
||||
|
||||
let func_id = module
|
||||
.declare_function("abc", Linkage::Local, &sig)
|
||||
.unwrap();
|
||||
|
||||
let mut ctx = Context::new();
|
||||
ctx.func = Function::with_name_signature(ExternalName::user(0, func_id.as_u32()), sig);
|
||||
let mut func_ctx = FunctionBuilderContext::new();
|
||||
{
|
||||
let mut bcx: FunctionBuilder = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
|
||||
let block = bcx.create_block();
|
||||
bcx.switch_to_block(block);
|
||||
bcx.ins().return_(&[]);
|
||||
}
|
||||
|
||||
let mut trap_sink = NullTrapSink {};
|
||||
module
|
||||
.define_function(func_id, &mut ctx, &mut trap_sink)
|
||||
.unwrap();
|
||||
|
||||
func_id
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Result::unwrap()` on an `Err` value: DuplicateDefinition(\"abc\")")]
|
||||
fn panic_on_define_after_finalize() {
|
||||
let mut flag_builder = settings::builder();
|
||||
flag_builder.set("use_colocated_libcalls", "false").unwrap();
|
||||
// FIXME set back to true once the x64 backend supports it.
|
||||
flag_builder.set("is_pic", "false").unwrap();
|
||||
let isa_builder = cranelift_native::builder().unwrap_or_else(|msg| {
|
||||
panic!("host machine is not supported: {}", msg);
|
||||
});
|
||||
let isa = isa_builder.finish(settings::Flags::new(flag_builder));
|
||||
let mut module = JITModule::new(JITBuilder::with_isa(isa, default_libcall_names()));
|
||||
|
||||
define_simple_function(&mut module);
|
||||
define_simple_function(&mut module);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switch_error() {
|
||||
use cranelift_codegen::settings;
|
||||
|
||||
let sig = Signature {
|
||||
params: vec![AbiParam::new(types::I32)],
|
||||
returns: vec![AbiParam::new(types::I32)],
|
||||
call_conv: CallConv::SystemV,
|
||||
};
|
||||
|
||||
let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
|
||||
|
||||
let mut func_ctx = FunctionBuilderContext::new();
|
||||
{
|
||||
let mut bcx: FunctionBuilder = FunctionBuilder::new(&mut func, &mut func_ctx);
|
||||
let start = bcx.create_block();
|
||||
let bb0 = bcx.create_block();
|
||||
let bb1 = bcx.create_block();
|
||||
let bb2 = bcx.create_block();
|
||||
let bb3 = bcx.create_block();
|
||||
println!("{} {} {} {} {}", start, bb0, bb1, bb2, bb3);
|
||||
|
||||
bcx.declare_var(Variable::new(0), types::I32);
|
||||
bcx.declare_var(Variable::new(1), types::I32);
|
||||
let in_val = bcx.append_block_param(start, types::I32);
|
||||
bcx.switch_to_block(start);
|
||||
bcx.def_var(Variable::new(0), in_val);
|
||||
bcx.ins().jump(bb0, &[]);
|
||||
|
||||
bcx.switch_to_block(bb0);
|
||||
let discr = bcx.use_var(Variable::new(0));
|
||||
let mut switch = cranelift_frontend::Switch::new();
|
||||
for &(index, bb) in &[
|
||||
(9, bb1),
|
||||
(13, bb1),
|
||||
(10, bb1),
|
||||
(92, bb1),
|
||||
(39, bb1),
|
||||
(34, bb1),
|
||||
] {
|
||||
switch.set_entry(index, bb);
|
||||
}
|
||||
switch.emit(&mut bcx, discr, bb2);
|
||||
|
||||
bcx.switch_to_block(bb1);
|
||||
let v = bcx.use_var(Variable::new(0));
|
||||
bcx.def_var(Variable::new(1), v);
|
||||
bcx.ins().jump(bb3, &[]);
|
||||
|
||||
bcx.switch_to_block(bb2);
|
||||
let v = bcx.use_var(Variable::new(0));
|
||||
bcx.def_var(Variable::new(1), v);
|
||||
bcx.ins().jump(bb3, &[]);
|
||||
|
||||
bcx.switch_to_block(bb3);
|
||||
let r = bcx.use_var(Variable::new(1));
|
||||
bcx.ins().return_(&[r]);
|
||||
|
||||
bcx.seal_all_blocks();
|
||||
bcx.finalize();
|
||||
}
|
||||
|
||||
let flags = settings::Flags::new(settings::builder());
|
||||
match cranelift_codegen::verify_function(&func, &flags) {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
let pretty_error =
|
||||
cranelift_codegen::print_errors::pretty_verifier_error(&func, None, None, err);
|
||||
panic!("pretty_error:\n{}", pretty_error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn libcall_function() {
|
||||
let mut flag_builder = settings::builder();
|
||||
flag_builder.set("use_colocated_libcalls", "false").unwrap();
|
||||
// FIXME set back to true once the x64 backend supports it.
|
||||
flag_builder.set("is_pic", "false").unwrap();
|
||||
let isa_builder = cranelift_native::builder().unwrap_or_else(|msg| {
|
||||
panic!("host machine is not supported: {}", msg);
|
||||
});
|
||||
let isa = isa_builder.finish(settings::Flags::new(flag_builder));
|
||||
let mut module = JITModule::new(JITBuilder::with_isa(isa, default_libcall_names()));
|
||||
|
||||
let sig = Signature {
|
||||
params: vec![],
|
||||
returns: vec![],
|
||||
call_conv: CallConv::SystemV,
|
||||
};
|
||||
|
||||
let func_id = module
|
||||
.declare_function("function", Linkage::Local, &sig)
|
||||
.unwrap();
|
||||
|
||||
let mut ctx = Context::new();
|
||||
ctx.func = Function::with_name_signature(ExternalName::user(0, func_id.as_u32()), sig);
|
||||
let mut func_ctx = FunctionBuilderContext::new();
|
||||
{
|
||||
let mut bcx: FunctionBuilder = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
|
||||
let block = bcx.create_block();
|
||||
bcx.switch_to_block(block);
|
||||
|
||||
let int = module.target_config().pointer_type();
|
||||
let zero = bcx.ins().iconst(I16, 0);
|
||||
let size = bcx.ins().iconst(int, 10);
|
||||
|
||||
let mut signature = module.make_signature();
|
||||
signature.params.push(AbiParam::new(int));
|
||||
signature.returns.push(AbiParam::new(int));
|
||||
let callee = module
|
||||
.declare_function("malloc", Linkage::Import, &signature)
|
||||
.expect("declare malloc function");
|
||||
let local_callee = module.declare_func_in_func(callee, &mut bcx.func);
|
||||
let argument_exprs = vec![size];
|
||||
let call = bcx.ins().call(local_callee, &argument_exprs);
|
||||
let buffer = bcx.inst_results(call)[0];
|
||||
|
||||
bcx.call_memset(module.target_config(), buffer, zero, size);
|
||||
|
||||
bcx.ins().return_(&[]);
|
||||
}
|
||||
|
||||
let mut trap_sink = NullTrapSink {};
|
||||
module
|
||||
.define_function(func_id, &mut ctx, &mut trap_sink)
|
||||
.unwrap();
|
||||
|
||||
module.finalize_definitions();
|
||||
}
|
||||
Reference in New Issue
Block a user