Thursday, April 13, 2017

How Meson is tested

A build system is a very important part of the development workflow and people depend on it to work reliably. In order to achieve this we do a lot of testing on Meson. As this is mostly invisible to end users I thought I'd write some information about our testing setup and practices.

Perhaps the most unconventional thing is that Meson has no unit tests in the traditional sense of the word. The code consists of functions, classes and modules as you would expect but there are no test for these individual items. Instead all testing is done on full projects. The bulk of tests are what could traditionally be called integration tests. That is, we take an entire project that does one thing, such as compile and install a shared library, and then configures it, builds it, runs tests and runs install and checks that the output is correct.

There are also smaller scale tests which are called unit tests. They also configure a project but then inspect the result directly. As an example test might set up a project and build it, and then touch one file and verify that it triggers a rebuild. Some people might claim that these are not unit tests either or that they should instead be tested with mock classes and the like. This is a valid point to make, but this is the terminology we have converged unto.

Enter The (Testing) Matrix

Our testing matrix is big. Really big. At its core are the three main supported platforms, Linux, Windows and OSX. We also support BSD's and the like but we currently don't have CI machines for them.

On Windows our Appveyor setup tests VS2010, 2015 and 2017 and in addition mingw and Cygwin. Apart from Cygwin these all are tested on both 32 and 64 bits variants. Visual studio is tested both with the Ninja and Visual Studio project generator backends.

OSX is the simplest, it is tested only with the Ninja backend using both regular and unity builds.

Linux tests do a lot more. In addition running the basic tests (both in unity and regular modes) it also runs the entire test suite in a cross compilation setup.

All of these tests are only for the core code. Meson supports a large amount of frameworks and libraries, such as GLib, Qt and Doxygen, and many programming languages. Every one of these has an associated test or, usually, several. This means that running the full test suite on Debian requires installing all of these:
  • Boost
  • D, Rust, Java, Fortran, C# and Swift compilers
  • Qt 5, WxWidgets, GTK+ 3
  • Valgrind
  • GNUstep
  • Protocol Buffers
  • Cython
  • GTest and GMock
And a bunch of other packages as well. The CI Docker image that has all of these installed takes 2 gigabytes of space. On many distros all dependencies are not available so packagers have to disable tests. Having a build dependency on all these packages sometimes yields interesting problems. As an example the Rust dependency means that Meson depends on LLVM. Every now and then it breaks on s390x meaning that Meson and every package that uses it to build get flagged for removal from Debian.

Every merge proposal to Meson master is run through all of these tests and is eligible for merging only if they all pass. There are no exceptions to this rule. 

There are some downsides to this, the biggest being that every now and then Appveyor and/or Travis get clogged and getting the green light takes forever. We looked briefly into getting paid instances but for our usage the bill would be in the neighborhood of $300 per month. Given that you can buy your own hardware for that kind of money, this has not been seen as a worthwhile investment. 

Saturday, April 8, 2017

Meson project status update

The text below is a copy of this post to the Meson development mailing list.

Hello everyone

The last few weeks have been an amazing ride for the Meson project. We
have gone from "interesting but niche" to being seriously considered
for such core infrastructure projects as Mesa, Wayland, Xorg and even
systemd. I would like to thank everyone who has contributed in making
this possible. Thanks to all contributors, evangelists, those who have
converted their projects, or even proposed it. We would not be here
without you.

However having this much growth brings with it new problems. The main
one of these, as most of you have probably noticed, is the growth in
pull request backlog. I know there are MRs that have been waiting for
quite a while and that this is very frustrating to those people who
have filed them. My apologies to you, we are trying to make this
better.

The second issue is the perennial problem of documentation.
Interestingly these two issues are quite tied together in unexpected
ways.

One of the things which is taking a lot of time for me personally is
making sure that all the documentation is up to date after merge
requests are done. This is a major problem and is limiting the number
of changes that can go in.

We have examined various ways of solving this problem. We have a PoC
for moving all documentation away from the Github wiki and inside the
main repository. This way we can require that all merge requests come
with corresponding documentation changes. This would reduce the review
burden.

A preview of the site can be seen here: http://mesonbuild.com/experimental/

The downside of this approach is that we would lose the ability to do
in-browser wiki editing, and even typo fixes would need to go via pull
requests. This is unfortunate. There does not seem to be a solution
that would work for both use cases. Final decisions on this have not
been made, so if there are people who have good suggestions or prior
experience with this, please speak up.

There are many other ways to help, too. Thus far I have done a large
fraction of, well, everything, ranging from bug reports to review to
designing new features and helping people on the mailing list. All of
these activities are fun and interesting, but there is only so much
time and I feel I'm already spreading myself too thin. This causes
problems such as the above mentioned backlog of merge requests.

We already have a wonderful group of people doing great work on IRC
and elsewhere. Thank you all for your efforts. But the fact of the
matter is that if the project continues seeing more uptake, we are
going to need more helpers, especially reviewers. Currently this task
rests almost entirely on me and Nirbheek. Any help on this would be
greatly appreciated. Just going over the code and saying "based on a
cursory glance this seems ok" would be helpful.

The one elephant in the room is that currently only I have merge
access to master. This is an obvious bottleneck, but if we manage to
fix the other issues listed above it should not be a limiting issue.
Still, if usage and contributions keep growing, we might consider a
multi-maintainer mode. The project is now large enough that we can
have subsystem maintainers, much in the same way as in the Linux
kernel. Example of these could include Windows maintainer, Gnome tools
maintainer, Qt maintainer, Android maintainer, documentation
maintainer and so on. A different approach would be to just have more
people with commit access and allowing them to move around the code as
they have interest. If you have experience or knowledge on how to best
handle this, please let us know.

Thank you all, and keep on compiling!

Tuesday, April 4, 2017

Inspector Gadget as an allegory of software engineering profession in the modern age

Many people think that Inspector Gadget is a quirky 80s animation series about a bumbling, but well meaning cyborg police inspector fighting an evil organization called MAD. This is not true. In reality the show is an allegory about the day to day work life in a modern software development company. It tells this story with foresight and accuracy that rivals, and sometimes even exceeds, Silicon Valley and its ilk.

This may seem like a bold claim, but let's us examine a typical episode and we shall see how facts stand firmly by this assertion.

The rockstar coder

The supposed hero of this series is Inspector Gadget himself. At the beginning of every episode he is spending his free time and is then unexpectedly called into work. Some sort of disaster has struck and he is the only one who can fix it. The Inspector then says Don't worry, chief, I'm always on duty and heads off.

From this simple exchange we know that the Inspector is the hotshot rockstar developer. The Ninja! The Cowboy Coder! The man who has no concept of work-life balance! He drops whatever it is he is doing and goes off to solve the problem.

Once at work we quickly discover that he is more than a rockstar. He is, in fact, an incompetent fool who thinks he is the greatest thing ever. During the course of the entire show, Inspector Gadget does not manage to make a single thing better. All he does is run around from one place to another and try arbitrary things that are not in any way helpful or even rational. Examples include swinging a mallet around randomly (while breaking expensive pieces of arg), inflating his coat for no rhyme or reason (usually knocking innocent people over) or even helping the bad guys perpetrate their crimes because they just ask for his help.

At no point does anyone call Inspector Gadget out for clearly being a useless idiot who only does harm. The entire organisation would work more efficiently if he was kicked out. But yet he remains, having reached a high enough level on the police force's organisation chart that he can't be fired, or even challenged.

The firefighter

The second person in our group of people is not actually a person, but a dog. Brain is the pet of Inspector Gadget. Whenever the inspector heads off to solve a case, Brain is given the same task: follow Inspector Gadget around and fix everything he breaks.

Here we find the only major disparity between Inspector Gadget the series and real life. In the latter, the incompetent rockstar (also known as Senior Systems Architect) breaks so many things that it takes more than one person to fix them. In extreme cases the group can consists of every other developer in the company. Perhaps this is the reason why Brain is portrayed as a dog. He does not represent a single person, but all of them.

If ew observe how Brain fixes the Inspector's bumblings, a common pattern arises. He always has to fix things in a way that the Inspector does not notice anything. Presumably if he were to notice these fixes, he would go back and change things back the way he left them. That is, completely broken.

Brain never does anything else, his life is a continuous stream of fighting fires that should never have been set alight. An illuminating example of this is the "pineapple incident" in episode Volcano Island, between 13m 54s and 14m 45s.

The fixer

The task of actually solving all problems is left to Penny, Gadget's niece. She does not fool around with pointless Rube Goldberg gadgets. She is highly competent and efficient in solving any problem. In an average episode Penny spends less than five minutes looking at the problem, finding the root cause, fixing it and wrapping everything up. She is a competent and smart person with solid engineering and problem solving skills. She single handedly thwarts MAD and is the main reason the entire world does not fall into anarchy.

Penny is never given any credit for this. In fact whenever she tries to talk some sense to the other characters, she is actively dismissed and belittled. Once the case is solved everyone goes to Inspector Gadget and congratulates him for doing a good job. The Inspector replies with something like I solved the case? I guess I did. Like any incompetent rockstar he is willing to take all the praise without doing any of the work.

In light of this it should be obvious why the character of Penny is a woman.

The wild card

The final person in this gallery is Dr. Claw, the leader of MAD. During the course of the show he does only two things. One: he looks at live video streams on his computer while scratching a cat. Two: he complains that everything done by everyone else is wrong (while never doing anything himself).

There are two differing theories on what he is supposed to represent. The first claims that he represents the company founder/owner who struck gold but since then has lost grasp of the present and just lashes out to his underlings at random.

The other theory claims that the creators of the show were incredibly foresighted and created Dr Claw as a prototype of modern day internet trolls 25 years before they actually appeared.

Sunday, March 26, 2017

Debian package dependency browser

The Debian package browser is great but it is somewhat limited. As an example even though you can get dependencies and build dependencies for any package but not reverse dependencies (i.e. list all packages that depend or build-depend on this package).

I wrote a simple program that downloads the package repository file, parses it and creates an SQLite DB with all the link information and a simple Flask web app to browse it. This is what it looks like when showing the information page on Flex.


In addition you can do all sorts of analysis on the data. As an example here are the 20 packages that are depended on the most followed by the number of packages that depend on them:

libc6 19759
libstdc++6 6362
libgcc1 5814
libglib2.0-0 2906
python 2802
zlib1g 2620
libcairo2 1410
libgdk-pixbuf2.0-0 1385
libpango-1.0-0 1303
libpangocairo-1.0-0 1139
libqt5core5a 1122
libatk1.0-0 1075
libgtk2.0-0 1010
libxml2 979
libfreetype6 976
perl 880
libqt5gui5 845
libfontconfig1 834
python3 825
libqtcore4 810

And here is the same for build-dependencies:

debhelper 27189
cdbs 3130
dh-autoreconf 3098
dh-python 2959
pkg-config 2698
autotools-dev 2331
python-setuptools 2193
python-all 1888
cmake 1643
python3-setuptools 1539
dpkg-dev 1446
python3-all 1412
perl 1372
zlib1g-dev 1317
dh-buildinfo 1303
python 1302
libglib2.0-dev 1133
gem2deb 1104
default-jdk 1078
libx11-dev 973

The numbers are not exact because the parser is not perfect but as rough estimates these should be reliable. Just don't use them for anything requiring actual accuracy, ok?

The code is here. I probably won't work on it any more due to other obligations, but feel free to play around with it if you wish. 

Thursday, March 16, 2017

Is static linking the solution to all of our problems?

Almost all programming languages designed in the last couple of years have a strong emphasis on static linking. Their approach to dependencies is to have them all in source which is compiled for each project separately. This provides many benefits, such as binaries that can be deployed everywhere and not needing to have or maintain a stable ABI in the language. Since everything is always recompiled and linked from scratch (apart from the standard library), ABI is not an issue.

The proponents of static linking often claim that shared libraries are unnecessary. Recompiling is fast and disks are big, thus it makes more sense to link statically than define and maintain ABI for shared libraries, which is a whole lot of ungrateful and hard work.

To see if this is the case, let's do an approximation experiment.

Enter the Dost!

Let's assume a new programming language called Dost. This language is special in that it provides code that is just as performant as the equivalent C code and takes the same amount of space (which is no small feat). It has every functionality anyone would ever need, does not require a garbage collector and whose syntax is loved by all. The only thing it does not do is dynamic linking. Let us further imagine that, by magic, all open source projects in the world get rewritten in Dost overnight. How will this affect a typical Linux distro?

Take for example the executables in /usr/bin. They are all implemented in Dost, and thus are linked statically. They are probably a bit larger than their original C versions which were linked dynamically. But by how much? How would we find out?

Science to the rescue

Getting a rough ballpark estimate is simple. Running ldd /usr/bin/executable gives a list of all libraries the given executable links against. If it were linked statically, the executable would have a duplicate copy of all these libraries. Said in another way, each executable grows by the size of its dependencies. Then it is a matter of writing a script that goes through all the executables, looks up their dependencies, removes language standard libraries (libc, stdlibc++, a few others) and adds up how much extra space these duplicated libraries would take.

The script to do this can be downloaded from this Github repo. Feel free to run it on your own machines to verify the results.

Measurement results

Running that script on a Raspberry Pi with Rasbian used for running an IRC client and random compile tests says that statically linked binaries would take an extra 4 gigabytes of space.

Yes, really.

Four gigabytes is more space than many people have on their Raspi SD card. Wasting all that on duplicates of the exact same data does not seem like the best use of those bits. The original shared libraries take only about 5% of this, static linking expands them 20 fold. Running the measurement script on a VirtualBox Ubuntu install says that on that machine the duplicates would take over 10 gigabytes. You can fit an entire Ubuntu install in that space. Twice. Even if this were not in issue for disk space, it would be catastrophic for instruction caches.

A counterargument people often make is that static linking is more efficient than dynamic linking because the linker can throw away those parts of dependencies that are not used. If we assume that the linker did this perfectly, executables would need to use only 5% of the code in their dependencies for static linking to take less space than dynamic linking. This seems unlikely to be the case in practice.

In conclusion

Static linking is great for many use cases. These include embedded software, firmwares and end user applications. If your use case is running a single application in a container or VM, static linking is a great solution that simplifies deployment and increases performance.

On the other hand claiming that a systems programming language that does not provide a stable ABI and shared libraries can be used to build the entire userland of a Linux distribution is delusional. 

Monday, March 13, 2017

Dependencies and unity builds with Meson

Prebuilt dependencies provided by the distro are awesome. You just install them and start working on your own project. Unfortunately there are many cases where distro packages are either not available or too old. This is especially common when compiling on non-Linux platforms such as Windows but happens on Linux as well when using jhbuild, Flatpak, Snappy or one of the many other aggregators. Dependencies obtained via Meson subprojects also fall into this category.

Unity builds

There is a surprisingly simple way of compiling projects faster: unity builds. The basic principle is that if your target has files foo.cpp, bar.cpp and baz.cpp, you don't compile them. Instead you generate a file called target-unity.cpp, whose contents are this:

#include<foo.cpp>
#include<bar.cpp>
#include<baz.cpp>

Then you compile just this file. This makes the compilation go faster. A lot faster. As an example converting Qt Creator to compile as a Unity build made it compile 90% faster. Counterintuitively it is even faster to compile a unity file with one core than to use four cores to build the files individually. If this is the first time you have encountered unity builds, this probably feels like a sham, something that just can't be possible. Not only is this possible, but unity builds are used in production in many places, especially in game development. As a different kind of example SQLite ships as a single "amalgamation file", which is the same thing as a unity build. Unity builds also act as a sort of poor man's link time optimization, which works even on compilers that do not support LTO natively.

Unity builds have their own limitations and problems. Some of them are discussed at the end of this article.

Dependencies

Meson has had unity build support available for a long time. The unfortunate downside is that incremental builds take a lot more time. This makes the edit-compile-debug cycle slower which is annoying. There are now two merge requests outstanding (number one, number two) that aim to make the user experience better.

