Skip to content

Minor clean up to a pile of unsafe code. #12445

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

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion mk/crates.mk
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ DEPS_rustc := syntax native:rustllvm flate arena serialize sync getopts \
collections time extra
DEPS_rustdoc := rustc native:sundown serialize sync getopts collections \
test time
DEPS_flate := std native:miniz
DEPS_flate := std extra native:miniz
DEPS_arena := std collections
DEPS_glob := std
DEPS_serialize := std
Expand Down
9 changes: 4 additions & 5 deletions src/libarena/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,13 +167,12 @@ unsafe fn destroy_chunk(chunk: &Chunk) {
// is necessary in order to properly do cleanup if a failure occurs
// during an initializer.
#[inline]
unsafe fn bitpack_tydesc_ptr(p: *TyDesc, is_done: bool) -> uint {
let p_bits: uint = transmute(p);
p_bits | (is_done as uint)
fn bitpack_tydesc_ptr(p: *TyDesc, is_done: bool) -> uint {
p as uint | (is_done as uint)
}
#[inline]
unsafe fn un_bitpack_tydesc_ptr(p: uint) -> (*TyDesc, bool) {
(transmute(p & !1), p & 1 == 1)
fn un_bitpack_tydesc_ptr(p: uint) -> (*TyDesc, bool) {
((p & !1) as *TyDesc, p & 1 == 1)
}

impl Arena {
Expand Down
16 changes: 16 additions & 0 deletions src/libextra/c_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@
* if necessary.
*/

use std::cast;
use std::ptr;
use std::raw;

/**
* The type representing a foreign chunk of memory
Expand Down Expand Up @@ -111,6 +113,20 @@ impl <T> CVec<T> {
}
}

/// View the stored data as a slice.
pub fn as_slice<'a>(&'a self) -> &'a [T] {
unsafe {
cast::transmute(raw::Slice { data: self.base as *T, len: self.len })
}
}

/// View the stored data as a mutable slice.
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
unsafe {
cast::transmute(raw::Slice { data: self.base as *T, len: self.len })
}
}

/**
* Retrieves an element at a given index
*
Expand Down
41 changes: 18 additions & 23 deletions src/libflate/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ Simple compression
#[license = "MIT/ASL2"];
#[allow(missing_doc)];

extern crate extra;
use std::libc::{c_void, size_t, c_int};
use std::libc;
use std::vec;
use extra::c_vec::CVec;

pub mod rustrt {
use std::libc::{c_int, c_void, size_t};
Expand All @@ -33,63 +34,57 @@ pub mod rustrt {
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *c_void;
-> *mut c_void;

pub fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *c_void;
-> *mut c_void;
}
}

static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum

fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> ~[u8] {
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> CVec<u8> {
unsafe {
let mut outsz : size_t = 0;
let res = rustrt::tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
assert!(res as int != 0);
let out = vec::raw::from_buf_raw(res as *u8,
outsz as uint);
libc::free(res as *mut c_void);
out
assert!(!res.is_null());
CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res))
}
}

pub fn deflate_bytes(bytes: &[u8]) -> ~[u8] {
pub fn deflate_bytes(bytes: &[u8]) -> CVec<u8> {
deflate_bytes_internal(bytes, LZ_NORM)
}

pub fn deflate_bytes_zlib(bytes: &[u8]) -> ~[u8] {
pub fn deflate_bytes_zlib(bytes: &[u8]) -> CVec<u8> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}

fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> ~[u8] {
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> CVec<u8> {
unsafe {
let mut outsz : size_t = 0;
let res = rustrt::tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
assert!(res as int != 0);
let out = vec::raw::from_buf_raw(res as *u8,
outsz as uint);
libc::free(res as *mut c_void);
out
assert!(!res.is_null());
CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res))
}
}

pub fn inflate_bytes(bytes: &[u8]) -> ~[u8] {
pub fn inflate_bytes(bytes: &[u8]) -> CVec<u8> {
inflate_bytes_internal(bytes, 0)
}

pub fn inflate_bytes_zlib(bytes: &[u8]) -> ~[u8] {
pub fn inflate_bytes_zlib(bytes: &[u8]) -> CVec<u8> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}

Expand All @@ -115,19 +110,19 @@ mod tests {
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input);
let out = inflate_bytes(cmp);
let out = inflate_bytes(cmp.as_slice());
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input, out);
assert_eq!(input.as_slice(), out.as_slice());
}
}

#[test]
fn test_zlib_flate() {
let bytes = ~[1, 2, 3, 4, 5];
let deflated = deflate_bytes(bytes);
let inflated = inflate_bytes(deflated);
assert_eq!(inflated, bytes);
let inflated = inflate_bytes(deflated.as_slice());
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
14 changes: 3 additions & 11 deletions src/libgreen/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
// except according to those terms.

use std::uint;
use std::cast::{transmute, transmute_mut_unsafe,
transmute_region, transmute_mut_region};
use std::cast::{transmute, transmute_mut_unsafe};
use stack::Stack;
use std::rt::stack;
use std::raw;
Expand Down Expand Up @@ -55,10 +54,6 @@ impl Context {
// Save and then immediately load the current context,
// which we will then modify to call the given function when restored
let mut regs = new_regs();
unsafe {
rust_swap_registers(transmute_mut_region(&mut *regs),
transmute_region(&*regs));
};

initialize_call_frame(&mut *regs,
init,
Expand Down Expand Up @@ -294,11 +289,8 @@ fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint,
}

fn align_down(sp: *mut uint) -> *mut uint {
unsafe {
let sp: uint = transmute(sp);
let sp = sp & !(16 - 1);
transmute::<uint, *mut uint>(sp)
}
let sp = (sp as uint) & !(16 - 1);
sp as *mut uint
}

// ptr::mut_offset is positive ints only
Expand Down
15 changes: 4 additions & 11 deletions src/libgreen/sched.rs
Original file line number Diff line number Diff line change
Expand Up @@ -612,9 +612,7 @@ impl Scheduler {
f: |&mut Scheduler, ~GreenTask|) -> ~GreenTask {
let f_opaque = ClosureConverter::from_fn(f);

let current_task_dupe = unsafe {
*cast::transmute::<&~GreenTask, &uint>(&current_task)
};
let current_task_dupe = &*current_task as *GreenTask;

// The current task is placed inside an enum with the cleanup
// function. This enum is then placed inside the scheduler.
Expand All @@ -633,13 +631,8 @@ impl Scheduler {
cast::transmute_mut_region(*next_task.sched.get_mut_ref());

let current_task: &mut GreenTask = match sched.cleanup_job {
Some(CleanupJob { task: ref task, .. }) => {
let task_ptr: *~GreenTask = task;
cast::transmute_mut_region(*cast::transmute_mut_unsafe(task_ptr))
}
None => {
rtabort!("no cleanup job");
}
Some(CleanupJob { task: ref mut task, .. }) => &mut **task,
None => rtabort!("no cleanup job")
};

let (current_task_context, next_task_context) =
Expand Down Expand Up @@ -852,7 +845,7 @@ impl Scheduler {

// * Utility Functions

pub fn sched_id(&self) -> uint { unsafe { cast::transmute(self) } }
pub fn sched_id(&self) -> uint { self as *Scheduler as uint }

pub fn run_cleanup_job(&mut self) {
let cleanup_job = self.cleanup_job.take_unwrap();
Expand Down
2 changes: 1 addition & 1 deletion src/libgreen/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ impl GreenTask {
// context switches

pub fn as_uint(&self) -> uint {
unsafe { cast::transmute(self) }
self as *GreenTask as uint
}

pub unsafe fn from_uint(val: uint) -> ~GreenTask { cast::transmute(val) }
Expand Down
12 changes: 6 additions & 6 deletions src/libnative/io/addrinfo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use std::cast;
use std::io::IoError;
use std::libc;
use std::libc::{c_char, c_int};
use std::ptr::null;
use std::ptr::{null, mut_null};

use super::net::sockaddr_to_addr;

Expand Down Expand Up @@ -42,13 +42,13 @@ impl GetAddrInfoRequest {
});

let hint_ptr = hint.as_ref().map_or(null(), |x| x as *libc::addrinfo);
let res = null();
let mut res = mut_null();

// Make the call
let s = unsafe {
let ch = if c_host.is_null() { null() } else { c_host.with_ref(|x| x) };
let cs = if c_serv.is_null() { null() } else { c_serv.with_ref(|x| x) };
getaddrinfo(ch, cs, hint_ptr, &res)
getaddrinfo(ch, cs, hint_ptr, &mut res)
};

// Error?
Expand All @@ -74,7 +74,7 @@ impl GetAddrInfoRequest {
flags: (*rp).ai_flags as uint
});

rp = (*rp).ai_next;
rp = (*rp).ai_next as *mut libc::addrinfo;
}
}

Expand All @@ -86,8 +86,8 @@ impl GetAddrInfoRequest {

extern "system" {
fn getaddrinfo(node: *c_char, service: *c_char,
hints: *libc::addrinfo, res: **libc::addrinfo) -> c_int;
fn freeaddrinfo(res: *libc::addrinfo);
hints: *libc::addrinfo, res: *mut *mut libc::addrinfo) -> c_int;
fn freeaddrinfo(res: *mut libc::addrinfo);
#[cfg(not(windows))]
fn gai_strerror(errcode: c_int) -> *c_char;
#[cfg(windows)]
Expand Down
2 changes: 1 addition & 1 deletion src/libnative/io/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl FileDesc {
#[cfg(not(windows))] type rlen = libc::size_t;
let ret = retry(|| unsafe {
libc::read(self.fd(),
buf.as_ptr() as *mut libc::c_void,
buf.as_mut_ptr() as *mut libc::c_void,
buf.len() as rlen) as libc::c_int
});
if ret == 0 {
Expand Down
2 changes: 1 addition & 1 deletion src/libnative/io/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ impl rtio::RtioTcpStream for TcpStream {
let ret = retry(|| {
unsafe {
libc::recv(self.fd(),
buf.as_ptr() as *mut libc::c_void,
buf.as_mut_ptr() as *mut libc::c_void,
buf.len() as wrlen,
0) as libc::c_int
}
Expand Down
4 changes: 2 additions & 2 deletions src/libnative/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ impl rt::Runtime for Ops {
cur_task.put_runtime(self as ~rt::Runtime);

unsafe {
let cur_task_dupe = *cast::transmute::<&~Task, &uint>(&cur_task);
let cur_task_dupe = &*cur_task as *Task;
let task = BlockedTask::block(cur_task);

if times == 1 {
Expand Down Expand Up @@ -218,7 +218,7 @@ impl rt::Runtime for Ops {
}
}
// re-acquire ownership of the task
cur_task = cast::transmute::<uint, ~Task>(cur_task_dupe);
cur_task = cast::transmute(cur_task_dupe);
}

// put the task back in TLS, and everything is as it once was.
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/back/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -944,7 +944,7 @@ fn link_rlib(sess: Session,
// into the archive.
let bc = obj_filename.with_extension("bc");
match fs::File::open(&bc).read_to_end().and_then(|data| {
fs::File::create(&bc).write(flate::deflate_bytes(data))
fs::File::create(&bc).write(flate::deflate_bytes(data).as_slice())
}) {
Ok(()) => {}
Err(e) => {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/back/lto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub fn run(sess: session::Session, llmod: ModuleRef,
let bc = bc.expect("missing bytecode in archive!");
let bc = time(sess.time_passes(), format!("inflate {}.bc", name), (), |_|
flate::inflate_bytes(bc));
let ptr = bc.as_ptr();
let ptr = bc.as_slice().as_ptr();
debug!("linking {}", name);
time(sess.time_passes(), format!("ll link {}", name), (), |()| unsafe {
if !llvm::LLVMRustLinkInExternalBitcode(llmod,
Expand Down
3 changes: 2 additions & 1 deletion src/librustc/metadata/cstore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use metadata::loader;

use std::cell::RefCell;
use collections::HashMap;
use extra::c_vec::CVec;
use syntax::ast;
use syntax::parse::token::IdentInterner;

Expand All @@ -28,7 +29,7 @@ use syntax::parse::token::IdentInterner;
pub type cnum_map = @RefCell<HashMap<ast::CrateNum, ast::CrateNum>>;

pub enum MetadataBlob {
MetadataVec(~[u8]),
MetadataVec(CVec<u8>),
MetadataArchive(loader::ArchiveMetadata),
}

Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/trans/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2569,7 +2569,7 @@ pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> ~[u8] {
let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
let metadata = encoder::encode_metadata(encode_parms, krate);
let compressed = encoder::metadata_encoding_version +
flate::deflate_bytes(metadata);
flate::deflate_bytes(metadata).as_slice();
let llmeta = C_bytes(compressed);
let llconst = C_struct([llmeta], false);
let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
Expand Down
2 changes: 1 addition & 1 deletion src/librustuv/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ impl QueuePool {
unsafe {
assert_eq!(uvll::uv_async_init(loop_.handle, handle, async_cb), 0);
uvll::uv_unref(handle);
let data: *c_void = *cast::transmute::<&~QueuePool, &*c_void>(&q);
let data = &*q as *QueuePool as *c_void;
uvll::set_data_for_uv_handle(handle, data);
}

Expand Down
4 changes: 1 addition & 3 deletions src/libserialize/ebml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,7 @@ pub mod reader {
];

unsafe {
let (ptr, _): (*u8, uint) = transmute(data);
let ptr = ptr.offset(start as int);
let ptr: *i32 = transmute(ptr);
let ptr = data.as_ptr().offset(start as int) as *i32;
let val = from_be32(*ptr) as u32;

let i = (val >> 28u) as uint;
Expand Down
Loading