9 ms·
Rust once, run everywhere
- sampo 12y ago> Rust makes it easy to communicate with C APIs without overhead Zero overhead vs. the case where you'd also have function call in C. But in some cases, especially with numerics, if you have a C library that is designed to be inlined, you get slowdown even calling C from C, if you prevent inlining. A random number generator, SIMD-oriented Fast Mersenne Twister [1], was such a case when I tried. Just calling with `_attribute__ ((noinline))` makes it 2x slower, even when calling from C. [1] http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/ http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/
- CyberDildonics 12y agoFor small functions that cannot be inlined, they should work across arrays that are as big as you can make them to make the overhead trivial.
- twoodfin 12y agoI don't see any reason (though I'd love to be enlightened) why the Rust implementation couldn't someday inline C functions. I'd actually be a little surprised if the underlying LLVM implementation can't use LTO to do it out of the box.
- kibwen 12y agoAs mentioned downthread, this is exactly what Servo intends to do to interop with SpiderMonkey. I'm very excited to see that project proceed.
- simias 12y agoCan't link time optimization help with that? I assume it's language agnostic.
- vezzy-fnord 12y agoI recall something about Rust's libc crate being glibc-specific. What's the status on that, and can one build the compiler on Solaris/illumos, NetBSD and OpenBSD?
- steveklabnik 12y ago> What's the status on that We still use glibc, yes. Being able to use musl instead is something that the community and team have been experimenting with lately. > can one build the compiler on Solaris/illumos, NetBSD and OpenBSD? The last two have community members that keep the build green. I _think_ illumos works, but I'm not sure.
- steveklabnik 12y agoOh, look what just popped up: https://github.com/rust-lang/rust/pull/24777 https://github.com/rust-lang/rust/pull/24777
- kibwen 12y agoHere's an experience report by someone who managed to get Rust running on musl, for the purpose of creating fully static Rust binaries: https://gist.github.com/cl91/bb927df2525738502131#file-static-linking-against-musl-md https://gist.github.com/cl91/bb927df2525738502131#file-stati... (discussion at https://www.reddit.com/r/rust/comments/33boew/weekend_experiment_link_rust_programs_against/ https://www.reddit.com/r/rust/comments/33boew/weekend_experi...).
- kibwen 12y agoUPDATE: Official (though still experimental) support for using musl with Rust code is landing in the compiler as we speak! https://github.com/rust-lang/rust/pull/24777 https://github.com/rust-lang/rust/pull/24777
- duaneb 12y ago> I recall something about Rust's libc crate being glibc-specific. If this is true, it's because support for others hasn't rolled out yet, not because it has some inherent dependency on that version of libc.
- tree_of_item 12y agoI was hoping this was an announcement of Emscripten support for Rust :(
- steveklabnik 12y agoWe need Emscripten to upgrade their LLVM, last I heard. We're running a pretty cutting-edge version at the moment.
- kibwen 12y agoPeople are eagerly working on it: http://users.rust-lang.org/t/rust-to-js-with-emscripten/587 http://users.rust-lang.org/t/rust-to-js-with-emscripten/587
- haberman 12y agoLikewise I keep hoping someone will make a compile-Rust-to-portable-C story realistic also! The LLVM C backend has been revived! https://github.com/draperlaboratory/llvm-cbe https://github.com/draperlaboratory/llvm-cbe http://lists.cs.uiuc.edu/pipermail/llvmdev/2014-August/075934.html http://lists.cs.uiuc.edu/pipermail/llvmdev/2014-August/07593...
- comex 12y agoLast October I tried using that repo to compile Rust to C and it proved to be totally broken (i.e. not Rust's fault). There have been a bunch of commits since then, so maybe it works these days... shouldn't be hard to test. However, don't expect it to generate code that's portable between architectures with different pointer widths.
- haberman 12y ago> However, don't expect it to generate code that's portable between architectures with different pointer widths. That's a limitation I can live with. If my only concession is that I have to have two builds (32/64), and everything else is portable, I'll be a very happy camper.
- 12y ago
- comex 12y agoNot sure why this post doesn't mention it, but for nontrivially sized C APIs, you don't have to convert the function signatures to Rust manually; instead you can use rust-bindgen: https://github.com/crabtw/rust-bindgen https://github.com/crabtw/rust-bindgen (Caveat: I think it would need to be fixed up to avoid unstable APIs in order to run on stable releases of Rust, as opposed to nightlies.)
- kibwen 12y agorust-bindgen is an amazing project, dating all the way back to Rust 0.1 and dutifully updated by various community members throughout more than three years of catastrophically breaking changes. It's an invaluable boon to anyone binding a C API from Rust. > I think it would need to be fixed up to avoid unstable > APIs in order to run on stable releases of Rust, as > opposed to nightlies. The code generated by rust-bindgen won't be using any unstable features, so even if rust-bindgen itself happens to require a nightly build of Rust (which would be less than ideal), it can still be used to generate interfaces that can be used by stable Rust.
- minthd 12y agoInteresting. Can rust-bindgen support object oriented c?
- comex 12y agoNot sure what you mean by "object oriented C". It doesn't support C++ presently (something I'd love to see improved); there are some projects that do Objective-C interop; if you just mean C that uses structs in an OO-like way, it shouldn't be that different from any other C.
- minthd 12y agoYes, when using structs in an OO like way. Does it generate c-style rust wrapper ? or can it generate class-based rust wrapper ,perhaps with some guidance ?
- Ygg2 12y agoThat said, I think Rust probably will need to improve on two fronts: 1) Better binding to C++ API 2) Compiling via MSVC on Windows. Windows is a bit of a red headed step child for lots of projects and Rust won't have that luxury
- steveklabnik 12y ago#1 is very hard. D is the only language I know of that's reasonable about this, and even then, it's not everything. #2 is something we care about, and want to have the option to do in the future.
- fsloth 12y agoYou do realize that 1) can be non-trivial to achieve even if one is using C++ :)
- kibwen 12y agoImproving our Windows story will be an enormous priority post-1.0, as mentioned here: http://internals.rust-lang.org/t/priorities-after-1-0/1901 http://internals.rust-lang.org/t/priorities-after-1-0/1901 It's especially important as Mozilla intends to start shipping minor pieces of Rust code in Firefox this year, but Rust-based components will be relegated to nightly Firefox until Windows support improves. Here's a patch-in-progress for the first Rust code to be integrated into Firefox (Servo's URL parser): https://bugzilla.mozilla.org/show_bug.cgi?id=1151899 https://bugzilla.mozilla.org/show_bug.cgi?id=1151899
- ufo 12y agoI remember hearing somewhere that servo is focusing first on things that are nicer to do in Rust than in C++. Do you know if there is something that makes Rust more suitable for URL parsing than C++?
- jruderman 12y agoServo is trying to answer ambitious questions like "can layout be done as a sequence of top-down and bottom-up parallel tree traversals", "can we GC Rust DOM objects safely", and "how much of a browser engine has to be infected with support for non-UTF-8 strings". Gecko, on the other hand, will gain Rust in modules that can be changed without replacing the entire browser. I'm happy that one of the first will be the code that supports the URLUtils DOM API. When the C++ code was changed from being just "URL parsing" to supporting segment changes, it came to have way more than its fair share of memory safety bugs. It needs a rewrite and it might as well be in Rust.
- andyl 12y agoCan anyone post a link to a RubyGem written with a Rust extension??
- steveklabnik 12y agohttps://github.com/steveklabnik/rust_example https://github.com/steveklabnik/rust_example is one way to do it, albiet the most complex one: a thin C wrapper over the Rust, which is then a C extension for Ruby. Easier ones are using FFI or Fiddle.
- vysakh0 12y agoI think they are referring to this http://blog.skylight.io/bending-the-curve-writing-safe-fast-native-gems-with-rust/ http://blog.skylight.io/bending-the-curve-writing-safe-fast-... in the blogpost
- carllerche 12y agoHere is how we bind the Skylight gem to the Rust bit: https://github.com/skylightio/skylight-ruby/blob/master/ext/skylight_native.c https://github.com/skylightio/skylight-ruby/blob/master/ext/...
- deleted 12y ago[deleted]
- xngzng 12y agoHere's PyCon2015 talk on how to call Rust from Python: https://www.youtube.com/watch?v=3CwJ0MH-4MA https://www.youtube.com/watch?v=3CwJ0MH-4MA
- madez 12y agoHas the call from C to Rust also zero overhead?
- alexcrichton 12y agoIt does indeed! Due to Rust's lack of a garbage collector or runtime altogether, when C calls into Rust there is no overhead. In the example in the blog post [1] you can see that the Rust function has no extra syntactic burden, and the compiler also will not add any form of conversion one way or another. The C code then just emits a direct call to the symbol, so everything is totally free! [1]: http://blog.rust-lang.org/2015/04/24/Rust-Once-Run-Everywhere.html#c-talking-to-rust http://blog.rust-lang.org/2015/04/24/Rust-Once-Run-Everywher...
- cpeterso 12y agoWhat happens if the double_input Rust function is declared extern but not no_mangle? When would you want a mangled extern Rust function?
- alexcrichton 12y agoIf you omit the `#[no_mangle]` definition then the compiler will end up emitting a mangled symbol (e.g. one with a long hash at the end that's hard to guess). Many C APIs take a callback function pointer, which in rust has the type `extern fn()`, and this is the primary use case for an `extern` function defined in Rust which doesn't have `#[no_mangle]` on it.
- lclarkmichalek 12y agoHere's an example of that in a lib I've been working on: https://github.com/bluepeppers/libnetfilter_queue/blob/master/src/queue.rs#L47-L102 https://github.com/bluepeppers/libnetfilter_queue/blob/maste...
- cpeterso 12y agoThanks for the example. What is the advantage of using an unmangled extern fn as a C callback? That the user-friendlier unmangled function name will appear in stack traces or can more safely be called from other Rust code?
- lclarkmichalek 12y agoTrue, though it wouldn't be hard to write a GDB extension to unmangle the names (I know D had this from quite early in it's lifetime). In general, I leave unmangled names to things that are part of the external interface: when unmangling the name, I'm explicitly saying "this symbol's name is part of the contract I have with user of this library".
- steveklabnik 12y ago
- tarblog 12y agoDoes using an FFI call eliminate the possibility of the compiler inlining the call?
- pcwalton 12y agoIn most cases, yes. However, with some work we should be able to allow inlining across language boundaries as long as you're using clang to compile the C and C++. This is because rustc uses the same backend as clang (LLVM).
- kibwen 12y agoThough it may seem like this would be brittle, it's worth mentioning that this is how Servo eventually intends to interoperate with SpiderMonkey, so it will be a strategy that is well-researched and officially supported.
- cpeterso 12y agoSpiderMonkey has an embedding API. Is the overheard between Servo (or Gecko) and SpiderMonkey so great that cross-language inlining is important?
- bzbarsky 12y ago> SpiderMonkey has an embedding API. Yes, but it's a C++ API and includes a bunch of inline bits in the form of RAII classes and so forth. Making those non-inline would be a noticeable performance hit. Similarly, using the non-inline jsapi.h versions of the various inline stuff in jsfriendapi.h would be a noticeable performance hit: those were added for Gecko to use based on performance measurement and profiling. The main place where this inlining is needed is in the DOM bindings, where pretty much anything you're doing is overhead on the path from JS to the actual implementation. This is especially noticeable when the actual implementation is fast (e.g. many getters in the DOM). In modern browsers the binding overhead is on the order of 2 dozen instructions or so. A non-inline function call takes... well, it depends on the ABI. On x86, with cdecl, you only have 3 caller-save registers but have to push all the args on the stack. On x86-64, with the AMD64 ABI (so everything except Windows), there's a ton of caller-save registers that might need to get pushed/popped around the call. Either way, the chance that you add noticeable overhead to an operation that's already <30 instructions is high. And that's if you only have to make one call. If you have to make _several_ such calls as part of the binding code, you're just screwed. And then you start adding APIs that compute and return all sorts of stuff in as single call (see the SpiderMonkey typed array APIs) and other such ugliness.
- hsivonen 12y agoCases with primitive arguments are easy to understand, but I think it would be beneficial for the Rust book to have way more detailed info about working with buffers and heap-allocated structs that the other language holds onto past the foreign call returning. Looking at examples on github (I don't mean the ones from this blog post), one can believe the examples work, but it also looks like there's undocumented knowledge about deep implentation detail involved when e.g. allocating something in one language and then letting the other language hold onto it.
- steveklabnik 12y ago> it would be beneficial for the Rust book to have way more detailed info I was just talking with someone on Twitter about this today, actually. I agree with you 100%, and want to fill that kind of stuff out. You gotta pick priorities, and since we'll have more new people than experienced people at first, I've been focusing on the basics. Now that the language isn't changing all the time, shortly after 1.0, I'll be able to start writing stuff like this, that covers topics in more depth. I also think that libraries will pop up to help with this specific kind of issue, too. We'll see.
- jbooth 12y agoWhile we're making doc requests on this topic, could you address passing function pointers between C/Rust at some point? Sorry if this is already obvious to more experienced Rust users.
- steveklabnik 12y agoI don't think it's obvious at all, and yeah, absolutely.
- Animats 12y agoI'm looking forward to seeing the major security-critical libraries being rewritten in Rust, even if they are then often called from C. Especially OpenSSL/LibreSSL, which is a mess inside, has way too much legacy code, and too many ways to turn encryption off, log keys, or weaken checks.
- le_lenny_face 12y agoAnd I'm NOT looking forward to the inevitable fashion statement where people would say "lol it's written in Rust, that means it's automatically secure!" and security holes get ignored and undetected for ages because of that.
- kibwen 12y agoUp to this point we've been encouraging people to not go wild implementing crypto et al in Rust simply because memory safety is not the only attack vector and we need to carefully consider language extensions and guarantees that would accommodate security-critical code. That said, I do personally think that Rust will one day be an excellent language to take the place of C in implementing fundamental cryptographic libraries. But first we need domain experts to hammer on the language and provide feedback.
- istvan__ 12y agoThis could give a kick to Rust. According to recent news they are going to have a stable syntax + features for a while. http://blog.rust-lang.org/2015/04/03/Rust-1.0-beta.html http://blog.rust-lang.org/2015/04/03/Rust-1.0-beta.html http://blog.rust-lang.org/2014/10/30/Stability.html http://blog.rust-lang.org/2014/10/30/Stability.html
- haberman 12y agoI would love to see this too, but it's not going to happen until Rust is as portable as C, which won't happen until it compiles to C, IMO.
- puetzk 12y agoI suspect you can have this already exists if you want it bat enough, given that rust generates llvm bitcode, and there is an llvm-cbe "target" architecture that just generates C. The results probably won't be well-optimized, though; C isn't actually very portable at this level, there's too much implementation-defined behavior that needs to be taken into account. You'll probably spend as much effort trying to robustly handle the quirks and deficiencies of some obscure platform's compiler than doing an LLVM backend for the processor...
- MichaelGG 12y agoThis ownership stuff is such a blessing and amazing. I'm currently working on a contract where we're trying to fixup some code that crashes under heavy load, as well as troubleshoot some perf issues. The root cause is that it's not clear who actually owns what until when, so in some cases an object is destructed while there's still some code thinking it can use it. Fun. For perf, 30% of the CPU is burned in malloc/free, due to them copying strings around. The system has an arena allocator built in, and many of these strings might be able to go in there. Except no one is sure exactly how long the lifetime is on these things. So everyone copies everything just to be sure. Rust would force addressing this kinda thing up front. (And this project coulda added an refcounted structure or something, but it's a few hundred kloc of C and C++ so...)
- Sanddancer 12y agoHave you considered using something like boehm-gc to profile the app to get a better handle on item lifetimes, leaks, etc? It seems fairly ideal for figuring out where things are going cactus on those leaky strings.
- MichaelGG 12y agoThat's a cool idea. Honestly though a lot of the core is rather grotty plus there's dozens of modules loaded in any given configuration, each which can hook into anything. It's not particularly fun.. (I don't name anything because the software does work for some scenarios and is giving a free basis to what would otherwise be expensive code... And the core devs are nice so I don't want to sound ungrateful or rude.)
- CyberDildonics 12y agoUhh... you do realize C++ std::string has small string optimizations right? That would probably take care of most of the 30%. const string& would probably take care of the rest. No program should have performance problems due to strings.
- Rusky 12y ago
- shmerl 12y agoC bindings are more straightforward. What about C++ however?
- kibwen 12y agoSee elsewhere in this thread for discussion on that.
- eliteraspberrie 12y agoBindings can leverage the ownership and borrowing principles in Rust to codify comments typically found in a C header about how its API should be used. Could the Rust compiler make use of design by contract style annotations in the C header? Maybe it could reason that an unsafe block is in some ways safe. There is a specification language for C called ACSL (which was designed for and is mainly used by Frama-C). Annotations look like: /*@ ensures \result >= 0; assigns \nothing; */ int foo(int x) { if (x < 0) return 0; return x; } I noticed there are annotations for Rust with the LibHoare library (https://github.com/nrc/libhoare https://github.com/nrc/libhoare). The example above might look like: #[postcond="result >= 0"] fn foo(x: int) -> int { if x < 0 { 0 } else { x } } It would be really cool if ACSL could be translated to LibHoare.
- dbaupp 12y agoI don't think it makes sense to build this functionality into the language or compiler directly, at least not at this time. However, it certainly makes a lot of sense to have tooling that uses annotations like that to generate safer Rust bindings than just the raw function declaration.
- zerocored 12y agoPlease become a popular language once 1.0 comes out. Please.
- unfamiliar 12y agoSo it is simple to interface with C, presumably because the C ABI is well established. But it is not a type safe interface, so you have to give it the function signature. It is not so easy to interface with the other languages, you have to do it through the C ABI. Doesn't that suggest a good opportunity for all these actively developed languages (Python, Ruby, Julia, Rust, Go, plus the output of GCC and LLVM) to get together and agree on some kind of type safe ABI for calling functions in a generic way? Even if it is just in the form of some metadata annotation of function signatures to go along with the C ABI?