Building Android from source

Building Android from source seems like a daunting task at first, but it’s really not that hard. I’ll walk through the steps as simply as possible to get your first AOSP build running on your handset. This is a rite of passage for many, and guaranteed to give insights on the inner workings of Android. First, let’s do a few push-ups and jumping jacks to mentally and physically prepare for the journey, and at the end of it, you’d wonder why you even had to do that.

What you need:

  • A 64-bit environment
  • ~150 GB of disk space
  • A working Linux installation (I use Debian, but take your pick). I suggest going with bare metal over virtual machines in the interest of sanity and general well being
  • A decent broadband connection (to download a significant portion of the internet)
  • Some time and patience
  • A healthy belief in the supernatural, and their inevitable involvement in the building of large complex codebases

Everything you need to know about the process is right here. Feel free to skimp through these docs first to get an overview of the entire process. What’s below is mostly a summary + a few things not explicitly mentioned that would stump the newbies.

Step 1

Prep your OS and install any dependencies. At the minimum you’re going to need java, python, C/C++, make, and git so make sure they’re installed using your favorite package manager. If you’re on Debian/Ubuntu, you’d run something similar to below:

sudo apt-get install openjdk-8-jdk git-core gnupg flex bison gperf build-essential zip curl zlib1g-dev gcc-multilib g++-multilib libc6-dev-i386 lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z-dev ccache libgl1-mesa-dev libxml2-utils xsltproc unzip

If you find that you need something else down the line that’s not mentioned above, be a man/woman, and just apt-get it. Also, your package names may vary depending on your choice of distribution.

Run the commands manually to do a quick sanity test that things are installed properly.

Step 2

Linux may require some configuration to udev to allow non-root users to work with USB devices, which is going to be required later on, so execute this command:

wget -S -O - | sed "s/<username>/$USER/" | sudo tee >/dev/null /etc/udev/rules.d/51-android.rules; sudo udevadm control --reload-rules

Step 3 (Optional)

Setup ccache to get extract some performance out of the build, by putting the following into your .bashrc:

export USE_CCACHE=1
export CCACHE_DIR=/path/to/empty/ccache/directory/where/cache/is/kept

Set the cache size to 50G using the following:

prebuilts/misc/linux-x86/ccache/ccache -M 50G

Step 4

The Android Open Source Project is a behemoth of a code base with multiple third party open source components and frameworks included such that it required its own layer on top of git just to manage the dependencies. That’s what repo is. On the positive side, it’s quite easy to get it working.

Download the repo tool to your ~/bin directory as follows:

$ curl > ~/bin/repo
$ chmod a+x ~/bin/repo

Make sure that ~/bin is in your $PATH. Type repo a few times and watch it barf in your face while saying:

error: repo is not installed.  Use "repo init" to install it here.

Do not fret, this is normal.

You see, you have to initialize repo and give it a manifest which will tell repo where to download the source from and help it initialize itself. You do this by navigating to an empty directory and executing:

repo init -u

If you do not specify a branch name with -b parameter, it will fetch the master branch, which is what we’re going to do here.

You should now see an empty directory, apart from a .repo with the metadata that it downloaded from the manifest file. Now I’m assuming that you’re probably at home and do not have complicated proxy arrangements to get to the internet so I’m going to avoid talking about the HTTP_PROXY environment variable that you have to set if you do, but I guess it’s all redundant now that I’ve already said it, so I’m just going to move on:

repo sync

This will download the internet. This will run for an inordinate amount of time. A few things you can do while this executes:

  • knit
  • write a book
  • have kids
  • watch the poles melt

A rough approximation, and the internet is very divided on this topic, is that it will require anywhere from 12 to 15 GB which will automatically expand to around 34GB on disk after it’s downloaded. In my experience, I’ve only been awake till about the 13GB mark, so didn’t quite get to see the transformation to its final glory. Add 50GB for the ccache and with some room to spare and you see why you need a lot of disk space to go through this.

Now you wait.

Step 5

In my case, I needed to run the build on my Nexus 5. The AOSP source tree doesn’t have everything you need to build images specifically for Nexus 5, so I had to go to this link, scroll down to Nexus 5 and download the Broadcom, LG and Qualcomm binary blobs for the hardware on the Nexus 5. Put them in the root of the Android source tree, and execute it, where it self extracts. This is a needed step if you want to run the image on the device later on.

