-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibc.c
104 lines (81 loc) · 1.64 KB
/
libc.c
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
/*
* libc.c
*/
#include <errors.h>
#include <libc.h>
#include <libpthread.h>
#include <types.h>
int errno;
extern int main();
// This is a small wrapper that initializes the libc for the user, similar to
// crt0.o
int __attribute__((__section__(".text.main"))) __start() {
_init_libc();
return main();
}
void _init_libc() {
if (__set_thread_wrapper(pthread_wrapper) != 0) {
int _errno = errno;
char msg[] =
"[LIBC initialization] Couldn't configure the thread wrapper: ";
write(1, msg, sizeof(msg));
errno = _errno;
perror();
}
}
inline char itoc(int n) {
if (n < 10)
return '0' + n;
else
return 'a' + n - 10;
}
void itoa(int value, char *str, int base) {
if (value == 0) {
str[0] = '0';
str[1] = '\0';
return;
}
int i = 0;
while (value > 0) {
str[i] = itoc(value % base);
value /= base;
++i;
}
for (int j = 0; j < i / 2; ++j) {
char c = str[j];
str[j] = str[i - j - 1];
str[i - j - 1] = c;
}
str[i] = 0;
}
int strlen(const char *a) {
int i;
i = 0;
while (a[i] != 0)
i++;
return i;
}
char *strcpy(char *dst, const char *src) {
int i;
for (i = 0; src[i] != '\0'; ++i) {
dst[i] = src[i];
}
dst[i] = '\0';
return dst;
}
char *strcat(char *dst, const char *src) {
int last = strlen(dst);
strcpy(&dst[last], src);
return dst;
}
void perror() {
const char *msg = sys_errlist[errno];
write(1, msg, strlen(msg));
write(1, "\n", 1);
}
void *memcpy(void *restrict dest, const void *restrict src, unsigned long num) {
for (unsigned long i = 0; i < num; ++i) {
((char *)dest)[i] = ((char *)src)[i];
}
return dest;
}