Skip to content

Commit

Permalink
Add some Rust utility functions and print support
Browse files Browse the repository at this point in the history
This gives an indication in the log that Tor was built with Rust
support, as well as laying some groundwork for further string-returning
APIs to be converted to Rust
  • Loading branch information
shahn authored and nmathewson committed May 19, 2017
1 parent 915fa39 commit f8ef7c6
Show file tree
Hide file tree
Showing 18 changed files with 386 additions and 1 deletion.
5 changes: 4 additions & 1 deletion Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ TESTING_TOR_BINARY=$(top_builddir)/src/or/tor$(EXEEXT)
endif

if USE_RUST
rust_ldadd=
rust_ldadd=$(top_builddir)/src/rust/target/release/libtor_util.a
else
rust_ldadd=
endif
Expand Down Expand Up @@ -236,3 +236,6 @@ mostlyclean-local:
rm -rf $(HTML_COVER_DIR)
rm -rf $(top_builddir)/doc/doxygen
rm -rf $(TEST_NETWORK_ALL_LOG_DIR)

clean-local:
rm -rf $(top_builddir)/src/rust/target
39 changes: 39 additions & 0 deletions src/common/compat_rust.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/* Copyright (c) 2017, The Tor Project, Inc. */
/* See LICENSE for licensing information */

/**
* \file rust_compat.c
* \brief Rust FFI compatibility functions and helpers. This file is only built
* if Rust is not used.
**/

#include "compat_rust.h"
#include "util.h"

/**
* Free storage pointed to by <b>str</b>, and itself.
*/
void
rust_str_free(rust_str_t str)
{
char *s = (char *)str;
tor_free(s);
}

/**
* Return zero-terminated contained string.
*/
const char *
rust_str_get(const rust_str_t str)
{
return (const char *)str;
}

/* If we were using Rust, we'd say so on startup. */
rust_str_t
rust_welcome_string(void)
{
char *s = tor_malloc_zero(1);
return (rust_str_t)s;
}

28 changes: 28 additions & 0 deletions src/common/compat_rust.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/* Copyright (c) 2017, The Tor Project, Inc. */
/* See LICENSE for licensing information */

/**
* \file rust_compat.h
* \brief Headers for rust_compat.c
**/

#ifndef TOR_RUST_COMPAT_H
#define TOR_RUST_COMPAT_H

#include "torint.h"

/**
* Strings allocated in Rust must be freed from Rust code again. Let's make
* it less likely to accidentally mess up and call tor_free() on it, because
* currently it'll just work but might break at any time.
*/
typedef uintptr_t rust_str_t;

void rust_str_free(rust_str_t);

const char *rust_str_get(const rust_str_t);

rust_str_t rust_welcome_string(void);

#endif

6 changes: 6 additions & 0 deletions src/common/include.am
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ LIBOR_A_SRC = \
$(threads_impl_source) \
$(readpassphrase_source)

if USE_RUST
else
LIBOR_A_SRC += src/common/compat_rust.c
endif

src/common/src_common_libor_testing_a-log.$(OBJEXT) \
src/common/log.$(OBJEXT): micro-revision.i

Expand Down Expand Up @@ -146,6 +151,7 @@ COMMONHEADERS = \
src/common/compat.h \
src/common/compat_libevent.h \
src/common/compat_openssl.h \
src/common/compat_rust.h \
src/common/compat_threads.h \
src/common/compat_time.h \
src/common/compress.h \
Expand Down
10 changes: 10 additions & 0 deletions src/or/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
#include "circuitlist.h"
#include "circuituse.h"
#include "command.h"
#include "compat_rust.h"
#include "compress.h"
#include "config.h"
#include "confparse.h"
Expand Down Expand Up @@ -3039,6 +3040,15 @@ tor_init(int argc, char *argv[])
"Expect more bugs than usual.");
}

{
rust_str_t rust_str = rust_welcome_string();
const char *s = rust_str_get(rust_str);
if (strlen(s) > 0) {
log_notice(LD_GENERAL, "%s", s);
}
rust_str_free(rust_str);
}

