452 points · by yarapavan · 7y ago · 224 comments
At my employer, the number one reason (I'm aware of) to open source our internal software is to solicit collaboration from other companies. Take away collaboration, and it's going to be a harder sell to open source anything.
I agree with A and B, but C just feels like gate-keeping. Open source license do not require collaboration with the original authors. You can freely fork any opensource codebase and modify it as you wish without asking someones permission.
I think the author means: if you're maintaining changes in your fork indefinitely and advertising this fork to others as superior to the original to use or as a canonical place to file issues, you should have a good reason. Communities are valuable; please don't divide them or throw them away lightly. Try working with the original maintainer first.
And what constitutes a good reason?
The epitome of open source is that you don't need to explain of your fork is really superior, the users will come.
Imagine a well-funded startup trying to make a name for themselves decided to fork the top 10 emerging open source projects, put their company name on them, and then spend millions in PR/marketing so that (A) it seems like they invented them, and (B) they fork the community. Are they free to? Is it right? What will it mean for the original authors and experts who created the software?
I happened to be reading this yesterday: dstat is dead. Red Hat decided to rewrite it using pcp, so the original author has given up. https://github.com/dagwieers/dstat/issues/170
Is Red Hat free to? (probably). Is it right? Now that's where I'd want to see a strong reason.
If the author of the original source had an issue with the above scenario, they would've chosen a more restrictive license that didn't make it possible.
Really smart computer nerds emotionally wrapped up in change they aren’t interested in. They know what the future needs! To stay just like yesterday!
Gen X has become the old geezers who want you to stay off their lawn.
Oh what? It may not be super popular like Linux? We all have to work on the same code bases? Individual drive and curiosity verboten! Your one person project won’t satisfy the general user base? You should just focus on computing as we see it.
Who cares. Generate whatever syntax you want. They don’t have to organize around the semantics if they don’t want.
Gimme a break.
So maybe instead of "rewrite it in Rust", the answer is "build a new solution in Rust that meets the needs of a community of people who already use Rust".
I think there are probably three cases here:
(1) You have perfectly good software and your only motivation to rewrite is infatuation with how great Rust seems. In this case, yes, that's unproductive. (Infatuation-driven design is poor engineering and is a fairly widespread problem in the software industry.)
(2) You already have other reasons to want to rewrite (design could be improved, code is in a poor state, etc.), and you're deciding between languages. In that case, a rewrite could be productive even if you didn't use Rust.
(3) You have mature software that appears relatively free of obvious, known bugs, but it's written in an unsafe language, and it would be valuable to have the additional confidence that a safe language could provide. Security-sensitive or other critical applications are where this is most likely to make sense.
at least Rust -> C ffi is zero cost (usually)
It would be wise to ignore the language distraction and remember that most urges to rewrite are just flat out wrong. The standard and well respected advice about rewrites doesn't go out the window just because of a fad language, if anything they apply more strongly.
Much of what people perceive as cruft is most of the actual value-- the stored knowledge from years of experience using the software in practice. Few "clean" programs are actually complete.
But I usually append that quote with "but then again, you're not Tridge" :)
Kernighan and Plauger said "don't patch bad code: rewrite it". That is definitely true. And there's a lot of bad code.
Mature software can have a bunch of hard to fix bugs that you can't motivate anyone to work on any longer. If you want to continue making progress you have to route around the damage somehow.
There is some concept[6] of converting Java to Rust, but it is far from being as useful as c2rust tool. Would be nice to integrate with c2rust somehow, if someone wants to help.
[1] https://github.com/immunant/c2rust
[2] https://c2rust.com/manual/c2rust-refactor/index.html
[3] https://github.com/tectonic-typesetting/tectonic/issues/459
[4] https://github.com/crlf0710/tectonic/tree/oxidize
[1] https://github.com/duneroadrunner/SaferCPlusPlus-AutoTransla...
[2] https://github.com/duneroadrunner/SaferCPlusPlus-AutoTransla...
> However at best, the temptation to RiiR is unproductive
> A much better alternative is to reuse the original library and just publish a safe interface to it.
Just as models are a lower dimensional representation of a more complex problem, [1] I have to re-iterate that there are no truth(ism)s in software and as in all engineering, there are trade offs. RiiR can and often is a valid choice. The author talks about "introducing bugs", under an engineering approach to a rewrite, more like a language-port, rewrites can _find_ a lot of bugs. One such way is as follows.
1. keep the same interface in the new system, client code should work against either system.
2. have a body of integration tests, capture these from the field OR write a small collection of orthogonal tests, somewhere between unit and integration.
3. use the tooling, bindgen, etc and generate as much of the interface programmatically as possible.
4. iterate on the port, doing differential testing against both systems.
Doing a language port is comparable in work to long term maintenance and refactoring of an existing codebase. As the tooling gets better, RiiR will be more of a smooth oxidization.
If you own the C/C++ that could possibly get rewritten, I'd think one needs to rationalize NOT RiiR. Better tooling (IDE, build), perf tooling is improving, low bug count, increased team velocity, build is improved, etc.
But the biggest reason to RiiR is safety. Integrating a body of C/C++ code into your rust codebase introduces a huge amount of unsafe code, much worse than surrounding your entire rust program with unsafe { }.
At least do what is outlined in the article but ALSO compile the native code into Wasm and run it from within a sandbox.
edit, something like a library for reading (parsing) a file format, should absolutely be RiiR or run from a sandbox. Data parsing and memory corruption vulnerabilities are excellent dance partners.
[1] see PCA https://en.wikipedia.org/wiki/Principal_component_analysis
100% agree. We had a C++ service that made heavy use of libcurl. A particular release of libcurl introduced some memory safety problems that caused frequent segfaults for us. These memory safety bugs were eventually fixed in another release, but it scared us enough that we investigated rewriting the service in Rust.
After successful experimentation with some prototypes, we eventually rewrote the service in Rust, auditing the unsafe code in our dependencies (of which there was very little). No segfaults ever since.
Side benefit: Since Rust networking libraries tend to have strong async support, and since some of our C++ libraries performed synchronous networking operations, we saw a big improvement in performance. The number of threads needed dropped by 5x.
This is not a good reason if there are cheaper ways to get safety (at least for existing codebases). Indeed, there are sound static analysis tools (like TrustInSoft) that guarantee no undefined behaviour in C code. Using them is not completely free, and it may even require adding annotations to the code or even changing the code, but it does seem significantly cheaper than a rewrite (in any language). Such sound static analysis tools are already being used for safety-critical systems in C, and I believe they are more popular than a rewrite in Rust in that domain (where there are reasons not to rewrite in Rust other than just cost, though).
> and it's far from clear that fixing all the bugs, or even all the undefined behavior, in an existing C library will be less effort than rewriting it
It's pretty clear to me.
> Consider that one of the worst security bugs in history
I'm not sure what bug you're referring to, but if it's Heartbleed, than that was an undefined behavior bug. Of course, a functional bug can be introduced at any time, including during a rewrite in another language.
Iiuc tools like TrustInSoft are for situations where you need not just safety, but "reliability" (i.e. no crashes, no exceptions). That doesn't really scale so well to larger applications.
TBH I don't see a future where RIIR every piece of software would make sense, and I think you sort of put it in there somewhere in your comments.
But yes I do see that for many it would and for those, RIIR would IMHO be an incremental process of oxidizing your project to the point that there's nothing left but Rust.
Writing something from scratch and waiting for it to finish is the biggest problem we face, cause eventually the will to continue with the effort just dies. But creating a meaningful ground not just some "safer" bindings does help in inviting others to help share the effort as well.
So hopefully people will be smart and identify what they should do for their projects, should it be a rewrite or should it be a new feature that you write in Rust. :)
And no I don't think bindings are the solution to anything, they serve no purpose in Rust community as a long term measure, you shouldn't have to sacrifice safety and/or performance incase of high level language.
It doesn't necessarily have to be Rust, and it's a process that may take decades. But I really do think that absolutely everything should be rewritten in a memory-safe language (i.e. not C/C++).
The vast majority of security issues are either stupid misconfigurations or memory-safety issues. And currently most security initiatives are undermined by the fact that they're resting on insecure foundations. Imagine if our computing platforms were truly secure. It would be a revolution, and IMO it's a revolution that's coming.
That said, I think containing C/C++ to a Wasm sandbox that can be integrated transparently with Rust would be a gigantic win for security, correctness and the Rust ecosystem.
Using standard library types, actually integrating sanitizers into CI, enable bounds checking (even on release builds) and above all avoid C style coding.
Naturally this doesn't work out for third party libraries that one doesn't have control over.
So from a business point of view it boils down how much one is willing to spend re-writing the world vs improving parts of it.
C++/CLI, C++/CX, GC pluggable API introduced in C++11, C++ Builder VCL in ARC mode, Unreal C++ managed classes.
Guess what, we even used to have a famous magazine called "The C/C++ Users Journal".
> at best, the temptation to RiiR is unproductive (unnecessary duplication of effort)
For tiny, mature libraries, this might be true.
But a rewrite in Rust can also vastly improve maintainability. If a library is under heavy maintenance (and will continue to be), your investment in rewriting it is likely to pay dividends by saving developers -- especially ones who are new to the library -- a lot of time.
Yes you could rewrite them in Rust, but considering these are tools which are used all over the ecosystem and have massive momentum behind them, your time would be better spent building cool things on top of existing work than reinventing the wheel and trying to convert the ecosystem to something which will (initially, at least) be an inferior product.
The original statement was deliberately opinionated and extreme, but I still feel like the pragmatic approach of reusing existing libraries instead of rewriting them is the best one for the short/medium term (jury's still out on the long term costs/effects).
But reading code is hard, it's easier to project your sense of confusion onto your predecessor than own it yourself, and once you rewrite the code in Rust and start to understand the true complexity that the previous code had to work around, you'll leave for another job (this time with Rust on your resume).
Sometime I catch them a few weeks before they quit and I get to ask why they developed a low level http server in java interpreting controller code written in javascript that nobody understand but them. "It's much more efficient than using php or nodejs or higher level java" "you benchmarked ?" "I have to go do more knowledge transfer, bye"...
I dont know what I'd do if they were allowed by the company to do Go or Rust :D Guess I'd redo their wheel reinvention in the majority language of the team... increasing the overall constant migration I see again and again...
I wonder if, as a stereotype, it's unique to the software industry.
Doubly true if you're not all-in on one of the major Bigcorp silos (Java, C#).
I occasionally check their LinkedIn and they're still spending 12-15 months every time at companies, being CTO or Big Data Strategist or whatever.
Mostly good experiences when it's a specialist gig that happens to require a specific technology. Like some parts of a stack aren't interchangeable and aren't easy to pick up overnight.
I think I must reject the premise a bit, unless I misunderstand how Rust works.
If you write a safe wrapper around unsafe code, is it not still the case, that if the unsafe code bombs out, it will take the safe Rust down with it, engulfed in shared flames?
(Unless you spawn unsafe code in its separate process or something elaborate like that.)
(Then again, from a practical standpoint the reasoning may be good. Maybe, even likely, the C library is very good and very battle tested. And very likely, my novice would be re-implementation in Rust would not be very good.)
This seems like the cleanest way to move a codebase forward without too much regression work. It reminds me of how TensorFlow 2.0 still contains tf.compat.v1 APIs so devs can write forward-facing code while maintaining existing modules.
You'll need to do this anyway if you want an actual library that can be independently packaged, because that means you have to use the system ABI in the library itself. Rust does not provide a stable ABI.
Do we admit that this is a factor in the decision to rewrite vs. reuse?
Allow me to introduce myself ;) I mostly work on new products and rewriting to me just a waste of time. I am interested in creating features that give actual ROI. The only time I rewrite a piece of code is if said piece presents a major problem (bugs, performance etc)
Wrapping your buggy C library in Rust isn't going to give you the kind of security against malicious data that a rewrite in Rust would give you.
https://medium.com/dwelo-r-d/using-c-libraries-in-rust-13961...
Autoconf creates a portable shell script, right? No need to have it installed just to build the project.
Why they published it like this is beyond me, however. The whole point of autotools is not making your users install them (unlike CMake and virtually every other build system for C there is).
"It" in my post referred to the Rust cargo package in question. The package ships configure.in, but not the generated configure. You do need autoconf for configure.in -> configure. Similarly, it ships Makefile.am, but not the generated Makefile.in for use with configure.
Note how I said "The whole point of autotools is not making your users install them".
I'm just being pedantic. It's a problem...
If you want to natively compile on a fairly recent linux with the common standard libraries autotools works well. Even though autotools was written to work around these differences, in most cases the developer didn't hook into autotools detecting that difference and so it doesn't work.
Did you happen to read the book? We cover strings early because this is a common pain point.
Also, if you have something more detailed than "get strings out of libraries", I can give better advice. It's tough to tell what the actual issue is.
use sha2::{Sha256, Digest};
fn main() {
let mut hasher = Sha256::new();
hasher.input(b"hello world");
let result = hasher.result();
??
}
How do I get a string with the hash value? Which chapter of which book should I read?In this case, the hash ends up being raw bytes. So the question is, what are you trying to do with this hash? Being a bunch of bytes, this may not be valid UTF-8 (and in this case, is not ASCII, let alone UTF-8). One option is to encode to base64:
use sha2::{Sha256, Digest};
use base64;
fn main() {
let mut hasher = Sha256::new();
hasher.input(b"hello world");
let result = hasher.result();
let encoded = base64::encode(&result);
assert_eq!("uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=", encoded);
}
But yeah, you can't exactly "get a string" out of a random bag of bytes unless you know how you want that bag of bytes to be represented, encoding wise. That's not exactly a satisfying answer, but such are strings!What many low-level data formats deal with are raw bytes ("byte strings" in some contexts). The output of a hasher is random binary data.
What most humans are accustomed to are some form of encoding that makes it easier to spell out the octets. Hex and base64 are common. But they are not the native representation that the machine deals with.
With almost everything being explicit in rust you need an explicit conversion from bytes to hex, base64, urlencode or some other format.
Those conversion methods (with their contract often expressed as a separate trait) may be provided by the same crate or you may have to pull them in from a different crate.
A hasher does not need to provide this itself because its output types can be enhanced by foreign traits.
The result of a hash is never a string, so it makes sense that you'd need another step to print it as one.
EDIT: sorry I don't know which docs I was looking at, I can't find it in the current version.
let my_rust_string = str::from_utf8(result).unwarp()
If there is a possibility of an error, (you read it from file, network ...) you can do: let my_rust_string = match str::from_utf8(result) {
Ok(str) => str,
Err(err) => panic!("Invalid utf8: {}", err),
};
Or you can do lossy conversion (will have that question mark on chars that it cant decode) let my_rust_string = String::from_utf8_lossy(result);
edit: Ok so i read sha2 api wrong. result() is raw bytes and result_str() is hex encoded string. Above wont be much use for either. And others have already explained what to use.I just stared programming in rust several months ago, and that was my pain also, since where i live we still have some other encoding in use.
str::from_utf8(result.as_slice())
https://docs.rs/generic-array/0.8.2/generic_array/struct.Gen...
The O'Reilly book is good too.
Nonetheless a cookbook for converting strings for different use cases isn’t a bad idea at all.
https://web.archive.org/web/20191023134247/http://adventures...
What are examples of the unheard of things?
In another language you'd risk having a pointer to invalid memory when the function returns if the pointer escapes the function, and so it is advised to use pointers to objects on the stack sparingly if at all.
In rust, the compiler will statically determine if a pointer to an object on the stack could escape the function, and if so will fail to compile.
At least in the C/C++ world, this is not true. Where possible, we prefer stack allocated objects. Stack allocation is fast and usually gives you better cache performance than heap allocation.
Rust's lifetime/borrow checker provides compiler support for well-established best practices amongst professional C and C++ users.
Just a nitpick, this is only true for non-garbage-collected (or refcounted) languages. :-)
A garbage-collected language wouldn't let you allocate such items on the stack in the first place.
GC languages tend not to let you choose where to allocate in the first place, and have obligatory heap semantics for reference types. Some compilers (including Go and Java, to my knowledge) will attempt to optimize the implementation to stack allocation when possible using escape analysis, but this is less precise, and more opaque, then Rust's allocation. And you won't get feedback if it stops working.
So, by GP's comment of "unheard of (or just plain dangerous)", the "unheard-of" applies to GC languages and "plain dangerous" would apply non-GC languages.
Ummm.... any pointers as to what the author is talking about?
This is how you avoid growing as a programmer.
Our job is not to program crap again and again, it's to deliver some value for the high fees we charge. Rewritting a working library to migrate language is really hard to defend...
You may question the usefulness of having “x but in Rust” and that is fair. However, people keep answering the reasons why you might do something like this and yet like amnesia the same bad opinions come out again next time.
— Sincerely, someone who also ships.
Rewriting in some language is a matter of skill and preference. To even consider a rewrite there should be a rational reason, i.e. it is broken or can't work in the ecosystem.
For fun and learning you can do what you want, of course.
So, an article titled, say, "how not to paint your house" would be expected to outline things to avoid when painting your house, and "how to not paint your house" could just be "go for a bike ride instead."
'How not to x' articles are typically self-deprecating articles that do x, but are critical of how they approached it and lessons learnt
'How to not x' is more explicit, i.e. How to avoid doing x
It also isn't the wording used in the original article title.
I think this kind of title is trying to do exactly that, or at least, that's how I took it.
> It also isn't the wording used in the original article title.
This is a good reason to switch it, for sure. I didn't realize this, if you had led with that, I wouldn't have said anything :)
Actually, this is the case. It describes the bad way (and bad reasons) to rewrite something in Rust.
How to not X = How to avoid doing X
How not to X = The wrong way to do X
...this is tongue-in-cheek comment. I do agree with the author, "rust rewrite" alternative of wrapping c library is way better in many cases for well established or legacy libs. However it depends on the momentum you can bring - as pure rust implementation for widely used areas can benefit from compiler grinding through it. I can see rust written low level libraries used across all high-level languages in the near future.