Skip to content

Commit

Permalink
auto merge of rust-lang#10943 : fhahn/rust/issue-7313-replace-c-types…
Browse files Browse the repository at this point in the history
…, r=alexcrichton

I've started working on a patch for rust-lang#7313 . So far I tried to replace C types in `src/libstd/unstable/*` and related files.

So far, I have two questions. Is there a convention for passing pointers around in `std` as Rust types? Sometimes pointers are passed around as `*c_char` (which seems to be an `*i8`), `*c_void` or `*u8`, which leads to a lot of casts. E.g: [`exchange_malloc`](https://github.com/fhahn/rust/compare/issue-7313-replace-c-types?expand=1#diff-39f44b8c3f4496abab854b3425ac1617R60) used to return a `*c_char` but the function in turn only calls `malloc_raw` which returns a `*c_void`.
Is there a specific reason for this?

The second question is about `CString` and related functions like `with_c_str`. At the moment these functions use `*c_char*`. Should I replace it with `*u8` or keep it, because it's an wrapper around classical C strings?
  • Loading branch information
bors committed Jan 22, 2014
2 parents de50c56 + 2eb4f05 commit aedf567
Show file tree
Hide file tree
Showing 19 changed files with 158 additions and 173 deletions.
5 changes: 2 additions & 3 deletions src/libstd/cleanup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@

#[doc(hidden)];

use libc::c_void;
use ptr;
use unstable::intrinsics::TyDesc;
use unstable::raw;

type DropGlue<'a> = 'a |**TyDesc, *c_void|;
type DropGlue<'a> = 'a |**TyDesc, *u8|;

static RC_IMMORTAL : uint = 0x77777777;

Expand Down Expand Up @@ -107,7 +106,7 @@ pub unsafe fn annihilate() {
stats.n_bytes_freed +=
(*((*alloc).type_desc)).size
+ mem::size_of::<raw::Box<()>>();
local_free(alloc as *i8);
local_free(alloc as *u8);
true
});

Expand Down
11 changes: 5 additions & 6 deletions src/libstd/local_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,9 @@ local_data::get(key_vector, |opt| assert_eq!(*opt.unwrap(), ~[4]));
// magic.

use cast;
use libc;
use prelude::*;
use rt::task::{Task, LocalStorage};
use util;
use util::replace;

