<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Kamal Marhubi</title>
    <description></description>
    <link>http://kamalmarhubi.com/</link>
    <atom:link href="http://kamalmarhubi.com/blog/feed.xml" rel="self" type="application/rss+xml" />
    <pubDate>Wed, 31 Jan 2018 23:37:20 -0500</pubDate>
    <lastBuildDate>Wed, 31 Jan 2018 23:37:20 -0500</lastBuildDate>
    <generator>Jekyll v2.5.3</generator>
      <item>
        <title>What happened to my hg advent series?</title>

        <pubDate>Sun, 09 Dec 2018 00:00:00 -0500</pubDate>
        <link>http://kamalmarhubi.com/blog/why-no-hg/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/why-no-hg/</guid>
      </item>
      <item>
        <title>hg advent -m '06: debugging hg-git'</title>

        <pubDate>Sun, 09 Dec 2018 00:00:00 -0500</pubDate>
        <link>http://kamalmarhubi.com/blog/hg-git-debug/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/hg-git-debug/</guid>
      </item>
      <item>
        <title>hg advent -m '05: heads and `hg commit --close`'</title>

        <pubDate>Thu, 06 Dec 2018 00:00:00 -0500</pubDate>
        <link>http://kamalmarhubi.com/blog/hg-heads/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/hg-heads/</guid>
      </item>
      <item>
        <title>hg advent -m '04: there is no index'</title>

        <pubDate>Sat, 3 Dec 2018 00:00:00 -0500</pubDate>
        <link>http://kamalmarhubi.com/blog/hg-index/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/hg-index/</guid>
      </item>
      <item>
        <title>hg advent -m '03: revsets!'</title>

        <pubDate>Sat, 3 Dec 2018 00:00:00 -0500</pubDate>
        <link>http://kamalmarhubi.com/blog/hg-revsets/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/hg-revsets/</guid>
      </item>
      <item>
        <title>hg advent -m '02: extensions'</title>

        <pubDate>Sat, 2 Dec 2018 00:00:00 -0500</pubDate>
        <link>http://kamalmarhubi.com/blog/hg-extensions/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/hg-extensions/</guid>
      </item>
      <item>
        <title>hg advent init</title>

        <description>&lt;p&gt;This is the start of a daily series in the run-up to Christmas where I learn mercurial. This first post will be about what's making me want to do this in the first place.</description>
        <pubDate>Sat, 1 Dec 2018 00:00:00 -0500</pubDate>
        <link>http://kamalmarhubi.com/blog/hg-advent/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/hg-advent/</guid>
      </item>
    
      <item>
        <title>Rust should be an excellent open source citizen #rust2018</title>
        <description>&lt;p&gt;Here’s my late &lt;a href=&quot;https://blog.rust-lang.org/2018/01/03/new-years-rust-a-call-for-community-blogposts.html&quot;&gt;#rust2018&lt;/a&gt; post. I contribute code to a lot of
projects in a lot of different languages. I think it’s really important not to
think about Rust in isolation, but in the context of the greater open source
world. Here area few specific ways I think about this:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;ease of contributing to projects in rust&lt;/li&gt;
  &lt;li&gt;interoperability with other languages (both directions)&lt;/li&gt;
  &lt;li&gt;ripgrep should be in debian&lt;/li&gt;
  &lt;li&gt;don’t fracture the ecosystem&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The rest of this post is going through these in turn.&lt;/p&gt;

&lt;h2 id=&quot;rust-projects-should-be-easy-to-contribute-to&quot;&gt;Rust projects should be easy to contribute to&lt;/h2&gt;

&lt;p&gt;I make a fair number of open source contributions, whether to fix small bugs,
or scratch an itch. Sometimes the projects are in languages I don’t know well,
or even at all. As a casual contributor, I want to be able to get in and make
my change with as little incidental difficulty and frustration as possible.&lt;/p&gt;

&lt;p&gt;But it doesn’t always work like that. The language a project is written in is a
huge factor in how easy or hard it is.&lt;/p&gt;

&lt;p&gt;My biggest wish for Rust in 2018 is that &lt;strong&gt;I would like to feel free to write
programs in Rust without worrying that I’m excluding people from contributing&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;I see a few ways that choice of language can affect who can contribute code
changes, and how easily:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;readability&lt;/li&gt;
  &lt;li&gt;writability&lt;/li&gt;
  &lt;li&gt;community coding style&lt;/li&gt;
  &lt;li&gt;tooling&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;readability&quot;&gt;Readability&lt;/h3&gt;

&lt;p&gt;To make a code change, you need to understand what the code is doing. The
language itself plays a big part. For example, Python code is very easy to
read, and Go is almost comically easy to read. It’s great!&lt;/p&gt;

&lt;p&gt;Rust is doing ok here, but there’s room for improvement. The ergonomics work
from 2017 will make a huge difference. It just needs to land! In particular,
&lt;code&gt;impl Trait&lt;/code&gt; and argument lifetimes will cut down on a huge amount of angle
bracket noise, and match default bindings will get rid of most uses of the
&lt;code&gt;ref&lt;/code&gt; keyword, which doesn’t come up anywhere else in the language.&lt;/p&gt;

&lt;p&gt;A core focus of 2017 was ergonomics and I don’t want that to go away.  Rust
should keep pushing on this throughout 2018, and beyond.&lt;/p&gt;

&lt;h3 id=&quot;writability&quot;&gt;Writability&lt;/h3&gt;

&lt;p&gt;If you’re making a small code contribution to a program you use, often you get
started by copy-paste-modify. Ideally the language doesn’t make that too hard.
This is another place where ergonomics are important. Ownership and borrowing
make this inherently harder than in other languages: I don’t know any other
languages where&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;foo(x);
foo(x);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;can be a compiler error!&lt;/p&gt;

&lt;p&gt;The compiler messages keep getting better, and this really does make a
difference.&lt;/p&gt;

&lt;p&gt;Going beyond copy-paste-modify coding, Rust’s syntax has a fair number of
gotchas.  Luckily there’s a bunch of ergonomics improvements that should land
soon. Even as a fairly experienced Rust programmer, I find the “how much
&lt;code&gt;&amp;amp;*[..]&lt;/code&gt; random noise do I need to add to make a thing work?” thing annoying.
I’m &lt;em&gt;really&lt;/em&gt; thankful for the effort that’s being poured into this.&lt;/p&gt;

&lt;p&gt;I can’t wait to be able to stop saying to people, ‘I know it’s bad, but it’s
being worked on’, and start saying ‘have you tried 1.28? All that nonsense is
gone now!’&lt;/p&gt;

&lt;h3 id=&quot;community-coding-style&quot;&gt;Community coding style&lt;/h3&gt;

&lt;p&gt;The kind of code that a language community prefers to write also makes a huge
difference. There was a project I wanted to make a change to, and it happened
to be written in Scala. The community coding style there is heavily slanted
towards highly generic code, even when solving a very specific and concrete
problem. I found it to be enough of an impediment that I never contributed.&lt;/p&gt;

&lt;p&gt;Rust’s expressive type system is responsible for so much of for so much of how
Rust can be low level and high level at the same time. Luckily it’s not quite
expressive enough yet to allow monads to enter normal discourse. :-)&lt;/p&gt;

&lt;p&gt;Most of the Rust projects whose code I’ve looked at have shied away from
complicating things via incidental cleverness. I want the community to keep
writing readable-if-verbose code as the type system learns more tricks.&lt;/p&gt;

&lt;h3 id=&quot;tooling&quot;&gt;Tooling&lt;/h3&gt;

&lt;p&gt;It should be dead simple to clone a project, build it, run its tests, and
modify its dependencies.&lt;/p&gt;

&lt;p&gt;Rust is doing a fantastic job of this: cargo is pretty damned amazing. I’m
struggling to think of a crate I’ve worked that didn’t use the default cargo
workflow for building, testing, and dependency management.&lt;/p&gt;

&lt;p&gt;If you compare the experience to Go, it’s really striking. I actually feel dumb
every time I try to contribute to a Go program.  I’m sure that if you’re
writing Go regularly, GOPATH and the seemingly random mishmash of plain &lt;code&gt;go
build&lt;/code&gt;, Makefiles, and other stuff are all easy to deal with. I’m usually
trying to get in and make a small change, and move on. All that non-uniformity
is a borderline showstopper. And that’s not even thinking about needing to
modify dependencies!  (Incidentally, I’m really excited to see Go making
improvements here this year!)&lt;/p&gt;

&lt;p&gt;If I had to pick one place I’d like to see get better, it’d be in finding the
right crate for the job among all the ones that are out there. The crates.io
search is not really all that great. I know that this is being worked on, and
I’m excited to see what this looks like in a few months.&lt;/p&gt;

&lt;h2 id=&quot;interoperate-well-with-other-languages&quot;&gt;Interoperate well with other languages&lt;/h2&gt;

&lt;p&gt;Rust’s lack of a runtime is a huge strength. It can call into C without
worrying about a GIL, or pinning threads or memory, or anything like that. And
other languages can call into Rust just as easily as into C.&lt;/p&gt;

&lt;p&gt;I want to see Rust really take advantage of this. Let’s avoid rewriting the
world in pure Rust, and instead make using existing C and C++ libraries way
easier. I’d like to see something like the Rust API guidelines, but focused on
FFI wrapping libraries and the question of how to best turn a C API into an
ergonomic and idiomatic Rust one. I want there to be a well-supported way of
handling C dependencies, including being easily able to depend on system
versions.&lt;/p&gt;

