summaryrefslogtreecommitdiff
path: root/in_practice/breakout/sys.c
blob: bba6ff2b73e58e4630b21d97a75be8c571ccbaee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "sys.h"
#include "types.h"

#include <stdarg.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

void info(const char *fmt, ...)
{
	va_list args;
	va_start(args, fmt);
	printf("info: ");
	vprintf(fmt, args);
	printf("\n");
	va_end(args);
}

void die(const char *fmt, ...)
{
	va_list args;
	va_start(args, fmt);
	fprintf(stderr, "error: ");
	vfprintf(stderr, fmt, args);
	printf("\n");
	va_end(args);
	_exit(1);
}

void *read_entire_file(const char *filename)
{
	void *result = 0;
	FILE *file = fopen(filename, "rb");
	if (!file) return result;
	fseek(file, 0, SEEK_END);
	long size = ftell(file);
	fseek(file, 0, SEEK_SET);
	result = malloc(size + 1);
	fread(result, size, 1, file);
	fclose(file);
	*((u8 *)result + size) = '\0';
	return result;
}

const char *get_bin_dir(void)
{
	char path[512];
	i64 len = readlink("/proc/self/exe", path, 512 - 1);
	if (len <= 0)
		return 0;
	path[len] = '\0';
	char *dir = strrchr(path, '/');
	len = dir - path;
	dir = malloc(len + 1);
	memmove(dir, path, len);
	dir[len] = '\0';
	return dir;
}