/**
* Indexes a task-local data slot. This pointer is used for comparison to
Expand Down Expand Up @@ -87,7 +86,7 @@ impl<T: 'static> LocalData for T {}
// n.b. If TLS is used heavily in future, this could be made more efficient with
// a proper map.
#[doc(hidden)]
pub type Map = ~[Option<(*libc::c_void, TLSValue, LoanState)>];
pub type Map = ~[Option<(*u8, TLSValue, LoanState)>];
type TLSValue = ~LocalData;

// Gets the map from the runtime. Lazily initialises if not done so already.
Expand Down Expand Up @@ -128,7 +127,7 @@ impl LoanState {
}
}

fn key_to_key_value<T: 'static>(key: Key<T>) -> *libc::c_void {
fn key_to_key_value<T: 'static>(key: Key<T>) -> *u8 {
unsafe { cast::transmute(key) }
}

Expand All @@ -151,7 +150,7 @@ pub fn pop<T: 'static>(key: Key<T>) -> Option<T> {
// Move the data out of the `entry` slot via util::replace.
// This is guaranteed to succeed because we already matched
// on `Some` above.
let data = match util::replace(entry, None) {
let data = match replace(entry, None) {
Some((_, data, _)) => data,
None => abort()
};
Expand Down Expand Up @@ -302,7 +301,7 @@ pub fn set<T: 'static>(key: Key<T>, data: T) {
let data = ~data as ~LocalData:;

fn insertion_position(map: &mut Map,
key: *libc::c_void) -> Option<uint> {
key: *u8) -> Option<uint> {
// First see if the map contains this key already
let curspot = map.iter().position(|entry| {
match *entry {
Expand Down
64 changes: 32 additions & 32 deletions src/libstd/os.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ use unstable::finally::Finally;
use sync::atomics::{AtomicInt, INIT_ATOMIC_INT, SeqCst};

/// Delegates to the libc close() function, returning the same return value.
pub fn close(fd: c_int) -> c_int {
pub fn close(fd: int) -> int {
unsafe {
libc::close(fd)
libc::close(fd as c_int) as int
}
}

Expand All @@ -57,7 +57,7 @@ static BUF_BYTES : uint = 2048u;
pub fn getcwd() -> Path {
use c_str::CString;

let mut buf = [0 as libc::c_char, ..BUF_BYTES];
let mut buf = [0 as c_char, ..BUF_BYTES];
unsafe {
if libc::getcwd(buf.as_mut_ptr(), buf.len() as size_t).is_null() {
fail!()
Expand Down Expand Up @@ -164,7 +164,7 @@ pub fn env() -> ~[(~str,~str)] {
os::last_os_error());
}
let mut result = ~[];
c_str::from_c_multistring(ch as *libc::c_char, None, |cstr| {
c_str::from_c_multistring(ch as *c_char, None, |cstr| {
result.push(cstr.as_str().unwrap().to_owned());
});
FreeEnvironmentStringsA(ch);
Expand All @@ -173,7 +173,7 @@ pub fn env() -> ~[(~str,~str)] {
#[cfg(unix)]
unsafe fn get_env_pairs() -> ~[~str] {
extern {
fn rust_env_pairs() -> **libc::c_char;
fn rust_env_pairs() -> **c_char;
}
let environ = rust_env_pairs();
if environ as uint == 0 {
Expand Down Expand Up @@ -306,9 +306,9 @@ pub struct Pipe {
#[cfg(unix)]
pub fn pipe() -> Pipe {
unsafe {
let mut fds = Pipe {input: 0 as c_int,
out: 0 as c_int };
assert_eq!(libc::pipe(&mut fds.input), (0 as c_int));
let mut fds = Pipe {input: 0,
out: 0};
assert_eq!(libc::pipe(&mut fds.input), 0);
return Pipe {input: fds.input, out: fds.out};
}
}
Expand All @@ -321,13 +321,13 @@ pub fn pipe() -> Pipe {
// fully understand. Here we explicitly make the pipe non-inheritable,
// which means to pass it to a subprocess they need to be duplicated
// first, as in std::run.
let mut fds = Pipe {input: 0 as c_int,
out: 0 as c_int };
let mut fds = Pipe {input: 0,
out: 0};
let res = libc::pipe(&mut fds.input, 1024 as ::libc::c_uint,
(libc::O_BINARY | libc::O_NOINHERIT) as c_int);
assert_eq!(res, 0 as c_int);
assert!((fds.input != -1 as c_int && fds.input != 0 as c_int));
assert!((fds.out != -1 as c_int && fds.input != 0 as c_int));
assert_eq!(res, 0);
assert!((fds.input != -1 && fds.input != 0 ));
assert!((fds.out != -1 && fds.input != 0));
return Pipe {input: fds.input, out: fds.out};
}
}
Expand Down Expand Up @@ -699,7 +699,7 @@ pub fn get_exit_status() -> int {
}

#[cfg(target_os = "macos")]
unsafe fn load_argc_and_argv(argc: c_int, argv: **c_char) -> ~[~str] {
unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> ~[~str] {
let mut args = ~[];
for i in range(0u, argc as uint) {
args.push(str::raw::from_c_str(*argv.offset(i as int)));
Expand All @@ -715,7 +715,7 @@ unsafe fn load_argc_and_argv(argc: c_int, argv: **c_char) -> ~[~str] {
#[cfg(target_os = "macos")]
fn real_args() -> ~[~str] {
unsafe {
let (argc, argv) = (*_NSGetArgc() as c_int,
let (argc, argv) = (*_NSGetArgc() as int,
*_NSGetArgv() as **c_char);
load_argc_and_argv(argc, argv)
}
Expand Down Expand Up @@ -833,7 +833,7 @@ pub struct MemoryMap {
/// Pointer to the memory created or modified by this map.
data: *mut u8,
/// Number of bytes this map applies to
len: size_t,
len: uint,
/// Type of mapping
kind: MemoryMapKind
}
Expand All @@ -842,7 +842,7 @@ pub struct MemoryMap {
pub enum MemoryMapKind {
/// Memory-mapped file. On Windows, the inner pointer is a handle to the mapping, and
/// corresponds to `CreateFileMapping`. Elsewhere, it is null.
MapFile(*c_void),
MapFile(*u8),
/// Virtual memory map. Usually used to change the permissions of a given chunk of memory.
/// Corresponds to `VirtualAlloc` on Windows.
MapVirtual
Expand All @@ -857,7 +857,7 @@ pub enum MapOption {
/// The memory should be executable
MapExecutable,
/// Create a map for a specific address range. Corresponds to `MAP_FIXED` on POSIX.
MapAddr(*c_void),
MapAddr(*u8),
/// Create a memory mapping for a file with a given fd.
MapFd(c_int),
/// When using `MapFd`, the start of the map is `uint` bytes from the start of the file.
Expand All @@ -881,7 +881,7 @@ pub enum MapError {
/// using `MapFd`, the target of the fd didn't have enough resources to fulfill the request.
ErrNoMem,
/// Unrecognized error. The inner value is the unrecognized errno.
ErrUnknown(libc::c_int),
ErrUnknown(int),
/// ## The following are win32-specific
///
/// Unsupported combination of protection flags (`MapReadable`/`MapWritable`/`MapExecutable`).
Expand Down Expand Up @@ -926,12 +926,12 @@ impl MemoryMap {
pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
use libc::off_t;

let mut addr: *c_void = ptr::null();
let mut prot: c_int = 0;
let mut flags: c_int = libc::MAP_PRIVATE;
let mut fd: c_int = -1;
let mut offset: off_t = 0;
let len = round_up(min_len, page_size()) as size_t;
let mut addr: *u8 = ptr::null();
let mut prot = 0;
let mut flags = libc::MAP_PRIVATE;
let mut fd = -1;
let mut offset = 0;
let len = round_up(min_len, page_size());

for &o in options.iter() {
match o {
Expand All @@ -952,7 +952,7 @@ impl MemoryMap {
if fd == -1 { flags |= libc::MAP_ANON; }

let r = unsafe {
libc::mmap(addr, len, prot, flags, fd, offset)
libc::mmap(addr as *c_void, len as size_t, prot, flags, fd, offset)
};
if r.equiv(&libc::MAP_FAILED) {
Err(match errno() as c_int {
Expand All @@ -961,7 +961,7 @@ impl MemoryMap {
libc::EINVAL => ErrUnaligned,
libc::ENODEV => ErrNoMapSupport,
libc::ENOMEM => ErrNoMem,
code => ErrUnknown(code)
code => ErrUnknown(code as int)
})
} else {
Ok(MemoryMap {
Expand All @@ -987,7 +987,7 @@ impl Drop for MemoryMap {
/// Unmap the mapping. Fails the task if `munmap` fails.
fn drop(&mut self) {
unsafe {
match libc::munmap(self.data as *c_void, self.len) {
match libc::munmap(self.data as *c_void, self.len as libc::size_t) {
0 => (),
-1 => match errno() as c_int {
libc::EINVAL => error!("invalid addr or len"),
Expand All @@ -1011,7 +1011,7 @@ impl MemoryMap {
let mut executable = false;
let mut fd: c_int = -1;
let mut offset: uint = 0;
let len = round_up(min_len, page_size()) as SIZE_T;
let len = round_up(min_len, page_size());

for &o in options.iter() {
match o {
Expand Down Expand Up @@ -1040,7 +1040,7 @@ impl MemoryMap {
}
let r = unsafe {
libc::VirtualAlloc(lpAddress,
len,
len as SIZE_T,
libc::MEM_COMMIT | libc::MEM_RESERVE,
flProtect)
};
Expand Down Expand Up @@ -1085,7 +1085,7 @@ impl MemoryMap {
_ => Ok(MemoryMap {
data: r as *mut u8,
len: len,
kind: MapFile(mapping as *c_void)
kind: MapFile(mapping as *u8)
})
}
}
Expand Down Expand Up @@ -1116,7 +1116,7 @@ impl Drop for MemoryMap {
match self.kind {
MapVirtual => {
if libc::VirtualFree(self.data as *mut c_void,
self.len,
self.len as size_t,
libc::MEM_RELEASE) == FALSE {
error!("VirtualFree failed: {}", errno());
}
Expand Down
4 changes: 2 additions & 2 deletions src/libstd/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ impl<T> Drop for Rc<T> {
if (*self.ptr).strong == 0 {
read_ptr(self.borrow()); // destroy the contained object
if (*self.ptr).weak == 0 {
exchange_free(self.ptr as *mut u8 as *i8)
exchange_free(self.ptr as *u8)
}
}
}
Expand Down Expand Up @@ -153,7 +153,7 @@ impl<T> Drop for Weak<T> {
if self.ptr != 0 as *mut RcBox<T> {
(*self.ptr).weak -= 1;
if (*self.ptr).weak == 0 && (*self.ptr).strong == 0 {
exchange_free(self.ptr as *mut u8 as *i8)
exchange_free(self.ptr as *u8)
}
}
}
Expand Down
7 changes: 3 additions & 4 deletions src/libstd/reflect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ Runtime type reflection
#[allow(missing_doc)];

use unstable::intrinsics::{Disr, Opaque, TyDesc, TyVisitor};
use libc::c_void;
use mem;
use unstable::raw;

Expand All @@ -28,7 +27,7 @@ use unstable::raw;
* then build a MovePtrAdaptor wrapped around your struct.
*/
pub trait MovePtr {
fn move_ptr(&mut self, adjustment: |*c_void| -> *c_void);
fn move_ptr(&mut self, adjustment: |*u8| -> *u8);
fn push_ptr(&mut self);
fn pop_ptr(&mut self);
}
Expand All @@ -50,12 +49,12 @@ pub fn MovePtrAdaptor<V:TyVisitor + MovePtr>(v: V) -> MovePtrAdaptor<V> {
impl<V:TyVisitor + MovePtr> MovePtrAdaptor<V> {
#[inline]
pub fn bump(&mut self, sz: uint) {
self.inner.move_ptr(|p| ((p as uint) + sz) as *c_void)
self.inner.move_ptr(|p| ((p as uint) + sz) as *u8)
}

#[inline]
pub fn align(&mut self, a: uint) {
self.inner.move_ptr(|p| align(p as uint, a) as *c_void)
self.inner.move_ptr(|p| align(p as uint, a) as *u8)
}

#[inline]
Expand Down
Loading

0 comments on commit aedf567

Please sign in to comment.