&lt;p&gt;In the other direction, there are some &lt;em&gt;really&lt;/em&gt; interesting projects out there
focused on making it easy to write native extensions in Rust. Here I’m thinking
of things like &lt;a href=&quot;https://usehelix.com/&quot;&gt;Helix&lt;/a&gt; for Ruby, &lt;a href=&quot;https://www.neon-bindings.com/&quot;&gt;Neon&lt;/a&gt; for node. It’s just magical that this
is possible:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#[macro_use]                                | $ irb                              
extern crate helix;                         | &amp;gt;&amp;gt; require &quot;console&quot;               
                                            | &amp;gt;&amp;gt; Console.log(&quot;I&#39;m in your Rust&quot;) 
ruby! {                                     | LOG: &quot;I&#39;m in your Rust&quot;            
    class Console {                         |
        def log(string: &amp;amp;str) {             |
            println!(&quot;LOG: {:?}&quot;, string);  |
        }                                   |
    }                                       |
}                                           |
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Rust has a lot to offer as a safe way to enter the world native extensions,
whether for performance, low level capabilities, or just fun. I’d love to see
these projects get more attention!&lt;/p&gt;

&lt;h2 id=&quot;ripgrep-should-be-in-debian&quot;&gt;ripgrep should be in Debian&lt;/h2&gt;

&lt;p&gt;Or your favourite non-bleeding-edge distro. This sounds simple but it’s not.
There’s a lot of work in working out to fit Rust into the Debian packaging
rules. I think a lot of the policy work is done, but the tooling isn’t quite at
the point where ripgrep and all its dependencies can be packaged. The six week
release cycle that allows Rust to get better so quickly also works against
this. As an example, the Firefox nightly PPA I use has had a failing build for
the last week because Firefox now needs Rust 1.23.0 to build. I have no idea
how to reconcile the Rust release cycle with the annual or semiannual release
cycle many distros have, but it’s something the community must figure out.&lt;/p&gt;

&lt;h2 id=&quot;dont-fracture-the-ecosystem&quot;&gt;Don’t fracture the ecosystem&lt;/h2&gt;

&lt;p&gt;The Rust async story is coming along nicely. But the community needs to take
care not to split the crate ecosystem up unnecessarily. For example,
historically Python had Twisted and Tornado that were two quite separate worlds
with a lot of duplicated functionality. And in Scala, there’s the world of
Twitter futures, the world of standard library Futures, and the world of akka.
I think Rust is not at too much risk, but it’s something I worry about a bit.&lt;/p&gt;

&lt;h2 id=&quot;closing&quot;&gt;Closing&lt;/h2&gt;

&lt;p&gt;I think a great way to judge how Rust is doing is to see there be more programs
in Rust that aren’t &lt;em&gt;about&lt;/em&gt; Rust. ripgrep is an inspiring example of taking the
power of Rust, and making a difference to a much wider audience. It’s even
included by default in at least a couple of text editors!&lt;/p&gt;

&lt;p&gt;I’d love to see more of this in 2018.&lt;/p&gt;
</description>
        <pubDate>Wed, 31 Jan 2018 00:00:00 -0500</pubDate>
        <link>http://kamalmarhubi.com/blog/2018/01/31/rust2018/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/2018/01/31/rust2018/</guid>
        
        
      </item>
    
      <item>
        <title>Poking around /usr/lib/git-core</title>
        <description>&lt;p&gt;A somewhat unknown bit of git trivia is that &lt;code&gt;git rebase&lt;/code&gt; is implemented as &lt;a href=&quot;https://github.com/git/git/blob/master/git-rebase.sh&quot;&gt;a ~600 line shell script&lt;/a&gt;.  A few months ago, I did a full-distro upgrade on my machine. I kept working while it updated, and was surprised when &lt;code&gt;git add --patch&lt;/code&gt; failed, because I was using other &lt;code&gt;git&lt;/code&gt; commands just fine. Even weirder, plain &lt;code&gt;git add&lt;/code&gt; worked! The message I got mentioned Perl and .pm files.&lt;/p&gt;

&lt;p&gt;This made me a bit curious to find out what other bits of git were outside the git binary and not in C. Knowing that &lt;code&gt;rebase&lt;/code&gt; was a shell script, and that the convention for external subcommands was &lt;code&gt;git-$SUBCOMMAND&lt;/code&gt;, I could strace git to find out where that script lived:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ strace -fe execve git rebase 2&amp;gt;&amp;amp;1 &amp;gt;/dev/null | grep git-rebase
[pid 21289] execve(&quot;/usr/lib/git-core/git-rebase&quot;, [&quot;git-rebase&quot;], [/* 51 vars */]) = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Ok, so &lt;code&gt;/usr/lib/git-core&lt;/code&gt; is the place to look! How many executables in there?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ find /usr/lib/git-core -type f -executable | wc -l
37
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;How many are shell scripts?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ file /usr/lib/git-core/* | grep &#39;shell script&#39; | wc -l
18
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let’s see which ones!&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ file /usr/lib/git-core/* \
&amp;gt; | grep &#39;shell script&#39; \
&amp;gt; | cut -f1 -d: \
&amp;gt; | xargs basename -a \
&amp;gt; | column                                       
git-gui--askpass        git-filter-branch       git-submodule
git-citool              git-merge-one-file      git-stash
git-gui                 git-merge-resolve       git-rebase
git-difftool--helper    git-request-pull        git-bisect
git-mergetool           git-web--browse         git-quiltimport
git-merge-octopus       git-instaweb            git-subtree
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Some of the surprising ones for me: &lt;code&gt;git submodule&lt;/code&gt;, and &lt;code&gt;git subtree&lt;/code&gt; because they seem ‘important’, as well as &lt;code&gt;git-stash&lt;/code&gt; which seems like a ‘built-in’ facility. Of course, they are all &lt;em&gt;important&lt;/em&gt; and &lt;em&gt;built-in&lt;/em&gt; in that they come with git-core! I think this is mostly a reflection of my programming background: I’d never implement something complex in shell because I just can’t do it quickly enough for it to make any sense.&lt;/p&gt;

&lt;p&gt;How about stats on the types of files?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ find /usr/lib/git-core/ -type f -executable \
&amp;gt; | xargs file \
&amp;gt; | cut -d&#39; &#39; -f 2- \
&amp;gt; | sed &#39;s/^ *//;s/, interp.*//&#39; \
&amp;gt; | sort \
&amp;gt; | uniq -c
     16 ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked
      3 Perl script text executable
     17 POSIX shell script, ASCII text executable
      1 POSIX shell script, ASCII text executable, with very long lines
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We came here curious about &lt;code&gt;git add --patch&lt;/code&gt; and Perl, and here we’ve got 3 Perl scripts. What are they?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ file /usr/lib/git-core/* \
&amp;gt; | grep &#39;shell script&#39; \
&amp;gt; | cut -f1 -d: \
&amp;gt; | xargs basename -a
git-difftool
git-relink
git-add--interactive
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Aha! &lt;code&gt;git-add--interactive&lt;/code&gt; sounds very likely. Of course we could have checked this much earlier on:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ strace -fe execve git add -p 2&amp;gt;&amp;amp;1 &amp;gt;/dev/null | grep add
execve(&quot;/usr/bin/git&quot;, [&quot;git&quot;, &quot;add&quot;, &quot;-p&quot;], [/* 49 vars */]) = 0
[pid 22871] execve(&quot;/usr/lib/git-core/git&quot;, [&quot;git&quot;, &quot;add--interactive&quot;, &quot;--patch&quot;, &quot;--&quot;], [/* 51 vars */]) = 0
[pid 22872] execve(&quot;/usr/lib/git-core/git-add--interactive&quot;, [&quot;git-add--interactive&quot;, &quot;--patch&quot;, &quot;--&quot;], [/* 51 vars */]) = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Proof. :-)&lt;/p&gt;
</description>
        <pubDate>Fri, 07 Oct 2016 15:20:01 -0400</pubDate>
        <link>http://kamalmarhubi.com/blog/2016/10/07/git-core/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/2016/10/07/git-core/</guid>
        
        
      </item>
    
      <item>
        <title>Spying on Android events without modifying source code</title>
        <description>&lt;p&gt;Let’s say you want to intercept events in an Android app, but don’t want to modify your source code. As a simple example, you want to add logging whenever the user clicks on any button in your app. I got a bit curious about whether it was possible so I spent some time last week figuring out how this might work. This was extra fun because I’ve never written and Android app, and it’s been years since I did anything in the Java ecosystem.&lt;/p&gt;

&lt;h2 id=&quot;whats-hard-about-intercepting-events-on-android&quot;&gt;What’s hard about intercepting events on Android?&lt;/h2&gt;

&lt;p&gt;There are a few things going on that make this harder to do on Android than on the web. JavaScript and the DOM let you do all kinds of things at runtime—which is the only time! Adding &lt;code&gt;&amp;lt;script src=&quot;blah.js&quot;&amp;gt;&lt;/code&gt; can pretty much catch anything you want without modifying any other code.&lt;/p&gt;

&lt;p&gt;In Java, once a class is loaded it’s fixed. You can do tricksy things to it via reflection, but that’s all you can do. You can’t get it to call custom code in response to a method call. On the JVM, you can provide a custom class loader and do even trickier things before a class is loaded, including modifying the bytecode. This would allow you to insert the custom code at the start of the method.&lt;/p&gt;

&lt;p&gt;But Android doesn’t run the JVM, and it doesn’t run JVM bytecode. Instead the code is translated to DEX, another bytecode format. In current Android versions, &lt;a href=&quot;http://source.android.com/devices/tech/dalvik/index.html&quot;&gt;even that isn’t what is actually run&lt;/a&gt;. Instead the DEX gets compiled further at install time, this time to native code for the device. This makes the modify-at-load-time approach seem somewhere between daunting and impossible.&lt;/p&gt;

&lt;p&gt;So, runtime modification and instrumentation isn’t going to work. We can drop back to compile-time instrumentation instead. We could modify either the JVM bytecode before DEX translation, or the DEX bytecode. There’s a lot of support for JVM bytecode modification, and JVM bytecode is easier to modify&lt;sup id=&quot;fnref:ft-jvm-easier&quot;&gt;&lt;a href=&quot;#fn:ft-jvm-easier&quot; class=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt; so we’ll go with that.&lt;/p&gt;

&lt;p&gt;As one last thing that makes things more difficult, the base SDK classes are completely off limits. For example, instrumenting the &lt;a href=&quot;https://developer.android.com/reference/android/view/View.html&quot;&gt;base &lt;code&gt;View&lt;/code&gt; class&lt;/a&gt; might be a useful thing to do, but we just can’t. They are preloaded in the &lt;a href=&quot;https://developer.android.com/topic/performance/memory-overview.html#SharingRAM&quot;&gt;zygote&lt;/a&gt;, which is sort of the primordial goop of a process that all apps launch from. This is to speed up app launch, and to save on some memory by allowing all apps to share those pages.&lt;/p&gt;

&lt;h2 id=&quot;lets-modify-the-bytecode&quot;&gt;Let’s modify the bytecode&lt;/h2&gt;

&lt;p&gt;So now we know we want to modify JVM bytecode, let’s actually do it. There are a bunch of libraries that help with Java bytecode instrumentation. I went with &lt;a href=&quot;http://asm.ow2.org/&quot;&gt;ASM&lt;/a&gt; for this experiment because I’d heard of it before.&lt;/p&gt;

&lt;p&gt;We only need to intercept one type of event to prove that this approach works. In this post we’ll just look at spying on clicks. There’s a &lt;a href=&quot;https://developer.android.com/guide/topics/ui/controls/button.html#ClickListener&quot;&gt;&lt;code&gt;View.OnClickListener&lt;/code&gt;&lt;/a&gt; interface that any listener implements. We need to check if a class implements that interface, and if so instrument its &lt;code&gt;onClick(View)&lt;/code&gt; method&lt;sup id=&quot;fnref:ft-onclick&quot;&gt;&lt;a href=&quot;#fn:ft-onclick&quot; class=&quot;footnote&quot;&gt;2&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;

&lt;p&gt;ASM presents a streaming view of the contents of a class, and calls methods on classes you define as it encounters the bits of a class file. For example, it calls &lt;code&gt;visit&lt;/code&gt; with the class name and some other stuff when it starts a new class, and it calls &lt;code&gt;visitMethod&lt;/code&gt; on each method.&lt;/p&gt;