Step 6

Now comes the compilation step. This is actually the easiest part.

Initialize the build environment by sourcing a script, you can use the bash source command or the good old dot command – whatever strikes your fancy:

. build/

This will inject a bunch of build related environment variables to your current shell. Note that you have to run this in every shell that you want to run a build from.



This will give a list of targets and allow you to select one. In my case, I selected “aosp_hammerhead-userdebug”. Hammerhead being the code name for the Nexus 5.

One more step, and that’s to start the build.

time make -j4

You could easily just say “make”, but I would like to know how long the build took when it eventually finished running, and with the -j4 flag indicate the concurrency level for make (rule of thumb: 2 x number of cores). Now you can go for lunch.

Things to do while this runs:

  • Read Game of Thrones (all the books)
  • Have a fabulous mid-life crisis
  • Watch Lawrence of Arabia

To be fair, it’s not that bad, just a few hours depending on your setup.

Step 7

Once the building is done, you will have a bunch of files under out/target/product/{device} which you can now start flashing.

Connect your Android phone to the computer and assuming that all the drivers and Android SDK is setup (a dependency that I somehow failed to mention before), you should be able to run the following command:

adb reboot bootloader

This can also be achieved by shutting down the device and starting it while pressing a combination of buttons (such as volume down + power on the Nexus 5). This would put you into fastboot mode. On the fastboot screen, pay attention to whether the bootloader is locked or not, if it is, execute the following to unlock it:

fastboot oem unlock

This would wipe the data on the device. To further clean things up, execute the following:

fastboot format cache
fastboot format userdata

Step 8

Navigate once again to the out/target/product/{device} directory and execute the following to flash the built images to the device:

fastboot flash boot boot.img
fastboot flash system system.img
fastboot flash userdata userdata.img
fastboot flash recovery recovery.img

Reboot the device and you’re all set.

This is just the tip of the iceberg, and hopefully you’ll be able to now play with the internals of Android to understand how things are really stitched together. Good luck on your journey.

Getting setup with the Intel Edison

Edison in handIntel Edison is an adorable little system on a chip packed with all the wireless and processing capabilities to build wearables and smart things. It features a dual-core Intel Atom processor @ 500 MHz, integrated Bluetooth 4 and wifi, USB controllers, 1GB of RAM and 4GB of eMMC flash memory, all in a tiny package. It also features a 32-bit onboard Intel Quark @ 100MHz that can be used as a micro-controller. Unlike the Raspberry Pi, it has no video output capabilities however. It runs Linux, specifically, Yocto Linux that is especially targetted for embedded systems.

If you’re interested in getting to know the Edison, I suggest purchasing a kit such as the Xadow wearable kit for the Intel Edison, which comes with a bunch of sensors and modules that you can use to build some useful applications. It comes with:

  • mini expansion board (a much smaller alternative to the Arduino expansion board),
  • barometer
  • 0.96″ OLED
  • vibration motor
  • NFC sensor with 3 programmable tags
  • a touch sensor
  • 3-axis accelerometer
  • buzzer
  • SD card module
  • breakout board
  • Li-Po battery
  • LED strip
  • FFC and power cables

All in all, a fairly comprehensive set of modules for a hobbyist connected device or wearables project. The kit does NOT include the Edison itself, which needs to be purchased separately. The folks at SparkFun has created a stackable set of “blocks” that can be used to build small form factor devices in a quite ingenious manner.

Fun fact: the Edison is powered by 3.3 to 4.5v and supports 40 GPIO pins that use 1.8v logic.

Step 1: To get started, take out the Xadow expansion board from the kit. It features a 70-pin hirose connector on the back where the Edison can be attached.

Expansion board and edison

Step 2: Place the Edison on top and press until you hear a click. You should then have a fairly firmly attached Edison to the Xadow expansion board.

Edison attached to expansion board

Step 3: Take the Xadow programmer module and a FFC (Flat Flexible Connector) cable from kit, flip open the connector locks on both the programmer module and expansion board. Place the FFC connector as shown below and close the connector lock to keep it in place. It should now look a little like what you see below. Flip the switch that’s highlighted in the red circle to the right, towards the “Device” label indicated by the arrow.

