…at least not in an embedded environment.

There’s a commonly held myth in modern software development that compilers are smarter than people at optimising code for its eventual runtime environment. By extension there’s no point in writing efficient code, because your idea of efficient code might not actually be all that efficient, and any time spent on doing that is wasted because the compiler will know better. This post is about one of those times when that’s not true. Functionally identical code can end up compiling into very different binaries, and that can lead to significant differences in resource usage on the target environment. That might not matter on a PC with a multi core multi GHz CPU and many GB or RAM, but it can make the difference between working and not working in an embedded environment – the kind of environment that the Internet of Things is being built out of.

The back story

A couple of years ago I did a simple project with my kids to make little boards that would flash their names in morse code. It used the cheap ($4.30) and popular TI MSP430 LaunchPad development kit. The code to do the morse bits was fugly but it worked.

Some time later my friend Andy Bennett asked me why I’d coded the project the way I had. The honest answer was that I’d been pretty lazy and cut’n’pasted the whole thing together, but for good measure I threw in a comment that I thought it would be easy for the compiler to digest and turn into an efficient binary for the highly constrained target environment of a low end MSP430 chip.

I’m still not quite sure whether Andy set out to prove me right or wrong, but I’m impressed by the effort and rigour that he put into his subsequent investigations. Some time later he presented his findings at OSHUG #25 (pdf slides).

The (more elegant) alternatives

Andy created three additional versions of the morse code flasher program (I’ve put all four into this Github repo – EmbeddedMorse). I think anybody with the slightest sense of smell around code would argue that all three are better than my original (#2). #1 and #3 make much better use of C data structures, #3 has some clever bit mapping of morse characters, and #4 uses a switch statement instead of many extra functions.

If the myth of compiler omnipotence held true then all four examples would have compiled down into the same binary for the MSP430.

They didn’t – it turns out that the compiler can be led astray.

A quick detour into a limited memory map

The MSP430G2211 device that I used has 2kB of Flash and 128 Bytes of RAM – so anything that’s going to change at runtime (variables) needs to fit into that 128 Bytes and everything else can be accommodated in the more generous 2048 Bytes of Flash. The actual memory map for an MSP430 device (or any other microcontroller for that matter) is a bit more complex, due to memory mapped peripherals etc., but that matters less when it comes to squeezing some code in.

Memory sections of compiled programs

A compiler will generate binary code to fit into various different sections such as .text (machine instructions), .data (static data such as constants) and .bss (space for variables).

For the compiled program to fit onto the device then .bss must go inside 128 Bytes and .text and .data combined can’t exceed 2048 Bytes.

Here’s what the compiler actually produced

Example .text .data .rodata .bss
1 391 832 156 0
2 1122 0 0 0
3 422 26 44 0
4 844 0 796 0

The first notable thing is that they’re all different – the compiler hasn’t spotted that the code is functionally identical, and it’s compiled it into different shaped binaries.

The second notable thing is that they all should work – none of the code uses any .bss, so that tiny 128 Bytes of RAM shouldn’t be an issue.

The only one that does work is #2, and it’s pretty obvious why that is – the entire compiled output is .text, which can go into flash.

It’s less clear why the other three examples don’t work:

#1 – if .data goes into RAM rather than flash then it’s clearly going to break past the 128 Byte limit

#4 – if .rodata goes into RAM rather than flash (which it totally doesn’t need to) then it will also break the 128 Byte limit

#3 – even if the .data and .rodata go into RAM then it’s only 70 Bytes, so there are 58 Bytes left. In theory that should be plenty, but in practice… some further analysis needed to figure out why it breaks.

Conclusion

Compilers aren’t as smart as people make out. Functionally identical source code can lead to very different binaries, and that can matter a lot in a constrained environment.

I didn’t know any of this when I wrote my initial implementation, and it’s just good luck that I picked an approach that worked first time. If it hadn’t then I might have done battle with the compiler for some time, or I might have given up and found an easier platform to get it working on.


I’ve been a big fan of Koss Spark Plug earbuds for many years. They’re cheap, comfortable and sound great. I got my first set after some very expensive Sony noise cancelling earbuds failed on my (just after the warranty ran out), and it was obvious straight away that a good snug fit was an excellent substitute for active noise cancelling.

As I find myself using Skype and Google Voice from my laptop (and my new phone) a lot for calls these days I’ve found that the built in microphone picks up too much noise, so I got the iSpark as an alternative. It’s basically the same headphones I’ve come to love with the Spark Plugs, but with the addition of a microphone and push switch. The microphone seems to work very well for calls, and the push switch is handy for pausing shows I’m watching on my iPad.

Although they’re marketed to go with the iPhone these things seem to work with anything that has a 3.5mm jack for combined headphones and microphone. They also come with a handy little carry pouch, so I’m more likely now to just pop them in my pocket rather than having them sat in the bottom of my bag.


TL;DR

The S4 mini is a fantastic piece of kit. The size is right, the screen is vibrant, the battery lasts, it works fine as a phone. The *only* thing I might ask for as an improvement would be a higher resolution screen. Dual SIM is very nice too.

Background

2 years is too long for a phone upgrade cycle, and I’d let it go even longer than that with my iPhone 4. It was frankly always a pretty useless phone, but it’s been a very nice pocket computer. I’ve started to need a phone that actually works recently, and ended up switching to my old San Francisco (ZTE Blade) as my primary phone – swapping the data only SIM I had for it over to the iPhone. The Blade was pretty satisfactory, but a three year old low end phone was really only good for emails and voice – I needed something newer for apps. I backed the Ubuntu Edge, but ultimately $32m was too much of an ask for the community – so that’s not happening. I waited for the iPhone 5s and 5c to launch, and decided I wanted neither (or perhaps I just wasn’t prepared to pay *that* much of a premium for an iPod touch with a modem in it).

Goldilocks screen size

I went for an S4 mini rather than the full S4 (or a Nexus 4) because my pockets just aren’t big enough. I generally have a tablet or two within reach if I want more screen real estate, so I want a phone rather than a phablet.

Enough performance

The S4 mini has a dual core 1.7Ghz CPU, which is a lot less than its big brother’s quad core 1.9GHz processor. It doesn’t matter – it’s plenty fast enough for anything I’ve tried to do with it. Everything feels snappy.

Relatively unmolested Android

If there was a Nexus version of the S4 mini Duos then I’d have tried to get it – I’ve yet to see anything that a manufacturer (or worse still an operator) has tried to add to stock Android that’s actually made it better rather than worse. Luckily Samsung don’t seem to have messed with Android too badly (or at least not badly enough to make me want to switch straight away to CyanogenMod).

Dual SIM

The ‘Duos’ naming means that the GT-I9192 can take two (micro) SIM cards. I’m finding this pretty useful for a couple of reasons:

  1. The most obvious is when travelling. I’m in the US right now, and have my T-Mobile PAYG SIM card in the phone so that I’m paying 10c/min rather than £1/min.
  2. Back at home I’m running a GiffGaff SIM in the second slot. Pretty much my whole family now use GiffGaff, and it means that they can call and text me for free (whilst I wait for my Vodafone contract to expire[1]).

The software makes it pretty easy to choose which SIM is used. One can be selected as default, but the phone dialer and text messaging app offer two buttons for dial/send so the right SIM can be used.

The one trade off with this model is that it doesn’t have LTE. I’m not that bothered as I don’t use any services that support yet.

Cost

The handset was £295 on eBay. Most of them seem to be coming from Singapore, but I paid a local UK supplier to avoid hassles with shipping and customs. Delivery was advertised as being 10 days, but I had it in my hands 2 days later :)

I’ve ordered a top of the range 64GB microSD card to supplement the 8GB internal memory (and 16GB microSD that I had lying around). It cost £34.99, which seems a whole lot more reasonable than the £160 premium for a 64GB iPhone 5s.

Leaving the iOS ecosystem

I’ve had feet in both camps (iOS and Android) for a few years now, so the new phone has been more of a transition than a switch. The only thing that I’ve left behind is TomTom. I bought the navigation apps for W Europe and USA & Canada a few years ago to use on my iPod Touch, and it was great to keep using them when I got an iPhone (along with a handy windscreen mounting widget from eBay). I may yet get TomTom for Android – I’m just not in a desperate hurry to re-buy £50+ of apps (and I’m also waiting for that 64GB microSD card so I have plenty of space for my music and apps).

