Skip to content

Commit

Permalink
Auto merge of #49488 - alexcrichton:small-wasm-panic, r=sfackler
Browse files Browse the repository at this point in the history
std: Minimize size of panicking on wasm

This commit applies a few code size optimizations for the wasm target to
the standard library, namely around panics. We notably know that in most
configurations it's impossible for us to print anything in
wasm32-unknown-unknown so we can skip larger portions of panicking that
are otherwise simply informative. This allows us to get quite a nice
size reduction.

Finally we can also tweak where the allocation happens for the
`Box<Any>` that we panic with. By only allocating once unwinding starts
we can reduce the size of a panicking wasm module from 44k to 350 bytes.
  • Loading branch information
bors committed Apr 16, 2018
2 parents 4a3ab8b + 46d16b6 commit 3809bbf
Show file tree
Hide file tree
Showing 22 changed files with 296 additions and 72 deletions.
6 changes: 6 additions & 0 deletions src/ci/docker/wasm32-unknown/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ ENV RUST_CONFIGURE_ARGS \
--set build.nodejs=/node-v9.2.0-linux-x64/bin/node \
--set rust.lld

# Some run-make tests have assertions about code size, and enabling debug
# assertions in libstd causes the binary to be much bigger than it would
# otherwise normally be. We already test libstd with debug assertions in lots of
# other contexts as well
ENV NO_DEBUG_ASSERTIONS=1

