Various clippy fixes. (#403)

This commit is contained in:
Dan Gohman
2019-10-09 13:32:52 -07:00
committed by GitHub
parent 9465668199
commit fd3efad781
25 changed files with 144 additions and 160 deletions

View File

@@ -1,3 +1,5 @@
#![allow(clippy::float_cmp)]
use crate::error::Error; use crate::error::Error;
use crate::microwasm::{BrTarget, Ieee32, Ieee64, SignlessType, Type, Value, F32, F64, I32, I64}; use crate::microwasm::{BrTarget, Ieee32, Ieee64, SignlessType, Type, Value, F32, F64, I32, I64};
use crate::module::ModuleContext; use crate::module::ModuleContext;
@@ -259,7 +261,7 @@ impl GPRs {
self.bits |= 1 << gpr; self.bits |= 1 << gpr;
} }
fn is_free(&self, gpr: RegId) -> bool { fn is_free(self, gpr: RegId) -> bool {
(self.bits & (1 << gpr)) != 0 (self.bits & (1 << gpr)) != 0
} }
} }
@@ -629,7 +631,7 @@ impl TranslatedCodeSection {
.func_starts .func_starts
.get(idx + 1) .get(idx + 1)
.map(|i| i.0) .map(|i| i.0)
.unwrap_or(self.exec_buf.len()); .unwrap_or_else(|| self.exec_buf.len());
self.func_starts[idx].0..end self.func_starts[idx].0..end
} }
@@ -2299,7 +2301,7 @@ impl<'this, M: ModuleContext> Context<'this, M> {
let label = target let label = target
.into() .into()
.label() .label()
.map(|c| *c) .copied()
.unwrap_or_else(|| self.ret_label()); .unwrap_or_else(|| self.ret_label());
let cond = match val { let cond = match val {
@@ -2332,7 +2334,7 @@ impl<'this, M: ModuleContext> Context<'this, M> {
let label = target let label = target
.into() .into()
.label() .label()
.map(|c| *c) .copied()
.unwrap_or_else(|| self.ret_label()); .unwrap_or_else(|| self.ret_label());
let cond = match val { let cond = match val {
@@ -2834,8 +2836,7 @@ impl<'this, M: ModuleContext> Context<'this, M> {
dynasm!(self.asm dynasm!(self.asm
; mov DWORD [rsp + out_offset], i as i32 ; mov DWORD [rsp + out_offset], i as i32
); );
} else { } else if let Some(scratch) = self.take_reg(I64) {
if let Some(scratch) = self.take_reg(I64) {
dynasm!(self.asm dynasm!(self.asm
; mov Rq(scratch.rq().unwrap()), QWORD i ; mov Rq(scratch.rq().unwrap()), QWORD i
; mov [rsp + out_offset], Rq(scratch.rq().unwrap()) ; mov [rsp + out_offset], Rq(scratch.rq().unwrap())
@@ -2851,7 +2852,6 @@ impl<'this, M: ModuleContext> Context<'this, M> {
); );
} }
} }
}
(ValueLocation::Stack(in_offset), CCLoc::Reg(out_reg)) => { (ValueLocation::Stack(in_offset), CCLoc::Reg(out_reg)) => {
let in_offset = self.adjusted_offset(in_offset); let in_offset = self.adjusted_offset(in_offset);
match out_reg { match out_reg {
@@ -4970,7 +4970,7 @@ impl<'this, M: ModuleContext> Context<'this, M> {
self.block_state.depth.reserve(1); self.block_state.depth.reserve(1);
} }
let depth = self.block_state.depth.clone(); let depth = self.block_state.depth;
self.pass_outgoing_args(&locs); self.pass_outgoing_args(&locs);
// 2 bytes for the 64-bit `mov` opcode + register ident, the rest is the immediate // 2 bytes for the 64-bit `mov` opcode + register ident, the rest is the immediate
@@ -5083,8 +5083,7 @@ impl<'this, M: ModuleContext> Context<'this, M> {
let mut slice = &mut stack[start..end]; let mut slice = &mut stack[start..end];
loop { while let Some((first, rest)) = slice.split_first_mut() {
if let Some((first, rest)) = slice.split_first_mut() {
if let ValueLocation::Reg(vreg) = *first { if let ValueLocation::Reg(vreg) = *first {
if regs.into_iter().any(|r| *r == vreg) { if regs.into_iter().any(|r| *r == vreg) {
let old = *first; let old = *first;
@@ -5099,9 +5098,6 @@ impl<'this, M: ModuleContext> Context<'this, M> {
} }
slice = rest; slice = rest;
} else {
break;
}
} }
mem::replace(&mut self.block_state.stack, stack); mem::replace(&mut self.block_state.stack, stack);
@@ -5226,7 +5222,7 @@ impl<'this, M: ModuleContext> Context<'this, M> {
; push Rq(VMCTX) ; push Rq(VMCTX)
); );
self.block_state.depth.reserve(1); self.block_state.depth.reserve(1);
let depth = self.block_state.depth.clone(); let depth = self.block_state.depth;
self.pass_outgoing_args(&locs); self.pass_outgoing_args(&locs);
@@ -5380,7 +5376,7 @@ impl<'this, M: ModuleContext> Context<'this, M> {
; push Rq(VMCTX) ; push Rq(VMCTX)
); );
self.block_state.depth.reserve(1); self.block_state.depth.reserve(1);
let depth = self.block_state.depth.clone(); let depth = self.block_state.depth;
self.save_volatile(..locs.len()); self.save_volatile(..locs.len());
self.pass_outgoing_args(&locs); self.pass_outgoing_args(&locs);

View File

@@ -19,17 +19,13 @@ pub fn disassemble(
let address = i.address(); let address = i.address();
loop { while let Some((offset, op)) = ops.first() {
if let Some((offset, op)) = ops.first() {
if offset.0 as u64 <= address { if offset.0 as u64 <= address {
ops = &ops[1..]; ops = &ops[1..];
println!("{}", op); println!("{}", op);
} else { } else {
break; break;
} }
} else {
break;
}
} }
write!(&mut line, "{:4x}:\t", i.address())?; write!(&mut line, "{:4x}:\t", i.address())?;

View File

@@ -24,9 +24,7 @@ where
let p = " "; let p = " ";
for op in microwasm { for op in microwasm {
if op.is_label() { if op.is_label() || op.is_block() {
writeln!(out, "{}", op)?;
} else if op.is_block() {
writeln!(out, "{}", op)?; writeln!(out, "{}", op)?;
} else { } else {
writeln!(out, "{}{}", p, op)?; writeln!(out, "{}{}", p, op)?;

View File

@@ -1,5 +1,7 @@
//! Debug utils for WebAssembly using Cranelift. //! Debug utils for WebAssembly using Cranelift.
#![allow(clippy::cast_ptr_alignment)]
use alloc::string::String; use alloc::string::String;
use alloc::vec::Vec; use alloc::vec::Vec;
use cranelift_codegen::isa::TargetFrontendConfig; use cranelift_codegen::isa::TargetFrontendConfig;
@@ -66,9 +68,9 @@ pub fn emit_debugsections_image(
vmctx_info: &ModuleVmctxInfo, vmctx_info: &ModuleVmctxInfo,
at: &ModuleAddressMap, at: &ModuleAddressMap,
ranges: &ValueLabelsRanges, ranges: &ValueLabelsRanges,
funcs: &Vec<(*const u8, usize)>, funcs: &[(*const u8, usize)],
) -> Result<Vec<u8>, Error> { ) -> Result<Vec<u8>, Error> {
let ref func_offsets = funcs let func_offsets = &funcs
.iter() .iter()
.map(|(ptr, _)| *ptr as u64) .map(|(ptr, _)| *ptr as u64)
.collect::<Vec<u64>>(); .collect::<Vec<u64>>();
@@ -79,7 +81,7 @@ pub fn emit_debugsections_image(
// Assuming all functions in the same code block, looking min/max of its range. // Assuming all functions in the same code block, looking min/max of its range.
assert!(funcs.len() > 0); assert!(funcs.len() > 0);
let mut segment_body: (usize, usize) = (!0, 0); let mut segment_body: (usize, usize) = (!0, 0);
for (body_ptr, body_len) in funcs.iter() { for (body_ptr, body_len) in funcs {
segment_body.0 = ::core::cmp::min(segment_body.0, *body_ptr as usize); segment_body.0 = ::core::cmp::min(segment_body.0, *body_ptr as usize);
segment_body.1 = ::core::cmp::max(segment_body.1, *body_ptr as usize + body_len); segment_body.1 = ::core::cmp::max(segment_body.1, *body_ptr as usize + body_len);
} }
@@ -168,8 +170,7 @@ fn convert_faerie_elf_to_loadable_file(bytes: &mut Vec<u8>, code_ptr: *const u8)
// LLDB wants segment with virtual address set, placing them at the end of ELF. // LLDB wants segment with virtual address set, placing them at the end of ELF.
let ph_off = bytes.len(); let ph_off = bytes.len();
if let Some((sh_offset, v_offset, sh_size)) = segment { if let Some((sh_offset, v_offset, sh_size)) = segment {
let mut segment = Vec::with_capacity(0x38); let segment = vec![0; 0x38];
segment.resize(0x38, 0);
unsafe { unsafe {
*(segment.as_ptr() as *mut u32) = /* PT_LOAD */ 0x1; *(segment.as_ptr() as *mut u32) = /* PT_LOAD */ 0x1;
*(segment.as_ptr().offset(0x8) as *mut u64) = sh_offset; *(segment.as_ptr().offset(0x8) as *mut u64) = sh_offset;

View File

@@ -39,7 +39,7 @@ pub(crate) fn clone_die_attributes<'a, R>(
context: &DebugInputContext<R>, context: &DebugInputContext<R>,
addr_tr: &'a AddressTransform, addr_tr: &'a AddressTransform,
frame_info: Option<&FunctionFrameInfo>, frame_info: Option<&FunctionFrameInfo>,
unit_encoding: &gimli::Encoding, unit_encoding: gimli::Encoding,
out_unit: &mut write::Unit, out_unit: &mut write::Unit,
current_scope_id: write::UnitEntryId, current_scope_id: write::UnitEntryId,
subprogram_range_builder: Option<RangeInfoBuilder>, subprogram_range_builder: Option<RangeInfoBuilder>,
@@ -58,15 +58,13 @@ where
let range_info = if let Some(subprogram_range_builder) = subprogram_range_builder { let range_info = if let Some(subprogram_range_builder) = subprogram_range_builder {
subprogram_range_builder subprogram_range_builder
} else { } else if entry.tag() == gimli::DW_TAG_compile_unit {
if entry.tag() == gimli::DW_TAG_compile_unit {
// FIXME currently address_transform operate on a single func range, // FIXME currently address_transform operate on a single func range,
// once it is fixed we can properly set DW_AT_ranges attribute. // once it is fixed we can properly set DW_AT_ranges attribute.
// Using for now DW_AT_low_pc = 0. // Using for now DW_AT_low_pc = 0.
RangeInfoBuilder::Position(0) RangeInfoBuilder::Position(0)
} else { } else {
RangeInfoBuilder::from(entry, context, unit_encoding, cu_low_pc)? RangeInfoBuilder::from(entry, context, unit_encoding, cu_low_pc)?
}
}; };
range_info.build(addr_tr, out_unit, current_scope_id); range_info.build(addr_tr, out_unit, current_scope_id);
@@ -127,7 +125,7 @@ where
let low_pc = 0; let low_pc = 0;
let mut locs = context.loclists.locations( let mut locs = context.loclists.locations(
r, r,
*unit_encoding, unit_encoding,
low_pc, low_pc,
&context.debug_addr, &context.debug_addr,
context.debug_addr_base, context.debug_addr_base,
@@ -190,7 +188,7 @@ where
if let Some(scope_ranges) = scope_ranges { if let Some(scope_ranges) = scope_ranges {
let exprs = let exprs =
expr.build_with_locals(scope_ranges, addr_tr, frame_info, endian); expr.build_with_locals(scope_ranges, addr_tr, frame_info, endian);
if exprs.len() == 0 { if exprs.is_empty() {
continue; continue;
} }
let found_single_expr = { let found_single_expr = {

View File

@@ -176,7 +176,7 @@ impl CompiledExpression {
if let [CompiledExpressionPart::Code(_)] = self.parts.as_slice() { if let [CompiledExpressionPart::Code(_)] = self.parts.as_slice() {
true true
} else { } else {
self.parts.len() == 0 self.parts.is_empty()
} }
} }
@@ -195,7 +195,7 @@ impl CompiledExpression {
frame_info: Option<&FunctionFrameInfo>, frame_info: Option<&FunctionFrameInfo>,
endian: gimli::RunTimeEndian, endian: gimli::RunTimeEndian,
) -> alloc::vec::Vec<(write::Address, u64, write::Expression)> { ) -> alloc::vec::Vec<(write::Address, u64, write::Expression)> {
if scope.len() == 0 { if scope.is_empty() {
return vec![]; return vec![];
} }
@@ -286,13 +286,13 @@ impl CompiledExpression {
)); ));
} }
return result; result
} }
} }
pub fn compile_expression<R>( pub fn compile_expression<R>(
expr: &Expression<R>, expr: &Expression<R>,
encoding: &gimli::Encoding, encoding: gimli::Encoding,
frame_base: Option<&CompiledExpression>, frame_base: Option<&CompiledExpression>,
) -> Result<Option<CompiledExpression>, Error> ) -> Result<Option<CompiledExpression>, Error>
where where
@@ -326,7 +326,7 @@ where
parts.push(CompiledExpressionPart::Local(label)); parts.push(CompiledExpressionPart::Local(label));
} else { } else {
let pos = pc.offset_from(&expr.0).into_u64() as usize; let pos = pc.offset_from(&expr.0).into_u64() as usize;
let op = Operation::parse(&mut pc, &expr.0, *encoding)?; let op = Operation::parse(&mut pc, &expr.0, encoding)?;
match op { match op {
Operation::Literal { .. } | Operation::PlusConstant { .. } => (), Operation::Literal { .. } | Operation::PlusConstant { .. } => (),
Operation::StackValue => { Operation::StackValue => {

View File

@@ -43,7 +43,7 @@ pub(crate) fn clone_line_program<R>(
unit: &Unit<R, R::Offset>, unit: &Unit<R, R::Offset>,
root: &DebuggingInformationEntry<R>, root: &DebuggingInformationEntry<R>,
addr_tr: &AddressTransform, addr_tr: &AddressTransform,
out_encoding: &gimli::Encoding, out_encoding: gimli::Encoding,
debug_str: &DebugStr<R>, debug_str: &DebugStr<R>,
debug_line: &DebugLine<R>, debug_line: &DebugLine<R>,
out_strings: &mut write::StringTable, out_strings: &mut write::StringTable,
@@ -89,7 +89,7 @@ where
line_range: header.line_range(), line_range: header.line_range(),
}; };
let mut out_program = write::LineProgram::new( let mut out_program = write::LineProgram::new(
*out_encoding, out_encoding,
line_encoding, line_encoding,
out_comp_dir, out_comp_dir,
out_comp_name, out_comp_name,

View File

@@ -90,7 +90,7 @@ pub fn transform_dwarf(
&context, &context,
&addr_tr, &addr_tr,
&ranges, &ranges,
&out_encoding, out_encoding,
&vmctx_info, &vmctx_info,
&mut out_units, &mut out_units,
&mut out_strings, &mut out_strings,
@@ -104,7 +104,7 @@ pub fn transform_dwarf(
&vmctx_info, &vmctx_info,
&ranges, &ranges,
&translated, &translated,
&out_encoding, out_encoding,
&mut out_units, &mut out_units,
&mut out_strings, &mut out_strings,
)?; )?;

View File

@@ -24,7 +24,7 @@ impl RangeInfoBuilder {
pub(crate) fn from<R>( pub(crate) fn from<R>(
entry: &DebuggingInformationEntry<R>, entry: &DebuggingInformationEntry<R>,
context: &DebugInputContext<R>, context: &DebugInputContext<R>,
unit_encoding: &gimli::Encoding, unit_encoding: gimli::Encoding,
cu_low_pc: u64, cu_low_pc: u64,
) -> Result<Self, Error> ) -> Result<Self, Error>
where where
@@ -53,7 +53,7 @@ impl RangeInfoBuilder {
pub(crate) fn from_ranges_ref<R>( pub(crate) fn from_ranges_ref<R>(
ranges: RangeListsOffset, ranges: RangeListsOffset,
context: &DebugInputContext<R>, context: &DebugInputContext<R>,
unit_encoding: &gimli::Encoding, unit_encoding: gimli::Encoding,
cu_low_pc: u64, cu_low_pc: u64,
) -> Result<Self, Error> ) -> Result<Self, Error>
where where
@@ -61,7 +61,7 @@ impl RangeInfoBuilder {
{ {
let mut ranges = context.rnglists.ranges( let mut ranges = context.rnglists.ranges(
ranges, ranges,
*unit_encoding, unit_encoding,
cu_low_pc, cu_low_pc,
&context.debug_addr, &context.debug_addr,
context.debug_addr_base, context.debug_addr_base,
@@ -74,17 +74,17 @@ impl RangeInfoBuilder {
result.push((range.begin, range.end)); result.push((range.begin, range.end));
} }
return Ok(if result.len() > 0 { Ok(if result.len() > 0 {
RangeInfoBuilder::Ranges(result) RangeInfoBuilder::Ranges(result)
} else { } else {
RangeInfoBuilder::Undefined RangeInfoBuilder::Undefined
}); })
} }
pub(crate) fn from_subprogram_die<R>( pub(crate) fn from_subprogram_die<R>(
entry: &DebuggingInformationEntry<R>, entry: &DebuggingInformationEntry<R>,
context: &DebugInputContext<R>, context: &DebugInputContext<R>,
unit_encoding: &gimli::Encoding, unit_encoding: gimli::Encoding,
addr_tr: &AddressTransform, addr_tr: &AddressTransform,
cu_low_pc: u64, cu_low_pc: u64,
) -> Result<Self, Error> ) -> Result<Self, Error>
@@ -99,7 +99,7 @@ impl RangeInfoBuilder {
{ {
let mut ranges = context.rnglists.ranges( let mut ranges = context.rnglists.ranges(
r, r,
*unit_encoding, unit_encoding,
cu_low_pc, cu_low_pc,
&context.debug_addr, &context.debug_addr,
context.debug_addr_base, context.debug_addr_base,

View File

@@ -21,7 +21,7 @@ const PRODUCER_NAME: &str = "wasmtime";
fn generate_line_info( fn generate_line_info(
addr_tr: &AddressTransform, addr_tr: &AddressTransform,
translated: &HashSet<u32>, translated: &HashSet<u32>,
out_encoding: &gimli::Encoding, out_encoding: gimli::Encoding,
w: &WasmFileInfo, w: &WasmFileInfo,
comp_dir_id: write::StringId, comp_dir_id: write::StringId,
name_id: write::StringId, name_id: write::StringId,
@@ -33,7 +33,7 @@ fn generate_line_info(
let line_encoding = LineEncoding::default(); let line_encoding = LineEncoding::default();
let mut out_program = write::LineProgram::new( let mut out_program = write::LineProgram::new(
*out_encoding, out_encoding,
line_encoding, line_encoding,
out_comp_dir, out_comp_dir,
out_comp_name, out_comp_name,
@@ -181,7 +181,7 @@ fn generate_vars(
) { ) {
let vmctx_label = get_vmctx_value_label(); let vmctx_label = get_vmctx_value_label();
for (label, _range) in frame_info.value_ranges { for label in frame_info.value_ranges.keys() {
if label.index() == vmctx_label.index() { if label.index() == vmctx_label.index() {
append_vmctx_info( append_vmctx_info(
unit, unit,
@@ -206,7 +206,7 @@ fn generate_vars(
let loc_list_id = { let loc_list_id = {
let endian = gimli::RunTimeEndian::Little; let endian = gimli::RunTimeEndian::Little;
let expr = CompiledExpression::from_label(label.clone()); let expr = CompiledExpression::from_label(*label);
let mut locs = Vec::new(); let mut locs = Vec::new();
for (begin, length, data) in for (begin, length, data) in
expr.build_with_locals(scope_ranges, addr_tr, Some(frame_info), endian) expr.build_with_locals(scope_ranges, addr_tr, Some(frame_info), endian)
@@ -254,7 +254,7 @@ pub fn generate_simulated_dwarf(
vmctx_info: &ModuleVmctxInfo, vmctx_info: &ModuleVmctxInfo,
ranges: &ValueLabelsRanges, ranges: &ValueLabelsRanges,
translated: &HashSet<u32>, translated: &HashSet<u32>,
out_encoding: &gimli::Encoding, out_encoding: gimli::Encoding,
out_units: &mut write::UnitTable, out_units: &mut write::UnitTable,
out_strings: &mut write::StringTable, out_strings: &mut write::StringTable,
) -> Result<(), Error> { ) -> Result<(), Error> {
@@ -288,7 +288,7 @@ pub fn generate_simulated_dwarf(
name, name,
)?; )?;
let unit_id = out_units.add(write::Unit::new(*out_encoding, out_program)); let unit_id = out_units.add(write::Unit::new(out_encoding, out_program));
let unit = out_units.get_mut(unit_id); let unit = out_units.get_mut(unit_id);
let root_id = unit.root(); let root_id = unit.root();

View File

@@ -157,7 +157,7 @@ pub(crate) fn clone_unit<'a, R>(
context: &DebugInputContext<R>, context: &DebugInputContext<R>,
addr_tr: &'a AddressTransform, addr_tr: &'a AddressTransform,
value_ranges: &'a ValueLabelsRanges, value_ranges: &'a ValueLabelsRanges,
out_encoding: &gimli::Encoding, out_encoding: gimli::Encoding,
module_info: &ModuleVmctxInfo, module_info: &ModuleVmctxInfo,
out_units: &mut write::UnitTable, out_units: &mut write::UnitTable,
out_strings: &mut write::StringTable, out_strings: &mut write::StringTable,
@@ -186,7 +186,7 @@ where
)?; )?;
if entry.tag() == gimli::DW_TAG_compile_unit { if entry.tag() == gimli::DW_TAG_compile_unit {
let unit_id = out_units.add(write::Unit::new(*out_encoding, out_line_program)); let unit_id = out_units.add(write::Unit::new(out_encoding, out_line_program));
let comp_unit = out_units.get_mut(unit_id); let comp_unit = out_units.get_mut(unit_id);
let root_id = comp_unit.root(); let root_id = comp_unit.root();
@@ -206,7 +206,7 @@ where
context, context,
addr_tr, addr_tr,
None, None,
&unit.encoding(), unit.encoding(),
comp_unit, comp_unit,
root_id, root_id,
None, None,
@@ -263,7 +263,7 @@ where
let range_builder = RangeInfoBuilder::from_subprogram_die( let range_builder = RangeInfoBuilder::from_subprogram_die(
entry, entry,
context, context,
&unit.encoding(), unit.encoding(),
addr_tr, addr_tr,
cu_low_pc, cu_low_pc,
)?; )?;
@@ -285,7 +285,7 @@ where
let ranges = entry.attr_value(gimli::DW_AT_ranges)?; let ranges = entry.attr_value(gimli::DW_AT_ranges)?;
if high_pc.is_some() || ranges.is_some() { if high_pc.is_some() || ranges.is_some() {
let range_builder = let range_builder =
RangeInfoBuilder::from(entry, context, &unit.encoding(), cu_low_pc)?; RangeInfoBuilder::from(entry, context, unit.encoding(), cu_low_pc)?;
current_scope_ranges.push(new_stack_len, range_builder.get_ranges(addr_tr)); current_scope_ranges.push(new_stack_len, range_builder.get_ranges(addr_tr));
Some(range_builder) Some(range_builder)
} else { } else {
@@ -302,7 +302,7 @@ where
} }
if let Some(AttributeValue::Exprloc(expr)) = entry.attr_value(gimli::DW_AT_frame_base)? { if let Some(AttributeValue::Exprloc(expr)) = entry.attr_value(gimli::DW_AT_frame_base)? {
if let Some(expr) = compile_expression(&expr, &unit.encoding(), None)? { if let Some(expr) = compile_expression(&expr, unit.encoding(), None)? {
current_frame_base.push(new_stack_len, expr); current_frame_base.push(new_stack_len, expr);
} }
} }
@@ -339,7 +339,7 @@ where
context, context,
addr_tr, addr_tr,
current_value_range.top(), current_value_range.top(),
&unit.encoding(), unit.encoding(),
&mut comp_unit, &mut comp_unit,
die_id, die_id,
range_builder, range_builder,

View File

@@ -39,13 +39,11 @@ lazy_static! {
.map_err(|_| warn!("Failed to get metadata of current executable")) .map_err(|_| warn!("Failed to get metadata of current executable"))
.ok() .ok()
}) })
.and_then(|mtime| { .map(|mtime| match mtime.duration_since(std::time::UNIX_EPOCH) {
Some(match mtime.duration_since(std::time::UNIX_EPOCH) {
Ok(duration) => format!("{}", duration.as_millis()), Ok(duration) => format!("{}", duration.as_millis()),
Err(err) => format!("m{}", err.duration().as_millis()), Err(err) => format!("m{}", err.duration().as_millis()),
}) })
}) .unwrap_or_else(|| "no-mtime".to_string())
.unwrap_or("no-mtime".to_string())
}; };
} }

View File

@@ -103,7 +103,7 @@ static INIT_CALLED: AtomicBool = AtomicBool::new(false);
/// If system has not been initialized, it disables it. /// If system has not been initialized, it disables it.
/// You mustn't call init() after it. /// You mustn't call init() after it.
pub fn cache_config() -> &'static CacheConfig { pub fn cache_config() -> &'static CacheConfig {
CONFIG.call_once(|| CacheConfig::new_cache_disabled()) CONFIG.call_once(CacheConfig::new_cache_disabled)
} }
/// Initializes the cache system. Should be called exactly once, /// Initializes the cache system. Should be called exactly once,
@@ -196,7 +196,7 @@ lazy_static! {
static ref DEFAULT_CONFIG_PATH: Result<PathBuf, String> = PROJECT_DIRS static ref DEFAULT_CONFIG_PATH: Result<PathBuf, String> = PROJECT_DIRS
.as_ref() .as_ref()
.map(|proj_dirs| proj_dirs.config_dir().join("wasmtime-cache-config.toml")) .map(|proj_dirs| proj_dirs.config_dir().join("wasmtime-cache-config.toml"))
.ok_or("Config file not specified and failed to get the default".to_string()); .ok_or_else(|| "Config file not specified and failed to get the default".to_string());
} }
// Default settings, you're welcome to tune them! // Default settings, you're welcome to tune them!
@@ -312,7 +312,7 @@ generate_deserializer!(deserialize_percent(num: u8, unit: &str) -> Option<u8> {
} }
}); });
static CACHE_IMPROPER_CONFIG_ERROR_MSG: &'static str = static CACHE_IMPROPER_CONFIG_ERROR_MSG: &str =
"Cache system should be enabled and all settings must be validated or defaulted"; "Cache system should be enabled and all settings must be validated or defaulted";
macro_rules! generate_setting_getter { macro_rules! generate_setting_getter {

View File

@@ -105,7 +105,7 @@ impl Worker {
Self { Self {
sender: tx, sender: tx,
#[cfg(test)] #[cfg(test)]
stats: stats, stats,
} }
} }
@@ -610,7 +610,7 @@ impl WorkerThread {
(0..=1, true) => enter_dir(vec, &path, level + 1, cache_config), (0..=1, true) => enter_dir(vec, &path, level + 1, cache_config),
(0..=1, false) => { (0..=1, false) => {
if level == 0 && path.file_stem() == Some(OsStr::new(".cleanup")) { if level == 0 && path.file_stem() == Some(OsStr::new(".cleanup")) {
if let Some(_) = path.extension() { if path.extension().is_some() {
// assume it's cleanup lock // assume it's cleanup lock
if !is_fs_lock_expired( if !is_fs_lock_expired(
Some(&entry), Some(&entry),
@@ -699,9 +699,11 @@ impl WorkerThread {
"Failed to get metadata/mtime, deleting the file", "Failed to get metadata/mtime, deleting the file",
stats_path stats_path
); );
// .into() called for the SystemTimeStub if cfg(test)
#[allow(clippy::identity_conversion)]
vec.push(CacheEntry::Recognized { vec.push(CacheEntry::Recognized {
path: mod_path.to_path_buf(), path: mod_path.to_path_buf(),
mtime: stats_mtime.into(), // .into() called for the SystemTimeStub if cfg(test) mtime: stats_mtime.into(),
size: mod_metadata.len(), size: mod_metadata.len(),
}) })
} }
@@ -715,9 +717,11 @@ impl WorkerThread {
"Failed to get metadata/mtime, deleting the file", "Failed to get metadata/mtime, deleting the file",
mod_path mod_path
); );
// .into() called for the SystemTimeStub if cfg(test)
#[allow(clippy::identity_conversion)]
vec.push(CacheEntry::Recognized { vec.push(CacheEntry::Recognized {
path: mod_path.to_path_buf(), path: mod_path.to_path_buf(),
mtime: mod_mtime.into(), // .into() called for the SystemTimeStub if cfg(test) mtime: mod_mtime.into(),
size: mod_metadata.len(), size: mod_metadata.len(),
}) })
} }

View File

@@ -298,7 +298,7 @@ impl crate::compilation::Compiler for Cranelift {
if let Some(address_transform) = address_transform { if let Some(address_transform) = address_transform {
address_transforms.push(address_transform); address_transforms.push(address_transform);
} }
value_ranges.push(ranges.unwrap_or(std::collections::HashMap::new())); value_ranges.push(ranges.unwrap_or_default());
stack_slots.push(sss); stack_slots.push(sss);
traps.push(function_traps); traps.push(function_traps);
}, },

View File

@@ -239,13 +239,13 @@ impl lightbeam::ModuleContext for FuncEnvironment<'_> {
fn defined_func_index(&self, func_index: u32) -> Option<u32> { fn defined_func_index(&self, func_index: u32) -> Option<u32> {
self.module self.module
.defined_func_index(FuncIndex::from_u32(func_index)) .defined_func_index(FuncIndex::from_u32(func_index))
.map(|i| i.as_u32()) .map(DefinedFuncIndex::as_u32)
} }
fn defined_global_index(&self, global_index: u32) -> Option<u32> { fn defined_global_index(&self, global_index: u32) -> Option<u32> {
self.module self.module
.defined_global_index(GlobalIndex::from_u32(global_index)) .defined_global_index(GlobalIndex::from_u32(global_index))
.map(|i| i.as_u32()) .map(DefinedGlobalIndex::as_u32)
} }
fn global_type(&self, global_index: u32) -> &Self::GlobalType { fn global_type(&self, global_index: u32) -> &Self::GlobalType {
@@ -263,13 +263,13 @@ impl lightbeam::ModuleContext for FuncEnvironment<'_> {
fn defined_table_index(&self, table_index: u32) -> Option<u32> { fn defined_table_index(&self, table_index: u32) -> Option<u32> {
self.module self.module
.defined_table_index(TableIndex::from_u32(table_index)) .defined_table_index(TableIndex::from_u32(table_index))
.map(|i| i.as_u32()) .map(DefinedTableIndex::as_u32)
} }
fn defined_memory_index(&self, memory_index: u32) -> Option<u32> { fn defined_memory_index(&self, memory_index: u32) -> Option<u32> {
self.module self.module
.defined_memory_index(MemoryIndex::from_u32(memory_index)) .defined_memory_index(MemoryIndex::from_u32(memory_index))
.map(|i| i.as_u32()) .map(DefinedMemoryIndex::as_u32)
} }
fn vmctx_vmfunction_import_body(&self, func_index: u32) -> u32 { fn vmctx_vmfunction_import_body(&self, func_index: u32) -> u32 {

View File

@@ -61,7 +61,7 @@ impl MemoryStyle {
// it static. // it static.
assert!(tunables.static_memory_bound >= memory.minimum); assert!(tunables.static_memory_bound >= memory.minimum);
return ( return (
MemoryStyle::Static { Self::Static {
bound: tunables.static_memory_bound, bound: tunables.static_memory_bound,
}, },
tunables.static_memory_offset_guard_size, tunables.static_memory_offset_guard_size,
@@ -70,10 +70,7 @@ impl MemoryStyle {
} }
// Otherwise, make it dynamic. // Otherwise, make it dynamic.
( (Self::Dynamic, tunables.dynamic_memory_offset_guard_size)
MemoryStyle::Dynamic,
tunables.dynamic_memory_offset_guard_size,
)
} }
} }
@@ -111,7 +108,7 @@ pub enum TableStyle {
impl TableStyle { impl TableStyle {
/// Decide on an implementation style for the given `Table`. /// Decide on an implementation style for the given `Table`.
pub fn for_table(_table: Table, _tunables: &Tunables) -> Self { pub fn for_table(_table: Table, _tunables: &Tunables) -> Self {
TableStyle::CallerChecksSignature Self::CallerChecksSignature
} }
} }

View File

@@ -557,11 +557,11 @@ pub struct TargetSharedSignatureIndex(u32);
impl TargetSharedSignatureIndex { impl TargetSharedSignatureIndex {
/// Constructs `TargetSharedSignatureIndex`. /// Constructs `TargetSharedSignatureIndex`.
pub fn new(value: u32) -> Self { pub fn new(value: u32) -> Self {
TargetSharedSignatureIndex(value) Self(value)
} }
/// Returns index value. /// Returns index value.
pub fn index(&self) -> u32 { pub fn index(self) -> u32 {
self.0 self.0
} }
} }

View File

@@ -28,18 +28,18 @@ impl RuntimeValue {
/// Return the type of this `RuntimeValue`. /// Return the type of this `RuntimeValue`.
pub fn value_type(self) -> ir::Type { pub fn value_type(self) -> ir::Type {
match self { match self {
RuntimeValue::I32(_) => ir::types::I32, Self::I32(_) => ir::types::I32,
RuntimeValue::I64(_) => ir::types::I64, Self::I64(_) => ir::types::I64,
RuntimeValue::F32(_) => ir::types::F32, Self::F32(_) => ir::types::F32,
RuntimeValue::F64(_) => ir::types::F64, Self::F64(_) => ir::types::F64,
RuntimeValue::V128(_) => ir::types::I8X16, Self::V128(_) => ir::types::I8X16,
} }
} }
/// Assuming this `RuntimeValue` holds an `i32`, return that value. /// Assuming this `RuntimeValue` holds an `i32`, return that value.
pub fn unwrap_i32(self) -> i32 { pub fn unwrap_i32(self) -> i32 {
match self { match self {
RuntimeValue::I32(x) => x, Self::I32(x) => x,
_ => panic!("unwrapping value of type {} as i32", self.value_type()), _ => panic!("unwrapping value of type {} as i32", self.value_type()),
} }
} }
@@ -47,7 +47,7 @@ impl RuntimeValue {
/// Assuming this `RuntimeValue` holds an `i64`, return that value. /// Assuming this `RuntimeValue` holds an `i64`, return that value.
pub fn unwrap_i64(self) -> i64 { pub fn unwrap_i64(self) -> i64 {
match self { match self {
RuntimeValue::I64(x) => x, Self::I64(x) => x,
_ => panic!("unwrapping value of type {} as i64", self.value_type()), _ => panic!("unwrapping value of type {} as i64", self.value_type()),
} }
} }
@@ -60,7 +60,7 @@ impl RuntimeValue {
/// Assuming this `RuntimeValue` holds an `f32`, return the bits of that value as a `u32`. /// Assuming this `RuntimeValue` holds an `f32`, return the bits of that value as a `u32`.
pub fn unwrap_f32_bits(self) -> u32 { pub fn unwrap_f32_bits(self) -> u32 {
match self { match self {
RuntimeValue::F32(x) => x, Self::F32(x) => x,
_ => panic!("unwrapping value of type {} as f32", self.value_type()), _ => panic!("unwrapping value of type {} as f32", self.value_type()),
} }
} }
@@ -73,7 +73,7 @@ impl RuntimeValue {
/// Assuming this `RuntimeValue` holds an `f64`, return the bits of that value as a `u64`. /// Assuming this `RuntimeValue` holds an `f64`, return the bits of that value as a `u64`.
pub fn unwrap_f64_bits(self) -> u64 { pub fn unwrap_f64_bits(self) -> u64 {
match self { match self {
RuntimeValue::F64(x) => x, Self::F64(x) => x,
_ => panic!("unwrapping value of type {} as f64", self.value_type()), _ => panic!("unwrapping value of type {} as f64", self.value_type()),
} }
} }
@@ -82,11 +82,11 @@ impl RuntimeValue {
impl fmt::Display for RuntimeValue { impl fmt::Display for RuntimeValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
RuntimeValue::I32(x) => write!(f, "{}: i32", x), Self::I32(x) => write!(f, "{}: i32", x),
RuntimeValue::I64(x) => write!(f, "{}: i64", x), Self::I64(x) => write!(f, "{}: i64", x),
RuntimeValue::F32(x) => write!(f, "{}: f32", x), Self::F32(x) => write!(f, "{}: f32", x),
RuntimeValue::F64(x) => write!(f, "{}: f64", x), Self::F64(x) => write!(f, "{}: f64", x),
RuntimeValue::V128(x) => write!(f, "{:?}: v128", x.to_vec()), Self::V128(x) => write!(f, "{:?}: v128", x.to_vec()),
} }
} }
} }

View File

@@ -1,3 +1,5 @@
#![allow(clippy::cast_ptr_alignment)]
use alloc::boxed::Box; use alloc::boxed::Box;
use alloc::vec::Vec; use alloc::vec::Vec;
use core::ptr; use core::ptr;
@@ -19,8 +21,7 @@ pub fn layout_vmcontext(
) -> (Box<[u8]>, Box<[TableRelocation]>) { ) -> (Box<[u8]>, Box<[TableRelocation]>) {
let ofs = VMOffsets::new(target_config.pointer_bytes(), &module); let ofs = VMOffsets::new(target_config.pointer_bytes(), &module);
let out_len = ofs.size_of_vmctx() as usize; let out_len = ofs.size_of_vmctx() as usize;
let mut out = Vec::with_capacity(out_len); let mut out = vec![0; out_len];
out.resize(out_len, 0);
// Assign unique indicies to unique signatures. // Assign unique indicies to unique signatures.
let mut signature_registry = HashMap::new(); let mut signature_registry = HashMap::new();

View File

@@ -56,7 +56,7 @@ impl Export {
vmctx: *mut VMContext, vmctx: *mut VMContext,
signature: ir::Signature, signature: ir::Signature,
) -> Self { ) -> Self {
Export::Function { Self::Function {
address, address,
vmctx, vmctx,
signature, signature,
@@ -69,7 +69,7 @@ impl Export {
vmctx: *mut VMContext, vmctx: *mut VMContext,
table: TablePlan, table: TablePlan,
) -> Self { ) -> Self {
Export::Table { Self::Table {
definition, definition,
vmctx, vmctx,
table, table,
@@ -82,7 +82,7 @@ impl Export {
vmctx: *mut VMContext, vmctx: *mut VMContext,
memory: MemoryPlan, memory: MemoryPlan,
) -> Self { ) -> Self {
Export::Memory { Self::Memory {
definition, definition,
vmctx, vmctx,
memory, memory,
@@ -95,7 +95,7 @@ impl Export {
vmctx: *mut VMContext, vmctx: *mut VMContext,
global: Global, global: Global,
) -> Self { ) -> Self {
Export::Global { Self::Global {
definition, definition,
vmctx, vmctx,
global, global,

View File

@@ -475,8 +475,8 @@ impl Instance {
} else if let Some(start_export) = self.module.exports.get("_start") { } else if let Some(start_export) = self.module.exports.get("_start") {
// As a compatibility measure, if the module doesn't have a start // As a compatibility measure, if the module doesn't have a start
// function but does have a _start function exported, call that. // function but does have a _start function exported, call that.
match start_export { match *start_export {
&wasmtime_environ::Export::Function(func_index) => { wasmtime_environ::Export::Function(func_index) => {
let sig = &self.module.signatures[self.module.functions[func_index]]; let sig = &self.module.signatures[self.module.functions[func_index]];
// No wasm params or returns; just the vmctx param. // No wasm params or returns; just the vmctx param.
if sig.params.len() == 1 && sig.returns.is_empty() { if sig.params.len() == 1 && sig.returns.is_empty() {
@@ -491,8 +491,8 @@ impl Instance {
// As a further compatibility measure, if the module doesn't have a // As a further compatibility measure, if the module doesn't have a
// start function or a _start function exported, but does have a main // start function or a _start function exported, but does have a main
// function exported, call that. // function exported, call that.
match main_export { match *main_export {
&wasmtime_environ::Export::Function(func_index) => { wasmtime_environ::Export::Function(func_index) => {
let sig = &self.module.signatures[self.module.functions[func_index]]; let sig = &self.module.signatures[self.module.functions[func_index]];
// No wasm params or returns; just the vmctx param. // No wasm params or returns; just the vmctx param.
if sig.params.len() == 1 && sig.returns.is_empty() { if sig.params.len() == 1 && sig.returns.is_empty() {

View File

@@ -53,8 +53,8 @@ pub struct GdbJitImageRegistration {
impl GdbJitImageRegistration { impl GdbJitImageRegistration {
/// Registers JIT image using __jit_debug_register_code /// Registers JIT image using __jit_debug_register_code
pub fn register(file: Vec<u8>) -> GdbJitImageRegistration { pub fn register(file: Vec<u8>) -> Self {
GdbJitImageRegistration { Self {
entry: unsafe { register_gdb_jit_image(&file) }, entry: unsafe { register_gdb_jit_image(&file) },
file, file,
} }
@@ -83,7 +83,7 @@ unsafe fn register_gdb_jit_image(file: &[u8]) -> *mut JITCodeEntry {
symfile_size: file.len() as u64, symfile_size: file.len() as u64,
})); }));
// Add it to the linked list in the JIT descriptor. // Add it to the linked list in the JIT descriptor.
if __jit_debug_descriptor.first_entry != ptr::null_mut() { if !__jit_debug_descriptor.first_entry.is_null() {
(*__jit_debug_descriptor.first_entry).prev_entry = entry; (*__jit_debug_descriptor.first_entry).prev_entry = entry;
} }
__jit_debug_descriptor.first_entry = entry; __jit_debug_descriptor.first_entry = entry;
@@ -100,12 +100,12 @@ unsafe fn register_gdb_jit_image(file: &[u8]) -> *mut JITCodeEntry {
unsafe fn unregister_gdb_jit_image(entry: *mut JITCodeEntry) { unsafe fn unregister_gdb_jit_image(entry: *mut JITCodeEntry) {
// Remove the code entry corresponding to the code from the linked list. // Remove the code entry corresponding to the code from the linked list.
if (*entry).prev_entry != ptr::null_mut() { if !(*entry).prev_entry.is_null() {
(*(*entry).prev_entry).next_entry = (*entry).next_entry; (*(*entry).prev_entry).next_entry = (*entry).next_entry;
} else { } else {
__jit_debug_descriptor.first_entry = (*entry).next_entry; __jit_debug_descriptor.first_entry = (*entry).next_entry;
} }
if (*entry).next_entry != ptr::null_mut() { if !(*entry).next_entry.is_null() {
(*(*entry).next_entry).prev_entry = (*entry).prev_entry; (*(*entry).next_entry).prev_entry = (*entry).prev_entry;
} }
// Point the relevant_entry field of the descriptor at the code entry. // Point the relevant_entry field of the descriptor at the code entry.

View File

@@ -24,13 +24,12 @@ impl Table {
unimplemented!("tables of types other than anyfunc ({})", ty) unimplemented!("tables of types other than anyfunc ({})", ty)
} }
}; };
assert!(
plan.table.minimum <= core::u32::MAX,
"Invariant check: vec.len() <= u32::MAX"
);
match plan.style { match plan.style {
TableStyle::CallerChecksSignature => Self { TableStyle::CallerChecksSignature => Self {
vec: vec![VMCallerCheckedAnyfunc::default(); plan.table.minimum as usize], vec: vec![
VMCallerCheckedAnyfunc::default();
usize::try_from(plan.table.minimum).unwrap()
],
maximum: plan.table.maximum, maximum: plan.table.maximum,
}, },
} }
@@ -59,10 +58,6 @@ impl Table {
return None; return None;
} }
}; };
assert!(
new_len <= core::u32::MAX,
"Invariant check: vec.len() <= u32::MAX"
);
self.vec.resize( self.vec.resize(
usize::try_from(new_len).unwrap(), usize::try_from(new_len).unwrap(),
VMCallerCheckedAnyfunc::default(), VMCallerCheckedAnyfunc::default(),

View File

@@ -450,13 +450,13 @@ mod test_vmshared_signature_index {
impl VMSharedSignatureIndex { impl VMSharedSignatureIndex {
/// Create a new `VMSharedSignatureIndex`. /// Create a new `VMSharedSignatureIndex`.
pub fn new(value: u32) -> Self { pub fn new(value: u32) -> Self {
VMSharedSignatureIndex(value) Self(value)
} }
} }
impl Default for VMSharedSignatureIndex { impl Default for VMSharedSignatureIndex {
fn default() -> Self { fn default() -> Self {
VMSharedSignatureIndex::new(u32::MAX) Self::new(u32::MAX)
} }
} }
@@ -573,7 +573,7 @@ mod test_vm_invoke_argument {
impl VMInvokeArgument { impl VMInvokeArgument {
/// Create a new invocation argument filled with zeroes /// Create a new invocation argument filled with zeroes
pub fn new() -> Self { pub fn new() -> Self {
VMInvokeArgument([0; 16]) Self([0; 16])
} }
} }