iPhone Syncthing Client (or Rust in the Wild)

It took a bit of time, but finally fsync is available in the AppStore.

From a user perspective it’s a pretty simple iPhone client for syncthing. If you never heard about syncthing and you ever needed a self-hosted Dropbox you should give it a try. It’s very nice piece of software, it runs almost anywhere (Linux, *BSDs, Windows). It’s open source and written in Go so if you want to practice Go language - you’re welcome to contribute.

Right now fsync works in mostly “read-only” mode, i.e. you can view files, you can delete them, but there is no way to edit. This is gonna change soon.

From a technical perspective it’s probably one of the earliest iOS applications, which are partially written in Rust.

There is a lot of things to talk about and I hope to provide more technical details in the following posts, while this one covers using Rust as a language for mobile development from my experience.

Write Only Mode

By accident I’ve read today about Joe Nelson’s life experiment.

It’s a really inspirational post for me as it resonates a lot with what I’ve though about recently. I can argue a lot of minor details (because “but the great man is he who in the midst of the crowd keeps with perfect sweetness the independence of solitude”), but I can’t agree more with general direction the author takes.

I believe that one of the most limiting factors for current civilization is a culture of consumption. We have too much to consume and our uncontrolled consumption as a result “consumes” our time and available resources, leaving no opportunity to produce and create something.

It’s especially true for developers as we’re overhelmed by available technologies/frameworks/libraries/languages and are interested in trying “one more” shiny, just released thing, which is awesome and just got to HN. I’ve personally done that mistake dosens of times and I’m gonna tell about the recent one in the following posts.

To clarify: it’s not about sticking forever with old tools. It’s about clearing as much space/time as possible for generating new things/thoughts/ideas/products.

I’m not sure I’m ready to formulate it more clearly now, so I’ll start a REPL with my own experiment - instead of limiting myself, I’m going to make sure that I’m in “write only mode”.

What’s the write only mode? It’s the mode where I produce at least as much accessible output as I consume in my expertise areas. Preferably it should be a publicly available output.

The idea here is that it’s actuallly impossible to stop consumption by itself - it’s a dead end, especially in non-expertise areas. But what really makes a difference is what comes out of consumption - my only joy or something others can also use.

Continuation: considerations and setup

Rust for iOS: Status Update

It’s been a while since last status update, but I hope it was worth waiting. Rust is now completely ported to iOS: all architectures for device/simulator are supported. Since green threads were removed, adding support of arm64 was actually almost straightforward. Special thanks this time goes to Will Glozer who was debugging remotely. Fortunately for our sanity, there were just a couple of minor issues.

Although all changes have been landed to master, cross-compiled libraries aren’t distributed with nightly, so in case you’re interested in trying it out, you can either build it from source (instructions) or use a pre-built dist.

As earlier, the main usage sample is located here. It still uses makefile based approach and I hope to update for cargo a little bit later.

Rust Docsets for Dash

Since I’m tracking Rust nightly and documentation from the last release was quite outdated, I’ve wrote a quite simple (at least I think so) docset generator for Dash (wonderful piece of software).

Here is the link to feed which is updated once new nightly released.

Once it was complete, I’ve understood that I’d like to see docs for my libraries in Dash as well and here is what I’ve got: rust-docset - it is a Python script which allows to generate Dash docsets and feed from any Rust docs.

It requires a pretty simple TOML manifest to be available, like this one:

name = "Piston"
bundle_id = "piston"
version = "0.0.1"
type = "docset.rust"
doc_dir = "../doc"
out_dir = "doc_out"

base_url = "http://s3-us-west-2.amazonaws.com/net.vhbit.rust-doc"
upload_cmd = "./upload.sh"

and upload.sh might look like this:


s3cmd put -P $1 s3://net.vhbit.rust-doc
s3cmd put -P $2 s3://net.vhbit.rust-doc

While it started as Rust only project, I believe it could be relatively easily programmed to work with documentation generated by other tools.

Rust for iOS: Merged Into Master

Current state

About a week ago it was finally merged into Rust master branch which is really great as it is much easier to work on smaller changes now.

Here are instructions on how to build it. So far there is no official iOS buildbot and therefore it might broke at any moment, in this case I recommend to use a original fork which could be considered a “stable” branch, tested to compile and work both on device and simulator. It might lag a bit from the master but not that much.

There is still one issue in LLVM which sometimes crashes compilation process. Patch was submitted but considering previous experience I wouldn’t expect it to be landed in less than a month.

I’ve started work on Arm64 port but it definitely will take much more time considering I have no test device.