Programmer module and expansion board

Step 4: Connect two micro-USB cables to the connectors on the programmer module and the other end to the computer. This should power up the Edison.

Step 5: Head over to Intel to download and install the IoT Developer Kit for your operating system. As part of the installation process, it will flash your Edison with Yocto. I’ll be covering the flashing process and Yocto in a little bit more detail in a later post, but for now, let Intel do the magic for you.

Step 6: Your Edison should be mostly setup now. There’s one last thing you may want to do, which is configure it to connect to your home wifi. You should see the boards all lit up by now:

Edison all set

At this point, the only way to connect it to is via a serial connection made possible through the USB port by FTDI drivers installed with the IoT developer kit. In fact, on the mac, you should see a device such as /dev/cu.usbserial-* which will be used to initiate this serial connection.

To get a shell on the Edison, just run:

screen /dev/cu.usbserial-DA00ZEOX 115200 -L

Which will initiate a serial connection to the Edison at a baud rate of 115200. Press RETURN a couple times and you should see something like this:

Poky (Yocto Project Reference Distro) 1.6 edison ttyMFD2

edison login: 

Enter ‘root’ for the login and you’ll be dropped into a root shell on the Edison. By default it does not have a password. You may also notice that the first character that you type is lost in some occasions. This is due to the Edison being on low power mode at the time that causes the first character to be lost, before it spins up the device.

One thing to note is that exiting a ‘screen’ session is not as straightforward as a telnet or ssh session. You will need to type CTRL-a followed by CTRL-\ to get a prompt to exit the session.

Finally, to configure wifi on the Edison, run configure_edision –wifi command:

Configure Edison: WiFi Connection

Scanning: 1 seconds left

0 :     Rescan for networks
1 :     Manually input a hidden SSID
2 :     ZTE
3 :     ninsei

