fix numerous ffi bugs

There were double-free and race condition bugs.
In addition, updated coding style a bit.

Signed-off-by: Jan Dvořák <mordae@anilinux.org>