if (network_init()<0) {
log_err(LD_BUG,"Error initializing network; exiting.");
return -1;
Expand Down
14 changes: 14 additions & 0 deletions src/rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions src/rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[workspace]
members = ["tor_util"]

[profile.release]
debug = true
panic = "abort"

[source.crates-io]
registry = 'https://github.com/rust-lang/crates.io-index'
replace-with = 'vendored-sources'

[source.vendored-sources]
directory = 'vendor'

5 changes: 5 additions & 0 deletions src/rust/include.am
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
include src/rust/tor_util/include.am

EXTRA_DIST +=\
src/rust/Cargo.toml \
src/rust/Cargo.lock
13 changes: 13 additions & 0 deletions src/rust/tor_util/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
authors = ["The Tor Project"]
name = "tor_util"
version = "0.0.1"

[lib]
name = "tor_util"
path = "lib.rs"
crate_type = ["rlib", "staticlib"]

[dependencies]
libc = "*"

56 changes: 56 additions & 0 deletions src/rust/tor_util/ffi.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//! FFI functions, only to be called from C.
//!
//! Equivalent C versions of these live in `src/common/compat_rust.c`

use std::mem::forget;
use std::ffi::CString;

use libc;
use rust_string::RustString;

/// Free the passed `RustString` (`rust_str_t` in C), to be used in place of
/// `tor_free`().
///
/// # Examples
/// ```c
/// rust_str_t r_s = rust_welcome_string();
/// rust_str_free(r_s);
/// ```
#[no_mangle]
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub unsafe extern "C" fn rust_str_free(_str: RustString) {
// Empty body: Just drop _str and we're done (Drop takes care of it).
}

/// Lends an immutable, NUL-terminated C String.
///
/// # Examples
/// ```c
/// rust_str_t r_s = rust_welcome_string();
/// const char *s = rust_str_get(r_s);
/// printf("%s", s);
/// rust_str_free(r_s);
/// ```
#[no_mangle]
pub unsafe extern "C" fn rust_str_get(str: RustString) -> *const libc::c_char {
let res = str.as_ptr();
forget(str);
res
}

/// Returns a short string to announce Rust support during startup.
///
/// # Examples
/// ```c
/// rust_str_t r_s = rust_welcome_string();
/// const char *s = rust_str_get(r_s);
/// printf("%s", s);
/// rust_str_free(r_s);
/// ```
#[no_mangle]
pub extern "C" fn rust_welcome_string() -> RustString {
let s = CString::new("Tor is running with Rust integration. Please report \
any bugs you encouter.")
.unwrap();
RustString::from(s)
}
12 changes: 12 additions & 0 deletions src/rust/tor_util/include.am
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
EXTRA_DIST +=\
src/rust/tor_util/Cargo.toml \
src/rust/tor_util/lib.rs \
src/rust/tor_util/ffi.rs \
src/rust/tor_util/rust_string.rs

src/rust/target/release/libtor_util.a: FORCE
( cd "$(abs_top_srcdir)/src/rust/tor_util" ; \
CARGO_TARGET_DIR="$(abs_top_builddir)/src/rust/target" \
$(CARGO) build --release --quiet --frozen )

FORCE:
13 changes: 13 additions & 0 deletions src/rust/tor_util/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
//! C <-> Rust compatibility helpers and types.
//!
//! Generically useful, small scale helpers should go here. This goes for both
//! the C side (in the form of the ffi module) as well as the Rust side
//! (individual modules per functionality). The corresponding C stuff lives in
//! `src/common/compat_rust.{c,h}`.

extern crate libc;

mod rust_string;
pub mod ffi;

pub use rust_string::*;
101 changes: 101 additions & 0 deletions src/rust/tor_util/rust_string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
use std::ffi::CString;
use std::mem::forget;
use libc;

/// Compatibility wrapper for strings allocated in Rust and passed to C.
///
/// Rust doesn't ensure the safety of freeing memory across an FFI boundary, so
/// we need to take special care to ensure we're not accidentally calling
/// `tor_free`() on any string allocated in Rust. To more easily differentiate
/// between strings that possibly (if Rust support is enabled) were allocated
/// in Rust, C has the `rust_str_t` helper type. The equivalent on the Rust
/// side is `RustString`.
///
/// Note: This type must not be used for strings allocated in C.
#[repr(C)]
#[derive(Debug)]
pub struct RustString(*mut libc::c_char);

impl RustString {
/// Returns a pointer to the underlying NUL-terminated byte array.
///
/// Note that this function is not typically useful for Rust callers,
/// except in a direct FFI context.
///
/// # Examples
/// ```
/// # use tor_util::RustString;
/// use std::ffi::CString;
///
/// let r = RustString::from(CString::new("asdf").unwrap());
/// let c_str = r.as_ptr();
/// assert_eq!(b'a', unsafe { *c_str as u8});
/// ```
pub fn as_ptr(&self) -> *const libc::c_char {
self.0 as *const libc::c_char
}
}

impl From<CString> for RustString {
/// Constructs a new `RustString`
///
/// # Examples
/// ```
/// # use tor_util::RustString;
/// use std::ffi::CString;
///
/// let r = RustString::from(CString::new("asdf").unwrap());
/// ```
fn from(str: CString) -> RustString {
RustString(str.into_raw())
}
}

impl Into<CString> for RustString {
/// Reconstructs a `CString` from this `RustString`.
///
/// Useful to take ownership back from a `RustString` that was given to C
/// code.
///
/// # Examples
/// ```
/// # use tor_util::RustString;
/// use std::ffi::CString;
///
/// let cs = CString::new("asdf").unwrap();
/// let r = RustString::from(cs.clone());
/// let cs2 = r.into();
/// assert_eq!(cs, cs2);
/// ```
fn into(self) -> CString {
// Calling from_raw is always OK here: We only construct self using
// valid CStrings and don't expose anything that could mutate it
let ret = unsafe { CString::from_raw(self.0) };
forget(self);
ret
}
}

impl Drop for RustString {
fn drop(&mut self) {
// Don't use into() here, because we would need to move out of
// self. Same safety consideration. Immediately drop the created
// CString, which takes care of freeing the wrapped string.
unsafe { CString::from_raw(self.0) };
}
}

#[cfg(test)]
mod test {
use std::mem;
use super::*;

use libc;

/// Ensures we're not adding overhead by using RustString.
#[test]
fn size_of() {
assert_eq!(mem::size_of::<*mut libc::c_char>(),
mem::size_of::<RustString>())
}
}
Loading

0 comments on commit f8ef7c6

Please sign in to comment.