ENV SCRIPT python2.7 /checkout/x.py test --target $TARGETS \
src/test/run-make \
src/test/ui \
Expand Down
23 changes: 15 additions & 8 deletions src/liballoc/raw_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ impl<T, A: Alloc> RawVec<T, A> {
unsafe {
let elem_size = mem::size_of::<T>();

let alloc_size = cap.checked_mul(elem_size).expect("capacity overflow");
alloc_guard(alloc_size).expect("capacity overflow");
let alloc_size = cap.checked_mul(elem_size).unwrap_or_else(|| capacity_overflow());
alloc_guard(alloc_size).unwrap_or_else(|_| capacity_overflow());

// handles ZSTs and `cap = 0` alike
let ptr = if alloc_size == 0 {
Expand Down Expand Up @@ -310,7 +310,7 @@ impl<T, A: Alloc> RawVec<T, A> {
// `from_size_align_unchecked`.
let new_cap = 2 * self.cap;
let new_size = new_cap * elem_size;
alloc_guard(new_size).expect("capacity overflow");
alloc_guard(new_size).unwrap_or_else(|_| capacity_overflow());
let ptr_res = self.a.realloc(NonNull::from(self.ptr).as_opaque(),
cur,
new_size);
Expand Down Expand Up @@ -369,7 +369,7 @@ impl<T, A: Alloc> RawVec<T, A> {
// overflow and the alignment is sufficiently small.
let new_cap = 2 * self.cap;
let new_size = new_cap * elem_size;
alloc_guard(new_size).expect("capacity overflow");
alloc_guard(new_size).unwrap_or_else(|_| capacity_overflow());
match self.a.grow_in_place(NonNull::from(self.ptr).as_opaque(), old_layout, new_size) {
Ok(_) => {
// We can't directly divide `size`.
Expand Down Expand Up @@ -441,7 +441,7 @@ impl<T, A: Alloc> RawVec<T, A> {

pub fn reserve_exact(&mut self, used_cap: usize, needed_extra_cap: usize) {
match self.try_reserve_exact(used_cap, needed_extra_cap) {
Err(CapacityOverflow) => panic!("capacity overflow"),
Err(CapacityOverflow) => capacity_overflow(),
Err(AllocErr) => self.a.oom(),
Ok(()) => { /* yay */ }
}
Expand Down Expand Up @@ -551,7 +551,7 @@ impl<T, A: Alloc> RawVec<T, A> {
/// The same as try_reserve, but errors are lowered to a call to oom().
pub fn reserve(&mut self, used_cap: usize, needed_extra_cap: usize) {
match self.try_reserve(used_cap, needed_extra_cap) {
Err(CapacityOverflow) => panic!("capacity overflow"),
Err(CapacityOverflow) => capacity_overflow(),
Err(AllocErr) => self.a.oom(),
Ok(()) => { /* yay */ }
}
Expand Down Expand Up @@ -592,15 +592,15 @@ impl<T, A: Alloc> RawVec<T, A> {
}

let new_cap = self.amortized_new_size(used_cap, needed_extra_cap)
.expect("capacity overflow");
.unwrap_or_else(|_| capacity_overflow());

// Here, `cap < used_cap + needed_extra_cap <= new_cap`
// (regardless of whether `self.cap - used_cap` wrapped).
// Therefore we can safely call grow_in_place.

let new_layout = Layout::new::<T>().repeat(new_cap).unwrap().0;
// FIXME: may crash and burn on over-reserve
alloc_guard(new_layout.size()).expect("capacity overflow");
alloc_guard(new_layout.size()).unwrap_or_else(|_| capacity_overflow());
match self.a.grow_in_place(
NonNull::from(self.ptr).as_opaque(), old_layout, new_layout.size(),
) {
Expand Down Expand Up @@ -732,6 +732,13 @@ fn alloc_guard(alloc_size: usize) -> Result<(), CollectionAllocErr> {
}
}

// One central function responsible for reporting capacity overflows. This'll
// ensure that the code generation related to these panics is minimal as there's
// only one location which panics rather than a bunch throughout the module.
fn capacity_overflow() -> ! {
panic!("capacity overflow")
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
6 changes: 5 additions & 1 deletion src/libcore/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1212,7 +1212,11 @@ impl<'a> Formatter<'a> {
// truncation. However other flags like `fill`, `width` and `align`
// must act as always.
if let Some((i, _)) = s.char_indices().skip(max).next() {
&s[..i]
// LLVM here can't prove that `..i` won't panic `&s[..i]`, but
// we know that it can't panic. Use `get` + `unwrap_or` to avoid
// `unsafe` and otherwise don't emit any panic-related code
// here.
s.get(..i).unwrap_or(&s)
} else {
&s
}
Expand Down
22 changes: 19 additions & 3 deletions src/libcore/panic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,17 @@ impl<'a> PanicInfo<'a> {
and related macros",
issue = "0")]
#[doc(hidden)]
pub fn internal_constructor(payload: &'a (Any + Send),
message: Option<&'a fmt::Arguments<'a>>,
#[inline]
pub fn internal_constructor(message: Option<&'a fmt::Arguments<'a>>,
location: Location<'a>)
-> Self {
PanicInfo { payload, location, message }
PanicInfo { payload: &(), location, message }
}

#[doc(hidden)]
#[inline]
pub fn set_payload(&mut self, info: &'a (Any + Send)) {
self.payload = info;
}

/// Returns the payload associated with the panic.
Expand Down Expand Up @@ -251,3 +257,13 @@ impl<'a> fmt::Display for Location<'a> {
write!(formatter, "{}:{}:{}", self.file, self.line, self.col)
}
}

/// An internal trait used by libstd to pass data from libstd to `panic_unwind`
/// and other panic runtimes. Not intended to be stabilized any time soon, do
/// not use.
#[unstable(feature = "std_internals", issue = "0")]
#[doc(hidden)]
pub unsafe trait BoxMeUp {
fn box_me_up(&mut self) -> *mut (Any + Send);
fn get(&mut self) -> &(Any + Send);
}
2 changes: 1 addition & 1 deletion src/libpanic_abort/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub unsafe extern fn __rust_maybe_catch_panic(f: fn(*mut u8),
// now hopefully.
#[no_mangle]
#[rustc_std_internal_symbol]
pub unsafe extern fn __rust_start_panic(_data: usize, _vtable: usize) -> u32 {
pub unsafe extern fn __rust_start_panic(_payload: usize) -> u32 {
abort();

#[cfg(any(unix, target_os = "cloudabi"))]
Expand Down
12 changes: 7 additions & 5 deletions src/libpanic_unwind/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@
html_root_url = "https://doc.rust-lang.org/nightly/",
issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/")]

#![feature(allocator_api)]
#![feature(alloc)]
#![feature(core_intrinsics)]
#![feature(lang_items)]
#![feature(libc)]
#![feature(panic_unwind)]
#![feature(raw)]
#![feature(staged_api)]
#![feature(std_internals)]
#![feature(unwind_attributes)]
#![cfg_attr(target_env = "msvc", feature(raw))]

Expand All @@ -47,9 +49,11 @@ extern crate libc;
#[cfg(not(any(target_env = "msvc", all(windows, target_arch = "x86_64", target_env = "gnu"))))]
extern crate unwind;

use alloc::boxed::Box;
use core::intrinsics;
use core::mem;
use core::raw;
use core::panic::BoxMeUp;

// Rust runtime's startup objects depend on these symbols, so make them public.
#[cfg(all(target_os="windows", target_arch = "x86", target_env="gnu"))]
Expand Down Expand Up @@ -112,9 +116,7 @@ pub unsafe extern "C" fn __rust_maybe_catch_panic(f: fn(*mut u8),
// implementation.
#[no_mangle]
#[unwind(allowed)]
pub unsafe extern "C" fn __rust_start_panic(data: usize, vtable: usize) -> u32 {
imp::panic(mem::transmute(raw::TraitObject {
data: data as *mut (),
vtable: vtable as *mut (),
}))
pub unsafe extern "C" fn __rust_start_panic(payload: usize) -> u32 {
let payload = payload as *mut &mut BoxMeUp;
imp::panic(Box::from_raw((*payload).box_me_up()))
}
1 change: 1 addition & 0 deletions src/libstd/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@
#![feature(rand)]
#![feature(raw)]
#![feature(rustc_attrs)]
#![feature(std_internals)]
#![feature(stdsimd)]
#![feature(shrink_to)]
#![feature(slice_bytes)]
Expand Down
Loading

0 comments on commit 3809bbf

Please sign in to comment.