With these changes you can tell Meson to unity build only subprojects, not the main project. This means that all your deps build really fast but the master project is built incrementally. In most use cases subprojects are read only. Only the master project is edited. For most people dependencies are slower to build than projects using them, so this gives a nice productivity boost. The other merge request enables finer grained control by allowing the user to override unityness for each target separately.

Please try out the branches and write your feedback and comments to the merge requests.

Problems of unity builds

Not all projects can be built as unity builds out of the box. The most common problem is having static variables and functions with the same name in different source files. In a unity build these will clash and not compile. There are other problems of similar nature, especially for projects that do crazy things with the preprocessor. These problems are fixable but take some effort. Most open source projects probably won't compile as unity builds out of the box.

Any project that wants to provide for a unity build must, in practice, have gating CI that compiles the source as a unity build. Otherwise it will break every now and then.

Monday, February 13, 2017

Looking into what Rust can do that other languages can't ... or can they

A recent blog post What Rust Can Do That Other Languages Can't the following statement is presented:

struct X {
  y: Y
}
impl X {
  fn y(&self) -> &Y { &self.y }
}

This defines an aggregate type containing a field y of type Y directly (not as a separate heap object). Then we define a getter method that returns the field by reference. Crucially, the Rust compiler will verify that all callers of the getter prevent the returned reference from outliving the X object. It compiles down to what you'd expect a C compiler to produce (pointer addition) with no space or time overhead.

Let's look into this a bit more deeply. But, since this is The Internet, first a pre-emptive statement.

Things not claimed in this blog post

To make things easier for forum discussers who have strong opinions but have hard time reading entire articles, here is a list of things that are not claimed. I repeat: not claimed.
  • that [other language] is as safe as Rust (it is most likely not)
  • that you should use [other language] instead of Rust
  • that you should use Rust instead of [other language]
  • that [other language] is safe out of the box (it probably is not)
  • security feature X of language Y will prevent all bugs of type Z (it does not)

To business

Plain C code corresponding to the setup above is roughly the following:

struct foo {
  int x;
};

struct bar {
  struct foo f;
};

A simple function that demonstrates the bug is the following:

int main(int argc, char **argv) {
  struct foo *f;
  struct bar *expiring = malloc(sizeof(struct bar));
  f = &expiring->f;
  free(expiring);
  do_something(f);
  return 0;
}

This uses an obviously invalid pointer in a function call. Neither GCC nor Clang warns about this when compiling. Scan-build, however, does detect the bug:

expired.c:23:3: warning: Use of memory after it is freed
  do_something(f);
  ^~~~~~~~~~~~~~~~~
1 warning generated.
scan-build: 1 bug found.

Address sanitizer also detects the invalid access operation inside do_something. Things get more interesting if we change the function so that expiring is on the stack instead of the heap.

int main(int argc, char **argv) {
  struct foo *b;
  {
    struct bar expiring;
    b = &expiring.f;
  }
  do_something(b);
  return 0;
}

This one is not detected at all. Neither GCC, Clang, Scan-build, Asan, CppCheck nor Valgrind see anything wrong with this. Yet this seems so simple and obvious that it should be detectable automatically.

Recently this has become possible with Address sanitizer. It grew a new argument -fsanitize-address-use-after-scope, which checks for exactly this and finds the bug effortlessly:

==10717==ERROR: AddressSanitizer: stack-use-after-scope on address 0x7ffe5d0c1920 at pc 0x00000050767f bp 0x7ffe5d0c18a0 sp 0x7ffe5d0c1898

This requires, of course, a run of the program that executes this code path. It would be nice to have this in a static analyzer so it could be found in even more cases (there is already a bug report for this for scan-build).

In conclusion

The security features of Rust are great. However many of them (not all, but many) that were unique to Rust are now possible in other languages as well. If you are managing a project in C or C++ and you are not using asan + scan-build + other error checkers on your code, you should use them all and fix the issues detected. Do it even if you intend to rewrite your code in Rust, Go or any other language. Do it now! There is no excuse.