Rust for iOS: Progress Report

Although there is no public indication, work on porting Rust to iOS continues, moreover it is going to the final stage. So far I’ve got all required pieces working:

  • fixed issue with mutexes crashing libgreen/rustuv runtime
  • got a working patch for LLVM to support segmented stacks
  • got working unwinding (another patch to LLVM compiler-rt)

In general, all major features are working now, providing first-class support of all Rust safety. There definitely might be small hiccups here and there but I believe they could be solved step-by-step, once the major part will be upstreamed to Rust master branch.

I need some time to clean up the code (as it has a lot of experimenting branches) and once patches to LLVM and compiler-rt landed - the last step will be rebase on current master and issue an PR.

I hope it will be finished this week.

Rust on iOS

Porting process

Finally got working Rust cross-compiler for iOS so now it is possible to create static libraries which could be used from Objective C. For now only armv7 architecture is supported (although there are upcoming commits in “try” branch which will update LLVM version with ARM64 support right from Apple).

These were main pain points:

  • Slow full rebuild… Yep, I know, I know, 3 stage bootstrapping to be extremely optimized but still… it was especially painful on initial stage while experimenting with built options and LLVM patching.

  • TLS isn’t supported on armv7 so it should be emulated. Initially I’ve started adding it to LLVM and with help from Tim Northover and Dan Olson even got it working. (BTW, Dan knows a lot about this topic as he got a working D compiler for iOS, so if you’re interested in modern compiled language for iOS - you can try it too). Just to discover that actually Rust has built-in TLS “emulation” support (actually using the same technique as in LLVM patches)… Grr, hate myself for not checking this before messing with LLVM.

  • There were absolutely crazy crashes hard to debug because some kind linker errors/misconfiguration when functions were resolved correctly but all the data was relocated incorrectly and contained garbage.

  • There were mystical crashes in hash function which automagically disappeared once I’ve increased optimization level.

  • The final show-stopper was happening in runtime finalization routine - it always crashed on misaligned data during mutex locking. The reason was that mutex opaque data was copied as a plain data. It wasn’t the case on desktop OSes but seemed to be a big difference on iOS. There is a simple fix for native runtime and should be similar fix for green/rustuv.

What works

  • armv7 only (ARM64 port should be quite easy to introduce)

  • it is possible to compile standard libraries and use them

  • “native”-based runtime

  • creating static libraries which could be used from iOS applications

Known issues

  • green/rustuv runtime crashes because of incorrect mutex implementation

  • segmented stacks aren’t working

  • it might require additional manual linking

  • no support for simulator yet

  • it only works on common compiler flags. It is critical to have exactly –opt-level 2 (or -O) as both decreasing and increasing opt level may cause a lot of unexplainable issues

~~Shut up and take my money~~ Build instructions

clone and create build dir

git clone git@github.com/vhbit/rust.git
cd rust
git checkout ios
mkdir build_ios
cd build_ios


../configure --target=arm-apple-ios



or (for 4 core CPU)

make -j4

There is a sample project with instructions on how to integrate.


Special thanks to Tim Northover (ARM TLS), Dan Olson (ARM TLS), Alex Crichton (Rust internals) and my wife for being patient.

Joe Armstrong об ООП, Concurrency

Две части замечательной беседы с Джо Армстронгом (создателем erlang’а) об объектно-ориентированном программировании и почему оно скоро упрется и вынуждено будет смещаться в сторону функционального.

Один из интересных тезисов - это то, что сейчас нас начинает поджимать железо, если раньше мощности росли в количестве гигагерц, то сейчас все идет за счет увеличения числа ядер. А это провоцирует на переход к concurrent-based программированию (есть, кстати, нормальный русский термин для этого?), где императивщина в чистом виде начинает загибаться из-за возрастающей сложности разнообразных локов и защит.

Материал 2007 года и этим вдвойне интересней, т.к. тренды, о которых говорит Джо, из гипотетических становятся все более и более ощутимыми.

Переопределяем метод класса в рантайме

В кои-то веки потребовалось в рантайме переопределять методы класса. В документации сразу нашлась подходящая функция:

BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)

единственный аргумент, который может смутить - это types, который задает типы аргументов и возвращаемого значения в закодированном текстовом виде. Нужные значения можно посмотреть либо в документации, либо исппользовать @encode.

Вторая тонкость оказалась в том, что эта функция добавляет (или переопределяет) метод экземпляра, а что же делать если нужно заменить метод самого класса?

Правильно, получить метакласс с помощью object_getClass(ourClass) и заменить его метод как обычно :)