Skip to content

Commit

Permalink
Have tidy ensure that we document all unsafe blocks in libcore
Browse files Browse the repository at this point in the history
  • Loading branch information
oli-obk committed Nov 6, 2019
1 parent e8b190a commit 02f9167
Show file tree
Hide file tree
Showing 41 changed files with 137 additions and 5 deletions.
2 changes: 2 additions & 0 deletions src/libcore/alloc.rs
@@ -1,5 +1,7 @@
//! Memory allocation APIs

// ignore-tidy-undocumented-unsafe

#![stable(feature = "alloc_module", since = "1.28.0")]

use crate::cmp;
Expand Down
6 changes: 6 additions & 0 deletions src/libcore/any.rs
Expand Up @@ -182,6 +182,7 @@ impl dyn Any {
#[inline]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
if self.is::<T>() {
// SAFETY: just checked whether we are pointing to the correct type
unsafe {
Some(&*(self as *const dyn Any as *const T))
}
Expand Down Expand Up @@ -217,6 +218,7 @@ impl dyn Any {
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
// SAFETY: just checked whether we are pointing to the correct type
unsafe {
Some(&mut *(self as *mut dyn Any as *mut T))
}
Expand Down Expand Up @@ -424,7 +426,11 @@ impl TypeId {
#[rustc_const_unstable(feature="const_type_id")]
pub const fn of<T: ?Sized + 'static>() -> TypeId {
TypeId {
#[cfg(boostrap_stdarch_ignore_this)]
// SAFETY: going away soon
t: unsafe { intrinsics::type_id::<T>() },
#[cfg(not(boostrap_stdarch_ignore_this))]
t: intrinsics::type_id::<T>(),
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/array/mod.rs
Expand Up @@ -156,6 +156,7 @@ where
fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
if slice.len() == N {
let ptr = slice.as_ptr() as *const [T; N];
// SAFETY: ok because we just checked that the length fits
unsafe { Ok(&*ptr) }
} else {
Err(TryFromSliceError(()))
Expand All @@ -173,6 +174,7 @@ where
fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
if slice.len() == N {
let ptr = slice.as_mut_ptr() as *mut [T; N];
// SAFETY: ok because we just checked that the length fits
unsafe { Ok(&mut *ptr) }
} else {
Err(TryFromSliceError(()))
Expand Down
1 change: 1 addition & 0 deletions src/libcore/ascii.rs
Expand Up @@ -135,6 +135,7 @@ impl FusedIterator for EscapeDefault {}
#[stable(feature = "ascii_escape_display", since = "1.39.0")]
impl fmt::Display for EscapeDefault {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// SAFETY: ok because `escape_default` created only valid utf-8 data
f.write_str(unsafe { from_utf8_unchecked(&self.data[self.range.clone()]) })
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/benches/ascii.rs
Expand Up @@ -118,6 +118,7 @@ benches! {
}

fn case07_fake_simd_u32(bytes: &mut [u8]) {
// SAFETY: transmuting a sequence of `u8` to `u32` is always fine
let (before, aligned, after) = unsafe {
bytes.align_to_mut::<u32>()
};
Expand All @@ -142,6 +143,7 @@ benches! {
}

fn case08_fake_simd_u64(bytes: &mut [u8]) {
// SAFETY: transmuting a sequence of `u8` to `u64` is always fine
let (before, aligned, after) = unsafe {
bytes.align_to_mut::<u64>()
};
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/cell.rs
Expand Up @@ -182,6 +182,8 @@
//! ```
//!

// ignore-tidy-undocumented-unsafe

#![stable(feature = "rust1", since = "1.0.0")]

use crate::cmp::Ordering;
Expand Down
1 change: 1 addition & 0 deletions src/libcore/char/convert.rs
Expand Up @@ -224,6 +224,7 @@ impl TryFrom<u32> for char {
if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
Err(CharTryFromError(()))
} else {
// SAFETY: checked that it's a legal unicode value
Ok(unsafe { from_u32_unchecked(i) })
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/libcore/char/decode.rs
Expand Up @@ -87,7 +87,7 @@ impl<I: Iterator<Item = u16>> Iterator for DecodeUtf16<I> {
};

if u < 0xD800 || 0xDFFF < u {
// not a surrogate
// SAFETY: not a surrogate
Some(Ok(unsafe { from_u32_unchecked(u as u32) }))
} else if u >= 0xDC00 {
// a trailing surrogate
Expand All @@ -107,6 +107,7 @@ impl<I: Iterator<Item = u16>> Iterator for DecodeUtf16<I> {

// all ok, so lets decode it.
let c = (((u - 0xD800) as u32) << 10 | (u2 - 0xDC00) as u32) + 0x1_0000;
// SAFETY: we checked that it's a legal unicode value
Some(Ok(unsafe { from_u32_unchecked(c) }))
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/char/methods.rs
Expand Up @@ -438,6 +438,7 @@ impl char {
#[inline]
pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
let code = self as u32;
// SAFETY: each arm checks the size of the slice and only uses `get_unchecked` unsafe ops
unsafe {
let len = if code < MAX_ONE_B && !dst.is_empty() {
*dst.get_unchecked_mut(0) = code as u8;
Expand Down Expand Up @@ -507,6 +508,7 @@ impl char {
#[inline]
pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
let mut code = self as u32;
// SAFETY: each arm checks whether there are enough bits to write into
unsafe {
if (code & 0xFFFF) == code && !dst.is_empty() {
// The BMP falls through (assuming non-surrogate, as it should)
Expand Down
1 change: 1 addition & 0 deletions src/libcore/ffi.rs
Expand Up @@ -315,6 +315,7 @@ impl<'f> Clone for VaListImpl<'f> {
#[inline]
fn clone(&self) -> Self {
let mut dest = crate::mem::MaybeUninit::uninit();
// SAFETY: we write to the `MaybeUninit`, thus it is initialized and `assume_init` is legal
unsafe {
va_copy(dest.as_mut_ptr(), self);
dest.assume_init()
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/fmt/float.rs
Expand Up @@ -2,6 +2,8 @@ use crate::fmt::{Formatter, Result, LowerExp, UpperExp, Display, Debug};
use crate::mem::MaybeUninit;
use crate::num::flt2dec;

// ignore-tidy-undocumented-unsafe

// Don't inline this so callers don't use the stack space this function
// requires unless they have to.
#[inline(never)]
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/fmt/mod.rs
@@ -1,5 +1,7 @@
//! Utilities for formatting and printing strings.

// ignore-tidy-undocumented-unsafe

#![stable(feature = "rust1", since = "1.0.0")]

use crate::cell::{UnsafeCell, Cell, RefCell, Ref, RefMut};
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/fmt/num.rs
@@ -1,5 +1,7 @@
//! Integer and floating-point number formatting

// ignore-tidy-undocumented-unsafe


use crate::fmt;
use crate::ops::{Div, Rem, Sub};
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/hash/mod.rs
Expand Up @@ -79,6 +79,8 @@
//! }
//! ```

// ignore-tidy-undocumented-unsafe

#![stable(feature = "rust1", since = "1.0.0")]

use crate::fmt;
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/hash/sip.rs
@@ -1,5 +1,7 @@
//! An implementation of SipHash.

// ignore-tidy-undocumented-unsafe

#![allow(deprecated)] // the types in this module are deprecated

use crate::marker::PhantomData;
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/hint.rs
Expand Up @@ -2,6 +2,8 @@

//! Hints to compiler that affects how code should be emitted or optimized.

// ignore-tidy-undocumented-unsafe

use crate::intrinsics;

/// Informs the compiler that this point in the code is not reachable, enabling
Expand Down
6 changes: 6 additions & 0 deletions src/libcore/iter/adapters/mod.rs
Expand Up @@ -517,9 +517,15 @@ impl<I> Iterator for StepBy<I> where I: Iterator {
// overflow handling
loop {
let mul = n.checked_mul(step);
#[cfg(boostrap_stdarch_ignore_this)]
// SAFETY: going away soon
if unsafe { intrinsics::likely(mul.is_some()) } {
return self.iter.nth(mul.unwrap() - 1);
}
#[cfg(not(boostrap_stdarch_ignore_this))]
if intrinsics::likely(mul.is_some()) {
return self.iter.nth(mul.unwrap() - 1);
}
let div_n = usize::MAX / n;
let div_step = usize::MAX / step;
let nth_n = div_n * n;
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/iter/adapters/zip.rs
@@ -1,3 +1,5 @@
// ignore-tidy-undocumented-unsafe

use crate::cmp;

use super::super::{Iterator, DoubleEndedIterator, ExactSizeIterator, FusedIterator, TrustedLen};
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/mem/maybe_uninit.rs
@@ -1,6 +1,8 @@
use crate::intrinsics;
use crate::mem::ManuallyDrop;

// ignore-tidy-undocumented-unsafe

/// A wrapper type to construct uninitialized instances of `T`.
///
/// # Initialization invariant
Expand Down
18 changes: 17 additions & 1 deletion src/libcore/mem/mod.rs
Expand Up @@ -93,6 +93,8 @@ pub fn forget<T>(t: T) {
#[inline]
#[unstable(feature = "forget_unsized", issue = "0")]
pub fn forget_unsized<T: ?Sized>(t: T) {
// SAFETY: the forget intrinsic could be safe, but there's no point in making it safe since
// we'll be implementing this function soon via `ManuallyDrop`
unsafe { intrinsics::forget(t) }
}

Expand Down Expand Up @@ -266,7 +268,11 @@ pub const fn size_of<T>() -> usize {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
#[cfg(boostrap_stdarch_ignore_this)]
// SAFETY: going away soon
unsafe { intrinsics::size_of_val(val) }
#[cfg(not(boostrap_stdarch_ignore_this))]
intrinsics::size_of_val(val)
}

/// Returns the [ABI]-required minimum alignment of a type.
Expand Down Expand Up @@ -310,7 +316,11 @@ pub fn min_align_of<T>() -> usize {
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
#[cfg(boostrap_stdarch_ignore_this)]
// SAFETY: going away soon
unsafe { intrinsics::min_align_of_val(val) }
#[cfg(not(boostrap_stdarch_ignore_this))]
intrinsics::min_align_of_val(val)
}

/// Returns the [ABI]-required minimum alignment of a type.
Expand Down Expand Up @@ -351,7 +361,7 @@ pub const fn align_of<T>() -> usize {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
unsafe { intrinsics::min_align_of_val(val) }
min_align_of_val(val)
}

/// Returns `true` if dropping values of type `T` matters.
Expand Down Expand Up @@ -508,6 +518,8 @@ pub unsafe fn uninitialized<T>() -> T {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn swap<T>(x: &mut T, y: &mut T) {
// SAFETY: the raw pointers have been created from safe mutable references satisfying all the
// constraints on `ptr::swap_nonoverlapping_one`
unsafe {
ptr::swap_nonoverlapping_one(x, y);
}
Expand Down Expand Up @@ -822,7 +834,11 @@ impl<T> fmt::Debug for Discriminant<T> {
/// ```
#[stable(feature = "discriminant_value", since = "1.21.0")]
pub fn discriminant<T>(v: &T) -> Discriminant<T> {
#[cfg(boostrap_stdarch_ignore_this)]
// SAFETY: going away soon
unsafe {
Discriminant(intrinsics::discriminant_value(v), PhantomData)
}
#[cfg(not(boostrap_stdarch_ignore_this))]
Discriminant(intrinsics::discriminant_value(v), PhantomData)
}
4 changes: 4 additions & 0 deletions src/libcore/num/dec2flt/algorithm.rs
Expand Up @@ -58,6 +58,8 @@ mod fpu_precision {
pub struct FPUControlWord(u16);

fn set_cw(cw: u16) {
// SAFETY: the `fldcw` instruction has been audited to be able to work correctly with
// any `u16`
unsafe { asm!("fldcw $0" :: "m" (cw) :: "volatile") }
}

Expand All @@ -74,6 +76,8 @@ mod fpu_precision {

// Get the original value of the control word to restore it later, when the
// `FPUControlWord` structure is dropped
// SAFETY: the `fnstcw` instruction has been audited to be able to work correctly with
// any `u16`
unsafe { asm!("fnstcw $0" : "=*m" (&cw) ::: "volatile") }

// Set the control word to the desired precision. This is achieved by masking away the old
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/num/f32.rs
Expand Up @@ -414,6 +414,7 @@ impl f32 {
#[stable(feature = "float_bits_conv", since = "1.20.0")]
#[inline]
pub fn to_bits(self) -> u32 {
// SAFETY: `u32` is a plain old datatype so we can always transmute to it
unsafe { mem::transmute(self) }
}

Expand Down Expand Up @@ -456,6 +457,7 @@ impl f32 {
#[stable(feature = "float_bits_conv", since = "1.20.0")]
#[inline]
pub fn from_bits(v: u32) -> Self {
// SAFETY: `u32` is a plain old datatype so we can always transmute from it
// It turns out the safety issues with sNaN were overblown! Hooray!
unsafe { mem::transmute(v) }
}
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/num/f64.rs
Expand Up @@ -427,6 +427,7 @@ impl f64 {
#[stable(feature = "float_bits_conv", since = "1.20.0")]
#[inline]
pub fn to_bits(self) -> u64 {
// SAFETY: `u64` is a plain old datatype so we can always transmute to it
unsafe { mem::transmute(self) }
}

Expand Down Expand Up @@ -469,6 +470,7 @@ impl f64 {
#[stable(feature = "float_bits_conv", since = "1.20.0")]
#[inline]
pub fn from_bits(v: u64) -> Self {
// SAFETY: `u64` is a plain old datatype so we can always transmute from it
// It turns out the safety issues with sNaN were overblown! Hooray!
unsafe { mem::transmute(v) }
}
Expand Down

0 comments on commit 02f9167

Please sign in to comment.