Sunday, February 13, 2011

Those who don't study Vista are doomed to repeat it.

A few years ago I got a brand new IBM ThinkPad that shipped with Windows Vista. I chose this platform because I had so much luck with an older ThinkPad running XP. The new laptop was in hindsight the best thing that ever happened to me. Because Vista was such a disaster - slow, unstable, unfamiliar, unusable - that I quickly replaced the ThinkPad with an Apple MacBook Air. Which I loved so much, I replaced my Windows XP-hosted desktop development environment with a Mac Mini with a 27" cinema display. And then got an iPad. And then an iPod Nano. Back when wooly mammoths strode my neighborhood I had converted from using a Mac Classic to a Windows box. But now I'm back.

It's possible that Vista might have been an improvement over XP. But who could tell? It was slow, buggy, and unstable. It would hang so severely that I had to not only power cycle the laptop but pull the battery to recover. The interface changes required a lot of effort to learn, which was hampered by the system hanging, crashing, and just plain making it difficult to get stuff done. I really wanted to hang in there with Windows, because my financial and cognitive investment was so high. But the shockingly low quality of the product just made it impossible to do so.

It was for me a Vistapocalypse. I'm a one-man company that relies on good tools to get my work done. I felt betrayed by Microsoft, who had up to that point been a reliable de facto business partner. I sometimes wonder how many tiny shops went out of business because they couldn't turn on a dime like I had to and adopt alternative technology due to reasons of technical expertise, cash-flow, or timing. I was lucky. But the trust was gone.

I eventually did a completely clean install of Windows 7, when that was released much later, on the laptop to get it back into usable form. I turn it on maybe once a month for some business application or another that only runs on Windows. Otherwise, I'm an Apple fanboy now.

As a professional product developer, I think about this a lot. If any company in the world could write functioning software, you would think it would be the largest, most successful, software company in the world. That they botched this, and so badly, gives me reason to pause. There's got to be a whole college course's worth of case studies in this, for both software engineering and business.

Those who don't study Windows Vista are doomed to repeat it.

(From a comment I originally published on io9, the Gawker Media science fiction blog.)

Friday, February 11, 2011

The System & The System: Overlaying GNU on Android on the Beagle Board

One of the best novels I read last year was The City & The City by China Miéville. This police procedural set in the present day takes place in the fictional European city-states of Beszel and Ul Qoma. What places this novel squarely in the realm of weird fiction is that Beszel and Ul Qoma occupy the same geographical space. Citizens of one city must unsee the citizens and features of the other city even as they live among them. This seperation extends even to buildings, where some floors or even rooms are in Beszel while others are in Ul Qoma. Citizens of each city must ignore the other lest they fall prey to Breach, a secret police whose operatives are apparently the only ones who can cross from one city to the other at will. It is a tribute to Miéville's ability that this bizarre concept is carried off without calling upon the reader to assume any supernatural agency; it is an act of perception and conditioning on behalf of the inhabitants of both cities.

And so it is with Contraption, my project to overlay a GNU environment on top of the otherwise very un-GNU-like Android on the Beagle Board. Like the citizens of Beszel and Ul Qoma, the GNU and Android environments co-exist in close proximity, within the same geographic file system and random access memory, yet kept separate through the auspices of the Breach-like Linux kernel. You can interact with Android from one one screen while running GNU-based software from a bash shell inside an ssh session from another. For the most part the two systems simply unsee one another by virtue of using different PATH and LD_LIBRARY_PATH environmental variables and by being dynamically linked to different shared objects. The Linux kernel and the dynamic loader keep it all separate.

This isn't some kind of virtual machine magic. It's just a trick of engineering. GNU software lives in /usr/sbin, /usr/bin, and /bin. Android software lives in /sbin, /system/sbin, /system/bin, and /system/xbin. GNU shared objects live in /lib, necessary because some GNU software ignores LD_LIBRARY_PATH. Android shared objects live in /system/lib. Android doesn't use /etc at all, opting instead for /system/etc. While Android forgoes all the usual user-level authentication mechanisms like /etc/passwd, GNU has full access to all of it, enabling for example the dropbear ssh server and the busybox telnet daemon to run unmodified. GNU software dynamically links to the GNU-based shared objects from the Sourcery G++ Lite ARM tool chain from CodeSourcery. Android software dynamically links to the shared objects from the Android ARM tool chain (which is a modified version of the CodeSourcery toolchain) from the FroYo release of the Rowboat port of Android to the Beagle Board.

