1// SPDX-License-Identifier: GPL-3.0-or-later
2
3#pragma once
4
5#include <mos/moslib_global.h>
6#include <mos/types.h>
7#include <stddef.h>
8
9/**
10 * @defgroup libs_stdlib libs.Stdlib
11 * @ingroup libs
12 * @brief Some standard library functions.
13 * @{
14 */
15
16MOSAPI unsigned char tolower(unsigned char c);
17MOSAPI s32 abs(s32 x);
18MOSAPI long labs(long x);
19MOSAPI s64 llabs(s64 x);
20MOSAPI s32 atoi(const char *nptr);
21
22MOSAPI unsigned long strtoul(const char *nptr, char **endptr, int base);
23MOSAPI s64 strtoll(const char *str, char **endptr, int base);
24MOSAPI s64 strntoll(const char *str, char **endptr, int base, size_t n);
25
26MOSAPI void format_size(char *buf, size_t buf_size, u64 size);
27MOSAPI char *string_trim(char *in);
28
29// clang-format off
30#define MIN(a, b) __extension__ ({ __extension__ __auto_type _a = (a); __auto_type _b = (b); _a < _b ? _a : _b; })
31#define MAX(a, b) __extension__ ({ __extension__ __auto_type _a = (a); __auto_type _b = (b); _a > _b ? _a : _b; })
32#define pow2(x) ((__typeof__(x)) 1 << (x))
33// clang-format on
34
35#ifdef __MOS_KERNEL__
36#include "mos/mm/slab.h"
37
38#define kmalloc(item) _Generic((item), slab_t *: kmemcache_alloc, default: slab_alloc)(item)
39
40should_inline __malloc void *kcalloc(size_t nmemb, size_t size)
41{
42 return slab_calloc(nmemb, size);
43}
44
45should_inline void *krealloc(void *ptr, size_t size)
46{
47 return slab_realloc(addr: ptr, size);
48}
49
50should_inline void kfree(const void *ptr)
51{
52 slab_free(addr: ptr);
53}
54
55#ifdef __IN_MOS_LIBS__
56#define malloc(size) slab_alloc(size)
57#define calloc(nmemb, size) slab_calloc(nmemb, size)
58#define realloc(ptr, size) slab_realloc(ptr, size)
59#define free(ptr) slab_free(ptr)
60#endif
61
62#else
63// malloc, free, calloc and realloc should be provided by libc
64MOSAPI pid_t spawn(const char *path, const char *const argv[]);
65#endif
66
67#ifndef __MOS_KERNEL__
68[[noreturn]] MOSAPI void exit(int status);
69MOSAPI int atexit(void (*func)(void));
70MOSAPI tid_t start_thread(const char *name, thread_entry_t entry, void *arg);
71[[noreturn]] MOSAPI void abort(void);
72#endif
73
74/** @} */
75