code: mafs

ref: 0325bdc87b12a33c16b792c6ed50400b8ffce325
dir: /misc.c/

View raw version
#include <u.h>
#include <libc.h>
#include "dat.h"
#include "fns.h"

s8 envpidx = -1;		/* the index in _privates holding the Errenv location. hack: hoping that this will be the same across all processes */
Errenv **envpp = nil;

void
chkrunlock(RWLock *q)
{
	if(q->readers <= 0)
		print("runlock(%#p): not locked: pc %#p\n",
			q, getcallerpc(&q));
	else
		runlock(q);
}

u8
chkwunlock(RWLock *q)
{
	if(q->writer <= 0){
		panic("wunlock(%#p): not locked: pc %#p\n",
			q, getcallerpc(&q));
		return 0;
	}
	wunlock(q);
	return 1;
}

void
chkqunlock(QLock *q)
{
	if(q->locked == 0)
		print("qunlock(%#p): not locked: pc %#p\n",
			q, getcallerpc(&q));
	else
		qunlock(q);
}

int
dprintfd(int fd, char *fmt, ...)
{
	static char buf[2048];
	static QLock lk;
	va_list va;
	int n;

	qlock(&lk);
	va_start(va, fmt);
	snprint(buf, 2048, "%d %llud: %s", getpid(), nsec(), fmt);
	n = vfprint(fd, buf, va);
	va_end(va);
	qunlock(&lk);
	return n;
}

int
dprint(char *fmt, ...)
{
	static char buf[2048];
	static QLock lk;
	va_list va;
	int n;

	qlock(&lk);
	va_start(va, fmt);
	snprint(buf, 2048, "%d %llud: %s", getpid(), nsec(), fmt);
	n = vfprint(2, buf, va);
	va_end(va);
	qunlock(&lk);
	return n;
}

void
panic(char *fmt, ...)
{
	char buf[8192], *s;
	va_list arg;


	s = buf;
	s += sprint(s, "%s %d: ", argv0, getpid());
	va_start(arg, fmt);
	s = vseprint(s, buf + sizeof(buf) / sizeof(*buf), fmt, arg);
	va_end(arg);
	*s++ = '\n';
	write(2, buf, s - buf);
	abort();
	exits(buf);
}

void *
emalloc(u32 sz)
{
	return mallocz((ulong)sz, 1);
}

int
waserror(void)
{
	Errenv *env = _privates[envpidx];
	++env->nlabel;
	return setjmp(env->label[env->nlabel-1]);
}

void
poperror(void)
{
	Errenv *env = *envpp;
	--env->nlabel;
}

void
nexterror(void)
{
	Errenv *env = _privates[envpidx];
	longjmp(env->label[--env->nlabel], 1);
}

void
error(s8 *fmt, ...)
{
	Errenv *env = _privates[envpidx];
	va_list arg;
	char buf[ERRMAX];

	va_start(arg, fmt);
	vseprint(buf, buf+ERRMAX, fmt, arg);
	va_end(arg);
	errstr(buf, ERRMAX);
	nexterror();
}