The only directory conflict was /sbin, which on Android contains only adbd, the Android debugging daemon that serves as a proxy on the target (the Beagle Board) for a development environment running on the host (my desktop). To allow Android to unsee the executables that would normally have been in GNU /sbin, I moved them to /usr/sbin where there were no conflicts with other GNU-based executables.

The utilities, shared object, and memory mapped device driver from my Diminuto project that I described in Memory Mapped Devices on the Beagle Board with Android live in /usr/local/bin, /usr/local/lib, and /lib/modules respectively. They work just as before, except the Android insmod and the busybox insmod have slightly different syntax!

The Contraption project consists almost solely of a single Makefile that configures and builds the necessary software, including the modified Linux kernel, the Android root file system, and the various GNU-based packages such as busybox, bash, strace, and dropbear, creates an SD card of the Android system that can be booted on the Beagle Board, then overlays Contraption on top of it.

Here is the cinema display showing an Eclipse IDE with the Contraption Makefile, a bash shell running via an ssh session on Beagle Board, a serial console to Beagle Board; a little green Android figure standing next to the Beagle Board; a second display showing a web browser running on Android on the Beagle Board.

The System & The System

Here's a screen snapshot of a of the Beagle Board serial console. I booted up Android and fired up the dropbear ssh server from the command line. (See below for some notes on how to automate this.)

macwise console android

Here's a screen snapshot of a bash session via ssh to the Beagle Board. I ran the busybox ps command and used grep to pick out some processes.

ssh bash android

And here is a close up of the second display.

Android Browser on the Beagle Board

Here's a close up of the Beagle Board sitting between the two displays.

Beagle Board and Zippy2 Expansion Board

As I worked on the design of this, I began to realize the architects of Android must have wanted it to be possible for their system to be used this way, probably to make Android easier to integrate with existing Linux-based mobile phone platforms. Even though I've worked in the telecommunications field for most of the past fifteen years, my inspiration for this project wasn't smart phones. It was the student paper "Using Android in Industrial Automation" by Manuel Di Cerbo and Andreas Rudolf at the University of Applied Sciences at Northwestern Switzerland that impressed me with the possibilities of using Android in other embedded domains.

To make the Android platform really usable in this way I felt it had to be able to easily exploit the huge volume of GNU-based software. Even if one had to reside in Beszel and the other in Ul Qoma.

(You can find a link to a tar ball containing the Contraption distribution on the project web page at the Digital Aggregates Corporation web site.)

Update (2011-02-18)

I added some screen snapshots since I originally published this article.

Update (2011-02-25)

I modified the /init.rc boot script to automate some of the stuff described here.

In the on boot section I changed

hostname localhost

to

hostname contraption

and added

setprop net.dns1 8.8.8.8
setprop net.dns2 8.8.4.4

where 8.8.8.8 and 8.8.4.4 are Google's public DNS servers.

At the bottom I added

service dropbear /usr/sbin/dropbear
oneshot

to start the ssh server automatically. The oneshot option is important: the server is a daemon which appears to Android to exit, and you don't want Android to continuously restart it, otherwise wackiness will ensue.

Friday, February 04, 2011

Can't We All Just Get Along, C++ and C?

Several times in my career I've found myself doing product development in large legacy code bases. By large I mean on the order of many millions of lines of code, representing software shared by many products across a broad product line. Successful product lines inevitably evolve over time to use different hardware targets, operating system platforms, and even programming languages.

One of the most common evolutionary paths I see is the transition from C to C++. C++ is a complex language; some say too complex. To quote C++ inventor Bjarne Stroustrup: "In C++ it's harder to shoot yourself in the foot, but when you do, you blow off your whole leg." But with some care and discipline it can be effectively used even in embedded systems, which can exploit the advanced performance and code generation capabilities that C++ brings to the table, while retaining the ability of C to work close to bare metal.

This evolution results in code bases that are a mixture of C and C++. Making them play well together is one of the paths to success in such an evolution. Using C code from C++ is business as usual; C++ developers routinely do this. Using C++ code from C is rarer, but it is not only possible, it can be a big win, allowing you to incrementally refactor C code into C++ without having to do a forklift upgrade on your entire code base. Here's how I do it.