Enter 0 to rescan for networks.
Enter 1 to input a hidden network SSID.
Enter a number between 2 to 3 to choose one of the listed network SSIDs: 3
Is ninsei correct? [Y or N]: y
What is the network password?: ********
Initiating connection to ninsei...
Done. Network access should be available shortly, please check 'wpa_cli status'.
Connected. Please go to in your browser to check if this is correct.
root@edison:~# ping
PING ( 56 data bytes
64 bytes from seq=0 ttl=58 time=32.917 ms
--- ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 32.917/32.917/32.917 ms

This allows you to ssh into your Edison over wifi using:

ssh root@

And you’re all set. Yocto comes preloaded with Node and gcc, so now you have in your hands a network enabled system on a chip for building that next great smart device.

On key signing and trust

Key signing is a hallowed tradition in the open source world with a very specific protocol for validating and confirming an identity before accepting someone to the web of trust. It’s almost never done without meeting the person being admitted into the trust relationship and it goes like this:

  1. Individuals meet for a beer, or at a key signing party (for those who just went wtf, yes, these things are real, and they are crazy fun! see below for the type of shenanigans that take place at these reality-altering parties)
  2. They exchange strips of paper or business cards with their name, email address, key fingerprint and key ID
  3. They validate each other’s identity using Government issued photo IDs
  4. Once cleared, they pull down each other’s key from the key servers
  5. They validate that the fingerprint of the downloaded key matches what’s written on the piece of paper and the photo IDs exchanged at introduction
  6. If everything checks out, they sign each other’s key
  7. For additional security, the signed key is encrypted using the public key of the recipient and emailed to the address indicated in the key

Let’s look at this unnerving and highly nerdy exchange that has replaced the “Hi, I’m Tom” with “Hi, I’m Tom and here’s my fingerprint and Government issued photo Id”. Here’s the rationale for some of the steps in this workflow.

The key is a personal identification and privacy instrument that is backed by strong science to assure non-repudiation. I will not go into the science in this post, but here’s where you may want to get started if you’re curious. An aspect about this workflow is that nothing is trusted until verified and the protocol is there to make sure that no compromise takes place.

At the beginning of the process, the public key is expected to be on a public key server network (such as and the meeting in person is to make sure that the key you’re signing (which is on a public system) belongs to the correct individual and not to an individual (or three letter agency) who’s masquerading as someone else. The most secure way to ensure that is in person (because we’re a paranoid bunch), as that will eliminate any chance of a malicious man in the middle. When one produces the piece of paper with the key fingerprint (again backed by strong science) the signer is able to confirm by comparing the fingerprint on the public server with the fingerprint that’s presented in person along with the official photo id, that the public key really belongs to the individual before him/her. The connection has now been made and technology has once again prevailed in mathematically assured validation of another’s identity. The party is just getting started.

Once identity is validated this way, the signer signs the key and uploads the key back to the key server or emails a copy of it. This can be done after the party in a more subdued setting without crazy paper shuffling and photo id validation madness. The astute and more paranoid amongst us, would encrypt it using the public key of the key being signed and email it to the address specified in the key because that’s a good way to validate the email address is correct and belongs to the right user. For the gnupg commands that make this workflow possible, check out the Debian Key signing howto.

In communities such as Debian, this process is mandatory to assure the trust in a system that is largely de-centralized. The Web of Trust that this creates gives rise to a truly magnificent network, which is difficult to subvert so long as the protocol is followed to ensure no compromise.

While this is good for cryptographically assured validation of one’s identity in a global network and non-repudiation of one’s contributions and electronic communications, trust is ultimately a very subjective attribute and probably can never be assured through a hash, because trust can be broken by people even though strong science says otherwise.

On Perl and Poetry

I first learnt of Perl in the late 90’s. Sometime around ’98 or ’99. Fresh on the heels of BASIC, I was yearning to try out something new when I heard of Perl. I heard it’s what the Internet ran on and it had an almost mythical air to it that made me want to learn it. If you wanted to build dynamic web sites at that time, you had few options, and Perl, Apache and UNIX was the workhorse. I wanted to build dynamic web sites so what I had to do was pretty clear. There was a new fangled thing called Java, but no way was it ever going to catch up to the dominance that Perl had over the Internet. Or so people thought.

Perl was the undisputed king of Internet 1.0. The language, with it’s knack for text processing coupled with it’s highly expressive syntax was ideal for building dynamic web sites. I saw how entwined Perl was in the UNIX sub-culture and how naturally it fit in, and together with Apache/mod_perl how it was poised to reign over the Internet for years to come. I then drifted into the world of enterprise Java and progressed from the monstrosity that was J2EE to the present day JEE, which has since redeemed itself and paid for it’s early sins, and when I came back several years have passed and Perl has been relegated to the position that new kids considered old and dead. However, nothing could be further from the truth.

In the often misunderstood syntax of Perl by those new to the language, who claim it to be cryptic or arcane, there’s an elegance and a beauty that is not always present in other languages and I find that I enjoy hacking on a Perl script more than chipping away at the Java mega-structures. It’s expressiveness and how you can mold the code to fit your pattern of thought by the many variations and permutations the language syntax offers plays a large part in this sense of aesthetic. There’s something about the language that’s reminiscent of a Bach fugue and poetry. I certainly do not feel the same way about Python, although Ruby comes a little close.

I don’t think I will ever stop coding Perl, and Perl 6 has a number of interesting language elements that I hope someday I will get to see, possible running on a GNU/HURD. Now wouldn’t that be a sight to behold?

To beacon, or not to beacon

The more I look into Bluetooth LE and beacon technology, the more I’m convinced that we’ve stumbled upon something very interesting and, even, *ahem* disruptive. I’m a bit reluctant to use the word “disruptive” as it has lost some of its meaning due to gross overuse, but I believe it describes the technology well. The wireless technology has being around for over a decade, but is now coming to the foreground specially on the micro-location front, which is showing a lot of promise. On another note, building a beacon using a Raspberry Pi seemed like an interesting project until I discovered that Bluetooth 4 USB modules are virtually non-existent in Sri Lanka. 

The PayPal beacon is a wonderful example of this at work. It’s very exciting to think about the possibilities that this could unleash. PayPal’s hands-free payments is completely re-defining the payment experience in a very novel way. It gets even more interesting when companies start carving out their own territories around this, as evidenced by Apple’s patent filings. My disgust for patents and the associated territorial pissing which in my opinion hinders innovation, is best left for another post.