Plan 9 from Bell Labs’s /usr/web/sources/contrib/nemo/root/acme/msgs/src/util.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include <u.h>
#include <libc.h>
#include <bio.h>
#include <thread.h>
#include <plumb.h>
#include "dat.h"

void*
emalloc(uint n)
{
	void *p;

	p = malloc(n);
	if(p == nil)
		error("can't malloc: %r");
	memset(p, 0, n);
	setmalloctag(p, getcallerpc(&n));
	return p;
}

void*
erealloc(void *p, uint n)
{
	p = realloc(p, n);
	if(p == nil)
		error("can't realloc: %r");
	setmalloctag(p, getcallerpc(&n));
	return p;
}

char*
estrdup(char *s)
{
	char *t;

	t = emalloc(strlen(s)+1);
	strcpy(t, s);
	return t;
}

char*
esmprint(char *fmt, ...)
{
	va_list args;
	char *s;

	va_start(args, fmt);
	s = vsmprint(fmt, args);
	va_end(args);
	if(s == nil)
		sysfatal("no memory");
	return s;
}

void
error(char *fmt, ...)
{
	Fmt f;
	char buf[64];
	va_list arg;

	fmtfdinit(&f, 2, buf, sizeof buf);
	fmtprint(&f, "%s: ", argv0);
	va_start(arg, fmt);
	fmtvprint(&f, fmt, arg);
	va_end(arg);
	fmtprint(&f, "\n");
	fmtfdflush(&f);
	threadexitsall(fmt);
}

void
ctlprint(int fd, char *fmt, ...)
{
	int n;
	va_list arg;

	va_start(arg, fmt);
	n = vfprint(fd, fmt, arg);
	va_end(arg);
	if(n <= 0)
		error("control file write error: %r");
}

char*
readfile(char *file, int *np)
{
	char *data;
	int fd, len;
	Dir *d;

	if(np != nil)
		*np = 0;
	fd = open(file, OREAD);
	if(fd < 0)
		return nil;
	d = dirfstat(fd);
	len = 0;
	if(d != nil)
		len = d->length;
	free(d);
	data = emalloc(len+1);
	read(fd, data, len);
	close(fd);
	if(np != nil)
		*np = len;
	return data;
}

char*
cleanpath(char* file, char* dir)
{
	char*	s;
	char*	t;
	char	cwd[512];

	assert(file && file[0]);
	if(file[1])
		file = estrdup(file);
	else {
		s = file; file = emalloc(3);
		file[0] = s[0];
		file[1] = 0;
	}
	s = cleanname(file);
	if(s[0] != '/' && access(s, AEXIST) == 0){
		getwd(cwd, sizeof(cwd));
		t = esmprint("%s/%s", cwd, s);
		free(s);
		return t;
	}
	if(s[0] != '/' && dir != nil && dir[0] != 0){
		t = esmprint("%s/%s", dir, s);
		free(s);
		s = cleanname(t);
	}
	return s;
}


Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.