(There are examples of everything I write about here in my Desperado library that implements design patterns I have found useful in fifteen years of developing embedded systems in C++.)

First, the basics that you may already know.

C and C++ have different linkage conventions, that is, different mechanisms through which the object code produced by each compiler makes functions calls, and with which the linker recognizes function names. C for the most part only understands C linkage conventions. C++ however can be directed to use linkage conventions different from the default C++ conventions. It does this by extending the extern keyword to take an optional argument: the language name. This new operator can be applied to a single C++ function prototype or function implementation, or to a block of them. When applied to a prototype, the operator tells the C++ compiler what linkage convention to use to call the function. When applied to an implementation, it tells the C++ compiler what linkage convention to use to be called. This mechanism can be used to allow C++ programs to call C functions, or C programs to call C++ functions.

Here are some examples that you might see in a C++ header file.

extern "C" size_t dump_bytes(Dump * that, const void * data, size_t length);

extern "C" {
void * heap_malloc(Heap * that, size_t size);
void heap_free(Heap * that, void * ptr);
}

This allows these C++ functions to be called by either C or C++. The C standard header files, for example stdio.h, routinely use this mechanism to make the C functions they declare available to C++ code. What's less well known is that your C++ compiler is allowed provide linkages for other languages as well. You can even specify "C++" as the language.

There are some limitations. C doesn't understand this new argument to extern, it's part of C++. You can't declare a C++ class or instance method to have C linkage, because C has no understanding of C++ classes, so you can only use this in freestanding C++ functions. C also has no understanding of C++ namespaces, so it only works on C++ functions in the global namespace. If you specify "C" as the linkage, you have to conform to C linkage conventions, for example you have to specify an empty parameter list as (void) instead of () just as you do with C. Finally, when you mix C and C++, your main program must be C++, otherwise the C++ runtime system will not be properly set up. (Your first clue that you botched this will be that your C++ static variables will mysteriously not be initialized.) We'll get past many of these issues in just a bit.

A header file can tell whether it is being compiled by a C or C++ compiler. The C++ compiler will automatically define the preprocessor symbol __cplusplus. (This isn't just part of the GNU C++ compiler, it is part of the ISO C++ standard.) So here is a code snippet illustrating a common pattern for a header file declaring C++ functions that is to be included in either C++ or C.

#if defined(__cplusplus)
extern "C" {
#endif

extern void * heap_malloc(Heap * that, size_t size);
extern void heap_free(Heap * that, void * ptr);

#if defined(__cplusplus)
}
#endif

A C++ program including this header file will understand that the functions have C linkage. A C program doing the same will just see the prototypes.

Here is another approach: Desperado has a cxxcapi.h (for C++/C Application Programming Interface) header file that defines preprocessor macros that simplify inoperability between C and C++. It has constructs like this.

#if defined(__cplusplus)
#define CXXCAPI extern "C"
#else
#define CXXCAPI extern
#endif

This allows you to do stuff like this in a header file destined to be included from either C or C++.

#include "cxxcapi.h"

CXXCAPI size_t dump_bytes(Dump * that, const void * data, size_t length);

Okay, that's the basics. Now here's the part that may make your head explode.

All this is well and good. But what you really want is a way to use C++ objects in a C program, not just C++ functions. You can.

In the examples above the types Dump and Heap are actually C++ classes, and the variable that represents a pointer to such an object in the C code, just as the built-in variable this does in a C++ program. Here's the funny thing about C that makes this more than just crazy talk. In C (and for that matter, in C++) you can declare a pointer to a type without actually defining the type. This is a form of forward reference: you are telling the compiler "I'll tell you what this type is later, just hang in there". As long as you never dereference the pointer in the C code or do something that requires the compiler to know something about the type, that is you never write *that or that->field or sizeof(Heap), you never have to define the type. The compiler is totally okay with this. It is so trusting.

typedef struct Heap Heap;
Heap * that;

This C code snippet declares but does not define a new structure named Heap, and a new type also named Heap for this structure. Then it declares that to be a pointer to an object of type Heap without saying exactly what a Heap is. You can pass the variable that around in your C code just as you please. The structure named Heap doesn't have to be defined unless you plan on dereferencing a pointer to it. It's an opaque type, but one that is type safe; its use takes advantage of all the C and C++ compile time type checking.

So, let's put all this together in a code snippet that would be part of a header file that could be included from either C or C++. It describes a C++ class that can be used from either language.

#if defined(__cplusplus)

class Heap {
public:
Heap();
virtual ~Heap();
virtual void * malloc(size_t size);
virtual void free(void * ptr);
};

extern "C" Heap * heap_new(void);
extern "C" void heap_delete(Heap * that);
extern "C" void * heap_malloc(Heap * that, size_t size);
extern "C" void heap_free(Heap * that, void * ptr);

#else

typedef struct Heap Heap;

extern Heap * heap_new(void);
extern void heap_delete(Heap * that);
extern void * heap_malloc(Heap * that, size_t size);
extern void heap_free(Heap * that, void * ptr);

#endif

This one snippet declares two different interfaces to the same Heap object: a C++ class-based interface, and a C function-based interface. Note that the C function-based interface can actually be used from C++. (This is especially useful if you are using a C++-based unit testing framework like Google Test, of which I am quite the fan.) But generally, your C++ code will use the C++ interface, and your C code will use the C interface. It is all in one header file, so it can be easily maintained in parallel.

I won't bore you with what the C++ class actually does; your imagination can fill in the details. The C functions could be implemented in the same C++ source file as the C++ class implementation. (In Desperado, I actually keep them separate so statically linked embedded C++ applications don't need to carry the extra baggage of the thin C implementation layer that they don't need and won't use.) We don't need any __cplusplus magic since it's all C++ code.

#include "Heap.h"

extern "C" Heap * heap_new(void) {
return new Heap;
}

extern "C" void heap_delete(Heap * that) {
delete that;
}

extern "C" void * heap_malloc(Heap * that, size_t size) {
return that->malloc(size);
}

extern "C" void heap_free(Heap * that, void * ptr) {
that->free(ptr);
}

Note that since this is a C++ source file, its Heap refers to the actual C++ Heap class. This is totally transparent to the C code that may carry around the address in its own pointer variable of type Heap. This C to C++ adaptation layer can take advantage of virtual functions and namespaces. It is full fledged C++ code.

So here's a snippet of a C application, compiled with the C compiler, that uses the C++ class.

#include "Heap.h"

Heap * heap;
void * data;

heap = heap_new();
data = heap_malloc(heap, 1024);
heap_free(heap, data);
heap_delete(heap);

This is especially cool when using virtual functions. If you have another C++ class that derives from Heap, say TraceableHeap, but its C interface is the same, you can just substitute your traceableheap_new() for heap_new() in your C code and rely on the existing Heap C interface to do all the heavy lifting.

With very little effort and minimal ongoing additional maintenance cost, you can use this technique to gradually introduce C++ into C code bases, and take advantage of not just C functions in C++ programs, but C++ classes in C programs.

(A big Thank You to Marshall Cline and the C++ FAQ from which I developed this technique many years ago.)

Update (2011-02-21)

You might be wondering if, instead of using an opaque type, you can define a complete C structure definition whose fields shadow those of the C++ class definition. That would allow you to access the C++ fields from C. The answer is: maybe; but it's really dangerous. That's because whether it works or not depends on how your C++ compiler implements objects.

For example, if you have virtual functions, the compiler will insert an invisible field known as the virtual pointer somewhere in your object. The virtual pointer points to a table of function pointers that point to the virtual functions for the class. C won't know squat about this. Some compilers place this pointer at the beginning of the object; others at the end. The ISO standard makes this an implementation issue.

Even if it worked, C could have no respect for the protected and private qualifiers in C++. Generally speaking: I recommend against it, for no other reasons than code portability.

The fact that your C++ compiler may place invisible fields in your object as part of its implementation is the same reason why you cannot safely apply memory operations from the C standard library, like memset and memcpy, to C++ objects. Doing so writes over these invisible fields. Specifically, they write over the virtual pointer. The result is (on a good day) your program crashes, or (on a bad day) it now behaves really weirdly because you've just caused the virtual pointer in a derived class object to now point to the virtual table of a base class object. Wackiness ensues.