Gnirehtet rewritten in Rust
21 Sep 2017 (également disponible en français)Several months ago, I introduced Gnirehtet, a reverse tethering tool for Android I wrote in Java.
Since then, I rewrote it in Rust.
And it’s also open source! Download it, plug an Android device, and execute:
./gnirehtet run
(adb must be installed)
Why Rust?
At Genymobile, we wanted Gnirehtet not to require the Java Runtime Environment, so the main requirement was to compile the application to a native executable binary.
Therefore, I first considered rewriting it in C or C++. But at that time (early May), I was interested in learning Rust, after vaguely hearing what it provided, namely:
- memory safety without garbage collection,
- concurrency without data races,
- abstraction without overhead.
However, I had never written a line of Rust code nor heard about Rust ownership, borrowing or lifetimes.
But I am convinced that the best way to learn a programming language is to work full-time on a real project in that language.
I was motivated, so after checking that it could fit our requirements (basically, I wrote a sample using the async I/O library mio, and executed it on both Linux and Windows), I decided to rewrite Gnirehtet in Rust.
Learning Rust
During the rewriting, I devoured successively the Rust book, Rust by example and the Rustonomicon. I learned a lot, and Rust is an awesome language. I now miss many of its features when I work on a C++ project, including:
- advanced type inference,
- enums,
- patterns,
- trait bounds,
Option<T>
(likestd::optional<T>
in C++17, but benefiting from enums and patterns),- hygienic macros,
- the absence of header files,
- the (so simple) build system, and of course
- guaranteed memory safety.
About learning, Paul Graham wrote:
Reading and experience train your model of the world. And even if you forget the experience or what you read, its effect on your model of the world persists. Your mind is like a compiled program you’ve lost the source of. It works, but you don’t know why.
Some of Rust concepts (like lifetimes or move semantics by default) provided a significantly different new training set which definitely affected my model of the world (of programming).
I am not going to present all these features (just click on the links to the documentation if you are interested). Instead, I will try to explain where and why Rust resisted to the design I wanted to implement, and how to rethink the problems within Rust constraints.
The following part requires some basic knowledge of Rust. You may want to skip directly to the stats.
Difficulties
The design of the Java application was pretty effective, so I wanted to reproduce the global architecture in the Rust version (with adaptations to make it more Rust idiomatic if necessary).
But I struggled on the details, especially to make the borrow checker happy. The rules are simple:
First, any borrow must last for a scope no greater than that of the owner. Second, you may have one or the other of these two kinds of borrows, but not both at the same time:
- one or more references (
&T
) to a resource,- exactly one mutable reference (
&mut T
).
However, it took me some time to realize how they conflict with some patterns or principles.
Here are my feedbacks. I selected 4 subjects which are general enough to be independent of this particular project:
- the conflicts with encapsulation;
- the observer pattern;
- how to share mutable data;
- a quick note about annoying compiler limitations.
Encapsulation
The borrowing rules constrain encapsulation. This was the first consequence I realized.
Here is a canonical sample:
We just create a new instance of Data
, then bind mutable references to the
header
and payload
arrays to local variables, through accessors.
However, this does not compile:
$ rustc sample.rs
error[E0499]: cannot borrow `data` as mutable more than once at a time
--> sample.rs:21:19
|
25 | let header = data.header();
| ---- first mutable borrow occurs here
26 | let payload = data.payload();
| ^^^^ second mutable borrow occurs here
27 | }
| - first borrow ends here
The compiler may not assume that header()
and payload()
return references to
disjoint data in the Data
struct. Therefore, each one borrows the whole data
structure. Since the borrowing rules forbid to get two mutables references to
the same resource, it rejects the second call.
Sometimes, we face temporary limitations because the compiler is not smart
enough (yet). This is not the case here: the implementation of header()
might
actually return a reference to payload
, or write to the payload
array,
violating the borrowing rules. And the validity of a method call may not depend
on the method implementation.
To fix the problem, the compiler must be able to know that the local variables
header
and payload
reference disjoint data, for example by accessing
the fields directly:
or by exposing a method providing both references simultaneously:
Similarly, inside a struct implementation, the borrowing rules also prevent factoring code into a private method easily. Consider this (artificial) example:
Here, the buf
field is an array storing some prefix and content contiguously.
We want to factorize the way we retrieve the content
slice, so that
the update_*()
methods are not bothered with the details. Let’s try:
Unfortunately, this does not compile:
error[E0506]: cannot assign to `self.sum` because it is borrowed
--> facto2.rs:11:9
|
10 | let content = self.content();
| ---- borrow of `self.sum` occurs here
11 | self.sum = content.iter().cloned().map(u32::from).sum();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `self.sum` occurs here
error[E0506]: cannot assign to `self.port` because it is borrowed
--> facto2.rs:16:9
|
15 | let content = self.content();
| ---- borrow of `self.port` occurs here
16 | self.port = (content[2] as u16) << 8 & content[3] as u16;
|
As in the previous exemple, retrieving the reference through a method borrows
the whole struct (here, self
).
To workaround the problem, we can explain to the compiler that the fields are disjoint:
This compiles, but totally defeats the purpose of factorization: the caller has to provide the necessary fields.
As an alternative, we can use a macro to inline the code:
But this seems far from ideal.
I think we must just live with it: encapsulation sometimes conflicts with the borrowing rules. After all, this is not so surprising: enforcing the borrowing rules requires to follow every concrete access to resources, while encapsulation aims to abstract them away.
Observer
The observer pattern is useful for registering event listeners on an object.
In some cases, this pattern may not be straightforward to implement in Rust.
For simplicity, let’s consider that the events are u32
values. Here
is a possible implementation:
For convenience, make closures implement our EventListener
trait:
Thus, its usage is simple:
This prints:
notifying...
received [42]
So far, so good.
However, things get a bit more complicated if we want to mutate a state when an event is received. For example, let’s implement a struct storing all the events we received:
To be able to fill this Storage
on each event received, we somehow have to
pass it along with the event listener, which will be stored in the Notifier
.
Therefore, we need a single instance of Storage
to be shared between the
caller code and the Notifier
.
Holding two mutable references to the same object obviously violates the borrowing rules, so we need a reference-counting pointer.
However, such a pointer is read-only, so we also need a RefCell
for interior mutability.
Thus, we will use an instance of Rc<RefCell<Storage>>
. It may seem too
verbose, but using Rc<RefCell<T>>
(or Arc<Mutex<T>>
for thread-safety) is
very common in Rust. And there is worse.
Here is the resulting client code:
That way, the Storage
is correctly mutated from the event listener.
All is not solved, though. In this example, we had access to the
Rc<RefCell<Storage>>
instance. What if we only have access to the Storage
,
e.g. if we want Storage
to register itself from one of its methods, without
requiring the caller to provide the Rc<RefCell<Storage>>
instance?
We need to retrieve the Rc<RefCell<Storage>>
from the Storage
in some way.
To do so, the idea consists in making the Storage
aware of its
reference-counting pointer. Of course, this only makes sense if Storage
is
constructed inside a Rc<RefCell<Storage>>
.
This is exactly what enable_shared_from_this
provides in C++, so we can draw
inspiration from how it works: just store a
Weak<RefCell<…>>
, downgraded from the Rc<RefCell<…>>
, into the structure
itself. That way, we can use it to get a &mut Storage
reference back in the
event listener:
Here is how to use it:
So it is possible to implement the observer pattern in Rust, but this is a bit more challenging than in Java ;-)
When possible, it might be preferable to avoid it.
Mutable data sharing
Mutable references cannot be aliased.
How to share mutable data, then?
We saw that we can use Rc<RefCell<…>>
(or Arc<Mutex<…>>
), that enforces the
borrowing rules at runtime. However, this is not always desirable:
- it forces a new allocation on the heap,
- each access has a runtime cost,
- it always borrows the whole resource.
Alternatively, we could use raw pointers manually inside unsafe code, but then this would be unsafe.
And there is another way, which consists in exposing temporary borrowing views of an object. Let me explain.
In Gnirehtet, a packet contains a reference to the raw data (stored in some buffer elsewhere) along with the IP and TCP/UDP header fields values (parsed from the raw data). We could have used a flat structure to store everything:
The Packet
would provide setters for all the header fields (updating both
the packet fields and the raw data). For example:
But this would be poor design (especially since TCP and UDP header fields are different).
Instead, we would like to extract IP and transport headers to separate structs, managing their own part of the raw data:
You immediately spotted the problem: there are several references to the
same resource, the raw
byte array, at the same time.
Note that splitting the array is not a possibility here, since the raw
slices overlap: we need to write the whole packet at once to the network, so the
raw
array in Packet
must include the headers.
We need a solution compatible with the borrowing rules.
Here is the one I came up with:
- store the header data separately, without the
raw
slices, - create view structs for IP and transport headers, with lifetime bounds,
- expose
Packet
methods returning view instances.
And here is a simplification of the actual implementation:
The setters are implemented on the views, where they hold a mutable reference to the raw array:
That way, the borrowing rules are respected, and the API is elegant:
Compiler limitations
Rust is a young language, and the compiler has some annoying pitfalls.
The worst, in my opinion, is related to non-lexical lifetimes, which leads to unexpected errors:
error[E0499]: cannot borrow `self.vec` as mutable more than once at a time
--> sample.rs:14:9
|
11 | if let Some(x) = self.find(v) {
| ---- first mutable borrow occurs here
...
14 | self.vec.push(v);
| ^^^^^^^^ second mutable borrow occurs here
15 | self.vec.last_mut().unwrap()
16 | }
| - first borrow ends here
Hopefully, it should be fixed soon.
The Impl Trait feature, allowing to return unboxed abstract types from functions, should also improve the experience (there is also an expanded proposal).
The compiler generally produces very helpful error messages. But when it does not, they can be very confusing.
Safety pitfalls
The first chapter of the Rustonomicon says:
Safe Rust is For Reals Totally Safe.
[…]
Safe Rust is the true Rust programming language. If all you do is write Safe Rust, you will never have to worry about type-safety or memory-safety. You will never endure a null or dangling pointer, or any of that Undefined Behavior nonsense.
That’s the goal. And that’s almost true.
Leakpocalypse
In the past, it was possible to write safe-Rust code accessing freed memory.
This “leakpocalypse” led to a clarification of the safety guarantees: not running a destructor is now considered safe. In other words, memory-safety may not rely on RAII anymore (in fact, it never could, but it has been noticed only belatedly).
As a consequence, std::mem::forget
is now safe, and JoinGuard
has been
deprecated and removed from the standard library (it has been moved to a
separate crate).
Other tools relying on RAII (like Vec::drain()
) must take special care to
prevent memory corruption.
Whew, memory-safety is (now) safe.
Undefined infinity
In C and C++, infinite loops without side-effects are undefined behavior. This makes it possible to write programs that unexpectedly disprove Fermat’s Last Theorem.
In practice, the Rust compiler relies on LLVM, which (currently) applies its optimizations assuming that infinite loops without side-effects are undefined behavior. As a consequence, such undefined behaviors also occur in Rust.
Here is a minimal sample to trigger it:
Running without optimizations, it behaves as “expected”:
$ rustc ub.rs && ./ub
^C (infinite loop, interrupt it)
Enabling optimizations makes the program panic:
$ rustc -O ub.rs && ./ub
thread 'main' panicked at 'assertion failed: c.borrow().is_none()', /checkout/src/libstd/sys_common/thread_info.rs:51
note: Run with `RUST_BACKTRACE=1` for a backtrace.
Alternatively, we can produce unexpected results without crashing:
$ rustc ub.rs && ./ub
^C (infinite loop, interrupt it)
But with optimizations:
$ rustc -O ub.rs && ./ub
end
This is a corner case, that will probably be solved in the future. In practice, Rust safety guarantees are pretty strong (at a cost of being constraining).
Segfault
This section has been added after the publication.
There are other sources of undefined behaviors (look at the issues tagged I-unsound).
For instance, casting a float value that cannot fit into the target type is undefined behavior, which can be propagated to trigger a segfault:
rustc -O ub.rs && ./ub
Segmentation fault
Stats
That’s all for my feedbacks about the language itself.
As an appendix, let’s compare the current Java and Rust versions of the relay server.
Number of lines
$ cloc relay-{java,rust}/src
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
Rust 29 687 655 4506
Java 37 726 701 2931
-------------------------------------------------------------------------------
(tests included)
The Rust project is significantly bigger, for several reasons:
- there are many borrowing views classes;
- the Rust version contains its own selector class, wrapping the lower-level
Poll
, while the Java version uses the standardSelector
; - the error handling for command-line parsing is more verbose.
The Java version has more files because the unit tests are separate, while in Rust they are in the same file as the classes they test.
Just for information, here are the results for the Android client:
$ cloc app/src
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
Java 15 198 321 875
XML 6 7 2 76
-------------------------------------------------------------------------------
SUM: 21 205 323 951
-------------------------------------------------------------------------------
Binary size
--------------------------------------------
Java gnirehtet.jar 61K
--------------------------------------------
Rust gnirehtet 3.0M
after "strip -g gnirehtet" 747K
after "strip gnirehtet" 588K
--------------------------------------------
The Java binary itself is far smaller. The comparison is not fair though, since it requires the Java Runtime Environment:
$ du -sh /usr/lib/jvm/java-1.8.0-openjdk-amd64/
156M /usr/lib/jvm/java-1.8.0-openjdk-amd64/
Memory usage
With a single TCP connection opened, here is the memory consumption for the Java relay server:
$ sudo pmap -x $RELAY_JAVA_PID
Kbytes RSS Dirty
total kB 4364052 86148 69316
(output filtered)
And for the Rust relay server:
$ sudo pmap -x $RELAY_RUST_PID
Kbytes RSS Dirty
total kB 19272 2736 640
Look at the RSS value, which indicates the actual memory used.
As expected, the Java version consumes more memory (86Mb) than the Rust one (less than 3Mb). Moreover, its value is unstable due to the allocation of tiny objects and their garbage collection, which also generates more dirty pages. On the contrary, the Rust value is very stable: once the connection is created, there are no memory allocations at all.
CPU usage
To compare CPU usage, here is my scenario: a 500Mb file is hosted by Apache on
my laptop, I start the relay server through perf stat
, then I download the
file from Firefox on Android. As soon as the file is downloaded, I stop the
relay server (Ctrl+C).
Here are the results for the Java version:
$ perf stat -B java -jar gnirehtet.jar relay
Performance counter stats for 'java -jar gnirehtet.jar relay':
11805,458302 task-clock:u (msec) # 0,088 CPUs utilized
0 context-switches:u # 0,000 K/sec
0 cpu-migrations:u # 0,000 K/sec
28 618 page-faults:u # 0,002 M/sec
17 908 360 446 cycles:u # 1,517 GHz
13 944 172 792 stalled-cycles-frontend:u # 77,86% frontend cycles idle
18 437 279 663 instructions:u # 1,03 insn per cycle
# 0,76 stalled cycles per insn
3 088 215 431 branches:u # 261,592 M/sec
70 647 760 branch-misses:u # 2,29% of all branches
133,975117164 seconds time elapsed
And for the Rust version:
$ perf stat -B ./gnirehtet relay
Performance counter stats for 'target/release/gnirehtet relay':
2707,479968 task-clock:u (msec) # 0,020 CPUs utilized
0 context-switches:u # 0,000 K/sec
0 cpu-migrations:u # 0,000 K/sec
1 001 page-faults:u # 0,370 K/sec
1 011 527 340 cycles:u # 0,374 GHz
2 033 810 378 stalled-cycles-frontend:u # 201,06% frontend cycles idle
981 103 003 instructions:u # 0,97 insn per cycle
# 2,07 stalled cycles per insn
98 929 222 branches:u # 36,539 M/sec
3 220 527 branch-misses:u # 3,26% of all branches
133,766035253 seconds time elapsed
I am not an expert in analyzing the results, but as far as I understand from
the task-clock:u
value, the Rust version consumes 4× less CPU-time.
Conclusion
Rewriting Gnirehtet in Rust was an amazing experience, where I learnt a great language and new programming concepts. And now, we get a native application showing better performances.
Happy reverse tethering!
Discuss on reddit and Hacker News.
Actually, in C (unlike C++), such loops are only UB if the loop condition is not a constant expression. However, LLVM fails to implement this exception as is thus breaking some correct C programs. This has been reported against LLVM already more than ten years ago: https://bugs.llvm.org/show_bug.cgi?id=965.