Skip to main content

Papers, please

via GIPHY

Regulatory prep

Canada is, of course, a different country. And, it inconveniently lies between the "lower 48" and Alaska. This post is less narrative, and more of a checklist and brain-dump for what I'll need for ADIZ crossings, and clearing customs in both countries.

Useful Links and resources

Documentation and regulations

  • [x] Pilot Certificate
  • [x] Medical
  • [x] Passports
  • [x] Airworthiness certificate
  • [x] Registration
  • [x] Operating limitations
  • [x] Weight and Balance
  • [x] Radio Station License
  • [x] Restricted Radio Telephone operator Permit
  • [x] Public Liability Insurance (See Insurance)

CBP Decal and fee

(e)Fee for arrival of a private vessel or private aircraft -

(1)Fee. Except as provided in paragraph (e)(3) of this section, the master or other person in charge of a private vessel or private aircraft must, upon first arrival in any calendar year, proceed to CBP and tender the sum of $27.50, as adjusted in accordance with the terms of paragraph (k) of this section, to cover services provided in connection with all arrivals of that vessel or aircraft during that calendar year. Either a properly completed CBP Form 339V (Annual User Fee Decal Request - Vessels) or CBP Form 339A (Annual User Fee Decal Request - Aircraft), must accompany the payment. Upon payment of the annual fee, a decal will be issued to be permanently affixed by adhesive to the vessel or aircraft, in accordance with accompanying instructions, as evidence that the fee has been paid. Except in the case of private aircraft, and aircraft landing at user fee airports authorized under 19 U.S.C. 58b, all overtime charges provided for in this part remain payable notwithstanding payment of the fee specified in this paragraph.

(2)Prepayment. A private vessel or private aircraft owner or operator may, at any time during the calendar year, prepay the $27.50 annual fee specified in paragraph (e)(1) of this section, as adjusted in accordance with the terms of paragraph (k) of this section. Prepayment must be made in accordance with the procedures and payment methods set forth in this paragraph and paragraph (i) of this section. The decal request and prepayment by credit card or ACH debit may be made via the Internet through the “Travel” link at the CBP Web site located at http://www.cbp.gov. Alternatively, prepayment may be sent by mail with credit card information, check, or money order made payable to U.S. Customs and Border Protection, along with a properly completed CBP Form 339V (Annual User Fee Decal Request - Vessels) or CBP Form 339A (Annual User Fee Decal Request - Aircraft), to the following address: U.S. Customs and Border Protection, Attn: DTOPS Program Administrator, 6650 Telecom Drive, Suite 100, Indianapolis, IN 46278.

Aircraft

  • [x] ELT (121.5 still OK)
  • [x] Mode C

eAPIS and Flight plans

Use an ICAO flight plan (I already do this anyway)

Provide CANPASS more than 2, but less than 48 hours notice of entry

Provide US CBP more than 1, but less than 24 hours notice of entry

ATC Fees

Canada charges $17.85 for ATC services per quarter.

Insurance

Canada requires liability insurance as documented in the Canadian Aviation Regulations section 606.02(1).

Liability Insurance 606.02 (1) This section applies to every owner of an aircraft, other than a remotely piloted aircraft, that is registered in Canada or registered under the laws of a foreign state and operated in Canada, if the owner is not required to subscribe to liability insurance in respect of the aircraft under section 7 of the Air Transportation Regulations.

(2) Doesn't apply?

(3) Doesn't apply?

(4) Doesn't apply?

(5) Doesn't apply?

(6) Doesn't apply?

(7) Doesn't apply?

(8) No aircraft owner not referred to in paragraph (2)(a), (b) or (c) shall operate an aircraft unless, in respect of every incident related to the operation of the aircraft, the owner has subscribed for liability insurance covering risks of public liability in an amount that is not less than

(a) $100,000, where the maximum permissible take-off weight of the aircraft is 1 043 kg (2,300 pounds) or less;

(b) $500,000, where the maximum permissible take-off weight of the aircraft is greater than 1 043 kg (2,300 pounds) but not greater than 2 268 kg (5,000 pounds);

(c) $1,000,000, where the maximum permissible take-off weight of the aircraft is greater than 2 268 kg (5,000 pounds) but not greater than 5 670 kg (12,500 pounds);

(d) $2,000,000, where the maximum permissible take-off weight of the aircraft is greater than 5 670 kg (12,500 pounds) but not greater than 34 020 kg (75,000 pounds); and

(e) $3,000,000, where the maximum permissible take-off weight of the aircraft is greater than 34 020 kg (75,000 pounds).

(9) Subject to subsection (10), no owner or operator of an aircraft shall operate the aircraft unless there is carried on board the aircraft proof that liability insurance is subscribed for in accordance with this section.

(10) Doesn't apply.

Let's get the GEAR

via GIPHY

Background

We're flying ourselves to Alaska. This is the first in a series of posts about our planning, preparing, flying, and touring the great state of Alaska. We're jumping right in with packing...

