Wednesday, March 7, 2012

Simpler, Faster, Better

For the past year or so, I've been working on and off on the next version of udisks and what is now known as the Disks GNOME application (née palimpsest):

Hello Shiny!

This code will ship in the upcoming GNOME 3.4 and Fedora 17 releases.

The motivation for rewriting udisks and palimpsest hadn't really anything to do with the user-experience per se - the main motivation was to port udisks/palimpsest code from dbus-glib to use all the D-Bus work I've been doing the last couple of years, e.g.

Since everything had to be rewritten to use new interfaces, I figured that while I was at it, I'd redesign the UI part as well. A big thanks goes to Jon McCann for helping me design the application and enduring my complicated descriptions of how storage works on Linux.

Cleanups

There's a couple of new user-visible features in the code but before delving into specifics I want to mention that we've also removed a couple of features. Why? Because the old interface was quickly becoming a mess and it certainly wasn't very GNOME3-ish neither in the way it looks nor the simplicity you'd expect. If there is one mantra that has driven this effort, it may very well be "don't try to expose everything in a desktop user interface" and I think this is something that extends to the greater GNOME 3 effort as well.

For example, the extent to which Disks support LVM (and MD RAID for that matter) is now that we only show the mapped devices (if the VG / array is running) and, except for e.g. showing the user-friendly (!) name /dev/vg_x61/lv_root instead of /dev/dm-2, that's pretty much it. You can still, of course, manipulate the device (such as changing the file system label) and its contents as if it was any other device (see below), but we no longer provide any UI to configure LVM or MD RAID itself - you are expected to use the command-line tools to do so yourself.

Another important goal of Disks that hasn't changed is the realization that we're only one tool among many - we don't pretend to own your machine and that we're the only tool you'll ever use. That's why you'd e.g. see device names in the user interface (without being primary identifiers) so you can copy/paste that to the terminal and use command-line tools on the device. Additionally, thanks to the notifications from udev, the Disks application will update its UI in response to changes you do from e.g. the command-line or other applications - for example, if you mkfs(8) a new filesystem, or add a new partition using parted(8).

Common operations

Fundamentally, the Disks end-user interface hasn't changed much (it's still basically a tree-view on the left and volume grid on the right), however instead of lots of buttons, most operations are initiated by accessing a popup-menu either for the volume or drive in question. Common operations like formatting a device, changing the passphrase of an encrypted device, creating a new partitionformatting a disk, checking ATA SMART data are pretty much the same, although the UI has been cleaned up some. Pretty basic stuff, really, no big changes here.

Mount and encryption options

A common theme since I started working on storage in desktop Linux (some eight years ago), is that some people are extreme control-freaks about where a device is mounted and with what options. Most of the time you won't need this (the desktop shell will automount the device somewhere in /media) but there's a couple of important uses for this. One common example, is that people are using their computer to serve media files to their TV or Media Jukebox over the LAN. For this to work you often need to make sure the device is mounted in say, /mnt/foo (because /mnt/foo is what you added to the config file for the media server) and that this happens before the media server is started.

We've been trying all sorts of things over the years (the most complex being the now deprecated gnome-mount program reading mount options from e.g. GConf) and while some of these things have worked great in theory, they were just way too complex; our users just didn't have the time nor the inclination to figure out how to use our software... and I don't blame them... my experience is that if the effort more complex than editing a single text file with emacs(1) or vi(1) you've lost most people.

(In retrospect, realizing when your software is too complex for people to use takes much longer than you think - worse, I suspect a lot of developers don't realize just how over-engineered their software is until it's too late.)

So, the way it has worked the past few years in GNOME is that if you want specific configuration for mounting a specific disk, I've been telling people to just add an entry to /etc/fstab and use one of the symlinks  in /dev/disk. Works great. So it was only natural to actually add some UI for this and the result is this dialog

Editing an entry in the /etc/fstab file

which basically correspond to the fields in the /etc/fstab file.

A nice touch here (I think) is that the "Identify As" combo box allows you to select any of the /dev/disk symlinks that currently point to the device, for example, you can make the given mount options apply to any disk connected to the given USB port (actually, partition 1 from said disk). This is of course nothing new, you've always been able to use any /dev/disk symlink in the /etc/fstab file but I bet most people don't have time or inclination to find out exactly what link to use so most just end up using e.g. /dev/sdb1 because that works right now for them. Again, the good old "if it's more complex than editing a single file" line of thought.

(My secret hope here is that even old Unix neck-beards will want to use such UI dialogs instead of editing the /etc/fstab file manually ... or at the very least realize how such a combo box adds value before they flame the tool to death :-) ...)

As for /etc/fstab, we also have similar UI for the /etc/crypttab file except that this is a bit more complex insofar that we allow managing passphrase-files to e.g. automatically unlock a device on boot-up... you may need encrypted /etc for this to be secure - this of course depends on your threat model but it could be you have provisions for securely shredding all content in /etc/luks-keys when needed etc. etc., I don't know :-)

Anyway, the nice thing about using standardized files such as /etc/fstab and /etc/crypttab for this, is interoperability with the rest of the OS - in particular, you can edit the mount options e.g. the boot file-system from the Disks application. Additionally, things like systemd will actually mount devices referenced in the /etc/fstab file at start-up (unless the noauto option is used) which is something you really want for the media server use-case mentioned above.

Disk images and loop devices

Another new feature has to do with disk images - the Disks application now allows you to create and restore disk images (including showing the speed and estimated time left) which is handy especially e.g. from a rescue live cd (it's basically just a GUI for dd(1)). Additionally, there is UI for attaching disk images and using them and, thanks to my friend Kay Sievers, it even works with partitioned disk images

Loop device, with partitions, oh my!

which I think is pretty handy.

Desktop integration

Another important part of the equation is what the user sees when it comes to storage devices in general (e.g. in general, not only when using the Disks application). This is largely the domain of the Desktop Shell, the Files application (née Nautilus) and the file chooser. These pieces all rely on the GLib Volume Monitor APIs which is a high-level abstraction with a stable API/ABI that applications can use (among other things) to figure out what volumes to present in their user interfaces.

In a nutshell, the volumes to show is a complex mixture of physical storage devices (say, mountable filesystems residing on a plugged-in USB stick), devices backed by GVfs backends (say, digital cameras and iPod that are not block devices), GVfs network backends (e.g. smb:// network mounts) and non-storage mounts such as e.g. NFS mounts, FUSE mounts and fstab entries representing things that can be mounted but may not already be mounted.

Now, the way GVfs works is pretty complex (there are multiple volume monitor daemons and storage backends instances) but the important point is that the volume monitor responsible for device and fstab mounts has been updated to use udisks2, the same storage daemon used by the Disks application. In addition to returning GDrive, GVolume and GMount objects for storage devices, this volume monitor also return GVolume entries for /etc/fstab entries so you can e.g. mount a NFS server by clicking an icon in Files (again, a common user request), like this

Desktop Integration. Bringing it all together

Note that the name, icon and desktop visibility of the GVolume instance representing the NFS mount is controlled by mount options in the /etc/fstab file - see this write-up for more information.

Thursday, September 22, 2011

New D-Bus features in GLib 2.30

For the upcoming GLib 2.30 release, there's a couple of new features to make it even easier to use D-Bus.

C Code Generator

GLib 2.30 ships with a command called gdbus-codegen(1) which can be used to generate C code. The command is similar in spirit to the dbus-binding-tool(1) command but it targets the D-Bus implementation added to GLib 2.26 (often informally referred to as GDBus). The command's manual page and migration documentation is the authoritative source of documentation, but from a 50,000 feet view what the tool does is simply to map a D-Bus interface (described by XML) to a couple of GObject-based types (including all D-Bus methods, signals and properties). It of course supports the PropertiesChanged signal added in D-Bus spec 0.14.

Even though the tool is targeting C programmers (most higher-level languages are a lot more dynamic than C so objects can be exported via e.g. language meta-data such as annotations), it's useful to note that the generated code is 100% annotated so it can be used from e.g. JavaScript through GObject Introspection - for example the GNOME Documents application (written in JavaScript) is consuming the GNOME Online Accounts client-library which is 99% generated by the gdbus-codegen(1) command.

In addition to just generating code, the gdbus-codegen(1) command can also generate very nice Docbook documentation (example 1, example 2) for D-Bus interfaces - in this respect it's useful even for non-GNOME applications in the same way a lot of libraries like libblkid and libudev are already using gtk-doc for their C library documentation.

Object Manager

Another part of GLib 2.30 is support for the org.freedesktop.DBus.ObjectManager D-Bus interface - in fact, the implementation in GLib, that is, the newly added GDBusObject{Proxy,Skeleton}and GDBusObjectManager{Client,Server} types, is actually what drove me to propose this as a standard interface instead of just doing a GLib-only thing (with shoutouts to my homeboys smcv and walters for excellent review and feedback).

In a nutshell, the org.freedesktop.DBus.ObjectManager interface is basically a formalization of what each and every non-trivial D-Bus service is already doing: offering some kind of GetAll() method (to return all objects) and signals ::Foo{Added,Removed} (to convey changes) on its Manager interface in its own special way (example 1, example 2). It first sounds weird to standardize such a simple thing as object enumeration and change signals but if you think about all the possible edge cases and race-conditions then using a well-tested implementation just makes everything so much easier. Additionally, with the way the interface is defined and the newly added path_namespace match rule, two method invocations and a single round-trip is all it takes for a client to grab the state from the service - this is a huge win compared to existing services that typically first retrieve a list of object paths and then gets properties for each object path (and only if you are lucky it does the latter in parallel).

When combined with the gdbus-codegen(1) command (which can also generate specialized GDBusObject types for use with GDBusObjectManager) you can start writing service-specific code right away and not worry about horrible implementation details like marshaling, too many round trips or race conditions. It just works out of the box as you'd expect it to.

Wednesday, July 6, 2011

Writing a C library, intro, conclusion and errata

This is a series of blog-posts about best practices for writing C libraries. See below for each part and the topics covered.

Table of contents

The entire series about best practices for writing C libraries covered 15 topics and was written over five parts posted over the course of approximately one week. Feel free to hotlink directly to each topic but please keep in mind that the content (like any other content on this blog) is copyrighted by its author and may not be reproduced without his consent (if you are friendly towards free software, like e.g. LWN, just ask and I will probably give you permission):

Topics not covered

Some topics relevant for writing a C library isn't (yet?) covered in this series either because I'm not an expert on the topic, the topic is still in development or for other reasons:
  • Networking
    You would think IP networking is easy but it's really not and the low-level APIs that are part of POSIX (e.g. BSD Sockets) are not really that helpful since they only do part of what you need. Difficult things here include name resolution, service resolutionproxy server handling, dual-stack addressing and transport security (including handling certificates for authentication).

    If you are using modern GLib networking primitives (such as GSocketClient or GSocketService) all of these problems are taken care of for you without you having to do much work; if not, well, talking to people (or at least, read the blogs) such as Dan Winship, Dan Williams or Lennart Poettering is probably your best bet.

  • Build systems
    This is a topic that continues to make me sad so I decided to not really cover it in the series because the best guidance I can give is to just copy/paste whatever other projects are doing - see e.g. the GLib source tree for how to nicely integrate unit testing (see Makefile.decl) and documentation (see docs/reference sub-directories) into the build system (link).

    Ideally we would have a single great IDE for developing Linux libraries and applications (integrating testing, documentation, distribution, package building and so on - see e.g. Sami's libhover video) but even if we did, most existing Linux programmers probably wouldn't use it because they are so used to e.g. emacs or vi (if you build it, they will come?). There's a couple of initiatives in this area including Eclipse CDT, Anjuta, KDevelop and MonoDevelop.

  • Bundling libraries/resources
    The traditional way of distributing applications on Linux is through so-called Linux distributions - the four most well-known being DebianFedoraopenSUSE and Ubuntu (in alphabetical order!). These guys, basically, take your source code, compile it against some version of other software it depends on (usually a different version than you, the developer, used), and then ship binary packages to users using dynamic linking.

    There's a couple of problems with this legacy model of distributing software (this list is not exhaustive): a) it can take up to one or two distribution release cycles (6-12 months) before your software is available to end users; and b) user X can't give a copy of the software to user Y - he can only tell him where to get it (it might not be available on user Y's distro); and c) it's all a hodgepodge of version skew e.g. the final product that your users are using is, most likely, using different versions of different libraries so who knows if it works; and d) the software is sometimes changed in ways that you, the original author, wasn't expecting or does not approve of (for example, by removing credits); and e) the distribution might not forward you bug reports or may forward you bug reports that is caused by downstream patches; and f) there's a peer pressure to not depend on too new libraries because distributions want to ship your software in old versions of their OS - for example, Mozilla wants to be able to run on a system with just GTK+ 2.8 installed (and hence won't use features in GTK+ 2.10 or later except for using dlopen()-techniques), similar for e.g. Google Chrome (maybe with a newer GTK+ version though). These problems are virtually unknown to developers on other platforms such as Microsoft Windows, Mac OS X or even some of the smartphone platforms such as iOS or Android - they all have fancy tools that bundles things up nicely so the developers won't have to worry about such things.

    There's a couple of interesting initiatives in this area see e.g. bockbuild, glick and the proposal to add a resource-system to GLib. Note that it's very very hard to do this properly since it depends not only on fixing a lot of libraries so they are relocatable, it also depends on identifying exactly what kind of run-time requirements each library in question has. The latter includes the kernel/udev version, the libc version (unless bundled or statically linked), the X11 server version (and its extensions such as e.g. RENDER) version, the presence of one or more message buses and so on. With modern techniques such as direct rendering this becomes even harder if you want to take advantage of hardware acceleration since you must assume that the host OS is providing recent enough versions of e.g. OpenGL or cairo libraries (since you don't want to bundle hardware drivers). And even after all this, you still need to deal with how each distribution patches core components. In some circumstances it might end up being easier to just ship a kernel+runtime along with the application, virtualized.
The way the series is set up is so it can be extended at a later point - so if there is a demand for one or more popular topics about writing a C library, I might write another blog entry and add it to this page as it's considered the canonical location for the entire series.

Errata

Please send me feedback and I will fix up the section in question and credit you here (I already have a couple of corrections lined up that I will add later).

Tuesday, July 5, 2011

Writing a C library, part 5

This is part five in a series of blog-posts about best practices for writing C libraries. Previous installments: part one, part two, part three, part four.

API design

A C library is, almost by definition, something that offers an API that is used in applications. Often an API can't be changed in incompatible ways (it can, however, be extended) so it is usually important to get right the first time because if you don't, you and your users will have to live with your mistakes for a long time.

This section is not a a full-blown guide to API design as there's a lot of literature, courses and presentations available on the subject - see e.g. Designing a library that's easy to use - but we will mention the most important principles and a couple of examples of good and bad API design.

The main goals when it comes to API design is, of course, to make the API easy to use - this include choosing good names for types, functions and constants. Be careful of abbreviations - atof might be quick to type but it's not exactly clear that the function parses a C string and returns a double (no, not a float as the name suggests). Typically nouns are used for types and while verbs are used for methods.

Another thing to keep in mind is the number of function arguments - ideally each function should take only a few arguments so it's easy to remember how to use it. For example, no-one probably ever remembers exactly what arguments to pass to g_spawn_async_with_pipes() so programmers end up looking up the docs, breaking the rhythm. A better approach (which is yet to be implemented in GLib), would be to create a new type, let's call it GProcess, with methods to set what you'd otherwise pass as arguments and then a method to spawn the actual program. Not only is this easier to use, it is also extensible as adding a method to a type doesn't break API while adding an argument to an existing function/method does. An example of such an API is libudev's udev_enumerate API - for example, at the time udev starting dealing with device tags, the udev_enumerate type gained the add_match_tag() method.

If using constants, it is often useful to use the C enum type since the compiler can warn if a switch statement isn't handling all cases. Generally avoid boolean types in functions and use flag enumerations instead - this has two advantages: first of all, it's sometimes easier to read foo_do_stuff(foo, FOO_FLAGS_FROBNICATOR) than foo_do_stuff(foo, TRUE) since the reader does not have to expend mental energy on remembering if TRUE translates into whether the frobnicator is to be used or not. Second, it means that several booleans arguments can be passed in one parameter so hard-to-use functions like e.g. gtk_box_pack_start() can be avoided (most programmers can't remember if the expand or fill boolean comes first). Additionally, this technique allows adding new flags without breaking API.

Often the compiler can help - for example, C functions can be annotated with all kinds of gcc-specific annotations that will cause warnings if the user is not using the function correctly. If using, GLib, some of these annotations are available as macros prefixed with G_GNUC, the most important ones being G_GNUC_CONST, G_GNUC_PURE, G_GNUC_MALLOC, G_GNUC_DEPRECATED_FORG_GNUC_PRINTF and G_GNUC_NULL_TERMINATED.

Checklist

  • Choose good type and function names (favor expressiveness over length).
  • Keep the number of arguments to functions down (consider introducing helper types).
  • Use the type system / compiler to your advantage instead of fighting it (enums, flags, compiler annotations).

Documentation

If your library is very simple, the best documentation might just be a nicely formatted C header file with inline comments. Often it's not that simple and people using your library might expect richer and cross-referenced documentation complete with code samples.

Many C libraries, including those in GLib and GNOME itself, use inline documentation tags that can be read by tools such as gtk-doc or Doxygen. Note that gtk-doc works just fine even on low-level non-GLib-using libraries - see e.g. libudev and libblkid API documentation.

If used with a GLib library, gtk-doc uses the GLib type system to draw type hierarchies and show type-specific things like properties and signals. gtk-doc can also easily integrate with any tool producing Docbook documentation such as manual pages or e.g. gdbus-codegen(1) when used to generate docs describing D-Bus interfaces (example with C API docs, D-Bus docs and man pages).

Checklist

  • Decide what level of documentation is needed (HTML, pdf, man pages, etc.).
  • Try to use standard tools such as Doxygen or gtk-doc.
  • If shipping commands/daemons/helpers (e.g. anything showing up in ps(1) output), consider shipping man pages for those as well.

Language bindings

C libraries are increasingly used from higher-level languages such as Python or JavaScript through a so-called language binding - for example, this is what allows the Desktop Shell in GNOME 3 to be written entirely in JavaScript while still using C libraries such as GLib, Clutter and Mutter underneath.

It's outside the scope of this article to go into detail on language bindings (however a lot of the advice given in this series does apply - see also: Writing Bindable APIs) but it's worth pointing out that the goal of the GObject Introspection project (which is what is used in GNOME's Shell) is aiming for 100% coverage of GLib libraries assuming the library is properly annotated. For example, this applies to the GUdev library (a thin wrapper on top of the libudev library) can be used from any language that supports GObject Introspection (JS example).

GObject Intropspection is interesting because if someone adds GObject Introspection support to a new language, X, then the GNOME platform (and a lot of the underlying Linux plumbing as well cf. GUdev) is now suddenly available from that language without any work.

Checklist

  • Make sure your API is easily bindable (avoid C-isms such as variadic functions).
  • If using GLib, set up GObject Introspection and ship GIR/typelibs (notes).
  • If writing a complicated application, consider writing parts of it in C and parts of it in a higher-level language.

ABI, API and versioning

While the API of a library describes how the programmer use it, the ABI describes how the API is mapped onto the target machine the library is running on. Roughly, a (shared) library is said to be compatible with a previous version if a recompile is not needed. The ABI involves a lot of factors including data alignment rules, calling conventions, file formats and other things that are not suitable to cover in this series; the important thing to know about when writing C libraries is how (and if) the ABI changes when the API changes. Specifically, since some changes (such as adding a new function) are backwards compatible, the interesting question is what kind of API changes result in non-backwards-compatible ABI changes.

Assuming all other factors like calling convention are constant, the rule of thumb about compatibility on the ABI level basically boils down to a very short list of allowed API changes:
  • you may add new C functions; and
  • you may add parameters to a function only if it doesn't cause a memory/resource leak; and
  • you may add a return value to a function returning void only if it doesn't cause a memory leak; and
  • modifiers such as const may be added / removed at will since they are not part of the ABI in C
The latter is an example of a change that breaks the API (causing compiler warnings when compiling existing programs that used to compile without warnings) but preserve the ABI (still allowing any previously compiled program to run) - see e.g. this GLib commit for a concrete example (note that this can't be done in C++ because of how name mangling work).

In general, you may not extend C structs that the user can allocate on the stack or embed in another C structure which is why opaque data types are often used since they can be extended without the user knowing. In case the data type is not opaque, an often used technique is to add padding to structs (example) and use it when adding a new virtual method or signal function pointer (example). Other types, such as enumeration types, may normally be extended with new constants but existing constants may not be changed unless explicitly allowed.

The semantics of a function, e.g. its side effect, is usually considered part of the ABI. For example, if the purpose of a function is to print diagnostics on standard output and it stops doing it in a later version of the library, one could argue it's an ABI break even when existing programs are able to call the function and return to the caller just fine possibly even returning the same value.

On Linux, shared libraries (similar to DLLs on Windows) use the so-called soname to maintain and provide backwards-compatibility as well as allowing having multiple incompatible run-time versions installed at the same time. The latter is achieved by increasing the major version number of a library every time a backwards-incompatible change is made. Additionally, other fields of the soname have other (complex) rules associated (more info).

One solution to managing non-backwards-compatible ABI changes without bumping the so-number is symbol versioning - however, apart from being hard to use, it only applies to functions and not e.g. higher-level run-time data structures like e.g. signals, properties and types registered with the GLib type-system.

It is often desirable to have multiple incompatible versions of libraries and their associated development tools installed at the same time (and in the same prefix) - for example, both version 2 and 3 of GTK+. To easily achieve this, many libraries (including GLib and up) include the major version number (which is what is bumped exactly when non-backwards-compatible changes are made) in the library name as well as names of tools and so on - see the Parallel Installation essay for more information.

Some libraries, especially when they are in their early stages of development, specifically gives no ABI guarantees (and thus, does not manage their soname when incompatible changes are made). Often, to better manage expectations, such unstable libraries require that the user defines a macro acknowledging this (example). Once the library is baked, this requirement is then removed and normal ABI stability rules starts applying (example).

Related to versioning, it's important to mention that in order for your library to be easy to use, it is absolutely crucial that it includes pkg-config files along with the header files and other development files (more information).

Checklist

  • Decide what ABI guarantees to give if any (and when)
  • Make sure your users understand the ABI guarantees (being explicit is good)
  • If possible, make it possible to have multiple incompatible versions of your library and tools installed at the same time (e.g. include the major version number in the library name)

Friday, July 1, 2011

Writing a C library, part 4

This is part four in a series of blog-posts about best practices for writing C libraries. Previous installments: part one, part two, part three.

Helpers and daemons

Occasionally it's useful for a program or library to call upon an external process to do its bidding. There are many reasons for doing this - for example, the code you want to use
  • might not be easily used from C - it could be written in say, python or, gosh, bash; or
  • could mess with signal handlers or other global process state; or
  • is not thread-safe or leaking or just bloated; or
  • its error handling is incompatible with how your library does things; or
  • the code needs elevated privileges; or
  • you have a bad feeling about the library but it's not worth (or (politically) feasible) to re-implement the functionality yourself. 
There are three main ways of doing this.

The first one is to just call fork(2) and start using the new library in the child process - this usually doesn't work because chances are that you are already using libraries that cannot be reliably used after the fork() call as discussed in previously (additionally, a lot of unnecessary COW might be happen if the parent process has a lot of writable pages mapped). If portability to Windows is a concern, this is also a non-starter as Windows does not have fork() or any meaningful equivalent that is as efficient.

The second way is to write a small helper program and distribute the helper along with your library. This also uses fork() but the difference is that one of the exec(3) functions is called immediately in the child process so all previous process state is cleaned up when the process image is replaced (except for file descriptors as they are inherited across exec() so be wary of undesired leaks). If using GLib, there's a couple of (portable) useful utility functions to do this (including support for automatically closing file descriptors).

The third way is to have your process communicate with a long-lived helper process (a socalled daemon or background process). The helper daemon can be launched either by dbus-daemon(1) (if you are using D-Bus as the IPC mechanism), systemd if you are using e.g. Unix domain sockets, an init script (uuidd(8) used to do this - wasteful if your library is not going to get used) or by the library itself.

Helper daemons usually serve multiple instances of library users, however it is sometimes desirable to have a helper daemon instance per library user instance. Note that having a library spawn a long-lived process by itself is usually a bad idea because the environment and other inherited process state might be wrong (or even insecure) - see Rethinking PID 1 for more details on why a good, known, minimal and secure working environment is desirable. Another thing that is horribly difficult to get right (or, rather, horribly easy to get wrong) is uniqueness - e.g. you want at most one instance of your helper daemon - see Colin's notes for details and how D-Bus can be used and note that things like GApplication has built-in support for uniqueness. Also, in a system-level daemon, note that you might need to set things like the loginuid (example of how to do this) so things like auditing work when rendering service for a client (this is related to the Windows concept known as impersonation).

As an example, GLib's libproxy-based GProxy implementation uses a helper daemon because dealing with proxy servers involves a interpreting JavaScript (!) and initializing a JS interpreter from every process wanting to make a connection is too much overhead not to mention the pollution caused (source, D-Bus activation file - also note how the helper daemon is activated by simply creating a D-Bus proxy).

If the helper needs to run with elevated privileges, a framework like PolicyKit is convenient to use (for checking whether the process using your library is authorized) since it nicely integrates with the desktop shell (and also console/ssh logins). If your library is just using a short-lived helper program, it's even simpler: just use the pkexec(1) command to launch your helper (example, policy file).

As an aside (since this write-up is about C libraries, not software architecture), many subsystems in today's Linux desktop are implemented as a system-level daemons (often running privileged) with the primary API being a D-Bus API (example) and a C library to access the functionality either not existing at all (applications then use generic D-Bus libraries or tools like gdbus(1) or dbus-send(1)) or mostly generated from the IDL-like D-Bus XML definition files (example). It's useful to contrast this approach to libraries using helpers since one is more or less upside down compared to the other.

Checklist

  • Identify when a helper program or helper daemon is needed
  • If possible, use D-Bus (or similar) for activation / uniqueness of helper daemons.
  • Communicating with a helper via the D-Bus protocol (instead of using a custom binary protocol) adds a layer of safety because message contents are checked.
  • Using D-Bus through a message bus router (instead of peer-to-peer connections) adds yet another layer of safety since the two processes are connected through an intermediate router process (a dbus-daemon(1) instance) which will also validate messages and disconnects processes sending garbage.
  • Hence, if the helper is privileged (meaning that it must a) treat the unprivileged application/library using it as untrusted and potentially compromised; and b) validate all data to it - see Wheeler's Secure Programming notes for details), activating a helper daemon on the D-Bus system bus is often a better idea than using a setuid root helper program spawned yourself.
  • If possible, in particular if you are writing code that is used on the Linux desktop, use PolicyKit (or similar) in privileged code to check if unprivileged code is authorized to carry out the requested operation.

Testing

A sign of maturity is when a library or application comes with a test suite; a good test suite is also incredible useful for ensuring mostly bug-free releases and, more importantly, ensuring that the maintainer is comfortable putting releases out without loosing too much sleep or sanity. Discussing specifics of testing is out of the scope for a series on writing C libraries, but it's worth pointing to the GLib test framework, how it's used (example, example and example) and how this is used by e.g. the GNOME buildbots.

One metric for measuring how good a test suite is (or at least how extensive it is), is determining how much of the code it covers - for this, the gcov tool can be used - see notes on how this is used in D-Bus. Specifically, if the test suite does not cover some edge case, the code paths for handling said edge case will appear as never being executed. Or if the code base handles OOM but the test suite isn't set up to handle it (for example, by failing each allocation) the code-paths for handling OOM should appear as untested.

Innovative approaches to testing can often help - for example, Mozilla employ a technique known as reftests (see also: notes on GTK+ reftests) while the Dracut test suite employs VMs for both client and server to test that booting from iSCSI work.

Checklist

  • Start writing a test suite as early as possible.
  • Use tools like gcov to ascertain how good the test suite is.
  • Run the test suite often - ideally integrate it into the build system ('make check'), release procedures, version control etc.

Wednesday, June 29, 2011

Writing a C library, part 3

This is part three in a series of blog-posts about best practices for writing C libraries. Previous installments: part one, part two.

Modularity and namespaces

The C programming language does not support the concept of namespaces (as used in e.g. C++ or Python) so it is usually emulated simply by using naming conventions. The main reason of namespaces is to avoid naming collisions - consider both libwoot and libkool providing a function called get_all_objects() - which one should be used if a program links to both libraries? Namespacing is an important part of a naming strategy and applies to variables, function names, type names (including structs, unions, enums and typedefs) and macros.

The standard convention is to use a short identifier, e.g. for libnm-glib you will see nm_ and NM being used, for Clutter it's clutter and Clutter and for libpolkit-agent-1, it's polkit_agent and PolkitAgent. For libraries that don't use CamelCase for its types, the same prefix is normally used for functions and types - for example, libudev the prefix used is simply udev.

Code that isn't using namespaces properly is not only hard to integrate into other libraries and applications (the chance of symbol collisions is high), there's also a chance that it will collide with future additions to the standard C library or POSIX standards.

One benefit of using namespaces in C (one that ironically is not present in a language with proper support for namespaces), is that it's a lot easier to pinpoint what the code is doing by just looking at a fragment of the source code - e.g. when you see an item being added to a container, you are usually not in doubt whether the programmer meant to invoke GtkContainer's add() method or ClutterContainer's add() method because of how C namespacing forces the programmer to be explicit, for better or worse.

In addition to choosing a good naming strategy, note that the visibility of what symbols (typically variables and functions) a library export can be fine-tuned, see these notes for why this is desirable.

On the topic of naming, it is usually a good idea to avoid C++ keywords (such as "class") for variable names, at least in header files that you except C++ code to include using e.g. extern "C". Additionally, generally avoid names of functions in the C standard library / POSIX for variable names such as "interface" or "index" because these functions can (and on Linux, actually is) be defined as macros.

Checklist

  • Choose a naming convention - and stick to it.
  • Do not export symbols that are not public API.

Error handling

If there's one statement that adequately describes error handling in the C programming language, it's perhaps that it's something that people rarely agree on. Most programmers, however, would agree that errors can be broken down into two categories 1) programmer errors; 2) run-time errors.

A programmer error is when the programmer isn't using a function correctly - e.g. passing a non-UTF-8 string to a function expecting a valid UTF-8 string such as g_variant_new_string() (if unsure, validate with g_utf8_validate() before calling the function) or passing an invalid D-Bus name to g_bus_own_name() (if unsure, validate with g_dbus_is_name() and g_dbus_is_unique_name() before calling).

Most libraries have undefined behavior in the presence of being used incorrectly - in the GLib case the macros g_return_if_fail() / g_return_val_if_fail() are used, see e.g. the checks in g_variant_new_string() and the checks in g_dbus_own_name().  Additionally, for performance, these checks can be disabled by defining the macro G_DISABLE_CHECKS when building either GLib itself or applications using GLib (but usually aren't). Not all parameters may be checked, however, and the check might not cover all cases because checks can be expensive. Combined with the G_DEBUG flag, it's even easy to trap this in debugger by running the program in an environment where G_DEBUG=fatal-warnings.

Having g_return_if_fail()-style checks is usually a trade-off - for example, GLib didn't initially have the UTF-8 check in g_variant_new_string() - it was only added when it became apparent that a considerable amount of users passed non-UTF-8 data which caused errors in unrelated code that was extremely hard to track down - see the commit message for details. If this cost is unacceptable, the programmer can easily use the g_variant_new_from_data() function passing TRUE as the trusted parameter.

Even with a library doing proper parameter validation (to catch programmer errors early on), if you pass garbage to a function you usually end up with undefined behavior and undefined behavior can mean anything including formatting your hard disk or evaporating all booze in a five-mile radius (oh noz). That's why some libraries simply calls abort() instead of carrying on pretending nothing happened. In general, a C library can never guarantee that it won't blow up no matter what data is passed - for example the user may pass a pointer to invalid data and, boom, SIGSEGV is raised when the library tries to accesses it. Of course the library could try to recover, longjmp(3) style, but since it's a library it can't mess around with process-wide state like signal handlers. Unfortunately, even smart people sometime fail to realize that the caller has a responsibility and instead blames the library instead of its user (for the record, libdbus-1 is fine which is why process 1 is able to use it without any problems). In most cases, problems like these are solved by just throwing documentation at the problem.

To conclude, when it comes to programmer errors, one key take away is that it's a good idea to document exactly what kind of input a function accepts. As the saying goes, "trust is good, control is better", it is also a good idea to verify that the programmer gets it right by using g_return_if_fail() style checks (and possibly provide API that does no such checks). Also, if your code does any kinds of checks, make sure that the functions used for checking (if non-trivial) are public so e.g. language bindings have a chance to validate input before calling the function (see also: notes on errors in libdbus).

A run-time error is e.g. if fopen(3) returns NULL (for example the file to be opened does not exist or the calling process is not privileged to open it), g_socket_client_connect() returns FALSE (the network might not be up) or g_try_malloc() returns NULL (might not have enough address space for a 8GiB array). By definition, run-time errors are recoverable although the code you are using might treat some (like malloc(3) failing) as irrecoverable because handling some run-time errors (such as OOM) would complicate the API not only on the function level (possibly by taking an error parameter), but also by requiring transactional semantics (e.g. rollback) on most data types (see also: write-up on why handling OOM is hard and a good explanation of Linux's overcommit feature).

For simple libraries just using libc's errno is often simplest approach to handling run-time errors (since it's thread-safe and every C programmer knows it) but note that some functions including asprintf(3) does not set errno to ENOMEM if e.g. failing to allocate memory. If you are basing your code on a library like GLib, use its native error type, e.g. GError, for run-time errors. An interesting approach to handling errors is the one used by the cairo 2D graphics library where (non-trivial) object instances track the error state (see e.g. cairo_status() and cairo_device_status()). There are many many other ways to convey run-time errors - as always, the important thing when writing a C library is to be consistent.

Checklist

  • Document valid and invalid value ranges for parameters (if any) and provide facilities to validate parameters (unless trivial) for programmers and language bindings
  • Try to validate incoming parameters at public API boundaries
  • Establish a policy on how to deal with programmer errors (e.g. undefined behavior or abort()).
  • Establish a policy on how to deal with run-time errors (e.g. use errno or GError)
  • Ensure the way you handle run-time errors map to common exception handling systems.

Encapsulation and OO design

While C as programming language does not have built-in support for object-oriented programming lots of C programmers use C that way - in many ways it's almost hard not to. In fact, many C programmers regard the simplicity of C (compared to, say, C++) as a feature insofar that you are not bound to any one object model - for example, the kernel uses various OO techniques and the GLib/GTK+ stack has its own dynamic type system called GType on which the GObject base class (that many classes are derived from) is built.

There's of course a price to pay for defining your own object model - it typically involves more typing (identifiers are longer) and, especially for GObject, involves actual function calls to register properties, add private instance data and so on (example). On the other hand, such a dynamic type system often offer some level of type introspection so it's possible to easy link the property for whether a check-button widget is active with whether an text-entry widget should use password mode using the g_object_bind_property() function (screenshot). Polymorphism in GObject is provided by embedding a virtual method table in the class struct (example) and providing a C functions that uses the function pointer (example) - note that derived types can access the class struct to chain up (example).

One important feature of object-oriented design in C is that it usually promotes encapsulation and data hiding through the use of opaque data types - this is desirable as it allows extending the data type (e.g. adding more properties or methods) without breaking or requiring a recompile existing programs using the library (a future installment will discuss API and ABI and what it means wrt. API design). In an opaque data type, fields that would usually be in the C struct are hidden from the user and instead are made available via a getter (example) and/or setter (example) - additionally, if the object model support properties, the member may also be made available as a property (example) - for example, this is useful for notifying when the property changes.

Of course, not every single data structure need to be a full-blown GObject - for example, in some cases data hiding might not be desirable (sometimes it's awkward to use a C getter function) or maybe it's too slow to do from an inner loop (direct struct access is without a doubt faster). Also, for simple data structures it is sometimes desirable to initialize struct instances directly in the code.

Even when a full-blown object model (like GType and GObject) isn't used, it's never a bad idea to use opaque data structures and getters/setters. As an interesting alternative to this, note that some libraries explicitly allows extending a C structure without considering it an ABI change - while there's no easy way to enforce this (the user may allocate the structure on the stack), at least the library author can always tell the programmer that he shouldn't have done so (which may or may not be useful).

Checklist

  • Establish an object model for your library (if applicable).
  • Hide as many implementation details as is practical without impacting performance
  • Ensure that you can extend your library and types without breaking API or ABI.
  • If possible, build on top of an established and well-understood object system (such as the GLib one)

Tuesday, June 28, 2011

Writing a C library, part 2

This is part two in a series of blog-posts about best practices for writing C libraries. Previous installments: part one.

Event handling and the main loop

Event-driven applications, especially GUI applications, are often built around the idea of a "main loop" that intercepts and dispatches all sorts of events such as key/button presses, incoming IPC calls, mouse movements, timers and file/socket I/O and so on. The main loop typically "call back" into the application whenever an event happens.

For example, the GLib/Gtk+ library stack is built around the GMainContext, GMainLoop and GSource types and other library stacks provide similar abstractions. Many kernel and systems-level programmers often look funny at GUI programmers when they utter the word "main loop" - much the same way GUI programmers stare confused at kernel programmers when they say put() or get() something. The truth is that a main-loop is really a well-known concept with a different name: it's basically an abstraction of OS primitives such as select(2), poll(2) or equivalent on e.g. Windows.

It is important to note that a multi-threaded application may run different main loops in different threads to ensure that callbacks happen in the right threads - in GLib this is achieved by using the g_main_context_push_thread_default() function which records the main loop for the current thread in thread-local storage. This variable is in turn read when starting an asynchronous operation (such as g_dbus_connection_call() or g_input_stream_read_async()) to ensure that the passed callback function is invoked in a thread running a main loop for the context set with g_main_context_push_thread_default() earlier.

Some main loops, for example the GLib one, allows creating recursive main loops and this is used to implement GtkDialog's run() method. While this indeed appears to block the calling thread, it is important to note that events are still being processed (to e.g. process input events and redraw animations). Specifically, this means that the functions (plural since applies to everything in the call stack) that brought up the dialog might end getting called again (from a callback). Thus, when using functions like gtk_dialog_run() you need to ensure that your functions are either re-entrant or that they are guaranteed to not get called when the dialog is showing (typically achieved by making the dialog modal so the UI action triggering the display of the dialog can't be accessed). Because of pitfalls like this, you must clearly document if a function is using a recursive main loop.

Note that main loops are not a GUI-only concept - a lot of daemons (e.g. background process without any GUI) are built around this concept since it nicely integrates events from any source whether they are file descriptor based or synthetic such as timers or logging events. In fact, a considerable part of the system-level software on a modern Linux system is built on top of GLib and uses its main event loop abstraction to dispatch events - most of the time such daemons sit idle in one or more main loops and wait for D-Bus messages to arrive (to service a client), a timeout to fire (maybe to kick off periodic house-keeping tasks) or a child process to terminate (when using a helper program or process to do work).

Now that we've explained what a main loop is (or rather, what the idea of a main loop is), let's look at why this matters if you a writing a C library. First of all, if your library doesn't need to deliver events to users, you don't need to worry about main loops. Most libraries, however, are not that simple - for example, libudev delivers events when devices are plugged or changed, NetworkManager wants to inform of changes in networking and so on.

If your library is using GLib, it is often suitable to just require that the user runs the GLib main loop (if the application is using another main loop, it can either integrate the GLib main loop (like Qt does) or run it in a separate thread) and use g_main_context_get_thread_default() when setting up a callback. This is the way many GObject-based libraries, such as libpolkit-gobject-1libnm-glib or libgudev work - for example, callbacks connected to the GUdevClient::uevent signal will be called in what was the thread-default main loop when the object was constructed. For a shared resource, such as a message bus connection, a good policy is that callbacks happen in what was the the thread-default main loop when the method was called (see e.g. g_dbus_connection_signal_subscribe() where this is the case) since applications or libraries have no absolute control of when the shared object was created. In any case, functions dealing with callbacks must always document in what context the callback happens in.

On the other hand, if your library is not using GLib, a good way to provide notification is simply to a) provide a file descriptor that e.g. turns readable when there are events to process; and b) provide a function that processes events (and possibly invoke callback functions registered by the user). A good example of this is libudev's udev_monitor_get_fd() and udev_monitor_receive_device() functions. This way the application (or the library using your library) can easily control what thread the event is handled in. As an example of how libudev is integrated into the GLib main loop, see here and here. In the libudev case, the returned file descriptor is the underlying netlink socket used to receive the event from udevd (via the kernel); in the case that there are no natural file descriptor (could be the event is only happening in response to a certain entry in, say, a log file), your library could use pipe(2) (or eventfd(2) if on Linux) and use a private worker thread to signal the other end.

If your library provide callback functions, make sure they take user_data arguments so the user can easily associate callbacks with other objects and data. If the scope of your callback is undefined (e.g. may fire more than once or if there is no way to disconnect the callback), also provide a way to free the user_data pointer when it is no longer needed - otherwise the application will leak data that needs to be freed later. See g_bus_watch_name() and  for an example.

Checklist

  • Provide APIs for main loop integration
  • Make sure callback functions take user_data arguments (possibly with free an accompanying free function)

Synchronous and Asynchronous I/O

It is important for users of a library to know if calling a function involves doing synchronous I/O (also called blocking I/O). For example, an application with an user interface need to be responsive to user input and may even need to update the user interface every frame for smooth animations (e.g. 60 times a second). To avoid unresponsive applications and jerky animations, its UI thread must never call any functions that does any synchronous I/O.

Note that even loading a file from local disk may block for a very long amount of time - sometimes tens of seconds. For example the file may not be in the page cache and the hard disk with the file system may be powered down - or the file may be in the users home directory which could be on a network filesystem such as NFS. Other examples of blocking IO includes local IPC such as D-Bus or Unix domain sockets.

If an operation is known to take a long time to complete (synchronous or otherwise), it is often nice if it is possible to easily cancel the it (perhaps from another thread). For example, see the GCancellable type in the GLib stack. Another nicety (although easily implemented via the GCancellable type) is a way to set a timeout for potentially long-running operations - see e.g. g_dbus_connection_send_message_with_reply() and g_dbus_proxy_call() and note how the latter has an object-wide timeout so the timeout only has to be set once.

Some libraries provide both synchronous and asynchronous versions of a function where the former blocks the calling thread and the latter doesn't. Typically asynchronous I/O is implemented using worker threads (where the worker thread is doing synchronous I/O) but it could also involve communicating with another process via IPC (e.g. D-Bus) or even TCP/IP. For example, in the libgio-2.0 case asynchronous file I/O is implemented via synchronous IO (e.g. basically read(2) and write(2) calls) in worker threads (using a GThreadPool) simply because the Linux kernel does not (yet?) provide an adequate way to do asynchronous I/O suitable for libraries (see also: colorful notes about Asynchronous I/O). On the upside, this is mostly an implementation detail and the libgio-2.0 implementation can migrate to a non-threaded approach should such a mechanism be made available in the future.

Asynchronous I/O typically involves callbacks (or at least some kind of event notification) and thus involves a main loop. If a library provides functions for this, it should clearly state what thread the callback will happen in, and whether it requires the application to run a (specific kind of) main loop - see the previous section about main loops for details.

If a library is thread-safe, it is often easier for the application itself to just use the synchronous version of a function in a worker-thread - if using GLib, g_io_scheduler_push_job() is the right way to do that.

In some cases synchronous I/O is implemented by using a recursive main loop (typically by using the asynchronous form of the function) - this should be avoided as it typically causes all kinds of problems because of reentrancy and events being processed while waiting for the supposedly synchronous operation to complete. As always, clearly document what your code is doing.

Some libraries, such as those in the GLib stack, use a consistent pattern for asynchronous I/O for all of its functions involving the GAsyncResult / GSimpleAsyncResult, GAsyncReadyCallback and GCancellable types - this makes it a lot easier both for programmers and for higher-level language bindings especially since important things like life-cycles are part of this model (for example, you are guaranteed that the callback will always happen, even on cancellation, timeout or error).

Checklist

  • Clearly document if a function does any synchronous I/O
  • Ideally suffix synchronous functions it with _sync() so it's easy to inspect large code-trees using e.g. grep(1) 
  • Consider if an operation needs to be available in synchronous or asychronous form or both.
  • Point to both synchronous and asynchronous functions in your API documentation.
  • If possible, use an established model (such as the GIO model) for I/O instead of rolling your own