&lt;p&gt;Because we only have this one-way streaming view of a class, we have to we’ll need to check the list of interfaces at the start and track whether we’re meant to do any work in an instance variable.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@Override
public void visit(
    int version,
    int access,
    String name,
    String signature,
    String superName,
    String[] interfaces) {

  // Call down the class visitor chain.
  cv.visit(version, access, name, signature, superName, interfaces);

  shouldInstrumentOnClick =
      Arrays.asList(interfaces).contains(&quot;android/view/View$OnClickListener&quot;);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Later, when we’re inspecting a method, we check to see if its name is &lt;code&gt;onClick&lt;/code&gt;. If so, we make sure to instrument it. The way this works is by returning a modified &lt;code&gt;MethodVisitor&lt;/code&gt; from &lt;code&gt;visitMethod&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@Override
public MethodVisitor visitMethod(
    int access, String name, String desc, String signature, String[] exceptions) {
  // Get a method visitor from further down the class visitor chain.
  MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);

  if (shouldInstrumentOnClick &amp;amp;&amp;amp; name.equals(&quot;onClick&quot;)) {
    // Add our method visitor to the chain.
    mv = new LogClickAdapter(mv);
  }
  return mv;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the part that actually adds the code! We just want to insert some code at the start of the method, which we can do in &lt;code&gt;visitCode&lt;/code&gt; in our &lt;code&gt;MethodVisitor&lt;/code&gt;. ASM calls this library just before it goes through any bytecode instructions, so adding code here puts it at the start of the method. This isn’t the nicest thing to look at, as we’re mirroring the bytecode we’re adding:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@Override
public void visitCode() {
  mv.visitCode();

  mv.visitLdcInsn(&quot;SPY&quot;);
  mv.visitTypeInsn(NEW, &quot;java/lang/StringBuilder&quot;);
  mv.visitInsn(DUP);
  mv.visitMethodInsn(INVOKESPECIAL, &quot;java/lang/StringBuilder&quot;, &quot;&amp;lt;init&amp;gt;&quot;, &quot;()V&quot;, false);
  mv.visitLdcInsn(&quot;saw click on &quot;);
  mv.visitMethodInsn(
      INVOKEVIRTUAL,
      &quot;java/lang/StringBuilder&quot;,
      &quot;append&quot;,
      &quot;(Ljava/lang/String;)Ljava/lang/StringBuilder;&quot;,
      false);
  mv.visitVarInsn(ALOAD, 1);
  mv.visitMethodInsn(
      INVOKEVIRTUAL,
      &quot;java/lang/StringBuilder&quot;,
      &quot;append&quot;,
      &quot;(Ljava/lang/Object;)Ljava/lang/StringBuilder;&quot;,
      false);
  mv.visitMethodInsn(
      INVOKEVIRTUAL, &quot;java/lang/StringBuilder&quot;, &quot;toString&quot;, &quot;()Ljava/lang/String;&quot;, false);
  mv.visitMethodInsn(
      INVOKESTATIC, &quot;android/util/Log&quot;, &quot;d&quot;, &quot;(Ljava/lang/String;Ljava/lang/String;)I&quot;, false);
  mv.visitInsn(POP);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That’s the ASM way to write out the bytecode corresponding to this Java code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Log.d(&quot;SPY&quot;, &quot;saw a click on &quot; + view);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Luckily, there’s a nifty utility called ASMifier which outputs the ASM code necessary to generate a class file. Even if you are familiar with JVM bytecode, the ASMified version isn’t going to be fun to write, so that’s really handy.&lt;/p&gt;

&lt;h2 id=&quot;making-it-super-easy-adding-a-plugin-to-the-build&quot;&gt;Making it super easy: adding a plugin to the build&lt;/h2&gt;

&lt;p&gt;Great! Now we can modify classes to add our custom spying code. But the aim here is to make this require as little modification to the application as possible. Android uses Gradle as its standard app build tool, so we can wrap the whole thing up in a Gradle plugin. This would reduce it down to just adding a couple of lines to the &lt;code&gt;build.gradle&lt;/code&gt; file for the app.&lt;/p&gt;

&lt;p&gt;This actually turned out to be the most time consuming part! I already knew enough about JVM bytecode and compilation to make the ASM part fairly straightforward. All I had to do was learn enough about the ASM API to do what I needed to do. For the plugin, I had to get my head around some Gradle architecture, and the overall Android build system so that I could decide where to slot the instrumentation in.&lt;/p&gt;

&lt;p&gt;In the end, it turned out that the Android build system folks did a great job of providing an API to transform classes before they get compiled to DEX. This is the well-named &lt;a href=&quot;http://google.github.io/android-gradle-dsl/javadoc/current/com/android/build/api/transform/package-summary.html&quot;&gt;Transform API&lt;/a&gt;. After I defined the transform, the plugin’s body was pretty much just a call to &lt;code&gt;registerTransform&lt;/code&gt; on the Android plugin. That handled setting up the Gradle task, its inputs and outputs and whatever else is involved.&lt;/p&gt;

&lt;h2 id=&quot;what-it-looks-like&quot;&gt;What it looks like&lt;/h2&gt;

&lt;p&gt;This isn’t exactly exciting, perhaps unless you’re me and you just got it to work. But here’s 
 &lt;a href=&quot;https://developer.android.com/samples/BorderlessButtons/index.html&quot;&gt;one of the Android samples&lt;/a&gt; with and without instrumentation.&lt;/p&gt;

&lt;h3 id=&quot;without-instrumentation&quot;&gt;Without instrumentation&lt;/h3&gt;

&lt;center&gt;
&lt;video width=&quot;100%&quot; src=&quot;/static/android-no-spy.webm&quot; autoplay=&quot;&quot; loop=&quot;&quot;&gt;&lt;/video&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;

&lt;h3 id=&quot;with-instrumentation&quot;&gt;With instrumentation&lt;/h3&gt;

&lt;p&gt;As I click on the buttons, it logs lines with &lt;code&gt;D/SPY&lt;/code&gt; and details on the thing I clicked on.&lt;/p&gt;

&lt;center&gt;
&lt;video width=&quot;100%&quot; src=&quot;/static/android-with-spy.webm&quot; autoplay=&quot;&quot; loop=&quot;&quot;&gt;&lt;/video&gt;
&lt;/center&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;

&lt;h3 id=&quot;the-diff&quot;&gt;The diff&lt;/h3&gt;

&lt;p&gt;The only differences between the two are in the &lt;code&gt;build.gradle&lt;/code&gt; file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;diff --git a/Application/build.gradle b/Application/build.gradle
index 990c615..8d05e53 100644
--- a/Application/build.gradle
+++ b/Application/build.gradle
@@ -1,15 +1,18 @@
 
 buildscript {
     repositories {
+        flatDir dirs: &quot;/home/kamal/projects/asm/build/libs&quot;
         jcenter()
     }
 
     dependencies {
+        classpath &#39;me:plugin:1&#39;
         classpath &#39;com.android.tools.build:gradle:2.2.0&#39;
     }
 }
 
 apply plugin: &#39;com.android.application&#39;
+apply plugin: &#39;track-plugin&#39;
 
 repositories {
     jcenter()
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;exploring-unfamiliar-ecosystems-can-be-fun&quot;&gt;Exploring unfamiliar ecosystems can be fun&lt;/h2&gt;

&lt;p&gt;I had a bunch of fun doing this. For one thing, spying on programs is generally a fun activity. Especially if they don’t know you’re doing it. I rarely write programs that respond to user input. While I only tested this on a couple of Android samples, I still saw direct feedback from me clicking on things—even if that feedback was just a log line in the Android Studio console.&lt;/p&gt;

&lt;p&gt;It was also rewarding to go from here’s-an-idea-I-have-no-idea-how-to-implement to totally-working-proof-of-concept in just a few days. Even more so because this was an entire code universe I hadn’t really set foot in before. I can write passable Java, but I’ve never touched a Java build system. My experience with Android is limited to having owned two or three Nexus devices over the years.&lt;/p&gt;

&lt;p&gt;This makes me curious about when it’s possible to dive into an unfamiliar area and do something non-trivial in a short period of time. I think there has to be a degree of familiarity with at least some of what you’re trying to do. In this instance, I wasn’t stumbling with Java syntax, and I’d done some stuff with JVM bytecode before. The unfamiliar areas were Android, and the build tooling.&lt;/p&gt;

&lt;p&gt;At the other end, when I first tried writing Rust, I was trying to do something I didn’t know how to do in a language I didn’t know. That turned out to be quite frustrating, and it was hard to make progress. It ended up delaying me learning Rust by a few months, because I gave up on the project and Rust along with it.&lt;/p&gt;

&lt;p&gt;This makes me think there’s an analog of &lt;a href=&quot;http://mcfunley.com/choose-boring-technology&quot;&gt;‘innovation tokens’&lt;/a&gt; at play here. Except instead of optimizing for reliability, we’re optimizing for a balance between challenge and fun. I’m really curious to hear other people’s experiences, so please &lt;a href=&quot;https://twitter.com/kamalmarhubi&quot;&gt;get in touch&lt;/a&gt;!&lt;/p&gt;

&lt;p&gt;&lt;br /&gt;&lt;/p&gt;

&lt;hr /&gt;
&lt;div class=&quot;footnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:ft-jvm-easier&quot;&gt;

      &lt;p&gt;In the JVM’s stack-based bytecode, inserted code just needs to ensure it doesn’t pop anything off the stack, or leave anything on the stack. Otherwise you can more or less insert any code with net-zero stack change. In the register-based DEX bytecode, some instructions can only work with a specific subset of the available registers, so you’ll almost certainly have to move data around and restore it afterwards. &lt;a href=&quot;#fnref:ft-jvm-easier&quot; class=&quot;reversefootnote&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:ft-onclick&quot;&gt;

      &lt;p&gt;Tracking clicks on Android turns out to be fairly complicated. There are a bunch of ways a click handler can be registered. I think the most obvious ones are &lt;code&gt;setOnClickListener&lt;/code&gt;, and setting the name of a method on the &lt;code&gt;Activity&lt;/code&gt; in the the &lt;code&gt;android:onclick&lt;/code&gt; XML attribute. The method I’ll outline only catches the &lt;code&gt;setOnClickListener&lt;/code&gt; ones. The XML attirbutes are a bit trickier as they result in using an &lt;code&gt;OnClickListener&lt;/code&gt; defined in the base SDK’s &lt;code&gt;View&lt;/code&gt; class. That’s not something we can instrument. Instead, the way to handle those is to get them from the XML layout files, and instrument the named methods. &lt;a href=&quot;#fnref:ft-onclick&quot; class=&quot;reversefootnote&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</description>
        <pubDate>Mon, 03 Oct 2016 10:10:46 -0400</pubDate>
        <link>http://kamalmarhubi.com/blog/2016/10/03/android-events/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/2016/10/03/android-events/</guid>
        
        
      </item>
    
      <item>
        <title>Some things I learned about libdwarf</title>
        <description>&lt;p&gt;In the last few days, I got drafted / nerd-sniped into helping Julia Evans on &lt;a href=&quot;http://jvns.ca/blog/2016/06/12/a-weird-system-call-process-vm-readv/&quot;&gt;her Ruby stacktrace spying program&lt;/a&gt;. Specifically, one of the next big things is to read type information out of the Ruby binary so that it’s not hardcoded to work for just one Ruby version.&lt;/p&gt;

&lt;p&gt;Going in, I didn’t know much about DWARF, its data model, or how to access it programmatically. This post is a minidump of things I learned about libdwarf, including reasons I’m probably not going to use it.&lt;/p&gt;

&lt;h2 id=&quot;what-dwarf-is-the-very-very-short-and-incomplete-version&quot;&gt;What DWARF is, the very very short and incomplete version&lt;/h2&gt;

&lt;p&gt;From the &lt;a href=&quot;http://dwarfstd.org/&quot;&gt;DWARF standard’s homepage&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;DWARF is a debugging file format used by many compilers and debuggers to support source level debugging.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here are some of the things stored in DWARF data:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;symbol names, like functions, parameters, variables&lt;/li&gt;
  &lt;li&gt;a way to go from source file lines to instruction addresses and vice versa, for setting breakpoints and stepping through functions&lt;/li&gt;
  &lt;li&gt;a way to find out where data for a variable is at a given point in the program&lt;/li&gt;
  &lt;li&gt;information about the types in a program, including their size and offsets of their fields&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I’m sure there’s lots of other stuff in there too. For the task at hand, I’m mostly interested in the last of these. The Ruby stacktrace program currently works by using some struct definitions from header files from Ruby itself. This ties it to a specific Ruby version. We want to make it work on any Ruby version by looking up the struct definitions in the DWARF data.&lt;/p&gt;

&lt;h2 id=&quot;libdwarf&quot;&gt;libdwarf&lt;/h2&gt;

&lt;p&gt;Linked off the dwarfstd.org site is libdwarf, a C library for reading DWARF.  This is great, because the DWARF format looks pretty complicated, and I definitely don’t want to write a reader from scratch! There’s an &lt;a href=&quot;https://sourceforge.net/p/libdwarf/code/ci/master/tree/dwarfexample/simplereader.c&quot;&gt;example program&lt;/a&gt; included with libdwarf to show you how to read debug info.&lt;/p&gt;

&lt;h2 id=&quot;things-i-found-weird-about-libdwarf&quot;&gt;Things I found weird about libdwarf&lt;/h2&gt;

&lt;p&gt;I started putting together a Rust wrapper for libdwarf, but ended up finding it a little too weird.&lt;/p&gt;

&lt;p&gt;NB: I don’t do much C programming beyond working with Linux system libraries, so these might not actually be weird practices for C libraries. But they were definitely weird for me!&lt;/p&gt;

&lt;h3 id=&quot;memory-management-tied-to-a-specific-libdwarf-session&quot;&gt;Memory management tied to a specific libdwarf session&lt;/h3&gt;

&lt;p&gt;Some libdwarf functions allocate memory for the data they return. The library provides a special &lt;code&gt;dwarf_dealloc&lt;/code&gt; function to free them. So far so good. But the deallocation also takes a handle to the &lt;code&gt;Dwarf_Debug&lt;/code&gt; session that the memory was allocated for. This isn’t too bad: a Rust wrapped object could just hold a handle to the &lt;code&gt;Dwarf_Debug&lt;/code&gt; session so that &lt;code&gt;dwarf_dealloc&lt;/code&gt; can be called in the destructor. There is a small niggle in that the library will deallocate all these objects for you if you call close the &lt;code&gt;Dwarf_Debug&lt;/code&gt; with &lt;code&gt;dwarf_finish&lt;/code&gt;. This can all be handled in a reasonable way from the Rust side by tying the lifetimes of things to the &lt;code&gt;Dwarf_Debug&lt;/code&gt; instance they came from.&lt;/p&gt;

&lt;h3 id=&quot;function-names-increment-with-library-changes&quot;&gt;Function names increment with library changes&lt;/h3&gt;

&lt;p&gt;Here are four function names from libdwarf:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code&gt;dwarf_next_cu_header()&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code&gt;dwarf_next_cu_header_b()&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code&gt;dwarf_next_cu_header_c()&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code&gt;dwarf_next_cu_header_d()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each one except for &lt;code&gt;dwarf_next_cu_header_d()&lt;/code&gt; includes a note like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;It operates exactly like &lt;code&gt;dwarf_next_cu_header_d()&lt;/code&gt; but is missing the &lt;code&gt;header_type&lt;/code&gt; field. This is kept for compatibility. All code using this should be changed to use &lt;code&gt;dwarf_next_cu_header_d()&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I don’t know how to handle compatibility and API evolution in C, but this is definitely the first time I’ve seen something like this! It does mean that code compiled against older versions will continue to work, which is good. But it strikes me as odd overall.&lt;/p&gt;

&lt;h3 id=&quot;error-handling&quot;&gt;Error handling&lt;/h3&gt;

&lt;p&gt;Most libdwarf functions take a &lt;code&gt;Dwarf_Error*&lt;/code&gt; as their last argument. If you pass a non-null pointer, then error data will stored there. If a null pointer is passed, then the library calls &lt;code&gt;abort()&lt;/code&gt; on your behalf instead. Except if you passed an error handler callback when creating the &lt;code&gt;Dwarf_Debug&lt;/code&gt; instance: errors will get passed to your callback. It’s unclear to me if you are meant the &lt;code&gt;dwarf_dealloc&lt;/code&gt; the error your callback gets passed in that case. If the callback returns (rather than exiting the program or throwing the error as an exception), then I think the whole call looks like nothing went wrong.&lt;/p&gt;

&lt;p&gt;Oh and if you do pass a non-null &lt;code&gt;Dwarf_Error*&lt;/code&gt;, you are in charge of freeing the error with &lt;code&gt;dwarf_dealloc&lt;/code&gt;, passing the &lt;code&gt;Dwarf_Debug&lt;/code&gt; instance, as mentioned above. Except if that error happened in the call to &lt;code&gt;dwarf_init&lt;/code&gt;, in which case there is no valid &lt;code&gt;Dwarf_Debug&lt;/code&gt; instance; in that case, you just free it with &lt;code&gt;free()&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&quot;sometimes-stateful-iteration&quot;&gt;Sometimes stateful iteration&lt;/h3&gt;

&lt;p&gt;There are a bunch of functions for iterating through bits and pieces of DWARF data. For some, there is a &lt;code&gt;next&lt;/code&gt; function that takes the current item and gives the next one. Iteration can be started from the beginning by passing in &lt;code&gt;NULL&lt;/code&gt; as the current item. But in one case, the iteration state is stored in the &lt;code&gt;Dwarf_Debug&lt;/code&gt; instance. You must repeatedly call the same function until it returns NULL: here’s no other way to restart the iteration.&lt;/p&gt;

&lt;h2 id=&quot;libdw&quot;&gt;libdw&lt;/h2&gt;

&lt;p&gt;None of those things were too weird in themselves, but taken together I was wondering about alternatives. The alternative I’m looking at right now is libdw from elfutils. At a short glance, it has a more straightforward API. There’s also a potentially useful higher level “frontend library” called libdwfl. I’ll be taking a closer look this week and putting together a rough binding to see how that goes!&lt;/p&gt;
</description>
        <pubDate>Mon, 25 Jul 2016 18:04:02 -0400</pubDate>
        <link>http://kamalmarhubi.com/blog/2016/07/25/some-things-i-learned-about-libdwarf/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/2016/07/25/some-things-i-learned-about-libdwarf/</guid>
        
        
      </item>
    
      <item>
        <title>Things you could do with the Rust AST</title>
        <description>&lt;p&gt;Lately I’ve been contributing to &lt;a href=&quot;https://github.com/rust-lang-nursery/rustfmt&quot;&gt;rustfmt&lt;/a&gt;, which is a tool for formatting Rust code. Right now, it formats entire files, which is great if you keep your entire project formatted by rustfmt. If you’re adding code to an existing unrustfmted project, using rustfmt leads to big diffs where most of the changes are just formatting. These can be really annoying to review, so the feature I’m working on is to allow it to format just parts of files. Then you could just reformat the parts you actually changed, making things much nicer for whoever is reviewing the change.&lt;/p&gt;

&lt;p&gt;Working on rustfmt has meant getting a bit of familiarity with Rust’s abstract syntax tree (AST), which is how the rustc compiler represents source code. The AST has nodes to represent each expression, statement, function, module, and all the other bits of syntax that make up a Rust program.
It’s been interesting and kind of cool to work with, and I wanted to share a bit!&lt;/p&gt;

&lt;h2 id=&quot;libsyntax-and-syntexsyntax&quot;&gt;libsyntax and syntex_syntax&lt;/h2&gt;

&lt;p&gt;The Rust compiler’s own parsing code is in a library called libsyntax. Sadly for programs that aren’t rustc, this is a private library inside the compiler source repository. If you’re willing to use the nightly compiler, there are some incantations that will tell rustc to let you use these internal libraries, but it’s not really encouraged. The Rust folks want to be able to make changes as they keep working on making Rust better, and not have to worry about breaking outside projects.&lt;/p&gt;

&lt;p&gt;But someone maintains a copy in Crates.io called &lt;a href=&quot;https://crates.io/crates/syntex_syntax&quot;&gt;syntex_syntax&lt;/a&gt;, with modifications to build with stable Rust. It’s part of a suite of tools for generating Rust code, initially created for &lt;a href=&quot;https://github.com/serde-rs/serde&quot;&gt;a serialization framework&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The upshot of this is that we can just add the line&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;syntex_syntax = &quot;0.33&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;to our &lt;code&gt;Cargo.toml&lt;/code&gt; file, and then we can parse Rust code in our programs!&lt;/p&gt;

&lt;h2 id=&quot;a-small-example-of-working-with-the-ast&quot;&gt;A small example of working with the AST&lt;/h2&gt;

&lt;p&gt;To get an idea of what working with the AST looks like, let’s look at a small example: printing the number of arguments for each function in a file.&lt;/p&gt;

&lt;p&gt;syntex_syntax has a &lt;code&gt;Visitor&lt;/code&gt; trait you can implement to walk an AST. The default implementation just walks the whole tree and doesn’t do anything else. To write a custom visitor, you can implement the &lt;code&gt;visit&lt;/code&gt; function for the node type you’re interested in, and leave the rest out. If you’re more used to Java-esque type systems, you can imagine inheriting from a base &lt;code&gt;DefaultVisitor&lt;/code&gt; class, and overriding the functions relating to the syntactic elements you are interested in.&lt;/p&gt;

&lt;p&gt;For our example, we override the implementation for &lt;code&gt;visit_fn&lt;/code&gt; to store the funciton name and number of arguments in a hashmap. The &lt;a href=&quot;https://github.com/kamalmarhubi/syntex-syntax-example&quot;&gt;full code is up on GitHub&lt;/a&gt;, but here are the important parts:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;struct CountFnArgs&amp;lt;&#39;a&amp;gt; {
    arg_counts: HashMap&amp;lt;String, usize&amp;gt;,
    // The codemap is necessary to go from a `Span` to actual line &amp;amp; column
    // numbers for closures.
    codemap: &amp;amp;&#39;a CodeMap,
}

impl&amp;lt;&#39;v, &#39;a&amp;gt; Visitor&amp;lt;&#39;v&amp;gt; for CountFnArgs&amp;lt;&#39;a&amp;gt; {
    fn visit_fn(&amp;amp;mut self,
                fn_kind: FnKind&amp;lt;&#39;v&amp;gt;,
                fn_decl: &amp;amp;&#39;v ast::FnDecl,
                block: &amp;amp;&#39;v ast::Block,
                span: Span,
                _id: ast::NodeId) {
        let fn_name = match fn_kind {
            FnKind::ItemFn(id, _, _, _, _, _) |
            FnKind::Method(id, _, _) =&amp;gt; id.name.as_str().to_string(),
            FnKind::Closure =&amp;gt; format!(&quot;&amp;lt;closure at {}&amp;gt;&quot;, self.format_span(span)),
        };

        self.arg_counts.insert(fn_name, fn_decl.inputs.len());

        // Continue walking the rest of the funciton so we pick up any functions
        // or closures defined in its body.
        visit::walk_fn(self, fn_kind, fn_decl, block, span);
    }
}

fn count_fn_args(krate: &amp;amp;ast::Crate, codemap: &amp;amp;CodeMap) -&amp;gt; HashMap&amp;lt;String, usize&amp;gt; {
    let mut visitor = CountFnArgs {
        arg_counts: HashMap::new(),
        codemap: codemap,
    };
    visitor.visit_mod(&amp;amp;krate.module, krate.span, 0);

    visitor.arg_counts
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Rust’s pattern matching really shines when working with ASTs. You can get a small glimpse of it here: we match on the &lt;code&gt;FnKind&lt;/code&gt; to see if the function is a method, a free function (&lt;code&gt;ItemFn&lt;/code&gt;), or a closure. In the first two cases, we just pull out the function’s name; in the third we get the source location to identify it better.&lt;/p&gt;

&lt;p&gt;Here’s the output for our little program running on its own source:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;FUNCTION                         ARGS
&amp;lt;closure at 40:19-40:39&amp;gt;         2
count_fn_args                    2
format_loc                       1
format_span                      2
main                             0
parse                            2
visit_fn                         6
visit_mac                        2
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Not bad!&lt;/p&gt;

&lt;h2 id=&quot;things-you-can-do-with-an-ast&quot;&gt;Things you can do with an AST&lt;/h2&gt;

&lt;p&gt;Being able to programmatically parse and work with source code opens up all kinds of cool possibilities. Here are a few.&lt;/p&gt;

&lt;h3 id=&quot;format-rust-code&quot;&gt;Format Rust code!&lt;/h3&gt;

&lt;p&gt;As I kind of mentioned at the start of this post, rustfmt uses the AST to format code. First it parses a file into an AST. Then it walks the tree, recursively printing each node according to a bunch of formatting fules. The &lt;a href=&quot;https://github.com/rust-lang-nursery/rustfmt/blob/master/Design.md#operate-on-the-ast&quot;&gt;design document&lt;/a&gt; gives bit more background on the approach, and why rustfmt works the way it does.&lt;/p&gt;

&lt;h3 id=&quot;throughly-test-c-apis&quot;&gt;Throughly test C APIs&lt;/h3&gt;

&lt;p&gt;The &lt;a href=&quot;https://github.com/rust-lang/libc&quot;&gt;libc crate&lt;/a&gt; is full of function declarations, struct definitions, and constants for working with system libraries. It has a really cool and thorough test suite that makes sure all the items match what’s in the system C headers. It works by parsing the Rust source, and &lt;em&gt;generating C code&lt;/em&gt; where it tests for equality of constants and matching type signatures and so on. It then generates some Rust code that calls the generated C code to check everything. So much code generation!&lt;/p&gt;

&lt;p&gt;Here’s a snippet of the generated C code to give you an idea of what it’s like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static int __test_const_O_RDONLY_val = O_RDONLY;
int* __test_const_O_RDONLY(void) {
    return &amp;amp;__test_const_O_RDONLY_val;
}


static int __test_const_O_WRONLY_val = O_WRONLY;
int* __test_const_O_WRONLY(void) {
    return &amp;amp;__test_const_O_WRONLY_val;
}


static int __test_const_O_RDWR_val = O_RDWR;
int* __test_const_O_RDWR(void) {
    return &amp;amp;__test_const_O_RDWR_val;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and it goes on and on and on for over 10,000 lines! The result is that the definitions in libc can be pretty safely relied on to match the definitions on the platform you’re working with, which is really great for doing systems programming (&lt;a href=&quot;http://kamalmarhubi.com/blog/2016/04/13/rust-nix-easier-unix-systems-programming-3/&quot;&gt;one of my favourite things&lt;/a&gt;).&lt;/p&gt;

&lt;h3 id=&quot;other-things-you-could-do&quot;&gt;Other things you could do!&lt;/h3&gt;

&lt;p&gt;There are all kinds of other things we can do! For example, it should be possible to build a syntax-aware find-and-replace tool to make some refactorings easier. I’m imagining something like &lt;a href=&quot;https://github.com/facebook/jscodeshift&quot;&gt;FaceBook’s jscodeshift tool for JavaScript&lt;/a&gt;, or their &lt;a href=&quot;https://github.com/facebook/pfff/wiki/Spatch&quot;&gt;spatch&lt;/a&gt; for PHP and some other languages. This would be great for situations like where you just changed the type of the third argument of that function from &lt;code&gt;String&lt;/code&gt; to &lt;code&gt;&amp;amp;str&lt;/code&gt; (string slice) and now you have to change all the call sites everywhere to add an &lt;code&gt;&amp;amp;&lt;/code&gt; to take a reference.&lt;/p&gt;

&lt;p&gt;If we’re willing to go a bit deeper into compiler internals—and require nighty Rust to build our project—we can also make tools that use type information. There’s no reason something like &lt;a href=&quot;https://www.haskell.org/hoogle/&quot;&gt;Hoogle&lt;/a&gt; couldn’t exist for Rust. Hoogle was amazing back when I used to write Haskell. You search by &lt;em&gt;type signature&lt;/em&gt;. It’s kind of magical to be able to say &lt;a href=&quot;https://www.haskell.org/hoogle/?hoogle=%5Ba%5D+-%3E+Int&quot;&gt;“I have a a list and I want an int”&lt;/a&gt; and it would have the &lt;code&gt;length&lt;/code&gt; function at the top of the results page.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/mozilla/dxr&quot;&gt;DXR&lt;/a&gt; is an example of an exisiting project using type information in Rust. It’s an indexing engine and web interface with fancy cross referencing of source code. As an example, you can &lt;a href=&quot;https://dxr.mozilla.org/rustfmt/source/src/visitor.rs#133&quot;&gt;browse things around the &lt;code&gt;visit_fn&lt;/code&gt; function in rustfmt&lt;/a&gt;. It’s really cool! This kind of interwingly source browsing can be really really powerful for understanding a new codebase.&lt;/p&gt;

&lt;p&gt;I really love tools like these that make developers’ lives easier. If you have any ideas for Rust, or examples from other languages to “borrow”, please send them my way!&lt;/p&gt;

&lt;p&gt;&lt;br /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;small&gt;&lt;em&gt;Thanks to Julia Evans for feedback on this post, and for suggesting I write it in the first place!&lt;/em&gt;&lt;/small&gt;&lt;/p&gt;
</description>
        <pubDate>Thu, 02 Jun 2016 06:47:58 -0400</pubDate>
        <link>http://kamalmarhubi.com/blog/2016/06/02/playing-with-the-rust-ast/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/2016/06/02/playing-with-the-rust-ast/</guid>
        
        
      </item>
    
      <item>
        <title>Segfaults are our friends and teachers</title>
        <description>&lt;p&gt;This afternoon, I got a segmentation fault in a Rust program, and was confused. This is Rust, I shouldn’t get segfaults! I quickly checked the couple of places I used &lt;code&gt;unsafe&lt;/code&gt;, and they were either calling C functions (and checking the errors), or telling the compiler not to initialize some memory because I was going to write into it unconditionally before reading from it.&lt;/p&gt;

&lt;p&gt;So, everything should be fine, right?&lt;/p&gt;

&lt;p&gt;Evidently not:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ cargo build --quiet
$ target/debug/kern-value 1
Segmentation fault
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;ok-but-what-is-a-segfault&quot;&gt;ok, but what is a segfault?&lt;/h2&gt;

&lt;p&gt;If you’ve written some C, you’ve almost certainly seen a segmentation fault at some point. I spent a long time thinking of it as a ‘thing that happens when you use pointers wrong in C’. That’s mostly true, but a segmentation fault actually has a very specific meaning. You get one when a process tries to access memory in a way that it’s not allowed to, or accessing invalid memory.&lt;/p&gt;

&lt;p&gt;Here’s an example of a really simple program that will segfault:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ cat segfault.c
#include &amp;lt;stdio.h&amp;gt;

int main(void) {
    char *uninitialized;
    printf(&quot;%c&quot;, *uninitialized);

    return 0;
}
$ gcc segfault.c
$ ./a.out
Segmentation fault
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This program segfaults because the entire stack is set to &lt;code&gt;0&lt;/code&gt; at program start. This includes the &lt;code&gt;uninitialized&lt;/code&gt; pointer, which will be a null pointer, pointing to &lt;code&gt;0x0&lt;/code&gt;. When the program tries to print the value it points to, it attempts to read from the null address. That address is invalid, and that’s why we get a segmentation fault.&lt;/p&gt;

&lt;p&gt;Segmentation faults are raised by the memory management unit (MMU), which is a piece of hardware! Sections of memory can have different access permissions on them: read, write, and execute. Operating systems use this to isolate processes, and to protect kernel memory from being written to by user code.&lt;/p&gt;

&lt;p&gt;If a process tries to write to read-only memory, say, or execute non-executable memory, then the MMU hardware tells the kernel there was a segmentation fault. The kernel delivers the news to the process as a signal: &lt;code&gt;SIGSEGV&lt;/code&gt;. By default, that terminates the process.&lt;/p&gt;

&lt;h2 id=&quot;how-we-got-the-segfault&quot;&gt;how we got the segfault&lt;/h2&gt;

&lt;p&gt;Some context: I’m playing around with reading and writing to pipes with large buffers. I’d previously been setting the pipe size to 1 MB, which is the maximum an unprivileged process can set it to on my machine:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ cat /proc/sys/fs/pipe-max-size
1048576
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;My code had a constant &lt;code&gt;PIPE_SIZE&lt;/code&gt; for the size of the pipe. I was &lt;em&gt;also&lt;/em&gt; using it as the size of a stack-allocated buffer. For my experiments, I’d just changed that constant from 1 MB to 16 MB to test bigger pipes when running as root.&lt;/p&gt;

&lt;p&gt;Realising this this set off something in the back of my mind: I vaguely remembered that stacks on Linux default to 8MB. Could the segfault be from going past the stack limit?&lt;/p&gt;

&lt;p&gt;I switched to C to verify it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ cat -n test-stack.c
     1  #include &amp;lt;stdio.h&amp;gt;
     2
     3  #define BUF_SIZE (16*1024*1024)
     4
     5  int main(void) {
     6      char buf[BUF_SIZE];
     7      printf(&quot;%lu\n&quot;, sizeof(buf));
     8
     9      return 0;
    10  }
$ gcc -Wall -Wextra -Werror test-stack.c
$ ./a.out
Segmentation fault
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Aha! A pretty minimal C program that has the same result. This program allocates a 16 MB array on the stack, and then prints its size. Except it segfaults instead. With the &lt;code&gt;BUF_SIZE&lt;/code&gt; set to 8 KB less than 8 MB, everything works. With it set to 8 MB, it segfaults.&lt;sup id=&quot;fnref:why-8-mb&quot;&gt;&lt;a href=&quot;#fn:why-8-mb&quot; class=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt; Hypothesis confirmed!&lt;sup id=&quot;fnref:why-rust-ok&quot;&gt;&lt;a href=&quot;#fn:why-rust-ok&quot; class=&quot;footnote&quot;&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;h2 id=&quot;seeing-which-instruction-failed&quot;&gt;seeing which instruction failed&lt;/h2&gt;

&lt;p&gt;I wanted to get an idea of exactly &lt;em&gt;when&lt;/em&gt; the segfault happened, so I ran it under gdb:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ gcc -g -Wall -Wextra -Werror test-stack.c
$ gdb -silent a.out
Reading symbols from a.out...done.
(gdb) run
Starting program: /tmp/a.out

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400520 in main () at test-stack.c:7
7               printf(&quot;%lu\n&quot;, sizeof(buf));
(gdb) backtrace
#0  0x0000000000400520 in main () at test-stack.c:7
(gdb) disassemble
Dump of assembler code for function main:
   0x0000000000400506 &amp;lt;+0&amp;gt;:     push   %rbp
   0x0000000000400507 &amp;lt;+1&amp;gt;:     mov    %rsp,%rbp
   0x000000000040050a &amp;lt;+4&amp;gt;:     sub    $0x1000000,%rsp
   0x0000000000400511 &amp;lt;+11&amp;gt;:    mov    $0x1000000,%esi
   0x0000000000400516 &amp;lt;+16&amp;gt;:    mov    $0x4005b4,%edi
   0x000000000040051b &amp;lt;+21&amp;gt;:    mov    $0x0,%eax
=&amp;gt; 0x0000000000400520 &amp;lt;+26&amp;gt;:    callq  0x4003e0 &amp;lt;printf@plt&amp;gt;
   0x0000000000400525 &amp;lt;+31&amp;gt;:    mov    $0x0,%eax
   0x000000000040052a &amp;lt;+36&amp;gt;:    leaveq
   0x000000000040052b &amp;lt;+37&amp;gt;:    retq
End of assembler dump.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So the failure was on the call to &lt;code&gt;printf&lt;/code&gt;. &lt;code&gt;0x1000000&lt;/code&gt; is 16 MB, the size of the buffer. The &lt;code&gt;sub    $0x1000000,%rsp&lt;/code&gt; instruction is modifying the stack pointer register &lt;code&gt;%rsp&lt;/code&gt; to make space for the buffer. When we get to the &lt;code&gt;callq&lt;/code&gt; instruction, things exploded!&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;callq&lt;/code&gt; instruction on x86 first pushes the return address onto the stack, then jumps to the called function. The return address is the current value instruction pointer register &lt;code&gt;%ip&lt;/code&gt;, and is where the &lt;code&gt;ret&lt;/code&gt; instruction in &lt;code&gt;printf&lt;/code&gt; will jump back to. The segfault happens at this point: the CPU attempts to store the return address somewhere outside of the region of memory that’s set aside for the stack, and boom!&lt;/p&gt;

&lt;h2 id=&quot;luck-and-guard-pages&quot;&gt;luck and guard pages&lt;/h2&gt;

&lt;p&gt;I think we’re actually kind of lucky to get a segfault. It’s quite possible the bit of memory that’s a few megabytes past our stack &lt;em&gt;was&lt;/em&gt; writeable by our process. We’d then go happily corrupting whatever memory was there and probably all kinds of bad things would happen. Segmentation faults are actually our friends!&lt;/p&gt;

&lt;p&gt;Modern compilers have stack protection features that help detect overflows. I’m &lt;em&gt;very&lt;/em&gt; hazy on the details, but I think they include setting some pages of memory just after the stack to be read only. These are called guard pages. Attempts to write there would result in a segmentation fault. This helps catch stack overflow attempts that involve marching off the end of the stack. However, writing 8 MB after the end of the stack is beyond the guard pages, so we &lt;em&gt;could&lt;/em&gt; have ended up in writeable memory.&lt;/p&gt;

&lt;h2 id=&quot;setting-stack-size-limits-in-the-shell-ulimit&quot;&gt;setting stack size limits in the shell: ulimit&lt;/h2&gt;

&lt;p&gt;I took this as an opportunity to Learn. I wanted to make this program run without changing its source. At first I thought I could set the stack size with compiler options, but some searching revealed this wasn’t true on Linux. It turns out you can set it with the &lt;code&gt;ulimit&lt;/code&gt; shell built-in&lt;sup id=&quot;fnref:why-builtin&quot;&gt;&lt;a href=&quot;#fn:why-builtin&quot; class=&quot;footnote&quot;&gt;3&lt;/a&gt;&lt;/sup&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ ulimit --soft --stack-size 32768
$ ./a.out
16777216
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Success, and without changing the source &lt;em&gt;or&lt;/em&gt; the binary! The &lt;code&gt;--stack-size&lt;/code&gt; flag says we’re setting the stack size to 32768 KB or 32 MB. The &lt;code&gt;--soft&lt;/code&gt; flag says to set the soft limit. I’ll just paste from my &lt;code&gt;man ulimit&lt;/code&gt; on my system to explain the difference between hard and soft limits—the &lt;code&gt;-S&lt;/code&gt; flag is short for &lt;code&gt;--soft&lt;/code&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;A hard limit can only be decreased. Once it is set it cannot be increased; a soft limit may be increased up to the value of the hard limit. If neither &lt;code&gt;-H&lt;/code&gt; nor &lt;code&gt;-S&lt;/code&gt; is specified, both the soft and hard limits are updated when assigning a new limit value, and the soft limit is used when reporting the current value.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;setting-stack-size-limits-from-inside-your-program-setrlimit2&quot;&gt;setting stack size limits from inside your program: setrlimit(2)&lt;/h2&gt;

&lt;p&gt;If you use a lot of stack, it’s not great to force the user to run &lt;code&gt;ulimit&lt;/code&gt; before running your program. Instead, you can set it yourself using the &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/setrlimit.html&quot;&gt;&lt;code&gt;setrlimit(2)&lt;/code&gt;&lt;/a&gt; system call. Here’s proof it works:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ cat -n test-stack.c
     1  #include &amp;lt;errno.h&amp;gt;
     2  #include &amp;lt;stdio.h&amp;gt;
     3  #include &amp;lt;sys/resource.h&amp;gt;
     4
     5  #define BUF_SIZE (16*1024*1024)
     6
     7  void run(void) {
     8      char buf[BUF_SIZE];
     9      printf(&quot;%lu\n&quot;, sizeof(buf));
    10  }
    11
    12  int main(void) {
    13      struct rlimit stack_limit = {
    14          .rlim_cur = 2 * BUF_SIZE,
    15          .rlim_max = RLIM_INFINITY,
    16      };
    17
    18      if (setrlimit(RLIMIT_STACK, &amp;amp;stack_limit)) {
    19          perror(&quot;setrlimit failed&quot;);
    20          return 1;
    21      }
    22
    23      run();
    24
    25      return 0;
    26  }
$ gcc -Wall -Wextra -Werror test-stack.c
$ ulimit -Ss 8192
$ ./a.out
16777216
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A fun note: we had to put the buffer in a separate function. Otherwise the stack pointer would be adjusted before the call to &lt;code&gt;setrlimit&lt;/code&gt;, and then &lt;em&gt;that&lt;/em&gt; call would result in a segfault! This way the stack adjustment happens after calling &lt;code&gt;setrlimit&lt;/code&gt;, and everything works out.&lt;/p&gt;

&lt;p&gt;Allocating lots of stack space in main isn’t a great idea anyway, since you limit what’s available for the rest of your program. A static buffer would probably be better for this program; for others a heap buffer would work better.&lt;/p&gt;

&lt;h2 id=&quot;diving-into-the-depths-for-fun-and-learning&quot;&gt;diving into the depths for fun and learning&lt;/h2&gt;

&lt;p&gt;I had a fun hour or two investigating this. It’s not always possible to take the time in the moment, but it’s really rewarding when you can. I only vaguely knew about the &lt;code&gt;ulimit&lt;/code&gt; command, and didn’t know anything at all about &lt;code&gt;setrlimit(2)&lt;/code&gt;. Since I’ve been programming in languages that output native code a bunch lately, I’ve also wanted to learn more about object file formats, linkers, in-process memory layout, and more. Learning a bit more about stack guard pages is a great step in that direction!&lt;/p&gt;

&lt;p&gt;&lt;br /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;small&gt;&lt;em&gt;Thanks to Julia Evans for feedback on this post.&lt;/em&gt;&lt;/small&gt;&lt;/p&gt;
&lt;div class=&quot;footnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:why-8-mb&quot;&gt;

      &lt;p&gt;Curiously, I found that if I had a buffer size of even 1 byte over (8 MB - 8 KB), I still got the segfault. I’m not yet sure what’s going on there! &lt;a href=&quot;#fnref:why-8-mb&quot; class=&quot;reversefootnote&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:why-rust-ok&quot;&gt;

      &lt;p&gt;Rust really likes to tout its memory safety. This seems like it should mean no segmentation faults, which is why I was confused at getting one. There’s &lt;a href=&quot;http://doc.rust-lang.org/reference.html#behavior-considered-undefined&quot;&gt;a very specific set of behaviors&lt;/a&gt; that aren’t allowed in Rust programs. The Rust program got a segmentation fault because it attempted to write to inaccessible memory, but only through the stack pointer. None of the undefined behaviors disallow this, which I think is why it’s ok for this Rust program to segfault. &lt;a href=&quot;#fnref:why-rust-ok&quot; class=&quot;reversefootnote&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:why-builtin&quot;&gt;

      &lt;p&gt;&lt;code&gt;ulimit&lt;/code&gt; must be a shell built-in and not an executable file because it sets a property of the shell’s process. Other fun examples include setting the working directory (&lt;code&gt;cd&lt;/code&gt;), and setting environment variables (&lt;code&gt;set -x&lt;/code&gt; in bash). These were some fun things I found out when &lt;a href=&quot;https://github.com/kamalmarhubi/shell-workshop&quot;&gt;building a shell&lt;/a&gt;, which is a totally worthwhile and fun exercise! &lt;a href=&quot;#fnref:why-builtin&quot; class=&quot;reversefootnote&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</description>
        <pubDate>Mon, 25 Apr 2016 16:47:14 -0400</pubDate>
        <link>http://kamalmarhubi.com/blog/2016/04/25/segfaults-are-our-friends-and-teachers/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/2016/04/25/segfaults-are-our-friends-and-teachers/</guid>
        
        
      </item>
    
      <item>
        <title>100:10:1 update 7</title>
        <description>&lt;p&gt;It’s been a month since the last update, which is definitely too long.
Here we go!&lt;/p&gt;

&lt;h2 id=&quot;projects-i-worked-since-last-update&quot;&gt;projects I worked since last update&lt;/h2&gt;

&lt;h3 id=&quot;cargo-fmt-diff&quot;&gt;cargo fmt-diff&lt;/h3&gt;

&lt;p&gt;After weeks of being “almost there”, I finally tidied up my initial work
into &lt;a href=&quot;https://github.com/rust-lang-nursery/rustfmt/pull/959&quot;&gt;a pull request&lt;/a&gt;! The pull request and commit
messages are good if you want to see details of what I did. The tl;dr is
that there is a &lt;code&gt;--experimental-file-lines&lt;/code&gt; flag that allows you to
specify &lt;code&gt;FILE:RANGE,RANGE,...&lt;/code&gt; to limit formatting to specific lines. It
only formats statements for now though!&lt;/p&gt;

&lt;p&gt;I had to do a bit of redesigning of my initial approach. I had been
assuming each run of the formatting function would affect only specific
files. However, by default it formats reachable files in the same crate.
This made me change the field on the configuration object from a set of
lines for a single file to a map from file names to line sets.&lt;/p&gt;

&lt;p&gt;There’s still some more refactoring work to put the line checks in the
right place, as well as making it handle more than just statements.
I wanted to get feedback on it before going further, since it’s already
a &lt;code&gt;+704 −131&lt;/code&gt; change. I was hoping it’d fall in at closer to &lt;code&gt;+400&lt;/code&gt; net.
Some of the surplus comes from including a few refactorings that &lt;em&gt;could&lt;/em&gt;
have been split out, but that I think make most sense in context of this
PR.&lt;/p&gt;

&lt;h3 id=&quot;silly-key-value-store&quot;&gt;silly key-value store&lt;/h3&gt;

&lt;p&gt;I did some experiments which resulted in the OOM killer going on a rampage
on my laptop. This was fun!&lt;/p&gt;

&lt;blockquote class=&quot;twitter-tweet&quot; data-lang=&quot;en&quot;&gt;&lt;p lang=&quot;en&quot; dir=&quot;ltr&quot;&gt;oh that was cool! I just got the OOM killer to kill stuff because I tried to fill 4GB of pipe buffers on system with 4GB RAM. still running!&lt;/p&gt;&amp;mdash; Kamal Marhubi (@kamalmarhubi) &lt;a href=&quot;https://twitter.com/kamalmarhubi/status/720386837953404928&quot;&gt;April 13, 2016&lt;/a&gt;&lt;/blockquote&gt;
&lt;script async=&quot;&quot; src=&quot;//platform.twitter.com/widgets.js&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;

&lt;p&gt;This is the project I’m expecting to work on most this week. There will
probably be a blog post or two as a result, and hopefully an exciting
update next time!&lt;/p&gt;

&lt;h2 id=&quot;projects-i-didnt-work-on&quot;&gt;projects I didn’t work on&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;tufcrates&lt;/li&gt;
  &lt;li&gt;containy-thing&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Mon, 25 Apr 2016 00:00:00 -0400</pubDate>
        <link>http://kamalmarhubi.com/blog/2016/04/25/100-10-1-update-7/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/2016/04/25/100-10-1-update-7/</guid>
        
        
      </item>
    
      <item>
        <title>Rust + nix = easier unix systems programming &lt;3</title>
        <description>&lt;p&gt;Lately I’m writing lots of &lt;a href=&quot;https://www.rust-lang.org/&quot;&gt;Rust&lt;/a&gt;, and I’m particularly interested in systems programming on unix. I’ve been using and contributing to a library called &lt;a href=&quot;https://github.com/nix-rust/nix&quot;&gt;nix&lt;/a&gt;&lt;sup id=&quot;fnref:not-that-nix&quot;&gt;&lt;a href=&quot;#fn:not-that-nix&quot; class=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;, whose mission is to provide ‘Rust friendly bindings to *nix APIs’.&lt;/p&gt;

&lt;p&gt;In this blog post, I hope to convince you that you might want to reach for Rust and nix the next time you need to do some unix systems programming, especially if you aren’t fluent in C. It’s no harder to write, you won’t have to write more code, and it makes it much easier to avoid a few classes of mistakes.&lt;/p&gt;

&lt;h2 id=&quot;first-off-what-is-systems-programming&quot;&gt;First off, what is systems programming?&lt;/h2&gt;

&lt;p&gt;The term systems programming can mean all sorts of things, and depends a lot on context and who you’re talking to. For this blog post, here’s my incredibly precise definition:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Systems programming is programming where you spend more time reading man pages than reading the internet.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;(As an aside, this means that systems programming is programming you can happily do on the subway if you happen to be in one of those places that doesn’t have connectivity in the tunnels, like New York. I definitely did this when taking the Q train back from the &lt;a href=&quot;https://www.recurse.com/&quot;&gt;Recurse Center&lt;/a&gt; late at night!)&lt;/p&gt;

&lt;p&gt;Here are a few examples of things that fall under this definition:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;managing processes (eg, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html&quot;&gt;&lt;code&gt;fork(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html&quot;&gt;&lt;code&gt;execve(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/waitpid.html&quot;&gt;&lt;code&gt;waitpid(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/signal.html&quot;&gt;&lt;code&gt;signal(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/kill.html&quot;&gt;&lt;code&gt;kill(2)&lt;/code&gt;&lt;/a&gt;)&lt;/li&gt;
  &lt;li&gt;working with files (eg, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html&quot;&gt;&lt;code&gt;open(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html&quot;&gt;&lt;code&gt;ftruncate(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/unlink.html&quot;&gt;&lt;code&gt;unlink(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html&quot;&gt;&lt;code&gt;read(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html&quot;&gt;&lt;code&gt;write(2)&lt;/code&gt;&lt;/a&gt;)&lt;/li&gt;
  &lt;li&gt;network programming (eg, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/socket.html&quot;&gt;&lt;code&gt;socket(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/setsockopt.html&quot;&gt;&lt;code&gt;setsockopt(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/listen.html&quot;&gt;&lt;code&gt;listen(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://man7.org/linux/man-pages/man2/sendfile.2.html&quot;&gt;&lt;code&gt;sendfile(2)&lt;/code&gt;&lt;/a&gt;)&lt;/li&gt;
  &lt;li&gt;Linux containers (eg, &lt;a href=&quot;http://man7.org/linux/man-pages/man2/clone.2.html&quot;&gt;&lt;code&gt;clone(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://man7.org/linux/man-pages/man2/unshare.2.html&quot;&gt;&lt;code&gt;unshare(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://man7.org/linux/man-pages/man2/pivot_root.2.html&quot;&gt;&lt;code&gt;pivot_root(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://man7.org/linux/man-pages/man2/mount.2.html&quot;&gt;&lt;code&gt;mount(2)&lt;/code&gt;&lt;/a&gt;)&lt;/li&gt;
  &lt;li&gt;interacting with hardware (eg, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/ioctl.html&quot;&gt;&lt;code&gt;ioctl(2)&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html&quot;&gt;&lt;code&gt;mmap(2)&lt;/code&gt;&lt;/a&gt;)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;fork2-and-kill2-an-example-of-how-badly-things-can-go&quot;&gt;fork(2) and kill(2): an example of how badly things can go&lt;/h2&gt;

&lt;p&gt;Here’s a fairly innocuous looking C program that uses &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html&quot;&gt;&lt;code&gt;fork(2)&lt;/code&gt;&lt;/a&gt; and &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/kill.html&quot;&gt;&lt;code&gt;kill(2)&lt;/code&gt;&lt;/a&gt; to spawn and kill a process:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &amp;lt;signal.h&amp;gt;
#include &amp;lt;unistd.h&amp;gt;

int main(void) {
        pid_t child = fork();
        if (child) {  // in parent
                sleep(5);
                kill(child, SIGKILL);
        } else {  // in child
                for (;;);  // loop until killed
        }

        return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This program compiles with no errors or warnings, not even with &lt;code&gt;-Wall -Wextra -Werror&lt;/code&gt;. I recommend you don’t run it though, and here’s why. From the POSIX specification for &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html&quot;&gt;&lt;code&gt;fork(2)&lt;/code&gt;&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Upon successful completion, fork() shall return 0 to the child process and shall return the process ID of the child process to the parent process. Both processes shall continue to execute from the fork() function. Otherwise, -1 shall be returned to the parent process, no child process shall be created, and errno shall be set to indicate the error.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;And from the specification for &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/kill.html&quot;&gt;&lt;code&gt;kill(2)&lt;/code&gt;&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;If pid is -1, &lt;strong&gt;sig shall be sent to all processes&lt;/strong&gt; (excluding an unspecified set of system processes) for which the process has permission to send that signal.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Putting the two together, that program could really ruin our day. If the &lt;code&gt;fork()&lt;/code&gt; call fails for some reason&lt;sup id=&quot;fnref:fork-failures&quot;&gt;&lt;a href=&quot;#fn:fork-failures&quot; class=&quot;footnote&quot;&gt;2&lt;/a&gt;&lt;/sup&gt;, we store &lt;code&gt;-1&lt;/code&gt; in &lt;code&gt;child&lt;/code&gt;. Later, we call &lt;code&gt;kill(-1, SIGKILL)&lt;/code&gt;, which tries to kill all our processes, and most likely hose our login. Not even &lt;code&gt;screen&lt;/code&gt; or &lt;code&gt;tmux&lt;/code&gt; will save us!&lt;sup id=&quot;fnref:rachel-fork-citation&quot;&gt;&lt;a href=&quot;#fn:rachel-fork-citation&quot; class=&quot;footnote&quot;&gt;3&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;It’s a pretty scary failure mode, and neither the library nor the language do anything at all to prevent us from having a terrible day.&lt;/p&gt;

&lt;h2 id=&quot;why-fork-and-kill-go-so-terribly-together&quot;&gt;Why fork and kill go so terribly together&lt;/h2&gt;

&lt;p&gt;I believe the main issue here is that the C library forces us to try and stick several meanings into one value. For &lt;code&gt;fork(2)&lt;/code&gt;, the return value is conveying &lt;em&gt;three&lt;/em&gt; different things all at once:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;whether or not the call succeeded (return value &lt;code&gt;-1&lt;/code&gt;)&lt;/li&gt;
  &lt;li&gt;if it succeeded, whether or not we are in the child (return value &lt;code&gt;0&lt;/code&gt;)&lt;/li&gt;
  &lt;li&gt;if we are the parent, what the child’s PID is (strictly positive return value)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That’s a lot of information for one poor little &lt;code&gt;pid_t&lt;/code&gt;—usually a 32-bit integer—to convey!&lt;/p&gt;

&lt;p&gt;In the case of &lt;code&gt;kill(2)&lt;/code&gt;, the &lt;code&gt;pid&lt;/code&gt; parameter conflates several different behaviors. From &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/kill.html#tag_16_286_03&quot;&gt;the POSIX specification&lt;/a&gt; again:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;ul&gt;
    &lt;li&gt;If pid is greater than 0, sig shall be sent to the process whose process ID is equal to pid.&lt;/li&gt;
    &lt;li&gt;If pid is 0, sig shall be sent to all processes (excluding an unspecified set of system processes) whose process group ID is equal to the process group ID of the sender, and for which the process has permission to send a signal.&lt;/li&gt;
    &lt;li&gt;If pid is -1, sig shall be sent to all processes (excluding an unspecified set of system processes) for which the process has permission to send that signal.&lt;/li&gt;
    &lt;li&gt;If pid is negative, but not -1, sig shall be sent to all processes (excluding an unspecified set of system processes) whose process group ID is equal to the absolute value of pid, and for which the process has permission to send a signal.&lt;/li&gt;
  &lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;Some extra badness comes from C’s way of treating all non-zero integral values as truthy in conditions, so our &lt;code&gt;if (child)&lt;/code&gt; check takes the true branch even when &lt;code&gt;fork()&lt;/code&gt; failed and returned &lt;code&gt;-1&lt;/code&gt;!&lt;/p&gt;

&lt;p&gt;The combination of &lt;code&gt;-1&lt;/code&gt; as failure value from &lt;code&gt;fork(2)&lt;/code&gt; and as a special value to &lt;code&gt;kill(2)&lt;/code&gt; is unfortunate and makes this example especially bad. But other functions treat a &lt;code&gt;pid&lt;/code&gt; value of &lt;code&gt;-1&lt;/code&gt; in a special way too, so even if we didn’t call &lt;code&gt;kill(2)&lt;/code&gt; this could still turn out badly. For example, if we called &lt;a href=&quot;http://pubs.opengroup.org/onlinepubs/9699919799/functions/waitpid.html&quot;&gt;&lt;code&gt;waitpid(2)&lt;/code&gt;&lt;/a&gt; instead, we’d end up either blocking execution waiting for termination of a child that doesn’t exist, or reaping a child that some other thread is waiting for. While they won’t ruin our system in quite the same way as &lt;code&gt;kill(-1, sig)&lt;/code&gt;, neither are failure modes that should be so easy to end up in!&lt;/p&gt;

&lt;h2 id=&quot;how-nix-and-rust-help-with-the-fork--kill-problem&quot;&gt;How nix and Rust help with the fork / kill problem&lt;/h2&gt;

&lt;p&gt;Here’s what this example would look like in Rust + nix:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;extern crate nix;

use nix::sys::signal::*;
use nix::unistd::*;

fn main() {
    match fork().expect(&quot;fork failed&quot;) {
        ForkResult::Parent{ child } =&amp;gt; {
            sleep(5);
            kill(child, SIGKILL).expect(&quot;kill failed&quot;);
        }
        ForkResult::Child =&amp;gt; {
            loop {}  // until killed
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We’ll go over it in detail below, but for now we’ll just notice that the structure and length are really similar to the C version. But it’s much safer, and won’t go on a process killing rampage!&lt;/p&gt;

&lt;p&gt;The nix wrapper for &lt;code&gt;fork(2)&lt;/code&gt; does two things to make it much easier to avoid accidentally killing all our processes. Both use &lt;a href=&quot;https://doc.rust-lang.org/stable/book/enums.html&quot;&gt;Rust’s enums&lt;/a&gt;, which are effectively tagged unions.&lt;/p&gt;

&lt;h3 id=&quot;separating-the-parent-and-child-returns-with-an-enum&quot;&gt;Separating the parent and child returns with an enum&lt;/h3&gt;

&lt;p&gt;For the success case, nix’s &lt;code&gt;fork()&lt;/code&gt; makes a really great use of a custom enum. Instead of returning just a plain &lt;code&gt;pid_t&lt;/code&gt;, it returns a &lt;code&gt;ForkResult&lt;/code&gt; type. The &lt;code&gt;ForkResult&lt;/code&gt; enum looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;pub enum ForkResult {
    Parent {
        child: pid_t
    },
    Child
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can read this definition as saying that a &lt;code&gt;ForkResult&lt;/code&gt; is either &lt;code&gt;Parent&lt;/code&gt; or &lt;code&gt;Child&lt;/code&gt;. If it’s &lt;code&gt;Parent&lt;/code&gt; then it contains a &lt;code&gt;pid_t&lt;/code&gt; value named &lt;code&gt;child&lt;/code&gt;, while if it’s &lt;code&gt;Child&lt;/code&gt; then it contains no value. Rust has &lt;a href=&quot;https://doc.rust-lang.org/stable/book/match.html#matching-on-enums&quot;&gt;a pattern matching syntax&lt;/a&gt; for easily checking which variant an enum value is. If we have a variable &lt;code&gt;fork_result&lt;/code&gt;, we can pattern match on it like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    match fork_result {
        ForkResult::Parent { child } =&amp;gt; {
            // stuff to do if we&#39;re in the parent
        }
        ForkResult::Child =&amp;gt; {
            // stuff do do if we&#39;re in the child
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id=&quot;separating-the-success-and-failure-cases-with-result&quot;&gt;Separating the success and failure cases with Result&lt;/h3&gt;

&lt;p&gt;The other big thing Rust does to help is having a &lt;a href=&quot;http://doc.rust-lang.org/std/result/enum.Result.html&quot;&gt;&lt;code&gt;Result&lt;/code&gt;&lt;/a&gt; type that’s used to represent the return from functions that can fail. Similar to how &lt;code&gt;ForkResult&lt;/code&gt; separated the parent and child cases, the built-in &lt;code&gt;Result&lt;/code&gt; type separates successes from failures. It looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#[must_use]
pub enum Result&amp;lt;T, E&amp;gt; {
    Ok(T),
    Err(E),
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can read this definition as saying that a &lt;code&gt;Result&amp;lt;T, E&amp;gt;&lt;/code&gt; is either &lt;code&gt;Ok&lt;/code&gt; to indicate success, or &lt;code&gt;Err&lt;/code&gt; to indicate failure. If it’s &lt;code&gt;Ok&lt;/code&gt;, it contains a &lt;code&gt;T&lt;/code&gt; value, while if it’s &lt;code&gt;Err&lt;/code&gt; it contains an &lt;code&gt;E&lt;/code&gt; value. For a specific case, you’d set &lt;code&gt;T&lt;/code&gt; to be the successful return type, and &lt;code&gt;E&lt;/code&gt; to be the type of error that can happen. And the &lt;code&gt;#[must_use]&lt;/code&gt; attribute tells the compiler to warn us if we ignore a &lt;code&gt;Result&lt;/code&gt; return value.&lt;sup id=&quot;fnref:compiler-warned&quot;&gt;&lt;a href=&quot;#fn:compiler-warned&quot; class=&quot;footnote&quot;&gt;4&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;For nix’s &lt;code&gt;fork()&lt;/code&gt; function, the return type is &lt;code&gt;Result&amp;lt;ForkResult, Errno&amp;gt;&lt;/code&gt;: our happy case is the &lt;code&gt;ForkResult&lt;/code&gt; type we talked about earlier. Our sad case is an &lt;code&gt;Errno&lt;/code&gt; value, which is simply an integer the OS uses to tell us why our call failed.&lt;/p&gt;

&lt;p&gt;We &lt;em&gt;could&lt;/em&gt; match on the return value of &lt;code&gt;fork()&lt;/code&gt; directly like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    match fork() {
        Ok(ForkResult::Parent { child }) =&amp;gt; {
            // stuff to do if we&#39;re in the parent
        }
        Ok(ForkResult::Child) =&amp;gt; {
            // stuff do do if we&#39;re in the child
        }
        Err(errno) =&amp;gt; {
            // stuff to do if there was an error
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However, Rust has some idioms useful for dealing with &lt;code&gt;Result&lt;/code&gt; values that make code a little bit tidier. The one we’ll rely on in this post is &lt;a href=&quot;http://doc.rust-lang.org/std/result/enum.Result.html#method.expect&quot;&gt;&lt;code&gt;expect()&lt;/code&gt;&lt;/a&gt;. It unwraps the success value from an &lt;code&gt;Ok&lt;/code&gt; result, or panics with a given error message if called on an &lt;code&gt;Err&lt;/code&gt; result. It’s a handy way to just crash the program with a semi-useful error message when an error happens. That’s pretty much perfect for prototyping, or for quick and dirty programs.&lt;/p&gt;

&lt;p&gt;With &lt;code&gt;expect()&lt;/code&gt;, our match only has to consider the success cases:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    match fork().expect(&quot;fork failed&quot;) {
        ForkResult::Parent { child } =&amp;gt; {
            // stuff to do if we&#39;re in the parent
        }
        ForkResult::Child =&amp;gt; {
            // stuff do do if we&#39;re in the child
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If &lt;code&gt;fork()&lt;/code&gt; failed, our program will exit with an error message that looks something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;thread &#39;&amp;lt;main&amp;gt;&#39; panicked at &#39;fork failed: ENOMEM&#39;, ../src/libcore/result.rs:709
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This tells us what failed, and why. For our tiny program, that’s enough to see what went wrong. For a more complicated program, we could ask for a backtrace by setting &lt;code&gt;RUST_BACKTRACE=1&lt;/code&gt; in the environment.&lt;/p&gt;

&lt;p&gt;If you want to find out more about error handling in Rust, The Rust book has &lt;a href=&quot;https://doc.rust-lang.org/stable/book/error-handling.html&quot;&gt;a chapter&lt;/a&gt; with a fantastic and detailed look at different approaches. I highly recommend reading it!&lt;/p&gt;

&lt;h2 id=&quot;join-us&quot;&gt;Join us!&lt;/h2&gt;

&lt;p&gt;I’ve really been enjoying doing this kind of programming in Rust. So much that I became a maintainer for nix! We’ve been exploring a few ways of using Rust’s features to help make systems programming safer and easier to not mess up.&lt;/p&gt;

&lt;p&gt;If this kind of thing interests you too, come help out! We have &lt;a href=&quot;https://github.com/nix-rust/nix/issues?q=is%3Aissue+is%3Aopen+label%3AE-good-first-bug&quot;&gt;good first bug label&lt;/a&gt; on our issue tracker, as well as a &lt;a href=&quot;https://github.com/nix-rust/nix/issues?q=is%3Aissue+is%3Aopen+label%3AE-mentor&quot;&gt;mentored bug label&lt;/a&gt;. We’d love to have your input and your help!&lt;/p&gt;

&lt;p&gt;&lt;br /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;small&gt;&lt;em&gt;Thanks to Ant6n Dubrau, Bryan Newbold, Dan Luu, Julia Evans, and Mathieu Guay-Paquet for feedback on drafts of this post.&lt;/em&gt;&lt;/small&gt;&lt;/p&gt;
&lt;div class=&quot;footnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:not-that-nix&quot;&gt;

      &lt;p&gt;Confusingly for some, the library has nothing to do with the &lt;a href=&quot;https://nixos.org/nix/&quot;&gt;Nix package manager&lt;/a&gt;, &lt;a href=&quot;https://nixos.org/&quot;&gt;NixOS&lt;/a&gt;, or any of the related projects. &lt;a href=&quot;#fnref:not-that-nix&quot; class=&quot;reversefootnote&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:fork-failures&quot;&gt;

      &lt;p&gt;There are two main ways &lt;code&gt;fork(2)&lt;/code&gt; can fail:&lt;/p&gt;

      &lt;ul&gt;
        &lt;li&gt;the system is out of memory&lt;/li&gt;
        &lt;li&gt;we’re at our process limit&lt;/li&gt;
      &lt;/ul&gt;

      &lt;p&gt;Either of these can happen, and code should be ready if they do! &lt;a href=&quot;#fnref:fork-failures&quot; class=&quot;reversefootnote&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:rachel-fork-citation&quot;&gt;

      &lt;p&gt;I first came across this issue in &lt;a href=&quot;http://rachelbythebay.com/w/2014/08/19/fork/&quot;&gt;a post on Rachel by the Bay&lt;/a&gt;—which incidentally is a great blog! &lt;a href=&quot;#fnref:rachel-fork-citation&quot; class=&quot;reversefootnote&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:compiler-warned&quot;&gt;

      &lt;p&gt;Fun fact: when I first wrote the example for this post, I forgot to check the return value from &lt;code&gt;kill()&lt;/code&gt;. Woops! But the compiler helpfully warned me that I was ignoring a &lt;code&gt;Result&lt;/code&gt; return value:&lt;/p&gt;

      &lt;pre&gt;&lt;code&gt;$ cargo build
   Compiling fork-rs v0.1.0 (file:///home/kamal/projects/talks/2016-03-24-rc/fork-rs)
src/main.rs:13:13: 13:34 warning: unused result which must be used, #[warn(unused_must_use)] on by default
src/main.rs:13             kill(child, SIGKILL);
                           ^~~~~~~~~~~~~~~~~~~~~
&lt;/code&gt;&lt;/pre&gt;
      &lt;p&gt;&lt;a href=&quot;#fnref:compiler-warned&quot; class=&quot;reversefootnote&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</description>
        <pubDate>Wed, 13 Apr 2016 00:00:00 -0400</pubDate>
        <link>http://kamalmarhubi.com/blog/2016/04/13/rust-nix-easier-unix-systems-programming-3/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/2016/04/13/rust-nix-easier-unix-systems-programming-3/</guid>
        
        
      </item>
    
      <item>
        <title>100:10:1 update 6</title>
        <description>&lt;p&gt;I said &lt;a href=&quot;/blog/2016/03/14/100-10-1-update-5/&quot;&gt;last time&lt;/a&gt; that I should keep a log; I didn’t. This is from
memory + what I could convince git and GitHub to tell me. Writing this also
makes me realize that now we’re two months into 100:10:1, I should promote some
more projects to round out my list of 10. I’ll try and make some progress there
this week!&lt;/p&gt;

&lt;h2 id=&quot;projects-i-worked-on-this-week&quot;&gt;projects I worked on this week&lt;/h2&gt;

&lt;h3 id=&quot;containy-thing&quot;&gt;containy-thing&lt;/h3&gt;

&lt;p&gt;I made some really minor changes to &lt;a href=&quot;https://github.com/kamalmarhubi/containy-thing&quot;&gt;containy-thing&lt;/a&gt;, which I haven’t pushed up
to GitHub yet. I switched to using the released version of &lt;a href=&quot;https://github.com/nix-rust/nix&quot;&gt;nix&lt;/a&gt; to pick up a
couple of changes I’d made to &lt;a href=&quot;https://github.com/nix-rust/nix/pull/231&quot;&gt;enable &lt;code&gt;mount(2)&lt;/code&gt;&lt;/a&gt;, and &lt;a href=&quot;https://github.com/nix-rust/nix/pull/224&quot;&gt;make safe
wrappers for &lt;code&gt;getuid(2)&lt;/code&gt; and &lt;code&gt;getgid(2)&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This is kind of cool because it’s popping some yaks off &lt;a href=&quot;/blog/2015/05/27/controlling-the-yak-stack/&quot;&gt;the yak
stack&lt;/a&gt;: I initially got involved with nix to make those changes.
Somehow I wound up making &lt;a href=&quot;https://github.com/nix-rust/nix/issues?utf8=%E2%9C%93&amp;amp;q=is%3Aissue+author%3Akamalmarhubi&quot;&gt;lots more&lt;/a&gt; &lt;a href=&quot;https://github.com/nix-rust/nix/commits?author=kamalmarhubi&quot;&gt;contributions&lt;/a&gt;,
and becoming a maintainer. It’s a fun circle, because I’m coming back to
containy-thing in order to get the CI for nix to run faster.&lt;/p&gt;

&lt;h3 id=&quot;silly-key-value-store&quot;&gt;silly key-value store&lt;/h3&gt;

&lt;p&gt;I did some initial work on this still-mysterious project. I’m pretty excited
for finally starting on it! Watch this space. :-)&lt;/p&gt;

&lt;h2 id=&quot;projects-i-didnt-work-on&quot;&gt;projects I didn’t work on&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;cargo fmt-diff&lt;/li&gt;
  &lt;li&gt;tufcrates&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Tue, 22 Mar 2016 14:06:52 -0400</pubDate>
        <link>http://kamalmarhubi.com/blog/2016/03/22/100-10-1-update-6/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/2016/03/22/100-10-1-update-6/</guid>
        
        
      </item>
    
      <item>
        <title>100:10:1 update 5</title>
        <description>&lt;p&gt;I need to find a better way to track my time and know what I worked on. Here’s my recollection:&lt;/p&gt;

&lt;h1 id=&quot;cargo-fmt-diff&quot;&gt;cargo fmt-diff&lt;/h1&gt;

&lt;p&gt;I reached a great state on Saturday: I can pass a set of line ranges in on the
command line, and statements—but only statements—in that range will be
reformatted! I probably spent half an hour trying different sets of arguments
just to see it go. This is really exciting!&lt;/p&gt;

&lt;p&gt;I still need to tidy up the code and send in the PR, but I’m at point where the
infrastructure for this project is pretty much done. Next up is lots of
heuristics for figuring out what to do when a syntactic element is partially in
a modified line range. To get an idea: if you modify one line in a function
body, you don’t want to reformat the whole function. But if you modify one line
in a function declaration, you &lt;em&gt;may&lt;/em&gt; want to reformat the whole declaration.&lt;/p&gt;

&lt;h1 id=&quot;tufcrates&quot;&gt;tufcrates&lt;/h1&gt;

&lt;p&gt;I finally printed off &lt;a href=&quot;https://isis.poly.edu/%7Ejcappos/papers/kuppusamy_nsdi_16.pdf&quot;&gt;the latest paper&lt;/a&gt; from &lt;a href=&quot;http://theupdateframework.com/&quot;&gt;The Update
Framework&lt;/a&gt; folks. I’m about half way through it. The paper makes some
excellent extensions for community repositories, which is exactly what
&lt;a href=&quot;https://crates.io/&quot;&gt;Crates.io&lt;/a&gt; is. I’ll continue reading the paper this week, and aim
to write something about TUF and the problems it solves some time soon.&lt;/p&gt;

&lt;h1 id=&quot;rust-bisect&quot;&gt;rust-bisect&lt;/h1&gt;

&lt;p&gt;Someone on the Rust IRC channel gave me a bit of feedback on rust-bisect. This
was a) really exciting because someone was using my project, and b) really
useful as I now have some idea of what would be good to add next.&lt;/p&gt;

&lt;p&gt;Specifically, the immediate next step is to allow an interactive mode where you
can run commands with the nightly version instead of needing to write a script.
This would be analogous to the git-bisect without the &lt;code&gt;run&lt;/code&gt; subcommand. I may
end up changing the CLI to more closely match git-bisect in that case.&lt;/p&gt;

&lt;p&gt;There’s are open questions of how to track progress, and how to override he
user’s environment in the least intrusive and most friendly way. Current ideas
I have:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;have rust-bisect fork a shell with the environment set up so that &lt;code&gt;rustc&lt;/code&gt;,
  &lt;code&gt;cargo&lt;/code&gt;, et al will run the correct nightly version
    &lt;ul&gt;
      &lt;li&gt;pros:
        &lt;ul&gt;
          &lt;li&gt;easy to keep track of state in the parent process&lt;/li&gt;
          &lt;li&gt;immediate access in the shell, so they can run &lt;code&gt;rustc&lt;/code&gt; and &lt;code&gt;cargo&lt;/code&gt;
  without prefixing&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;cons:&lt;/p&gt;

        &lt;ul&gt;
          &lt;li&gt;it’s not obvious how to communicate the outcome up to the parent process
from the shell: the obvious things involve terminating the shell and
forking a new one, but&lt;/li&gt;
          &lt;li&gt;I would most likely be overriding the user’s shell preference&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;store state in the filesystem, and require that they prefix commands with
  &lt;code&gt;rust-bisect run&lt;/code&gt; or a similar subcommand
    &lt;ul&gt;
      &lt;li&gt;pros:
        &lt;ul&gt;
          &lt;li&gt;easier to communicate the outcome, as there’s no environment overriding
going on&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;cons:
        &lt;ul&gt;
          &lt;li&gt;it’s unclear &lt;em&gt;where&lt;/em&gt; I should store the state. Current directory won’t
work, because they might go up and down the tree while testing. Home
directory might work, but would force at most one bisect at a time.&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;something akin to what virtualenv does, providing a script to source that
  overrides the current shell’s environment.
    &lt;ul&gt;
      &lt;li&gt;pros:
        &lt;ul&gt;
          &lt;li&gt;it lets the user use their shell, and not prefix any commands&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;cons:
        &lt;ul&gt;
          &lt;li&gt;I don’t like it&lt;/li&gt;
          &lt;li&gt;I’d have to provide scripts for a couple of different shells&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I need to give this a bit more thought before implementing.&lt;/p&gt;

&lt;h1 id=&quot;projects-i-didnt-touch&quot;&gt;Projects I didn’t touch&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;containy-thing&lt;/li&gt;
  &lt;li&gt;silly key-value store&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Mon, 14 Mar 2016 11:59:21 -0400</pubDate>
        <link>http://kamalmarhubi.com/blog/2016/03/14/100-10-1-update-5/</link>
        <guid isPermaLink="true">http://kamalmarhubi.com/blog/2016/03/14/100-10-1-update-5/</guid>
        
        
      </item>
    
  </channel>
</rss>