We've never been light packers. This is more true for Katie than Will, but when we travel we tend to take all the things. We have one of those rolling suitcase sets that includes a giant case (good luck keeping it less than 50 pounds) and a carry-on. We'd easily fill the large one, and the carry-on. Then we'd each have backpacks for under our seats, and Emma would have her own trunki

Trunki Suitcase

Because we're flying ourselves, and flying into small municipal airports, our usual overpacking wasn't going to work. For one thing, the baggage compartment of the Cirrus is not that large.

Cirrus Cabin

The big suitcase does fit (but only just). Finally, and most importantly, the indignity of showing up in small Alaskan towns dragging around a rolling suitcase it just too much to bear.

Suitcase in mud

Travel Backpacks

So, Katie did a ton of research. She came across the Pack Hacker blog and geeked out. We kinda settled on getting a travel backpack each. I had a backpacking backpack before, but the travel ones are more optimized for motorized travel, and less for hiking under your own power. I'll share the short-list of options she came up with:

Katie's:

Will's:

Emma:

Osprey FarPoint 55REI RuckPack 40Osprey HydraJet 15

Of course, no amount of planning and research is too much to just throw it all out and get something else when you actually get to the store. So, I got the Osprey Farpoint 55, and Katie got the REI Ruckpack 40. I'm hoping that I can get away with carrying-on my pack on my commercial flights for work, which I take about once-a-month. It's a few inches too-long for Alaska Airlines, but I'm hoping that they let me get away with it. The main selling point for me is that it has a zip-off day pack, and I intend to use that for my under-seat stuff (Laptop, headphones, and iPad). We did end up getting Emma the Osprey Jet, but it ended up being the HydraJet. The HydraJet is just what REI had in stock, and turns out she loves the water bladder.

Capsule Wardrobe

Packs are only one piece of the puzzle, though. To pack lighter, you have to pack less. So, another thing Katie came across in her research is the travel capsule wardrobe. The idea behind the capsule wardrobe is a collection of a small number of essential items that don't go out of fashion, can be mixed-and-matched, and travel well. So, for travel, we chose mostly black and grey clothes made of merino wool. Merino Wool is naturally odor resistant. This is a pretty big deal for us, because we're pretty obsessively clean, and do not like re-wearing dirty clothes. I think it's going to be a bit of an adjustment, but that's how we're packing, so we'll have to deal.

Compression bags

Another way we're trying to maximize packing space is via compression bags. These are very thin nylon (like parachute fabric) bags with zippers that compress-down the contents.

Will's things unpackedWill's things baggedWill's things packed

Initial testing with Will's pack turned out pretty well

Complications

One of the biggest complications we're facing for this trip is that Will has to travel to Mass. for most of the week prior to our departure. He arrives home late on August first, and we leave for Alaska on the second. To stay safe, we're going to sleep-in and take it kinda easy on the first day. What that means is that he has to pack for both trips prior to departing to Mass. Luckily he has just enough underwear! 😆

Conclusions

This is all we're taking ... those three packs ... for 12 days. This is unprecedented for us. Of course, the lie in that statement is that the airplane survival pack (with camp stove, water, tent, sleeping bag, etc.) life vests, boots, airplane emergency pack (oil, tools, windshield cleaner, etc.) will be coming along for the ride as well. I'll update you with the eventual weights of everything, and a weight and balance report.

SwiftVision Supplemental Materials

Swift Vision

Recently, I posted a "short" video about the CM5 lights and transcribing their states automatically in Swift. Here is a link to the github repository. I've just committed an update that includes and enables "Mode 5″ of the LED panel, in addition to the "Mode7″ that I had before.

For fun, here's a new histogram of the mode 5 video, which I captured on aniPad.

histogram

Also, the timeline for mode 5 (really more a function of the lighting and ipad)

timeline

What I'm sure iskunk and Mark are really after is the transcribed animation steps: Mode 5

Netboot Debian Sid on Nvidia TX1

This is a follow-on to my last post and to the excellent instructions at the nvidia forums. The purpose to writing it again here is to mostly keep a recipe for myself and others. It may be possible to replace the rootfs from Linux 4 Tegra using this method, and I'm going to try that.

Pre-requisites:
  • X86-64 machine running Ubuntu 14.04
  • Micro USB cable
  • Nvidia TX1
  • 16+ GB SD Card (may be optional)
  • 3.3 volt TTL-level usb serial port installed on ttyS0
Background and Considerations

The general theory of operation is to use the Debian netboot/netinstall initrd image. This image is enough to begin the install process using internet-sourced packages. There is no netboot server required in this case. The last post used the Jessie distro's initrd, and I'm going to try the Sid one this time. As I said, no net boot server is required. So, to get the initrd onto the device, we'll put it in the boot directory of the factory mmc image. Then, we can modify the boot configuration file to boot using the initrd. Once it has booted into the installer, we should be able replace the contents on the mmc rootfs.

Steps on the x86_64 machine

  • Login and download and install the L4T package.
  • Download the ARM64 Sid net install initrd.
  • Unpack, apply_binaries.sh, and repack the initrd following these instructions.
  • Open a serial terminal for the TX1′s serial port and reboot the TX1
  • At the uBoot prompt of the TX1 enter UMS mode
  • Mount the TX1 rootfs, and copy the new initrd into /boot
  • Edit the /boot/extlinux/extlinux.conf to add the reference to the new initrd.
  • Backup the entire /boot directory from the TX1.
  • Reboot the TX1 and allow u-boot to run the autoboot
  • In the next boot menu (extlinux) choose your new netboot option
Steps on the TX1
  • Choose your locale settings
  • Select the network interface that looks most like eth0 and configure
  • Follow the instructions normally until you get to partitioning
  • DO NOT CHOOSE GUIDED PARTITIONING
  • Select Manual partitioning
  • select the APP partition (of mmc0 or mmc1, mmc0 is on-board)
  • Use as Ext4
  • Format
  • Mount as root
  • "Done setting up this partition"
  • Finish and write to disk
  • Accept that no swap space is used.
  • Wait for the installation to finish (mine hung making install log)
  • Reboot
Back on the x86-64 machine:
  • In the serial terminal, re-start UMS mode
  • Re-mount the root file system
  • Re-run the apply-binaries.sh, but on the mounted TX1 root filesystem this time
  • Copy the /boot/extlinux folder from your backup of boot into the new /boot
  • Unmount and reboot

64-bit userspace on Nvidia TX1

I've been having trouble getting a 64-bit userspace up on the Nvidia TX1 (Linux4Tegra uses 32-bit), so I thought I'd share my progress and steps.

See the end of this post for a comment about how I actually got this working. These instructions don 't work as they are, but I'm leaving them here for posterity.

To begin with, I use Debian (or Ubuntu, or whatever) for most of my work, so that's what this guide will be based on. Also, you'll need to have another drive to use with your TX1. Linux4Tegra (L4T) will be installed on the on-board MMC device, and we'll be installing Debian Sid on the other drive.

You'll need to copy the extensive partition scheme that Nvidia builds on theMMC (there's something like 8-9 partitions) onto your target drive. I do this by dd'ing the entire MMC onto the target

sudo dd if=/dev/mmcblk0 of=/dev/mmcblk1 bs=4096

Then we need to mount the root filesystem on the target device somewhere

sudo mkdir /mnt/rootfs
sudo mkfs.ext3 /dev/mmcblk1p1
sudo mount /dev/mmcblk1p1 /mnt/rootfs

Debootstrap will do the work of making the new (very minimal) root filesystem.It's very important to include the -arch flag, otherwise the bootstrap process will generate a rootfs using armhf, and we'll be stuck with a 32-bit userspace again.

sudo apt-get install debootstrap
sudo debootstrap -arch=arm64 sid /mnt/rootfs http://debian.osuosl.org/debian  `

As I said the rootfs will be VERY minimal, so we need to install tons of important stuff, including locales, keyboard maps, ssh server, etc… But, before we do that we have to chroot into the new rootfs:

sudo mount -o rbind /dev rootfs/dev
sudo mount -t proc none rootfs/proc
sudo mount -o bind /sys rootfs/sys
sudo chroot rootfs /bin/bash
source /etc/profile
apt-get update
apt-get install
ssh openssh-server
make gcc libncurses5-dev bc locales
dpkg-reconfigure locales

Then, we need to add information about the network interface to/etc/network/interfaces:

auto lo
iface lo inet loopback`

allow-hotplug eth0
iface eth0 inet dhcp`

The current linux-upstream kernel has support (though apparently, rudimentary)for the TX1. This should obviate the need for the binaries supplied with L4T.So, let's clone the kernel repo and build one.

cd /usr/src
git clone git://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.gitlinux-next
cd linux-next
cp /proc/config.gz ./
gunzip config.gz
cp config .config
make oldconfig (press enter until it's done)
make menuconfig
  (in General Setup, select "open by fhandle syscalls")
  (in Drivers->General, delete all the extra firmware names listed)
make
cp build

Next, we have to copy the entry that selects the boot mode in /boot/extlinux/extlinux.conf and edit it to select our new rootfs. We'll leave the old one there so we can swift back and forth. This is especially helpful if something breaks.

LABEL debian
MENU LABEL debian kernel
LINUX /boot/Image-next
FDT /boot/tegra210-p2371-2180.dtb
APPEND fbcon=map:0 console=tty0 console=ttyS0,115200n8 tegraid=21.1.2.0.0 ddr_die=2048M@2048M ddr_die=2048M@4096M section=256M memtype=0 vpr_resize usb_port_owner_info=0 lane_owner_info=0 emc_max_dvfs=0 touch_id=0@63 video=tegrafb no_console_suspend=1 debug_uartport=lsport,0 earlyprintk=uart8250-32bit,0x70006000 maxcpus=4 usbcore.old_scheme_first=1 lp0_vec=${lp0_vec} nvdumper_reserved=${nvdumper_reserved} core_edp_mv=1125 core_edp_ma=4000 gpt root=/dev/mmcblk1p1 rw rootwait

The last thing to do in the chroot is to set the root password to something, and allow (for now, change it later!!) root login over ssh:

passwd
vi /etc/ssh/sshd_config

PermitRootLogin yes

Now, we need to really dive into to some somewhat painful work. We have to setup a serial console onto the board, and have another computer (specifically a x86-64 machine running Ubuntu 14.04) to run the L4T apply_binaries.sh tool.First, the serial port connection is explained at elinux. Then, you need open a serial terminal to the board with 115200 baud. Once that's done, reboot the board, and prevent u-boot from auto booting. In the uboot console, enable the USB Mass Storage mode:

Tegra210 (P2371-2180) # ums 0 mmc 1 UMS: disk start sector: 0x0, count: 0x39f0000

Then, with the usb cable connected from the TX1 to your x86-64 box runapply_binaries.sh:

sudo mount /dev/sdg1 /mnt/rootfs/
sudo LDK_ROOTFS_DIR=/mnt/rootfs ./apply_binaries.sh
sudo umount /mnt/rootfs

The problem I've been having is that the USB keyboard that I have doesn't work on the console. It's obviously a HUGE bummer to not be able to login to a machine using the console. 😡

I ended up following these instructions to net-install debian arm64 on my SD card. The limitation here is that most of the things that makes this an Nvidia device (GPU, CUDA, etc) don't work. For my needs, I only want a Arm64 to work on a Swift port, soI don't care.

References:

Getting started with Swift and Raspi V.2

While progress with Swift on ARM has been very encouraging, there have been a few reports of people having trouble with it. This post is intended to be a step-by-step, starting with a brand-new Raspberry Pi version 2 and a freshly-made Raspian image (note that other distributions might work, I've only verified raspian).

Setup the raspberry pi

I expect that you can ssh to your raspberry pi (hereto referred to as raspi),and that you've run the raspi-config utility.

First, you need to expand the range of debian repositories in order to access the required prerequisites. To do that, edit /etc/apt/sources.list:

sudo nano /etc/apt/sources.list

and uncomment the last line in the file, which should look like this:

deb-src http://archive.raspbian.org/raspbian/ jessie main contrib non-free rpi

Then, you'll need to update your repositories.

sudo apt-get update

Install prerequisite software

Once that's complete, install clang

sudo apt-get install clang

Option 1: install from tarball

A tar of the swift installation (usually more up to date) is available from my website. You can install this in either your system root, or from another directory. I do all of my testing with it installed in the system root, and therefore things are more likely to work. However, you're putting your system at more risk by doing that. Keep in mind, though, that you're playing around with alpha-level software on your <$100 computer… YOLO.

cd /
sudo wget http://housedillon.com/other/swift-armv7.tar.gz
sudo tar -xzpf swift-armv7.tar.gz
rm swift-armv7.tar.gz    

Option 2: install with Joe Bell's repo

Joe @iachievedit did a fantastic job creating a debian repository for the swift compiler and tools, and he's hosting it in an amazon aws instance. Taking this route has some huge advantages. First among them is that they're only updated when things are stable-ish. The version hosted at my website can change frequently, and it might even be completely broken!

Rejoice!

Now, assuming that everything went according to plan, you should be able to compile programs written in swift. Also, you should be able to use glibc andFoundation.

pi@raspberrypi:~ $ cat hello.swift
import Glibc
import Foundation
let now = NSDate()
print("Hello world at \(now)")
pi@raspberrypi:~ $ swiftc hello.swift
pi@raspberrypi:~ $ ./hello
Hello world at 2016-01-09 05:36:31 +0000
pi@raspberrypi:~ $ uname -a
Linux raspberrypi 4.1.13-v7+ #826 SMP PREEMPT Fri Nov 13 20:19:03 GMT 2015 armv7l GNU/Linux    

Not so fast

Ok, so there are some caveats. For one, it seems like the REPL is kinda broken on the Raspi v.2. Joe noticed this, too. I'm not sure what the root cause is for this one. It works on the original raspberry pi (armv6), and it works on the Beaglebone Black and Nvidia Tegra (armv7).

Also, things are very alpha-level, so expect the unexpected.

Swift available for Beaglebone/RasPi

I was able to succeed in building Swift and Foundation for Ubuntu on ARMv7.This includes the Beagle Bone/Board, the Raspberry Pi, Tegra TK1, Cubox, and so much more…

This is more-or-less alpha-level at this point, but you should be able to compile and run basic swift programs that use the standard library, Glibc, orFoundation. Keep in mind that, even for x86_64, Foundation is far from complete.

To install, you can either un-tar in your root directory (which will install into /usr) or, create a new directory in /opt (for example /opt/apple, or/opt/swift) and update your paths. If you choose to install into /usr you're running a much greater risk to your system, and you had better be willing tore-install if from scratch!! :)

Once it's installed, give swiftc a try:

wdillon@arm:~$ cat hello.swift
print("Hello world!")
wdillon@arm:~$ swiftc hello.swift]
wdillon@arm:~$ ./hello
Hello world!
wdillon@arm:~$ uname -a
Linux arm 4.1.12-ti-r29 #1 SMP PREEMPT Tue Nov 10 00:38:08 UTC 2015 armv7l armv7l armv7l GNU/Linux
wdillon@arm:~$    

You can download the file here.

If you want to contribute to the effort, there are still a few tests that fail in stdlib that could be addressed, the swift package manager still doesn't work, lldb doesn't work, Foundation isn't finished, and it would probably be pretty great to have swift wrappers for GPIO pins and peripherals (such asSPI, I2C, etc.)

Building open source Swift on ARMv7

Apple recently open sourced their Swift language and compiler. I'm pretty excited about this (huge Swift fan), and I wanted t project to help motivate me to dig in. I also do a lot of work with embedded linux at work, so I'meager to use this great language there, too. So, I found an existing feature request in the issue tracker that Apple set up for swift. I was pleased that they had already given it 'medium' priority, but I know that if you want something to happen sooner than later, you should just start working on it.

I've done enough linux work that I know that if you start deviating from the officially supported distro. you start making work for yourself pretty quickly, so I decided to limit myself to only ARMv7 systems that I can get aUbuntu 14.04 image for. In my case that was a BeagleBone Black (BBB) and an Nvidia Tegra TK1. If you can, go with the Nvidia every time (The TX1 has 3GBof RAM). It's much faster, and has 2GB of RAM to the BBB's 512MB. Whatever amount of RAM you have (less than probably 16GB), you'll need to setup some swap space. Also, depending on whether you're using a SD card, you might need to set aside at least 8GB of space to store the source and build products.

utils/build-scrip

To begin with, we need to understand the build process. Apple's documentation makes it plain that you should use the utils/build-script script to build, and that any processes outside of that system aren 't supported:

For all automated build environments, this tool is regarded as the only way to build Swift. This is not a technical limitation of the Swift build system. It is a policy decision aimed at making the builds uniform across all environments and easily reproducible by engineers who are not familiar with the details of the setups of other systems or automated environments.

This script is responsible for parsing the arguments presented on the command line, printing help text, making build directories, and a prepares things for utils/build-script-impl. A read through it yields no information about architectures at all, so we move on to build-script-impl.

utils/build-script-impl

Most of the real work occurs in build-scipt-impl. Right away, we're presented with architecture specific parts.

LLVM_TARGETS_TO_BUILD="X86;ARM;AArch64″

This line sets a variable that will eventually tell the LLVM build process(several packages need to build to support Swift. One of those is LLVM, another is Clang) which architectures it should be able to generate machine code for.

This script is a little hard to follow because it's well over 1000 LOC, and there are functions mixed in with top level code. In this section, I'll trace the execution of the file rather than file order. I'll also omit anything that doesn't have a bearing on target/host architecture.

# A list of deployment targets to compile the Swift host tools for, in cases
# where we can run the resulting binaries natively on the build machine.
NATIVE_TOOLS_DEPLOYMENT_TARGETS=()
# A list of deployment targets to cross-compile the Swift host tools for.
# We can't run the resulting binaries on the build machine.
CROSS_TOOLS_DEPLOYMENT_TARGETS=()
# Determine the native deployment target for the build machine, that will be
# used to jumpstart the standard library build when cross-compiling.
case "$(uname -s -m)" in
        Linux\ x86_64)
            NATIVE_TOOLS_DEPLOYMENT_TARGETS=("linux-x86_64″)
            ;;        Linux\ armv7*)
            NATIVE_TOOLS_DEPLOYMENT_TARGETS=("linux-armv7″)
            ;;        Linux\ aarch64)
            NATIVE_TOOLS_DEPLOYMENT_TARGETS=("linux-aarch64″)
            ;;        Darwin\ x86_64)
            NATIVE_TOOLS_DEPLOYMENT_TARGETS=("macosx-x86_64″)
            ;;        FreeBSD\ x86_64)
            NATIVE_TOOLS_DEPLOYMENT_TARGETS=("freebsd-x86_64″)
            ;;
        *)
            echo "Unknown operating system"
            exit 1
            ;;
    esac    

This section of code determines what the native platform is, both in terms ofOS and architecture. The native tools deployment targets is an array of native targets. This could be something like building for multiple arm targets that(may) be binary compatible, like different hard(or soft)-float versions. The case block matches on the results of uname -s -m, which on most ARM platforms will return something like this: "Linux armv7l". You'll almost always see the 'l' after armv7. We don't want to be that specific, so we'll match just the armv7 part. The cross tools deployment targets variable is used to specify the cross compilers that should be built. However, we can't just put linux-armv7 into this list to build a cross compiler, not yet anyway:

# Sanitize the list of cross-compilation targets.
    for t in ${CROSS_COMPILE_TOOLS_DEPLOYMENT_TARGETS} ; do
        case ${t} in
            iphonesimulator-i386 | iphonesimulator-x86_64 | \
            iphoneos-arm64 | iphoneos-armv7 | \
            appletvos-arm64 | appletvsimulator-x86_64 | \
            watchos-armv7k | watchsimulator-i386)
                CROSS_TOOLS_DEPLOYMENT_TARGETS=(
                    "${CROSS_TOOLS_DEPLOYMENT_TARGETS[@]}"
                    "${t}"
                )
                ;;
            *)
                echo "Unknown deployment target"
                exit 1
                ;;
        esac
    done    

This code will trap on any entry in that array that isn't in the list above.It would probably be possible to add linux targets there eventually, but for now let's move on. I want a native compiler for ARM, not a cross compiler. The next thing that we come across is the determination of the platform for which we want the stdlib built for. This case, like the prior one, matches on armv7, and ignores the suffix.

# A list of deployment targets that we compile or cross-compile the
# Swift standard library for.
    STDLIB_DEPLOYMENT_TARGETS=()
    case "$(uname -s -m)" in
        Linux\ x86_64)
            STDLIB_DEPLOYMENT_TARGETS=("linux-x86_64″)
            ;;
        Linux\ armv7*)
            STDLIB_DEPLOYMENT_TARGETS=("linux-armv7″)
            ;;
        Linux\ aarch64)
            STDLIB_DEPLOYMENT_TARGETS=("linux-aarch64″)
            ;;
        Darwin\ x86_64)
            STDLIB_DEPLOYMENT_TARGETS=(
                "macosx-x86_64″
                "iphonesimulator-i386″
                "iphonesimulator-x86_64″
                "appletvsimulator-x86_64″
                "watchsimulator-i386″
                    # Put iOS native targets last so that we test them last
                # (it takes a long time).
                "iphoneos-arm64″
                "iphoneos-armv7″
                "appletvos-arm64″
                "watchos-armv7k"
            )
            ;;
        FreeBSD\ x86_64)
            STDLIB_DEPLOYMENT_TARGETS=("freebsd-x86_64″)
            ;;
        *)
            echo "Unknown operating system"
            exit 1
            ;;
    esac    

After skipping lots more functions, we come across the meat of the process.

#
# Configure and build each product
#
# Start with native deployment targets because the resulting tools 
# are used during cross-compilation.
for deployment_target in "${NATIVE_TOOLS_DEPLOYMENT_TARGETS[@]}" \
                         "${CROSS_TOOLS_DEPLOYMENT_TARGETS[@]}"; do
    set_deployment_target_based_options

    # ... skipped compile option flag management ...

    # Build.
done

function set_deployment_target_based_options() {
    llvm_cmake_options=()
    swift_cmake_options=()
    cmark_cmake_options=()
    swiftpm_bootstrap_options=()

    case $deployment_target in
        linux-x86_64)
            SWIFT_HOST_VARIANT_ARCH="x86_64"
            ;;
        linux-armv7)
            SWIFT_HOST_VARIANT_ARCH="armv7"
            ;;
        linux-aarch64)
            SWIFT_HOST_VARIANT_ARCH="aarch64"
            ;;
        freebsd-x86_64)
            SWIFT_HOST_VARIANT_ARCH="x86_64"
            ;;
        macosx-* | iphoneos-* | iphonesimulator-* | \
          appletvos-* | appletvsimulator-* | \
            watchos-* | watchsimulator-*)
            # ... snipped tons of cross-compile for Apple devices stuff ...
        *)
            echo "Unknown compiler deployment target: $deployment_target"
            exit 1
            ;;
    esac
}

The important thing here is that the build process runs in full for each native target and cross target. At the beginning of the process the set_deployment_target_based_options function runs, and it sets the host variant for Swift. Remember at this point, its target variant, not host variant.

The rest of the script does the work of testing, packaging, and installing.

CMakeLists.txt

The CMakeLists.txt file provides CMake instructions on how to actually build the tools using the flags and options determined by build-script and build-script-impl. I am far less than a novice in all things CMake, so please correct me if I make mistakes in this area, but this is what I 'm able to infer from what's happening.

Within CMakeLists.txt , we have to manually set CMAKE_SYSTEM_PROCESSOR unless the build is cross-compiled, or otherwise already set. In linux (andFreeBSD) it 's set to the value of uname -m; it 's just set to i386.

# Reset CMAKE_SYSTEM_PROCESSOR if not cross-compiling.
# CMake refuses to use `uname -m` on OS X
# http://public.kitware.com/Bug/view.phpid=10326
if(NOT CMAKE_CROSSCOMPILING AND CMAKE_SYSTEM_PROCESSOR STREQUAL "i386″)
  execute_process(
    COMMAND "uname" "-m"
    OUTPUT_VARIABLE CMAKE_SYSTEM_PROCESSOR
    OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()    

Later, we use the value of CMAKE_SYSTEM_PROCESSOR to determine what architecture to build. Remember that if we're not cross-compiling, its value is the host architecture. Also, note that cross-compiling is only available onDarwin (macosx):

# FIXME: separate the notions of SDKs used for compiler tools and target
# binaries.
if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
  set(CMAKE_EXECUTABLE_FORMAT "ELF")

  set(SWIFT_HOST_VARIANT "linux" CACHE STRING
      "Deployment OS for Swift host tools (the compiler) [linux].")

  set(SWIFT_HOST_VARIANT_SDK "LINUX")
  set(SWIFT_PRIMARY_VARIANT_SDK_default "LINUX")

  # FIXME: This will not work while trying to cross-compile.
  if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64")
    configure_sdk_unix(LINUX "Linux" "linux" "linux" 
      "x86_64" "x86_64-unknown-linux-gnu")
    set(SWIFT_HOST_VARIANT_ARCH "x86_64")
    set(SWIFT_PRIMARY_VARIANT_ARCH_default "x86_64")
  # FIXME: This only matches ARMv7l (by far the most common variant).
  elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l")
    configure_sdk_unix(LINUX "Linux" "linux" "linux" 
      "armv7" "armv7-unknown-linux-gnueabihf")
    set(SWIFT_HOST_VARIANT_ARCH "armv7")
    set(SWIFT_PRIMARY_VARIANT_ARCH_default "armv7")
  elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "aarch64")
    configure_sdk_unix(LINUX "Linux" "linux" "linux" 
      "aarch64" "aarch64-unknown-linux-gnu")
    set(SWIFT_HOST_VARIANT_ARCH "aarch64")
    set(SWIFT_PRIMARY_VARIANT_ARCH_default "aarch64")
  else()
    message(FATAL_ERROR "Unknown or unsupported architecture: ${CMAKE_SYSTEM_PROCESSOR}")
  endif()
# ... snipped FreeBSD and Darwin branches ...

To make sense of this we really need to dig into the implementation of the configure_sdk_unix macro in SwiftConfigureSDK.cmake, otherwise the arguments are just a bunch of "linux" strings with an arch. and a triple.

macro(configure_sdk_unix
    prefix name lib_subdir triple_name arch triple)
  # Note: this has to be implemented as a macro because it sets global
  # variables.

  set(SWIFT_SDK_${prefix}_NAME "${name}")
  set(SWIFT_SDK_${prefix}_PATH "/")
  set(SWIFT_SDK_${prefix}_VERSION "don't use")
  set(SWIFT_SDK_${prefix}_BUILD_NUMBER "don't use")
  set(SWIFT_SDK_${prefix}_DEPLOYMENT_VERSION "don't use")
  set(SWIFT_SDK_${prefix}_LIB_SUBDIR "${lib_subdir}")
  set(SWIFT_SDK_${prefix}_VERSION_MIN_NAME "")
  set(SWIFT_SDK_${prefix}_TRIPLE_NAME "${triple_name}")
  set(SWIFT_SDK_${prefix}_ARCHITECTURES "${arch}")

  set(SWIFT_SDK_${prefix}_ARCH_${arch}_TRIPLE "${triple}")

  # Add this to the list of known SDKs.
  list(APPEND SWIFT_CONFIGURED_SDKS "${prefix}")

  _report_sdk("${prefix}")
endmacro()

This macro sets a number of CMake variables that will be used in both the generation of the swift compiler as well as the standard lib. An interesting thing to note is that the 4th linux should probably be linux-x86_64 and linux-arm.

While building swift files, these variables are ultimately consumed in the cmake/modules/AddSwift file for a variety of tasks, such as finding the path to the libraries, setting sdk and target flags, etc. Not that in this module, what was ${prefix} becomes ${sdk}.

function(_add_variant_swift_compile_flags
    # … sniplist(APPEND result
        "-sdk" "${SWIFT_SDK_${sdk}_PATH}"
        "-target" "${SWIFT_SDK_${sdk}_ARCH_${arch}_TRIPLE}")
    # … snipped stuff about optimization, etc. …
endfunction()

function(_add_variant_link_flags
    # … snip_add_variant_c_compile_link_flags(
        "${sdk}"
        "${arch}"
        "${build_type}"
        "${enable_assertions}"
        result)

    if("${sdk}" STREQUAL "LINUX")
        list(APPEND result "-lpthread" "-ldl")
    elseif("${sdk}" STREQUAL "FREEBSD")
        # No extra libraries required.
    else()
        list(APPEND result "-lobjc")
    endif()
    # … snipendfunction()    

In cases where it's not obvious where control flow leaves you, especially with how CMake seems to make liberal use of globals, I find it helpful to grep for variable names. Doing so for SWIFT_SDK_${ led me to…

stdlib/public/runtime/CMakeLists.txt

Where I found this gem!

foreach(sdk ${SWIFT_CONFIGURED_SDKS})
  if("${sdk}" STREQUAL "LINUX" OR "${sdk}" STREQUAL "FREEBSD")
    foreach(arch ${SWIFT_SDK_${sdk}_ARCHITECTURES})
      set(arch_subdir "${SWIFT_SDK_${sdk}_LIB_SUBDIR}/${arch}")

      # FIXME: We will need a different linker script for 32-bit builds.
      configure_file(
          "swift.ld" "${SWIFTLIB_DIR}/${arch_subdir}/swift.ld" COPYONLY)

      swift_install_in_component(compiler
          FILES "swift.ld"
          DESTINATION "lib/swift/${arch_subdir}")

    endforeach()
  endif()
endforeach()

This FIXME is a big deal, because I hadn't found it before. I was having linker issues with my binary, and this holds some promise helping address that issue. I'll go ahead and add a check here, copy the 64-bit script and edit it for 32 bit.

foreach(sdk ${SWIFT_CONFIGURED_SDKS})
  if("${sdk}" STREQUAL "LINUX" OR "${sdk}" STREQUAL "FREEBSD")
    foreach(arch ${SWIFT_SDK_${sdk}_ARCHITECTURES})
      set(arch_subdir "${SWIFT_SDK_${sdk}_LIB_SUBDIR}/${arch}")

      if("${arch}" STREQUAL "arm")
        configure_file(
            "swift_32.ld" "${SWIFTLIB_DIR}/${arch_subdir}/swift.ld" COPYONLY)
      else()
        configure_file(
            "swift_64.ld" "${SWIFTLIB_DIR}/${arch_subdir}/swift.ld" COPYONLY)
      endif()

      swift_install_in_component(compiler
          FILES "swift.ld"
          DESTINATION "lib/swift/${arch_subdir}")

    endforeach()
  endif()
endforeach()

The 64-bit ld script is pretty small, and doesn't seem too intimidating (I've never seen an ld script before):

SECTIONS
{
  .swift2_protocol_conformances :
  {
    .swift2_protocol_conformances_start = . ;
    QUAD(SIZEOF(.swift2_protocol_conformances) - 8) ;
    *(.swift2_protocol_conformances) ;
  }
}
INSERT AFTER .dtors

The only problem is that it's far from obvious what needs to change when porting that to a 32-bit system!! My only guess is that 8*8 is 64-bits, so maybe that -8 needs to be a -4! :)

SECTIONS
{
  .swift2_protocol_conformances :
  {
    .swift2_protocol_conformances_start = . ;
    QUAD(SIZEOF(.swift2_protocol_conformances) - 4) ;
    *(.swift2_protocol_conformances) ;
  }
}
INSERT AFTER .dtors

Unfortunately, that got me nowhere. Anyway, I'm getting ahead of myself. Moving on…

stdlib/public/SwiftShims/LibcShims.h

This one is an easy one… All we have to do is make a new typedef for __swift_ssize_t for the 32-bit arm:

#if defined(__linux__) && defined (__arm__)
typedef      int __swift_ssize_t;
#else
 typedef long int __swift_ssize_t;
#endif

stdlib/public/stubs/Stubs.cpp

Next, we have to deal with the fact that a multiply with overflow is missing from what libgcc provides us. I'll leave this out for brevity, but basically I just copied an implementation from the compiler-rt project.

lib/Driver/ToolChains.cpp

ToolChains.cpp is an interesting one because it is responsible for linking the compiler pieces together when building swift applications. In the original version, the x86_64 path to the swift stdlib was hard-coded in there. Now, we just have to query the target triple, and select the correct path to the library.

- Arguments.push_back(      +    
-   context.Args.MakeArgString(Twine(RuntimeLibPath) + "/x86_64/swift.ld"));

~ becomes ~

+ Arguments.push_back(context.Args.MakeArgString(
+   Twine(RuntimeLibPath) + "/" + getTriple().getArchName() + "/swift.ld"));

Testing files

There were several files that affect the testing suite. This post is already way to long, so I'll leave those out. If you want to see all the changes I've made, checkout the commit:

Summary

This port is getting pretty close. My 32-bit linker script doesn't fix anything, and I'm still looking for other potential problems. But, for now I'm happy with the progress. I hope this helps anyone else exploring other ports.The 32-bit arm port is potentially the simplest possible one, because the older iPhones and iWatch use 32-bit arm chips.

Update 12/16/2015

I was able to fix the linking problem by looking at another exciting swift port (SwiftAndroid), and noticing that -Bsymbolc is being used in the AddSwift cmake module.

if("${sdk}" STREQUAL "LINUX")
    list(APPEND result "-lpthread" "-ldl" "-Wl,-Bsymbolic")
  elseif("${sdk}" STREQUAL "FREEBSD")
    # No extra libraries required.
  else()
    list(APPEND result "-lobjc")
  endif()

I added that to my copy of AddSwift, and it seems to work beautifully. I will do some more testing and clean up, and submit a new pull request.

$ cat hello.swift 
print("Hello world!")
$ swiftc hello.swift 
$ ./hello
Hello world!
$ uname -s -m
Linux armv7l

On advertising

This is going to be a simple and short post. In my circles in news and twitter, there's a lot of discussion about ad blocking (relating, it seems, to iOS9′s new content blocking features). I've been mulling the purpose of my blog and online advertising over the past few months, and I've come to the conclusion that the pittance that Google returns me for the privilege of running ads on my site isn't worth it. Therefore, I'm going to disable all theads on the site, which should improve load times and reduce general annoyance for the 1% of you that don't block them anyway! :)

If you enjoy what's on the site (even though I haven't posted in a while) feel free to donate via paypal using the link in the sidebar. If you don't feel like it, that's ok too!

Cheers!