Skip to content

Commit e2311fc

Browse files
committed
Remove dangerous and unnecessary casts of |usize| to |libc::size_t|.
Since |usize| may be larger than |libc::size_t|, it is generally not safe to cast from |usize| to |libc::size_t|. The effect of this commit is to cause the build to fail on a platform where `libc::size_t` isn't the same as `usize`. But, that is better than the current state of affairs, where unsafe truncations can occur on such platforms, potentially leading to buffer overflows and other unsafety.
1 parent efdc16b commit e2311fc

File tree

16 files changed

+43
-59
lines changed

16 files changed

+43
-59
lines changed

src/liballoc_jemalloc/lib.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ fn align_to_flags(align: usize) -> c_int {
7777
#[no_mangle]
7878
pub extern "C" fn __rust_allocate(size: usize, align: usize) -> *mut u8 {
7979
let flags = align_to_flags(align);
80-
unsafe { je_mallocx(size as size_t, flags) as *mut u8 }
80+
unsafe { je_mallocx(size, flags) as *mut u8 }
8181
}
8282

8383
#[no_mangle]
@@ -87,7 +87,7 @@ pub extern "C" fn __rust_reallocate(ptr: *mut u8,
8787
align: usize)
8888
-> *mut u8 {
8989
let flags = align_to_flags(align);
90-
unsafe { je_rallocx(ptr as *mut c_void, size as size_t, flags) as *mut u8 }
90+
unsafe { je_rallocx(ptr as *mut c_void, size, flags) as *mut u8 }
9191
}
9292

9393
#[no_mangle]
@@ -97,17 +97,17 @@ pub extern "C" fn __rust_reallocate_inplace(ptr: *mut u8,
9797
align: usize)
9898
-> usize {
9999
let flags = align_to_flags(align);
100-
unsafe { je_xallocx(ptr as *mut c_void, size as size_t, 0, flags) as usize }
100+
unsafe { je_xallocx(ptr as *mut c_void, size, 0, flags) as usize }
101101
}
102102

103103
#[no_mangle]
104104
pub extern "C" fn __rust_deallocate(ptr: *mut u8, old_size: usize, align: usize) {
105105
let flags = align_to_flags(align);
106-
unsafe { je_sdallocx(ptr as *mut c_void, old_size as size_t, flags) }
106+
unsafe { je_sdallocx(ptr as *mut c_void, old_size, flags) }
107107
}
108108

109109
#[no_mangle]
110110
pub extern "C" fn __rust_usable_size(size: usize, align: usize) -> usize {
111111
let flags = align_to_flags(align);
112-
unsafe { je_nallocx(size as size_t, flags) as usize }
112+
unsafe { je_nallocx(size, flags) as usize }
113113
}

src/liballoc_system/lib.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -92,16 +92,16 @@ mod imp {
9292

9393
pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 {
9494
if align <= MIN_ALIGN {
95-
libc::malloc(size as libc::size_t) as *mut u8
95+
libc::malloc(size) as *mut u8
9696
} else {
9797
#[cfg(target_os = "android")]
9898
unsafe fn more_aligned_malloc(size: usize, align: usize) -> *mut u8 {
99-
memalign(align as libc::size_t, size as libc::size_t) as *mut u8
99+
memalign(align, size) as *mut u8
100100
}
101101
#[cfg(not(target_os = "android"))]
102102
unsafe fn more_aligned_malloc(size: usize, align: usize) -> *mut u8 {
103103
let mut out = ptr::null_mut();
104-
let ret = posix_memalign(&mut out, align as libc::size_t, size as libc::size_t);
104+
let ret = posix_memalign(&mut out, align, size);
105105
if ret != 0 {
106106
ptr::null_mut()
107107
} else {
@@ -114,7 +114,7 @@ mod imp {
114114

115115
pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 {
116116
if align <= MIN_ALIGN {
117-
libc::realloc(ptr as *mut libc::c_void, size as libc::size_t) as *mut u8
117+
libc::realloc(ptr as *mut libc::c_void, size) as *mut u8
118118
} else {
119119
let new_ptr = allocate(size, align);
120120
ptr::copy(ptr, new_ptr, cmp::min(size, old_size));
@@ -171,7 +171,7 @@ mod imp {
171171
if align <= MIN_ALIGN {
172172
HeapAlloc(GetProcessHeap(), 0, size as SIZE_T) as *mut u8
173173
} else {
174-
let ptr = HeapAlloc(GetProcessHeap(), 0, (size + align) as SIZE_T) as *mut u8;
174+
let ptr = HeapAlloc(GetProcessHeap(), 0, size + align) as *mut u8;
175175
if ptr.is_null() {
176176
return ptr
177177
}
@@ -204,7 +204,7 @@ mod imp {
204204
let new = HeapReAlloc(GetProcessHeap(),
205205
HEAP_REALLOC_IN_PLACE_ONLY,
206206
ptr as LPVOID,
207-
size as SIZE_T) as *mut u8;
207+
size) as *mut u8;
208208
if new.is_null() {
209209
old_size
210210
} else {

src/libflate/lib.rs

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,8 @@ const TDEFL_WRITE_ZLIB_HEADER: c_int = 0x01000; // write zlib header and adler32
103103
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Bytes {
104104
unsafe {
105105
let mut outsz: size_t = 0;
106-
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *const _,
107-
bytes.len() as size_t,
108-
&mut outsz,
109-
flags);
106+
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *const _, bytes.len(),
107+
&mut outsz, flags);
110108
assert!(!res.is_null());
111109
Bytes {
112110
ptr: Unique::new(res as *mut u8),
@@ -129,9 +127,7 @@ fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Result<Bytes, Error> {
129127
unsafe {
130128
let mut outsz: size_t = 0;
131129
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *const _,
132-
bytes.len() as size_t,
133-
&mut outsz,
134-
flags);
130+
bytes.len(), &mut outsz, flags);
135131
if !res.is_null() {
136132
Ok(Bytes {
137133
ptr: Unique::new(res as *mut u8),

src/librustc_trans/back/archive.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ use std::process::{Command, Output, Stdio};
2121
use std::ptr;
2222
use std::str;
2323

24-
use libc;
2524
use llvm::archive_ro::{ArchiveRO, Child};
2625
use llvm::{self, ArchiveKind};
2726
use rustc::metadata::loader::METADATA_FILENAME;
@@ -489,8 +488,7 @@ impl<'a> ArchiveBuilder<'a> {
489488

490489
let dst = self.config.dst.to_str().unwrap().as_bytes();
491490
let dst = try!(CString::new(dst));
492-
let r = llvm::LLVMRustWriteArchive(dst.as_ptr(),
493-
members.len() as libc::size_t,
491+
let r = llvm::LLVMRustWriteArchive(dst.as_ptr(), members.len(),
494492
members.as_ptr(),
495493
self.should_update_symbols,
496494
kind);

src/librustc_trans/back/lto.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef,
100100
time(sess.time_passes(), &format!("ll link {}", name), || unsafe {
101101
if !llvm::LLVMRustLinkInExternalBitcode(llmod,
102102
ptr as *const libc::c_char,
103-
bc_decoded.len() as libc::size_t) {
103+
bc_decoded.len()) {
104104
write::llvm_err(sess.diagnostic().handler(),
105105
format!("failed to load bc of `{}`",
106106
&name[..]));
@@ -118,7 +118,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef,
118118
unsafe {
119119
llvm::LLVMRustRunRestrictionPass(llmod,
120120
ptr as *const *const libc::c_char,
121-
arr.len() as libc::size_t);
121+
arr.len());
122122
}
123123

124124
if sess.no_landing_pads() {

src/librustdoc/html/markdown.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -371,8 +371,7 @@ pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result {
371371
(*renderer).codespan = Some(codespan);
372372

373373
let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
374-
hoedown_document_render(document, ob, s.as_ptr(),
375-
s.len() as libc::size_t);
374+
hoedown_document_render(document, ob, s.as_ptr(), s.len());
376375
hoedown_document_free(document);
377376

378377
hoedown_html_renderer_free(renderer);
@@ -444,8 +443,7 @@ pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
444443
= tests as *mut _ as *mut libc::c_void;
445444

446445
let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
447-
hoedown_document_render(document, ob, doc.as_ptr(),
448-
doc.len() as libc::size_t);
446+
hoedown_document_render(document, ob, doc.as_ptr(), doc.len());
449447
hoedown_document_free(document);
450448

451449
hoedown_html_renderer_free(renderer);
@@ -565,8 +563,7 @@ pub fn plain_summary_line(md: &str) -> String {
565563
(*renderer).normal_text = Some(normal_text);
566564

567565
let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
568-
hoedown_document_render(document, ob, md.as_ptr(),
569-
md.len() as libc::size_t);
566+
hoedown_document_render(document, ob, md.as_ptr(), md.len());
570567
hoedown_document_free(document);
571568
let plain_slice = (*ob).as_bytes();
572569
let plain = str::from_utf8(plain_slice).unwrap_or("").to_owned();

src/libstd/rand/os.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,8 +236,7 @@ mod imp {
236236
}
237237
fn fill_bytes(&mut self, v: &mut [u8]) {
238238
let ret = unsafe {
239-
SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t,
240-
v.as_mut_ptr())
239+
SecRandomCopyBytes(kSecRandomDefault, v.len(), v.as_mut_ptr())
241240
};
242241
if ret == -1 {
243242
panic!("couldn't generate random bytes: {}",

src/libstd/sys/common/net.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ extern "system" {
143143
flags: c_int) -> c_int;
144144
}
145145

146-
const NI_MAXHOST: usize = 1025;
146+
const NI_MAXHOST: libc::size_t = 1025;
147147

148148
pub fn lookup_addr(addr: &IpAddr) -> io::Result<String> {
149149
init();
@@ -154,7 +154,7 @@ pub fn lookup_addr(addr: &IpAddr) -> io::Result<String> {
154154

155155
let data = unsafe {
156156
try!(cvt_gai(getnameinfo(inner, len,
157-
hostbuf.as_mut_ptr(), NI_MAXHOST as libc::size_t,
157+
hostbuf.as_mut_ptr(), NI_MAXHOST,
158158
ptr::null_mut(), 0, 0)));
159159

160160
CStr::from_ptr(hostbuf.as_ptr())

src/libstd/sys/unix/fd.rs

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
// except according to those terms.
1010

1111
use io;
12-
use libc::{self, c_int, size_t, c_void};
12+
use libc::{self, c_int, c_void};
1313
use mem;
1414
use sys::c;
1515
use sys::cvt;
@@ -35,18 +35,14 @@ impl FileDesc {
3535

3636
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
3737
let ret = try!(cvt(unsafe {
38-
libc::read(self.fd,
39-
buf.as_mut_ptr() as *mut c_void,
40-
buf.len() as size_t)
38+
libc::read(self.fd, buf.as_mut_ptr() as *mut c_void, buf.len())
4139
}));
4240
Ok(ret as usize)
4341
}
4442

4543
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
4644
let ret = try!(cvt(unsafe {
47-
libc::write(self.fd,
48-
buf.as_ptr() as *const c_void,
49-
buf.len() as size_t)
45+
libc::write(self.fd, buf.as_ptr() as *const c_void, buf.len())
5046
}));
5147
Ok(ret as usize)
5248
}

src/libstd/sys/unix/fs.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use os::unix::prelude::*;
1414
use ffi::{CString, CStr, OsString, OsStr};
1515
use fmt;
1616
use io::{self, Error, ErrorKind, SeekFrom};
17-
use libc::{self, c_int, size_t, off_t, c_char, mode_t};
17+
use libc::{self, c_int, off_t, c_char, mode_t};
1818
use mem;
1919
use path::{Path, PathBuf};
2020
use ptr;
@@ -478,7 +478,7 @@ pub fn readlink(p: &Path) -> io::Result<PathBuf> {
478478

479479
loop {
480480
let buf_read = try!(cvt(unsafe {
481-
libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity() as libc::size_t)
481+
libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity())
482482
})) as usize;
483483

484484
unsafe { buf.set_len(buf_read); }

src/libstd/sys/unix/os.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ pub fn error_string(errno: i32) -> String {
8383

8484
let p = buf.as_mut_ptr();
8585
unsafe {
86-
if strerror_r(errno as c_int, p, buf.len() as libc::size_t) < 0 {
86+
if strerror_r(errno as c_int, p, buf.len()) < 0 {
8787
panic!("strerror_r failure");
8888
}
8989

@@ -97,7 +97,7 @@ pub fn getcwd() -> io::Result<PathBuf> {
9797
loop {
9898
unsafe {
9999
let ptr = buf.as_mut_ptr() as *mut libc::c_char;
100-
if !libc::getcwd(ptr, buf.capacity() as libc::size_t).is_null() {
100+
if !libc::getcwd(ptr, buf.capacity()).is_null() {
101101
let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
102102
buf.set_len(len);
103103
buf.shrink_to_fit();
@@ -488,8 +488,7 @@ pub fn home_dir() -> Option<PathBuf> {
488488
let mut passwd: c::passwd = mem::zeroed();
489489
let mut result = ptr::null_mut();
490490
match c::getpwuid_r(me, &mut passwd, buf.as_mut_ptr(),
491-
buf.capacity() as libc::size_t,
492-
&mut result) {
491+
buf.capacity(), &mut result) {
493492
0 if !result.is_null() => {}
494493
_ => return None
495494
}

src/libstd/sys/unix/thread.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ impl Thread {
4343
assert_eq!(pthread_attr_init(&mut attr), 0);
4444

4545
let stack_size = cmp::max(stack, min_stack_size(&attr));
46-
match pthread_attr_setstacksize(&mut attr, stack_size as libc::size_t) {
46+
match pthread_attr_setstacksize(&mut attr, stack_size) {
4747
0 => {}
4848
n => {
4949
assert_eq!(n, libc::EINVAL);
@@ -54,7 +54,7 @@ impl Thread {
5454
let page_size = os::page_size();
5555
let stack_size = (stack_size + page_size - 1) &
5656
(-(page_size as isize - 1) as usize - 1);
57-
let stack_size = stack_size as libc::size_t;
57+
let stack_size = stack_size;
5858
assert_eq!(pthread_attr_setstacksize(&mut attr, stack_size), 0);
5959
}
6060
};
@@ -251,7 +251,7 @@ pub mod guard {
251251
// This ensures SIGBUS will be raised on
252252
// stack overflow.
253253
let result = mmap(stackaddr,
254-
psize as libc::size_t,
254+
psize,
255255
PROT_NONE,
256256
MAP_PRIVATE | MAP_ANON | MAP_FIXED,
257257
-1,
@@ -272,7 +272,7 @@ pub mod guard {
272272
fn pthread_get_stackaddr_np(thread: pthread_t) -> *mut libc::c_void;
273273
fn pthread_get_stacksize_np(thread: pthread_t) -> libc::size_t;
274274
}
275-
Some((pthread_get_stackaddr_np(pthread_self()) as libc::size_t -
275+
Some((pthread_get_stackaddr_np(pthread_self()) -
276276
pthread_get_stacksize_np(pthread_self())) as usize)
277277
}
278278

src/libstd/sys/windows/thread.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,9 @@ impl Thread {
3737
// Round up to the next 64 kB because that's what the NT kernel does,
3838
// might as well make it explicit.
3939
let stack_size = (stack + 0xfffe) & (!0xfffe);
40-
let ret = c::CreateThread(ptr::null_mut(), stack_size as libc::size_t,
41-
thread_start, &*p as *const _ as *mut _,
42-
0, ptr::null_mut());
40+
let ret = c::CreateThread(ptr::null_mut(), stack_size, thread_start,
41+
&*p as *const _ as *mut _, 0,
42+
ptr::null_mut());
4343

4444
return if ret as usize == 0 {
4545
Err(io::Error::last_os_error())

src/test/auxiliary/allocator-dummy.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ pub static mut HITS: usize = 0;
2323
pub extern fn __rust_allocate(size: usize, align: usize) -> *mut u8 {
2424
unsafe {
2525
HITS += 1;
26-
libc::malloc(size as libc::size_t) as *mut u8
26+
libc::malloc(size) as *mut u8
2727
}
2828
}
2929

@@ -39,7 +39,7 @@ pub extern fn __rust_deallocate(ptr: *mut u8, old_size: usize, align: usize) {
3939
pub extern fn __rust_reallocate(ptr: *mut u8, old_size: usize, size: usize,
4040
align: usize) -> *mut u8 {
4141
unsafe {
42-
libc::realloc(ptr as *mut _, size as libc::size_t) as *mut u8
42+
libc::realloc(ptr as *mut _, size) as *mut u8
4343
}
4444
}
4545

src/test/bench/shootout-reverse-complement.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,9 @@ impl Tables {
103103

104104
/// Finds the first position at which `b` occurs in `s`.
105105
fn memchr(h: &[u8], n: u8) -> Option<usize> {
106-
use libc::{c_void, c_int, size_t};
106+
use libc::{c_void, c_int};
107107
let res = unsafe {
108-
libc::memchr(h.as_ptr() as *const c_void, n as c_int, h.len() as size_t)
108+
libc::memchr(h.as_ptr() as *const c_void, n as c_int, h.len())
109109
};
110110
if res.is_null() {
111111
None

src/test/run-pass/regions-mock-trans.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@ struct Ccx {
3232

3333
fn alloc<'a>(_bcx : &'a arena) -> &'a Bcx<'a> {
3434
unsafe {
35-
mem::transmute(libc::malloc(mem::size_of::<Bcx<'a>>()
36-
as libc::size_t))
35+
mem::transmute(libc::malloc(mem::size_of::<Bcx<'a>>()))
3736
}
3837
}
3938

0 commit comments

Comments
 (0)