summaryrefslogtreecommitdiff
path: root/src/user/lib/stdlib.c
blob: 994521f7abd1bd35b709f98909257a400db0761c (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <_proc.h>
#include <bits/panic.h>
#include <camellia.h>
#include <camellia/syscalls.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>

_Noreturn void abort(void) {
	_sys_exit(1);
}

static const char *progname;
const char *getprogname(void) {
	return progname;
}
void setprogname(const char *pg) {
	progname = pg;
}

void setproctitle(const char *fmt, ...) {
	if (!fmt) {
		strcpy(_libc_psdata, progname);
		return;
	}
	sprintf(_libc_psdata, "%s: ", progname);

	va_list argp;
	va_start(argp, fmt);
	vsnprintf(_libc_psdata + strlen(_libc_psdata), 128, fmt, argp);
	va_end(argp);
}

int mkstemp(char *template) {
	// TODO randomize template
	hid_t h = camellia_open(template, OPEN_CREATE | OPEN_RW);
	if (h < 0) {
		errno = -h;
		return -1;
	}
	// TODO truncate
	return h;
}

// TODO process env
char *getenv(const char *name) {
	(void)name;
	return NULL;
}

// TODO system()
int system(const char *cmd) {
	(void)cmd;
	errno = ENOSYS;
	return -1;
}

int abs(int i) {
	return i < 0 ? -i : i;
}

int atoi(const char *s) {
	return strtol(s, NULL, 10);
}

double atof(const char *s) {
	(void)s;
	__libc_panic("unimplemented");
}

static unsigned long long
strton(const char *restrict s, char **restrict end, int base, int *sign)
{
	long res = 0;

	while (isspace(*s)) s++;

	if (sign) *sign = 1;
	if (*s == '+') {
		s++;
	} else if (*s == '-') {
		s++;
		if (sign) *sign = -1;
	}

	if (base == 0) {
		if (*s == '0') {
			s++;
			if (*s == 'x' || *s == 'X') {
				s++;
				base = 16;
			} else {
				base = 8;
			}
		} else {
			base = 10;
		}
	}

	for (;;) {
		unsigned char digit = *s;
		if      ('0' <= digit && digit <= '9') digit -= '0';
		else if ('a' <= digit && digit <= 'z') digit -= 'a' - 10;
		else if ('A' <= digit && digit <= 'Z') digit -= 'A' - 10;
		else break;

		if (digit >= base) break;
		// TODO overflow check
		res *= base;
		res += digit;

		s++;
	}
	if (end) *end = (void*)s;
	return res;
}

long strtol(const char *restrict s, char **restrict end, int base) {
	int sign;
	long n = strton(s, end, base, &sign);
	return n * sign;
}

unsigned long strtoul(const char *restrict s, char **restrict end, int base) {
	return strton(s, end, base, NULL);
}

unsigned long long strtoull(const char *restrict s, char **restrict end, int base) {
	return strton(s, end, base, NULL);
}

double strtod(const char *restrict s, char **restrict end) {
	(void)s; (void)end;
	__libc_panic("unimplemented");
}