1 /* SPDX-License-Identifier: LGPL-2.1 OR MIT */
2 /*
3 * stdlib function definitions for NOLIBC
4 * Copyright (C) 2017-2021 Willy Tarreau <w@1wt.eu>
5 */
6
7 /* make sure to include all global symbols */
8 #include "nolibc.h"
9
10 #ifndef _NOLIBC_STDLIB_H
11 #define _NOLIBC_STDLIB_H
12
13 #include "std.h"
14 #include "arch.h"
15 #include "types.h"
16 #include "sys.h"
17 #include "string.h"
18 #include <linux/auxvec.h>
19
20 struct nolibc_heap {
21 size_t len;
22 char user_p[] __attribute__((__aligned__));
23 };
24
25 /* Buffer used to store int-to-ASCII conversions. Will only be implemented if
26 * any of the related functions is implemented. The area is large enough to
27 * store "18446744073709551615" or "-9223372036854775808" and the final zero.
28 */
29 static __attribute__((unused)) char itoa_buffer[21];
30
31 /*
32 * As much as possible, please keep functions alphabetically sorted.
33 */
34
35 static __inline__
abs(int j)36 int abs(int j)
37 {
38 return j >= 0 ? j : -j;
39 }
40
41 static __inline__
labs(long j)42 long labs(long j)
43 {
44 return j >= 0 ? j : -j;
45 }
46
47 static __inline__
llabs(long long j)48 long long llabs(long long j)
49 {
50 return j >= 0 ? j : -j;
51 }
52
53 /* must be exported, as it's used by libgcc for various divide functions */
54 void abort(void);
55 __attribute__((weak,unused,noreturn,section(".text.nolibc_abort")))
abort(void)56 void abort(void)
57 {
58 _sys_kill(_sys_getpid(), SIGABRT);
59 for (;;);
60 }
61
62 static __attribute__((unused))
atol(const char * s)63 long atol(const char *s)
64 {
65 unsigned long ret = 0;
66 unsigned long d;
67 int neg = 0;
68
69 if (*s == '-') {
70 neg = 1;
71 s++;
72 }
73
74 while (1) {
75 d = (*s++) - '0';
76 if (d > 9)
77 break;
78 ret *= 10;
79 ret += d;
80 }
81
82 return neg ? -ret : ret;
83 }
84
85 static __attribute__((unused))
atoi(const char * s)86 int atoi(const char *s)
87 {
88 return atol(s);
89 }
90
91 static __attribute__((unused))
free(void * ptr)92 void free(void *ptr)
93 {
94 struct nolibc_heap *heap;
95
96 if (!ptr)
97 return;
98
99 heap = container_of(ptr, struct nolibc_heap, user_p);
100 munmap(heap, heap->len);
101 }
102
103 #ifndef NOLIBC_NO_RUNTIME
104 /* getenv() tries to find the environment variable named <name> in the
105 * environment array pointed to by global variable "environ" which must be
106 * declared as a char **, and must be terminated by a NULL (it is recommended
107 * to set this variable to the "envp" argument of main()). If the requested
108 * environment variable exists its value is returned otherwise NULL is
109 * returned.
110 */
111 static __attribute__((unused))
getenv(const char * name)112 char *getenv(const char *name)
113 {
114 int idx, i;
115
116 if (environ) {
117 for (idx = 0; environ[idx]; idx++) {
118 for (i = 0; name[i] && name[i] == environ[idx][i];)
119 i++;
120 if (!name[i] && environ[idx][i] == '=')
121 return &environ[idx][i+1];
122 }
123 }
124 return NULL;
125 }
126 #endif /* NOLIBC_NO_RUNTIME */
127
128 static __attribute__((unused))
malloc(size_t len)129 void *malloc(size_t len)
130 {
131 struct nolibc_heap *heap;
132
133 if (__builtin_expect(__builtin_add_overflow(len, sizeof(*heap), &len), 0)) {
134 SET_ERRNO(ENOMEM);
135 return NULL;
136 }
137
138 heap = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE,
139 -1, 0);
140 if (__builtin_expect(heap == MAP_FAILED, 0))
141 return NULL;
142
143 heap->len = len;
144 return heap->user_p;
145 }
146
147 static __attribute__((unused))
calloc(size_t nmemb,size_t size)148 void *calloc(size_t nmemb, size_t size)
149 {
150 size_t x;
151
152 if (__builtin_expect(__builtin_mul_overflow(size, nmemb, &x), 0)) {
153 SET_ERRNO(ENOMEM);
154 return NULL;
155 }
156
157 /*
158 * No need to zero the heap, the MAP_ANONYMOUS in malloc()
159 * already does it.
160 */
161 return malloc(x);
162 }
163
164 static __attribute__((unused))
realloc(void * old_ptr,size_t new_size)165 void *realloc(void *old_ptr, size_t new_size)
166 {
167 struct nolibc_heap *heap;
168 size_t user_p_len;
169 void *ret;
170
171 if (!old_ptr)
172 return malloc(new_size);
173
174 heap = container_of(old_ptr, struct nolibc_heap, user_p);
175 user_p_len = heap->len - sizeof(*heap);
176 /*
177 * Don't realloc() if @user_p_len >= @new_size, this block of
178 * memory is still enough to handle the @new_size. Just return
179 * the same pointer.
180 */
181 if (user_p_len >= new_size)
182 return old_ptr;
183
184 ret = malloc(new_size);
185 if (__builtin_expect(!ret, 0))
186 return NULL;
187
188 memcpy(ret, heap->user_p, user_p_len);
189 munmap(heap, heap->len);
190 return ret;
191 }
192
193 /* Converts the unsigned 64bit integer <in> to base <base> ascii into
194 * buffer <buffer>, which must be long enough to store the number and the
195 * trailing zero. The buffer is filled from the first byte, and the number
196 * of characters emitted (not counting the trailing zero) is returned.
197 * The function uses 'multiply by reciprocal' for the divisions and
198 * requires the caller pass the correct reciprocal.
199 *
200 * Note that unlike __div64_const32() in asm-generic/div64.h there isn't
201 * an extra shift done (by ___p), the reciprocal has to be lower resulting
202 * in a slightly low quotient.
203 * Keep things simple by correcting for the error.
204 * This also saves calculating the 'low * low' product (e2 below) which is
205 * very unlikely to be significant.
206 *
207 * Some maths:
208 * recip = p2 / base - e1; // With e1 < base.
209 * q = (recip * in - e2) / p2; // With e2 < p2.
210 * = base / in - (e1 * in + e2) / p2;
211 * > base / in - (e1 * p2 + p2) / p2;
212 * = base / in - ((e1 + 1) * p2) / p2;
213 * > base / in - base;
214 * So the maximum error is less than 'base'.
215 * Hence the largest possible digit is '2 * base - 1'.
216 * For base 10 e1 is 6 and you can get digits of 15 (eg from 2**64-1).
217 * Error e1 is largest for a base that is a factor of 2**64+1, the smallest is 274177
218 * and converting 2**42-1 in base 274177 does generate a digit of 274177+274175.
219 * This all means only a single correction is needed rather than a loop.
220 *
221 * __int128 isn't used for mips because gcc prior to 10.0 will call
222 * __multi3 for MIPS64r6. The same also happens for SPARC and clang.
223 */
224 #define _NOLIBC_U64TOA_RECIP(base) ((base) & 1 ? ~0ull / (base) : (1ull << 63) / ((base) / 2))
225 static __attribute__((unused, noinline))
_nolibc_u64toa_base(uint64_t in,char * buffer,unsigned int base,uint64_t recip)226 int _nolibc_u64toa_base(uint64_t in, char *buffer, unsigned int base, uint64_t recip)
227 {
228 unsigned int digits = 0;
229 unsigned int dig;
230 uint64_t q;
231 char *p;
232
233 /* Generate least significant digit first */
234 do {
235 #if defined(__SIZEOF_INT128__) && !defined(__mips__) && !defined(__sparc__) && !defined(__hppa__)
236 q = ((unsigned __int128)in * recip) >> 64;
237 #else
238 uint64_t p = (uint32_t)in * (recip >> 32);
239 q = (in >> 32) * (recip >> 32) + (p >> 32);
240 p = (uint32_t)p + (in >> 32) * (uint32_t)recip;
241 q += p >> 32;
242 #endif
243 dig = in - q * base;
244 /* Correct for any rounding errors */
245 if (dig >= base) {
246 dig -= base;
247 q++;
248 }
249 if (dig > 9)
250 dig += 'a' - '0' - 10;
251 buffer[digits++] = '0' + dig;
252 } while ((in = q));
253
254 buffer[digits] = 0;
255
256 /* Order reverse to result */
257 for (p = buffer + digits - 1; p > buffer; buffer++, p--) {
258 dig = *buffer;
259 *buffer = *p;
260 *p = dig;
261 }
262
263 return digits;
264 }
265
266 /* Converts the unsigned long integer <in> to its hex representation into
267 * buffer <buffer>, which must be long enough to store the number and the
268 * trailing zero (17 bytes for "ffffffffffffffff" or 9 for "ffffffff"). The
269 * buffer is filled from the first byte, and the number of characters emitted
270 * (not counting the trailing zero) is returned.
271 */
272 static __inline__ __attribute__((unused))
utoh_r(unsigned long in,char * buffer)273 int utoh_r(unsigned long in, char *buffer)
274 {
275 return _nolibc_u64toa_base(in, buffer, 16, _NOLIBC_U64TOA_RECIP(16));
276 }
277
278 /* converts unsigned long <in> to an hex string using the static itoa_buffer
279 * and returns the pointer to that string.
280 */
281 static __inline__ __attribute__((unused))
utoh(unsigned long in)282 char *utoh(unsigned long in)
283 {
284 utoh_r(in, itoa_buffer);
285 return itoa_buffer;
286 }
287
288 /* Converts the unsigned long integer <in> to its string representation into
289 * buffer <buffer>, which must be long enough to store the number and the
290 * trailing zero (21 bytes for 18446744073709551615 in 64-bit, 11 for
291 * 4294967295 in 32-bit). The buffer is filled from the first byte, and the
292 * number of characters emitted (not counting the trailing zero) is returned.
293 */
294 static __inline__ __attribute__((unused))
utoa_r(unsigned long in,char * buffer)295 int utoa_r(unsigned long in, char *buffer)
296 {
297 return _nolibc_u64toa_base(in, buffer, 10, _NOLIBC_U64TOA_RECIP(10));
298 }
299
300 /* Converts the signed long integer <in> to its string representation into
301 * buffer <buffer>, which must be long enough to store the number and the
302 * trailing zero (21 bytes for -9223372036854775808 in 64-bit, 12 for
303 * -2147483648 in 32-bit). The buffer is filled from the first byte, and the
304 * number of characters emitted (not counting the trailing zero) is returned.
305 */
306 static __attribute__((unused))
itoa_r(long in,char * buffer)307 int itoa_r(long in, char *buffer)
308 {
309 char *ptr = buffer;
310 int len = 0;
311
312 if (in < 0) {
313 in = -(unsigned long)in;
314 *(ptr++) = '-';
315 len++;
316 }
317 len += utoa_r(in, ptr);
318 return len;
319 }
320
321 /* for historical compatibility, same as above but returns the pointer to the
322 * buffer.
323 */
324 static __inline__ __attribute__((unused))
ltoa_r(long in,char * buffer)325 char *ltoa_r(long in, char *buffer)
326 {
327 itoa_r(in, buffer);
328 return buffer;
329 }
330
331 /* converts long integer <in> to a string using the static itoa_buffer and
332 * returns the pointer to that string.
333 */
334 static __inline__ __attribute__((unused))
itoa(long in)335 char *itoa(long in)
336 {
337 itoa_r(in, itoa_buffer);
338 return itoa_buffer;
339 }
340
341 /* converts long integer <in> to a string using the static itoa_buffer and
342 * returns the pointer to that string. Same as above, for compatibility.
343 */
344 static __inline__ __attribute__((unused))
ltoa(long in)345 char *ltoa(long in)
346 {
347 itoa_r(in, itoa_buffer);
348 return itoa_buffer;
349 }
350
351 /* converts unsigned long integer <in> to a string using the static itoa_buffer
352 * and returns the pointer to that string.
353 */
354 static __inline__ __attribute__((unused))
utoa(unsigned long in)355 char *utoa(unsigned long in)
356 {
357 utoa_r(in, itoa_buffer);
358 return itoa_buffer;
359 }
360
361 /* Converts the unsigned 64-bit integer <in> to its hex representation into
362 * buffer <buffer>, which must be long enough to store the number and the
363 * trailing zero (17 bytes for "ffffffffffffffff"). The buffer is filled from
364 * the first byte, and the number of characters emitted (not counting the
365 * trailing zero) is returned.
366 */
367 static __inline__ __attribute__((unused))
u64toh_r(uint64_t in,char * buffer)368 int u64toh_r(uint64_t in, char *buffer)
369 {
370 return _nolibc_u64toa_base(in, buffer, 16, _NOLIBC_U64TOA_RECIP(16));
371 }
372
373 /* converts uint64_t <in> to an hex string using the static itoa_buffer and
374 * returns the pointer to that string.
375 */
376 static __inline__ __attribute__((unused))
u64toh(uint64_t in)377 char *u64toh(uint64_t in)
378 {
379 u64toh_r(in, itoa_buffer);
380 return itoa_buffer;
381 }
382
383 /* Converts the unsigned 64-bit integer <in> to its string representation into
384 * buffer <buffer>, which must be long enough to store the number and the
385 * trailing zero (21 bytes for 18446744073709551615). The buffer is filled from
386 * the first byte, and the number of characters emitted (not counting the
387 * trailing zero) is returned.
388 */
389 static __inline__ __attribute__((unused))
u64toa_r(uint64_t in,char * buffer)390 int u64toa_r(uint64_t in, char *buffer)
391 {
392 return _nolibc_u64toa_base(in, buffer, 10, _NOLIBC_U64TOA_RECIP(10));
393 }
394
395 /* Converts the signed 64-bit integer <in> to its string representation into
396 * buffer <buffer>, which must be long enough to store the number and the
397 * trailing zero (21 bytes for -9223372036854775808). The buffer is filled from
398 * the first byte, and the number of characters emitted (not counting the
399 * trailing zero) is returned.
400 */
401 static __attribute__((unused))
i64toa_r(int64_t in,char * buffer)402 int i64toa_r(int64_t in, char *buffer)
403 {
404 char *ptr = buffer;
405 int len = 0;
406
407 if (in < 0) {
408 in = -(uint64_t)in;
409 *(ptr++) = '-';
410 len++;
411 }
412 len += u64toa_r(in, ptr);
413 return len;
414 }
415
416 /* converts int64_t <in> to a string using the static itoa_buffer and returns
417 * the pointer to that string.
418 */
419 static __inline__ __attribute__((unused))
i64toa(int64_t in)420 char *i64toa(int64_t in)
421 {
422 i64toa_r(in, itoa_buffer);
423 return itoa_buffer;
424 }
425
426 /* converts uint64_t <in> to a string using the static itoa_buffer and returns
427 * the pointer to that string.
428 */
429 static __inline__ __attribute__((unused))
u64toa(uint64_t in)430 char *u64toa(uint64_t in)
431 {
432 u64toa_r(in, itoa_buffer);
433 return itoa_buffer;
434 }
435
436 static __attribute__((unused))
__strtox(const char * nptr,char ** endptr,int base,intmax_t lower_limit,uintmax_t upper_limit)437 uintmax_t __strtox(const char *nptr, char **endptr, int base, intmax_t lower_limit, uintmax_t upper_limit)
438 {
439 const char signed_ = lower_limit != 0;
440 unsigned char neg = 0, overflow = 0;
441 uintmax_t val = 0, limit, old_val;
442 char c;
443
444 if (base < 0 || base > 36) {
445 SET_ERRNO(EINVAL);
446 goto out;
447 }
448
449 while (isspace(*nptr))
450 nptr++;
451
452 if (*nptr == '+') {
453 nptr++;
454 } else if (*nptr == '-') {
455 neg = 1;
456 nptr++;
457 }
458
459 if (signed_ && neg)
460 limit = -(uintmax_t)lower_limit;
461 else
462 limit = upper_limit;
463
464 if ((base == 0 || base == 16) &&
465 (strncmp(nptr, "0x", 2) == 0 || strncmp(nptr, "0X", 2) == 0)) {
466 base = 16;
467 nptr += 2;
468 } else if (base == 0 && strncmp(nptr, "0", 1) == 0) {
469 base = 8;
470 nptr += 1;
471 } else if (base == 0) {
472 base = 10;
473 }
474
475 while (*nptr) {
476 c = *nptr;
477
478 if (c >= '0' && c <= '9')
479 c -= '0';
480 else if (c >= 'a' && c <= 'z')
481 c = c - 'a' + 10;
482 else if (c >= 'A' && c <= 'Z')
483 c = c - 'A' + 10;
484 else
485 goto out;
486
487 if (c >= base)
488 goto out;
489
490 nptr++;
491 old_val = val;
492 val *= base;
493 val += c;
494
495 if (val > limit || val < old_val)
496 overflow = 1;
497 }
498
499 out:
500 if (overflow) {
501 SET_ERRNO(ERANGE);
502 val = limit;
503 }
504 if (endptr)
505 *endptr = (char *)nptr;
506 return neg ? -val : val;
507 }
508
509 static __attribute__((unused))
strtol(const char * nptr,char ** endptr,int base)510 long strtol(const char *nptr, char **endptr, int base)
511 {
512 return __strtox(nptr, endptr, base, LONG_MIN, LONG_MAX);
513 }
514
515 static __attribute__((unused))
strtoul(const char * nptr,char ** endptr,int base)516 unsigned long strtoul(const char *nptr, char **endptr, int base)
517 {
518 return __strtox(nptr, endptr, base, 0, ULONG_MAX);
519 }
520
521 static __attribute__((unused))
strtoll(const char * nptr,char ** endptr,int base)522 long long strtoll(const char *nptr, char **endptr, int base)
523 {
524 return __strtox(nptr, endptr, base, LLONG_MIN, LLONG_MAX);
525 }
526
527 static __attribute__((unused))
strtoull(const char * nptr,char ** endptr,int base)528 unsigned long long strtoull(const char *nptr, char **endptr, int base)
529 {
530 return __strtox(nptr, endptr, base, 0, ULLONG_MAX);
531 }
532
533 static __attribute__((unused))
strtoimax(const char * nptr,char ** endptr,int base)534 intmax_t strtoimax(const char *nptr, char **endptr, int base)
535 {
536 return __strtox(nptr, endptr, base, INTMAX_MIN, INTMAX_MAX);
537 }
538
539 static __attribute__((unused))
strtoumax(const char * nptr,char ** endptr,int base)540 uintmax_t strtoumax(const char *nptr, char **endptr, int base)
541 {
542 return __strtox(nptr, endptr, base, 0, UINTMAX_MAX);
543 }
544
545 #endif /* _NOLIBC_STDLIB_H */
546