Skip to content

Instantly share code, notes, and snippets.

@DblD
Last active June 11, 2019 19:56
Show Gist options
  • Save DblD/93429352ecf4e0ff7bce97901290a035 to your computer and use it in GitHub Desktop.
Save DblD/93429352ecf4e0ff7bce97901290a035 to your computer and use it in GitHub Desktop.
Yes we can - aka pick your favourite language and make it "script able"

Linux kernel magic

In Linux we can load and execute any file with its executable bit set. Thanks to the linux kernel binfmt_misc module we can dynamically extend and add support for varaitey of executable formats directly from userspace using well defined and documented procfs interface.

Making Golang our scripting language of choice

We can achive this by making binary format descriptions for our .go files. To do this we need to ensure we have special binfmt_misc filesystem mounted to /proc/sys/fs/binfmt_misc. Any relativly reacent Linux system should already have this mounted. So to check this, run following :

$ mount | grep binfmt_misc
systemd-1 on /proc/sys/fs/binfmt_misc type autofs (rw,relatime,fd=27,pgrp=1,timeout=0,minproto=5,maxproto=5,direct)

Our script should return correct exit codes, so we will user gorun wrapper as our "interperter".

$ go get github.com/erning/gorun
$ sudo mv ~/go/bin/gorun /usr/local/bin/

Register our new Go script binary format:

$ echo ':golang:E::go::/usr/local/bin/gorun:OC' | sudo tee /proc/sys/fs/binfmt_misc/register
:golang:E::go::/usr/local/bin/gorun:OC

When the system successfully registeres the format, a new file golang should appear under /proc/sys/fs/binfmt_misc directory.

Now we can create our golang script, set executable bit, modify to our liking and changes will be in affect next time the file is executed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment