Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create CommunicationError::DerefErr to avoid panics #418

Merged
merged 6 commits into from
Jun 11, 2020
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@
directly to get back the external dependencies.
- Rename `MockQuerier::with_staking` to `MockQuerier::update_staking` to match
`::update_balance`.
- Instead of panicking, `read_region`/`write_region`/`get_region`/`set_region`
now return a new `CommunicationError::DerefErr` when dereferencing a pointer
provided by the contract fails.

## 0.8.1 (2020-06-08)

Expand Down
34 changes: 33 additions & 1 deletion packages/vm/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,14 +239,35 @@ pub type VmResult<T> = core::result::Result<T, VmError>;
pub enum CommunicationError {
#[snafu(display("Got a zero Wasm address"))]
ZeroAddress { backtrace: snafu::Backtrace },
#[snafu(display(
"The Wasm memory address {} provided by the contract could not be dereferenced: {}",
offset,
msg
))]
DerefErr {
/// the position in a Wasm linear memory
offset: u32,
msg: String,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need this message field?
All the messages written here are basically the same, and basicall say the same thing as the name of the variant plus the offset field.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we need it for a lot of important context information in read_region/write_region as described in https://github.com/CosmWasm/cosmwasm/pull/418/files#r438383917. Those two need different context information than the Region deref.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think i see your point. You want to make sure that the pointers are dereferencable in different contexts, and you want to be able to later debug what exactly went wrong

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this case it is not me debugging this but it is other people who build standard libraries for contract development in other languages that need to get Region handling right. Once this job is done, you hardly see this error again.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See also #419

backtrace: snafu::Backtrace,
},
}

impl CommunicationError {
pub fn zero_address() -> Self {
ZeroAddress {}.build()
}

pub fn deref_err<S: Into<String>>(offset: u32, msg: S) -> Self {
DerefErr {
offset,
msg: msg.into(),
}
.build()
}
}

pub type CommunicationResult<T> = core::result::Result<T, CommunicationError>;

impl From<CommunicationError> for VmError {
fn from(communication_error: CommunicationError) -> Self {
VmError::CommunicationErr {
Expand Down Expand Up @@ -494,7 +515,6 @@ mod test {

// CommunicationError constructors

#[allow(unreachable_patterns)] // since CommunicationError is non_exhaustive, this should not create a warning. But it does :(
reuvenpo marked this conversation as resolved.
Show resolved Hide resolved
#[test]
fn communication_error_zero_address() {
let error = CommunicationError::zero_address();
Expand All @@ -504,6 +524,18 @@ mod test {
}
}

#[test]
fn communication_error_deref_err() {
let error = CommunicationError::deref_err(345, "broken stuff");
match error {
CommunicationError::DerefErr { offset, msg, .. } => {
assert_eq!(offset, 345);
assert_eq!(msg, "broken stuff");
}
e => panic!("Unexpected error: {:?}", e),
}
}

// FfiError constructors

#[test]
Expand Down
42 changes: 28 additions & 14 deletions packages/vm/src/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use wasmer_runtime_core::{
};

use crate::conversion::to_u32;
use crate::errors::{VmError, VmResult};
use crate::errors::{CommunicationError, CommunicationResult, VmError, VmResult};

/****** read/write to wasm memory buffer ****/

Expand Down Expand Up @@ -62,7 +62,7 @@ pub fn get_memory_info(ctx: &Ctx) -> MemoryInfo {
/// memory region, which is copied in the second step.
/// Errors if the length of the region exceeds `max_length`.
pub fn read_region(ctx: &Ctx, ptr: u32, max_length: usize) -> VmResult<Vec<u8>> {
let region = get_region(ctx, ptr);
let region = get_region(ctx, ptr)?;

if region.length > to_u32(max_length)? {
return Err(VmError::region_length_too_big(
Expand All @@ -83,11 +83,11 @@ pub fn read_region(ctx: &Ctx, ptr: u32, max_length: usize) -> VmResult<Vec<u8>>
}
Ok(result)
}
None => panic!(
None => Err(CommunicationError::deref_err(region.offset, format!(
"Error dereferencing region {:?} in wasm memory of size {}. This typically happens when the given pointer does not point to a Region struct.",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need all this text? It will be embedded inside:
The Wasm memory address {} provided by the contract could not be dereferenced: {}

We can simplify the wording here. (But I like returning this types error over a panic)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can try compress the text slightly, but this text and the debug info are is very helpful. When you read a Region it almost always succeeds, since you can read any 12 bytes into a Region, even if you got completely broken data.

Now you try to read the region and get some error. Most likely the deref that returns the error is not the problem but the Region you read before was garbage. E.g. when you should read a 12 MB Region but the Wasm memory is only 1 MB long. Or when you are supposed to read a Region with length > capacity. This is why I add so context here and the helper text. Even a stacktrace is probably way less helpful.

"Error dereferencing region" however is wrong since the Region was dereferenced before. It must be "Tried to access memory of region {:?} in wasm memory of size {}. This typically happens when the given Region pointer does not point to a valid Region struct."

region,
memory.size().bytes().0
),
)).into()),
}
}

Expand All @@ -106,7 +106,7 @@ pub fn maybe_read_region(ctx: &Ctx, ptr: u32, max_length: usize) -> VmResult<Opt
///
/// Returns number of bytes written on success.
pub fn write_region(ctx: &Ctx, ptr: u32, data: &[u8]) -> VmResult<()> {
let mut region = get_region(ctx, ptr);
let mut region = get_region(ctx, ptr)?;

let region_capacity = region.capacity as usize;
if data.len() > region_capacity {
Expand All @@ -122,29 +122,43 @@ pub fn write_region(ctx: &Ctx, ptr: u32, data: &[u8]) -> VmResult<()> {
cells[i].set(data[i])
}
region.length = data.len() as u32;
set_region(ctx, ptr, region);
set_region(ctx, ptr, region)?;
Ok(())
},
None => panic!(
None => Err(CommunicationError::deref_err(region.offset, format!(
"Error dereferencing region {:?} in wasm memory of size {}. This typically happens when the given pointer does not point to a Region struct.",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here with verbage

region,
memory.size().bytes().0
),
)).into()),
}
}

/// Reads in a Region at ptr in wasm memory and returns a copy of it
fn get_region(ctx: &Ctx, ptr: u32) -> Region {
fn get_region(ctx: &Ctx, ptr: u32) -> CommunicationResult<Region> {
let memory = ctx.memory(0);
let wptr = WasmPtr::<Region>::new(ptr);
let cell = wptr.deref(memory).unwrap();
cell.get()
match wptr.deref(memory) {
webmaster128 marked this conversation as resolved.
Show resolved Hide resolved
Some(cell) => Ok(cell.get()),
None => Err(CommunicationError::deref_err(
ptr,
"Could not dereference this pointer to a Region",
)),
}
}

/// Overrides a Region at ptr in wasm memory with data
fn set_region(ctx: &Ctx, ptr: u32, data: Region) {
fn set_region(ctx: &Ctx, ptr: u32, data: Region) -> CommunicationResult<()> {
let memory = ctx.memory(0);
let wptr = WasmPtr::<Region>::new(ptr);
let cell = wptr.deref(memory).unwrap();
cell.set(data);

match wptr.deref(memory) {
Some(cell) => {
cell.set(data);
Ok(())
}
None => Err(CommunicationError::deref_err(
ptr,
"Could not dereference this pointer to a Region",
)),
}
}