#include <9pm/windows.h>
#include <9pm/u.h>
#include <9pm/libc.h>
#include "syscall.h"

typedef struct Frok Frok;
struct Frok {
	void (*fn)(void*);
	void *arg;
	int pid;
};

static DWORD WINAPI
froklaunch(void *a)
{
	Frok frok;

	frok = *(Frok*)a;
	free(a);

	_syscallinit(frok.pid);
	if(frok.pid != getpid())
		abort();
	(*frok.fn)(frok.arg);

	_exits("ffork");
	return 0;
}

int
ffork(int flags, void (*fn)(void*), void *arg, int stack)
{
	int pid;
	HANDLE h;
	Frok *frok;

	frok = malloc(sizeof(Frok));
	if(frok == nil)
		return -1;

	frok->fn = fn;
	frok->arg = arg;
	pid = rfork(RFPROC|flags);
	frok->pid = pid;
	h = CreateThread(nil, stack, froklaunch, frok, 0, nil);
	CloseHandle(h);
	return pid;
}