Skip to content

Commit

Permalink
Auto merge of #61864 - lzutao:ptr-null, r=sfackler
Browse files Browse the repository at this point in the history
Make use of `ptr::null(_mut)` instead of casting zero

There are few places that I don't replace the zero casting pointer with `ptr::null`
or `ptr::null_mut`:
```bash
% git grep -E '[ ([{]0 as \*'
src/libcore/ptr/mod.rs:216:pub const fn null<T>() -> *const T { 0 as *const T }
src/libcore/ptr/mod.rs:231:pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
src/test/run-pass/consts/const-cast-ptr-int.rs:12:static a: TestStruct = TestStruct{x: 0 as *const u8};
src/test/ui/issues/issue-45730.rs:5:    let x: *const _ = 0 as *const _; //~ ERROR cannot cast
src/test/ui/issues/issue-45730.rs:8:    let x = 0 as *const i32 as *const _ as *mut _; //~ ERROR cannot cast
src/test/ui/issues/issue-45730.stderr:14:LL |     let x: *const _ = 0 as *const _;
src/test/ui/issues/issue-45730.stderr:24:LL |     let x = 0 as *const i32 as *const _ as *mut _;
src/test/ui/lint/lint-forbid-internal-unsafe.rs:15:    println!("{}", evil!(*(0 as *const u8)));
src/test/ui/order-dependent-cast-inference.rs:5:    let mut y = 0 as *const _;
src/test/ui/order-dependent-cast-inference.stderr:4:LL |     let mut y = 0 as *const _;
```

r? @sfackler
  • Loading branch information
bors committed Jun 18, 2019
2 parents 704ab2b + 7d69d4c commit a6a8f6c
Show file tree
Hide file tree
Showing 33 changed files with 55 additions and 52 deletions.
9 changes: 5 additions & 4 deletions src/bootstrap/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
use std::env;
use std::io;
use std::mem;
use std::ptr;
use crate::Build;

type HANDLE = *mut u8;
Expand Down Expand Up @@ -118,8 +119,8 @@ pub unsafe fn setup(build: &mut Build) {
SetErrorMode(mode & !SEM_NOGPFAULTERRORBOX);

// Create a new job object for us to use
let job = CreateJobObjectW(0 as *mut _, 0 as *const _);
assert!(job != 0 as *mut _, "{}", io::Error::last_os_error());
let job = CreateJobObjectW(ptr::null_mut(), ptr::null());
assert!(!job.is_null(), "{}", io::Error::last_os_error());

// Indicate that when all handles to the job object are gone that all
// process in the object should be killed. Note that this includes our
Expand Down Expand Up @@ -166,8 +167,8 @@ pub unsafe fn setup(build: &mut Build) {
};

let parent = OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid.parse().unwrap());
assert!(parent != 0 as *mut _, "{}", io::Error::last_os_error());
let mut parent_handle = 0 as *mut _;
assert!(!parent.is_null(), "{}", io::Error::last_os_error());
let mut parent_handle = ptr::null_mut();
let r = DuplicateHandle(GetCurrentProcess(), job,
parent, &mut parent_handle,
0, FALSE, DUPLICATE_SAME_ACCESS);
Expand Down
2 changes: 1 addition & 1 deletion src/bootstrap/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
let h = CreateFileW(path.as_ptr(),
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0 as *mut _,
ptr::null_mut(),
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
ptr::null_mut());
Expand Down
8 changes: 4 additions & 4 deletions src/libarena/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,8 @@ impl<T> Default for TypedArena<T> {
TypedArena {
// We set both `ptr` and `end` to 0 so that the first call to
// alloc() will trigger a grow().
ptr: Cell::new(0 as *mut T),
end: Cell::new(0 as *mut T),
ptr: Cell::new(ptr::null_mut()),
end: Cell::new(ptr::null_mut()),
chunks: RefCell::new(vec![]),
_own: PhantomData,
}
Expand Down Expand Up @@ -370,8 +370,8 @@ impl Default for DroplessArena {
#[inline]
fn default() -> DroplessArena {
DroplessArena {
ptr: Cell::new(0 as *mut u8),
end: Cell::new(0 as *mut u8),
ptr: Cell::new(ptr::null_mut()),
end: Cell::new(ptr::null_mut()),
chunks: Default::default(),
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/libpanic_unwind/dummy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use core::any::Any;
use core::intrinsics;

pub fn payload() -> *mut u8 {
0 as *mut u8
core::ptr::null_mut()
}

pub unsafe fn cleanup(_ptr: *mut u8) -> Box<dyn Any + Send> {
Expand Down
6 changes: 3 additions & 3 deletions src/libpanic_unwind/seh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ mod imp {
pub const NAME2: [u8; 7] = [b'.', b'P', b'A', b'X', 0, 0, 0];

macro_rules! ptr {
(0) => (0 as *mut u8);
(0) => (core::ptr::null_mut());
($e:expr) => ($e as *mut u8);
}
}
Expand Down Expand Up @@ -223,13 +223,13 @@ extern "C" {
#[cfg_attr(not(test), lang = "msvc_try_filter")]
static mut TYPE_DESCRIPTOR1: _TypeDescriptor = _TypeDescriptor {
pVFTable: unsafe { &TYPE_INFO_VTABLE } as *const _ as *const _,
spare: 0 as *mut _,
spare: core::ptr::null_mut(),
name: imp::NAME1,
};

static mut TYPE_DESCRIPTOR2: _TypeDescriptor = _TypeDescriptor {
pVFTable: unsafe { &TYPE_INFO_VTABLE } as *const _ as *const _,
spare: 0 as *mut _,
spare: core::ptr::null_mut(),
name: imp::NAME2,
};

Expand Down
2 changes: 1 addition & 1 deletion src/librustc_errors/lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ pub fn acquire_global_lock(name: &str) -> Box<dyn Any> {
//
// This will silently create one if it doesn't already exist, or it'll
// open up a handle to one if it already exists.
let mutex = CreateMutexA(0 as *mut _, 0, cname.as_ptr() as *const u8);
let mutex = CreateMutexA(std::ptr::null_mut(), 0, cname.as_ptr() as *const u8);
if mutex.is_null() {
panic!("failed to create global mutex named `{}`: {}",
name,
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_metadata/dynamic_lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ mod dl {
{
use std::sync::{Mutex, Once};
static INIT: Once = Once::new();
static mut LOCK: *mut Mutex<()> = 0 as *mut _;
static mut LOCK: *mut Mutex<()> = ptr::null_mut();
unsafe {
INIT.call_once(|| {
LOCK = Box::into_raw(Box::new(Mutex::new(())));
Expand Down
6 changes: 3 additions & 3 deletions src/librustc_typeck/error_codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3904,7 +3904,7 @@ x as Vec<u8>; // error: non-primitive cast: `u8` as `std::vec::Vec<u8>`
// Another example
let v = 0 as *const u8; // So here, `v` is a `*const u8`.
let v = core::ptr::null::<u8>(); // So here, `v` is a `*const u8`.
v as &u8; // error: non-primitive cast: `*const u8` as `&u8`
```
Expand All @@ -3914,7 +3914,7 @@ Only primitive types can be cast into each other. Examples:
let x = 0u8;
x as u32; // ok!
let v = 0 as *const u8;
let v = core::ptr::null::<u8>();
v as *const i8; // ok!
```
Expand Down Expand Up @@ -3954,7 +3954,7 @@ A cast between a thin and a fat pointer was attempted.
Erroneous code example:
```compile_fail,E0607
let v = 0 as *const u8;
let v = core::ptr::null::<u8>();
v as *const [u8];
```
Expand Down
2 changes: 1 addition & 1 deletion src/libstd/sys/wasi/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ fn maybe_args() -> io::Result<Args> {
let (mut argc, mut argv_buf_size) = (0, 0);
cvt_wasi(libc::__wasi_args_sizes_get(&mut argc, &mut argv_buf_size))?;

let mut argc = vec![0 as *mut libc::c_char; argc];
let mut argc = vec![core::ptr::null_mut::<libc::c_char>(); argc];
let mut argv_buf = vec![0; argv_buf_size];
cvt_wasi(libc::__wasi_args_get(argc.as_mut_ptr(), argv_buf.as_mut_ptr()))?;

Expand Down
2 changes: 1 addition & 1 deletion src/libstd/sys/wasm/thread_local_atomics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ struct ThreadControlBlock {
impl ThreadControlBlock {
fn new() -> ThreadControlBlock {
ThreadControlBlock {
keys: [0 as *mut u8; MAX_KEYS],
keys: [core::ptr::null_mut(); MAX_KEYS],
}
}

Expand Down
6 changes: 4 additions & 2 deletions src/test/run-make-fulldeps/alloc-extern-crates/fakealloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@
#![no_std]

#[inline]
pub unsafe fn allocate(_size: usize, _align: usize) -> *mut u8 { 0 as *mut u8 }
pub unsafe fn allocate(_size: usize, _align: usize) -> *mut u8 {
core::ptr::null_mut()
}

#[inline]
pub unsafe fn deallocate(_ptr: *mut u8, _old_size: usize, _align: usize) { }

#[inline]
pub unsafe fn reallocate(_ptr: *mut u8, _old_size: usize, _size: usize, _align: usize) -> *mut u8 {
0 as *mut u8
core::ptr::null_mut()
}

#[inline]
Expand Down
2 changes: 1 addition & 1 deletion src/test/run-pass/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@ pub fn main() {
// Test that `_` is correctly inferred.
let x = &"hello";
let mut y = x as *const _;
y = 0 as *const _;
y = core::ptr::null_mut();
}
2 changes: 1 addition & 1 deletion src/test/run-pass/cleanup-shortcircuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ pub fn main() {

if args.len() >= 2 && args[1] == "signal" {
// Raise a segfault.
unsafe { *(0 as *mut isize) = 0; }
unsafe { *std::ptr::null_mut::<isize>() = 0; }
}
}
4 changes: 2 additions & 2 deletions src/test/run-pass/consts/const-block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ static BLOCK_EXPLICIT_UNIT: () = { () };
static BLOCK_IMPLICIT_UNIT: () = { };
static BLOCK_FLOAT: f64 = { 1.0 };
static BLOCK_ENUM: Option<usize> = { Some(100) };
static BLOCK_STRUCT: Foo = { Foo { a: 12, b: 0 as *const () } };
static BLOCK_STRUCT: Foo = { Foo { a: 12, b: std::ptr::null::<()>() } };
static BLOCK_UNSAFE: usize = unsafe { 1000 };

static BLOCK_FN_INFERRED: fn(usize) -> usize = { foo };
Expand All @@ -36,7 +36,7 @@ pub fn main() {
assert_eq!(BLOCK_IMPLICIT_UNIT, ());
assert_eq!(BLOCK_FLOAT, 1.0_f64);
assert_eq!(BLOCK_STRUCT.a, 12);
assert_eq!(BLOCK_STRUCT.b, 0 as *const ());
assert_eq!(BLOCK_STRUCT.b, std::ptr::null::<()>());
assert_eq!(BLOCK_ENUM, Some(100));
assert_eq!(BLOCK_UNSAFE, 1000);
assert_eq!(BLOCK_FN_INFERRED(300), 300);
Expand Down
4 changes: 2 additions & 2 deletions src/test/run-pass/issues/issue-13259-windows-tcb-trash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ mod imp {
pub fn test() {
let mut buf: [u16; 50] = [0; 50];
let ret = unsafe {
FormatMessageW(0x1000, 0 as *mut _, 1, 0x400,
buf.as_mut_ptr(), buf.len() as u32, 0 as *const _)
FormatMessageW(0x1000, core::ptr::null_mut(), 1, 0x400,
buf.as_mut_ptr(), buf.len() as u32, core::ptr::null())
};
// On some 32-bit Windowses (Win7-8 at least) this will panic with segmented
// stacks taking control of pvArbitrary
Expand Down
2 changes: 1 addition & 1 deletion src/test/run-pass/issues/issue-19001.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ struct Loopy {
}

fn main() {
let _t = Loopy { ptr: 0 as *mut _ };
let _t = Loopy { ptr: core::ptr::null_mut() };
}
2 changes: 1 addition & 1 deletion src/test/run-pass/issues/issue-39367.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fn arena() -> &'static ArenaSet<Vec<u8>> {
fn require_sync<T: Sync>(_: &T) { }
unsafe fn __stability() -> &'static ArenaSet<Vec<u8>> {
use std::mem::transmute;
static mut DATA: *const ArenaSet<Vec<u8>> = 0 as *const ArenaSet<Vec<u8>>;
static mut DATA: *const ArenaSet<Vec<u8>> = std::ptr::null_mut();

static mut ONCE: Once = Once::new();
ONCE.call_once(|| {
Expand Down
2 changes: 1 addition & 1 deletion src/test/run-pass/issues/issue-46069.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ fn copy_ex() {
}

fn main() {
let _f = 0 as *mut <Fuse<Cloned<Iter<u8>>> as Iterator>::Item;
let _f: *mut <Fuse<Cloned<Iter<u8>>> as Iterator>::Item = std::ptr::null_mut();

copy_ex();
}
2 changes: 1 addition & 1 deletion src/test/run-pass/structs-enums/enum-null-pointer-opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ fn main() {

// The optimization can't apply to raw pointers or unions with a ZST field.
assert!(size_of::<Option<*const isize>>() != size_of::<*const isize>());
assert!(Some(0 as *const isize).is_some()); // Can't collapse None to null
assert!(Some(std::ptr::null::<isize>()).is_some()); // Can't collapse None to null
assert_ne!(size_of::<fn(isize)>(), size_of::<Option<MaybeUninitUnion<fn(isize)>>>());
assert_ne!(size_of::<&str>(), size_of::<Option<MaybeUninitUnion<&str>>>());
assert_ne!(size_of::<NonNull<isize>>(), size_of::<Option<MaybeUninitUnion<NonNull<isize>>>>());
Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/casts-issue-46365.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ struct Lorem {
}

fn main() {
let _foo: *mut Lorem = 0 as *mut _; // no error here
let _foo: *mut Lorem = core::ptr::null_mut(); // no error here
}
2 changes: 1 addition & 1 deletion src/test/ui/consts/const-eval/ice-generic-assoc-const.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub trait Nullable {
}

impl<T> Nullable for *const T {
const NULL: Self = 0 as *const T;
const NULL: Self = core::ptr::null::<T>();

fn is_null(&self) -> bool {
*self == Self::NULL
Expand Down
4 changes: 2 additions & 2 deletions src/test/ui/consts/min_const_fn/min_const_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ const fn i32_ops3(c: i32, d: i32) -> bool { c != d }
const fn i32_ops4(c: i32, d: i32) -> i32 { c + d }
const fn char_cast(u: u8) -> char { u as char }
const unsafe fn ret_i32_no_unsafe() -> i32 { 42 }
const unsafe fn ret_null_ptr_no_unsafe<T>() -> *const T { 0 as *const T }
const unsafe fn ret_null_mut_ptr_no_unsafe<T>() -> *mut T { 0 as *mut T }
const unsafe fn ret_null_ptr_no_unsafe<T>() -> *const T { core::ptr::null() }
const unsafe fn ret_null_mut_ptr_no_unsafe<T>() -> *mut T { core::ptr::null_mut() }

// not ok
const fn foo11<T: std::fmt::Display>(t: T) -> T { t }
Expand Down
4 changes: 2 additions & 2 deletions src/test/ui/consts/min_const_fn/min_const_fn_unsafe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
//------------------------------------------------------------------------------

const unsafe fn ret_i32_no_unsafe() -> i32 { 42 }
const unsafe fn ret_null_ptr_no_unsafe<T>() -> *const T { 0 as *const T }
const unsafe fn ret_null_mut_ptr_no_unsafe<T>() -> *mut T { 0 as *mut T }
const unsafe fn ret_null_ptr_no_unsafe<T>() -> *const T { std::ptr::null() }
const unsafe fn ret_null_mut_ptr_no_unsafe<T>() -> *mut T { std::ptr::null_mut() }
const fn no_unsafe() { unsafe {} }

const fn call_unsafe_const_fn() -> i32 {
Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/derived-errors/issue-31997.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ fn closure<F, T>(x: F) -> Result<T, ()>
}

fn foo() -> Result<(), ()> {
try!(closure(|| bar(0 as *mut _))); //~ ERROR cannot find function `bar` in this scope
try!(closure(|| bar(core::ptr::null_mut()))); //~ ERROR cannot find function `bar` in this scope
Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/derived-errors/issue-31997.stderr
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
error[E0425]: cannot find function `bar` in this scope
--> $DIR/issue-31997.rs:13:21
|
LL | try!(closure(|| bar(0 as *mut _)));
LL | try!(closure(|| bar(core::ptr::null_mut())));
| ^^^ not found in this scope

error: aborting due to previous error
Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/error-codes/E0605.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ fn main() {
let x = 0u8;
x as Vec<u8>; //~ ERROR E0605

let v = 0 as *const u8;
let v = std::ptr::null::<u8>();
v as &u8; //~ ERROR E0605
}
2 changes: 1 addition & 1 deletion src/test/ui/error-codes/E0607.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
fn main() {
let v = 0 as *const u8;
let v = core::ptr::null::<u8>();
v as *const [u8]; //~ ERROR E0607
}
2 changes: 1 addition & 1 deletion src/test/ui/error-festival.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ fn main() {
let y: u32 = x as u32;
//~^ ERROR E0606

let v = 0 as *const u8;
let v = core::ptr::null::<u8>();
v as *const [u8];
//~^ ERROR E0607
}
2 changes: 1 addition & 1 deletion src/test/ui/issues/issue-17458.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
static X: usize = unsafe { 0 as *const usize as usize };
static X: usize = unsafe { core::ptr::null::<usize>() as usize };
//~^ ERROR: casting pointers to integers in statics is unstable

fn main() {
Expand Down
4 changes: 2 additions & 2 deletions src/test/ui/issues/issue-17458.stderr
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
error[E0658]: casting pointers to integers in statics is unstable
--> $DIR/issue-17458.rs:1:28
|
LL | static X: usize = unsafe { 0 as *const usize as usize };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
LL | static X: usize = unsafe { core::ptr::null::<usize>() as usize };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: for more information, see https://github.com/rust-lang/rust/issues/51910
= help: add #![feature(const_raw_ptr_to_usize_cast)] to the crate attributes to enable
Expand Down
4 changes: 2 additions & 2 deletions src/test/ui/issues/issue-20801.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ fn mut_ref() -> &'static mut T {
}

fn mut_ptr() -> *mut T {
unsafe { 0 as *mut T }
unsafe { core::ptr::null_mut() }
}

fn const_ptr() -> *const T {
unsafe { 0 as *const T }
unsafe { core::ptr::null() }
}

pub fn main() {
Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/issues/issue-22034.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
extern crate libc;

fn main() {
let ptr: *mut () = 0 as *mut _;
let ptr: *mut () = core::ptr::null_mut();
let _: &mut dyn Fn() = unsafe {
&mut *(ptr as *mut dyn Fn())
//~^ ERROR expected a `std::ops::Fn<()>` closure, found `()`
Expand Down
6 changes: 3 additions & 3 deletions src/test/ui/mismatched_types/cast-rfc0401.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ enum E {
fn main()
{
let f: f32 = 1.2;
let v = 0 as *const u8;
let fat_v : *const [u8] = unsafe { &*(0 as *const [u8; 1])};
let fat_sv : *const [i8] = unsafe { &*(0 as *const [i8; 1])};
let v = core::ptr::null::<u8>();
let fat_v : *const [u8] = unsafe { &*core::ptr::null::<[u8; 1]>()};
let fat_sv : *const [i8] = unsafe { &*core::ptr::null::<[i8; 1]>()};
let foo: &dyn Foo = &f;

let _ = v as &u8; //~ ERROR non-primitive cast
Expand Down

0 comments on commit a6a8f6c

Please sign in to comment.