Sunday, April 7, 2013

Shared Object with GHC 7

I was hitting my face on my desk for a few hours today trying to work this out. So here's my post to hopefully save anyone else who ended up stuck on this. I made a bash script to do it all, so here's the script. Note that this makes dynamic shared objects (.so files), still trying to figure out how to do it statically.

#!/bin/bash

TMPHELP="module_init.c"
FILENAME=${1%.*}
declare -i EXITCODE

cat <<TMPHELPER > $TMPHELP
#define CAT(a,b) XCAT(a,b)
#define XCAT(a,b) a ## b
#define STR(a) XSTR(a)
#define XSTR(a) #a

#include <HsFFI.h>

extern void CAT(__stginit_, MODULE)(void);

static void library_init(void) __attribute__((constructor));
static void library_init(void) {
    /* This seems to be a no-op, but it makes the GHCRTS envvar work. */
    static char *argv[] = { STR(MODULE) ".so", 0 }, **argv_ = argv;
    static int argc = 1;

    hs_init(&argc, &argv_);
    hs_add_root(CAT(__stginit_, MODULE));
}

static void library_exit(void) __attribute__((destructor));
static void library_exit(void) {
    hs_exit();
}
TMPHELPER

ghc -O2 --make -dynamic -shared -fPIC $2 -o "${FILENAME}.so" -optl-Wl,-rpath,/usr/lib/ghc/ -lHSrts_debug-ghc7.4.1 $1 $TMPHELP  >&1

EXITCODE=$?

set -x

if [[ $EXITCODE -eq 0 ]] ; then
    rm "${FILENAME}.hi"
    rm "${FILENAME}.o"
fi

if [[ -f ${FILENAME}_stub.h ]] ; then
    rm "${FILENAME}_stub.h"
fi

rm $TMPHELP
exit $EXITCODE

I'm honestly not 100% sure how everything works, but my main goal was to create shared objects so I could use them in Python. One thing to note if you are loading a shared object into Python made with Haskell, the IO functions don't seem to display on IDLE (works fine on the terminal).

No comments:

Post a Comment

Tag Cloud

.NET (2) A+ (5) ad ds (1) addon (4) Android (4) anonymous functions (1) application (9) arduino (1) artificial intelligence (1) backup (1) bash (6) camera (2) certifications (3) comptia (5) css (2) customize (11) encryption (3) error (13) exploit (5) ftp (1) funny (4) gadget (4) games (3) GUI (5) hardware (16) haskell (6) help (14) HTML (3) imaging (2) irc (1) it (1) java (2) javascript (13) jobs (1) Linux (19) lua (1) Mac (4) malware (1) math (6) msp (1) network (13) perl (2) php (3) plugin (2) powershell (8) privacy (2) programming (24) python (10) radio (2) regex (3) repair (2) security (16) sound (2) speakers (2) ssh (1) story (5) Techs from the Crypt (5) telnet (1) tools (13) troubleshooting (11) tutorial (9) Ubuntu (4) Unix (2) virtualization (2) web design (6) Windows (16) world of warcraft (1) wow (1) wx (1)