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

Code quality fixes including fix for undefined behavior in Message::with_size and <Message as From<&[u8]>>::from #403

Open
wants to merge 7 commits into
base: master
Choose a base branch
from

Conversation

antonilol
Copy link

See commit messages for detailed explanations.

Message::with_size and <Message as From<&[u8]>>::from call msg.as_mut_ptr() on a msg that contains uninitialized bytes, as_mut_ptr did not exist on Message, so the one of &mut [u8] was used, through DerefMut. This created a &mut [u8] to uninitialized data.

including:
- replace `str::from_utf8(cstr.to_bytes())` with `cstr.to_str()`
- remove unnecessary `as` casts (numeric and pointer)
- remove unused import `std::str`, not detected by rustc because of a bug
- added PartialOrd, Ord, Clone, Default and Hash
- moved PartialEq and Eq from between Deref and DerefMut
…y as_mut_ptr through DerefMut

- add `as_ptr` and `as_mut_ptr`, these methods create no intermediate
  reference, previously these methods from `&mut [u8]` (or `&[u8]`)
  would be used, which is ub if the data is uninitialized.
- use `ptr::slice_from_raw_parts_mut` when dropping a contained Box in a
  message to not create an intermediate reference to its contents. if
  this is ub, this has now been fixed. also, explicitly dropping here
  better expressed the goal of this function.
- add methods to get the raw pointer of a Message, and get the length of
  the bytes without creating an intermediate reference.
@antonilol
Copy link
Author

rust-zmq/src/message.rs

Lines 78 to 84 in 4b873ae

/// # Safety
///
/// The returned message contains uninitialized memory, and hence the
/// `Deref` and `DerefMut` traits must not be used until the memory has been
/// initialized. Since there is no proper API to do so, this function is
/// basically not usable safely, unless you happen to invoke C code that
/// takes a raw message pointer and initializes its contents.

This safety comment names not using DerefMut before the data is initialized, but this can be hard because Deref/DerefMut calls are inserted implicitly, I would prefer explicit functions instead (AsRef/AsMut implementations), but this would be a breaking change. Also, I added some API to get raw pointers, so maybe the function this doc comment is for can be useful.

src/message.rs Outdated Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants