the trials, tribulations and life of a geek.

Codesigning GDB on macOS

When I first started using a Mac for most of my work and personal projects, I was pretty upset that the gnu debugger didn't work out of the box. The error shouted by it was met with a myriad of bunk solutions online, so for a while I forwent using it entirely. However, after giving searching another go sometime later I came across this gem of a fix!

Resizing a Ubuntu VirtualBox VDI on OSX

I often underestimate the amount of disk space needed when creating and using a VirtualBox vm, but luckily for me it's not too hard to expand them. Here's how.

First, shutdown your VM. From your host OS, in this case OSX, run the following command with appropriate arguments replaced.

$ /Applications/VirtualBox.app/Contents/MacOS/VBoxManage modifyhd "[path to vdi]" --resize [Size in MB]

After that, boot your Ubuntu VM back up. Run the following command from a terminal window running on the VM.

$ fdisk [path to disk device]

From the fdisk REPL print partitions.

> p

Your primary partition may have a swap partition between it and the new unallocated space that you wish to extend it with. If this is the case. You will need to delete said partition. Find the number corresponding to the blocking partition in the list printed by the command above. Then use the following command to delete it.

> d [ number of swap/ext partition ]

Exit fdisk, and save your changes. After that reboot the VM. If you don't already have it installed, go ahead and fetch gparted.

$ sudo apt-get install gparted
$ gparted

Use gparted to resize your remaining primary partition, and reboot!

My First Robotics Competition: A Post-mortem

Alt For the last 9 months or so, I've been tinkering with the design, construction and implementation of a robot capable of competing in Sparkfun's AVC. AVC, an acronym for Autonomous Vehicle Competition, is a fairly straight-forward, single lap race featuring home built robotic vehicles attempting to out perform one another. Typically the race takes place annually, in Sparkfun's parking lot. The course features hay bails, jumps, and various obstacles to try your machine's navigational metal. I first learned of the race from Sparkfun's website whilst buying parts for another project a few years ago. However, this year I finally decided to give it a go.

Like so many things in life, the first go was far from flawless. I visited the race course the day before the actual event. I made a few attempts, but I was only able to make it 2/3 of the way through the track. According to other competitors, it was a much more narrow course than what it had been in years prior. What was somewhat reassuring was the amount of trouble the other competitors were also having, including those who were veterans of the event. Regardless of the outcome, much was learned. I want to take some time here to chronicle those lessons learned.

Focus on solving the problem at hand

Large projects often have countless facets that could steal away your attention from the big picture. And it's easy to let the scope creep, and grow larger and larger. It often becomes all too common (for me at least) to lose sight of what the actual end goal is, and rather, get caught up in solving various sub problems which, albeit useful, frequently detract from successfully executing your true goal. I found myself, building, reading and learning about much much more than I needed to really solve the problem. Though this is great for personal development, it doesn't immediately help win races. :)

Start Small

In a way, this goes back to the point above. Starting small, and trying to solve the problem in the most minimal way possible is the best way to begin. Over engineering a solution will result in many more problems than just those which you began with. Once you've solved the problem, then you should seek to optimize. Just remember! KISS!

One thing at a time / Keep it modular!

As I built my robot, I found myself getting stuck, bored or disinterested with certain tasks. This unintentionally introduced many down-right stupid bugs into my code. As subtlely broken systems slyly introduced their bugs into the system as a whole, bugs that proved to be very difficult to track down. This can be remedied by strickly adhering to good branching discipline, and keeping each feature modular. That way, even if you do thrash between features those that are unfinished / not totally perfect will not screw with those that are.

Modular design for any system is beneficial for a myriad of reasons. Mostly it allows different system components to be built and operate largely independently of one another. This also helps to improve over all quality and testability. Plus, if one component is found to be a pain point, rebuilding, refactoring or ripping it out will be much less painful if systems are not tangled together. Also, modular components are easier to experiment with and decrease the risk of muddying up the surrounding infrastructure and systems.

Prove it! Run experiments and tests

Do you think you got something working? Did you finally solve the problem? Don't celebrate quite yet. Be your own worst critic, try to prove that it in fact doesn't work. Setup tests that you think it might have trouble with. Run some experiments with the goal of showing your past-self to be wrong. Just accepting a success in one circumstance does not mean it won't fail miserably in another.

Put together a good test environment

You can plug away at building things and think it through as carefully as you please, but at the end of the day, you'll still need to try it out. For me this was often difficult. I started construction of this project in the winter months, and being from Michigan that meant snow, salt and water all at once. These are not the best conditions to be running a small scale robotic car in. However, it was the only way I could give the system a true test. After the fact, I realized that I would have been much better off testing a simulated car, in a simulated environment. Aside from the convenience of being able to run valid trials from the warmth of a coffee shop, the simulated environment would also allow for the freedom to carefully control different sources of interference and other environmental anomalies.

Be explicit about units

This got me into trouble a number of times. Between GPS, the IMU, rotary encoder and LIDAR sensors; mismatched unit types abounded. Despite that, I used the same vector types for nearly every one of them. This often resulted in units getting mixed with incompatible units which in turn generated all kinds of unwanted bugs that were particularly difficult to track down. I strongly suggest explicitly disallowing this kind of mixing and matching in favor of purpose built types for each unit and explicit conversions between them if you really must.

Build robust self-check / diagnostic systems

This might be a pain in the ass, but it will save you a ton of time and frustration in the long run. Especially as your project complexity grows. Many times I discovered a broken wire or some other physical failure after hunting around in my code for the culprit. Self check systems that narrow down the issue without human investigation are well worth your time. Configurable diagnostics and logging are also hugely beneficial.

Maintain version awareness

This really only applies to self contained systems that communicate with one another. Particular examples from my project included the wheel encoder micro-controller talking to the main computer. The main computer talking to diagnostic apps, and diagnostic apps and programs talking to various system daemons. A number of times I found myself stumped as to why I was getting garbage data from the robot, only to find that I had, unknowingly, slightly changed the packet structure. A simple wrapping header confirming protocol/packet version would have easily caught this oversight, and if handled correctly reported it.

Don't hesitate to refactor construction

Code gets refactored frequently, but the same should also go for mechanical/electrical parts. If something breaks don't just patch it up and leave it. It failed for a reason, and the patch will certainly fail too. Take some time to redesign given what you learned about weak points in your previous attempt.

Use utilities and tools that let you iterate quickly

I'm a fanboy for the C programming language. I love its simplicity and power. However I did find myself in situations where it was a bit of a hinderance. Trying to quickly build some algorithmic code, especially if it was math heavy, was often slow, tedious and error prone. Use higher level tools to try things out and prove validity before pursuing a final and possibly more finicky implementation. Even for the final implementation, I would recommended using a language or set of libraries that allow you to express higher level concepts with ease (such as a good C++ linear algebra library).

Robots are realtime

Robots live in our world, and time in our world marches on relentlessly. As such, a robot's accurate perception of time is key for commonly used algorithms to function correctly. Traditional, non-realtime operating systems present a problem for such algorithms. In my case, this problem was Linux. At any moment, your process can be suspended for a short time to allow another system process to run. For most applications this doesn't matter much. However, when you are integrating sensor data a fixed and very small time step will save you a lot of headache by reducing error. In my future projects, I will definitely consider deferring all highly time sensitive tasks to either a micro controller, or a computer running a proper RTOS.

Creating a Unix Daemon

To quote Wikipedia,

In multitasking computer operating systems, a daemon (/ˈdiːmən/ or /ˈdeɪmən/)[1] is a computer program that runs as a background process, rather than being under the direct control of an interactive user.

In practice daemons are used any time a service needs to be accessible at a moment's notice. A good example would be a server applicaion. A server spends most of it's time sitting, waiting, for a request or connection that could come at any time; then honoring that request as quickly as possible.

Recently I created my first daemon, a TCP server for uploading gps data to the computer on a robot. So I wanted to document what I learned.

Here's how to create a minimal Unix daemon in C.

#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>

int main()
    // When you start the daemon initially the process that is spawned
    // is attached to the user's current session. So the first a child
    // process is spawned. fork() accomplishes this. From this point on you
    // can think of your program now existing as two processes, both of which
    // just finished executing the line below. One of these processes is the
    // parent, the other is the child
    pid_t pid = fork();

    if(pid > 0){
        printf("parent: the daemon's pid is %d\n", pid);
        return -1; // the parent has nothing else to do, simply exit
    else if(pid < 0){
        // if the pid returned is -1, then the fork() failed.
        printf("parent: and the daemon failed to start (%d).\n", errno);
        return -2;

    // if the pid is 0 then this process is the child
    // setsid() makes the process the leader of a new session. This is the
    // reason we had to fork() above. Since the parent was already the process
    // group leader creating another session would fail.
    if(setsid() < 0){
        printf("daemon: I failed to create a new session.\n");
        return -3;

    // when the child is spawned all its' properties are inherited from
    // the parent including the working directory as shown below
    char workingDirectory[256];
    char* wd = getwd(workingDirectory);
    printf("daemon: current working directory is '%s'\n", wd);

    // change the working directory appropriately. (to root for example)
    wd = getwd(workingDirectory);
    printf("daemon: new current working directory is '%s'\n", wd);

    // close whatever file descriptors might have been
    // inherited from the parent, such as stdin stdout
    for(int i = sysconf(_SC_OPEN_MAX); i--;){

    // stdio is closed, you won't hear anything more from the daemon
    printf("daemon: now I'm silent!\n");

    // like everything else, file permissions are also inherited from the
    // parent process. This is an octal number which follows the chmod
    // pattern. The default value is 022. (write access for owner only)

    // keep the daemon alive for 10 seconds.
    // here is where you would actually do some work :)

    return 0;

Duplicated File Descriptors and system()

For the last month or so I've been pretty heavily invested in building and programming an autonomous R/C car for Sparkfun's AVC. I decided to use a Raspberry Pi Model A+ as my embedded platform with an Arch Arm distro installed on it. All had been going quite well until I started working on the control software.

The Problem

Some time ago I stumbled across a fantastic driver written by richardghirst for the Raspberry Pi called servoblaster. Essentially, this driver enables the configuration and use of the Pi's GPIO header pins as PWM outputs. In other words, it allows you to easily drive R/C servos from the Pi with no additional hardware! This was exactly what I was looking for. There were two implementations of the driver, one kernel level, and another user level. richardghirst recommended the user level, so I decided to heed his suggestion.

At this time I began working on a simple UDP server that would run on the Pi. The server would allow me to control the car remotely over WiFi. This is what the beginning of that server looked like.

int main(int argc, char* argv[])
    // open socket, setup sockaddr_in structure
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in addr = { };
    addr.sin_family      = AF_INET;
    addr.sin_port        = htons(atoi(argv[1]));
    addr.sin_addr.s_addr = INADDR_ANY;

    printf("Setup using port %d\n", ntohs(addr.sin_port)); // say what port

    assert(sock > 0); // sanity check

    // bind the process to the desired port
    int res = bind(sock, (const struct sockaddr*)&addr, sizeof(addr));
    assert(res >= 0); // sanity check

    // start up the control module, and servoblaster

    // ...

In the function call conInit() the driver daemon is started with the following calls.

    // does the servo blaster device exist? (is the driver running?)
    if(!stat("/dev/servoblaster", &buf)){
        fprintf(stderr, "Servo driver already running\n");
    // execute the servo blaster daemon
    else if(system("servod --p1pins=37,38")){
        fprintf(stderr, "Failed to start servo driver\n");
        return -1;

Here, the program first looks to see if the driver has been started. It assumes if the device file exists, then the driver is live. Otherwise it attempts to start it with the call system("servod --p1pins=37,38").

This is where the problem was. If the driver isn't running and system("servod --p1pins=37,38") is called it forks a new child process. When that occurs all open file descriptors in the host process are automatically inherited by the child. So that means...

    int sock = socket(AF_INET, SOCK_DGRAM, 0);

is thus inherited by the child process, which in this case is the servo driver. But because the driver is a daemon it will keep running after the UDP server has shut down. This means, the servo driver will keep sock open and bound to the port specified above. Which will result in an EADDRINUSE errno if a bind() to that port is attempted again.

The Solution

After some searching I found that luckily this was a very easy fix. It came down entirely to adding one function call shortly after opening the socket.

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    fcntl(sock, F_SETFD, fcntl(sock, F_GETFD) | FD_CLOEXEC);

The fcntl function is used to get and set properties of file descriptors. The current flags of sock are retrieved with the fcntl(sock, F_GETFD) call. Those flags are then or'ed together with the flag FD_CLOEXEC. Here's what the man pages say about that flag.

                Close-on-exec; the given file descriptor will be auto-
                matically closed in the successor process image when
                one of the execv(2) or posix_spawn(2) family of system
                calls is invoked.

Perfect! That was exactly the behavior that I had needed. And sure enough the server worked as intended. So much so that I could drive my car around from my laptop :)

A video posted by Kirk Roerig (@mrpossoms) on