Overall

I’m still in the honeymoon period, but so far I’m loving the S4 mini Duos.

Notes

[1] It was a mistake to sign up for another year with Vodafone just to get reasonable roaming rates in Europe. I’d almost certainly have been better off switching sooner to GiffGaff and putting up with whatever their deal is for roaming.


Now that OpenELEC 3.2 is out the dev team are moving to 3.3 (which will eventually become stable as 3.4).

The dev team have asked me to wait until things are more stable (for around 4 weeks) before doing more builds from the master branch.

The dev team have also made a decision to remove .bz2 compression. Let me know if you’d rather stick with tar.bz2, or go with the flow to straight .tar files (which are about 10MB bigger)?


Yesterday I wrote about how Google Wallet is even worse than PayPal. A quick reminder:

  1. When I buy stuff on PayPal I don’t have to pretend to have a billing address in a different country. They’re quite happy for me to use my UK issued card for payments to US suppliers.
  2. I don’t recall ever having a PayPal transaction cause an issue with Amex.
  3. The PayPal resolution process only required me to submit one form of ID.
  4. The PayPal resolution process completed same day.
  5. I’m not dependent on PayPal for Google services (like renewing Google Apps domains or buying apps or content on my Android phone/tablet).

The saga continues…. The good news is that it didn’t take 3-5 days to get a response. The bad news is that they’ve rejected my proof of ID as being inadequate.

They asked for a scan of my credit card statement with the first 12 numbers blanked out:

Wallet_first_12

This I did. As it’s an Amex card, which has 15 digits, this left 3 digits showing.

Now they email saying that they want the last 4 numbers visible.

Wallet_last_4

Make you minds up guys. If you don’t give me clear resolution instructions, then your response makes you look like dicks.

For extra irony I should point out that my full credit card number without any digits blacked out was at the bottom of the scan – where’s the harm – they have the whole number anyway.

There’s another possible twist here… As I used a supplementary card for the recent transaction I can’t possibly send a statement with that number. It just doesn’t exist – the statements only carry the number of the main card. (I’ve written before on the topic of additional cardholders being a weeping sore in the security model for online payments).

I’ll try a utility bill.

Congratulations Google – you’re the topic for my 300th blog post.

PS I should have added to my post yesterday that when I bought an iPad online from the US Apple Store and had it shipped to my friend in Virginia I had no trouble whatsoever (and Apple didn’t make me use iTunes to pay for it ).

Update 13 Sep 2013

Once again Google have replied within a day, but once again it’s not good news. They’re insisting on a statement showing the additional card number, which simply doesn’t exist:

wallet_must_have

I’ve (once again) resubmitted my documents, this time with the following comment:

The last transaction on my account was made using an additional card. The numbers for additional cards are not shown on my statement, and therefore I have no way of supplying the information you’re now insisting on.

I’ve done my best to comply with this process, but you’re now asking for stuff that I (or anybody else ever using an additional card) cannot provide. So we meet an impasse.

I have proven my identity. I have proven my address. Amex approved the payment (second time around after I’d been through their fraud prevention false positive hoops).

What now? Do I have to abandon my Google Apps and stop using Android phones because I can’t pay for anything with Wallet any more?

I have a Google apps domain that’s due for renewal next Tuesday (17th) and I have no way to pay for that. Suggestions?

I predict this won’t end well.

My plans to get a Nexus 7 LTE (and a Galaxy S4 mini) are now on hold – what’s the point in having Google devices if they shut down the means to pay for anything?

Update 18 Sep

No word from Google – the daily back and forth seems to have stopped.

It seems that I’m not alone having this kind of problem when buying Nexus products. It also seems that Google is systematically unable to do anything about such issues.

Update 22 Sep

I’ve called Google Wallet support twice in the last couple of days. The first agent (Neysa) told me to send in a photo of my additional card. This didn’t help. The second agent (Jamie) told me that she couldn’t do anything to help as it was ‘a different department’.


I spent Saturday manning the @BrightonPi stand at Brighton Mini Maker Faire showing off various projects with Gareth James. It was great fun, and I really enjoyed talking to people about the potential of the Raspberry Pi.

There were a few questions that got asked a lot… hence this post.

The projects

I was showing off 80’s joystick with 80’s arcade game, OpenELEC, Ladder Board and a Sous Vide water bath. $son0 was adding the RPi camera to his alarm project (and generally messing around with Scratch).  Gareth brought along his timetable and secret squirrel.

1. Where can I buy a ladder board?

The Raspberry Pi ladder kit is a great introductory physical computing project, and can easily be made by kids who’ve learned to do basic soldering. It’s available online from Tandy (though sadly out of stock at the time of writing).

2. What’s that game (being projected onto the wall)?

It’s Targ, and it should be available for download from the MAME web site ROMs page (though sadly the download link seems to be broken at the moment). The classic 80’s gameplay proved too difficult for many modern gamers, and nobody made it to level 3 on the day (or set a high score). Gareth and I were amused to see a succession of kids holding the joystick upside down..

If you want to run MAME (and other classic games emulators) on your Pi then the easiest way is probably PiMAME.

3. What WiFi adaptor are you using?

I use the Edimax EW-7811UN as it’s small, inexpensive, and works easily and reliably with Raspbian and OpenELEC.

Any more?

I think that’s it for the frequently asked questions. If you have any more then please ask in the comments.


I’ve seen a ton of bad news stories about PayPal over the last few years – here are just the top three from my payments tag on pinboard.in. I’ve even run afoul of their over sensitive fraud detection myself in the last couple of months (whilst trying to buy Club Penguin subscriptions for my kids whilst travelling[1]). Today’s experience with Google Wallet is much worse than anything I’ve personally seen with PayPal.

NOFORN. Google don’t want me to buy one of these. NOFORN

I want to buy a new Nexus 7 LTE (as my original Samsung Galaxy Tab 3G is feeling very old and creaky these days, and the 2013 Nexus 7 has received rave reviews). I want the LTE version as I know from using 3G on my existing tab that I need data on the go. Having just been launched, the LTE version isn’t yet available for me at home in the UK. No problem, I’m over in the US at the end of the month, and I can get it shipped to one of my friends that I’ll be seeing. No problem perhaps with almost any retailer except Google Play. I should have known better from my last dreadful experience trying to buy Nexus 7s from the Play store.

The trouble started with ‘no supported payment method’ showing when I went to check out. Google Wallet doesn’t straight out tell you that you need a US billing address to order in the US, but it doesn’t take much searching to find that’s the case. Time for the supplementary card dodge (I’ve used this one before)… I register another card with a US address (of the company I work for) and now I can place my order.

Payment is declined, as the hair trigger of Amex’s fraud detection has been set off. This is sadly pretty much the norm, so I called up Amex, jumped through their security hoops and resubmitted the payment through Google Wallet. All looked good.

And then Google suspended my Google Wallet account and cancelled the order for my Nexus 7.

I’ve submitted scans of government issued ID and credit card statements (in a process not dissimilar to the one PayPal made me go through), and I’ll now wait the 3-5 business days for the issue to be resolved. Hopefully it will be at the early end of that scale as I need my account back in good standing for a domain renewal that’s due next Tuesday (4 business days away).

So how’s this worse than PayPal? Let’s count the ways:

  1. When I buy stuff on PayPal I don’t have to pretend to have a billing address in a different country. They’re quite happy for me to use my UK issued card for payments to US suppliers.
  2. I don’t recall ever having a PayPal transaction cause an issue with Amex.
  3. The PayPal resolution process only required me to submit one form of ID.
  4. The PayPal resolution process completed same day.
  5. I’m not dependent on PayPal for Google services (like renewing Google Apps domains).

Looks like I should just ask my friend to order my new tablet and pay him good old cash.

Notes

1. I suspect that PayPal use IP address geolocation as part of their fraud countermeasures, and that I mess things up by using a mix of US and UK IPs. It’s worth noting here that Google seem to treat Amazon EC2 IPs as being outside the US, so you can’t even try to buy things from the US Play store by using EC2 as a web proxy (but they’re fine with Google Compute Engine IPs – so they get my 2¢).


A friend of mine recently returned from working in the US for 3 years, where he’d got to like listening to Internet radio using Pandora. He wanted to get things set up so that he could listen to Pandora on his kitchen stereo.

Challenge #1 – be in the US

Pandora uses IP geolocation to restrict service to US IPs, so we needed a point of presence in the US. After signing up to Amazon Web Services (AWS) a t1.micro machine running in their free tier provided the requisite local IP address with access over SSH and OpenVPN.

We then configured FoxyProxy to send *.pandora.*/* to a SOCKS proxy running on PuTTY that was in turn connected to the Amazon machine and music streamed.

Challenge #2 – make it elegant

Getting Pandora on a laptop was fine, but it wasn’t connected to the kitchen stereo, and hooking it up would be a inelegant mess.

We tried repurposing some old iPhones, but they were too old to run the Pandora or OpenVPN apps.

We then tried using an Android tablet, which was able to work fine with the Pandora and OpenVPN apps from the Play store, but it looked a bit precarious sat up by the stereo, and I was worried that it was only a matter of time before the tablet would be hurtling towards the kitchen floor.

A Raspberry Pi tucked behind the stereo seemed like a much more elegant approach, and luckily my friend had one sat in a box waiting for its first project.

Three steps to success

To make the Raspbeery Pi work we needed network connectivity, VPN connectivity and a Pandora client:

1. Network connectivity

The kitchen stereo was nowhere near my friend’s router, so a cabled connection to the Pi wasn’t an easy option. I did suggest using some Powerline adaptors, but WiFi using a USB adaptor was going to be cheaper. Sadly he didn’t have an (ever reliable) Edimax EW-7811Un WiFi on hand, and I hadn’t brought one with me. We picked up a TPLink TL-WN725N from a local store after confirming that it worked with the Raspberry Pi.

Sadly the TL-WN725N we got didn’t work out of the box with (Jul 2013) Raspbian, but luckily putting the right drivers in place was not too hard (thanks to the pi3g blog):

wget http://resources.pichimney.com/Drivers/WiFi/8188eu/8188eu-20130209.tar.gz
tar -xvf 8188eu-20130209.tar.gz
sudo install -p -m 644 8188eu.ko /lib/modules/3.6.11+/kernel/drivers/net/wireless
sudo depmod -a
sudo modprobe 8188eu
sudo ifdown wlan0
sudo ifup wlan0

With that down the Pi was then available over WiFi.

2. OpenVPN

The OpenVPN client is a standard Raspbian repository, so:

sudo apt-get install -y openvpn

Then copy the client.ovpn file from the OpenVPN server to /etc/openvpn/client.conf

I didn’t want the openvpn to start on boot (as it was prompting for username and password) so the service was set to manually start:

sudo update-rc.d -f openvpn remove

With that done the tunnel could be brought up with:

sudo service openvpn start

and I could confirm that it was working by:

wget http://ipecho.net/plain -O – -q ; echo

and observing the US IP address of the AWS EC2 virtual machine.

3. Pandora client

There’s a command line client for Pandora called pianobar, which is part of the standard Raspbian respository:

sudo apt-get install -y pianobar

It needs a small config file in place before it works:

mkdir -p ~/.config/pianobar
echo ‘user = YOUR_EMAIL_ADDRESS‘ >>  ~/.config/pianobar/config
echo ‘password = YOUR_PASSWORD‘ >> ~/.config/pianobar/config

Make sure to substitute your own email address and Pandora password in the lines above. The following needs to be entered on a single line:

fingerprint=`openssl s_client -connect tuner.pandora.com:443 < /dev/null 2> /dev/null | openssl x509 -noout -fingerprint | tr -d ‘:’ | cut -d’=’ -f2` && echo tls_fingerprint = $fingerprint >> ~/.config/pianobar/config

To make sure that audio comes out of the 3.5mm jack on the Pi:

sudo amixer cset numid=3 1

At this stage pianobar can be run (and if all is right a list of channels will appear):

pianobar

Success :)

With the Raspberry Pi plugged into the kitchen stereo we could now listen to my friend’s favourite stations.

Improvements

Adafruit make a Raspberry Pi WiFi radio kit that adds buttons for channel selection and a dot matrix screen to show track info. I should also investigate web and mobile clients, but a command line station selection seems good enough.

Conclusion

The Raspberry Pi makes a good receiver for Pandora Internet radio, wherever you might be.


I got an email from my bank yesterday telling me that they’re rolling out two factor authentication (2FA) to protect their my money from fraudsters. It looks like a pretty standard one time password (OTP) based scheme that will have a choice between mobile and physical tokens. They’re being pretty inflexible about the deployment model by enforcing a one person one token approach, but that’s pretty normal behaviour[1]. They’re also offering a token free option for low risk transactions[2], but it’s unclear whether you have to choose ahead of time that you have no token or if you can do low risk transactions without using the token.

The problem with mobile tokens

The crypto wonks will tell you that mobile OTPs are less secure than physical ones because the mobile OS is vulnerable leaving the private key (aka seed) for the OTP vulnerable. This is mostly theoretical nonsense, and in the real world mobile OTPs have proven resilient whilst some physical schemes (I’m looking at you SecurID) have fallen victim to attacks.

The real problem with mobile tokens is that they break the separation between a second factor (something you have) and the transaction (something you’re doing). If the OTP is on my phone and somebody steals it (or pwns it) then they have the thing I’m supposed to have, and the whole scheme fails.

I spent a lot of time in my last job trying to figure out ways to elegantly combine mobile banking with something else that you might reasonably be expected to carry around (mobile, wallet, keys)[3], and NFC seems to be the way to go (if only Apple weren’t missing the point about NFC).

It’s not clear yet whether the mobile user experience will involve going to one part of the app to get an OTP then go to another part of the app to enter it, but too many systems do that. Another example of security theatre as an audience participation event.

How’s the Twitter scheme better?

Firstly I should point out that the Twitter scheme also relies on the mobile as token, so it does nothing to help with the stolen/pwned phone problem.

As explained in this Wired article (thanks to Bruce Schneier for the pointer) the Twitter scheme is able to carry a bunch of (transaction related) metadata that can be presented to the user as part of the authentication process. In many ways this is a software equivalent of schemes that use hardware tokens to sign transaction summaries.

Best of all the Twitter scheme doesn’t involve the user in reading off then typing in sequences of random numbers (which nobody likes doing, particularly on the glass keypad of a mobile device).

One perceived weakness of the Twitter scheme is that it relies on connectivity, but you can’t do online banking without connectivity, so that’s probably a false concern. Twitter also have a neat new take on strike lists as a fall back.

Why does this matter?

We’re entering a phase where the social networks are starting to do a better job of protecting our identity/security than the banks. This could be a sign that for the average person their online persona is more valuable than the contents of their chequeing account.

I think it also means that the banks are out of the game when it comes to federated identity, which is a shame as it means their ceding what was a natural advantage in stronger proofing mechanisms and customer trust[4].

Conclusion

Twitter are doing a better job of 2FA implementation than my bank, and I’m using my bank as a reference example of most banks – there are precious few that are even trying to be better. The social networks are winning on user experience and winning on security. This will have consequences in ecosystems based on trust.

Notes

[1] The exceptions I can think of are PayPal, which allows a number of Verisign Symantec OTPs to be registered (though it seems nobody told their mobile web/app designers, so it totally fails there), and systems like Google Authenticator where the private key is generated giving the opportunity to register the key with as many devices as you can reach at the time.
[2] Pretty much the universal definition of low risk transactions is making payments to previously registered payees (and viewing account statements/balances). Sending money to new people is (quite rightly) deemed high risk. Bad implementations that I’ve seen often make it so changing the reference for past payees is also considered high risk – not a problem if your reference is a customer number, a pain if your reference is an ever changing invoice number.
[3] There’s a problem looming here. In Singapore the trend is towards card entry for homes – no keys, and in Hong Kong the trend is towards card payment for everything – no wallet (the card is often placed in a mobile phone cover. The overall trend is towards leaving the home with just one thing – the phone – as it takes over the roles of keys and wallet.
[4] Though how much customer trust remains post 2008 is a different question.